content stringlengths 4 20k |
|---|
"""Utility functions for use with the Google App Engine Pipeline API."""
__all__ = ["for_name",
"JsonEncoder",
"JsonDecoder"]
#pylint: disable=g-bad-name
import datetime
import inspect
import logging
import os
# Relative imports
from mapreduce.third_party import simplejson
# pylint: disable=p... |
"""
Copyright 2008-2011 Free Software Foundation, Inc.
This file is part of GNU Radio
GNU Radio Companion 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 l... |
import math
import time
import random
money = 1000
print('Punto Banco rules. Tie bets pay 8:1.')
print('5 percent commission on winning Banker bets.')
print('You start out with ${money}.'.format(money = money))
values = {'2 of <3': 2, '3 of <3': 3, '4 of <3': 4, '5 of <3': 5,
'6 of <3': 6, '7 of <3': 7, '8 of <3': 8, ... |
"""
Tests for Session Tokens
"""
import unittest
import os
from boto.exception import BotoServerError
from boto.sts.connection import STSConnection
from boto.sts.credentials import Credentials
from boto.s3.connection import S3Connection
class SessionTokenTest(unittest.TestCase):
sts = True
def test_session_... |
"""Tests for our flags implementation."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from tensorflow.python.platform import app
from tensorflow.python.platform import flags
FLAGS = flags.FLAGS
flags.DEFINE_boolean('myflag', False, '')
def ... |
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Initialize Qt resources from file resources.py
import resources_rc
# Import the code for the dialog
from maindialog import MainDialog
class Qgis2Web(object):
"""Class abstraction for managing Qgis2Web plugin in QGIS."""
def __init_... |
"""Tests for MNIST Dataset with tf.keras."""
import os
import sys
import pytest
if sys.platform == "darwin":
pytest.skip(
"Documentation test only need to be run on Linux, skip macOS",
allow_module_level=True,
)
def extract_block(filename, lang):
"""extract_block"""
source = ""
... |
import pickle
import glob
import numpy as np
import os
import pandas as pd
import json
from sklearn.preprocessing import StandardScaler
import common
import time
"""
patches.py: computes the patches and normalizes de data.
Requires the previous run of 'exp_setup.py'.
The results and parameters of this script are sto... |
import os
try:
import MySQLdb
mysqldb_found = True
except ImportError:
mysqldb_found = False
def mysql_connect(module, login_user=None, login_password=None, config_file='', ssl_cert=None, ssl_key=None, ssl_ca=None, db=None, cursor_class=None,
connect_timeout=30):
config = {}
if... |
"""
Some basic admin tests.
Rather than testing the frontend UI -- that's be a job for something like
Selenium -- this does a bunch of mocking and just tests the various admin
callbacks.
"""
from __future__ import absolute_import
import mock
from django.contrib import admin
from django.contrib.auth.models import Use... |
import urllib
from itertools import ifilter
from swift.common import bufferedhttp
from swift.common import exceptions
from swift.common import http
class Sender(object):
"""
Sends SSYNC requests to the object server.
These requests are eventually handled by
:py:mod:`.ssync_receiver` and full document... |
"""Implementation of JSONDecoder
"""
import re
import sys
import struct
from lib.simplejson.scanner import make_scanner
try:
from lib.simplejson._speedups import scanstring as c_scanstring
except ImportError:
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _fl... |
import json
from ansible.module_utils.urls import fetch_url
try:
from urllib import quote_plus # Python 2.X
except ImportError:
from urllib.parse import quote_plus # Python 3+
def request(module, api_url, project, path, access_token, private_token, rawdata='', method='GET'):
url = "%s/v4/projects/%s%s... |
from __future__ import unicode_literals
import frappe, erpnext
from frappe import _
from frappe.utils import flt, fmt_money, getdate, formatdate
from frappe.model.document import Document
from erpnext.accounts.party import validate_party_gle_currency, validate_party_frozen_disabled
from erpnext.accounts.utils import ge... |
# -*- 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):
# Adding field 'GeneratedCertificate.name'
db.add_column('certificates_generatedcertificate', 'name',
... |
from .charsetprober import CharSetProber
from .constants import eNotMe
from .compat import wrap_ord
FREQ_CAT_NUM = 4
UDF = 0 # undefined
OTH = 1 # other
ASC = 2 # ascii capital letter
ASS = 3 # ascii small letter
ACV = 4 # accent capital vowel
ACO = 5 # accent capital other
ASV = 6 # accent small vowel
ASO = 7... |
from copy import copy
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
# Cache of actual callables.
_standard_context_processors = None
# We need the CSRF processor no matter what the user has in their settings,
# because otherwise it is a security vulnerability,... |
from operator import attrgetter, lt, gt
class Walker(object):
__slots__ = ['_node', '_stack', '_tree']
def __init__(self, tree):
self._tree = tree
self._node = tree.root
self._stack = []
def reset(self):
self._stack = []
self._node = self._tree.root
@property... |
#Run this file after automatic conversion of the VisualStudio 2008 solution by VisualStudio 2010.
#This can be done whenever the 2008 solution changes.
#It will make the necessary cleanup and updates to the vcxproj files
#the .props files need to be maintained by hand if the .vsprops files change
from __future__ impor... |
"""Tests for Keras optimizers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gc
import weakref
import numpy as np
from tensorflow.python import keras
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
from ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json",
}
imp... |
#!/usr/bin/env python
"""Check Nginx config on readthedocs.org."""
import sys
import requests
# Globals to keep count of test results
TESTS = 0
FAILS = 0
def served_by_nginx(url):
"""Return True if url returns 200 and is served by Nginx."""
r = requests.get(url, allow_redirects=False)
status = (r.stat... |
""" General Server side utilities
"""
import pythoncom
import policy
import winerror
from exception import COMException
def wrap(ob, iid=None, usePolicy=None, useDispatcher=None):
"""Wraps an object in a PyGDispatch gateway.
Returns a client side PyI{iid} interface.
Interface and gateway support must ex... |
"""
The most important decorator in this module is `@api_view`, which is used
for writing function-based views with REST framework.
There are also various decorators for setting the API policies on function
based views, as well as the `@detail_route` and `@list_route` decorators, which are
used to annotate methods on ... |
from .main import TorrentShack
def start():
return TorrentShack()
config = [{
'name': 'torrentshack',
'groups': [
{
'tab': 'searcher',
'list': 'torrent_providers',
'name': 'TorrentShack',
'description': 'See <a href="https://www.torrentshack.net/">T... |
"""
WRITEME
"""
from __future__ import print_function
import logging
import numpy
import theano
from theano import gof
import theano.gof.vm
from theano.configparser import config
from theano.compile.ops import _output_guard
from six import string_types
_logger = logging.getLogger('theano.compile.mode')
def check... |
"""measure the runtime of a command by repeatedly running it.
"""
import time
import subprocess
import sys
devnull = open('/dev/null', 'w')
def run(cmd, repeat=10):
print 'sampling:',
sys.stdout.flush()
samples = []
for _ in range(repeat):
start = time.time()
subprocess.call(cmd, std... |
from __future__ import unicode_literals, print_function
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
#from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
#from seleniu... |
import sys, logging, locale, codecs, subprocess, time, signal, threading, base64
from pyxmpp.all import JID, Iq, Presence, Message, StreamError
from pyxmpp.jabber.client import JabberClient
from pyxmpp import streamtls
from pyxmpp.stanza import Stanza
## pyrepl appears to conflict with screen - get EINTR in os.read()... |
import os
import shutil
import tempfile
from oslo_config import cfg
from oslo_log import log as logging
from nova import exception
from nova.i18n import _, _LI, _LW
from nova.network import dns_driver
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
class MiniDNS(dns_driver.DNSDriver):
"""Trivial DNS driver. ... |
from gettext import NullTranslations
from sys import version_info
import base64
import itertools
import locale
import types
PY3 = version_info.major >= 3
if PY3:
from io import StringIO
import queue
import urllib.parse
# functions renamed in py3
Queue = queue.Queue
basestring = unicode = str
... |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from nose.tools import (assert_equal, assert_is, assert_is_not,
assert_raises)
import pandas as pd
from ggplot import *
from ggplot.utils.exceptions import GgplotError
from . import clea... |
import functools
from engineio import json as _json
(CONNECT, DISCONNECT, EVENT, ACK, CONNECT_ERROR, BINARY_EVENT, BINARY_ACK) = \
(0, 1, 2, 3, 4, 5, 6)
packet_names = ['CONNECT', 'DISCONNECT', 'EVENT', 'ACK', 'CONNECT_ERROR',
'BINARY_EVENT', 'BINARY_ACK']
class Packet(object):
"""Socket.IO p... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Issues"),
"items": [
{
"type": "doctype",
"name": "Issue",
"description": _("Support queries from customers."),
},
{
"type": "doctype",
"name": "Communication",
"descri... |
"""Test if correct arguments are passed to Whoosh to search
indexed content
"""
from mock import patch
from pyramid import testing
from unittest import TestCase
class TestSearchAttr(TestCase):
attr = []
def _return_attr(self, *args, **kwargs):
"""Saves arguments passed to WhooshFulltext
sea... |
# pylint: disable=C0302,bare-except,print-statement
"""pylint option block-disable"""
__revision__ = None
class Foo(object):
"""block-disable test"""
def __init__(self):
pass
def meth1(self, arg):
"""this issues a message"""
print self
def meth2(self, arg):
"""and thi... |
import re
import traceback
from bs4 import BeautifulSoup
from couchpotato.core.helpers.variable import tryInt, simplifyString
from couchpotato.core.logger import CPLog
from couchpotato.core.media._base.providers.nzb.base import NZBProvider
log = CPLog(__name__)
class Base(NZBProvider):
urls = {
'downl... |
"""
Unit tests for Windows Hyper-V virtual switch neutron driver
"""
import mock
from oslo.config import cfg
from neutron.plugins.hyperv.agent import hyperv_neutron_agent
from neutron.plugins.hyperv.agent import utilsfactory
from neutron.tests import base
class TestHyperVNeutronAgent(base.BaseTestCase):
def se... |
"""Fixer for it.next() -> next(it), per PEP 3114."""
# Things that currently aren't covered:
# - listcomp "next" names aren't warned
# - "with" statement targets aren't checked
# Local imports
from ..pgen2 import token
from ..pygram import python_symbols as syms
from .. import fixer_base
from ..fixer_util import ... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
translate.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
from MaKaC.common.contextManager import ContextManager
class AccessWrapper:
"""This class encapsulates the information about an access to the system. It
must be initialised by clients if they want to perform access
control operations over the objects in the system.
"""
def __init_... |
from __future__ import unicode_literals
import os
import base64
import datetime
import hashlib
import copy
import itertools
import codecs
import six
from bisect import insort
from moto.core import BaseBackend, BaseModel
from moto.core.utils import iso_8601_datetime_with_milliseconds, rfc_1123_datetime
from .exceptions... |
class Base(object):
""" Base class for vcf_filter.py filters """
name = 'f'
""" name used to activate filter and in VCF headers """
description = 'VCF filter base class'
""" descrtiption used in vcf headers """
@classmethod
def customize_parser(self, parser):
""" hook to extend ar... |
"""A parser for HTML and XHTML."""
# This file is based on sgmllib.py, but the API is slightly different.
# XXX There should be a way to distinguish between PCDATA (parsed
# character data -- the normal case), RCDATA (replaceable character
# data -- only char and entity references and end tags are special)
# a... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'core'}
try:
import selinux
HAVE_SELINUX=True
except ImportError:
HAVE_SELINUX=False
try:
import semanage
HAVE_SEMANAGE=True
except ImportError:
HAVE_SEMANAGE=... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**Impact Function Manager**
Contact : <EMAIL>
.. note:: 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; eithe... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'core'}
import re
from ansible.module_utils.iosxr import run_commands
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import iteritems
from ansible.module_u... |
"""
Utilities used to convert a field to human classic reprentation of data.
"""
from lib.hachoir_core.tools import (
humanDuration, humanFilesize, alignValue,
durationWin64 as doDurationWin64,
deprecated)
from types import FunctionType, MethodType
from lib.hachoir_core.field import Field
def textHandler(... |
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from UGM_Database import settings
from django.shortcuts import redirect
from django.contrib.staticfiles.urls import staticfiles_urlpatterns,static
def Print(value):
print '\n\n\n\n',value
test = [i for ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutInheritance(Koan):
class Dog:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def bark(self):
return "WOOF"
... |
import unittest
import plistlib
import os
import datetime
from test import test_support
# This test data was generated through Cocoa's NSDictionary class
TESTDATA = """<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" \
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist... |
#!/usr/bin/env python
import sys, json
from argparse import ArgumentParser, FileType
from configparser import ConfigParser
from models import FrogjumpDB
from OpenSSL import SSL, crypto
from random import randint
from traceback import print_exc
from twisted.internet import ssl
from twisted.internet.defer import Deferre... |
"""
Cross Site Request Forgery Middleware.
This module provides a middleware that implements protection
against request forgeries from other sites.
"""
from __future__ import unicode_literals
import logging
import re
from django.conf import settings
from django.core.urlresolvers import get_callable
from django.utils... |
"""Working with audio using FFmpeg.
See the @{$python/contrib.ffmpeg} guide.
@@decode_audio
@@encode_audio
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.ffmpeg.ffmpeg_ops import decode_audio
from tensorflow.contrib.ffmpeg.ffm... |
# -*- coding: utf-8 -*-
import logging
import requests
from datetime import timedelta, datetime
import statistics
import json
import re
from time import sleep
logger = logging.getLogger(__name__)
DEFAULT_TIMEOUT = 60 * 30 # 60 seconds * 30 (30 minutes)
class EventKitClient(object):
def __init__(self, url, use... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: wait_for_connection
short_description: Waits until remo... |
"""Tests for tf.contrib.gan.python.features.random_tensor_pool."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.gan.python.features.python.random_tensor_pool_impl import tensor_pool
from tensorflow.python.frame... |
import argparse
import gym
from gym import wrappers
import os.path as osp
import random
import numpy as np
import tensorflow as tf
import tensorflow.contrib.layers as layers
import dqn
from dqn_utils import *
from atari_wrappers import *
def atari_model(ram_in, num_actions, scope, reuse=False):
with tf.variable_... |
import pygame, sys, math, time
class Player():
def __init__(self, size=[52, 56], maxSpeed =5 , speed=[0, 0], pos=[0,64]):
self.imageLeft = pygame.image.load("Resources/Player/Player Left.png")
self.imageRight = pygame.image.load("Resources/Player/Player Right.png")
self.imageUpleft = ... |
"""
Benchmark for SGD regression
Compares SGD regression against coordinate descent and Ridge
on synthetic data.
"""
print(__doc__)
# License: BSD 3 clause
import numpy as np
import pylab as pl
import gc
from time import time
from sklearn.linear_model import Ridge, SGDRegressor, ElasticNet
from sklearn.metrics i... |
import os
test = {
"deployment_code": os.path.join(os.path.dirname(os.path.abspath(__file__)), "deployment.py"),
"test_code": [
os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_suites/base_tests_multiple_iteration.py")],
"perf_code": os.path.join(os.path.dirname(os.path.abspath(__file__)), "p... |
""" This module implements a class registry.
We scan the memory_plugins directory for all python files and add those
classes which should be registered into their own lookup tables. These
are then ordered as required. The rest of Volatility will then call onto the
registered classes when needed.
This mechanism allows... |
"""Solvers for linear least-squares."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from tensorflow.contrib.solvers.python.ops import util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dt... |
"""
Email backend that writes messages to console instead of sending them.
"""
import sys
import threading
from django.core.mail.backends.base import BaseEmailBackend
from django.utils import six
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
self.stream = kwargs.pop('stream', ... |
{
'name': 'Rental',
'version': '8.0.0.1.0',
'category': 'Sales Management',
'license': 'AGPL-3',
'summary': 'Manage Rental of Products',
'author': 'Akretion',
'website': 'http://www.akretion.com',
'depends': ['sale_start_end_dates', 'stock'],
'data': [
'sale_view.xml',
... |
# -*- coding: utf-8 -*-
import unittest
from wechatpy import replies
def create_reply(cls, **kwargs):
return cls(source="source", target="target", time=123456789, **kwargs)
class DeserializeReplyTestCase(unittest.TestCase):
def test_empty_reply_deserialize(self):
reply = replies.EmptyReply()
... |
#!/usr/bin/python
#
# tests leaking file descriptors
#
#
# USAGE: $0 SERVER SYSTEMID
import os
import sys
sys.path.append('..')
from rhn.rpclib import Server
from threading import Thread
import time
SERVER = "xmlrpc.rhn.redhat.com"
HANDLER = "/XMLRPC"
system_id_file = '/etc/sysconfig/rhn/systemid'
try:
SERVER =... |
__all__ = ['Profile',
'FirefoxProfile',
'MetroFirefoxProfile',
'ThunderbirdProfile']
import os
import time
import tempfile
import types
import uuid
from addons import AddonManager
import mozfile
from permissions import Permissions
from prefs import Preferences
from shutil import copyt... |
from openerp import http
from openerp.addons.website_sale.controllers.main import website_sale
class WebsiteSale(website_sale):
@http.route(
['/shop',
'/shop/page/<int:page>',
'/shop/category/<model("product.public.category"):category>',
'/shop/category/<model("product.public.ca... |
import logging
from fabric.api import serial, task, parallel, env, execute, runs_once, settings,sudo
from fabfile.safety import noopable
from multiprocessing import Manager
from timestamps import no_ts
from packages import PackageInfo
import tempfile
from output import notify
@task
@parallel
def collect_installed_pac... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
parse_iso8601,
parse_duration,
)
class SkyNewsArabiaBaseIE(InfoExtractor):
_IMAGE_BASE_URL = 'http://www.skynewsarabia.com/web/images'
def _call_api(self, p... |
__version__ = '0.70a1'
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event',... |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline compliance reporting for transportation fuel suppliers in accordance with the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: v1
... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsComposition.
.. note:: 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.
"""
__... |
#!/usr/bin/env python
from __future__ import print_function
import fileinput
import sys
import turbostat_to_csv as turbostat_to_csv
from src.pipelines import csv_to_json as csv_to_json
from src.pipelines import json_to_TSDB_json as json_to_TSDB_json
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **k... |
from sqlalchemy.engine import default
from sqlalchemy.databases import *
from sqlalchemy.orm import mapper
from sqlalchemy.orm import Session
from sqlalchemy.testing import AssertsCompiledSQL, eq_
from sqlalchemy.testing import assert_raises_message
from sqlalchemy import exc
from test.orm import _fixtures
class Lega... |
# -*- coding: utf-8 -*-
import os
from cerberus import Validator
import pprint
from json import JSONDecodeError
import json
"""
Utilities for validating parameters
We use the `cerberus` schema validation library: http://docs.python-cerberus.org
"""
def validate_simple_report_params(params):
""" Validate all para... |
"""Discrete approximations to continuous distributions"""
# Contributors:
# Copyright (c) 2014, Stanford University
# All rights reserved.
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __futur... |
"""
A shim for the TemporalMemory class that transparently implements TP,
for use with tests.
"""
import numpy
from nupic.math import GetNTAReal
from nupic.research.TP import TP
from nupic.research.TP10X2 import TP10X2
from nupic.research.connections import Connections
TPClass = TP10X2
dtype = GetNTAReal()
clas... |
from openerp import api, fields, models, _
class ProductCategory(models.Model):
_inherit = 'product.category'
no_create_variants = fields.Boolean(
string="Don't create variants automatically",
help='This check disables the automatic creation of product variants '
'for all the pro... |
import numpy as np
from sklearn.preprocessing import OneHotEncoder
import matplotlib.pyplot as plt
from data import sample_gmm_2d, eval_perf_binary, graph_data, graph_surface
def forward(X, w_1, w_2, b_1, b_2):
s_1 = np.dot(X, w_1) + b_1
h_1 = np.maximum(s_1, np.zeros(s_1.shape))
s_2 = np.dot(h_1, w... |
import time, os
delay = 0.25
print "Getting list of all projects"
v = os.listdir('/projects')
print "Got %s projects"%len(v)
for project_id in sorted(v):
c = "bup_storage.py chown %s"%project_id
print c
os.system(c)
time.sleep(delay) |
"""Shared utilities for dealing with taskqueue."""
import datetime
from google.appengine.api import apiproxy_stub_map
from google.appengine.api.taskqueue import taskqueue_service_pb
def _human_readable_eta(eta_usec):
eta = datetime.datetime.utcfromtimestamp(eta_usec / 1e6)
return eta.strftime('%Y/%m/%d %H:%M:... |
"""
Views for manual refunds in the student support UI.
This interface is used by the support team to track refunds
entered manually in CyberSource (our payment gateway).
DEPRECATION WARNING:
We are currently in the process of replacing lms/djangoapps/shoppingcart
with an E-Commerce service that supports automatic re... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RoomReservation'
db.create_table(u'logistics_roomreservat... |
# -*- coding: utf-8 -*-
import base64
import logging
import os
import re
import zlib
from babelfish import Language, language_converters
from guessit import guess_episode_info, guess_movie_info
from six.moves.xmlrpc_client import ServerProxy
from . import Provider, TimeoutSafeTransport, get_version
from .. import __v... |
#!/usr/bin/env py.test
"""Unit test for HarmonicSmoothing and ALE"""
# Copyright (C) 2013 Jan Blechta
#
# This file is part of DOLFIN.
#
# DOLFIN is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either... |
from Screens.Screen import Screen
from Components.ActionMap import NumberActionMap
from Components.Label import Label
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from InfoBarGenerics import InfoBarShowHide, InfoBarMenu, InfoBarInstantRecord, InfoBarTimeshift, InfoBarSeek, InfoBarTi... |
# encoding: utf-8
# module PyQt4.QtXml
# from /usr/lib/python2.7/dist-packages/PyQt4/QtXml.so
# by generator 1.135
# no doc
# no imports
class QDomNamedNodeMap(): # skipped bases: <type 'sip.simplewrapper'>
"""
QDomNamedNodeMap()
QDomNamedNodeMap(QDomNamedNodeMap)
"""
def contains(self, QString): #... |
"""Deal with Microsoft-specific Authenticode data."""
# Comments and constant names as extracted from pecoff_v8 specs.
# Variable names are also used as defined in the PECOFF specification.
# pylint: disable-msg=C6409
# Version 1, legacy version of Win_Certificate structure. It is supported
# only for purposes of ver... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
from waflib.Options import OptionsContext
import optparse
class Feature(object):
def __init__(self, group, feature):
self.group = group
self.identifier, self.attributes = feature['name'], feature
def add_options(self):
[self.add_option(option_rule) for option_rule in self.option_ru... |
"""
Tests for DOT Adapter
"""
from datetime import timedelta
import ddt
from django.conf import settings
from django.test import TestCase
from django.utils.timezone import now
from oauth2_provider import models
import unittest
from student.tests.factories import UserFactory
from ..adapters import DOTAdapter
from .c... |
"""
Create certificates and private keys for the 'simple' example.
"""
from OpenSSL import crypto
from certgen import * # yes yes, I know, I'm lazy
cakey = createKeyPair(TYPE_RSA, 2048)
careq = createCertRequest(cakey, CN='Certificate Authority')
cacert = createCertificate(careq, (careq, cakey), 0, (0, 60*60*24*365*... |
#!/usr/bin/env python
'''
This extension converts a path into a dashed line using 'stroke-dasharray'
It is a modification of the file addnodes.py
Copyright (C) 2005,2007 Aaron Spike, <EMAIL>
Copyright (C) 2009 Alvin Penner, <EMAIL>
This program is free software; you can redistribute it and/or modify
it under the ter... |
import builtins
open = builtins.open
# for seek()
SEEK_SET = 0
SEEK_CUR = 1
SEEK_END = 2
r"""File-like objects that read from or write to a string buffer.
This implements (nearly) all stdio methods.
f = StringIO() # ready for writing
f = StringIO(buf) # ready for reading
f.close() # explicitly rel... |
import os
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import base64
class Options(object):
def __init__(self):
self._binary_location = ''
self._arguments = []
self._extension_files = []
self._experimental_options = {}
@property
def binar... |
""" 'editor' hooks for common editors that work well with ipython
They should honor the line number argument, at least.
Contributions are *very* welcome.
"""
import IPython.ipapi
ip = IPython.ipapi.get()
from IPython.Itpl import itplns
import os
def install_editor(run_template, wait = False):
""" Gets a templa... |
__problem_title__ = "Luxury Hampers"
__problem_url___ = "https://projecteuler.net/problem=236"
__problem_description__ = "Suppliers 'A' and 'B' provided the following numbers of products for " \
"the luxury hamper market: Although the suppliers try very hard to " \
"s... |
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Relation(models.Model):
pass
class AbstractPerson(models.Model):
# DATA fields
data_abstract = models.CharField(max_len... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.