content stringlengths 4 20k |
|---|
import colors
import os
import sys
import traceback
_colors_supported = 'TERM' in os.environ and os.environ['TERM'] != 'unknown'
using_colors = _colors_supported
_uncolored = lambda x: x
_error_colorizer = colors.red
_warning_colorizer = colors.yellow
def _indent(txt, indent_count=1):
return ' ' * indent_cou... |
"""Documentation Flask Blueprint."""
from __future__ import unicode_literals
import os
from flask import Blueprint, abort, current_app, render_template, url_for
from flask.helpers import send_from_directory
from flask_breadcrumbs import current_breadcrumbs, default_breadcrumb_root, \
register_breadcrumb
from f... |
FACEBOOK_TEMPLATES = (
('question',(
#one-line
['{*actor*} <a href="{*url*}">asked a question about the article</a>: {*headline*}.'],
[{#short story
'template_title': '{*actor*} <a href="{*url*}">asked a question about the article</a>: {*headline*}.',
'template_body':... |
import gzip
import cPickle
import numpy as np
import os
import os.path
import sys
import time
from trainer import Trainer
from model import PI_MNIST_model, MNIST_model, CIFAR10_SVHN_model
from pylearn2.datasets.mnist import MNIST
from pylearn2.datasets.zca_dataset import ZCA_Dataset
from pylearn2.... |
"""
.. versionadded:: 0.93
Geopy can calculate geodesic distance between two points using the
[Vincenty distance](https://en.wikipedia.org/wiki/Vincenty's_formulae) or
[great-circle distance](https://en.wikipedia.org/wiki/Great-circle_distance)
formulas, with a default of Vincenty available as the function
`geopy.dist... |
# -*- coding: utf-8 -*-
from django import forms
from django.utils.six.moves import xrange
ASC = 'asc'
DESC = 'desc'
SORT_DIRS = (
(ASC, ASC),
(DESC, DESC),
)
class DatatablesForm(forms.Form):
'''
Datatables server side processing Form
See: http://www.datatables.net/usage/server-side
'''
... |
import os
from core import path_util
from core import perf_benchmark
from telemetry import benchmark
from telemetry import page as page_module
from telemetry.page import legacy_page_test
from telemetry.page import shared_page_state
from telemetry import story
from telemetry.value import list_of_scalar_values
from be... |
import pickle
import time
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from alexnet import AlexNet
nb_classes = 43
epochs = 10
batch_size = 128
with open('./train.p', 'rb') as f:
data = pickle.load(f)
X_train, X_val, y_train, y_val = train_test_s... |
"""Miscellaneous functions.
run_command borrowed from Cheesecake - See CREDITS.
"""
import os
import signal
import subprocess
import time
def get_yolk_dir():
"""Return location we store config files and data."""
return os.path.abspath('%s/.yolk' % os.path.expanduser('~'))
def run_command(args, env=None, ... |
import sys
sys.path.append('./')
import logging
import struct
from collections import defaultdict
import tools.modified.androguard.core.androconf as androconf
import tools.modified.androguard.decompiler.dad.util as util
from tools.modified.androguard.core.analysis import analysis
from tools.modified.androguard.core.by... |
"""
Test that updating an alias saves it to the roster.
"""
import dbus
from servicetest import EventPattern, call_async, assertEquals
from gabbletest import (
acknowledge_iq, exec_test, make_result_iq, sync_stream, elem
)
import constants as cs
import ns
from rostertest import expect_contact_list_signals, se... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from provider.compat import user_model_label
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Client'
db.create_table('oauth2_client', (
... |
#!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
# Program Parameters
#
import os
import s... |
"""Tests for RNN cells."""
# pylint: disable=g-bad-import-order,unused-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tens... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Resources\ui_files\settings\database_settings_widget.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DatabaseSettingsWidget(o... |
"""Unit test for depstree."""
__author__ = '<EMAIL> (Nathan Naze)'
import os
import unittest
import jscompiler
class JsCompilerTestCase(unittest.TestCase):
"""Unit tests for jscompiler module."""
def testGetFlagFile(self):
flags_file = jscompiler._GetFlagFile(['path/to/src1.js', 'path/to/src2.js'],
... |
import six
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
from django.core.cache import cache
from django.utils.functional import lazy
from wagtailsystemtext.models import SystemString
from wagtailsystemtext import app_settings
_thread_locals = local()
... |
"""Helper methods for various modules."""
from collections.abc import MutableSet
from itertools import chain
import threading
import queue
from datetime import datetime
import re
import enum
import socket
import random
import string
from functools import wraps
from types import MappingProxyType
from typing import Any,... |
# A Job consists of many "Tasks".
# A task is the run of an external tool, with proper methods for failure handling
from Tools.CList import CList
class Job(object):
NOT_STARTED, IN_PROGRESS, FINISHED, FAILED = range(4)
def __init__(self, name):
self.tasks = [ ]
self.resident_tasks = [ ]
self.workspace = "/tmp... |
"""
Check the the latest "whatsnew" contributions files have usable names.
The files in "./docs...whatsnew/contributions_<xx.xx>/" should have filenames
with a particular structure, which encodes a summary name.
These names are interpreted by "./docs...whatsnew/aggregate_directory.py".
This test just ensures that all ... |
"""
Views for managing Neutron Networks.
"""
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import tables
from horizon.utils import memoized
from horizon import workflows
from openstack_das... |
from rest_framework import status as http_status
from flask import redirect, request
import markupsafe
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError, PermissionsError
from framework import status
from osf.exceptions import UnsupportedSanctionHandlerKind, TokenErro... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from __future__ import print_function
from elasticsearch import Elasticsearch, helpers
class ElasticsearchPipeline(object):
... |
""" utility functions """
from functools import wraps
import logging
import os
import sys
# pylint: disable=invalid-name,no-self-use,dangerous-default-value
# ---------------------------------------------------------
# common consts
PRIMARY = 'mysql-primary'
REPLICA = 'mysql'
UNASSIGNED = 'UNASSIGNED'
# -----------... |
import os
import sys
import traceback
__all__ = ['IgnoreException', 'importall',]
DEBUG=0
get_frame = sys._getframe
class IgnoreException(Exception):
"Ignoring this exception due to disabled feature"
def output_exception(printstream = sys.stdout):
try:
type, value, tb = sys.exc_info()
info ... |
from __future__ import print_function
from itertools import chain, groupby
from six import itervalues
from networkx import Graph, NetworkXUnfeasible, relabel_nodes
from networkx.algorithms.bipartite import is_bipartite_node_set
from matching import maxmatch_len
from pqueue import PriorityQueue as minheap
from py3compat... |
from pointtransformer import PointTransformer
class PointTransformerXML(PointTransformer):
def point2text(self, l, id=None):
i = ""
if id is not None:
i = " id='" + id + "'"
return "<point" + i + " x='" + str(l[0]) + "' y='" + str(l[1]) + "' />"
def face2text(self, l, id=... |
"""Support for the MaryTTS service."""
import asyncio
import logging
import re
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.helpers.aiohttp_client impor... |
from collections import namedtuple
from squares import *
# Location = namedtuple("Location", ["x","y"]) # named tuple for coordinates only
# Position = namedtuple("Position", ["loc","orient"]) # named tuple for Loc + orient
class Location:
def __init__(self,x,y):
self.x = x
self.y = y
def __... |
from .tokenize import new_token_base
from .dfa import NFAState, nfa2dfa
ASTTokenBase = new_token_base()
class Num(ASTTokenBase):
regular_expr = '[0-9]+'
class String(ASTTokenBase):
__slots__ = ['string']
regular_expr = "'[^']*'"
def __init__(self, data):
# TODO string escape
self.... |
"""This module implements tools for integrating rational functions. """
from __future__ import print_function, division
from sympy import S, Symbol, symbols, I, log, atan, \
roots, collect, solve, RootSum, Lambda, cancel, Dummy
from sympy.polys import Poly, subresultants, resultant, ZZ
from sympy.core.compatibil... |
import logging
from pylons import cache, request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.decorators import rest
from kai.lib.base import BaseController, CMSObject, render
from kai.lib.decorators import validate
from kai.lib.helpers import success_flas... |
__doc__="""info.py
Representation of ApcPdu components.
$Id: info.py,v 1.2 2010/12/14 20:45:46 jc Exp $"""
__version__ = "$Revision: 1.4 $"[11:-2]
from zope.interface import implements
from Products.Zuul.infos import ProxyProperty
from Products.Zuul.infos.component import ComponentInfo
from Products.Zuul.decorators... |
import Adafruit_BMP.BMP085 as BMP085
# Default constructor will pick a default I2C bus.
#
# For the Raspberry Pi this means you should hook up to the only exposed I2C bus
# from the main GPIO header and the library will figure out the bus number based
# on the Pi's revision.
#
# For the Beaglebone Black the library wi... |
import github.GithubObject
class Topic(github.GithubObject.NonCompletableGithubObject):
"""
This class represents topics as used by https://github.com/topics. The object reference can be found here https://docs.github.com/en/rest/reference/search#search-topics
"""
def __repr__(self):
return s... |
"""Module to create a simple http server."""
# -*- coding: utf-8 -*-
import io
import os
import mimetypes
BUFF_LENGTH = 1024
class RequestError(BaseException):
"""Class for creating new exceptions for HTTP requests."""
def __init__(self, code, reason):
"""Inherit from BaseException class."""
... |
"""Represent resource consumption statistics for processes
This module exposes one class: the ProcessSample, used to represent resource consumption. A single
ProcessSample might correspond to one individual process, or to an aggregate of multiple processes.
"""
from collections import namedtuple
class ProcessSampl... |
"""Fix task status NULLability
Revision ID: 19b9071910f9
Revises: 431e4e2ccbba
Create Date: 2014-10-07 14:56:14.828618
"""
# revision identifiers, used by Alembic.
revision = '19b9071910f9'
down_revision = '431e4e2ccbba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column('job', 'stat... |
"""Macintosh binhex compression/decompression.
easy interface:
binhex(inputfilename, outputfilename)
hexbin(inputfilename, outputfilename)
"""
#
# Jack Jansen, CWI, August 1995.
#
# The module is supposed to be as compatible as possible. Especially the
# easy interface should work "as expected" on any plat... |
"""Constants used in the Mikrotik components."""
DOMAIN = "mikrotik"
DEFAULT_NAME = "Mikrotik"
DEFAULT_API_PORT = 8728
DEFAULT_DETECTION_TIME = 300
ATTR_MANUFACTURER = "Mikrotik"
ATTR_SERIAL_NUMBER = "serial-number"
ATTR_FIRMWARE = "current-firmware"
ATTR_MODEL = "model"
CONF_ARP_PING = "arp_ping"
CONF_FORCE_DHCP = ... |
# -*- encoding: utf-8 -*-
from abjad.tools import mathtools
from abjad.tools.abctools.AbjadValueObject import AbjadValueObject
class RehearsalMark(AbjadValueObject):
r'''A rehearsal mark.
.. container:: example
**Example 1.** Rehearsal A:
::
>>> staff = Staff("c'4 d' e' f'")
... |
from gi.repository import Gtk
from pychess.System.prefix import addDataPrefix
from .__init__ import CENTER, TabReceiver
from .PyDockComposite import PyDockComposite
from .StarArrowButton import StarArrowButton
from .HighlightArea import HighlightArea
class PyDockLeaf(TabReceiver):
def __init__(self, widget, ti... |
import email.parser
import email.policy
import os
import tempfile
import unittest
from unittest import mock
from alot.db import envelope
SETTINGS = {
'user_agent': 'agent',
}
class TestEnvelope(unittest.TestCase):
def assertEmailEqual(self, first, second):
with self.subTest('body'):
sel... |
# -*- coding: iso-8859-1 -*-
from time import time
from boxbranding import getImageVersion
from enigma import eConsoleAppContainer
from Components.Console import Console
from Components.PackageInfo import PackageInfoHandler
from Components.Language import language
from Components.Sources.List import List
from Compone... |
import jwt
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework.authentication import (BaseAuthentication,
get_authorization_header)
from rest_framework_jwt import utils
from ... |
# -*- coding: utf-8 -*-
"""
sphinx.builders.devhelp
~~~~~~~~~~~~~~~~~~~~~~~
Build HTML documentation and Devhelp_ support files.
.. _Devhelp: http://live.gnome.org/devhelp
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __futur... |
# This module exports classes for the various canvas item types
# NOTE: This module was an experiment and is now obsolete.
# It's best to use the Tkinter.Canvas class directly.
from Tkinter import Canvas, _cnfmerge, _flatten
class CanvasItem:
def __init__(self, canvas, itemType, *args, **kw):
self.canva... |
"""RBAC Role based parametrization and checking
The purpose of this fixture is to allow tests to be run within the context of multiple different
users, without the hastle or modifying the test. To this end, the RBAC module and fixture do not
require any modifications to the test body.
The RBAC fixture starts by recei... |
import os
import sys
import functools
STATUS = 0
def error_unless_permitted(env_var, message):
global STATUS
if not os.getenv(env_var):
sys.stderr.write(message)
STATUS = 1
def only_on(platforms):
def decorator(func):
@functools.wraps(func)
def inner():
if an... |
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
import packaging.version
import pkg_resources
import google.auth # type: ignore
import google.api_core # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # ty... |
'''list_pubs.py - list Azure publishers'''
import json
import sys
import azurerm
def main():
'''Main routine.'''
# Load Azure app defaults
try:
with open('azurermconfig.json') as config_file:
config_data = json.load(config_file)
except FileNotFoundError:
sys.exit("Error: Ex... |
from zeobuilder.actions.abstract import AddBase
from zeobuilder.actions.collections.menu import MenuInfo
from zeobuilder.nodes.meta import Property
from zeobuilder.nodes.model_object import ModelObject, ModelObjectInfo
from zeobuilder.gui.fields_dialogs import DialogFieldInfo
import zeobuilder.gui.fields as fields
impo... |
"""Multi-credential file store with lock support.
This module implements a JSON credential store where multiple
credentials can be stored in one file. That file supports locking
both in a single process and across processes.
The credential themselves are keyed off of:
* client_id
* user_agent
* scope
The format of ... |
import os
import shutil
from lib.util.mysqlBaseTestCase import mysqlBaseTestCase
server_requirements = [['--innodb_file_per_table']]
servers = []
server_manager = None
test_executor = None
# we explicitly use the --no-timestamp option
# here. We will be using a generic / vanilla backup dir
backup_path = None
class ... |
from __future__ import unicode_literals
import unittest
import frappe
import json
import frappe.defaults
from frappe.utils import cint, nowdate, nowtime, cstr, add_days, flt
from erpnext.stock.stock_ledger import get_previous_sle
from erpnext.accounts.utils import get_balance_on
from erpnext.stock.doctype.purchase_rece... |
#!/usr/bin/env python
# File created on 09 Feb 2010
from __future__ import division
import operator
import numpy
import os
import sys
from qiime.collate_alpha import write_output_file, make_output_row
from qiime.parse import parse_matrix, parse_rarefaction_fname
from qiime.util import FunctionWithParams
from qiime.util... |
#!/usr/bin/env python3
import ijson.backends.asyncio as ijson
from statsSend.teamCity.teamCityBuildConfiguration import TeamCityBuildConfiguration
class TeamCityProject:
def __init__(self, session, id):
self.session = session
self.id = id
#{
# "nextHref": "/httpAuth/app/rest/buildType... |
"""
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 this ... |
from webkitpy.tool.commands.abstractsequencedcommand import AbstractSequencedCommand
from webkitpy.tool import steps
class PrettyDiff(AbstractSequencedCommand):
name = "pretty-diff"
help_text = "Shows the pretty diff in the default browser"
steps = [
steps.ConfirmDiff,
] |
"""TensorFlow Lite Python Interface: Sanity check."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.lite.python import convert
from tensorflow.lite.python import op_hint
from tensorflow.lite.python.interpreter import Int... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
#
# All Plot3D scalar functions
#
# Create the RenderWindow, Renderer and both Actors
#
renWin = vtk.vtkRenderWindow()
iren = vtk.vtkRenderWindowInteractor()
iren.SetRend... |
import json
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
class CreateMappingForm(forms.SelfHandlingForm):
id = forms.CharField(label=_("Mapping ID"),
max... |
import sys
import os
import time
from .server_tools import create_session_on_server, reset_database
from .management.commands.create_session import create_pre_authenticated_session
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
fr... |
# encoding: 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):
# Adding field 'Member.average_monthly_committee_presence'
db.add_column('mks_member', 'average_monthly_co... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
GdalAlgorithmTests.py
---------------------
Date : January 2016
Copyright : (C) 2016 by Matthias Kuhn
Email : <EMAIL>
***********************************... |
"""Test whether task queues work."""
import pytest
import psycopg2
import testing.postgresql
import pgtq
@pytest.fixture()
def db():
"""Yield a handle to a temporary Postgres database."""
pg = testing.postgresql.Postgresql()
yield pg
pg.stop()
def test_can_make_queue(db):
"""Test whether a task ... |
# -*- coding: utf-8 -*-
# vim: set ts=4 et
import cgi
import requests
from six.moves.html_parser import HTMLParser
from plugin import *
content_types = (
'text/html',
'text/xml',
'application/xhtml+xml',
'application/xml'
)
class TitleParser(HTMLParser):
def __init__(self):
HTMLParser._... |
import sys
import appuifw
import e32
class Console:
def __init__(self):
from e32 import Ao_lock
from key_codes import EKeyEnter
self.input_wait_lock = Ao_lock()
self.input_stopped = False
self.control = self.text = appuifw.Text()
self.text.bind(EKeyEnter, self.input_... |
from __future__ import unicode_literals
from django.utils.encoding import smart_str
from waffle.utils import get_setting
class WaffleMiddleware(object):
def process_response(self, request, response):
secure = get_setting('SECURE')
max_age = get_setting('MAX_AGE')
if hasattr(request, 'wa... |
#!/usr/bin/env python
import os,socket, sys
import json
from fabric.state import _AttributeDict, env
from fabric.operations import run, sudo
from fabric.context_managers import cd, settings
from fabric.contrib.files import append, contains, exists
from fabric.decorators import runs_once
from woven.decorators import r... |
from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.cpuinfo import cpu
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import ex... |
from PyQt4 import QtCore, QtGui
import sys, DB_manager, DB_manager2, DB_manager3, MDB_manager
from match2 import Ui_MatchManager
from player import Ui_PlayerManager
from resultats import Ui_ResultsManager
from comp import Ui_competition
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUt... |
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe import msgprint, _
from frappe.model.naming import make_autoname
from frappe.contacts.address_and_contact import load_address_and_contact, delete_contact_and_address
from erpnext.utilities.transaction_base import TransactionBase
fr... |
# -*- coding: utf-8 -*-
import functools
import httplib as http
import markupsafe
from django.core.paginator import Paginator
from django.db.models import Q, QuerySet
from flask import request
from framework.exceptions import HTTPError
from osf.utils.requests import check_select_for_update
def get_or_http_error(Mod... |
# A little library for the generation and attribute checking of
# matrix of integers
from numpy import *
def symmetricPositiveDefinite(n, maxValue= 1):
''' Generates a n x n random symmetric, positive-definite matrix.
The optionnal maxValue argument can be used to specify a maximum
absolute value for extr... |
try:
from pysqlite2 import dbapi2 as sqlite
except ImportError:
import sqlite3 as sqlite
from pprint import pprint
import os
class accessdb:
def __init__(self, dbname='sqlite.db'):
self.conn = sqlite.connect(dbname)
def close(self):
self.conn.close()
def hit(self, ip, version, po... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class CreateFork(Choreography):
def __init__(self, temboo_session):
"""
Create a ne... |
"""A demonstration of oslo.i18n integration module usage.
This example requires the following module to be installed.
$ pip install oslo.i18n
More information can be found at:
http://docs.openstack.org/developer/oslo.i18n/usage.html
http://docs.openstack.org/developer/oslo.i18n/guidelines.html
http://docs.ope... |
import logging
from unittest import mock
import fixtures
from snapcraft.main import main
from snapcraft import (
storeapi,
tests,
)
class ChannelClosingTestCase(tests.TestCase):
def setUp(self):
super().setUp()
self.fake_logger = fixtures.FakeLogger(level=logging.DEBUG)
self.use... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# $Id: test_maximal_independent_set.py 577 2011-03-01 06:07:53Z lleeoo $
"""
Tests for maximal (not maximum) independent sets.
"""
# Copyright (C) 2004-2010 by
# Leo Lopes <<EMAIL>>
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# ... |
#!/usr/bin/env python
'''test cairo.ImageSurface.create_from_png() and
cairo.Surface.write_to_png()
'''
import os
import tempfile
import cairo
if not (cairo.HAS_IMAGE_SURFACE and cairo.HAS_PNG_FUNCTIONS):
raise SystemExit ('cairo was not compiled with ImageSurface and PNG support')
inFileName = os.path.jo... |
import sys
import gc
import uos as os
import uerrno as errno
import ujson as json
import uzlib
import upip_utarfile as tarfile
gc.collect()
debug = False
install_path = None
cleanup_files = []
gzdict_sz = 16 + 15
file_buf = bytearray(512)
class NotFoundError(Exception):
pass
def op_split(path):
if path == ... |
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import quota_classes
from nova.api.openstack import wsgi
from nova import test
from nova.tests.api.openstack import fakes
def quota_set(class_name):
return {'quota_class_set': {'id': class_name, 'metadata_items': 128,
'volume... |
"""
Returns the right style name for any kind of tag (status, priority, etc)
"""
from django.conf import settings
from django.template.base import Library
from django.utils.safestring import mark_safe
from motte.tagcss.models import TagCssEntry
register = Library()
@register.filter("tagstyle", is_safe=False)
def st... |
"""
Copyright 2015 - Ivan Dortulov
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 i... |
"""
Support for inheritance of fields down an XBlock hierarchy.
"""
from __future__ import absolute_import
from datetime import datetime
from django.conf import settings
from pytz import UTC
from xmodule.partitions.partitions import UserPartition
from xblock.fields import Scope, Boolean, String, Float, XBlockMixin, D... |
#! -*- coding: utf-8 -*-
import sys
import unittest
from JapaneseTokenizer.mecab_wrapper import MecabWrapper
from JapaneseTokenizer.datamodels import TokenizedSenetence, FilteredObject, TokenizedResult
import os
__author__ = 'kensuke-mi'
class TestFilter(unittest.TestCase):
def setUp(self):
'''紗倉 まな(さくらまな... |
import parser
import ast
import sys
import getopt
import os
from subprocess import call
def usage():
print "Usage: "
print " python check.py --input filename.jff --print (optional)"
print " python check.py --clean"
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "i:pc", ["input=", "p... |
#coding: utf-8
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
HEADRequest,
)
class AparatIE(InfoExtractor):
_VALID_URL = r'^https?://(?:www\.)?aparat\.com/(?:v/|video/video/embed/videohash/)(?P<id>[a-zA-Z0-9]+)'
_TEST = {
u'url': u'http://www.aparat.com/v/... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = u'WiCS Undergraduate Committee'
SITENAME = u'Women in Computer Science'
SITEURL = ''
PATH = 'content'
STATIC_PATHS = [ 'images', 'extra' ]
EXTRA_PATH_METADATA = {
'extra/robots.txt': # sit these in the top directory... |
import socket, time, threading
from jedie_python_ping.ping import verbose_ping
class StoppableThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stop_event = threading.Event()
def stop(self):
if self.isAlive() == True:
# set event to signal t... |
#!/usr/bin/env python3
import sys
from util import proctal_cli, sleeper, algorithms
permission_flags = ["r", "w", "x"]
# All possible combinations.
possible_permissions = algorithms.all_combinations(permission_flags)
possible_permissions = map(lambda x: ''.join(x), possible_permissions)
guinea = sleeper.run()
for ... |
#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of se... |
import sys
import string
# Slice off the script name
args = sys.argv[1:]
if len(args) != 2 :
print "Usage: createDialogTemplate algorithm-name yes|no\n" \
"\tyes - Create the class so that it can be used with Qt designer\n"\
"\tno - Create the class so that the layout must be created by hand"
exit(1)... |
import os
import re
import sys
import json
import optparse
#--------------------------------------------------------------------
# reads:
# http://svn.webkit.org/repository/webkit/trunk/WebCore/css/CSSPropertyNames.in
# writes:
# json array
#--------------------------------------------------------------------
def ... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2012-2015 ARM Limited
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 ... |
import logging
LOG_FORMATTER = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
ROOT_LOGGER = logging.getLogger()
ROOT_LOGGER.setLevel(logging.WARN)
CONSOLE_HANDLER = logging.StreamHandler()
CONSOLE_HANDLER.setFormatter(LOG_FORMATTER)
ROOT_LOGGER.addHa... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ansible.compat.te... |
import rospy
from sensor_msgs.msg import Range
#import NAO dependencies
from naoqi_driver.naoqi_node import NaoqiNode
class SonarSensor(object):
# default values
# NAO sonar specs
# see https://community.aldebaran.com/doc/1-14/family/robots/sonar_robot.html
SONAR_FREQ = 10
SONAR_MIN_RANGE = 0.25
... |
from flask import request
from funcy import project
from redash import models
from redash.permissions import require_admin_or_owner
from redash.handlers.base import BaseResource, require_fields, get_object_or_404
class QuerySnippetResource(BaseResource):
def get(self, snippet_id):
snippet = get_object_or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.