code stringlengths 1 199k |
|---|
import jinja2
from jingo import register
from tower import ugettext_lazy as _lazy
from mkt.site.helpers import page_title
@register.function
@jinja2.contextfunction
def operators_page_title(context, title=None):
section = _lazy('Operator Dashboard')
title = u'%s | %s' % (title, section) if title else section
... |
from __future__ import unicode_literals
from frappe.model.document import Document
class CashFlowMapper(Document):
pass |
"""
The MIT License (MIT)
Copyright (c) 2015-2016 Rapptz
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, pu... |
import pandas as pd
import pytz
import numpy as np
from six import integer_types
from unittest import TestCase
import zipline.utils.factory as factory
from zipline.sources import (DataFrameSource,
DataPanelSource,
RandomWalkSource)
from zipline.utils import trad... |
import agents as ag
import envgui as gui
import submissions.Porter.vacuum2 as v2
class Dirt(ag.Thing):
pass
class VacuumEnvironment(ag.XYEnvironment):
"""The environment of [Ex. 2.12]. Agent perceives dirty or clean,
and bump (into obstacle) or not; 2D discrete world of unknown size;
performance measure... |
"""
Implement common functions for tests
"""
from __future__ import print_function
from __future__ import unicode_literals
import io
import sys
def parse_yaml(yaml_file):
"""
Parses a yaml file, returning its contents as a dict.
"""
try:
import yaml
except ImportError:
sys.exit("Unab... |
import waterfall_window
import common
from gnuradio import gr, blks2
from pubsub import pubsub
from constants import *
class _waterfall_sink_base(gr.hier_block2, common.wxgui_hb):
"""
An fft block with real/complex inputs and a gui window.
"""
def __init__(
self,
parent,
baseband_freq=0,
ref_level=50,
sam... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from pants.util.dirutil import safe_mkdir_for
class ReproMixin(object):
""" Additional helper methods for use in Repro tests"""
def add_file(self, root, p... |
import base64
import os
import unittest
import zipfile
try:
from io import BytesIO
except ImportError:
from cStringIO import StringIO as BytesIO
try:
unicode
except NameError:
unicode = str
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.test.sel... |
from tests.package.test_python import TestPythonPackageBase
class TestPythonPy2Can(TestPythonPackageBase):
__test__ = True
config = TestPythonPackageBase.config + \
"""
BR2_PACKAGE_PYTHON=y
BR2_PACKAGE_PYTHON_CAN=y
"""
sample_scripts = ["tests/package/sample_python_can.py"]
... |
from boto.s3.user import User
class ResultSet(list):
"""
The ResultSet is used to pass results back from the Amazon services
to the client. It is light wrapper around Python's :py:class:`list` class,
with some additional methods for parsing XML results from AWS.
Because I don't really want any depen... |
"""Provides factories for Split."""
from xmodule.modulestore import ModuleStoreEnum
from xmodule.course_module import CourseDescriptor
from xmodule.x_module import XModuleDescriptor
import factory
from factory.helpers import lazy_attribute
from opaque_keys.edx.keys import UsageKey
class SplitFactory(factory.Factory):
... |
from Model import * |
import frappe
from frappe.exceptions import ValidationError
import unittest
class TestBatch(unittest.TestCase):
def test_item_has_batch_enabled(self):
self.assertRaises(ValidationError, frappe.get_doc({
"doctype": "Batch",
"name": "_test Batch",
"item": "_Test Item"
}).save) |
from .....testing import assert_equal
from ..specialized import BRAINSDemonWarp
def test_BRAINSDemonWarp_inputs():
input_map = dict(args=dict(argstr='%s',
),
arrayOfPyramidLevelIterations=dict(argstr='--arrayOfPyramidLevelIterations %s',
sep=',',
),
backgroundFillValue=dict(argstr='--backgroundF... |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"NetworkedMultiplayerENet",
]
def get_doc_path():
return "doc_classes" |
from __future__ import division, print_function, absolute_import
import numpy as np
import scipy.interpolate as interp
from numpy.testing import assert_almost_equal
class TestRegression(object):
def test_spalde_scalar_input(self):
"""Ticket #629"""
x = np.linspace(0,10)
y = x**3
tck ... |
class TestRouter(object):
def allow_migrate(self, db, app_label, model_name=None, **hints):
"""
The Tribble model should be the only one to appear in the 'other' db.
"""
if model_name == 'tribble':
return db == 'other'
elif db == 'other':
return False |
"""
Test cases related to XPath evaluation and the XPath class
"""
import unittest, sys, os.path
this_dir = os.path.dirname(__file__)
if this_dir not in sys.path:
sys.path.insert(0, this_dir) # needed for Py3
from common_imports import etree, HelperTestCase, _bytes, BytesIO
from common_imports import doctest, make_... |
from . import models |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(?P<id>\d+)'
_TE... |
"""
sentry.plugins.base.structs
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ['ReleaseHook']
from sentry.models import Release
from sentry.plugins ... |
def test_local_variable():
x = 1
x = 2 |
import os
import sys
import types
def setpath():
dllpath='%s/dll' %(os.path.dirname(os.path.realpath(__file__)))
if 'PATH' in os.environ:
if dllpath not in os.environ['PATH']:
os.environ['PATH']='%s;%s' % (dllpath, os.environ['PATH'])
else:
os.environ['PATH']=dllpath
setpath()
fr... |
DOCUMENTATION = '''
---
module: raw
version_added: historical
short_description: Executes a low-down and dirty SSH command
options:
free_form:
description:
- the raw module takes a free form command to run
required: true
executable:
description:
- change the shell used to execute the command... |
"""
TODO: add a docstring.
"""
class Delimiters(object):
def first(self):
return "It worked the first time."
def second(self):
return "And it worked the second time."
def third(self):
return "Then, surprisingly, it worked the third time." |
""" Various kinds of icon widgets.
"""
from __future__ import absolute_import
from ...properties import Bool, Float, Enum
from ...enums import NamedIcon
from ..widget import Widget
class AbstractIcon(Widget):
""" An abstract base class for icon widgets. ``AbstractIcon``
is not generally useful to instantiate on... |
from __future__ import unicode_literals
from .novamov import NovaMovIE
class NowVideoIE(NovaMovIE):
IE_NAME = 'nowvideo'
IE_DESC = 'NowVideo'
_VALID_URL = NovaMovIE._VALID_URL_TEMPLATE % {'host': 'nowvideo\.(?:ch|ec|sx|eu|at|ag|co|li)'}
_HOST = 'www.nowvideo.ch'
_FILE_DELETED_REGEX = r'>This file no... |
"""
This file tests the MNISTPlus class. majorly concerning the X and y member
of the dataset and their corresponding sizes, data scales and topological
views.
"""
from pylearn2.datasets.mnistplus import MNISTPlus
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_... |
"""Regresssion tests for urllib"""
import urllib
import httplib
import unittest
import os
import sys
import mimetools
import tempfile
import StringIO
from test import test_support
from base64 import b64encode
def hexescape(char):
"""Escape char as RFC 2396 specifies"""
hex_repr = hex(ord(char))[2:].upper()
... |
"""
Romanian specific form helpers.
"""
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError, Field, RegexField, Select
from django.utils.translation import ugettext_lazy as _
class ROCIFField(RegexField):
"""
A Romanian fiscal identity code (CIF) field
For CIF ... |
from __future__ import unicode_literals
import io
import optparse
import os
import sys
ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, ROOT_DIR)
import youtube_dl
def main():
parser = optparse.OptionParser(usage='%prog OUTFILE.md')
options, args = parser.parse_args()
if len(args)... |
import _codecs_kr, codecs
import _multibytecodec as mbc
codec = _codecs_kr.getcodec('johab')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.MultibyteIncrementalEncoder,
codecs.IncrementalEncoder):
codec = codec
class IncrementalDe... |
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, pass_d0=False)
t.write("sleep.bat", """\
::@timeout /T %1 /NOBREAK >nul
@ping 127.0.0.1 -n 2 -w 1000 >nul
@ping 127.0.0.1 -n %1 -w 1000 >nul
@exit /B 0
""")
t.write("file.jam", """\
if $(NT)
{
SLEEP = @call sleep.bat ;
}
else
{
SLEEP = sleep ;
}
actions .g... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nxos_vtp_password
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Manages VTP password configuration.
description:
-... |
class C:
def foo(self):
x = 1
y = 2
x = 1
def foo():
pass |
import getpass
import os
import urllib
DEFAULT_GAIA_URL = "https://www.google.com:443/accounts/ClientLogin"
class GaiaAuthenticator:
def __init__(self, service, url = DEFAULT_GAIA_URL):
self._service = service
self._url = url
## Logins to gaia and returns auth token.
def authenticate(self, email, passwd):... |
"""Checker for spelling errors in comments and docstrings.
"""
import sys
import tokenize
import string
import re
if sys.version_info[0] >= 3:
maketrans = str.maketrans
else:
maketrans = string.maketrans
from pylint.interfaces import ITokenChecker, IAstroidChecker
from pylint.checkers import BaseTokenChecker
fr... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_parse_qs,
compat_urlparse,
)
from ..utils import (
determine_ext,
int_or_none,
xpath_text,
)
class InternetVideoArchiveIE(InfoExtractor):
_VALID_URL = r'https?://video\.internetvideoarchive\.n... |
from __future__ import unicode_literals
import frappe
test_records = frappe.get_test_records('Blog Category') |
import re
from django.template import Node, Variable, VariableNode
from django.template import TemplateSyntaxError, TokenParser, Library
from django.template import TOKEN_TEXT, TOKEN_VAR
from django.template.base import _render_value_in_context
from django.utils import translation
from django.utils.encoding import forc... |
"""This test checks for correct wait4() behavior.
"""
import os
import time
from test.fork_wait import ForkWait
from test.test_support import run_unittest, reap_children, get_attribute
get_attribute(os, 'fork')
get_attribute(os, 'wait4')
class Wait4Test(ForkWait):
def wait_impl(self, cpid):
for i in range(1... |
a = {'b',] |
from __future__ import division, absolute_import, print_function
import unittest
import os
import sys
import copy
from numpy import (
array, alltrue, ndarray, zeros, dtype, intp, clongdouble
)
from numpy.testing import (
run_module_suite, assert_, assert_equal, SkipTest
)
from numpy.core.multiarray import typei... |
from __future__ import absolute_import
import logging
import re
import pip
from pip.req import InstallRequirement
from pip.req.req_file import COMMENT_RE
from pip.utils import get_installed_distributions
from pip._vendor import pkg_resources
from pip._vendor.packaging.utils import canonicalize_name
from pip._vendor.pkg... |
"""
Base classes for writing management commands (named commands which can
be executed through ``django-admin`` or ``manage.py``).
"""
from __future__ import unicode_literals
import os
import sys
import warnings
from argparse import ArgumentParser
from optparse import OptionParser
import django
from django.core import ... |
from django import template
from django.apps import apps
from django.utils.encoding import iri_to_uri
from django.utils.six.moves.urllib.parse import urljoin
register = template.Library()
class PrefixNode(template.Node):
def __repr__(self):
return "<PrefixNode for %r>" % self.name
def __init__(self, var... |
urlpatterns = []
handler404 = 'csrf_tests.views.csrf_token_error_handler' |
"""Class for storing shared keys."""
from utils.cryptomath import *
from utils.compat import *
from mathtls import *
from Session import Session
from BaseDB import BaseDB
class SharedKeyDB(BaseDB):
"""This class represent an in-memory or on-disk database of shared
keys.
A SharedKeyDB can be passed to a serv... |
"""Utility functions for Windows builds.
These functions are executed via gyp-win-tool when using the ninja generator.
"""
from ctypes import windll, wintypes
import os
import shutil
import subprocess
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def main(args):
executor = WinTool()
exit_code = e... |
from tests import unittest
from tests import mock
from unbound_ec2 import server
from tests import attrs
class TestServer(server.Server):
HANDLE_FORWARD_RESULT = 'dummy_handle_forward'
HANDLE_PASS_RESULT = True
DNSMSG = mock.MagicMock()
def handle_request(self, _id, event, qstate, qdata, request_type):
... |
import csv
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as stats
from scipy.optimize import curve_fit
def countKey(key,listDataDicts):
outDict = {}
for row in listDataDicts:
try:
outDict[row[key]] += 1
except KeyError:
outDict[row[key]] = 1
re... |
import sys
import types
import typing as t
import decorator as deco
from gssapi.raw.misc import GSSError
if t.TYPE_CHECKING:
from gssapi.sec_contexts import SecurityContext
def import_gssapi_extension(
name: str,
) -> t.Optional[types.ModuleType]:
"""Import a GSSAPI extension module
This method imports ... |
from __future__ import division
from libtbx.test_utils import approx_equal
from libtbx.utils import Usage
from libtbx import easy_run
import libtbx.load_env
import platform
import time
import sys, os
op = os.path
__this_script__ = "cctbx_project/fable/test/sf_times.py"
# based on cctbx_project/compcomm/newslett... |
import numpy as np
from metaworld.policies.action import Action
from metaworld.policies.policy import Policy, assert_fully_parsed, move
class SawyerCoffeeButtonV1Policy(Policy):
@staticmethod
@assert_fully_parsed
def _parse_obs(obs):
return {
'hand_pos': obs[:3],
'mug_pos': o... |
from runner.koan import *
class AboutDictionaries(Koan):
def test_creating_dictionaries(self):
empty_dict = dict()
self.assertEqual(dict, type(empty_dict))
self.assertEqual(dict(), empty_dict)
self.assertEqual(0, len(empty_dict))
def test_dictionary_literals(self):
empty_... |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
from ..workspace import Block
from twisted.internet import defer
from .variables import lexical_variable
import operator
class logic_null (Block):
def eval (self):
return defer.succeed(None)
class logic_boolean (Block):
def eval (self):
return defer.succeed(self.fields['BOOL'] == 'TRUE')
class logic_negate (Block... |
"""
Hack to get scripts to run from source checkout without having to set
PYTHONPATH.
"""
import sys
from os.path import dirname, join, abspath
db_path = dirname(__file__)
project_path = abspath(join(db_path, ".."))
sys.path.insert(0, project_path) |
__version__ = '0.3.9' |
'''
Grid Layout
===========
.. only:: html
.. image:: images/gridlayout.gif
:align: right
.. only:: latex
.. image:: images/gridlayout.png
:align: right
.. versionadded:: 1.0.4
The :class:`GridLayout` arranges children in a matrix. It takes the available
space and divides it into columns and row... |
"""
89. Gray Code
https://leetcode.com/problems/gray-code/
"""
from typing import List
class Solution:
def grayCode(self, n: int) -> List[int]:
res = [0]
for i in range(n):
res += [x + 2**i for x in reversed(res)]
return res
def main():
s = Solution()
print(s.grayCode(3))... |
"""
Test storage
"""
from django.test import TestCase
class StorageTestCase(TestCase):
def test_import(self):
from launchlab_django_utils.storage import StaticRootS3Boto3Storage
from launchlab_django_utils.storage import MediaRootS3Boto3Storage |
"""Linear Algebra Helper Routines."""
from warnings import warn
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import aslinearoperator
from scipy.linalg import lapack, get_blas_funcs, eig, svd
from .params import set_tol
def norm(x, pnorm='2'):
"""2-norm of a vector.
Parameters
-------... |
import sys
sys.path.insert(0,'../src/')
import rospy
import math
from math import sin, cos
from geometry_msgs.msg import Twist
from sensor_msgs.msg import LaserScan
from collections import namedtuple
Obstacle = namedtuple('Obstacle', ['r', 'theta'])
from obstacle_avoidance import ObstacleAvoidance
import unittest
class... |
import os, struct, time
try:
import fcntl
CAN_LOCK = True
except ImportError:
CAN_LOCK = False
LOCK = False
CACHE_HEADERS = False
__headerCache = {}
longFormat = "!L"
longSize = struct.calcsize(longFormat)
floatFormat = "!f"
floatSize = struct.calcsize(floatFormat)
timestampFormat = "!L"
timestampSize = struct.ca... |
'''
:author: Patrick Lauer
This class holds the Artificial Bee Colony(ABC) algorithm, based on Karaboga (2007):
D. Karaboga, AN IDEA BASED ON HONEY BEE SWARM FOR NUMERICAL OPTIMIZATION,TECHNICAL REPORT-TR06, Erciyes University, Engineering Faculty, Computer Engineering Department 2005.
D. Karaboga, B. Basturk, A powerf... |
import json
import sys
from importlib import import_module
from importlib.util import find_spec
from owlmixin import OwlMixin, TOption
from owlmixin.util import load_json
from jumeaux.addons.res2res import Res2ResExecutor
from jumeaux.logger import Logger
from jumeaux.models import Res2ResAddOnPayload, Response, Reques... |
"""
Prototype to DOT (Graphviz) converter by Dario Gomez
Table format from django-extensions
"""
from protoExt.utils.utilsBase import Enum, getClassName
from protoExt.utils.utilsConvert import slugify2
class GraphModel():
def __init__(self):
self.tblStyle = False
self.dotSource = 'digraph Sm {'
... |
import json
f = file('treasures.json', 'r')
try:
foo = json.load(f)
json_contents = foo
except ValueError:
json_contents = dict()
f.close()
print 'Type \'q\' to [q]uit'
while True:
name = raw_input('Treasure Name: ')
if name == 'q':
break
print 'Type \'n\' to stop entering heroes and go ... |
import json
from tornado import httpclient as hc
from tornado import gen
from graphite_beacon.handlers import LOGGER, AbstractHandler
class HipChatHandler(AbstractHandler):
name = 'hipchat'
# Default options
defaults = {
'url': 'https://api.hipchat.com',
'room': None,
'key': None,
... |
"""
Task description (in Estonian):
3. Maatriksi vähendamine (6p)
Kirjuta funktsioon vähenda, mis võtab argumendiks arvumaatriksi, milles ridu ja
veerge on paarisarv, ning tagastab uue maatriksi, milles on kaks korda vähem
ridu ja kaks korda vähem veerge, ja kus iga element on esialgse maatriksi nelja
elemendi keskmine... |
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import xgboost as xgb
import argparse
from os import path
import os
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
from utils import *
import pic... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import chainer
from chainer import functions as F
from chaine... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'esite.settings')
import django
django.setup()
from auto.models import Car
def add_car(make, model, km, year, color, eng, drive,trans, icolor):
c = Car.objects.get_or_create(make=make, model=model, kilometers=km, year=year, color=color, engine_size=eng, driv... |
import aioamqp
import asyncio
import umsgpack as msgpack
import logging
from functools import wraps
from uuid import uuid4
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class RemoteException(Exception):
pass
class Client(object):
def __init__(self,... |
def my_max(a, b):
if a > b:
return a
elif b > a:
return b
else:
return None
x = my_max(1, 2)
print x
print my_max(3, 2) |
import pandas as pd
import pytest
from athletic_pandas.algorithms import heartrate_models
def test_heartrate_model():
heartrate = pd.Series(range(50))
power = pd.Series(range(0, 100, 2))
model, predictions = heartrate_models.heartrate_model(heartrate, power)
assert model.params['hr_rest'].value == 0.000... |
__all__ = ['acfun_download']
from ..common import *
from .letv import letvcloud_download_by_vu
from .qq import qq_download_by_vid
from .sina import sina_download_by_vid
from .tudou import tudou_download_by_iid
from .youku import youku_download_by_vid
import json, re
def get_srt_json(id):
url = 'http://danmu.aixifan... |
import math
from autoprotocol import UserError
from modules.utils import *
def transform(protocol, params):
# general parameters
constructs = params['constructs']
num_constructs = len(constructs)
plates = list(set([construct.container for construct in constructs]))
if len(plates) != 1:
raise... |
import sys
import os
import getopt
import xattr
import zlib
def usage(e=None):
if e:
print(e)
print("")
name = os.path.basename(sys.argv[0])
print("usage: %s [-lz] file [file ...]" % (name,))
print(" %s -p [-lz] attr_name file [file ...]" % (name,))
print(" %s -w [-z] att... |
from datetime import datetime
from threading import Timer
from queue import Queue
import uuid
import logging
try:
from time import perf_counter
except ImportError:
from time import clock as perf_counter
log = logging.getLogger(__name__)
class _Task:
_processing_time = 10
_scheduler = None
def __init... |
from functional_tests import FunctionalTest, ROOT, USERS
import time
from selenium.webdriver.support.ui import WebDriverWait
class AddBasicAction (FunctionalTest):
def setUp(self):
self.url = ROOT + '/default/user/login'
get_browser=self.browser.get(self.url)
username = WebDriverWait(self, 1... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients', '0002_contact'),
]
operations = [
migrations.AlterField(
model_name='contact',
name='alternate_email',
fiel... |
from blob import Blob
from foreground_processor import ForegroundProcessor
import cv2
import operator
import rospy
from blob_detector.msg import Blob as BlobMsg
from blob_detector.msg import Blobs as BlobsMsg
import numpy as np
class BlobDetector(ForegroundProcessor):
def __init__(self, node_name):
super(Bl... |
import ctypes
import numpy as np
import os
libpath = os.path.dirname(os.path.realpath(__file__))
lib = ctypes.cdll.LoadLibrary(libpath+'\libscatt_bg.so')
scatt_bg_c = lib.scatt_bg
scatt_bg_c.restype = ctypes.c_void_p # reset return types. default is c_int
scatt_bg_c.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_... |
"""Tests for forms in eCommerce app."""
from django.test import TestCase
from ecommerce.forms import OrderForm
required_fields = {
'phone': '123456789',
'email': 'valid@email.ru',
}
invalid_form_email = {
'email': 'clearly!not_@_email',
'phone': '123456789'
}
no_phone = {'email': 'sss@sss.sss'}
class Te... |
from builtins import range
def writeMeshMatlabFormat(mesh,meshFileBase):
"""
build array data structures for matlab finite element mesh representation
and write to a file to view and play with in matlatb
in matlab can then print mesh with
pdemesh(p,e,t)
where
p is the vertex or point matrix
... |
def test_root(client):
response = client.get('/')
assert response.status_code == 200
assert response.data.decode('utf-8') == 'Hey enlil' |
import os.path
from subprocess import call
class InstallerTools(object):
@staticmethod
def update_environment(file_path,environment_path):
update_file = open(file_path, 'r')
original_lines = update_file.readlines()
original_lines[0] = environment_path+'\n'
update_file.close()
update_file = open(file_path, '... |
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("0.0.0.0", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever() |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'toolsforbiology.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
) |
from django.conf import settings
from django.db import models
from .ticket import Ticket
class Attachment(models.Model):
"""Ticket attachment model."""
ticket = models.ForeignKey(
Ticket, blank=False, related_name='attachments', db_index=True,
on_delete=models.DO_NOTHING)
user = models.Forei... |
import unittest
from juggling.notation import siteswap
class SiteswapUtilsTests(unittest.TestCase):
def test_siteswap_char_to_int(self):
self.assertEqual(siteswap.siteswap_char_to_int('0'), 0)
self.assertEqual(siteswap.siteswap_char_to_int('1'), 1)
self.assertEqual(siteswap.siteswap_char_to_... |
"""Run pytest with coverage and generate an html report."""
from sys import argv
from os import system as run
def main(): # noqa
run_str = 'python -m coverage run --include={} --omit=./* -m pytest {} {}'
arg = ''
# All source files included in coverage
includes = '../*'
if len(argv) >= 2:
a... |
from copy import deepcopy
class IModel():
def __init__(self):
self.list = []
def __getitem__(self, index):
'''
Getter for the [] operator
'''
if index >= len(self.list):
raise IndexError("Index out of range.")
return self.list[index]
def __setitem_... |
"""XML files parser backend, should be available always.
.. versionchanged:: 0.1.0
Added XML dump support.
- Format to support: XML, e.g. http://www.w3.org/TR/xml11/
- Requirements: one of the followings
- lxml2.etree if available
- xml.etree.ElementTree in standard lib if python >= 2.5
- elementtree.ElementTr... |
"""
Hannah Aizenman
10/13/2013
Generates a random subset of size 10^P for p in [1,MAX_P) from [0, 10^8)
"""
import random
MAX_P = 8
max_value = 10**MAX_P
large_set = range(max_value)
for p in xrange(1,MAX_P):
print "list of size: 10^{0}".format(p)
f = open("p{0}.txt".format(p), 'w')
sample = random.sample(l... |
import sys
import os
import re
import optparse
import math
buildscriptDir = os.path.dirname(__file__)
buildscriptDir = os.path.abspath(os.path.join(buildscriptDir, os.path.pardir))
sys.path.append(buildscriptDir)
import sandbox
import codescan
import xmail
import metadata
from ioutil import *
EXT_PAT = metadata.INTERES... |
from __future__ import division, print_function
from builtins import object
import time, copy
import numpy as np
from climlab.domain.field import Field
from climlab.domain.domain import _Domain, zonal_mean_surface
from climlab.utils import walk
from attrdict import AttrDict
from climlab.domain.xarray import state_to_xa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.