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 |
|---|---|---|---|---|---|---|---|---|
SRI-CSL/ETB | tests/remote_queries.py | Python | gpl-3.0 | 1,959 | 0.007147 |
from etb_manager import ETBNetwork
from etb_tests import etb_test, ETBTest
from etb.terms import mk_subst, mk_map, mk_stringconst, mk_idconst, mk_numberconst, mk_claim, mk_literal
from etb.parser import parse_literal
class RemoteTest(ETBTest):
@etb_test
def invalid(self):
query = self.etb.etb().query... | tb.etb().query('between(1,4,12)')
self.etb.etb().query_wait(query)
return (self.etb.query_claims(query), [])
@etb_test
def valid(self):
| query = self.etb.etb().query('between(1,4,3)')
self.etb.etb().query_wait(query)
return (self.etb.query_answers(query), [mk_subst()])
@etb_test
def valid_claims(self):
query = self.etb.etb().query('between(1,4,2)')
self.etb.etb().query_wait(query)
return (self.etb.al... |
sallyom/atomic | atomic_dbus.py | Python | lgpl-2.1 | 2,069 | 0.000483 | #!/usr/bin/python -Es
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GLib
import slip.dbus.service
from slip.dbus import polkit
from . import Atomic
class atomic_dbus(slip.dbus.service.Object):
default_polkit_auth_required = "org.atomic.readwrite"
class Args():
... | """
@slip.dbus.polkit.require_auth("org.atomic.read")
@dbus.service.method("org.at | omic", in_signature='as', out_signature='av')
def verify(self, images):
verifications = []
for image in images:
args = self.Args(str(image))
self.atomic.set_args(args)
verifications.append({"Image": image,
"Verification": self.ato... |
dyve/django-bootstrap3 | example/app/settings.py | Python | bsd-3-clause | 5,053 | 0.000396 | import os
import sys
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
# Include BOOTSTRAP3_FOLDER in path
BOOTSTRAP3_FOLDER = os.path.abspath(os.path.join(BASE_DIR, "..", "bootstrap3"))
if BOOTSTRAP3_FOLDER not in sys.path:
sys.path.insert(0, BOOTSTRAP3_FOLDER)
DEBUG = True
ADMINS = ()
... | ope/Amsterdam"
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set ... | ango will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ""
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/m... |
eadgarchen/tensorflow | tensorflow/python/grappler/model_analyzer.py | Python | apache-2.0 | 1,476 | 0.002033 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _on_not_ok_status():
ret_from_swig = tf_wrap.GenerateModelReport(metagraph.SerializeToString(),
| debug)
return ret_from_swig
|
dbcli/sqlcomplete | tests/parseutils/test_parseutils.py | Python | bsd-3-clause | 8,627 | 0.000348 | import pytest
from sqlcomplete.parseutils.tables import extract_tables
from sqlcomplete.parseutils.utils import find_prev_keyword, is_open_quote
def test_empty_string():
tables = extract_tables('')
assert tables == ()
def test_simple_select_single_table():
tables = extract_tables('select * from abc')
... | , False),
('def', 'ghi', None, False)])
def test_select_with_hanging_comma_single_table():
tables = extract_tables('select a, from abc')
assert tables == | ((None, 'abc', None, False),)
def test_select_with_hanging_comma_multiple_tables():
tables = extract_tables('select a, from abc, def')
assert set(tables) == set([(None, 'abc', None, False),
(None, 'def', None, False)])
def test_select_with_hanging_period_multiple_tables():
... |
hanlind/nova | nova/tests/unit/virt/libvirt/storage/test_lvm.py | Python | apache-2.0 | 8,203 | 0.000244 | # Copyright 2012 NTT Data. All Rights Reserved.
# Copyright 2012 Yahoo! 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/li... | unt=1', 'oflag=direct')]
lvm.clear_volume('/dev/v7')
self.assertEqual(expected_commands, executes)
CONF.set_override('volume_clear_size', '2', 'libvirt')
lvm_size = 1048576
executes = []
expected_commands | = [('dd', 'bs=1048576', 'if=/dev/zero', 'of=/dev/v9',
'seek=0', 'count=1', 'oflag=direct')]
lvm.clear_volume('/dev/v9')
self.assertEqual(expected_commands, executes)
# Test volume_clear=shred
CONF.set_override('volume_clear', 'shred', 'libvirt')
CON... |
bsipocz/astropy | astropy/constants/iau2015.py | Python | bsd-3-clause | 3,502 | 0 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astronomical and physics constants in SI units. See :mod:`astropy.constants`
for a complete listing of constants defined in Astropy.
"""
import numpy as np
from .constant import Constant
from .config import codata
# ASTRONOMICAL CONSTANTS
class I... | ('GM_sun', 'Nominal solar mass parameter', 1.3271244e20,
'm3 / (s2)', 0.0, "IAU 2015 Resolution B 3", system='si')
# Solar mass (derived from mass parameter and gravitational constant)
M_sun = IAU2015('M_sun', "Solar mass", GM_sun.value / codata.G.value,
'kg', ((codata.G.uncertainty / ... | (GM_sun.value / codata.G.value)),
f"IAU 2015 Resolution B 3 + {codata.G.reference}",
system='si')
# Solar radius
R_sun = IAU2015('R_sun', "Nominal solar radius", 6.957e8, 'm', 0.0,
"IAU 2015 Resolution B 3", system='si')
# OTHER SOLAR SYSTEM QUANTI... |
Linaro/squad | test/javascript.py | Python | agpl-3.0 | 895 | 0.001117 | import os
import subprocess
imp | ort shutil
karma = os.path.join(os.path.dirname(__file__), '../node_modules/.bin/karma')
def javascript_tests():
if not shutil.which('nodejs'):
print("W: nodejs not available, skipping javascript tests")
return 0
elif os.path.exists(karma):
chrome_exec = shutil.which('chromium') or s... |
if chrome_exec:
os.environ["CHROME_BIN"] = chrome_exec
else:
print("Please install a chromium browser package in order"
"to run javascript unit tests.")
return 2
return subprocess.call(
[karma, "start", "test/karma.conf.js", "--s... |
casualuser/ajenti | plugins/cron/main.py | Python | lgpl-3.0 | 13,334 | 0.0042 | from ajenti.ui import UI
from ajenti.api import event, helpers, ConfManager
from ajenti.utils import shell
import backend
class CronPlugin(helpers.CategoryPlugin):
text = 'Cron'
icon = '/dl/cron/icon.png'
folder = 'system'
def on_init(self):
self._tasks, self._others = backend.read_crontab(se... | if self._editing_other < len(self._others) else ''
ui.find("other_str").set("value", other_value)
#Nothing happens with non-task string
else:
ui.remove('dlgEditOther')
return ui
#noinspection PyUnusedLocal
@event('button/click')
@event('linklabel/click')
... |
self._show_dialog = 1
self._newtask = True
if params[0] == 'edit_task':
self._editing_task = int(params[1])
self._show_dialog = 1
if params[0] == 'del_task':
self._tasks.pop(int(params[1]))
self._error = backend.write_crontab(self.... |
vinhqdang/my_mooc | MOOC-work/edx/MIT 6002 Intro to Computational thinking and Data Science/Week 4/lectureCode_L17_code.py | Python | mit | 6,929 | 0.012989 | import pylab, random
def getData(fileName):
dataFile = open(fileName, 'r')
distances = []
masses = []
discardHeader = dataFile.readline()
for line in dataFile:
d, m = line.split()
distances.append(float(d))
masses.append(float(m))
dataFile.close()
return (masses, dis... | d, h1, h2, h3, h4 = line.split()
distances.append(float(d))
heights1.append(float(h1))
heights2.append(float(h2))
heights3.append(float(h3))
heights4.append(float(h4))
dataFile.close()
return (distances, [heights1, heights2, heights3, heights4])
def tryFits(fName):
... | for h in heights:
totHeights = totHeights + pylab.array(h)
pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
pylab.xlabel('Inches from Launch Point')
pylab.ylabel('Inches Above Launch Point')
meanHeights = totHeights/float(len(heights))
pylab.plot(distances, meanHeights, 'bo')
... |
selectnull/ave | setup.py | Python | mit | 345 | 0 | from distutils.core import setup
setup(
name='ave',
version='0.8.0', |
author='Sasha Matijasic',
author_email='sasha@selectnull.com',
scripts=['ave.sh', ],
url='https://github.com/selectnull/ave',
license='LICENSE',
| description='ave Activates Virtual Environment',
long_description=open('README.md').read(),
)
|
ForensicTools/GRREAT-475_2141-Chaigon-Failey-Siebert | lib/export_utils.py | Python | apache-2.0 | 12,525 | 0.008942 | #!/usr/bin/env python
# Copyright 2012 Google Inc. All Rights Reserved.
"""Utils exporting data from AFF4 to the rest of the world."""
import os
import Queue
import stat
import time
import logging
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import serialize
from grr.lib import threadpool
from... | x_age
oldest_time = (time.time() - self.max_age) * 1e6
if fd.Get(aff4.VFSGRRClient.SchemaC | ls.PING) >= oldest_time:
yield fd
def DownloadFile(file_obj, target_path, buffer_size=BUFFER_SIZE):
"""Download an aff4 file to the local filesystem overwriting it if it exists.
Args:
file_obj: An aff4 object that supports the file interface (Read, Seek)
target_path: Full path of file to write ... |
glugmpstme/dotjot | Adarna/Adarna/urls.py | Python | apache-2.0 | 795 | 0 | """Adarna URL Configuration
The `urlpatterns` list routes URLs to view | s. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Fu | nction views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import t... |
ofer43211/unisubs | apps/videos/migrations/0169_auto__chg_field_videourl_url__del_unique_videourl_url_type.py | Python | agpl-3.0 | 36,444 | 0.008095 | # -*- 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):
# Removing unique constraint on 'VideoUrl', fields ['url', 'type']
db.delete_unique('videos_videourl', ['url... | ngo.db.models.fields.IntegerField', [], {'def | ault': '0'}),
'biography': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'can_send_messages': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'create... |
honzajavorek/film2trello | tests/test_csfd.py | Python | mit | 2,770 | 0.000361 | from lxml import html
from pathlib import Path
import pytest
from film2trello import csfd
@pytest.fixture()
def csfd_html():
path = Path(__file__).parent / 'csfd.html'
return html.fromstring(path.read_text())
@pytest.mark.parametrize('url', (
'http://csfd.cz/film/8283-posledni-skaut/',
'http://www... | csfd.normalize_url(url) == 'https://www.csfd.cz/film/8283/'
@pytest.mark.parametrize('url', (
'hello world',
'https://www.imdb.com/title/tt3864916/',
'https://w | ww.csfd.cz/dvd-a-bluray/mesicne/',
))
def test_normalize_url_error(url):
with pytest.raises(ValueError):
csfd.normalize_url(url)
def test_parse_title(csfd_html):
title = 'Poslední skaut / The Last Boy Scout (1991)'
assert csfd.parse_title(csfd_html) == title
def test_parse_title_same_name():
... |
Aloomaio/googleads-python-lib | examples/ad_manager/v201805/publisher_query_language_service/get_all_programmatic_buyers.py | Python | apache-2.0 | 1,687 | 0.00652 | #!/us | r/bin/env python
#
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi | red by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example f... |
kdeloach/nyc-trees | src/nyc_trees/apps/home/training/decorators.py | Python | agpl-3.0 | 1,779 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from functools import wraps
from django.db import transaction
from django.http import Http404
from django.contrib.flatpages.views import flatpage
def render_flatpage(url):
def ... | gs):
if no | t step.is_visitable(request.user):
raise Http404()
else:
return view_fn(request, *args, **kwargs)
return wrapper
return outer_decorator
|
gee-community/gee_tools | geetools/tools/imagecollection.py | Python | mit | 39,458 | 0.000532 | # coding=utf-8
""" Module holding tools for ee.ImageCollections """
import ee
import ee.data
import pandas as pd
import math
from . import date, ee_list
from . import image as image_module
from . import collection as eecollection
from ..utils import castImage
from .. import composite
def add(collection, image):
"... | ame:
:return:
"""
enumerated = eecollection.enumerate(collection)
def over_list(l):
l = ee.List(l)
index = ee.Number(l.get(0))
element = l.get(1)
return ee.Image(element).set(name, index)
imlist = enumerated.map(over_list)
return ee.ImageCollection(imlist)
def... | numeration, so if the order of features changes over time, the numbers
will not be in order """
size = collection.size()
collist = collection.toList(size)
seq = ee.List.sequence(0, size.subtract(1))
def wrap(n):
n = ee.Number(n).toInt()
feat = collist.get(n)
return ee.Image(... |
zifter/nonogram | src/sudoku/sudoku_descr.py | Python | mit | 1,836 | 0.001089 | import json
import math
from common.matrix import Matrix
class SudokuDescr(object):
def __init__(self, matrix=None):
self.matrix = Matrix(matrix=matrix)
y_size = int(math.sqrt(self.matrix.shape[0]))
x_size = int(math.sqrt(self.matrix.shape[1]))
self._box_shape = (x_size, y_size)
... | None \
and self.matrix == other.matrix
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return SudokuDescrPrinter.pretty_string(self)
def values(self):
return self._values
def box_shape(self):
return self._box_shape
def sav... | ith open(filepath, 'w') as outfile:
json.dump(self.save(), outfile, indent=4, sort_keys=False)
@staticmethod
def load(data):
return SudokuDescr(**data)
@staticmethod
def load_from_file(filepath):
with open(filepath, "r") as inputfile:
return SudokuDescr.load(jso... |
psnj/petl | examples/comparison.py | Python | mit | 353 | 0.002833 | from __future__ import | absolute_import, print_function, division
import petl as etl
table = [['foo', 'bar'],
['a', 1],
['b', None]]
# raises exception under Python 3
etl.select(table, 'bar', lambda v: v > | 0)
# no error under Python 3
etl.selectgt(table, 'bar', 0)
# or ...
etl.select(table, 'bar', lambda v: v > etl.Comparable(0))
|
tao12345666333/Talk-Is-Cheap | conf-sys/web_app.py | Python | mit | 1,765 | 0.00057 | #!/usr/bin/env python
# coding=utf-8
"""
/ 提供基础页面
"""
import json
import time
import subprocess
import tornado.concurrent
import tornado.gen
import tornado.httpclient
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.template
import pymongo
from tornado.options im... | nt conf.generate(ip=ip, port=port)
wi | th open('confs/{}'.format(data.inserted_id), 'w+') as f:
f.write(conf.generate(ip=ip, port=port))
self.redirect('/')
if __name__ == "__main__":
tornado.options.parse_command_line()
app = tornado.web.Application(handlers=[
(r"/", MainHandler),
(r"/create", CreateHandler),
... |
dmlc/tvm | python/tvm/relay/op/contrib/ethosn.py | Python | apache-2.0 | 10,270 | 0.000779 | # 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 u... | return False
rs = tvm.relay.op.reshape(*args, attrs["newshape"])
return support.reshape(rs)
@tvm.ir.register_op_attr("qnn.add", "target.ethos-n")
def qnn_add(expr):
"""Check if an addition is supported by Ethos-N."""
if not ethosn_available():
return False
args = expr.args
add = _qnn... | ")
def qnn_concatenate(expr):
"""Check if a concatenate is supported by Ethos-N."""
if not ethosn_available():
return |
solashirai/edx-platform | lms/djangoapps/gating/tests/test_signals.py | Python | agpl-3.0 | 1,936 | 0.002583 | """
Unit tests for gating.signals module
"""
from mock import patch
from opaque_keys.edx.keys import UsageKey
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.django import modulestore
from gating.signals impo... | e_prerequisite')
def test_gating_enabled(self, mock_evaluate):
""" Test evaluate_prerequisite is called when course.enable_subsection_gating is True """
self.course.enable_subsection_gating = True
modulestore().update_item(self.course, 0)
han | dle_score_changed(
sender=None,
points_possible=1,
points_earned=1,
user_id=self.test_user_id,
course_id=unicode(self.course.id),
usage_id=unicode(self.test_usage_key)
)
mock_evaluate.assert_called_with(self.course, self.test_usage_... |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/multi_map_remove_entry_codec.py | Python | apache-2.0 | 1,112 | 0.002698 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import D... | itial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key)
DataCodec.encode(buf, value, True)
return OutboundMessage(buf, False)
def decode_response(msg):
in... | SPONSE_RESPONSE_OFFSET)
|
srinath-chakravarthy/ovito | doc/python/example_snippets/simulation_cell.py | Python | gpl-3.0 | 503 | 0.007952 | from ovito.io import import_file
import numpy.linalg
node = import_file("simulation.dump")
cell = node.source.cell
# Compute simulation cell volume by taking the determinant of | the
# left 3x3 submatrix:
volume = abs(numpy.linalg.det(cell.matrix[0:3,0:3] | ))
# Make cell twice as large along the Y direction by scaling the
# second cell vector.
mat = cell.matrix.copy()
mat[:,1] = mat[:,1] * 2.0
cell.matrix = mat
# Change color of simulation cell to red:
cell.display.rendering_color = (1.0, 0.0, 0.0) |
archen/mantistrack | mantistrack/mantises/admin.py | Python | mit | 831 | 0.002407 | # Core Django imports
from django.contrib import admin
# Third party app imports
fro | m reversion import VersionAdmin
# Local app imports
from mantises.models import Mantis, Breed, Molt
class MantisAdmin(VersionAdmin):
list_display = ('__str__',)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
class BreedAdmin(VersionAdmin):
list_dis... | = request.user
obj.save()
class MoltAdmin(VersionAdmin):
list_display = ('__str__',)
def save_model(self, request, obj, form, change):
obj.user = request.user
obj.save()
admin.site.register(Mantis, MantisAdmin)
admin.site.register(Breed, BreedAdmin)
admin.site.register(Molt, MoltAdm... |
Dabug123/owlCore64 | scripts/gcc-wrapper.py | Python | gpl-2.0 | 3,609 | 0.001385 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in sourc | e and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and | the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation nor
# the na... |
pjlong/cambNet | cambnet/home/urls.py | Python | mit | 342 | 0.026316 | from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name="index"),
url( | r'^contacts/$', views.ContactsView.as_view(), name="contacts"),
url(r'^login/$', views.Login | View.as_view(), name="login"),
url(r'^logout/$', views.LogoutView.as_view(), name="logout"),
) |
PowerKiKi/mqueue | library/searchengine/nova/fix_encoding.py | Python | mit | 11,785 | 0.010098 | # Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Collection of functions and classes to fix various encoding problems on
multiple platforms with python.
"""
import codecs
import locale
import os
imp... | p option arguments to the Python interpreter.
while len(argv) > 0:
arg = argv[ | 0]
if not arg.startswith(u'-') or arg == u'-':
break
argv = argv[1:]
if arg == u'-m':
# sys.argv[0] should really be the absolute path of the
# module source, but never mind.
break
if arg == u'-c':
argv[0] = u'-c'
break
sys.argv = argv
_SYS_ARG... |
Donkyhotay/MoonPy | zope/app/cache/interfaces/ram.py | Python | gpl-3.0 | 1,471 | 0.00068 | ##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subjec | t to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRI... | RTICULAR PURPOSE.
#
##############################################################################
"""RAM cache interface.
$Id: ram.py 67630 2006-04-27 00:54:03Z jim $
"""
__docformat__ = 'restructuredtext'
from zope.interface import Attribute
from zope.app.cache.interfaces import ICache
class IRAMCache(ICache):
... |
execunix/vinos | external/gpl3/gcc/dist/contrib/update-copyright.py | Python | apache-2.0 | 27,069 | 0.011231 | #!/usr/bin/python
#
# Copyright (C) 2013 Free Software Foundation, Inc.
#
# This script 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 Soft | ware Foundation; either version 3, or (at your option)
# any later version.
# This script adjusts the copyright notices at the top of source files
# so that they have the form:
#
# Copyright XXXX-YYYY Free Software Foundation, Inc.
#
# It doesn't change code that is known to be maintained elsewhere | or
# that carries a non-FSF copyright.
#
# The script also doesn't change testsuite files, except those in
# libstdc++-v3. This is because libstdc++-v3 has a conformance testsuite,
# while most tests in other directories are just things that failed at some
# point in the past.
#
# Pass --this-year to the script if yo... |
ceb8/astroquery | astroquery/utils/tap/model/modelutils.py | Python | bsd-3-clause | 1,243 | 0.000805 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
=============
TAP plus
=============
@author: Juan Carlos Segovia
@contact: juan.carlos.segovia@sciops.esa.int
European Space Astronomy Centre (ESAC)
European Space Agency (ESA)
Created on 30 jun. 2016
"""
import os
from astropy.table import Table... | isinstance(col.unit, str):
col.unit = col | .unit.replace(".", " ").replace("'", "")
return result
else:
return None
|
horiam/codebuild-emulator | codebuild_emulator/jobpoller.py | Python | apache-2.0 | 4,019 | 0.012192 | #!/usr/bin/python
import boto3
import shutil
import zipfile
from zipfile import ZipFile, ZipInfo
import os
import tempfile
import time
import threading
from os.path import join
from botocore.client import Config
class JobPoller:
def __init__(self, action_type_id, builder):
self._action_type_id = action_... | loadBucket = job['data'][ | 'outputArtifacts'][0]['location']['s3Location']['bucketName']
uploadKey = job['data']['outputArtifacts'][0]['location']['s3Location']['objectKey']
print('Uploading artifact %s to bucket %s' % (uploadKey, uploadBucket))
s3.upload_file(join(tempdir, 'output.zip'), uploadBucket, uploadKey... |
GarySparrow/mFlaskWeb | venv/Lib/site-packages/requests_futures/sessions.py | Python | mit | 2,820 | 0 | # -*- coding: utf-8 -*-
"""
requests_futures
~~~~~~~~~~~~~~~~
This module provides a small add-on for the requests http library. It makes use
of python 3.3's concurrent.futures or the futures backport for previous
releases of python.
from requests_futures im | port FuturesSession
session = FuturesSession()
# request is run in the background
future = session.get('http://httpbin.org/get')
# ... do other stuff ...
# wait for the request to complete, if it hasn't already
response = future.result()
print('response status: {0}'.format(response.status_c... | import Session
from requests.adapters import DEFAULT_POOLSIZE, HTTPAdapter
class FuturesSession(Session):
def __init__(self, executor=None, max_workers=2, session=None, *args,
**kwargs):
"""Creates a FuturesSession
Notes
~~~~~
* ProcessPoolExecutor is not suppo... |
geertj/draco2 | draco2/util/uri.py | Python | mit | 5,926 | 0.005569 | # vi: ts=8 sts=4 sw=4 et
#
# uri.py: various URI related utilties
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the D... | ""
uri = ''
if scheme:
uri += '%s:' % scheme
if host:
uri += '//%s' % host
if path:
uri += '/%s' % path
if query:
uri += '?%s' % query
return uri
def parse_path(path):
"""Parse the "path" component of an URI.
The result is a list of path components.
... | path" component of an URI.
This function is the reverse of parse_path().
"""
parts = [ quote_url(pa) for pa in parts ]
path = '/'.join(parts)
return path
def parse_query(query):
"""Parse the "query" component of an URI.
The result is a dictionary that maps a string key to a list with
... |
thomasballinger/remixcast | setup.py | Python | mit | 2,203 | 0 | from setuptools import setup
import ast
import os
import io
def version():
"""Return version string."""
with open(os.path.join('remixcast', '__init__.py')) as input_file:
for line in input_file:
if line.startswith('__version__'):
return ast.parse(line).body[0].value.s
def... | 'feedgen',
' | parsimonious',
'podcastparser',
'pydub',
],
tests_require=[
'pytest'
],
entry_points={
'console_scripts': [
'mix = remixcast.mix:main',
'feedmix = remixcast.feedmix:main',
]
},
classifiers=[
"Deve... |
thonkify/thonkify | src/lib/future/backports/email/base64mime.py | Python | mit | 3,724 | 0 | # Copyright (C) 2002-2007 Python Software Foundation
# Author: Ben Gertzfield
# Contact: email-sig@python.org
"""Base64 content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode arbitrary 8-bit data using the three 8-bit bytes in four 7-bit
ch... |
`encoded-word' in a header. This method is commonly used for 8-bit real names
in To:, From:, Cc:, etc. fields, as well as Subject: lines.
This module does not do the line wrapping or end-of-line character conversion
necessary for prop | er internationalized headers; it only does dumb encoding and
decoding. To deal with the various line wrapping issues, use the email.header
module.
"""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future.builtins import range
from future.builtins im... |
kakaiu/codeTracker | git/user/Get_Info/syn_tags.py | Python | gpl-3.0 | 2,741 | 0.018242 | import json
import multiprocessing
import time
import requests
import sys
def request_api(api):
app_key = '&key=ZEaUTt2btGSROV8q3NeOQg(('
info = requests.get(api + app_key)
info = info.json()
return info
def delete_duplicate(dict):
"""delete the duplicated items in the list"""
Info = []
... | em)
tags_list.remove(item)
print("Remove list: {}".format(remove_list))
print("Tags: {}".format(tags_list))
syn_list = former_syn_list
for tag in tags_list:
syn_tags = []
api = 'https://api.stackexchange.com/2.2/tags/{}/synonyms' \
'?pagesize=100&order... | .format(tag,syn_info))
syn_info = syn_info["items"]
if not syn_info == []:
for item in syn_info:
syn_tags.append(item["from_tag"])
# The query of synonymous tags can't return the input tag
syn_tags.append(tag.lower())
syn_list[tag.lo... |
glotaran/glotaran | glotaran/cli/commands/optimize.py | Python | gpl-3.0 | 4,194 | 0.002861 | import sys
import typing
import click
import glotaran as gta
from . import util
@click.option('--dataformat', '-dfmt', default=None,
type=click.Choice(gta.io.reader.known_reading_formats.keys()),
help='The input format of the data. Will be infered from extension if not set.')
@click.opti... | click.echo('Error: Neither scheme nor model specified', err=True)
sys.exit(1)
model = util.load_model_file(model, verbose=True)
if parameter is None:
click.echo('Error: Neither scheme nor parameter specified', err=True)
sys.exit(1)
parameter = util.load_pa... | ameter, verbose=True)
if len(data) == 0:
click.echo('Error: Neither scheme nor data specified', err=True)
sys.exit(1)
dataset_files = {arg[0]: arg[1] for arg in data}
datasets = {}
for label in model.dataset:
if label not in dataset_files:
... |
joachimmetz/dfvfs | tests/vfs/attribute.py | Python | apache-2.0 | 545 | 0.005505 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the VFS attribute interface."""
im | port unittest
from dfvfs.vfs import attribute
from tests import test_lib as shared_test_lib
class AttributeTest(shared_test_lib.BaseTestCase):
"""Tests the VFS attribute interface."""
def testTypeIndicator(self):
"""Tests the type_indicator property."""
test_attribute = attribute.Attribute()
self.a... | ndicator)
if __name__ == '__main__':
unittest.main()
|
clusterfudge/boomer | boomer/skills/wolfram_alpha/__init__.py | Python | gpl-3.0 | 7,636 | 0.000786 | # Copyright 2016 Boomer AI, Inc.
#
# This file is part of Boomer Core.
#
# Boomer Core 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.
... | (utterance)
if match:
return self._normalize(match.groupdict())
return None
class WolframAlphaSkill(BoomerSkill):
POD_ID_CANDIDATES = [
'Value',
'NotableFacts:PeopleData',
'BasicInformation:PeopleData',
| 'Definition',
'DecimalApproximation',
]
def __init__(self):
BoomerSkill.__init__(self, name="WolframAlphaSkill")
self.__init_client()
self.question_parser = EnglishQuestionParser()
def __init_client(self):
key = self.config.get('api_key')
self.client... |
niteoweb/libcloud | libcloud/dns/drivers/cloudns.py | Python | apache-2.0 | 7,000 | 0 | # 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 use ... | ]
while True:
page_result = self.connection.request(
'/dns/list-zones.json', params=params).object
if not page_result:
break
zones_list.extend(page_result)
params['page'] += 1
for item in zones_list:
yield self._... | params = {'domain-name': domain, 'zone-type': 'master'}
self.connection.request(
'/dns/register.json', params=params).object
zone = Zone(id=domain, domain=domain,
type='master', ttl=3600, driver=self)
return zone
def delete_zone(self, zone):
self... |
tomas-edwardsson/check_mk | web/htdocs/multitar.py | Python | gpl-2.0 | 4,222 | 0.003553 | #!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ /... | # Extract without use of temporary files
subtar = tarfile.open(fileobj = subtarstream)
subtar.extractall(target_dir)
def wipe_directory(path):
for entry | in os.listdir(path):
if entry not in [ '.', '..' ]:
p = path + "/" + entry
if os.path.isdir(p):
shutil.rmtree(p)
else:
os.remove(p)
|
trevren11/byu-hummedia-api | hummedia/models.py | Python | mpl-2.0 | 8,507 | 0.01775 | from mongokit import Document, Connection, CustomType, OR
from config import MONGODB_HOST, MONGODB_PORT, MONGODB_DB
import datetime
class IsoDate(CustomType):
mongo_type = unicode
python_type = datetime.datetime
init_type = None
def to_bson(self, value):
return unicode(datetime.datetime.strf... | "username": basestring,
"email": basestring,
"firstname": unicode,
"lastname": unicode,
"role": basestring,
"userid": basestring,
"superuser": bool,
"ta":bool,
"preferredLanguage": basestring,
"o | auth": {
"google": {"id": basestring, "email": basestring, "access_token": list},
"facebook": dict,
"twitter": dict
}
}
required_fields=["username","email"]
default_values={"username":"","email":"","preferredLanguage":"en","role":"student","superuser":False,"ta":F... |
jjmleiro/hue | desktop/libs/aws/src/aws/s3/s3fs.py | Python | apache-2.0 | 11,345 | 0.012076 | # Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file ex... | '/'):
path += '/'
return path
@staticmethod
def _cut_separator(path):
return path.endswith('/') and path[:-1] or path
@staticmethod
def isroot(path):
return s3.is_root(path)
@staticmethod
def join(*comp_list):
return s3.join(*comp_list)
@staticmethod
def normpath(path):
ret... | method
def parent_path(path):
parent_dir = S3FileSystem._append_separator(path)
if not s3.is_root(parent_dir):
bucket_name, key_name, basename = s3.parse_uri(path)
if not basename: # bucket is top-level so return root
parent_dir = S3_ROOT
else:
bucket_path = '%s%s' % (S3_ROO... |
jbogarin/ciscosparkapi | examples/ngrokwebhook.py | Python | mit | 2,209 | 0.022182 | #sample script that reads ngrok info from localhost:4040 and create Cisco Spark Webhook
#typicall ngrok is called "ngrok http 8080" to redirect localhost:8080 to Internet
#accesible ngrok url
#
#To use script simply launch ngrok, then launch this script. After ngrok is killed, run this
#script a second time to re... | re
import sys
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
from ciscosparkapi import CiscoSparkAPI, Webhook
def findwebhookidbyname(api, webhookname):
webhooks = api.webhooks.list()
for wh in webhooks:
if wh.name == webhookname:
return wh.id
... | "/sparkwebhook"
#grab the at from a local at.txt file instead of global variable
fat=open ("at.txt","r+")
at=fat.readline().rstrip()
fat.close
api = CiscoSparkAPI(at)
#go to the localhost page for nogrok and grab the public url for http
try:
ngrokpage = requests.get("http://127.0.0.1:4040").text
exce... |
ericholscher/django | django/contrib/gis/tests/geogapp/models.py | Python | bsd-3-clause | 876 | 0.003425 | from django.contrib.gis.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class City(models.Model):
name = models.CharField(max_length=30)
point = models.PointField(geography=True)
objec | ts = models.GeoManager()
def __str__(self):
retur | n self.name
@python_2_unicode_compatible
class Zipcode(models.Model):
code = models.CharField(max_length=10)
poly = models.PolygonField(geography=True)
objects = models.GeoManager()
def __str__(self):
return self.code
@python_2_unicode_compatible
class County(models.Model):
name = models.... |
agacek/camkes-tool | camkes/parser/__init__.py | Python | bsd-2-clause | 410 | 0.002439 | #
# Copyrig | ht 2014, NICTA
#
# This software may be distributed and modified according to the terms of
# the BSD 2-Clause license. Note that NO WARRANTY is provided.
# See "LICENSE_BSD2.txt" for details.
#
# @TAG(NICTA_BSD)
#
from camkestr import dedupe, parse_to_ast, resolve_imports, resolve_references, show, \
pretty, log, ... | , assign_filenames
from Exceptions import CAmkESSyntaxError
|
uhuc-de/minecraft-vanilla-server-toolset | bin/mvst/wrapper_handler.py | Python | gpl-3.0 | 5,058 | 0.037169 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import datetime
import logging # used for logging
import time # needed for sleep() and duration
from .core_functions import CoreFunctions as Core
from .config import Config
from .daemon_handler import DaemonHandler
class WrapperHandler:
"""
This class handles... | nfig")
self.config = config
self.log = logging.getLogger('WrapperHandler')
self.log.setLevel( 10*int | (self.config.getLoglevel("wrapper")) )
self.daemon = DaemonHandler(self.config, "wrapper")
def start(self):
"""
Start the wrapper as a daemon
Return 0 by success
and 1 by failure
"""
if not self.getEulaStatus():
print("You need to accept the EULA in {0}eula.txt".format(self.config.getServerDir()))... |
Aurantia/AurantiaWebService | settings.py | Python | gpl-3.0 | 667 | 0.004498 | #!/usr/bin/env python |
# -*- encoding: utf-8 -*-
import os
class Config(object):
DEBUG = False
TESTING = False
| CSRF_ENABLED = True
WTF_CSRF_ENABLED = True
SECRET_KEY = "4c2cc707e708b9b2ad8a5d427868d580e85ea3943912d916"
SECURITY_PASSWORD_SALT = "3e5fade13026ad4d6121d428c6eb43adf078d1719d1f4615"
SQLALCHEMY_DATABASE_URI = os.environ["DATABASE_URL"]
#BCRYPT_LOG_ROUNDS = 13
class ProdutionConfig(Config):
... |
dhavalpowar/learn | python/data_structures/node.py | Python | mit | 421 | 0.009501 | class LinkedNode(object):
def __init__(self, val):
self.val = val
self.next = None
class BinaryNode(object):
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
class DoublyLinkedNode(object):
de | f __init__(self, val, prev=None, nex | t=None):
self.val, self.prev, self.next = val, prev, next
if __name__ == '__main__':
pass |
stvstnfrd/edx-platform | openedx/core/djangoapps/dark_lang/middleware.py | Python | agpl-3.0 | 5,890 | 0.002037 | """
Middleware for dark-launching languages. These languages won't be used
when determining which translation to give a user based on their browser
header, but can be selected by setting the Preview Languages on the Dark
Language setting page.
This middleware must be placed before the LocaleMiddleware, but after
the S... | er's dark language setting in the session and apply it
"""
| auth_user = request.user.is_authenticated
preview_lang = None
if auth_user:
# Get the request user's dark lang preference
preview_lang = get_user_preference(request.user, DARK_LANGUAGE_KEY)
# User doesn't have a dark lang preference, so just return
if not... |
phsmit/Smit-Fuel | templatetags/extratags.py | Python | bsd-2-clause | 159 | 0.012579 | from google.appengine.ext.webapp import template
register = template.Library()
@register.fi | lter
def inttofloat(value, arg):
return float(valu | e) / 1000.0;
|
ohmu/pglookout | test/test_pgutil.py | Python | apache-2.0 | 2,593 | 0.002314 | # Copied from https://github.com/ohmu/ohmu_common_py test/test_pgutil.py version 0.0.1-0-unknown-fa54b44
"""
pglookout - postgresql utility function tests
Copyright (c) 2015 Ohmu Ltd
See LICENSE for details
"""
from pglookout.pgutil import (
create_connection_string, get_conne | ction_info, mask_connection_info,
)
from pytest import raises
def test_connection_info():
url = "postgres://hannu:secret@dbhost.local:5555/abc?replication=true&sslmode=foobar&sslmode=require"
cs = "host=dbhost.local user='hannu' dbname='abc'\n" \
"replication=true password=secret sslmode=require ... | =5555"
ci = {
"host": "dbhost.local",
"port": "5555",
"user": "hannu",
"password": "secret",
"dbname": "abc",
"replication": "true",
"sslmode": "require",
}
assert get_connection_info(ci) == get_connection_info(cs)
assert get_connection_info(ci) ==... |
jarhart/SublimeSBT | sbtview.py | Python | mit | 5,229 | 0.000765 | import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
... | f._erase_output(*self.panel.sel())
|
def update_writability(self):
self.panel.set_read_only(not self._running or
self.panel.sel()[0].begin() < self._output_size)
def _set_running(self, running):
self._running = running
self.update_writability()
def _append_output(self, output):
... |
edx/opaque-keys | opaque_keys/edx/tests/test_default_deprecated.py | Python | agpl-3.0 | 1,382 | 0.001447 | """
Test that old keys deserialize just by importing opaque keys
"""
from unittest import TestCase
from opaque_keys.edx.keys import CourseKey, LearningContextKey, UsageKey
class TestDefault(TestCase):
"""
Check that clients which merely import CourseKey can deserialize the expected keys, etc
"""
def t... | 'org.id/course_id/run')
self.assertEqual(key.org, 'org.id')
| key = CourseKey.from_string('course-v1:org.id+course_id+run')
self.assertEqual(key.org, 'org.id')
def test_learning_context_key(self):
"""
Test CourseKey
"""
key = LearningContextKey.from_string('org.id/course_id/run')
self.assertEqual(key.org, 'org.id')
s... |
shj00007/DODO | test.py | Python | apache-2.0 | 1,569 | 0.007648 | import tornado.ioloop
import tornado.web
import tornado.websocket
import os
UPLOAD_FILE_PATH = "./tempfiles/"
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("./templates/main.html", title = "Main Page");
class EchoWebSocket(tornado.websocket.WebSocketHandler):
all_client = ... |
EchoWebSocket.all_client.add(self)
def on_message(self, message):
print message
for client in EchoWebSocket.all_client:
| client.write_message(u"You said: " + message)
# self.write_message(u"You said: " + message)
def on_close(self):
print("WebSocket closed")
EchoWebSocket.all_client.remove(self)
class UploadHandler(tornado.web.RequestHandler):
def post(self):
uploadFile = self.request.files... |
JackDanger/sentry | tests/sentry/api/endpoints/test_group_events_latest.py | Python | bsd-3-clause | 793 | 0 | from __future__ import absolute_import
import six
from datetime import datetime
from sentry.testutils import APITestCase
class | GroupEventsLatestTest(APITestCase):
def test_simple(self):
self.login_as(us | er=self.user)
group = self.create_group()
self.create_event(
event_id='a',
group=group,
datetime=datetime(2013, 8, 13, 3, 8, 25),
)
event_2 = self.create_event(
event_id='b',
group=group,
datetime=datetime(2013, 8, ... |
gunan/tensorflow | tensorflow/python/kernel_tests/aggregate_ops_test.py | Python | apache-2.0 | 5,147 | 0.00816 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | l = self.evaluate(math_ops.add_n(data))
expected = np.sum(np.vstack(
[np.expand_dims(d, 0) for d in data]), axis=0)
tol = 5e-3 if dtype == dtypes.float16 else 5e-7
self.assertAllClose(expected, actual, rtol=tol, atol=tol)
| @test_util.run_deprecated_v1
def testUnknownShapes(self):
np.random.seed(12345)
with self.session(use_gpu=True) as sess:
for dtype in self._supported_types():
data = self._buildData((2, 2), dtype)
for count in range(1, self._MAX_N + 1):
data_ph = array_ops.placeholder(dtype=d... |
OCA/purchase-workflow | purchase_deposit/wizard/purchase_make_invoice_advance.py | Python | agpl-3.0 | 8,892 | 0.000787 | # Copyright 2019 Elico Corp, Dominique K. <dominique.k@elico-corp.com.sg>
# Copyright 2019 Ecosoft Co., Ltd., Kitti U. <kittiu@ecosoft.co.th>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import time
from datetime import datetime
from odoo import _, api, fields, models
from odoo.exceptions impo... | se
)
if not account_id:
raise UserError(
_(
"There is no purchase account defined for this product: %s."
"\nYou may have to install a chart of account from "
"Accounting app, settings menu."
)
... | ."))
context = {"lang": order.partner_id.lang}
amount = self.amount
if self.advance_payment_method == "percentage": # Case percent
if self.amount > 100:
raise UserError(_("The percentage of the deposit must be not over 100"))
amount = self.amount / 100 * ... |
ahb0327/intellij-community | python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertTupleWithoutParenthesesToList.py | Python | apache-2.0 | 17 | 0.117647 | xs = 1<care | t>, | 2
|
andymcguinness/Planet-Lab | backend/src/backend/common/resource.py | Python | bsd-3-clause | 7,704 | 0.000779 | """Common tools for building restful resources."""
import flask
import flask_restful
import flask_restful.reqparse
import functools
import sqlalchemy
import sqlalchemy.orm as orm
import backend
import backend.common.auth as auth
class RequestParser(flask_restful.reqparse.RequestParser):
"""RequestParser subcla... | on.commit()
if not rows_deleted:
return flask.Response('', 404)
class SimpleCreate(flask_restful.Resource | ):
"""Base class defining the simplest POST for a new resource."""
parser = None
resource_type = None
def as_dict(self, resource):
"""Needs to be implemented by child classes. Given an object,
returns a serializable dictionary representing that object to
be returned after the ... |
rht/universe | universe/spaces/vnc_event.py | Python | mit | 2,568 | 0.002336 | import string
from universe import error
from universe.vncdriver import constants
class VNCEvent(object):
pass
def keycode(key):
if key in constants.KEYMAP:
return constants.KEYMAP.get(key)
elif len(key) == 1:
return ord(key)
else:
raise error.Error('Not sure how to translate t... | return 'KeyEvent', self.key, self.down
def __repr__(self):
if self.down:
direction = 'down'
else:
direction = 'up'
name = self._keysym_to_name.get(self.key)
if not name | :
name = '0x{:x}'.format(self.key)
else:
name = '{} (0x{:x})'.format(name, self.key)
return 'KeyEvent<key={} direction={}>'.format(name, direction)
def __str__(self):
return repr(self)
def __hash__(self):
return (self.key, self.down).__hash__()
def ... |
micha-shepher/oervoer-wizard | oervoer-django/oervoer/src/wizard/tables.py | Python | gpl-3.0 | 5,346 | 0.009166 | '''
Created on Apr 4, 2015
@author: mshepher
'''
from django.utils.safestring import mark_safe
from django_tables2.utils import A # alias for Accessor
import django_tables2 as tables
from models import Taste, Product, Order, Owner, Pet, PickList
# from setuptools.dist import sequence
class ProductTable(tables.Tabl... | class Meta:
# add class="paleblue" to <table> tag
| attrs = {"class": "paleblue"}
orderable = False
class BriefTable(tables.Table):
vleestype = tables.Column()
name = tables.Column()
aantal = tables.Column()
class Meta:
# add class="paleblue" to <table> tag
attrs = {"class": "paleblue"}
orderable = False
class ... |
yephper/django | tests/i18n/forms.py | Python | bsd-3-clause | 820 | 0.00122 | from django import forms
from .models import Company
class I18nForm(forms.Form):
decimal_field = forms.DecimalField(localize=True)
float_field = forms.FloatField(localize=True)
date_field = forms.DateField(localize=True)
datetime_field = forms.DateTimeField(localize=True)
time_field = f... | =4, decimal_pl | aces=2, localize=True)
products_delivered = forms.IntegerField(localize=True)
date_added = forms.DateTimeField(localize=True)
class Meta:
model = Company
fields = '__all__'
|
helfertool/helfertool | src/helfertool/override_translations.py | Python | agpl-3.0 | 410 | 0.002439 | from django.utils.translation import ugettext_lazy as _
# Django uses the first translation it detects in an installed app.
# The "helfertool" app is listed first, so we have can override default translations here.
#
# Just put the english text here and tr | anslate it, this vesion will be used.
# There is no other purpose of this file, it is not included anywhere. |
override_translations = [
_("User"),
]
|
team-xue/xue | xue/cms/migrations/0009_added_meta_fields.py | Python | bsd-3-clause | 7,114 | 0.011808 | # -*- coding: utf-8 -*-
from south.db import db
from django.db import models
from cms.models import *
import datetime
class Migration:
def forwards(self, orm):
# Adding field 'Title.meta_keywords'
db.add_column('cms_title', 'meta_keywords', models.CharField(_("keywords"), max_length=2... | ('models.BooleanField', ["_('login required')"], {'default': 'False' | }),
'navigation_extenders': ('models.CharField', ['_("navigation extenders")'], {'blank': 'True', 'max_length': '80', 'null': 'True', 'db_index': 'True'}),
'parent': ('models.ForeignKey', ['Page'], {'db_index': 'True', 'related_name': "'children'", 'null': 'True', 'blank': 'True'}),
... |
mmetak/streamlink | src/streamlink/plugins/tf1.py | Python | bsd-2-clause | 2,485 | 0.002817 | from __future__ import print_function
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, useragents
from streamlink.stream import HDSStream
from streamlink.stream import HLSStream
class TF1(Plugin):
url_re = re.compile(r"https?://(?:www\.)?(?:tf1\.fr/(\w+)/direct|(lci).fr/dire... | oidliveconnect", "lci": "androidlivelci"}
hls_channel_remap = {"lci": "LCI", "tf1": "V4"}
@classmethod
def can_handle_url(cls, url):
return cls.url_re.match(url) is not None
def _get_hds_streams(self, channel):
channel = self.hds_channel_remap.get(cha | nnel, "{0}live".format(channel))
manifest_url = http.get(self.api_url.format(channel),
params={"getURL": 1},
headers={"User-Agent": useragents.FIREFOX}).text
for s in HDSStream.parse_manifest(self.session,
... |
twotreeszf/AriaThunder | xunlei-lixian/lixian_colors_console.py | Python | bsd-3-clause | 845 | 0.048521 |
__all__ = ['Console']
import sys
styles = [
'black',
'blue',
'green',
'red',
'cyan',
'yellow',
'purple',
'white',
'bold',
'italic',
'underline',
'inverse',
]
class Console:
def __init__(self, output=None, styles=[]):
output = output or sys.stdout
if isinstance(output, | Console):
self.output = output.output
self.styles = output.styles + styles
else:
self.output = output
self.styles = styles
assert not isinstance(self.output, Console)
def __getattr__(self, name):
if name in styles:
return self.ansi(name)
else:
raise AttributeError(name)
def ansi(self, code)... | .write(s)
def write(self, s):
self.output.write(s)
def flush(self, *args):
self.output.flush(*args)
|
manjitkumar/drf-url-filters | filters/tests/tests.py | Python | mit | 102 | 0 | import unittest
class | MyTest(unittest.TestCase):
def | test(self):
self.assertEqual(4, 4)
|
tibotic/simple-pokemongo-bot | pokemongo_bot/socketio_server/app.py | Python | mit | 852 | 0.004695 | import logging
import socket | io
from flask import Flask
sio = socketio.Server(async_mode='eventlet', logging=logging.NullHandler)
app = Flask(__name__)
# client asks for data
@sio.on('remote:send_request')
def remote_control(sid, command):
if not 'account' in command:
return False
bot_name = command.pop('account')
event = 'b... | on('bot:send_reply')
def request_reply(sid, response):
event = response.pop('command')
account = response['account']
event = "{}:{}".format(event, account)
sio.emit(event, response)
@sio.on('bot:broadcast')
def bot_broadcast(sid, env):
event = env['event']
account = env['account']
event_nam... |
kevinbeaty/mvw | mvw/converters/pygmentsconvert.py | Python | mit | 1,084 | 0.000923 | """ Converter using Pygments.
Registers Pygments for all lexer file types. Should
be registered first to allow overriding other converters
for specific extensions (markdown, etc). """
import codecs
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_for_f... | urn self.config.render_template(theme, content, **context)
def handles(self, source):
try:
return get_lexer_for_filename(source) is not None
except:
| return False
|
bheni/sql4json | sql4json/boolean_expressions/tree_nodes.py | Python | apache-2.0 | 3,354 | 0.001789 | """
Base class for all nodes created and used by the binary expression
BooleanExpressionTree defines an interface used for evaluating the tree.
"""
class Node(object):
def evaluate(self, evaluation_param):
raise NotImplementedError("evaluate not implemented")
def add_child(self, node):
raise ... | __str__(self):
return ' '.join(self.expression_tokens)
"""
UnaryOperatorNodes evaluate boolean operations on a single operand node
"""
class UnaryOperatorNode(Node):
OPERATORS = frozenset(tuple("!"))
def __init__(self, operator, operand_node=None):
self.operator = operator
self.oper... | = operand_node
def evaluate(self, evaluation_param):
if self.operator == "!":
return not self.operand_node.evaluate(evaluation_param)
else:
raise Exception("Unary operator %s not defined" % self.operator)
def add_child(self, node):
if self.operand_node is not N... |
syats/ModuleReusability | aux/decompositionWithSurrogates.py | Python | gpl-3.0 | 10,182 | 0.042035 | '''
Author: Victor Mireles - Freie Universitaet Berlin
Email: syats.vm@gmail.com
Latest version: https://github.com/syats/ModuleReusability
Distributed under GPL V3.0
'''
import numpy as np
import pickle
import glob
import scipy as sci
from scipy.stats import entropy
import permutationsOfArtifi... | x and some random equivalents of it (surrogates). The main aim of this is to refrain from recompouting decompositions and surrogates which might take a while"""
def __init__(self, description, Creal=None,heuristicParameters=None):
self.realC = Creal;
self.realHash = hash(str(Creal));
self.realCurves = [];
sel... | teDecompositions = []
self.surrogateHashes = [];
self.description = description;
self.heuristicParameters = heuristicParameters;
def addC(self,C,typeC,curves,curveNames,Bs=[]):
if typeC=='real' or typeC=='REAL':
self.realC = C;
d = dict();
for cn in range(len(curveNames)):
name = curveNames[cn]... |
eli261/jumpserver | apps/terminal/backends/command/es.py | Python | gpl-2.0 | 734 | 0 | # -*- coding: utf-8 -*-
#
from jms_storage.es import ESStorage
from | .base import CommandBase
from .models import AbstractSessionCommand
class CommandStore(ESStorage, CommandBase):
def __init__(self, params):
super().__init__(params)
def filter(self, date_from=None, date_to=None,
user=None, asset=None, system_user=None,
input=None, sessio... | None):
data = super().filter(date_from=date_from, date_to=date_to,
user=user, asset=asset, system_user=system_user,
input=input, session=session)
return AbstractSessionCommand.from_multi_dict(
[item["_source"] for item in data["hit... |
spnow/grr | lib/export_test.py | Python | apache-2.0 | 27,095 | 0.001513 | #!/usr/bin/env python
"""Tests for export converters."""
import os
import socket
# 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 export
from grr.lib import flags
from grr.lib import ... | testConverterIsCorrectlyFound(self):
dummy_value = DummyRDFValue("result")
result = list(export.ConvertValues(rdfvalue.ExportedMetadata(),
[dummy_value]))
self.assertEqual(len(result), 1)
self.assertTrue(isinstance(result[0], rdfvalue.RDFString))
self.assertEq... | lt")
def testRaisesWhenNoConverterFound(self):
dummy_value = DummyRDFValue2("some")
result_gen = export.ConvertValues(rdfvalue.ExportedMetadata(),
[dummy_value])
self.assertRaises(export.NoConverterFound, list, result_gen)
def testConvertsSingleValueWithMultipleAs... |
roubert/python-phonenumbers | python/phonenumbers/data/region_SJ.py | Python | apache-2.0 | 1,827 | 0.007663 | """Auto-generated file, do not edit by hand. SJ metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_SJ = PhoneMetadata(id='SJ', country_code=47, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='0\\d{4}|[4789]\\d{7}', possible_number_pa... | r_pattern='\\d{8}', example_number='81021234'),
personal_number=PhoneNumberDesc(national_number_pattern='880\\d{5}', possible_number_pattern='\\d{8}', e | xample_number='88012345'),
voip=PhoneNumberDesc(national_number_pattern='85[0-5]\\d{5}', possible_number_pattern='\\d{8}', example_number='85012345'),
pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
uan=PhoneNumberDesc(national_number_pattern='0\\d{4}|81(?:0(?:0[7-9]|1\\d)... |
bilke/OpenSG-1.8 | SConsLocal/scons-local-0.96.1/SCons/Tool/suncc.py | Python | lgpl-2.1 | 1,732 | 0.002309 | """SCons.Tool.suncc
Tool-specific initialization for Sun Solaris (Forte) CC and cc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004 The SCons Foundation
#
# Permission... | antial 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
# LIABLE FOR ANY CLAI... | SING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "/home/scons/scons/branch.0/baseline/src/engine/SCons/Tool/suncc.py 0.96.1.D001 2004/08/23 09:55:29 knight"
import cc
def generate(env):
"""
Add Builders and construction variables for Forte ... |
eduNEXT/edx-platform | common/lib/capa/capa/safe_exec/safe_exec.py | Python | agpl-3.0 | 6,279 | 0.000956 | """Capa's specialized use of codejail.safe_exec."""
import hashlib
from codejail.safe_exec import SafeExecException, json_safe
from codejail.safe_exec import not_safe_exec as codejail_not_safe_exec
from codejail.safe_exec import safe_exec as codejail_safe_exec
from edx_django_utils.monitoring import function_trace
i... | nsafely": unsafely,
"extra_files": extra_files,
}
emsg, exception = get_remote_exec(data)
else:
# Decide | which code executor to use.
if unsafely:
exec_fn = codejail_not_safe_exec
else:
exec_fn = codejail_safe_exec
# Run the code! Results are side effects in globals_dict.
try:
exec_fn(
code_prolog + LAZY_IMPORTS + code,
g... |
ryfeus/lambda-packs | Keras_tensorflow_nightly/source2.7/tensorflow/contrib/stateless/gen_stateless_random_ops.py | Python | mit | 13,285 | 0.007 | """Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: stateless_random_ops.cc
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _cont... | loat32
dtype = _execute.make_type(dtype, "dtype")
_, _, _op = _op_def_lib._apply_op_helper(
"StatelessRandomUniform", shape=shape, seed=seed, dtype=dtype,
name=name)
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("dtype", _op.get_attr("dtype"), "T", _op.get_attr("T"), "... | _op.get_attr("Tseed"))
_execute.record_gradient(
"StatelessRandomUniform", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
else:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._eager_context.device_name,
"St... |
zuun77/givemegoogletshirts | leetcode/python/980_unique_paths_III.py | Python | apache-2.0 | 938 | 0.036247 | class Solution:
def uniquePathsIII(self, grid: 'List[List[int]]') -> 'int':
self.res = 0
R, C, E = len(grid), len(grid[0]), 1
for i in range(R):
for j in range(C):
if grid[i][j] == 1: x,y = (i, j)
elif grid[i][j] == 2: end = (i, j)
... | 1
def dfs(x, y, E):
if not (0 <= x < R and 0 <= y < C and grid[x][y] >= 0): return
if (x,y) == end and E == 0:
self.res += 1
return
grid[x][y] = -2
dfs(x+1, y, E-1)
dfs(x- | 1, y, E-1)
dfs(x, y+1, E-1)
dfs(x, y-1, E-1)
grid[x][y] = 0
dfs(x, y, E)
return self.res
s = Solution()
print(s.uniquePathsIII([[1,0,0,0],[0,0,0,0],[0,0,2,-1]]))
print(s.uniquePathsIII([[1,0,0,0],[0,0,0,0],[0,0,0,2]]))
print(s.uniquePathsIII([[0,1],[2,0]]))
|
tensorflow/agents | tf_agents/replay_buffers/py_replay_buffers_test.py | Python | apache-2.0 | 12,535 | 0.005185 | # coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | elf._transition_count):
self._replay_buffer.add_batch(nest_utils.batch_nested_array(
trajectory.from_trans | ition(
time_steps[k], dummy_action, time_steps[k + 1])))
def _generate_replay_buffer(self, rb_cls):
self._create_replay_buffer(rb_cls)
self._fill_replay_buffer()
@parameterized.named_parameters(
[('WithoutHashing', py_uniform_replay_buffer.PyUniformReplayBuffer),
('WithHashing',... |
KonradIT/gopro-py-api | examples/dump_sdcard.py | Python | mit | 186 | 0.010753 | from goprocam import GoProCamera, c | onstants
gpCam = GoProCamera.GoPro()
|
## Downloads all of the SD card's contents and then formats the sd card.
gpCam.downloadAll()
gpCam.delete("all") |
macagua/joomla2plone-transmogrifier | src/joomla2plone.policy/setup.py | Python | gpl-2.0 | 1,795 | 0.004457 | from setuptools import setup, find_packages
import os
version = '1.0'
setup(name='joomla2plone.policy',
version=version,
description="A policy package to manage a Plone installation",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt"))... | p']),
namespace_packages=['joomla2plone'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'Plone',
'Products.CMFPlacefulWorkflow',
'joomla2plone.migration',
# 'transmogrify.joomla2nitf',
# 'collective.nitf',
#... | 'collective.upload==1.0b5',
# 'collective.polls==1.0.1',
# 'collective.polls==1.4',
# 'collective.flowplayer',
],
entry_points="""
[z3c.autoinclude.plugin]
target = plone
""",
)
|
jrha/aquilon | upgrade/1.4.5/aquilon/aqdb/model/building.py | Python | apache-2.0 | 2,077 | 0.00674 | # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabs | top=4 shiftwidth=4:
#
# Copyright (C) 2008,2009,2010,2013 Contributor
#
# 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.or | g/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation... |
openx/python3-protobuf | python/google/protobuf/internal/utils.py | Python | bsd-3-clause | 3,630 | 0.002479 | from __future__ import unicode_literals
"""
This module abstracts all the bytes<-->string conversions so that the python 2
and 3 code everywhere else is similar. This also has a few simple functions
that deal with the fact that bytes are different between the 2 versions even
when using from __future__ import unicode_... | urn bytes([ord(c) for c in text])
def bytes_to_string(byte_array):
"""
Inverse of string_to_bytes.
"""
return ''.join([chr(b) for b in byte_array])
def string_to_bytestr(string):
"""
Convert a string to a bytes object. This encodes the object as well which
... | will typically change ord on each element & change the length (i.e. 1 char
could become 1/2/3 bytes)
"""
return string.encode('utf-8')
def bytestr_to_string(bytestr):
"""
Inverse of string_to_bytestr.
"""
return bytes([c for c in bytestr]).decode('utf-8')
... |
pySTEPS/pysteps | pysteps/motion/lucaskanade.py | Python | bsd-3-clause | 9,903 | 0.000505 | # -*- coding: utf-8 -*-
"""
pysteps.motion.lucaskanade
==========================
The Lucas-Kanade (LK) local feature tracking module.
This module implements the interface to the local `Lucas-Kanade`_ routine
available in OpenCV_.
For its dense method, it additionally interpolates the sparse vectors over a
regular g... | ection components o | f the vectors.
Return two empty arrays when no motion is detected.
See also
--------
pysteps.motion.lucaskanade.track_features
References
----------
Bouguet, J.-Y.: Pyramidal implementation of the affine Lucas Kanade
feature tracker description of the algorithm, Intel Corp.,... |
zjurelinac/pyFrisc | simulator.py | Python | mit | 11,657 | 0.051042 | from utils import *
import sys
class FRISCProcessor:
def __init__( self, mem_size, program = None ):
self.MEM_SIZE = mem_size
self.SP = '111'
self.memory = []
self.annotations = []
self.registers = {}
self.last_changed_address = -1
self.flags = {
... | ] = '{0:0>8b}'.for | mat( int( l[ j : ( j+2 ) ], 16 ) )
except ValueError:
pass
tnum = num
self.annotations[ num ] = a.strip()
def run( self ):
try:
while( not self.flags[ 'TERM' ] ):
self.run_step()
# self.show_registers()... |
aESeguridad/GERE | venv/lib/python2.7/site-packages/pyphen/__init__.py | Python | gpl-3.0 | 10,375 | 0 | # This file is part of Pyphen
#
# Copyright 2008 - Wilbert Berendsen <info@wilbertberendsen.nl>
# Copyright 2012-2013 - Guillaume Ayoub <guillaume.ayoub@kozea.fr>
#
# This library is free software. It is released under the
# GPL 2.0+/LGPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and
# COPYING.MPL for m... | ts patterns.
:param filename: filename of hyph_*.dic to read
"""
self.patterns = {}
with open(filename, 'rb') as stream:
# see " | man 4 hunspell", iscii-devanagari is not supported by python
charset = stream.readline().strip().decode('ascii')
if charset.lower() == 'microsoft-cp1251':
charset = 'cp1251'
for pattern in stream:
pattern = pattern.decode(charset).strip()
... |
FeitianSmartcardReader/pssi | pssi/plugins/emv/plugin.py | Python | gpl-3.0 | 1,019 | 0.003929 | # -*- coding: utf-8 -*-
# -- plugin.py
# Functions required by every plugin
# Copyright © 2010 Eric Bourry & Julien Flaissy
# This file is part of PSSI (Python Simple Smartcard Interpreter).
# PSSI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publ... | ic License
# along with PSSI. If not, see <http://www.gnu.org/licenses/>
import interpreters
import structures
def getClassByte():
return 0x00
def getRootStructure() | :
return structures.structEMV
def getInterpretersTable():
return interpreters.interpretingFunctions
|
gkbrk/hackchat | setup.py | Python | mit | 404 | 0.044554 | from setuptools import setup
setup(
name = "hackchat",
py_modules = ["hackchat"],
version = "0.2.0",
description = "An event-driven hack.chat client library.",
author = "Gokberk Yaltirakli",
| author_email = "webdosusb@gmail.com",
url = "https://github.com/gkbrk/hackchat",
keywords = ["hack.chat", "event", "c | lient", "chat"],
install_requires = ["websocket-client"]
)
|
dcalacci/love-in-the-time-of-communism | src/mention_graph.py | Python | mit | 401 | 0.002494 | #!/usr/bin/env python
import networkx as nx
import pandas as pd
| import numpy as np
def mention_graph_no_sentiment():
df = pd.read_pickle('pickles/with_corenlp_mentions.p')
G = nx.DiGraph()
for n, row in df.iterrows():
speaker = row['speaker']
mentions = row['corenlp_mentions']
for ment | ion in mentions:
G.add_edge(speaker, mentions)
return G
|
aglitke/vdsm | tests/gluster_cli_tests.py | Python | gpl-2.0 | 45,993 | 0 | #
# Copyright 2012 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in th... | <value>*</value>
</option>
</options>
</volume>
<volume>
<name>test1</name>
<id>b444ed94-f346-4cda-bd55-0282f21d22db</id>
<status>2</status>
<statusStr>Stopped</statusStr>
<brickCount>1</brickCount>
<distCount>1</distCount>
<strip... | /typeStr>
<transport>1</transport>
<bricks>
<brick>192.168.122.2:/tmp/test1-b1</brick>
</bricks>
<optCount>0</optCount>
<options/>
</volume>
<count>2</count>
</volumes>
</volInfo>
</cliOutput>
"""
tree = etree.fromstring(out)
oVolumeInf... |
s-leger/archipack | archipack_molding.py | Python | gpl-3.0 | 29,198 | 0.000959 | # -*- coding:utf-8 -*-
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ... | self.length = 0
| self.user_defined_post = None
self.user_defined_uvs = None
self.user_defined_mat = None
def add_part(self, part):
if len(self.segs) < 1:
s = None
else:
s = self.segs[-1]
# start a new molding
if s is None:
p = Vector((0, 0... |
MasLinoma/scrapy_crawl | tongbutui/tongbutui/spiders/tongbutui_spider.py | Python | gpl-2.0 | 11,003 | 0.035408 | #!/usr/bin/python2.7
# -*- coding=utf-8 -*-
fro | m scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
import time
from tongbutui.items import htmlItem
import re,sys
class tongbutuiSpider(BaseSpider):
"""
用于抓取tong... | p://app.tongbu.com/',
]
def printhxs(self,hxs):
for i in hxs:
print i.encode('utf-8')
def parse_one_game(self, response):
hxs = HtmlXPathSelector(response)
#print "parse_one_game"
#self.printhxs(response.meta['game_category'])
error = hxs.select("//div[@class='error']/text()") or ['ok']
if(e... |
SUNET/eduid-webapp | src/eduid_webapp/actions/tests/test_tou.py | Python | bsd-3-clause | 10,899 | 0.001835 | # -*- coding: utf8 -*-#
# Copyright (c) 2015 NORDUnet A/S
# 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. Redistributions of source code must retain the above copyright
# ... | NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import json
from datetime import datetime, timedelta
from typing import Any, Optional
from bson import ObjectId
from mock import patch
from eduid_common.session import session
from ... | ns.testing import ActionsTestCase, MockIdPContext
__author__ = 'eperez'
TOU_ACTION = {
'_id': ObjectId('234567890123456789012301'),
'eppn': 'hubba-bubba',
'action': 'tou',
'preference': 100,
'params': {'version': 'test-version'},
}
class MockRTask(object):
@staticmethod
def get(timeout: ... |
Velmont/digital-signage-server | lib/utils/dockit.py | Python | mit | 943 | 0.006363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012, Rui Carmo
Description: Docstring utility functions
License: MIT (see LICENSE.md for details)
"""
import os, sys, logging
import inspect
from bottle import app
log = logging.getLogger()
def docs():
"""Gather all docstrings related to routes an... | if not doc:
doc = ''
module = inspect.getmodule(route.callback).__name__
item = {
'method': route.method,
'route': route.rule,
'function': route.callback.__name__,
'module': module,
'doc': inspect.cleandoc(doc)
}
... | modules[module] = []
modules[module].append(item)
return modules |
Andrew-McNab-UK/DIRAC | tests/Integration/Monitoring/Test_MonitoringSystem.py | Python | gpl-3.0 | 18,888 | 0.011859 | """
It is used to test client->db-> service. It requires the Monitoring service.
"""
import unittest
import tempfile
import time
from datetime import datetime
from DIRAC import gLogger
from DIRAC.MonitoringSystem.Client.MonitoringClient import MonitoringClient
from DIRAC.Core... | Type': u'MCSimulation', u'MinorStatus': u'unset', u'Site': u'LCG.IHEP.su', u'Reschedules': 0, u'ApplicationStatus': u'unset', u'User': u'phicharp', u'JobGroup': u'00050248', u'UserGroup': u'lhcb_mc', u'metric': u'WMSHistory'},
{u'Status': u'Running', 'Jobs': 12, u'timestamp': 1458218413, u'JobSplitType... | AF.it', u'Reschedules': 0, u'ApplicationStatus': u'unset', u'User': u'phicharp', u'JobGroup': u'00050248', u'UserGroup': u'lhcb_mc', u'metric': u'WMSHistory'},
{u'Status': u'Running', 'Jobs': 5, u'timestamp': 1458218413, u'JobSplitType': u'MCSimulation', u'MinorStatus': u'unset', u'Site': u'LCG.CNAF.it... |
ddico/account-financial-tools | account_invoice_constraint_chronology/__init__.py | Python | agpl-3.0 | 40 | 0 | from . import model
from | . import tes | ts
|
beagles/neutron_hacking | neutron/db/migration/alembic_migrations/versions/40b0aff0302e_mlnx_initial.py | Python | apache-2.0 | 7,472 | 0.000401 | # Copyright 2014 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 'routerl3agentbindings',
sa.Column('id', sa.String(length=36), nullable=False),
sa.Column('router_id', sa.String(length=36), nullable=True),
sa.Column('l3_agent_id', sa.String(length=36), nullable=True),
sa.ForeignKeyConstraint(['l3_agent_id'], ['agents.id'],
... | ),
sa.PrimaryKeyConstraint('id'),
)
op.create_table(
'routerroutes',
sa.Column('destination', sa.String(length=64), nullable=False),
sa.Column('nexthop', sa.String(length=64), nullable=False),
sa.Column('router_id', sa.String(length=36), nullable=False),
sa.Forei... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.