content stringlengths 4 20k |
|---|
import os
from import_relative import import_relative
Mbase_cmd = import_relative('base_cmd', top_name='trepan')
Mfile = import_relative('file', '...lib', 'trepan')
Mcmdbreak = import_relative('cmdbreak', '..', 'trepan')
class ContinueCommand(Mbase_cmd.DebuggerCommand):
"""**continue** [[*file*:]*lineno* |... |
import mock
from heat.engine.resources.openstack.cinder import cinder_encrypted_vol_type
from heat.engine import stack
from heat.engine import template
from heat.tests import common
from heat.tests import utils
cinder_volume_type_encryption = {
'heat_template_version': '2015-04-30',
'resources': {
'my... |
import operator
# Local
from base.g import *
from base import device, utils, maint
from prnt import cups
from base.codes import *
from .ui_utils import *
# Qt
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Ui
from .pqdiagdialog_base import Ui_Dialog
class PQDiagDialog(QDialog, Ui_Dialog):
def __init__(... |
import sys, os
from datetime import datetime
from twisted.internet import reactor, defer, protocol, error
from twisted.application.service import Service
from twisted.python import log
from scrapy.utils.py26 import cpu_count
from scrapy.utils.python import stringify_dict
from scrapyd.utils import get_crawl_args
from ... |
#!/usr/bin/env python
# example checkbutton.py
import pygtk
pygtk.require('2.0')
import gtk
class CheckButton:
# Our callback.
# The data passed to this method is printed to stdout
def callback(self, widget, data=None):
print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
#... |
"""Fichier contenant la classe Joueur, détaillée plus bas."""
from datetime import datetime
from abstraits.obase import BaseObj
from corps.fonctions import lisser as fn_lisser
from primaires.perso.exceptions.stat import DepassementStat
from primaires.perso.personnage import Personnage
from primaires.format.descriptio... |
"""The tests for the Google Assistant component."""
# pylint: disable=protected-access
import asyncio
import json
from aiohttp.hdrs import CONTENT_TYPE, AUTHORIZATION
import pytest
from homeassistant import core, const, setup
from homeassistant.components import (
fan, cover, light, switch, lock, media_player)
fr... |
from spack import *
class Callpath(CMakePackage):
"""FIXME: Put a proper description of your package here."""
# FIXME: Add a proper url for your package's homepage here.
homepage = "http://www.example.com"
url = "https://github.com/llnl/callpath/archive/v1.0.1.tar.gz"
version('1.0.3', 'c890... |
# -*- coding: utf-8 -*-
import datetime
import hashlib
import logging
import os
import alerts
import enhancements
import jsonschema
import ruletypes
import yaml
import yaml.scanner
from opsgenie import OpsGenieAlerter
from staticconf.loader import yaml_loader
from util import dt_to_ts
from util import dt_to_unix
from ... |
#############################################################################
#
# $Id: remote_nons.py,v 1.5.2.1 2008/06/26 21:19:52 irmen Exp $
# simple Pyro connection module, without requiring Pyro's NameServer
# (adapted from John Wiegley's remote.py)
#
# This is part of "Pyro" - Python Remote Objects
# whi... |
from django.db import models
class Period(models.Model):
name = models.CharField(max_length=50, blank=True, null=True)
name.help_text = "Recommended. Makes identifying the period easier"
date_from = models.DateField(blank=True, null=True)
date_from.help_text = "The start date of this period. Can be le... |
"""Utilities related to loggers and logging."""
from contextlib import contextmanager
import logging
import sys
import threading
try:
import colorlog
except ImportError:
colorlog = None
DEBUG = 'debug'
INFO = 'info'
LOG_LEVELS = {
DEBUG: logging.DEBUG,
INFO: logging.INFO
}
thread_local = threading.loc... |
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import Asyn... |
from distutils.core import setup, Extension, Command
# Used by TestCommand and CleanCommand
from unittest import TextTestRunner, TestLoader
from glob import glob
from os.path import splitext, basename, join as pjoin, walk
import os
class TestCommand(Command):
# From: http://da44en.wordpress.com/2002/11/22/using-dist... |
"""Handle intents with scripts."""
import copy
import logging
import voluptuous as vol
from homeassistant.helpers import (
intent, template, script, config_validation as cv)
DOMAIN = 'intent_script'
CONF_INTENTS = 'intents'
CONF_SPEECH = 'speech'
CONF_ACTION = 'action'
CONF_CARD = 'card'
CONF_TYPE = 'type'
CON... |
"""
Module containing weather data classes and data structures.
"""
import json
import xml.etree.ElementTree as ET
from pyowm.webapi25.xsd.xmlnsconfig import (
WEATHER_XMLNS_PREFIX, WEATHER_XMLNS_URL)
from pyowm.utils import timeformatutils, temputils, xmlutils
class Weather(object):
"""
A class encapsul... |
"""Library for gcloud operations."""
from __future__ import print_function
import re
from chromite.compute import compute_configs
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import timeout_util
class GCContextException(Exception):
"""Base exception f... |
#python-encoding: UTF-8
from csc.nl.ja.util import *
import re
class JaDebug():
''' Handles Debug Output for csc.nl.ja
Note: Not pretty. Probably never will be.
'''
def __init__(self, colorize = True):
self.colors = {}
self.colors['header'] = '\033[092m' if colorize else ''
... |
"""BibEncode frame extraction module.
"""
__revision__ = "$Id$"
from invenio.modules.encoder.config import (
CFG_BIBENCODE_FFMPEG_EXTRACT_COMMAND,
)
from invenio.legacy.bibsched.bibtask import (
task_update_progress,
... |
import numpy as np
import time
import gym
import queue
import ray
from ray.rllib.agents.ppo.ppo_tf_policy import PPOTFPolicy
from ray.rllib.evaluation.worker_set import WorkerSet
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.execution.concurrency_ops import Concurrently, Enqueue, Dequeue... |
# coding: utf8
#############################################
# Ce code prend en input une matrice a, un vecteur v
# des scalaires scalar_u et scalar_v, ainsi que les
# dimensions de la matrice et du vecteur.
# La matrice a est donc multipliée par le scalar_u
# et on lui additionne scalar_v fois le vecteur v
#
########... |
from __future__ import absolute_import, print_function
import os
import configparser
_config = configparser.RawConfigParser()
def read_from_files(files):
readed = _config.read(files)
print('Readed config from files:')
for f in readed:
print(' * ' + f)
print('')
def write_to_file(file):
... |
"""dnspython release version information."""
MAJOR = 1
MINOR = 9
MICRO = 5
RELEASELEVEL = 0x0f
SERIAL = 0
if RELEASELEVEL == 0x0f:
version = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
elif RELEASELEVEL == 0x00:
version = '%d.%d.%dx%d' % \
(MAJOR, MINOR, MICRO, SERIAL)
else:
version = '%d.%d.%d%x%d' ... |
import mock
from neutron.common import constants
from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent \
import ovs_test_base
call = mock.call # short hand
class OVSBridgeTestBase(ovs_test_base.OVSOFCtlTestBase):
def setup_bridge_mock(self, name, cls):
self.br = cls(name)
mock_add... |
import openerp.tests.common as common
class test_cancel_purchase_requisition(common.TransactionCase):
""" Test the cancellation of purchase requisition and ensure that related
Purchase Orders/Request For Quotation are cancelled
"""
def setUp(self):
super(test_cancel_purchase_requisition, self... |
import rospy
from rosauth.srv import Authentication
from functools import partial
from tornado.ioloop import IOLoop
from tornado.websocket import WebSocketHandler
from rosbridge_library.rosbridge_protocol import RosbridgeProtocol
from rosbridge_library.util import json
import bson
class RosbridgeWebSocket(WebSocke... |
import BaseHTTPServer
from collections import namedtuple
import errno
import gzip
import logging
import mimetypes
import os
import SimpleHTTPServer
import socket
import SocketServer
import StringIO
import sys
import traceback
import urlparse
from telemetry.core import local_server
ByteRange = namedtuple('ByteRange', ... |
import sys
sys.path.insert(0, "") # for running from cmake
from conftest import make_session
import pytest
import md5
import elliptics
def format_result(node, backend, result, counter):
'''
Formats and returns string that represents iteration result.
'''
return "{0}, key: {1}, user_flags: {2}, timest... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import nose
import nose.tools
import numpy
from selective_search import algorithm
class TestCalcAdjecencyMatrix:
def setup_method(self, method):
self.label = numpy.zeros((4, 4), dtype=int)
def test_only_1_segment(self):
# 0, 0, 0, 0
# 0, ... |
"""
Unit tests for the notes app.
"""
from mock import patch, Mock
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.core.exceptions i... |
import os
import sys
import time
import subprocess
import threading
from itertools import chain
from werkzeug._internal import _log
from werkzeug._compat import PY2, iteritems, text_type
def _iter_module_files():
"""This iterates over all relevant Python files. It goes through all
loaded files from modules,... |
import os
import sys
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession
class ClientSession(ApplicationSession):
def onConnect(self):
print('Client session connected.')
self.join(self.config.realm, [u'anonymous... |
import numpy as np
import math as math
import word2vec
from utilities import Sentence, Product, AspectPattern
class AspectPatterns(object):
def __init__(self, pattern_name_list):
#possible pattern_name: adj_nn, nn, adj, adv
self.aspectPatterns_list = []
for pattern_name in pattern_name_list:
if pattern_name ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'statu... |
"""Tests for draw_bounding_box_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class DrawBoundingBoxOpTest(tf.test.TestCase):
def _fillBorder(self, image, color):
"""Fill the border of the image.
... |
"""
Signaler client.
Receives signals from the backend and sends to the signaling server.
"""
import Queue
import threading
import time
import zmq
from leap.bitmask.backend.api import SIGNALS
from leap.bitmask.backend.utils import get_frontend_certificates
import logging
logger = logging.getLogger(__name__)
class ... |
from akvo.rsr.models import Partnership
from ..serializers import PartnershipSerializer, PartnershipBasicSerializer
from ..viewsets import PublicProjectViewSet
class PartnershipViewSet(PublicProjectViewSet):
"""
"""
queryset = Partnership.objects.select_related('organisation', 'project').all()
serial... |
# THIS FILE IS NOT USED, DELETE IT
"""Convertors are used for LiteralInputs, to make sure, input data are OK
"""
class MODE:
"""Convertion mode
NONE: return input value as it is
BASIC: make only convertion
VALIDATE: check for aditional input rules
STRICT: check for various potential problems (SQL ... |
#!/usr/bin/env python
from distutils.version import StrictVersion
from urllib2 import urlopen
import time
import subprocess
import webbrowser
import os
import unittest
import sys
from gomatic import *
def start_go_server(gocd_version):
with open('Dockerfile', 'w') as f:
f.write(open("Dockerfile.tmpl").re... |
import glob
import os
import numpy as np
def clean_dir(path):
filelist = glob.glob(path + "/inputs/*")
filelist.extend(glob.glob(path + "/embeddings/*"))
filelist.extend(glob.glob(path + "/tmp/*"))
for f in filelist:
os.remove(f)
def split_data(Y, P, path, dname):
'''
split_data
S... |
# -*- coding: utf-8 -*-
import re
import linecache
import traceback
import functools
from colorama import Fore, Style
from ..config import config
from .base import BaseReporter
class Trace(object):
"""
Python < 3.4 traceback compatibility wrapper for Python +3.5
"""
def __init__(self, trace):
... |
""" Formatting for all sorts of DNS Records """
from aquilon.aqdb.model import NsRecord
from aquilon.worker.formats.list import ListFormatter
from aquilon.worker.formats.formatters import ObjectFormatter
class NsRecordFormatter(ObjectFormatter):
template_raw = "ns_record.mako"
def csv_fields(self, ns):
... |
"""Undocumented Module"""
__all__ = ['TestInterval']
"""
Contains the ParticleInterval class
"""
from panda3d.core import *
from panda3d.direct import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from Interval import Interval
class TestInterval(Interval):
# Name counter
particleNum = 1... |
"""
A simple client that uses the Python ACME library to run a test issuance against
a local Boulder server. Usage:
$ virtualenv venv
$ . venv/bin/activate
$ pip install -r requirements.txt
$ python chisel.py foo.com bar.com
"""
import json
import logging
import os
import socket
import sys
import threading
import time... |
#!/usr/bin/env python
'''wrapper module for rt (python RT api module'''
import rt
import datetime
import os
import re
import smtplib
import ConfigParser
from email.mime.text import MIMEText
#################################################
# Configuration #
# ... |
import re
from django.contrib.gis import forms
from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget
from django.contrib.gis.geos import GEOSGeometry
from django.forms import ValidationError
from django.test import SimpleTestCase, override_settings
from django.utils.html import escape
class Geome... |
#!/usr/bin/python
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
class CORSRequestHandler(SimpleHTTPRequestHandler):
def do_POST(self):
print "post"
content_length = int(self.headers['Content-length'])
bytes_read = 0
while bytes_read < content_length:
... |
from discord.ext import commands
from sqlalchemy.exc import IntegrityError
from . import util
from .util import m
class SpellCategory (util.Cog):
@commands.group('spell', invoke_without_command=True)
async def group(self, ctx):
'''
Manage character spell list
'''
raise util.in... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed i... |
""" Invenio bibsched task for uploading multiple documents
or metadata files. This task can run in two different modes:
metadata or documents.
The parent directory from where the folders metadata and
documents are expected to be found has to be specified
in the invenio config file.
"""
import os.pat... |
# encoding: utf-8
import datetime as dt
from datetime import datetime
import re
import time
from django import template
from django.core.cache import cache
from django.utils.safestring import mark_safe
from django.utils import translation
from django.utils.dateformat import DateFormat
from django.utils.translation imp... |
import pytest
from web3.utils.events import (
construct_event_topic_set,
)
EVENT_1_ABI = {
"anonymous": False,
"inputs": [
{"indexed": False,"name":"arg0","type":"uint256"},
{"indexed": True,"name":"arg1","type":"uint256"},
{"indexed": True,"name":"arg2","type":"uint256"},
... |
"""Test Pandoc module"""
#-----------------------------------------------------------------------------
# Copyright (C) 2014 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#----------------------------... |
#!/usr/bin/env python3
from collections import OrderedDict as OD
import asyncio
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from .tooltip import ToolTip
from .columns import c_server
from .data import Obj
from . import MyUI, MyAIO
from .server import proxy
class Control(MyUI):
... |
# NamoInstaller ActiveX Control 1.x - 3.x
# CVE-NOMATCH
import logging
log = logging.getLogger("Thug")
def Install(self, arg):
if len(arg) > 1024:
log.ThugLogging.log_exploit_event(self._window.url,
"NamoInstaller ActiveX",
... |
from openerp.osv import orm, fields
from tools.translate import _
import time
class wizard_assign_ddt(orm.TransientModel):
_name = "wizard.assign.ddt"
def assign_ddt(self, cr, uid, ids, context=None):
picking_obj = self.pool.get('stock.picking.out')
for picking in picking_obj.browse(cr, uid, ... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: type_Params.py
from types import *
class Params:
def __init__(self):
self.__dict__['bufferSize'] = 5120
def __getattr__(self, name... |
from flask.ext.restful import fields
class OptionalNestedField(fields.Raw):
"""This can be used to nest Fieldsets into each other.
It works like the Nested field but uses Fieldsets as nested
structure instead of a simple dict. The user can select
fields from the nested set by prefixing the fieldname ... |
from sqlalchemy.ext.declarative import declared_attr
from indico.core.db import db
from indico.core.db.sqlalchemy import PyIntEnum
from indico.core.db.sqlalchemy.review_comments import ReviewCommentMixin
from indico.modules.events.models.reviews import ProposalCommentMixin
from indico.modules.events.papers.models.revi... |
#! /usr/bin/env python
from ROOT import TCanvas, TGraphErrors, TLegend, TPaveText
from ROOT import kBlack, kBlue, kRed
from Helper import Frame, ReadHistList
from Graphics import Style
from SpectrumContainer import DataContainer
from copy import deepcopy
class PeriodComparisonPlot:
def __init__(self):
... |
from __future__ import unicode_literals
import unittest
import frappe
from frappe.test_runner import make_test_records
from erpnext.controllers.item_variant import (create_variant, ItemVariantExistsError,
InvalidItemAttributeValueError, get_variant)
from frappe.model.rename_doc import rename_doc
from erpnext.stock.d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os.path
import glob
import os
import sys
import string
import shutil
import stat
import time
from time import gmtime, strftime
from random import Random
existing_types = [ "Sang",
"Plasma",
"Serum",
"Urine",
"Selles",
"Crachat",
"Secretion Ureth... |
from data import *
def pass1(logger, filename):
# Open file
try:
fin = open(filename, "r")
except:
logger.log("Can not open input file for pass1 with read mode!", error_flag=True)
return
try:
fout = open(".pass1.tmp", "w")
except:
logger.log("Can not open out... |
import coord
import canvas
class T(coord.T):
def __init__(self, data, col):
"""This attribute is meaningful only when x_coord_system ==
'category'. This attribute selects the column of
'x_category_data' from which X values are computed.
Meaningful only when x_coord_system == 'categ... |
from __future__ import unicode_literals
from .common import InfoExtractor
class SlutloadIE(InfoExtractor):
_VALID_URL = r'https?://(?:\w+\.)?slutload\.com/(?:video/[^/]+|embed_player|watch)/(?P<id>[^/]+)'
_TESTS = [{
'url': 'http://www.slutload.com/video/virginie-baisee-en-cam/TD73btpBqSxc/',
... |
import os
import shutil
import unittest
from jinja2 import Environment, FileSystemLoader
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace
HDL_DIAGRAMS_PATH = os.path.abspath("..")
## Helpers
def get_sphinx_dirs(test_build_dir):
sphinx_dirs = {
"srcdir": test_buil... |
import mock
from oslo_config import cfg
from rally.plugins.openstack.scenarios.murano import utils
from tests.unit import test
MRN_UTILS = "rally.plugins.openstack.scenarios.murano.utils"
CONF = cfg.CONF
class MuranoScenarioTestCase(test.ScenarioTestCase):
def test_list_environments(self):
self.clients... |
from nose.tools import * # noqa
import json
import httpretty
import datetime, dateutil
from tests.base import OsfTestCase
from tests.factories import ProjectFactory, UserFactory
from website.project.model import Auth, Node
from website.settings import POPULAR_LINKS_NODE, NEW_AND_NOTEWORTHY_LINKS_NODE
from scripts ... |
"""Turn discourse data into a cool rotating globe showing when everyone signed up.
You will need dump.sql from your discourse backup (/var/discourse/shared/standalone/backups/default/)
which you then gzip to make it smaller. You'll also need a bunch of matplotlib stuff, and you'll need
GeoLiteCity.dat from... |
from openerp import SUPERUSER_ID
def _default_reservation_location_data(cr, registry, company_id):
model, record_id = registry['ir.model.data'].get_object_reference(
cr, SUPERUSER_ID, 'stock', 'stock_location_locations')
return {
'name': 'Reservation Stock',
'reserved': True,
... |
# -*- coding: utf-8 -*-
import os
import re
import uuid
import shutil
from scrapy.cmdline import execute
from scrapy.utils.log import logging
def syncdir(src: str, dst: str, match=re.compile(r"(^[^_])|(\.py$)").search):
# check params
if not os.path.isdir(src):
pass
if not os.path.isdir(dst):
... |
import logging
from google.appengine.api import mail
from google.appengine.api import taskqueue
from google.appengine.ext import webapp
#from google.appengine.ext.webapp import util
from dateutil import date_for_retrieval
from model import (compute_following,
Snippet,
user_from_e... |
import logging
import os
import re
import struct
import zipfile
# The default zipfile python module cannot open APKs properly, but this
# fixes it. Note that simply importing this file is sufficient to
# ensure that zip works correctly for all other modules. See:
# http://bugs.python.org/issue14315
# https://hg.python... |
import urllib
from xml.etree import ElementTree
from xl import common
import logging
logger = logging.getLogger(__name__)
# TODO: The 'new' API doesn't allow general queries, only allows exact
# matching.. if they fix it, we'll fix it. >_>
search_url = 'http://librivox.org/api/feed/audiobooks/?title='
class Book():... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import sys, os, importlib, time
from PyQt5.Qt import QIcon
from calibre.con... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import logging
from collections import defaultdict
from checkm.defaultValues import DefaultValues
from checkm.markerSets import MarkerSetParser, BinMarkerSets
from unitem.defaults import ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
import matplotlib.cm as cm
from matplotlib.mlab import griddata
from numpy.random import uniform, seed
import scipy.interpolate
def normal_interp(x, y, a, xi, yi):
rbf = scipy.interpolate.Rbf(x, y, a)
ai = rbf(xi, yi)
return a... |
import logging
import json
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from vio.pub.utils import syscomm
from vio.pub.vim.vimapi.network import OperateSubnet
logger = logging.getLogger(__name__)
class CreateSubnetView(APIView):
def pos... |
from .common import Benchmark, get_squares_, get_indexes_rand, TYPES1
import numpy as np
class Eindot(Benchmark):
def setup(self):
self.a = np.arange(60000.0).reshape(150, 400)
self.ac = self.a.copy()
self.at = self.a.T
self.atc = self.a.T.copy()
self.b = np.arange(240000.... |
"""
Script for auto-increasing the version on bleeding_edge.
The script can be run regularly by a cron job. It will increase the build
level of the version on bleeding_edge if:
- the lkgr version is smaller than the version of the latest revision,
- the lkgr version is not a version change itself,
- the tree is not cl... |
from lib.cuckoo.common.abstracts import Signature
class AntiVMIDE(Signature):
name = "antivm_generic_ide"
description = "Checks the presence of IDE drives in the registry, possibly for anti-virtualization"
severity = 3
categories = ["anti-vm"]
authors = ["nex"]
minimum = "0.5"
def run(self... |
#!/usr/bin/env python3
class Solution:
def uniquePathsIII(self, grid):
self.left = 0
nr, nc = len(grid), len(grid[0])
for i in range(nr):
for j in range(nc):
if grid[i][j] == 0:
self.left += 1
elif grid[i][j] == 1:
... |
'''
'''
# 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");... |
"""The WaveBlocks Project
Asymptotic approximation to Hermite polynomials of very high degree.
@author: R. Bourquin
@copyright: Copyright (C) 2015, 2016 R. Bourquin
@license: Modified BSD License
"""
from numpy import (sqrt, log, sin, cos, arccos, sinh, cosh, arccosh, exp,
zeros_like, floating, at... |
import unittest
from LibvirtQMFTest import *
PROPERTIES = ('hostname', 'uri', 'libvirtVersion', 'apiVersion',
'hypervisorVersion', 'hypervisorType', 'model', 'memory', 'cpus', 'mhz',
'nodes', 'sockets', 'cores', 'threads')
class NodeTest(unittest.TestCase, LibvirtQMFTest):
@classmethod
def setUpCla... |
# Same as basic_example, but writes files using a single MovieWriter instance
# without putting on screen
# -*- noplot -*-
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def update_line(num, data, line):
line.set_data(data[..., :... |
import tempfile
import shutil
from os.path import abspath, join, dirname
from preggy import expect
from thumbor.transformer import Transformer
from thumbor.config import Config
from thumbor.importer import Importer
from thumbor.context import Context, ServerParameters
from tests.base import TestCase
from tests.fixtur... |
from esc import NUL, S7C1T, S8C1T
import escargs
import esccmd
import escio
from escutil import AssertEQ, AssertScreenCharsInRectEqual, GetCursorPosition, GetScreenSize, knownBug, optionRequired
from esctypes import Point, Rect
class RITests(object):
def test_RI_Basic(self):
"""Reverse index moves the cursor up ... |
'''Script generating bash completion code from input.xml.
'''
import os
import sys
import optparse
import xml.etree.ElementTree as ET
try:
import ms.version
except ImportError:
pass
else:
ms.version.addpkg('Cheetah', '2.4.4')
from Cheetah.Template import Template
usage = """%prog [options] template1 [te... |
import httplib2
from oslo_config import cfg
from oslo_log import log as logging
import six.moves.urllib.parse as urlparse
import webob
from neutron.agent.linux import daemon
from neutron.agent.linux import utils as agent_utils
from neutron.common import config
from neutron.common import exceptions
from neutron.common ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# this interferes with ServiceRouter/SWIG
# @lint-avoid-python-3-compatibility-imports
#from __future__ import unicode_literals
# @lint-avoid-servicerouter-import-warning
from ServiceRouter import ServiceOption... |
from spack import *
class RForcats(RPackage):
"""Helpers for reordering factor levels (including moving specified levels
to front, ordering by first appearance, reversing, and randomly
shuffling), and tools for modifying factor levels (including collapsing
rare levels into other, 'anonymising... |
"""Tests for the moderator page."""
from core.domain import rights_manager
from core.tests import test_utils
class ModeratorTest(test_utils.GenericTestBase):
def test_moderator_page(self):
"""Tests access to the Moderator page"""
# Try accessing the moderator page without logging in.
res... |
import threading
from webkitpy.common.host_mock import MockHost
from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot
from webkitpy.common.net.statusserver_mock import MockStatusServer
from webkitpy.common.net.irc.irc_mock import MockIRC
# FIXME: Old-style "Ports" need to die and be replaced by modern l... |
"""Views used to render e-mail previews."""
from __future__ import unicode_literals
from django.views.generic.base import View
from reviewboard.notifications.email.decorators import preview_email
class BasePreviewEmailView(View):
"""Generic view used to preview rendered e-mails.
This is a convenience for ... |
#!/usr/bin/python2
import sys, re, os, json, urllib, urllib2
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, TIT2, TOPE, TPE1, TPE4, APIC, TCON, TLEN, COMM, TORY, WOAF, WOAR, error
from pprint import pprint
# Global vars
client_id = ""
downloaded = {}
download_dir = ""
PREF_FILENAME = "config.pref"
remix = F... |
# internal
import phial.pipelines
import phial.utils
class TestPipeline:
def test_concat(self):
files = [phial.documents.file("a"), phial.documents.file("b")]
for i, f in enumerate(files):
f.write(str(i))
source = phial.pipelines.PipelineSource(files)
source.pipe(phial... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import unittest
import mock
from botocore.stub import Stubber
from stacker.lookups.handlers.dynamodb import DynamodbLookup
import boto3
from stacker.tests.factories import SessionStub
class TestDynamoDBHandler... |
"""Support for ZHA AnalogOutput cluster."""
import functools
import logging
from homeassistant.components.number import DOMAIN, NumberEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .core import discovery
from .core.const import (
CHANNEL_A... |
from lib.utils.DevTreeUtils import DevTree
from lib.utils.Logger import Log
from lib.utils.ProcessUtils import ExecutableRunner
def execute_command(args):
build_type = args.type
if build_type == 'dbg':
build_dir = DevTree.dbg_build_dir
elif build_type == 'opt':
build_dir = DevTree.opt_bui... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.