content stringlengths 4 20k |
|---|
import json
import threading
import time
import xml.etree.ElementTree as ElementTree
import requests
import websocket
from WinkAutomation import WinkAutomation
from PhilipsHueAutomation import PhilipsHueAutomation
from DumbTools import DumbKeyboard
from RoomsHandler import Rooms
#####################################... |
import sys
if sys.version < '3':
from StringIO import StringIO
from Tkinter import *
import tkFileDialog
import tkMessageBox
else:
from io import StringIO
from tkinter import *
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
import imp
try:
i... |
import datetime
from ecl.util.util import BoolVector
from ecl.util.test import TestAreaContext
from tests import ResTest
from res.enkf import MeasBlock, MeasData
class MeasDataTest(ResTest):
def test_create(self):
ens_size = 10
ens_mask = BoolVector( default_value = True , initial_size = ens_si... |
from odoo import models, fields, api
class RecurringContract(models.Model):
_inherit = 'recurring.contract'
@api.model
def create(self, vals):
if 'origin_id' in vals:
origin = self.env['recurring.contract.origin'].\
search([('id', '=', vals['origin_id'])])
... |
#!/usr/bin/env python
import httplib
import gnupg
import getpass
from Tkinter import *
secret = getpass.getpass("enter password")
path = getpass.getpass("~/path/to/youre/key/") # alternative is hardcoding or using arguments
def auth():
# Retrieve the encrypted message
conn = httplib.HTTPConnection("bitcoin-o... |
#!/usr/bin/env python
import sys
from setuptools import setup
import chainer_setup_build
install_requires = [
'Cython>=0.23',
'filelock',
'nose',
'numpy>=1.9.0',
'protobuf',
'six>=1.9.0']
# Hack for Read the Docs
on_rtd = chainer_setup_build.check_readthedocs_environment()
if not on_rtd:
... |
from django.core.management.base import BaseCommand
from django.db import connection
from catmaid.control.stats import populate_stats_summary
from catmaid.models import Project
class Command(BaseCommand):
help = "Rebuild statistics summary information, optionally from scratch."
def add_arguments(self, parse... |
from glance.api import cached_images
from glance.api.middleware import cache_manage
import glance.common.config
import glance.common.wsgi
import glance.image_cache
from glance.tests import utils as test_utils
import mock
import webob
class TestCacheManageFilter(test_utils.BaseTestCase):
@mock.patch.object(glance... |
"""Test block processing.
This reimplements tests from the bitcoinj/FullBlockTestGenerator used
by the pull-tester.
We use the testing framework in which we expect a particular answer from
each test.
"""
from io import BytesIO
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util... |
import uuid
from openstack import resource
class Message(resource.Resource):
# FIXME(anyone): The name string of `location` field of Zaqar API response
# is lower case. That is inconsistent with the guide from API-WG. This is
# a workaround for this issue.
location = resource.Header("location")
... |
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA).
"""
# Olivier Grisel <<EMAIL>>
# Michael Becker <<EMAIL>>
# License: 3-clause BSD.
import numpy as np
import scipy.sparse as sp
from scipy.sparse.linalg import svds
from ..base import BaseEstimator, TransformerMixin
from ..util... |
from django.db import models
from django.urls import reverse
from entries.models import ResultsFormatFields
from scores.result_modes import get_result_modes
class League(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField()
def __str__(self):
return self.name
clas... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 la... |
# coding: utf8
"""
Данные для отладчика
"""
import json
from PyQt4 import QtGui
class DebugDataProvider ():
@classmethod
def __init__ (cls, main_window):
cls.STEP_TYPE_STEP_OVER = 1
cls.STEP_TYPE_STEP_INTO_PROCEDURE = 2
cls.STEP_TYPE_STEP_INTO_MODULE = 3
cls.STEP_TYPE_STEP_OUT_PROCEDURE = 4
cls.STEP_TYPE... |
from taichi.lang.kernel_impl import TaichiCallableTemplateMapper
import taichi as ti
@ti.all_archs
def test_callable_template_mapper():
x = ti.field(ti.i32)
y = ti.field(ti.f32)
ti.root.place(x, y)
mapper = TaichiCallableTemplateMapper(
(ti.template(), ti.template(), ti.template()),
... |
import datetime
from google import auth
from googleapiclient import discovery
import utils
from utils import logging
MM = utils.MetadataManager
MD = None
MASTER_KEY = None
OSLOGIN_TESTER = None
OSADMINLOGIN_TESTER = None
TESTEE = None
TESTER_SH = 'slave_tester.sh'
OSLOGIN_USERS_LIB = None
UNIQUE_ID_USER = None
def ... |
import logging
import numpy
import os
import time
from contextlib import closing
from six.moves import cPickle
from blocks.extensions.saveload import SAVED_TO, LOADED_FROM
from blocks.extensions import TrainingExtension, SimpleExtension
from blocks.serialization import secure_dump, load, BRICK_DELIMITER
from blocks.u... |
"""File-system Transport.
Transport using the file-system as the message store.
"""
from __future__ import absolute_import, unicode_literals
import os
import shutil
import uuid
import tempfile
from . import virtual
from kombu.exceptions import ChannelError
from kombu.five import Empty, monotonic
from kombu.utils.enc... |
import argparse
from typing import List
from cmd2 import with_argparser, argparse_completer, with_category
from argparse import ArgumentParser
import tableformatter as tf
from common.models.client import Client
from shell import BasePlugin
from shell.utils.screen import available_max_width_on_screen_for_clients
cla... |
'''Tracing controller class. This class manages
multiple tracing agents and collects data from all of them. It also
manages the clock sync process.
'''
import ast
import json
import sys
import py_utils
import tempfile
import uuid
from systrace import trace_result
from systrace import tracing_agents
from py_trace_even... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import stochopy
DISTNAME = "stochopy"
DESCRIPTION = "StochOPy"
LONG_DESCRIPTION = """StochOPy (STOCHastic OPtimization for PYthon) provides user-friendly routines to sample or optimize objective functions with the most popular algorithms."""
AUTHOR ... |
"""
Support for the Meraki CMX location service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.meraki/
"""
import logging
import json
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const... |
from pprint import pformat
import os
import sys
from difflib import SequenceMatcher
from .. import logs, types, const
from ..conf import settings
from ..corrector import get_corrected_commands
from ..exceptions import EmptyCommand
from ..ui import select_command
from ..utils import get_alias, get_all_executables
def ... |
import shutil
from coalib.bears.GlobalBear import GlobalBear
from coalib.misc.Shell import run_shell_command
from coalib.results.Result import Result
class GitCommitBear(GlobalBear):
_git_command = "git log -1 --pretty=%B"
@classmethod
def check_prerequisites(cls):
if shutil.which("git") is None... |
import json
import glob
import numpy as np
conditionslist=glob.glob("./conditions.*")
size=8*8*8
numatoms=2
a=np.array([2,0,0])
b=np.array([0,1,1])
o=np.array([1,0,1])
Tmat=np.vstack((a,b,o)).T #This matrix converts parametric to normal composition (also works for chemical potentials)
d=np.linalg.det(Tmat)
#0-... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from search import views as search_views
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
... |
#!/usr/bin/env python
import sys
import re
import tokenize
import StringIO
_versions = {
'2.7.6' : '2.7',
'3.3.5' : '3.3',
}
_baseUrl = "http://docs.python.org/%s/reference/grammar.html"
_nodeTypes = {
'SINGLE': 0,
'MULTIPLE': 1,
}
class Leaf(object):
def __init__(self, value, optional, multiple,... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 3 16:35:56 2018
@author: Andreas
"""
import os
import re
import numpy as np
import pandas as pd
import pdblp
class PDBLP2():
def __init__(self, Tickers, cBatches = 50):
self.Tickers = Tickers
self.cBatches = cBatches
self.con = pdbl... |
from ceilometer.hardware import plugin
from ceilometer.hardware.pollsters import util
from ceilometer import sample
class _Base(plugin.HardwarePollster):
CACHE_KEY = 'degree'
INSPECT_METHOD = 'inspect_temperature'
class DegreeTemperaturePollster(_Base):
@staticmethod
def generate_one_sample(host, ... |
"""
Author : Guillaume "iXce" Seguin
Email : <EMAIL>
Copyright (C) 2008, Guillaume Seguin <<EMAIL>>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the... |
import pickle
from asyncio import gather, get_event_loop, open_connection
from os import close as os_close, chdir, dup2, execve, fork, mkdir, \
open as os_open, path, set_inheritable, spawnve, waitpid, \
O_RDONLY, O_WRONLY, P_WAIT
from pty import STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO
... |
DEPS = [
'build/file',
'depot_tools/bot_update',
'depot_tools/gclient',
'recipe_engine/json',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/python',
'recipe_engine/step',
]
def checkout_steps(api):
"""Run the steps to obtain a checkout of Skia."""
# Find the workdir and cache di... |
import random
import instances
import palette
import registry
from entities import animation
from entities.items import weapon
class Sword(weapon.Weapon):
def __init__(self, char='s', position=(0, 0)):
super().__init__(char, position)
self.state = DefaultParryWeaponState(self)
self.damag... |
from pyparsing import *
text = """Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in ... |
from Screens.Screen import Screen
from Components.About import about
from Components.ActionMap import ActionMap
from Components.config import config
from Components.AVSwitch import AVSwitch
from Components.SystemInfo import SystemInfo
from GlobalActions import globalActionMap
from enigma import eDVBVolumecontrol, eTime... |
from typing import List
from enum import Enum
from recognizers_number.number.extractors import ReVal, BaseNumberExtractor
from recognizers_text.utilities import RegExpUtility
from recognizers_number.number.constants import Constants
from recognizers_number.resources.japanese_numeric import JapaneseNumeric
class Japan... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from urllib import urlencode
import urllib2, sys
from bs4 import BeautifulSoup
from collections import Counter
def home(request2):
return render(request2, '... |
"""Triggers."""
import asyncio
import logging
from types import MappingProxyType
from typing import Any, Callable, Dict, List, Optional, Union
import voluptuous as vol
from homeassistant.const import CONF_PLATFORM
from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.exceptions import HomeAssistan... |
import os
import sys
from scipy.stats.mstats import mquantiles
import FittingUtilities
import matplotlib.pyplot as plt
import numpy as np
import Bootstrap
import HelperFunctions
# Define regions contaminated by telluric residuals or other defects. We will not use those regions in the cross-correlation
badregions =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.forms import models
from djanban.apps.hourly_rates.models import HourlyRate
from django import forms
# Hourly rate creation and edition form
class HourlyRateForm(models.ModelForm):
clas... |
import itk
from sys import argv, stderr, exit
itk.auto_progress(2)
if(len(argv) < 2):
print((
"Missing Parameters \n Usage: IntensityWindowingImageFilter.py inputImageFile"), file=stderr)
exit(1)
image = itk.imread(argv[1], itk.F)
# Verifies that ITK supports getting tuples for filter parameters. Not... |
from ..report import Report
from ..db2_query import DB2_Query
from coredata.models import Semester
import string
class GPAs_Query(DB2_Query):
query = string.Template("""
SELECT plan.acad_plan, term.cum_gpa, plantbl.descr, plantbl.trnscr_descr
FROM ps_acad_prog prog, ps_acad_plan plan, ps_stdnt... |
from inputs import SECOND
dimensionstrings = SECOND.dimensionstrings
class packerl:
l = None
w = None
h = None
def __init__(self, dimensions):
self.l = int(dimensions.split('x')[0])
self.w = int(dimensions.split('x')[1])
self.h = int(dimensions.split('x')[2])
def wrapping... |
import logging
import time
import os
import signal
from autotest.client.shared import error
from virttest import utils_test
def run(test, params, env):
"""
Time drift test with stop/continue the guest:
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Stop the running of the... |
#!/usr/bin/python
# build_native.py
# Build native codes
import sys
import os, os.path
import shutil
from optparse import OptionParser
def check_environment_variables_sdk():
''' Checking the environment ANDROID_SDK_ROOT, which will be used for building
'''
try:
SDK_ROOT = os.environ['ANDROID_SDK... |
"""add more indexes
Revision ID: b262149925a7
Revises: 92235b77ea53
Create Date: 2017-10-14 15:37:56.451984
"""
# revision identifiers, used by Alembic.
revision = 'b262149925a7'
down_revision = '92235b77ea53'
from collections import defaultdict
from alembic import op
import sqlalchemy as sa
from sqlalchemy import... |
import copy
import math
import netaddr
import uuid
import webob
from nova.api.openstack.compute.contrib import networks
from nova.api.openstack.compute.contrib import networks_associate
from nova import exception
from nova.openstack.common import cfg
from nova import test
from nova.tests.api.openstack import fakes
C... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = 'd0au$i5he(#ais5@-i@rv=963$a@4d2p2fmnc7(gyc2ecoi^_)'
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.s... |
import pytest
from markus.backends import statsd
from markus.main import MetricsFilter, MetricsRecord
class MockStatsd:
def __init__(self, *args, **kwargs):
self.initargs = args
self.initkwargs = kwargs
self.calls = []
def incr(self, *args, **kwargs):
self.calls.append(("incr... |
import hackersh.objects
# Metadata
__author__ = "Itzik Kotler <<EMAIL>>"
__version__ = "0.1.0"
# Implementation
class DnsDict6(hackersh.objects.ExternalComponentStdoutOutput):
class DnsDict6IPv4Output(hackersh.objects.SimpleRegExHandler):
PATTERN = "(?P<HOSTNAME>.*)\s+->\s+(?P<IPV4_ADDRESS>.*)"
... |
import asyncio
class WorkItem:
def __init__(self, context, fn, args, kwargs):
self.context = context
self.fn = fn
self.args = args
self.kwargs = kwargs
class ExecutionResult:
def __init__(self, context, result, exception):
self.context = context
self.result = ... |
import re
from django import template
from feeder.models import Feed
register = template.Library()
class SingleFeedRetriever(template.Node):
def __init__(self, slug, var_name):
self.slug = slug
self.var_name = var_name
def render(self, context):
try:
context[self.va... |
"""
This module contains class definitions for open ai gym environments.
"""
import os
import collections
import argparse
import random
from datetime import datetime
import time
from functools import reduce
import numpy as np
import tensorflow as tf
from qnetwork import DeepQNetwork, update_target_network
from repla... |
"""Test framework for starwels utils.
Runs automatically during `make check`.
Can also be run manually."""
from __future__ import division,print_function,unicode_literals
import argparse
import binascii
try:
import configparser
except ImportError:
import ConfigParser as configparser
import difflib
import js... |
def recordAllZeros(conservationFile, numBases):
# Record a row of zeros
for i in range(numBases):
# Record a 0 for each base
conservationFile.write("0" + "\t")
conservationFile.write("\n")
def processPhastconsHeader(PhastconsLineElements):
# Process a header in a Phastcons file
PhastconsChromInfo = Phastcons... |
import numpy as np
def l2_distance(a, b):
"""Computes the Euclidean distance matrix between a and b.
Inputs:
A: D x M array.
B: D x N array.
Returns:
E: M x N Euclidean distances between vectors in A and B.
Author : Roland Bunschoten
University of Amsterdam
... |
from pysnmp.carrier import error
class TimerCallable(object):
def __init__(self, cbFun, callInterval):
self.__cbFun = cbFun
self.__callInterval = callInterval
self.__nextCall = 0
def __call__(self, timeNow):
if self.__nextCall <= timeNow:
self.__cbFun(timeNow)
... |
# -*- coding: utf-8 -*-
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 model 'RubricOption'
db.create_table('controller_rubricoption', (
('id', self.gf('djang... |
from __future__ import print_function
# Copyright (c) 2014 Intel Corporation.
#
# 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 ... |
from django.contrib import admin
from frontend.models import Usuario, TipoIncidencia, EstadoIncidencia, Incidencia, Comentario
admin.site.register(Usuario)
admin.site.register(TipoIncidencia)
admin.site.register(EstadoIncidencia)
admin.site.register(Incidencia)
admin.site.register(Comentario) |
from weboob.tools.browser import BaseBrowser, BrowserHTTPNotFound
from .pages import SeriePage, SearchPage, SeasonPage, HomePage
__all__ = ['TvsubtitlesBrowser']
LANGUAGE_LIST = ['en', 'es', 'fr', 'de', 'br', 'ru', 'ua', 'it', 'gr',
'ar', 'hu', 'pl', 'tr', 'nl', 'pt', 'sv', 'da', 'fi',
... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid and World Bank
- **Impact function Test Cases.**
.. note:: 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; eithe... |
#!/usr/bin/env python3
#-*- coding:utf-8 -*-
import pymongo
class Db():
def __init__(self, reponame, **kw):
self.__connection = pymongo.MongoClient(**kw)
self.__db = self.__connection[str(reponame)]
def drop_commit(self):
self.__db.drop_collection('commit')
def drop_user(self):
self.__db.drop_collecti... |
from IPython.nbformat import read as read_nb
from IPython.nbformat import current_nbformat
from IPython.utils.traitlets import Unicode
from nbgrader.preprocessors import NbGraderPreprocessor
class IncludeHeaderFooter(NbGraderPreprocessor):
"""A preprocessor for adding header and/or footer cells to a notebook."""... |
from util import uid
from PyQt4 import QtGui, QtCore
class Bone(object):
"""Bone data"""
def __init__(self):
self.__id = uid.generateUID()
self.__name = "bone" + self.__id
self.__pos = QtCore.QPointF(0, 0)
self.__scale = QtCore.QPointF(1, 1)
self.__length = 0
s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Calculate waveguide modes
2017
Xaratustra
"""
from scipy.constants import pi, epsilon_0, mu_0, c
import numpy as np
import sys
def eng_notation(value, unit=''):
ref = {15: 'P', 12: 'T', 9: 'G', 6: 'M', 3: 'k', 0: '', -3: 'm', -6: 'u', -9: 'n', -12: 'p', -15: '... |
from __future__ import absolute_import, division, print_function
import functools
import numpy as np
from .. import Variable
from ..core import indexing
from ..core.pycompat import OrderedDict, bytes_type, iteritems, unicode_type
from ..core.utils import FrozenOrderedDict, close_on_error
from .common import (
HD... |
from typing import Any, Optional, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from azure.core.credentials_async import AsyncTokenCredential
VERSION = "unknown"
class AzureAppConf... |
import yaml;
from utils.dictionaries import RecursiveDictionary
class ConfigException(Exception):
"""Base config exception."""
pass
class NotExistsLevel(NotExistsLevel):
"""Exception raised when config path does not exists."""
pass
class SetSameLevel(NotExistsLevel):
"""Exception rais... |
# -*- coding: utf-8 -*-
#########################################################################
## This is a samples controller
## - index is the default action of any application
## - user is required for authentication and authorization
## - download is for downloading files uploaded in the db (does streami... |
# imports - standard imports
import os
import json
# imports - compatibility imports
from flask import request, jsonify
# imports - module imports
from digdet.config.server import ServerConfig
from digdet.server.app import app
from digdet.server.response import Response
from digdet.util import b64_to_image
import di... |
from uw_canvas import Canvas
from uw_canvas.courses import Courses
from uw_canvas.groups import Groups
from uw_canvas.enrollments import Enrollments
from uw_canvas.models import CanvasEnrollment
from uw_canvas.conversations import Conversations
from random import random
import re
import json
__conversations_run_id = N... |
from . import account, login_first
import flask
from zeeguu.model import Bookmark, Text
import zeeguu
@account.route("/bookmarks")
@login_first
def bookmarks():
bookmarks_list, dates = flask.g.user.bookmarks_by_date()
most_recent_seven_days = dates[0:6]
urls_by_date = {}
bookmarks_by_url = {}
fo... |
import pygame
from pygame.locals import *
import sys, os, traceback
if sys.platform == 'win32' or sys.platform == 'win64':
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.init()
pygame.font.init()
screen_size = [500,700]
icon = pygame.Surface((1,1)); icon.set_alpha(0); pygame.display.set_icon(icon)
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org'
TIMEZONE = "Europe/Paris"
# can be useful in development, but set to False when you're ready to publish
RELATIVE_URLS = True
GITHUB_URL = 'http://github.com/ameta... |
#!/usr/bin/env python
import pynotify
import argparse
import gtk
import time
import procutil
import logging
import logconfig
logger = logging.getLogger(__name__)
class GUINotifier(object):
"""
Send notifications via system notification bubbles.
"""
def __init__(self):
pynotify.init("Why do I ... |
from bs4 import BeautifulSoup
from OSMPythonTools.element import Element
from OSMPythonTools.internal.cacheObject import CacheObject
from OSMPythonTools.internal.singletonApi import SingletonApi
class Api(CacheObject):
def __init__(self, endpoint='http://www.openstreetmap.org/api/0.6/', **kwargs):
super()... |
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
MODEL_CLS_PATH = os.path.join(base_dir, 'model.py')
MODEL_CLS_NAME = 'KerasVGG16Model'
MODEL_LOAD_ARGS = {
'data_dir': os.path.join(base_dir, 'data-volume'),
} |
import unittest
from nose.plugins.attrib import attr
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.test.utils.tools import TestClient
@attr('slow')
class CMakeFindPathGeneratorTest(unittest.TestCase):
def cmake_find_package_system_libs_test(self):
conanfile = """from co... |
import unittest
from element.plugins.formatter import Formatter
class FormatterTest(unittest.TestCase):
def setUp(self):
self.formmater = Formatter()
def test_markdown(self):
content = self.formmater.format(u'**bold**')
self.assertEquals("<p><strong>bold</strong></p>", content)
... |
"""
The Game database model class and associated methods.
"""
__authors__ = ['"Bill Magnuson" <<EMAIL>>']
from google.appengine.ext import db
from game_instance import GameInstance
class Game(db.Model):
""" A model for a game type.
A Game is the parent object of GameInstance objects. Each Game
object should c... |
test_sub_dir = "test_data/1019436/session_1"
def test_remove_zero_variance_voxels():
import os
import pickle
import pkg_resources as p
import nibabel as nb
from qap.dvars import remove_zero_variance_voxels
func_motion = p.resource_filename("qap", os.path.join(test_sub_dir, \
... |
'''
Copyright (c) 2013-2017, Joshua Pitts
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and t... |
import numpy as np
import astropy.constants as const
def calculate_mu(X,Y,Z=None):
"""
Calculates mean molecular weight
Assumes:
Fully ionized gas
Composition of Hydrogen, Helium, Metals
Inputs:
X - Hydrogen mass fraction
Y - Helium mass fraction
[Z] - Metals mass fraction
- if Z omitte... |
from django.db import models
from thing.models.character import Character
from thing.models.corpwallet import CorpWallet
from thing.models.item import Item
from thing.models.station import Station
class StationOrderUpdater(models.Model):
"""Station orders"""
order_id = models.BigIntegerField(primary_key=True... |
from pylru import *
import random
# This tests PyLRU by fuzzing it with random operations, then checking the
# results against another, simpler, LRU cache implementation.
class simplelrucache:
def __init__(self, size):
# Initialize the cache as empty.
self.cache = []
self.size = size
... |
"""AsyncSSH: Asynchronous SSHv2 client and server library
AsyncSSH is a Python package which provides an asynchronous client and
server implementation of the SSHv2 protocol on top of the Python asyncio
framework. It requires Python 3.4 or later and either the PyCA library or
the PyCrypto library for some cryptographic... |
# -*-coding:utf8;-*-
import socket
import random, time
def arena(conn):
print 'A new botnet thread was started'
def clientthread(conn, minn, maxn):
time.sleep(0.5)
data = 'nodata'
try:
conn.settimeout(37)
data = conn.recv(10)
conn.settimeout(None)
... |
PINYIN_DICT = {
"a" : 1, "ai" : 2, "an" : 3, "ang" : 4, "ao" : 5,
"ba" : 6, "bai" : 7, "ban" : 8, "bang" : 9, "bao" : 10,
"bei" : 11, "ben" : 12, "beng" : 13, "bi" : 14, "bian" : 15,
"biao" : 16, "bie" : 17, "bin" : 18, "bing" : 19, "bo" : 20,
"bu" : 21, "ca" : 22, "cai" : 23, "can" : 24, "cang" : 2... |
# -*- coding:utf8 -*-
#!usr/bin/python
####################################### PART0 Description ##############################################################
# Description : separate questions and matching answers from a file
# E-mail:
# Create:2015-8-3
####################################### Part1 : Coding ######... |
from beritest_tools import BaseBERITestCase
from nose.plugins.attrib import attr
class test_cp0_hwrenable(BaseBERITestCase):
@attr('rdhwr')
def test_cp0_hwrenable_1(self):
'''Test can write and read 0 from CP0.HWREna'''
self.assertRegisterEqual(self.MIPS.a0, 0x0, "Did not read 0 from CP0.HWREn... |
#This code is mostly from Tweepy
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
#Variables that contains the user credentials to access Twitter API
access_token = "772218532801220608-FvglncyFsjQ4GvDqEwV7V98gDzCT... |
# coding=utf-8
#!/usr/bin/env python
from setuptools import setup, find_packages
VERSION = "1.0.0-rc2"
def params():
name = "SilverServer"
version = VERSION
description = "A responsive web interface for 3D printers"
long_description = open("README.md").read()
classifiers = [
"Development Status :: 4 - Beta",
... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
""" This daemon downloads and schedules the Series that dosage is tracking
because Bandwith is allways scarce there are some policies implemented in
order to improve the performance and make the dosage daemon the less invasive
posible.
The policies for downloading Tv Series... |
"""Tests for tensorflow_graphics.datasets.features.camera_feature."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow_graphics.datasets.features import camera_fea... |
"""
This file originates from the 'jupyter-packaging' package, and
contains a set of useful utilities for including npm packages
within a Python package.
"""
import os
from os.path import join as pjoin
import functools
import pipes
import sys
from subprocess import check_call
from setuptools import Command
from setup... |
#!python
#!/usr/bin/env python
# Surendra Nadh Somala, Caltech 2012
import cubit
import cubit2specfem3d
import os
import sys
from save_fault_nodes_elements import *
from absorbing_boundary import *
from boundary_definition import *
cubit.cmd('playback "TPV16.jou" ')
os.system('mkdir -p MESH')
xmin = [4]
xmax = [6]
... |
from datetime import datetime
from dateutil.tz import gettz
import pytest
import pytz
from pytz import utc
from pandas._libs.tslibs import NaT, Timestamp, conversion, to_offset
from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG
import pandas.util._test_decorators as td
import pandas._testing as tm
cl... |
from zope.interface import implementer
from twisted.protocols.policies import ProtocolWrapper
try:
# noinspection PyUnresolvedReferences
from twisted.web.error import NoResource
except ImportError:
# starting from Twisted 12.2, NoResource has moved
from twisted.web.resource import NoResource
from twist... |
from app import db
from flask.ext.restful import Resource, marshal, reqparse, abort
from models import Measurement, FrequencyMeasurement, User, FrequencyMeasurementDaily
class MeasurementAPI(Resource):
reqparse = reqparse.RequestParser(bundle_errors=True)
reqparse.add_argument('user_id', type=int, location='j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.