code
stringlengths
1
199k
""" mbed SDK Copyright (c) 2011-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writi...
import time from java.awt import GridLayout from java.awt.event import WindowAdapter from javax.swing import JLabel, JOptionPane, JPanel, JPasswordField, JTextField from javax.swing.JOptionPane import PLAIN_MESSAGE, UNINITIALIZED_VALUE, \ YES_NO_OPTION, OK_CANCEL_OPTION, OK_OPTION, DEFAULT_OPTION class _SwingDialog...
from runner.koan import * class AboutPackages(Koan): def test_subfolders_can_form_part_of_a_module_package(self): # Import ./a_package_folder/a_module.py from .a_package_folder.a_module import Duck duck = Duck() self.assertEqual(__, duck.name) def test_subfolders_become_modules_i...
"""Test for checking stats accumulator related ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.boosted_trees.lib.learner.batch import ordinal_split_handler from tensorflow.contrib.boosted_trees.proto import learner_pb2 from ten...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: os_server_facts short_description: Retrieve facts about one or more compute instances author: Monty version_added: "2.0" description: - Retrieve ...
import re from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon ...
test_records = [[{"doctype":"Designation", "designation_name":"_Test Designation"}]]
"""Utilities to evaluate models with respect to a variable """ import warnings import numpy as np from .base import is_classifier, clone from .cross_validation import check_cv from .externals.joblib import Parallel, delayed from .cross_validation import _safe_split, _score, _fit_and_score from .metrics.scorer import ch...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'curated'} DOCUMENTATION = ''' --- module: ec2_vpc_subnet short_description: Manage subnets in AWS virtual private clouds description: - Manage subnets in AWS virtual private clouds ...
''' EC2 external inventory script ================================= Generates inventory that Ansible can understand by making API request to AWS EC2 using the Boto library. NOTE: This script assumes Ansible is being executed where the environment variables needed for Boto have already been set: export AWS_ACCESS_KE...
from __future__ import print_function import socket import telnetlib import sys from ftplib import FTP import ftplib def is_ip(address): try: socket.inet_aton(address) ip = True except socket.error: ip = False return ip def split_into_path_and_file(name): if name.count('/') <= 0:...
""" Tutorial - Object inheritance You are free to derive your request handler classes from any base class you wish. In most real-world applications, you will probably want to create a central base class used for all your pages, which takes care of things like printing a common page header and footer. """ import cherryp...
"""Momentum for TensorFlow.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.optimizer_v2 import optimizer_v2 from tensorflow.python.training import training_ops class MomentumOptimizer(optimizer_v2.OptimizerV2): """Optimizer that ...
import datetime from django.db import DEFAULT_DB_ALIAS from django.test import TestCase from django.utils import tzinfo from models import Donut, RumBaba from django.conf import settings class DataTypesTestCase(TestCase): def test_boolean_type(self): d = Donut(name='Apple Fritter') self.assertFalse(...
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 'QueryHistory.server_name' db.add_column('beeswax_queryhistory', 'server_name', self.gf('django.db.models.fields.CharFie...
import re from urlparse import urlparse def matchFirst(string, *args): """ matches against list of regexp and returns first match""" for patternlist in args: for pattern in patternlist: r = pattern.search(string) if r is not None: name = r.group(1) ...
from . import attendance_summary
"""The ign_sismologia component."""
from __future__ import unicode_literals import frappe import unittest class TestStudent(unittest.TestCase): pass
""" Ansible module to manage mysql replication (c) 2013, Balazs Pocze <banyek@gawker.com> Certain parts are taken from Mark Theunissen's mysqldb module This file is part of Ansible Ansible is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Fr...
import threading import time from types import ListType import unittest from nose.plugins.attrib import attr from aggregator import MetricsAggregator from dogstatsd import Server from jmxfetch import JMXFetch from tests.checks.common import Fixtures STATSD_PORT = 8121 class DummyReporter(threading.Thread): def __in...
import BoostBuild import string t = BoostBuild.Tester(pass_toolset=0) t.write("core-dependency-helpers", """ rule hdrrule { INCLUDES $(1) : $(2) ; } actions copy { cp $(>) $(<) } """) code = """include core-dependency-helpers ; DEPENDS all : a ; DEPENDS a : b ; actions create-b { echo '#include <foo.h>' > $(<)...
from __future__ import unicode_literals import frappe import unittest class TestStudentBatchName(unittest.TestCase): pass
from . import constants import sys from .escsm import HZSMModel, ISO2022CNSMModel, ISO2022JPSMModel, ISO2022KRSMModel from .charsetprober import CharSetProber from .codingstatemachine import CodingStateMachine class EscCharSetProber(CharSetProber): def __init__(self): CharSetProber.__init__(self) se...
import numpy as np from numpy.testing import assert_ import scipy.special.orthogonal as orth from scipy.special._testutils import FuncData def test_eval_chebyt(): n = np.arange(0, 10000, 7) x = 2*np.random.rand() - 1 v1 = np.cos(n*np.arccos(x)) v2 = orth.eval_chebyt(n, x) assert_(np.allclose(v1, v2,...
import time from twisted.internet import reactor, protocol from twisted.trial import unittest from twisted.test.proto_helpers import StringTransport from twisted.conch import mixin class TestBufferingProto(mixin.BufferingMixin): scheduled = False rescheduled = 0 def schedule(self): self.scheduled = ...
from yowsup.structs import ProtocolEntity, ProtocolTreeNode from .iq import IqProtocolEntity class PingIqProtocolEntity(IqProtocolEntity): ''' Receive <iq type="get" xmlns="urn:xmpp:ping" from="s.whatsapp.net" id="1416174955-ping"> </iq> Send <iq type="get" xmlns="w:p" to="s.whatsapp.net" id="14...
from PIL._binary import o8 class PaletteFile(object): rawmode = "RGB" def __init__(self, fp): self.palette = [(i, i, i) for i in range(256)] while True: s = fp.readline() if not s: break if s[0:1] == b"#": continue i...
""" Gnome keyring parser. Sources: - Gnome Keyring source code, function generate_file() in keyrings/gkr-keyring.c, Author: Victor Stinner Creation date: 2008-04-09 """ from hachoir_core.tools import paddingSize from hachoir_parser import Parser from hachoir_core.field import (FieldSet, Bit, NullBits, NullBytes...
import controllers
"""Get log settings.""" import os import platform import sys from logging.handlers import SysLogHandler LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] def get_logger_config(log_dir, logging_env="no_env", tracking_filename="tracking.log", ...
""" SQS Message A Message represents the data stored in an SQS queue. The rules for what is allowed within an SQS Message are here: http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/Query_QuerySendMessage.html So, at it's simplest level a Message just needs to allow a developer t...
try: import simplejson as json except ImportError: import json import logging import werkzeug from openerp import http from openerp.http import request _logger = logging.getLogger(__name__) class SipsController(http.Controller): _notify_url = '/payment/sips/ipn/' _return_url = '/payment/sips/dpn/' d...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( parse_duration, int_or_none, ) class AnySexIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?anysex\.com/(?P<id>\d+)' _TEST = { 'url': 'http://anysex.com/156592/', 'md5': '023e9fb...
__version__ = '0.4' __author__ = 'Martin Natano <natano@natano.net>' _repository = None _branch = 'git-orm' _remote = 'origin' class GitError(Exception): pass def set_repository(value): from pygit2 import discover_repository, Repository global _repository if value is None: _repository = None ...
""" mod_customized Controllers =================== In this module, users can test their fork branch with customized set of regression tests """ from flask import Blueprint, g, request, redirect, url_for, flash from github import GitHub, ApiError from datetime import datetime, timedelta from decorators import template_r...
"""Identity related views.""" from reversion import revisions as reversion from django.contrib.auth import mixins as auth_mixins from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test ) from django.shortcuts import render from django.template.loader import render_to_strin...
from gi.repository import GObject, Gtk, Gedit, PeasGtk import ConfigParser UI_XML = '''<ui> <menubar name="MenuBar"> <menu name="ToolsMenu" action="Tools"> <placeholder name="ToolsOps_2"> <menuitem name="Change Indent" action="ChangeIndentPlugin"/> </placeholder> </menu> </menubar> </ui>''' ...
from netforce.controller import Controller from netforce.template import render from netforce.model import get_model from netforce.database import get_connection, get_active_db # XXX: move this from netforce.locale import set_active_locale, get_active_locale from .cms_base import BaseController def list_parent(obj, ls...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('bidders', '0002_bidder_photo'), ] operations = [ migrations.AddField( model_name='bidder', name='address', field=mode...
import os import signal import subprocess class Camera(object): # In order to run mjpg-streamer through Python, make sure # mjpg-streamer-experimental is installed so the .so objects # and mjpg-streamer are all on defualt PATH so we don't have # to specify path (was getting a lot of errors resulting fro...
import _plotly_utils.basevalidators class VisibleValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(self, plotly_name="visible", parent_name="heatmapgl", **kwargs): super(VisibleValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
from .user import User from .phone_certificate import PhoneCertificate
import logging def initLogger(): # create logger logger = logging.getLogger('cam') logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages file_handler = logging.FileHandler('cam.log') file_handler.setLevel(logging.DEBUG) # create console handler with a higher log level console_handl...
""" Created on Wed Mar 2 10:56:34 2016 @author: jmjj (Jari Juopperi, jmjj@juopperi.org) """ from .main import *
from util import app import hashlib import os phase2_url = '/phase2-%s/' % os.environ.get('PHASE2_TOKEN') admin_password = u'adminpass' admin_hash = hashlib.sha1(admin_password.encode('utf-8')).hexdigest() session_key = 'sessionkey' admin_session_key = 'adminsessionkey' def init_data(redis): redis.set('user:test:pa...
import click from do_cli.contexts import CTX from do_cli.commands.common import host_commands @click.command('list') @click.option('-f', '--force-refresh', is_flag=True, help='Pull data from the API') @click.option('-h', '--host-names', help='Comma separated list of host names') @CTX def cli(ctx, force_refresh, host_na...
class Request(object): def __init__(self, value): self.__value = value def get_value(self): return self.__value
import matplotlib class SinglePeak(): """Creat a class as a Peak Container""" def __init__(self,StandardPeak): self.StandardPeak=StandardPeak self.Indicator=False self.RecordIntegrationTime=0 self.MaxCounts=0 self.PeakPixel=0 self.pixel=[] self.CountsRange=[20000,50000] def GetPixel(self,Wavelength): ...
from matplotlib import pylab as plt (x,y,yEA) = in_object print(in_object) plt.plot(x,y/y.max(),label="Fully coherent") plt.plot(x,yEA/yEA.max(),label="Partial coherent") plt.xlabel("Z [um]") plt.ylabel("Intensity [Arbitrary Units]") plt.legend() plt.show()
""" By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23. 3 7 4 2 4 6 8 5 9 3 That is, 3 + 7 + 4 + 9 = 23. Find the maximum total from top to bottom of the triangle below: """ triangle = """ 75 95 64...
""" Copyright (c) 2014 l8orre Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublice...
""" Utility functions for atmospheric data wrangling / preparation. - ndarrays - netCDF files - Lat-lon geophysical data - Pressure level data and topography """ from __future__ import division import numpy as np import pandas as pd import collections import scipy.interpolate as interp from mpl_toolkits import basemap ...
import logging from pymatgen.core import Molecule from pymatgen.io.qchem_io.inputs import QCInput from pymatgen.io.qchem_io.utils import lower_and_check_unique __author__ = "Samuel Blau, Brandon Wood, Shyam Dwaraknath" __copyright__ = "Copyright 2018, The Materials Project" __version__ = "0.1" logger = logging.getLogge...
from typing import Any import pytest from run_test_service_helper import start_service def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None: with pytest.raises(SystemExit): services, future = start_service("tests/services/no_service_existing.py", monkeypatch) out, err = capsys.rea...
"""Test that arguments passed to a script Menu.main(loop=True) execute properly.""" from testlib import * SCRIPT = "script_1.py" class TestCase(unittest.TestCase): def _cleanup(self): rmfile("foo") rmfile("bar") rmfile("caz") def setUp(self): self._cleanup() self.assertFa...
from app import db from sqlalchemy import Column, String, Integer, ForeignKey class VotingVariant(db.Model): __tablename__ = 'voting_variants' id = Column(Integer, primary_key=True) voting_id = Column(Integer, ForeignKey('votings.id')) title = Column(String(255)) description = Column(String(1000)) ...
def modes(self, ell_max=None, **kwargs): """Return mode weights of function decomposed into SWSHs This method uses `spinsfast` to convert values on an equiangular grid to mode weights. The output array has one less dimension than this object; rather than the last two axes giving the values on the two-di...
import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness, PyAPITestHarness import openmc from openmc.stats import Box from openmc.source import Source class MultipoleTestHarness(PyAPITestHarness): def _build_inputs(self): #################### # Materials ###...
""" Serialize data to/from JSON """ from __future__ import absolute_import, unicode_literals import datetime import decimal import json import sys import uuid from io import BytesIO from django.core.serializers.base import DeserializationError from django.core.serializers.python import ( Deserializer as PythonDeser...
import math def calc_dist(a,b): ax=a[0] ay=a[1] bx=b[0] by=b[1] return math.sqrt((ax-bx)**2+(ay-by)**2) def normalize(shapes): """Normalize shapes >>> normalize([[(0,2.5),(2.5,2.5),(0,0),(2.5,0)],[(0,1),(1,1),(0,0),(1,0)],[(0,1),(1,1),(0,0),(1,0)],[(0,1),(1,1),(0,0),(1,0)],[(0,1),(1,1),(0,0),(1,0)],[(0,1),(1,...
"""A collection of (reusable) urwid widgets Widgets that are specific to calendaring/khal should go into __init__.py or, if they are large, into their own files """ from datetime import date, datetime, timedelta import re import urwid class DateConversionError(Exception): pass def delete_last_word(text, number=1): ...
class RCInput(): CHANNEL_COUNT = 14 channels = [] def __init__(self): for i in range(0, self.CHANNEL_COUNT): try: f = open("/sys/kernel/rcio/rcin/ch%d" % i, "r") self.channels.append(f) except: print ("Can't open file /sys/kerne...
from channels.routing import route from .consumer import party_connected, party_disconnected, party_message karaoke_routing = [ route("websocket.connect", party_connected, path=r"^/party/(?P<party_id>[a-zA-Z0-9_-]+)"), route("websocket.receive", party_message), route("websocket.disconnect", party_disconnect...
import ConfigParser class Config: def __init__(self, cfg): """@param cfg: configuration file.""" config = ConfigParser.ConfigParser(allow_no_value=True) config.read(cfg) for section in config.sections(): for name, raw_value in config.items(section): try: ...
from django.conf import settings from django.db import migrations, models import django.db.models.deletion import easy_thumbnails.fields import userena.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
from distutils.core import setup setup( name = 'moretext', packages = ['moretext'], version = '0.1', description = 'Get dummy Chinese text (lorem ipsum) with Handlino serivce.', author = 'Pomin Wu', author_email = 'pomin5@gmail.com', url = 'https://github.com/pm5/python-moretext', downlo...
from msrest.pipeline import ClientRawResponse from .. import models class DictionaryOperations(object): """DictionaryOperations operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: ...
from django.contrib import admin from Aplicacio.models import Movie, Character, Location, Team, Power admin.site.register(Movie) admin.site.register(Character) admin.site.register(Location) admin.site.register(Team) admin.site.register(Power)
from decorator import decorator from inspect import getargspec def lazy_property(func): """Decorator that makes a property lazy-evaluated. """ attr_name = '_lazy_' + func.__name__ @property def _lazy_property(self): if not hasattr(self, attr_name): setattr(self, attr_name, func(s...
import datetime naive = datetime.datetime(2015, 10, 21, 4, 29) pacific = datetime.timezone(datetime.timedelta(hours=-8)) hill_valley = datetime.datetime(2015, 10, 21, 4, 29, tzinfo=pacific) new_timezone = datetime.timezone(datetime.timedelta(hours=1)) paris = hill_valley.astimezone(new_timezone)
import math, sys import shtns import numpy as np class shtnsfiledata: # # Adopted from https://bitbucket.org/nschaeff/shtns/src/master/examples/shallow_water.py # def __init__( self, rsphere = 1.0 ): self.rsphere = rsphere def setup(self, file_info, anti_aliasing=...
""" 使用mongodb作为缓存器 测试本地缓存 """ import sys reload(sys) sys.setdefaultencoding('utf8') import json from pymongo import MongoClient from datetime import datetime, timedelta from bson.binary import Binary import zlib import time class MongoCache: def __init__(self, client=None, expires=timedelta(days=30)): self....
""" Run the contents of a spectrum library through the 4GP pipeline. """ import argparse import logging from os import path as os_path from fourgp_pipeline import PipelineFGK from fourgp_pipeline import PipelineManager from fourgp_speclib import SpectrumLibrarySqlite class PipelineManagerReadFromSpectrumLibrary(Pipelin...
from api import Api def full_url(resource): return Api.url_base.format(resource=resource)
import sys import reader import poi_emails def getToFromStrings(f): f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails = reader.parseAddresses( to_string ) from_emails = reader.parseAddresses( from_string ) cc_emails = reader.parseAddresses( cc_string ) return t...
from __future__ import print_function from django.core.management.base import BaseCommand, CommandError from alapage.models import Page class Command(BaseCommand): help = 'Creates a page' def add_arguments(self, parser): parser.add_argument('name', nargs='+', type=str) parser.add_argument('url',...
from django.views.decorators.csrf import csrf_exempt from django.utils import timezone from .models import UrlShrinked from .forms import UrlShrinkedForm from django.shortcuts import render, get_object_or_404,redirect from django.contrib.sites.shortcuts import get_current_site from django.http import JsonResponse,HttpR...
import sys from PyQt5.QtCore import Qt, QAbstractTableModel, QVariant from PyQt5.QtWidgets import QApplication, QTableView class MyData: def __init__(self): self._num_rows = 3 self._num_columns = 2 self._data = [["hello" for j in range(self._num_columns)] for i in range(self._num_rows)] ...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='WebsiteContact', fields=[ ('id', models.AutoField(serialize=False, primary_k...
import requests import os print('\n***数据与算法 GitHub自动上传脚本***\n') username = input('输入你在GitHub上的用户名,如 Robert Ying:') email = input('输入你注册GitHub用的Email:') print('\n开始配置Git...') os.system('git config --global user.name "' + username + '"') os.system('git config --global user.email ' + email) print('\n你输入的信息如下:') os.system(...
""" scitran.data.meeg ================= Data format for M/EEG data using mne-python. """ import logging import tempfile import zipfile import warnings import os from os import path as op from datetime import datetime, date import shutil from mne.io import read_raw_fif from .. import data log = logging.getLogger(__name_...
from collections import namedtuple from pybliometrics.scopus.superclasses import Retrieval from pybliometrics.scopus.utils import check_parameter_value, get_link class SerialTitle(Retrieval): @property def aggregation_type(self): """The type of the source.""" return self._entry['prism:aggregatio...
exec(open("../index.py").read()) from waitress import serve serve(application, host='0.0.0.0', port=8080, threads=1, channel_timeout=1)
import sys import numpy as np if __name__ == '__main__': print 'Loading word vectors...' wordvecs = None wordlist = [] for i, line in enumerate(sys.stdin): word, vec = line.strip().split(' ', 1) vec = map(float, vec.split()) if wordvecs is None: wordvecs = np.ones((400000, len(vec)), dtype=np....
from runner.koan import * class AboutTuples(Koan): def test_creating_a_tuple(self): count_of_three = (1, 2, 5) self.assertEqual(5, count_of_three[2]) def test_tuples_are_immutable_so_item_assignment_is_not_possible(self): count_of_three = (1, 2, 5) try: count_of_three...
from axiom.test.historic.stubloader import StubbedTest from xquotient.compose import Composer, Drafts class ComposerUpgradeTestCase(StubbedTest): """ Test that the Composer no longer has a 'drafts' attribute, that no Drafts items have been created and that the other attributes have been copied. """ ...
import astra def gpu_fp(pg, vg, v): v_id = astra.data2d.create('-vol', vg, v) rt_id = astra.data2d.create('-sino', pg) fp_cfg = astra.astra_dict('FP_CUDA') fp_cfg['VolumeDataId'] = v_id fp_cfg['ProjectionDataId'] = rt_id fp_id = astra.algorithm.create(fp_cfg) astra.algorithm.run(fp_id) out = astra.data2...
from __future__ import absolute_import import json from django import forms from django.contrib.auth.models import AnonymousUser from django.core.exceptions import ObjectDoesNotExist try: from django.urls import reverse, resolve except: from django.core.urlresolvers import reverse, resolve from django.core.vali...
class Covalent(object): x = { "H": 0.37, "He": 0.32, "Li": 1.34, "Be": 0.90, "B": 0.82, "C": 0.77, "N": 0.75, "O": 0.73, "F": 0.71, "Ne": 0.69, "Na": 1.54, "Mg": 1.30, "Al": 1.18, "Si": 1.11, "P": 1.06, "S": 1.02, "Cl": 0.99, "Ar": 0.97, "K": 1.96, "Ca": 1.74, "Sc": 1.44, "Ti": 1.36, "V": 1....
from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('transcripts', '0001_initial'), ] operations = [ migrations.AddField( model_name='transc...
""" Load pp, plot and save 8km difference """ import os, sys import matplotlib matplotlib.use('Agg') from matplotlib import rc from matplotlib.font_manager import FontProperties from matplotlib import rcParams from mpl_toolkits.basemap import Basemap rc('font', family = 'serif', serif = 'cmr10') rc('text', usetex=True)...
from __future__ import division from pyvx import * from array import array class TestDiv(object): def test_div(self): g = Graph() with g: img = Image(3, 4, DF_IMAGE_U8, array('B', range(12))) sa1 = img / 2 sa2 = img // 2 sa1.force() sa2.for...
from bundleprocessing import interpolateMetric import pandas as pd import nibabel as nib import argparse parser = argparse.ArgumentParser() parser.add_argument('-templateBundle', '--templateBundle', required = True) parser.add_argument('-subjectBundle', '--subjectBundle', required = True) parser.add_argument('-metric',...
import subprocess import os def path(*path_segments): return os.path.join(os.getcwd(), *path_segments) def open_file(*path_segments): file_path = path(*path_segments) open(file_path, 'w').close() return open(file_path, 'a') header = open(path('README_header.rst'), 'r') readme = open_file('README.rst') s...
import http_client def get_by_species(species): path = '/info/analysis/%s' % species return http_client.get(path)
import sys from pdb import Pdb from ipdb.__main__ import update_stdout, def_colors, wrap_sys_excepthook class Tdb(Pdb): def __init__(self, *args, **kwargs): Pdb.__init__(self, *args, **kwargs) self.botframe = None self.quitting = False self.stopframe = None self.codemap = {} ...
import logging import subprocess import os log = logging.getLogger('notifier') class ExecutedScript(Exception): '''Signals a script has executed''' def __init__(self, name, *args): self.name = name self.args = args def __str__(self): '''Prints useful information''' tmp = '' for arg in self.args: tmp +=...
""" Collection of raw lexer test cases and class constructor. """ from __future__ import unicode_literals import textwrap swapquotes = { 39: 34, 34: 39, # note the follow are interim error messages 96: 39, } es5_cases = [ ( # Identifiers 'identifiers_ascii', ('i my_variable_name ...
"""Provide the standard Python string.Template engine.""" from __future__ import absolute_import from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant...