content string |
|---|
import Get_MW
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import numpy as np
N=10 #number of frequencies
#These values are starting positions for coronal CME radio observations
ParmIn=29*[0] # input array
ParmIn[0] =8e19 # Area, cm^2
ParmIn[1] =5e9 # Depth, cm
ParmIn[2] =3... |
# -*- coding: utf-8 -*-
r"""
werkzeug.posixemulation
~~~~~~~~~~~~~~~~~~~~~~~
Provides a POSIX emulation for some features that are relevant to
web applications. The main purpose is to simplify support for
systems such as Windows NT that are not 100% POSIX compatible.
Currently this only imple... |
import traceback
try:
import ovirtsdk4.types as otypes
except ImportError:
pass
from collections import defaultdict
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
BaseModule,
check_sdk,
create_connection,
ovirt_full_argument_spec,
)
ANSIBLE_META... |
import os
import unittest
from telemetry.core import discover
from telemetry.core import util
class DiscoverTest(unittest.TestCase):
def setUp(self):
self._base_dir = util.GetUnittestDataDir()
self._start_dir = os.path.join(self._base_dir, 'discoverable_classes')
self._base_class = Exception
def test... |
{
'name': 'Honduras - Accounting',
'version': '0.1',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Honduras.
====================================================================
Agrega una nomenclatura contable para Honduras... |
"""Python functions for directly manipulating TFRecord-formatted files.
See the @{$python/python_io} guide.
@@TFRecordWriter
@@tf_record_iterator
@@TFRecordCompressionType
@@TFRecordOptions
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# go/tf-wildc... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y'
TIME_FORMAT = 'G:i'
DATETIME_FORMAT = 'j. E Y G:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.... |
import webob
import glance.api.v2.image_tags
from glance.common import exception
from glance.tests.unit import base
import glance.tests.unit.utils as unit_test_utils
import glance.tests.unit.v2.test_image_data_resource as image_data_tests
import glance.tests.utils as test_utils
class TestImageTagsController(base.Iso... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
compat_parse_qs,
compat_urllib_request,
)
class ScreencastIE(InfoExtractor):
_VALID_URL = r'https?://www\.screencast\.com/t/(?P<id>[a-zA-Z0-9]+)'
_TES... |
"""
Rdio OAuth1 and OAuth2 backends, docs at:
http://psa.matiasaguirre.net/docs/backends/rdio.html
"""
from social.backends.oauth import BaseOAuth1, BaseOAuth2, OAuthAuth
RDIO_API = 'https://www.rdio.com/api/1/'
class BaseRdio(OAuthAuth):
ID_KEY = 'key'
def get_user_details(self, response):
ful... |
from thrift.protocol.TProtocol import TProtocolBase
from types import *
class TProtocolDecorator():
def __init__(self, protocol):
TProtocolBase(protocol)
self.protocol = protocol
def __getattr__(self, name):
if hasattr(self.protocol, name):
member = getattr(self.protocol, name)
if type(mem... |
import pygame as gameapi
import pygame.midi as piano
import sys, random
import pygame.locals as apiVar
gameapi.init()
fpsClock = gameapi.time.Clock()
windowSurfaceObj = gameapi.display.set_mode((640, 480))
gameapi.display.set_caption('set_caption')
redColor = gameapi.Color(255,0,0)
greenColor = gameapi.Color(0,255,0... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Host(A10BaseClass):
"""Class Description::
Set remote syslog host DNS name or ip address.
Class host supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param ipv6ad... |
import logging
from core.logger import logger
from twisted.internet.protocol import ClientFactory
formatter = logging.Formatter("%(asctime)s [ServerConnectionFactory] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
log = logger().setup_logger("ServerConnectionFactory", formatter)
class ServerConnectionFactory(ClientFacto... |
def includepath_to_dict(includepath):
search_path = {}
if includepath:
for path in includepath:
key = path[:path.find(':')]
value = path[path.find(':')+1:]
if value:
search_path.setdefault(key, []).append(value)
return search_path |
'''
Created on 19/2/2015
@author: PC29
'''
from app import app
from ec.edu.itsae.dao import PersonaDAO
from flask import render_template, request, redirect, url_for
@app.route("/mainPersona")
def personamain():
objR=PersonaDAO.PersonaDAO().reportarPersona()
return render_template("prueba.html"... |
from mapproxy import grid as mapproxy_grid
from eventkit_cloud.tasks.models import ExportRun
import logging
import json
import math
logger = logging.getLogger(__name__)
_dbg_geom_cache_misses = 0
def _create_cache_geom_entry(job):
"""
Constructs a geometry cache entry
:param job: job contains the geomet... |
keymap_remote = {
"16": 'power' ,#EJECT
"64": None ,#AUDIO
"65": None ,#ANGLE
"63": 'subtitle' ,#SUBTITLE
"0f": None ,#CLEAR
"28": None ,#TIME
"00": 'one' ,#1
"01": 'two' ,#2
"02": 'three' ,#3
"03": 'four' ,#4
"04": 'five' ,#5
"05": 'six'... |
def get_project_stats(project):
"""Return stats for project."""
return [
{
"language": str(tup.language),
"code": tup.language.code,
"total": tup.all,
"translated": tup.translated,
"translated_percent": tup.translated_percent,
"tota... |
'''
Created on May 5, 2011
@author: evan
'''
from kayako.tests import KayakoAPITest
class TestKayakoAPI(KayakoAPITest):
def test_init_without_url(self):
from kayako.api import KayakoAPI
from kayako.exception import KayakoInitializationError
self.assertRaises(KayakoInitializationError, Ka... |
# -*- coding: utf-8 -*-
"""
pythoncompat
"""
from .packages import chardet
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except (ImportError, SyntaxError):
# si... |
from ROOT import TCanvas, TF1, TPaveLabel, TPad, TText
from ROOT import gROOT
nut = TCanvas( 'nut', 'FirstSession', 100, 10, 700, 900 )
nut.Range( 0, 0, 20, 24 )
nut.SetFillColor( 10 )
nut.SetBorderSize( 2 )
pl = TPaveLabel( 3, 22, 17, 23.7, 'My first PyROOT interactive session', 'br' )
pl.SetFillColor( 18 )
pl.Draw... |
# PermWrapper and PermLookupDict proxy the permissions system into objects that
# the template system can understand.
class PermLookupDict:
def __init__(self, user, app_label):
self.user, self.app_label = user, app_label
def __repr__(self):
return str(self.user.get_all_permissions())
def... |
"""TPU system metadata and associated tooling."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import re
from tensorflow.contrib.tpu.python.tpu import tpu
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client i... |
from m5.objects import *
from arm_generic import *
import switcheroo
root = LinuxArmFSSwitcheroo(
cpu_classes=(AtomicSimpleCPU, TimingSimpleCPU, DerivO3CPU)
).create_root()
# Setup a custom test method that uses the switcheroo tester that
# switches between CPU models.
run_test = switcheroo.run_test |
import keystoneclient
import mock
from cloudferrylib.os.compute import keypairs
from tests import test
from cloudferrylib.os.actions import transport_compute_resources as tcr
from cloudferrylib.utils import utils as utl
class KeyPairObjectTestCase(test.TestCase):
def test_key_pair_does_not_include_autoincrement_... |
# -*- coding: utf-8 -*-
"""
sockjs.tornado.transports.jsonp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JSONP transport implementation.
"""
import logging
from tornado.web import asynchronous
from sockjs.tornado import proto
from sockjs.tornado.transports import pollingbase
from sockjs.tornado.util import bytes_to_s... |
from django.apps import AppConfig
from django.apps import apps
from django.db.models import signals
from taiga.projects import signals as generic_handlers
from taiga.projects.custom_attributes import signals as custom_attributes_handlers
from . import signals as handlers
def connect_userstories_signals():
# ... |
from datetime import date
import sys
if len(sys.argv) < 2:
from freetype import *
out_file_cpp = 'Overlay_font_autogen.cpp'
out_file_h = 'Overlay_font_autogen.h'
font_file = 'overlay/DejaVuSansMono-Bold.ttf'
template_out_file_h = u"""// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using {font_file... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
('jury', '__first__'),
migrations.swappable_dependency(settings.AUT... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
parse_duration,
remove_end,
xpath_element,
xpath_text,
)
class DigitallySpeakingIE(InfoExtractor):
_VALID_URL = r'https?://(?:s?evt\.dispeak|events\.digitallyspeaking)\.com/... |
"""
CrayPGI toolchain: Cray compilers (PGI) and MPI via Cray compiler drivers (PrgEnv-pgi) minus LibSci minus Cray FFTW
:author: Jg Piccinali (CSCS)
"""
from easybuild.toolchains.compiler.craype import CrayPEPGI
from easybuild.toolchains.mpi.craympich import CrayMPICH
from easybuild.tools.toolchain import DUMMY_TOOLCHA... |
from __future__ import unicode_literals
from ctypes import windll, Structure, byref, c_uint
from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL
import os.path as op
from .compat import text_type
shell32 = windll.shell32
SHFileOperationW = shell32.SHFileOperationW
class SHFILEOPSTRUCTW(Structure):
_fields_ = ... |
# coding=utf-8
import os
from lxml import etree
from django.test import TestCase
from corehq.apps.app_manager.models import Application
from corehq.apps.app_manager.tests.util import SuiteMixin
from corehq.apps.app_manager.translations import escape_output_value
import commcare_translations
class AppManagerTransla... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
parse_duration,
int_or_none,
determine_protocol,
)
class SWRMediathekIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?swrmediathek\.de/(?:content/)?player\.htm\?show=(?P<id>[\da-f]{8}-[... |
"""The tests for the REST sensor platform."""
import unittest
from pytest import raises
from unittest.mock import patch, Mock
import requests
from requests.exceptions import Timeout, MissingSchema, RequestException
import requests_mock
from homeassistant.exceptions import PlatformNotReady
from homeassistant.setup imp... |
"""
This module turns Lino into a basic calendar client.
When using this app, you probably also like to set
:settings:`use_extensible` to True.
"""
#~ class SiteMixin(object):
#~ """
#~ Class methods and attibutes added to a Site by this module.
#~ """
#~ def get_reminder_generators_by_us... |
"""
Specific tests for (some of) the methods in L{twisted.web.domhelpers}.
"""
from xml.dom import minidom
from twisted.trial.unittest import TestCase
from twisted.web import microdom
from twisted.web import domhelpers
class DOMHelpersTestsMixin:
"""
A mixin for L{TestCase} subclasses which defines test m... |
"""Implementation of JSONEncoder
"""
import re
try:
from _json import encode_basestring_ascii as c_encode_basestring_ascii
except ImportError:
c_encode_basestring_ascii = None
try:
from _json import make_encoder as c_make_encoder
except ImportError:
c_make_encoder = None
ESCAPE = re.compile(r'[\x00-\x... |
"""
.. dialect:: mysql+mysqlconnector
:name: MySQL Connector/Python
:dbapi: myconnpy
:connectstring: mysql+mysqlconnector://<user>:<password>@\
<host>[:<port>]/<dbname>
:url: http://dev.mysql.com/downloads/connector/python/
Unicode
-------
Please see :ref:`mysql_unicode` for current recommendations o... |
import warnings
from eventsourcing.domain.model.entity import EventSourcedEntity
from eventsourcing.domain.model.entity import entity_mutator
from eventsourcing.domain.model.entity import singledispatch
from eventsourcing.domain.model.decorators import subscribe_to
from eventsourcing.domain.model.events import publish... |
import copy
import csv
import os
class Gate:
def __init__(self, Sockets):
self.Sockets = Sockets
self.Inputs = []
self.UniqueInputs = ""
def canPass(self):
return(True)
def getInput(self, I):
if( (type(I) == Input) &
(I.sym().casefold() not ... |
"""
========================================
Comparison of Calibration of Classifiers
========================================
Well calibrated classifiers are probabilistic classifiers for which the output
of the predict_proba method can be directly interpreted as a confidence level.
For instance a well calibrated (bi... |
from twisted.web import client
from twisted.internet import reactor, defer
from twisted.python import failure
class HTTPProgressDownloader(client.HTTPDownloader):
def __init__(self, url, outfile, headers=None):
client.HTTPDownloader.__init__(self, url, outfile, headers=headers, agent="STB_BOX HTTP Downloader")
se... |
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from tastypie.test import ResourceTestCase
from django.contrib.auth import get_user_model
from guardian.shortcuts import get_anonymous_user, assign_perm, remove_perm
from geonode.base.populate_test_data import create_models, all... |
# Class for reading .emd file by Velox.
# This code was written based on FormatSER.py from https://github.com/cctbx/dxtbx/blob/master/format/FormatSER.py
from __future__ import absolute_import, division, print_function
import struct
import h5py
import numpy
import os
import json
from scitbx.array_family import flex
f... |
"""test_scenarios.py
End-end-end tests for the Harvester.
"""
import sys
import os
import RDF
from glharvest import jobs, registry, void
def test_can_update_a_provider_with_a_new_resource(repository):
"""This test tests the case where a provider gives informationa about one
resource at time t0 then, at tim... |
"""Event Decorators for custom components."""
import functools
import logging
# pylint: disable=unused-import
from typing import Optional # NOQA
from homeassistant.core import HomeAssistant # NOQA
from homeassistant.helpers import event
HASS = None # type: Optional[HomeAssistant]
_LOGGER = logging.getLogger(__nam... |
"""Defines a set of constants shared by test runners and other scripts."""
import os
import subprocess
import sys
DIR_SOURCE_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
os.pardir, os.pardir, os.pardir))
ISOLATE_DEPS_DIR = os.path.join(DIR_SOURCE_ROOT,... |
"""Determines the declaration, r/w status, and last use of each variable"""
import ast
import sys
from .runtime import HYBRID_GLOBALS
from .utils import _internal_assert
class PyVariableUsage(ast.NodeVisitor):
"""The vistor class to determine the declaration, r/w status, and last use of each variable"""
# p... |
# Nomenclature
# Copyright (C) 2015 BOUVIN Valentin, HONNORATY Vincent, LEVY-FALK Hugo
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opti... |
# dialog.py -- Tkinter interface to the tk_dialog script.
from Tkinter import *
from Tkinter import _cnfmerge
if TkVersion <= 3.6:
DIALOG_ICON = 'warning'
else:
DIALOG_ICON = 'questhead'
class Dialog(Widget):
def __init__(self, master=None, cnf={}, **kw):
cnf = _cnfmerge((cnf, kw))
self.... |
import sys
try:
from setuptools import setup, Extension
except:
from distutils.core import setup, Extension, Command
from distutils.command.build_ext import build_ext
from distutils.errors import CCompilerError, DistutilsExecError, DistutilsPlatformError
# Fix to build sdist under vagrant
import os
if 'vagran... |
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '))%*y#of%4cnju5=$-1sab!k... |
def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0])
_CSP = "object-src " + url2 +... |
import Framework
class GitBlob(Framework.TestCase):
def setUp(self):
Framework.TestCase.setUp(self)
self.blob = self.g.get_user().get_repo("PyGithub").get_git_blob("53bce9fa919b4544e67275089b3ec5b44be20667")
def testAttributes(self):
self.assertTrue(self.blob.content.startswith("IyEvd... |
from django.forms import CheckboxSelectMultiple
from .base import WidgetTest
class CheckboxSelectMultipleTest(WidgetTest):
widget = CheckboxSelectMultiple
def test_render_value(self):
self.check_html(self.widget(choices=self.beatles), 'beatles', ['J'], html=(
"""<ul>
<li><lab... |
"""Decorators for API access management."""
from functools import wraps
from django.core.urlresolvers import reverse
from django.http import HttpResponseNotFound
from django.shortcuts import redirect
from openedx.core.djangoapps.api_admin.models import ApiAccessRequest, ApiAccessConfig
def api_access_enabled_or_404... |
"""
Tests for the gating API
"""
import unittest
import six
from completion.models import BlockCompletion
from ddt import data, ddt, unpack
from django.conf import settings
from milestones import api as milestones_api
from milestones.tests.utils import MilestonesTestCaseMixin
from mock import Mock, patch
from lms.d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class PodiumVenue(object):
"""
Object that represents a Venue.
**Attributes:**
**venue_id** (int): Venue Id
**uri** (string): URI for the Venue.
**name** (string): The Venue's name.
"""
def __init__(self, venue_i... |
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.common.config.ports import DeprecatedPort
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool import steps
class StepsTest(unittest.TestCase):
def _step_options(self):
options... |
from openerp.osv import fields, osv
class res_company(osv.osv):
"""Override company to add Header object link a company can have many header and logos"""
_inherit = "res.company"
_columns = {
'header_image' : fields.many2many(
'ir.header_... |
from msrest.serialization import Model
class CustomDomain(Model):
"""
The custom domain assigned to this storage account. This can be set via
Update.
:param name: Gets or sets the custom domain name. Name is the CNAME
source.
:type name: str
:param use_sub_domain: Indicates whether indir... |
from gi.repository import Gtk, Gdk, GObject, Pango
from softwarecenter.utils import utf8
from softwarecenter.ui.gtk3.em import EM
from softwarecenter.ui.gtk3.models.appstore2 import CategoryRowReference
from stars import StarRenderer, StarSize
class CellButtonIDs:
INFO = 0
ACTION = 1
# custom cell rendere... |
#!/usr/bin/env python
#coding:utf-8
from toughradius.tools.secret import gen_secret
def echo_radiusd_cnf():
return '''[DEFAULT]
debug = 0
tz = CST-8
secret = %s
ssl = 1
privatekey = /var/toughradius/privkey.pem
certificate = /var/toughradius/cacert.pem
[database]
dbtype = mysql
dburl = mysql://radiusd:<EMAIL>/tou... |
import PIL.Image
import X, pax
from Sketch import _, Publisher, SketchError, _sketch
from Sketch import Blend, CreateRGBColor, MultiGradient
from Sketch.const import DROP_COLOR
from Sketch.warn import pdebug
from Sketch.Graphics import color
from Tkinter import Frame, Button
from Tkinter import BOTTOM, LEFT, RIGHT, B... |
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 XMLToXLS(Choreography):
def __init__(self, temboo_session):
"""
Create a new ... |
from unittest import TestCase
import simplejson as json
# Fri Dec 30 18:57:26 2005
JSONDOCS = [
# http://json.org/JSON_checker/test/fail1.json
'"A JSON payload should be an object or array, not a string."',
# http://json.org/JSON_checker/test/fail2.json
'["Unclosed array"',
# http://json.org/JSON_... |
import WebIDL
def WebIDLTest(parser, harness):
def checkArgument(argument, QName, name, type, optional, variadic):
harness.ok(isinstance(argument, WebIDL.IDLArgument),
"Should be an IDLArgument")
harness.check(argument.identifier.QName(), QName, "Argument has the right QName")
... |
import openerp.tests.common as common
class TestAccountInvoiceShippement(common.TransactionCase):
def setUp(self):
super(TestAccountInvoiceShippement, self).setUp()
self.inv_model = self.env['account.invoice']
self.stock_model = self.env['stock.picking']
self.partner_2 = self.ref... |
import pytest
import uqbar.strings
import supriya
def test_do_not_coerce_arguments():
synth = supriya.realtime.Synth()
group = supriya.realtime.Group()
assert synth.node_id is None
assert group.node_id is None
request = supriya.commands.SynthNewRequest(
node_id=synth, synthdef=synth.synth... |
import six
from six.moves import http_client as httplib
from six.moves.urllib import parse as urlparse
from tempest.lib.common import rest_client
class ObjectClient(rest_client.RestClient):
def create_object(self, container, object_name, data,
params=None, metadata=None, headers=None):
... |
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import traceback
import warnings
import re
warnings.simplefilter("error")
from .support import get_data_files
from .support import TestData, convert, convertExpected, treeTypes
from html5lib import html5parser, constants
# Run t... |
from __future__ import division
from io import BytesIO
import math
import numpy
from PIL import Image
from six import PY3
try:
from ._image import window_batch_bchw
window_batch_bchw_available = True
except ImportError:
window_batch_bchw_available = False
from . import ExpectsAxisLabels, SourcewiseTransfo... |
from rdkit import Geometry
from rdkit.Chem.FeatMaps import FeatMaps, FeatMapPoint
import re
"""
ScoreMode=All
DirScoreMode=Ignore
BeginParams
family=Aromatic radius=2.5 width=1.0 profile=Gaussian
family=Acceptor radius=1.5
EndParams
# optional
BeginPoints
family=Acceptor pos=(1.0, 0.0, 5.0) weight=1.25 dir=(1,... |
"""A module proxy for delayed importing of modules.
From http://barnesc.blogspot.com/2006/06/automatic-python-imports-with-autoimp.html,
in the public domain.
"""
import sys
class LazyModule(object):
"""A lazy module proxy."""
def __init__(self, modname):
self.__dict__['__name__'] = modname
... |
from django.contrib.gis import feeds
from django.contrib.gis.tests.utils import mysql
from models import City, Country
class TestGeoRSS1(feeds.Feed):
link = '/city/'
title = 'Test GeoDjango Cities'
def items(self):
return City.objects.all()
def item_link(self, item):
return '/city/%s/... |
import sys
import unittest
from libcloud.test.file_fixtures import ComputeFileFixtures
class FileFixturesTests(unittest.TestCase):
def test_success(self):
f = ComputeFileFixtures('meta')
self.assertEqual("Hello, World!", f.load('helloworld.txt'))
def test_failure(self):
f = ComputeF... |
"""
This command exports a course from CMS to a git repository.
It takes as arguments the course id to export (i.e MITx/999/2020 ) and
the repository to commit too. It takes username as an option for identifying
the commit, as well as a directory path to place the git repository.
By default it will use settings.GIT_R... |
import asyncio
import datetime
import logging
from contextlib import suppress
from aiohttp import web
logger = logging.getLogger(__file__)
class Periodic:
def __init__(self, func, time):
self.func = func
self.time = time
self.is_started = False
self._task = None
async def st... |
"""
Common terminal messages used across Empire.
Titles, agent displays, listener displays, etc.
"""
import os
import time
import textwrap
# Empire imports
import helpers
###############################################################
#
# Messages
#
###############################################################... |
__doc__ = """
collections compatibility module for older (pre-2.4) Python versions
This does not not NOT (repeat, *NOT*) provide complete collections
functionality. It only wraps the portions of collections functionality
used by SCons, in an interface that looks enough like collections for
our purposes.
"""
__revisi... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from tensorflow.python.client import session
from tensorflow.python.framework import ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import gfile
from tensorflow.pytho... |
import os, sys
import random
import time
import feedparser
import itertools
import HTMLParser
from feed import Feed
if os.getcwd().rstrip(os.sep).endswith('feeds'):
os.chdir('..')
sys.path.insert(0, os.getcwd())
from gui_client import new_rpc
import web
import reddit
class RSSFeed(Feed):
def __init__(se... |
def normalize_permissions(p):
perms = ['-','-','-']
for char in p:
if char == 'r':
perms[0] = 'r'
if char == 'w':
perms[1] = 'w'
if char == 'x':
perms[2] = 'x'
if char == 'X':
if perms[2] != 'x': # 'x' is more permissive
... |
class Verifier:
"""Verifies that the current machine states match the expectation."""
def VerifyInput(self, verifier_input, variable_expander):
"""Verifies that the current machine states match |verifier_input|.
Args:
verifier_input: An input to the verifier. It is a dictionary where each
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_... |
import os
from datetime import datetime
from disco.test import TestCase
from disco.util import flatten, iterify, urlsplit
def function(x):
return x + 0
sequence = 0, [1, [2, 3], [[4, [5, [6]]]]]
class UtilTestCase(TestCase):
def test_flatten(self):
self.assertEquals(list(range(7)), list(flatten(sequ... |
class Vocab:
def __init__(self, vocabFile=None):
self.nextId = 1
self.word2id = {}
self.id2word = {}
if vocabFile:
for line in open(vocabFile):
line = line.rstrip('\n')
(word, wid) = line.split('\t')
self.word2id[word] = int... |
"""Base class for defining triggers.
Although this module is in extensions/, it is not provided as an extension
framework for third-party developers. This is because reacting to triggers
involves changes to core code.
"""
from extensions import domain
class BaseTrigger(object):
"""Base trigger definition class.... |
from basetest import BaseToscaTest
from core.models import Instance, Slice
class ComputeTest(BaseToscaTest):
tests = [ # "create_compute_m1_tiny", XXX m1.tiny does not exist on cloudlab
"create_compute_m1_small",
"create_compute_m1_large_8192MB",
"create_compute_m1_large_8GB... |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8332")
else:
access = Ser... |
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...worksheet import Worksheet
from ...format import Format
class TestAssembleWorksheet(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
... |
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the following automatically:
- fetch all translations using the tx tool
- post-process them into valid and committable format
- remove invalid control characters
- remove location tags (makes diffs less noisy)... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'core',
'version': '1.0'}
import time
from ansible.module_utils.netcfg import NetworkConfig, dumps
from ansible.module_utils.eos import NetworkModule, NetworkError
from ansible.module_utils.basic import get_exception
d... |
{
'name': 'Tips',
'category': 'Usability',
'description': """
OpenERP Web tips.
========================
""",
'version': '0.1',
'author': 'OpenERP SA',
'depends': ['web'],
'data': [
'security/ir.model.access.csv',
'views/tip.xml',
'web_tip_view.xml'
],
'auto_... |
# Test the windows specific win32reg module.
# Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey
import os, sys
import unittest
from test import support
threading = support.import_module("threading")
from platform import machine
# Do this first so test will be skipped if module doesn't exis... |
# -*- coding: utf-8 -*-
"""
sphinx.linkcheck
~~~~~~~~~~~~~~~~
The CheckExternalLinksBuilder class.
:copyright: 2008 by Georg Brandl, Thomas Lamb.
:license: BSD.
"""
import socket
from os import path
from urllib2 import build_opener, HTTPError
from docutils import nodes
from sphinx.builder impor... |
"""
Acceptance tests for Studio related to the asset index page.
"""
from ...pages.studio.asset_index import AssetIndexPage
from .base_studio_test import StudioCourseTest
from ...fixtures.base import StudioApiLoginError
class AssetIndexTest(StudioCourseTest):
"""
Tests for the Asset index page.
"""
... |
import pygame
import tmx
class Player(pygame.sprite.Sprite):
def __init__(self, location, orientation, *groups):
super(Player, self).__init__(*groups)
self.image = pygame.image.load('sprites/player.png')
self.imageDefault = self.image.copy()
self.rect = pygame.Rect(location, (64,64)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.