code stringlengths 1 199k |
|---|
"""senseira URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.cloud.automl.v1beta1", manifest={"AnnotationSpec",},
)
class AnnotationSpec(proto.Message):
r"""A definition of an annotation spec.
Attributes:
name (str):
Output only. Resource name of the annotation spec. Form:
... |
from os.path import basename
import tensorflow as tf
from third_party.xiuminglib import xiuminglib as xm
from . import logging as logutil, img as imgutil, tensor as tutil
logger = logutil.Logger(loggee="util/light")
def vis_light(light_probe, outpath=None, h=None):
# In case we are predicting too low of a resolutio... |
from django.utils.translation import ugettext_lazy as _
from model_mommy import mommy
from .base import CMSPluginTestCase
from ..interface import models
class GridPluginTest(CMSPluginTestCase):
plugin = 'GridPlugin'
atributos = {
'name': _('Grid'),
'allow_children': True,
'child_classes'... |
from heapq import heappush, heappop
from itertools import cycle
import six
from six.moves import xrange, zip
from threading import Condition
import sys
from cassandra.cluster import ResultSet
import logging
log = logging.getLogger(__name__)
def execute_concurrent(session, statements_and_parameters, concurrency=100, rai... |
from .ipahttp import ipa |
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
import os
class ImagePrefix(Resource):
def __init__(self):
self.resourceName = 'imageprefix'
self.route('GET', (), self.getImagePrefix)
@access.public
def getImagePrefix(self, param... |
import os,re,shutil
import gen_trend_html
class TrendItem(object):
def __init__(self, chart_file, csv_file):
self.chart_file = chart_file
self.csv_file = csv_file
chart_file_items = chart_file.split('/')
self.name = chart_file_items[len(chart_file_items)-1]
def gen_sum(indir, sum_t... |
__source__ = 'https://leetcode.com/problems/array-partition-i/'
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(sorted(nums)[::2])
if __name__ == "__main__":
print Solution().arrayPairSum([1,4,3,2])
Java = '''
App... |
from pipeline.param.base_param import BaseParam
class DataTransformParam(BaseParam):
"""
Define data_transform parameters that used in federated ml.
Parameters
----------
input_format : str, accepted 'dense','sparse' 'tag' only in this version. default: 'dense'.
please have a look... |
from .__about__ import (
__title__, __summary__, __uri__, __version__, __author__, __email__,
__license__, __copyright__
)
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
] |
"""
Copyright 2017 Ronald J. Nowling
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 writing, software... |
import copy
from oslo_serialization import jsonutils
import six
from nova import objects
from nova.objects import base
from nova.objects import fields
from nova import utils
@base.NovaObjectRegistry.register
class PciDevicePool(base.NovaObject):
# Version 1.0: Initial version
# Version 1.1: Added numa_node fiel... |
from __future__ import absolute_import, division, print_function, unicode_literals
from webpages import *
@pytest.fixture
def page(browser, server_url, access_token):
return LogsPage(browser, server_url, access_token)
class TestLogsPage(object):
def test_should_find_page_div(self, page):
page.open()
... |
'''
Energy prices, especially Oil and Natural Gas, are in general fairly correlated,
meaning they typically move in the same direction as an overall trend. This Alpha
uses this idea and implements an Alpha Model that takes Natural Gas ETF price
movements as a leading indicator for Crude Oil ETF price mo... |
"""The sensor tests for the nut platform."""
from homeassistant.const import PERCENTAGE
from .util import async_init_integration
async def test_pr3000rt2u(hass):
"""Test creation of PR3000RT2U sensors."""
await async_init_integration(hass, "PR3000RT2U", ["battery.charge"])
registry = await hass.helpers.enti... |
"""The Uniform distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.py... |
from JumpScale import j
from urllib.parse import urlparse
class Offliner:
"""
functionality to inspect objectr structure and generate apifile
"""
def __init__(self):
self.__jslocation__ = "j.tools.offliner"
# @asyncio.coroutine
def getSiteDownloadCmd(self, url, dest="", level=5, docEleme... |
"""Provide functionality for TTS."""
import asyncio
import ctypes
import functools as ft
import hashlib
import io
import logging
import mimetypes
import os
import re
from typing import Optional
from aiohttp import web
import mutagen
import voluptuous as vol
from homeassistant.components.http import HomeAssistantView
fr... |
from __future__ import unicode_literals |
from tempest_lib import exceptions as lib_exc
from tempest.api.database import base
from tempest import test
class DatabaseFlavorsNegativeTest(base.BaseDatabaseTest):
@classmethod
def setup_clients(cls):
super(DatabaseFlavorsNegativeTest, cls).setup_clients()
cls.client = cls.database_flavors_cl... |
import pandas
f1 = pandas.read_csv("f1.csv")
f2 = pandas.read_csv("f2.csv",";")
print("Исходные данные")
print(f1)
print(f2)
print("Добавление столбцов")
country = [u'Украина',u'РФ',u'Беларусь',u'РФ',u'РФ']
f2.insert(0, 'country', country)
print("Выборка")
dset = f2[f2.country == u'РФ']
print(dset)
print("Добавление ст... |
from __future__ import unicode_literals
from unittest import TestCase
from hamcrest import assert_that, equal_to, has_items, close_to, \
contains_string, instance_of, has_length, none
from storops import DiskTechnologyEnum, TierTypeEnum, HotSparePolicyStatusEnum
from storops.unity.resource.disk import UnityDiskList... |
import requests as rq
from pyramid.view import view_config, view_defaults
from pyramid.httpexceptions import HTTPError, HTTPBadRequest, HTTPClientError
from ddb.models.base import DBSession
from ddb.models.pois import Poi
from ddb.controller import CommonController
from ddb.controller.cluster import Cluster
from geoalc... |
import logging
import time
import asyncio
import os
from concurrent.futures import ProcessPoolExecutor
import functools
import traceback
import psutil
from . import stats
from . import config
LOGGER = logging.getLogger(__name__)
def stats_wrap(partial, name, url=None):
'''
Helper function to propagate stats bac... |
"""Fix missing nested domain DB migration
Revision ID: 27583c259fa7
Revises: 799f0516bc08
Create Date: 2020-05-27 14:18:11.909757
"""
revision = '27583c259fa7'
down_revision = '799f0516bc08'
import os
import sys
from neutron.db import migration
from oslo_utils import importutils
from gbpservice.neutron.db.migration imp... |
__version__ = """1.27.0.dev0""" |
"""Tests for certbot.client."""
import os
import shutil
import tempfile
import unittest
import OpenSSL
import mock
from acme import jose
from certbot import account
from certbot import errors
from certbot import le_util
from certbot.tests import test_util
KEY = test_util.load_vector("rsa512_key.pem")
CSR_SAN = test_uti... |
from django import http
from django.contrib import messages
from django.core.urlresolvers import reverse
from mox import IgnoreArg, IsA
from horizon import api
from horizon import test
class NetworkViewTests(test.BaseViewTests):
def setUp(self):
super(NetworkViewTests, self).setUp()
self.network = {... |
"""
WSGI config for do_ipam project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_M... |
import requests
import geojson
from geojson import Feature, FeatureCollection, Point
from drf_yasg.utils import swagger_auto_schema
from rest_framework.response import Response
from rest_framework.views import APIView
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exemp... |
from setuptools import setup, find_packages
setup(
name="swfcarve",
version="3.0.0",
author="Marcus LaFerrera (@mlaferrera)",
url="https://github.com/PUNCH-Cyber/stoq-plugins-public",
license="Apache License 2.0",
description="Carve and decompress SWF files from payloads",
packages=find_pack... |
"""Invokes all the unit tests for the module."""
import unittest
import dir_archive_test
import path2listtest
import pyfib_test
def suite():
"""Returns the suite of unit tests."""
suites = [dir_archive_test.suite(), path2listtest.suite(),
pyfib_test.suite()]
return unittest.TestSuite(suites)
i... |
"""This is the setup file for airdialogue python library."""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="airdialogue-essentials",
version="0.1",
scripts=["airdialogue/bin/airdialogue"],
author="Wei Wei",
author_email="wewei@google.com",... |
import os
from typing import List
from dbt.dataclass_schema import ValidationError
from dbt.contracts.graph.parsed import (
IntermediateSnapshotNode, ParsedSnapshotNode
)
from dbt.exceptions import (
ParsingException, validator_error_message
)
from dbt.node_types import NodeType
from dbt.parser.base import SQLP... |
import os
import sys
from twisted.internet import utils
from txweb2.test import test_server
from txweb2 import resource
from txweb2 import http
from txweb2.test import test_http
from twisted.internet.defer import waitForDeferred, deferredGenerator
from twisted.python import util
class Pipeline(test_server.BaseCase):
... |
GRAVITATION = 9.81
TANK_DIAMETER = 1.38
TANK_SECTION = 1.5
PUMP_FLOWRATE_IN = 2.55 # Per hour
PUMP_FLOWRATE_OUT = 2.45 # Per hour
PH_PUMP_FLOWRATE_IN = 0.7
PH_PUMP_FLOWRATE_OUT = 0.7
PUMP_FLOWRATE_OUT_2 = 2.5
LIT_101_M = {
'LL': 0.250,
'L': 0.50,
'H': 0.800,
'HH': 1.200
}
PH_201_M = {
'LL': 0.50,
'L': 0.700,... |
"""
Route module encapsulates functions related to static routing and
related configurations on NGFW.
When retrieving routing, it is done from the engine context.
For example, retrieve all routing for an engine in context::
>>> engine = Engine('sg_vm')
>>> for route_node in engine.routing:
... print(route... |
from twisted.spread import pb
from twisted.internet import reactor
from twisted.cred import credentials
class Client(pb.Referenceable):
def remote_print(self, message):
print message
def connect(self):
factory = pb.PBClientFactory()
reactor.connectTCP("localhost", 8800, factory)
... |
from mininet.topo import Topo
class MyTopo( Topo ):
"Simple topology example."
def __init__( self):
"Create custom topo."
# Add default members to class.
Topo.__init__(self)
# Add nodes
Host1=self.addHost('h1', ip='10.0.0.1/24')
Host2=self.addHost('h2', ip='10.0.0... |
import os
from imposm.parser import OSMParser
from nose.tools import eq_
class ParserTestBase(object):
osm_filename = None
ways_filter = None
nodes_filter = None
relations_filter = None
def __init__(self):
self.nodes = []
self.coords = []
self.ways = []
self.relations... |
"""
Inline token class, used to configure inline callouts for easy search and replace.
Doctests:
>>> InlineToken(':FOO:', 'https://www.example.org/foo.png').expand()
'<img alt=":FOO:" title=":FOO:" style="vertical-align: text-bottom; position: relative" src="https://www.example.org/foo.png"/>'
>>> InlineToken(':HINT:',... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
[TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'],
[TestAction.create_mini_vm, 'vm2', 'cluster=cluster1'],
[... |
'''
@author: sheng
@license:
'''
import unittest
from meridian.acupoints import zhigou11
class TestZhigou11Functions(unittest.TestCase):
def setUp(self):
pass
def test_xxx(self):
pass
if __name__ == '__main__':
unittest.main() |
_base_ = './cascade_mask_rcnn_r101_fpn_random_seesaw_loss_mstrain_2x_lvis_v1.py' # noqa: E501
model = dict(
roi_head=dict(
mask_head=dict(
predictor_cfg=dict(type='NormedConv2d', tempearture=20)))) |
"""
gene.py realize the methods that are related to system recommendation.
@author: Bowen
"""
from system.models import gene, reaction, compound, reaction_compound, compound_gene, pathway, pathway_compound, organism
from system.fasta_reader import parse_fasta_str
from elasticsearch import Elasticsearch
import traceback... |
"""Simple output handler"""
import json
import typing
import collections
from .stage import Stage, Stage_to_str
from .filter import InvalidStage
from .abstract_output_handler import AbstractOutputHandler
class OutputHandler(AbstractOutputHandler):
"""Output handler used in standalone mode."""
def __init__(self,... |
"""Input pipelines."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v2 as tf
def decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_feat... |
import sys
from fn.core import main
ROOT = "http://seriesblanco.com"
URL_TREE = ROOT+"/serie/1531/black_sails.html"
URL = ROOT+"/serie/1531/temporada-{}/capitulo-{}/black_sails.html"
main(sys.argv, ROOT, URL_TREE, URL) |
"""Backend-dependent tests for the Python XLA client."""
import functools
import itertools
import re
import threading
import unittest
from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
import numpy as np
from tensorflow.compiler.xla.python import xla_client
try:
from tenso... |
"""
The module contains internal data representation in SATOSA and general converteras that can be used
for converting from SAML/OAuth/OpenID connect to the internal representation.
"""
import datetime
import hashlib
from enum import Enum
class UserIdHashType(Enum):
"""
All different user id hash types
"""
... |
import unittest
import threading
from simple_condition import SimpleCondition
import time
class SimpleConditionTest(unittest.TestCase):
def test_simple_bool(self):
cond = SimpleCondition(False)
self.assertEqual(cond.get(), False)
def set_true():
time.sleep(0.5)
cond.s... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")
# sys.path.append('../')
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
def one():
fig = plt.figure()
ax1 = fig.add_subplot(121, aspect='equal', autoscale_on=False, xlim=(-0, 2), ylim=(-1.5, 1.5))
ax2 = fig.add_subplot(122, aspect='equal', autoscale_on=False, xlim=(-1.1, 1.1), ylim=(-1.1, 1... |
from __future__ import print_function
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.ticker import MaxNLocator
import cPickle as pickle
import copy
from operator import itemgetter
import numpy as np
import scipy.special as special
import scipy.optimize
import scipy.stats
from scipy.stats.mstats imp... |
from bee import *
import libcontext
from libcontext.pluginclasses import *
from libcontext.socketclasses import *
class keyboardmove(drone):
def __init__(self, player):
assert player in ("White", "Black")
self.player = player
self.moveprocessors = []
def move(self, event):
if sel... |
import datetime
from .. import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
groups_table = db.Table('group_to_user',
db.Column('user_id', db.Integer,
db.ForeignKey('users.id')),
db.Column('gr... |
"""
Copyright (c) 2012-2014, Austin Benson and David Gleich
All rights reserved.
This file is part of MRTSQR and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
"""
"""
This is a script to run the TSQR with... |
__author__ = 'HSING LI'
'''
Database operation module. This module is independent with db module.
'''
import time, logging
import db
class Field(object):
_count = 0
def __init__(self, **kw):
self.name = kw.get('name', None)
self._default = kw.get('default', None)
self.primary_key = kw.ge... |
'''Test helper utilities'''
import tempfile
import os
import numpy as np
import pytest
import crema.utils
from crema.exceptions import DataError
def test_git_version():
ver = crema.utils.git_version()
assert len(ver) == 7 and isinstance(ver, str)
@pytest.fixture
def fake_dir():
fdir = tempfile.mkdtemp()
... |
import logging
import glob
import os
import sys
from nymms.daemon import NymmsDaemon
from nymms.config import yaml_config
from nymms.utils import load_object_from_string, logutil
from nymms.exceptions import OutOfDateState
logger = logging.getLogger(__name__)
class Reactor(NymmsDaemon):
def __init__(self):
... |
from husk import Repo
from husk.decorators import cli
__doc__ = """\
Moves an existing note to a new path.
"""
@cli(description=__doc__)
def parser(options):
# Find the nearest repo
repo = Repo.findrepo(options.repo)
src = repo.relpath(options.src)
dest = repo.relpath(options.dest)
repo.notes.move(s... |
from __future__ import absolute_import, division, print_function
import numpy as np
from astropy.wcs import WCSSUB_CELESTIAL
from ..wcs_utils import convert_world_coordinates
from ..array_utils import iterate_over_celestial_slices, pad_edge_1
__all__ = ['reproject_celestial']
def map_coordinates(image, coords, **kwargs... |
import os
from setuptools import setup, find_packages
VERSION = "1.7.2"
src_dir = os.path.dirname(__file__)
install_requires = [
"future",
"troposphere>=1.9.0",
'botocore>=1.12.111', # matching boto3 requirement
"boto3>=1.9.111,<2.0",
"PyYAML>=3.13b1",
"awacs>=0.6.0",
"gitpython>=2.0,<3.0",... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Log'
db.delete_table('pypi_log')
# Deleting model 'ChangeLog'
db.delete_table('pypi_changelog')
... |
__author__ = 'Dave Foster <dfoster@asascience.com>'
from pyon.ion.process import IonProcessThread
from pyon.ion.endpoint import ProcessRPCServer
from gevent.event import AsyncResult, Event
from gevent.coros import Semaphore
from gevent.timeout import Timeout
from pyon.util.unit_test import PyonTestCase
from pyon.util.i... |
import argparse
import datetime
import re
import subprocess
import sys
def get_cert_chain_from(filename):
begin_regex = r'^-+?BEGIN CERTIFICATE-+\n$'
end_regex = r'^-+?END CERTIFICATE-+\n?$'
chain = []
try:
with open(filename, 'rb') as f:
begin_seen = False
for line in f:... |
from django.contrib import admin
from videos.module.chapters.models import Chapter
from feincms import extensions
class ChapterInline(admin.TabularInline):
fields = ('title', 'timecode', 'preview')
model = Chapter
extra = 1
class Extension(extensions.Extension):
def handle_model(self):
pass
... |
"""
@package mi.instrument.nortek.aquadopp.playback.driver
@author Pete Cable
@brief Driver for the aquadopp ascii mode playback
Release notes:
Driver for Aquadopp DW
"""
import datetime
from mi.core.exceptions import SampleException
from mi.core.instrument.chunker import StringChunker
from mi.core.instrument.instrumen... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'moneypertime.views.home', name='home'),
# url(r'^moneypertime/', include('moneypertime.foo.urls')),
# Uncomment the admin/doc line below to enabl... |
from django.urls import path
from django.contrib.auth.decorators import login_required
from oauth_api.views import AuthorizationView, TokenView, TokenRevocationView
app_name = 'oauth_api'
urlpatterns = [
path('authorize/', login_required(AuthorizationView.as_view()), name='authorize'),
path('token/', TokenView.... |
"""Make client.key a UUID
Revision ID: 8a9bf9d385c2
Revises: f65c00c0cfc3
Create Date: 2020-03-20 18:43:41.802182
"""
from alembic import op
from sqlalchemy.sql import column, table
from sqlalchemy_utils import UUIDType
import sqlalchemy as sa
from progressbar import ProgressBar
import progressbar.widgets
from coaster.... |
import logging
import nose
import os
import cle
TEST_BASE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.join('..', '..', 'binaries'))
def test_xbe():
xbe = os.path.join(TEST_BASE, 'tests', 'x86', 'xbox', 'triangle.xbe')
ld = cle.Loader(xbe, auto_loa... |
from __future__ import absolute_import
from pymongo.cursor import Cursor as PymongoCursor
class Cursor(PymongoCursor):
def __init__(self, *args, **kwargs):
self.__wrap = None
if kwargs:
self.__wrap = kwargs.pop('document_class', None)
super(Cursor, self).__init__(*args, **kwargs)... |
"""
Created on Fri Nov 07 11:57:42 2014
@author: Wasit
"""
import cv2
import numpy as np
def draw_circle(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),100,(255,0,0),-1)
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle... |
import itertools
from .base import dotted_to_nested, deepmixdicts
from .core import Parametric
from .apps import Computer
from .descriptors import Dict, OfType, Choice, dynamic_class
class ParamBuilder(Parametric):
choices = Dict(str, (list, tuple), default={})
ranges = Dict(str, (list, tuple), default={})
... |
import pygame
import sys
from helpers import load_image
from pygame.locals import MOUSEBUTTONUP
class GUI:
# Constants
EMPTY = 0
PLAYER_ONE = 1
PLAYER_TWO = 2
BOARD_WIDTH = 9
BOARD_HEIGHT = 5
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 431
SPACE_DIST = 45
STONE_SIZE = 47
X_OFFSET = Y_... |
import datetime
import os
import uuid
from decimal import Decimal
import pytest
from django.http import QueryDict
from django.test import TestCase, override_settings
from django.utils import six, timezone
import rest_framework
from rest_framework import serializers
class TestEmpty:
"""
Tests for `required`, `al... |
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
h = NullHandler()
logging.getLogger('elderberrypy').addHandler(h) |
from django.core.exceptions import NON_FIELD_ERRORS, FieldDoesNotExist, ValidationError
__ALL__ = (
"_get_pk_val",
"serializable_value",
"full_clean",
"_get_unique_checks",
"_perform_unique_checks",
"_perform_date_checks",
"validate_unique",
"clean",
"clean_fields",
)
def _get_pk_val... |
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import TableBuild as tb |
import unittest
from adrian import cgen
from testutils import CgenTestCase
stdlib_incl = cgen.Include("stdlib.h")
malloc_func = cgen.CFuncDescr(
name="malloc", rettype=cgen.CTypes.ptr(cgen.CTypes.void),
args=(cgen.CTypes.size, ),
includes=[stdlib_incl])
class DeclTest(CgenTestCase):
def test_no_size(sel... |
""" Open the current documentation in a web browser. """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import webbrowser
import qidoc.parsers
import qisys.sh
import qisys.command
import qisys.parsers
from qisys import ui
def con... |
'''
=============================================
Open Facebook - A generic Facebook API
=============================================
This API is actively maintained, just fork on github if you wan
to improve things.
Follow the author: Thierry Schellenbach (@tschellenbach)
blog: http://www.mellowmorning.com/
my compan... |
from django.contrib.syndication.feeds import Feed
from django.core.urlresolvers import reverse
from django.conf import settings
from journal.models import Entry
class EntryEntryFeed(Feed):
title = settings.CMSPLUGIN_NEWS_RSS_TITLE
description = settings.CMSPLUGIN_NEWS_RSS_DESCRIPTION
def items(self):
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import hickle as hkl
import numpy as np
np.random.seed(2 ** 10)
from keras import backend as K
K.set_image_dim_ordering('tf')
import tensorflow as tf
import time
from keras import regularizers
from keras.layers ... |
"""
WSGI config for nvuptime project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
os.environ.... |
from __future__ import unicode_literals
from django.conf.urls import url, include
from django.contrib import admin
from cruds.urls import (
crud_for_model,
)
from .models import Author, Country
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
urlpatterns += crud_for_model(Author, urlprefix='testapp/')
urlpat... |
'''
Build a attention-based neural machine translation model
'''
import theano
import theano.tensor as tensor
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import cPickle as pkl
import numpy
import copy
import os
import warnings
import sys
import time
from scipy import optimize, stats
from colle... |
import unittest
from cybox.objects.win_mailslot_object import WinMailslot
from cybox.test.objects import ObjectTestCase
class TestWinMailslot(ObjectTestCase, unittest.TestCase):
object_type = "WindowsMailslotObjectType"
klass = WinMailslot
_full_dict = {
'handle': {
'name': "First Mailsl... |
from __future__ import division, print_function, absolute_import
from os.path import join, dirname
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_equal
from scipy.fftpack.realtransforms import dct, idct, dst, idst
MDATA = np.load(join(dirname(__file__), 'test.npz'))
X = [MDATA['x%d' % i]... |
from __future__ import print_function
import json
from os import listdir, getcwd, remove
from os.path import join, isfile
from src.handlers.jsonHandler import JsonHandler as js
from tests.test_utils import returnFiles
class TestJsonHandler:
def setup(self):
self.path = join(getcwd(), 'test_handlers', 'test_... |
import numpy as np
import re
import itertools
from collections import Counter
import unicodedata
def strip_accents(text):
"""
Strip accents from input String.
:param text: The input string.
:type text: String.
:returns: The processed String.
:rtype: String.
"""
try:
text = unicod... |
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'2gis'
copyright = u'2012, svartalf'
version = release = '1.3.1' # dgis.__version__
exclude_patterns = ['_build']
pygments_style = 'sphi... |
from __future__ import absolute_import, print_function
import os
import sys
import glob
import tempfile
import subprocess
from distutils import log
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.errors import CompileError, LinkError
from .setup_helpers imp... |
"""
This module contains utility functions that are commonly needed in other
qutip modules.
"""
__all__ = ['n_thermal', 'linspace_with', 'clebsch', 'convert_unit',
'view_methods']
import numpy as np
from scipy.misc import factorial
def n_thermal(w, w_th):
"""
Return the number of photons in thermal e... |
def get_version():
return '1.0.0alpha1' |
def extractLazyinuWordpressCom(item):
'''
Parser for 'lazyinu.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', ... |
"""
Created by Yann N. Dauphin on 2008-11-11.
Copyright (c) 2008 Lambda Tree Media. All rights reserved.
You only need to modify this file to add or remove instructions.
This file defines:
- The Assembly Language that is supported
- The machine code that is generated
So the compiler is easily retargetable.
"""
INSTRUCT... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import zipfile
from PySide.QtCore import Qt
from arrow import arrow
from PySide import QtGui, QtCore
from mcedit2.appsettings import RecentFilesSetting
from mcedit2.rendering import blockmeshes
from mcedit2.rendering.blockmodel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.