content
stringlengths
4
20k
import numpy as np import astropy.units as u import astropy.constants as const from astropy.time import Time from astropy.coordinates import SkyCoord from EXOSIMS.Prototypes.TargetList import TargetList import os import astropy.io import inspect import scipy.interpolate class EclipticTargetList(TargetList): """Tar...
from lxml import etree from openerp import models, fields, api, _ from openerp.addons import decimal_precision as dp from openerp.exceptions import except_orm from openerp.exceptions import Warning as UserError from .l10n_br_account import PRODUCT_FISCAL_TYPE, PRODUCT_FISCAL_TYPE_DEFAULT OPERATION_TYPE = { 'out_...
import os import unittest here = os.path.dirname(__file__) class Test_get_app(unittest.TestCase): def _callFUT(self, config_file, section_name, **kw): from pyramid.paster import get_app return get_app(config_file, section_name, **kw) def test_it(self): app = DummyApp() loadapp...
import time import unittest from datetime import timedelta from airflow.exceptions import AirflowSensorTimeout, AirflowSkipException from airflow.models.dag import DAG from airflow.sensors.base import BaseSensorOperator from airflow.utils import timezone from airflow.utils.decorators import apply_defaults from airflow...
import bohrium import util import functools import operator class test_set_bool_mask_scalar: def init(self): for dtype in bohrium._info.numpy_types: dtype = "np.%s"%dtype.name for cmd, shape in util.gen_random_arrays("R", 2, min_ndim=1, samples_in_each_ndim=1, ...
from spack import * import sys class Xsdk(BundlePackage): """Xsdk is a suite of Department of Energy (DOE) packages for numerical simulation. This is a Spack bundle package that installs the xSDK packages """ homepage = "http://xsdk.info" maintainers = ['balay', 'luszczek'] versio...
#!/usr/bin/env python # coding:utf-8 # GAE limit: # only support http/https request, don't support tcp/udp connect for unpaid user. # max timeout for every request is 60 seconds # max upload data size is 30M # max download data size is 10M # How to Download file large then 10M? # HTTP protocol support range fetch. #...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse def main(): # まずはじめにArgumentParserオブジェクトソ生成する. # ArgumentParserオブジェクトに,コマンドラインを解析する全ての情報が保持される. parser = argparse.ArgumentParser(description="sum here") # 位置引数を作成.オブション引数か位置引数かは第一引数で判別させる. # nargsオプションで複数の引数をアクションに渡せるようにする. parser....
""" """ import sys import hashlib def bytes(text): """ Convert Unicode text to UTF-8 encoded bytes. Since Python 2.6+ and Python 3+ have similar but incompatible signatures, this function unifies the two to keep code sane. :param text: Unicode text to convert to bytes :rtype: bytes (Python3...
""" Django settings for test_project project. Generated by 'django-admin startproject' using Django 1.9. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os...
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================= SVM Margins Example ========================================================= The plots below illustrate the effect the parameter `C` has on the seperation line. A large value of `C` basically tells our model that w...
__author__ = 'nicolas' import MySQLdb as mdb con = mdb.connect('localhost', 'nicolas', '', '') cur = con.cursor() cur.execute("SELECT VERSION()") print(cur.fetchone()) cur.execute("USE mysql") cur.execute("DROP TABLE ptm_eukarya") cur.execute("DROP TABLE ptm_bacteria") cur.execute("DROP TABLE ptm_archaea") cur.exec...
# -*- coding: utf-8 -*- """ Contains classes to combine files into one """ from fnmatch import fnmatch from hyde.model import Expando from hyde.plugin import Plugin class CombinePlugin(Plugin): """ To use this combine, the following configuration should be added to meta data:: combine: ...
""" mission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions. Full documentation is provided at http://python.dronekit.io/examples/mission_basic.html """ import time import math from droneapi.lib import VehicleMode, Location, Command from pymavlink...
import os from zope.interface import implements from twisted.web2.stream import SimpleStream, IByteStream from twisted.vfs.ivfs import IFileSystemLeaf, VFSError from twisted.python import components class FileSystemLeafStream(SimpleStream): implements(IByteStream) """A stream that reads data from a FileSystem...
from pychron.envisage.tasks.base_task import BaseManagerTask # ============= standard library imports ======================== # ============= local library imports ========================== from pychron.entry.tasks.sensitivity.panes import SensitivityPane from pychron.entry.entry_views.sensitivity_entry import Sens...
"""Utility functions for d-note.""" from Crypto.Hash import SHA from Crypto.Random import random from note import DATA_DIR def duress_text(): """Return 5 random sentences of the Zen of Python.""" import subprocess text = '' python = subprocess.Popen(('python', '-c', 'import this'), ...
import pymssql import pandas as pd import numpy as np from sqlalchemy import create_engine from bcpp_export import urls # DO NOT DELETE from bhp066.apps.bcpp_lab.models import Aliquot as EdcAliquot, Receive, SubjectRequisition, ClinicRequisition class Aliquot(object): def __init__(self, requisition): s...
from __future__ import print_function, absolute_import, unicode_literals, division import textwrap import mock import requests_mock import requests import logging from afp_alppaca import IMSCredentialsProvider, NoRolesFoundException, NoCredentialsFoundException from afp_alppaca.compat import unittest from test_utils...
from nimbus.network.nodes.basin import basin as bsn from nimbus.reports import report as rp from nimbus.data import object as ob class Node: def __init__(self, name=None, start_stage=None, network=None): self.name = name self.start_stage = start_stage self.network = network ...
from pyactor.exceptions import PyActorTimeoutError k = 7 MAX = 2 ** k def decr(value, size): if size <= value: return value - size else: return MAX - (size - value) # ---------BETWEEN--------- def between(value, init, end): if init == end: return True elif init > end: ...
from datetime import timedelta from math import ceil from django.conf import settings from django.contrib.postgres.fields import JSONField from django.db import models from django.utils import timezone class Poll(models.Model): category = models.ForeignKey('misago_categories.Category') thread = models.OneToO...
import os import sys from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="seantis-questionnaire", version="2.0.1", description="A Django application for creating online questionnaires/surveys.", long_descriptio...
from typing import Optional, Dict # By age 35, you should have written an ad-hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp. # https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule # https://twitter.com/NeckbeardHacker/status/999087537883942912 from src.independent.util import chc...
"""Grouper for grouping similar looking testcases.""" import six from base import errors from crash_analysis.crash_comparer import CrashComparer from datastore import data_handler from datastore import data_types from libs.issue_management import issue_tracker_utils from metrics import logs from . import group_leade...
import os, sys, subprocess, re import inspect from argparse import ArgumentParser, FileType """ """ def read_genome(genome_file): chr_dic, chr_names, chr_full_names = {}, [], [] chr_name, chr_full_name, sequence = "", "", "" for line in genome_file: if line.startswith(">"): if chr_name...
import logging import os import pdb import sys import unittest test_path = os.path.dirname(__file__) sys.path.insert(0, os.path.join(test_path, '../../DNP3')) import parseInput class TestParseInput(unittest.TestCase): def test_bad_exit(self): 'Verifies the function returns an empty string when no data is...
import os # third-party modules import scipy # own modules from . import header from ..core import Logger from ..core import ImageTypeError, DependencyError,\ ImageLoadingError # !TODO: Change to not work with the Exceptions anymore, as these hides bugs! # code def load(image): r""" Loads the ``image`` ...
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.helpers.encoding import tryUrlencode from couchpotato.core.helpers.variable import tryInt, tryFloat, splitString from couchpotato.core.logger import CPLog from couchpotato.core.providers.info.base import MovieProvider import json import re imp...
"""Test Home Assistant scenes.""" import pytest import voluptuous as vol from homeassistant.components.homeassistant import scene as ha_scene from homeassistant.components.homeassistant.scene import EVENT_SCENE_RELOADED from homeassistant.setup import async_setup_component from tests.async_mock import patch from test...
"""Component to interface with locks that can be controlled remotely.""" from datetime import timedelta import functools as ft import logging import voluptuous as vol from homeassistant.loader import bind_hass from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.entity import ...
# -*- coding: utf-8 -*- #------------------------------------------------------------ # streamondemand - XBMC Plugin # Conector para novamov # http://www.mimediacenter.info/foro/viewforum.php?f=36 #------------------------------------------------------------ # Credits: # Unwise and main algorithm taken from Eldorado ur...
from tempfile import mkdtemp from unittest.case import skip from django.conf import settings from django.test import TransactionTestCase, tag # noqa from django.test.utils import override_settings from django_revision.apps import check_revision from django_revision.revision import Revision, site_revision from django_...
import sys, os, csv, pprint, math import argparse import numpy as np import random import shutil import time from util_scripts.psbased_remapping_random_params_generation import generate_random_params ## uncomment when running under CLI only version ## #import matplotlib #matplotlib.use('Agg') import matplotlib.pyplo...
#!/usr/bin/env python # coding: utf-8 import json import os import sys import unittest # Allow direct execution sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import youtube_dl.FileDownloader import youtube_dl.InfoExtractors from youtube_dl.utils import * PARAMETERS_FILE = os.path.join...
# -*- coding: utf-8 -*- ''' Copyright (c) 2012, Tarek Galal <<EMAIL>> This file is part of Wazapp, an IM application for Meego Harmattan platform that allows communication with Whatsapp users Wazapp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as publis...
""" maintenanceview.py Contains maintenance views for performing dark magic upon data. """ from datetime import datetime from admin_helpers import * from flask import redirect, flash, request from flask.ext.admin import BaseView, expose from flask.ext.admin.helpers import get_redirect_target from remedy.remedybluep...
"""This example adds demographic criteria to an ad group. To get a list of ad groups, run get_ad_groups.py. The LoadFromStorage method is pulling credentials and properties from a "googleads.yaml" file. By default, it looks for this file in your home directory. For more information, see the "Caching authentication in...
# -*- coding: utf-8 -*- """ Created on Wed Jan 12 15:36:44 2011 @author: - """ #Copyright 2011 Dan Klinedinst # #This file is part of Gibson. # #Gibson 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 ver...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Pelix remote services implementation based on Herald messaging and jsonrpclib-pelix :author: Thomas Calmant :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 1.0.1 :status: Alpha .. Copyright 2014 isandlaTech Licensed und...
from datetime import datetime from django.utils import timezone from uccaApp.models import Tabs, Constants, Roles from django.db import models from django.contrib.auth.models import User, Group class LogLogin(models.Model): id = models.AutoField(primary_key=True) login = models.CharField(max_length=100, defau...
'''Runs the basic test suite through a cross compiler. Not part of the main test suite because of two reasons: 1) setup of the cross build is platform specific 2) it can be slow (e.g. when invoking test apps via wine) Eventually migrate to something fancier.''' import sys import os from pathlib import Path import ar...
""" A number of functions that enhance IDLE on Mac OSX. """ import sys import tkinter from os import path import warnings def runningAsOSXApp(): warnings.warn("runningAsOSXApp() is deprecated, use isAquaTk()", DeprecationWarning, stacklevel=2) return isAquaTk() def isCarbonAquaTk(root)...
# !/usr/bin/env python3 # -*- encoding: utf-8 -*- """ ERP+ """ __author__ = ['António Anacleto', 'Jair Medina'] __credits__ = [] __version__ = "1.0" __maintainer__ = ['António Anacleto', 'Jair Medina'] __status__ = "Development" __model_name__= 'sai_declaracao.Sai_declaracao' #import base_models#auth, from orm import ...
#!/usr/bin/env python from grr_response_core.lib import rdfvalue from grr_response_server.rdfvalues import objects as rdf_objects from grr.test_lib import test_lib def _Date(date, time="00:00:00"): return rdfvalue.RDFDatetime.FromHumanReadable("{} {}".format(date, time)) class DatabaseTestEventsMixin(object): ...
# -*- coding: utf-8 -*- import numpy as np import scipy.io as sio import matplotlib.pyplot as plt import ann import data as files #import the data matfn=u'mnist/mnist_uint8.mat' data=sio.loadmat(matfn) train_data = np.float64(data['train_x']) /255 train_result = np.float64(data['train_y']) test_data = np.float64(...
# -*- coding: utf-8 -*- import bpy from bpy.types import Panel, UIList from mmd_tools import operators import mmd_tools.core.model as mmd_model class _PanelBase(object): bl_space_type = 'VIEW_3D' bl_region_type = 'TOOLS' bl_category = 'mmd_tools' class MMDToolsObjectPanel(_PanelBase, Panel): bl_id...
import errno import socket import types import xmlrpclib from xen.util.xmlrpclib2 import UnixXMLRPCServer, TCPXMLRPCServer try: from SSLXMLRPCServer import SSLXMLRPCServer ssl_enabled = True except ImportError: ssl_enabled = False from xen.xend import XendAPI, XendDomain, XendDomainInfo, XendNode from xen....
from setuptools import setup, find_packages import os version = '0.2.3b1' setup(name='uwosh.requirements', version=version, description="this products provides basic requirements to all uwosh plone site", long_description=open("README.txt").read() + "\n" + open(os.path.join("d...
import logging from ovirt_hosted_engine_ha.broker import submonitor_base from ovirt_hosted_engine_ha.lib import log_filter from ovirt_hosted_engine_ha.lib import util as util from vdsm.client import ServerError def register(): return "mem-free" class Submonitor(submonitor_base.SubmonitorBase): def setup(s...
import jira_bot # Standard imports import pathlib from setuptools import setup, find_packages def sources_dir(): return pathlib.Path(__file__).parent def readfile(filename): with (sources_dir() / filename).open(encoding='UTF-8') as f: return f.read() def get_requirements_from(filename): with ...
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Pelix HTTP package. Defines the interfaces that must respect HTTP service implementations. :author: Thomas Calmant :copyright: Copyright 2014, isandlaTech :license: Apache License 2.0 :version: 0.5.7 :status: Beta .. Copyright 2014 isandlaTech Licen...
import logging import json class JSONConfig(): """ This class imports a configuturation file from disk in JSON format. """ filename = None def __init__(self, filename=None): """ Initialise the JSONConfig object. :param filename: config file to work with. ...
from traits.api import HasTraits, Str, Int, Bool, Any, Float, \ Dict, Instance, List, Date, Time, Long, Bytes, Tuple # ============= standard library imports ======================== # ============= local library imports ========================== class PersistenceSpec(HasTraits): run_spec = Instance('pych...
""" FlexGet Plugin Tests. Copyright (c) 2011 The PyroScope Project <<EMAIL>> """ # 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 l...
class Context: user = ... def get_result(calculation, instrument, tmax): pass def _run(calculation, output_instruments, log, storage): with Context() as context: for r in calculation.inputs: r.restore(storage, context) run_script = ''' import boyle proc...
""" Defines ToggleColumnMixIn class """ from __future__ import print_function import logging from qframer.qt import QtCore, QtGui from qframer.qt.QtCore import Qt logger = logging.getLogger(__name__) class ToggleColumnMixIn(object): """ Adds actions to a QTableView that can show/hide columns by right c...
# -*- encoding: utf-8 -*- from django.db import models from django.contrib.auth.models import User import sys # sys.setdefaultencoding is cancelled by site.py reload(sys) # to re-enable sys.setdefaultencoding() sys.setdefaultencoding('utf-8') #rom django.contrib.auth.models import AbstractBaseUser # Create your m...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.utils.encoding import python_2_unicode_compatible MUNICIPIOS_GEO = getattr(settings, 'MUNICIPIOS_GEO', False) if MUNICIPIOS_GEO: from django.contrib.gis.db import models else: from django.db import mo...
""" Support for monitoring the local system.. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.systemmonitor/ """ import logging import homeassistant.util.dt as dt_util from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.helpers....
import json from oslo_utils import uuidutils from testtools import testcase import websocket from zaqar.tests.functional import base class TestQueues(base.V1_1FunctionalTestBase): config_file = 'websocket_mongodb.conf' server_class = base.ZaqarServer def setUp(self): if not base._TEST_INTEGRAT...
"""Sync a git repository to a given manifest. This script is intended to define all of the ways that a source checkout can be defined for a Chrome OS builder. If a sync completes successfully, the checked out code will exactly match whatever manifest is defined, and no local git branches will remain. Extraneous files...
#!/usr/bin/python # This script is just a thin wrapper on top of the E' model in implied.eprime import sys,os,getopt minionbin="./minion" (optargs, other)=getopt.gnu_getopt(sys.argv, "", ["q=", "lambda=", "d=", "numcodes=", "numsols=", "timelimit=", "fillin="]) if len(other)!=1: print("Usage: efpa.py --q=<alphab...
""" Utils for video bumper """ from __future__ import absolute_import import copy import json import logging from collections import OrderedDict from datetime import datetime, timedelta import pytz from django.conf import settings from .video_utils import set_query_parameter try: import edxval.api as edxval_api...
""" Functions for uploading files to server via SFTP. """ from __future__ import print_function, division, absolute_import import os import ctypes import multiprocessing import time import datetime import logging import binascii import paramiko try: # Python 2 import Queue except: # Python 3 import...
import json from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseBadRequest, \ HttpResponseNotAllowed, HttpResponseRedirect from django.conf import settings from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db import transaction # Creat...
"""Module for testing.""" from unittest import TestCase from unittest.mock import Mock from grortir.main.model.core.abstract_stage import AbstractStage class TestAbstractStage(TestCase): """Class for testing AbstractStage.""" def test___init__(self): """Constructor test.""" tested_object = ...
#!/usr/bin/env python # ================================================================================ # Python Modual # ================================================================================ import os import sys import string import time # ================================================================...
from django.http import HttpResponse from django.template import RequestContext from django.shortcuts import render_to_response from lingcod.screencasts.models import Screencast, YoutubeScreencast from django.conf import settings def listTutorials(request, screencasts_template='tutorials.html'): return re...
# encoding: utf-8 from setuptools import setup, find_packages import os setup( name = "django-secdownload-storage", version = "0.1.1", url = 'https://bitbucket.org/ionelmc/django-secdownload-storage', download_url = '', license = 'BSD', description = """Django storage backend that can be used ...
from __future__ import absolute_import, division, print_function, unicode_literals from azure_common import BaseTest, arm_template class ContainerRegistryTest(BaseTest): def setUp(self): super(ContainerRegistryTest, self).setUp() def test_container_registry_schema_validate(self): with self.s...
# -*- coding: utf-8 -*- from django.views.generic.edit import View from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from dead_users.mixins import PermissionRequiredMixin from dead_base.utilities import get_client_ip from dead_base import constants from dead_base.mixins import AddMe...
from django.core.urlresolvers import reverse as urlreverse from django.db.models.query import QuerySet from django.forms.widgets import Widget from django.utils.safestring import mark_safe from django.utils.html import conditional_escape class ButtonWidget(Widget): def __init__(self, *args, **kwargs): sel...
import datetime import store.models CART_ID = 'CART-ID' class ItemAlreadyExists(Exception): pass class ItemDoesNotExist(Exception): pass class Cart: def __init__(self, request): cart_id = request.session.get(CART_ID) if cart_id: try: cart = store.models.Cart.objects.get(id=cart_id, checked_out=F...
from typing import Dict from unittest.mock import patch import orjson from zerver.lib.test_classes import WebhookTestCase class TrelloHookTests(WebhookTestCase): STREAM_NAME = "trello" URL_TEMPLATE = "/api/v1/external/trello?stream={stream}&api_key={api_key}" WEBHOOK_DIR_NAME = "trello" def test_tr...
""" Process ppapi header files, e.g. ../ppapi/c/ppp_*h and ../ppapi/c/ppb_*h And check whether they could cause pnacl calling convention problems """ from __future__ import print_function import sys import re # NOTE: there is an extra white space at the end # which distinguishes them from pointer types # ...
#!/bin/python import numpy import unittest from src import ciphertext from src import homomorphic_arithmetic class HomomorphicArithmeticTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.dimension = 3 cls.odd_modulus = 5 cls.ciphertexts = [ ciphertext.Ciphertex...
import json from flask import Flask from mock import Mock import unittest2 as unittest from werkzeug.exceptions import NotAcceptable from molly.apps.homepage.endpoints import HomepageEndpoint class EndpointTestCase(unittest.TestCase): APP_MODULE = 'http://example.com/test' APP_INSTANCE_NAME = 'test' APP_...
''' 发信人: peking2 (clojure), 信区: JobHunting 标 题: 我的面试题总结 发信站: BBS 未名空间站 (Sat Oct 26 19:32:12 2013, 美东) 好多人问,我就发到这里吧。 面试题的构成和分类 首先声明一下,这里的面试题主要所指数据结构和算法的题目,题目的分析集中在 Leetcode上面的题目上。 我认为一道面试题由以下几个方面组成的 Question Data structure in question Data structure in solution Algorithm in solution Coding 题目:非常关键,一个题目通常有一些...
"""A parser for SGML, using the derived class as a static DTD.""" # XXX This only supports those SGML features used by HTML. # 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 ...
"""Tests for tensorflow.ops.tf.gather_nd.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import numpy as np from tensorflow.python.client import session from tensorflow.python.framework import constant_op from tensorflow.python.framework i...
#Deadly Defense: Complete Scoundrel, p. 76 from templeplus.pymod import PythonModifier from toee import * import tpdp print "Registering Deadly Defense" #Check if the weapons is usable with finesse def IsFinesseWeapon(creature, weapon): #Unarmed works if (weapon == OBJ_HANDLE_NULL): return 1 #Ranged weapons...
"""Runs perf tests. Our buildbot infrastructure requires each slave to run steps serially. This is sub-optimal for android, where these steps can run independently on multiple connected devices. The buildbots will run this script multiple times per cycle: - First: all steps listed in --steps in will be executed in pa...
#!/usr/bin/env python import shutil from optparse import OptionParser PREFIX='~/gcc48mipsci20' TARGET='mipsel-linux-gnu' SRCROOT='~/work/src_root' TARGETROOT='~/work/target_root/MIPSCreatorCI20' my_ver_binutils='2.24' my_ver_gmp='5.1.3' my_ver_mpfr='3.1.2' my_ver_mpc='1.0.2' my_ver_isl='0.12.2' my_ver_cloog='0.18.1'...
from ceilometerclient import exc as ceilometerclient_exc from heat.common import exception from heat.engine import constraints from heat.engine import properties from heat.engine import resource from heat.engine import watchrule COMMON_PROPERTIES = ( ALARM_ACTIONS, OK_ACTIONS, REPEAT_ACTIONS, INSUFFICIENT_DATA_A...
from __future__ import absolute_import, print_function, unicode_literals import datetime import logging import tempfile from sqlalchemy.orm.exc import NoResultFound from requests.exceptions import RequestException from ckan.lib import search from ckan.plugins import PluginImplementations, toolkit from .config impor...
from django.core import urlresolvers from django.conf.urls import include, url from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import Permission from wagtail.wagtailcore import hooks from wagtail.contrib.wagtailsearchpromotions import admin_urls from wagtail.wagtailadmin.menu i...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ hare = turtle = head while hare and ha...
import os import check_manifest from .base import Tool, Issue IGNORE_MSGS = ( 'lists of files in version control and sdist match', ) class CheckManifestIssue(Issue): tool = 'manifest' pylint_type = 'W' class CheckManifestUI(check_manifest.UI): def __init__(self, dirname): super().__init_...
"""Rendering pool for grow documents.""" import random import threading from grow.templates import filters from grow.templates import jinja_dependency from grow.templates import tags from grow.templates import tests as jinja_tests class Error(Exception): """Base rendering pool error.""" def __init__(self, m...
#!/usr/bin/env python import roslib; roslib.load_manifest('lisa_drive') import rospy import sys import argparse from nav_msgs.msg import Odometry from geometry_msgs.msg import Twist import numpy as np import matplotlib.pyplot as plt class VelocityControl: def __init__(self, target_speed, alpha): self.target_spee...
from flask import render_template, flash, redirect, session, url_for, request, \ g, jsonify from flask.ext.login import login_user, logout_user, current_user, \ login_required from flask.ext.sqlalchemy import get_debug_queries from flask.ext.babel import gettext from datetime import datetime from guess_language...
import logging from .BaseClassifier import BaseClassifier log = logging.getLogger("Thug") class CookieClassifier(BaseClassifier): default_rule_file = "rules/cookieclassifier.yar" default_filter_file = "rules/cookiefilter.yar" _classifier = "Cookie Classifier" def __init__(self): Ba...
import datetime import os import sys import traceback if sys.version_info[0] == 3: def to_str(value): return value.decode(sys.getfilesystemencoding()) def execfile(path, global_dict): """Execute a file""" with open(path, 'r') as f: code = f.read() code = code.repla...
"""The testing suite for seqtools""" import unittest, sys, gzip, hashlib, cStringIO, os from seqtools.range import GenomicRange from tempfile import NamedTemporaryFile THIS_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = THIS_DIR+'/../../../data' import seqtools.format.fasta as fasta class FASTA(unittest....
#!/usr/bin/env python """ 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");...
import sys def get_all_components(): from landlab.components import COMPONENTS from landlab.core.model_component import Component components = [] for cls in COMPONENTS: if issubclass(cls, Component): components.append(cls) return components def get_all_components_by_name():...
from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab from django.core import management from celery import shared_task #from datasets.tasks import compute_priority_score_taxonomy_node # set the default Django settings module for the 'celery' ...
import sys, os __all__ = ["context"] class Error(Exception): pass class Context(object): def __init__(self): # find the data files fn_datadir = os.path.join(os.path.dirname(__file__), "datadir.txt") if os.path.isfile(fn_datadir): f = file(fn_datadir) datadir...
from string import ascii_uppercase from hypothesis import given, example from hypothesis.strategies import sampled_from, just, binary from cryptopals.s1 import break_single_char_xor, single_char_xor, english_score def test_challenge3(): # The hex encoded string: s = '1b37373331363f78151b7f2b783431333d7839782...