content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from django.db import models
from django import forms
class BElem(models.Model):
name = models.CharField(max_length = 200)
amount = models.IntegerField()
class CodesProfit(models.Model):
code = models.CharField(max_length = 20)
name = models.TextField()
deep = models.Inte... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
try:
import requests.exceptions
from influxdb import InfluxDBClient
... |
def extractWorkNwongNet(item):
'''
Parser for 'work.nwong.net'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Poison-Wielding Fugitive', 'Poison-Wielding Fugitive', ... |
import logging
from diskimage_builder.block_device.plugin import NodeBase
from diskimage_builder.block_device.plugin import PluginBase
logger = logging.getLogger(__name__)
class FstabNode(NodeBase):
def __init__(self, config, state):
super(FstabNode, self).__init__(config['name'], state)
self.b... |
from practice.cnn.network_module import network
from dataset.mnist import load_mnist
import numpy as np
import matplotlib.pyplot as plt
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=False, one_hot_label=True)
x_train, t_train = x_train[:5000], t_train[:5000]
x_test, t_test = x_test[:1000], t_test[:1000]
... |
#!/usr/bin/env python3
from collections import OrderedDict
from enum import Enum
from cachesimulator.bin_addr import BinaryAddress
from cachesimulator.word_addr import WordAddress
# An address reference consisting of the address and all of its components
class Reference(object):
def __init__(self, word_addr, n... |
from spack import *
class RPhylostratr(RPackage):
"""Predict and explore the age of genes using phylostratigraphic methods"""
homepage = "https://github.com/arenasee/phylostratr"
git = "https://github.com/arendsee/phylostratr.git"
version('20190323', commit='9f6d1ee2e93d973dabcfc72a44af9a032cb7... |
"""
Load multiple pp diagnostic files, aggregate by year, day etc, calcualte mean, sum etc and pickle
"""
import os, sys
import glob
import itertools
import matplotlib.pyplot as plt
import matplotlib.cm as mpl_cm
import numpy as np
from mpl_toolkits.basemap import Basemap
import cPickle as pickle
import iris
impo... |
import pecan
from barbican import api
from barbican.api import controllers
from barbican.common import quota
from barbican.common import utils
from barbican.common import validators
from barbican import i18n as u
LOG = utils.getLogger(__name__)
class QuotasController(controllers.ACLMixin):
"""Handles quota retr... |
import sparkpost
from .exceptions import SparkPostAPIException
class RequestsTransport(object):
def __init__(self):
import requests
self.sess = requests.Session()
def request(self, method, uri, headers, **kwargs):
response = self.sess.request(method, uri, headers=headers, **kwargs)
... |
from tests.integration.models.orm.fixtures import *
import pytest
class TestModelGetRelatedHard(object):
@pytest.mark.asyncio(forbid_global_loop=False)
async def test_get_related_with_all_models_related_each_other(self, session):
m11 = await Model1.new(session, id=1)
m12 = await Model1.new(se... |
from __future__ import absolute_import, division, print_function, unicode_literals
import datetime
import re
def valid_year(year):
return 1920 < year < datetime.date.today().year + 5
def search_year(string):
"""Looks for year patterns, and if found return the year and group span.
Assumes there are sent... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './Plugins/VcsPlugins/vcsMercurial/LargefilesExtension/LfRevisionsInputDialog.ui'
#
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_LfRevi... |
from nicotb import *
import numpy as np
class Master(Receiver):
__slots__ = [
"vsync", "hsync", "data", "clk",
"VRANGE", "VSYNC", "VVALID",
"HRANGE", "HSYNC", "HVALID",
"strict",
]
def _Translate(self, timing):
idx = np.arange(sum(timing), dtype=np.int32)
return (
idx,
np.bitwise_or(idx < timing[0... |
import re
import logging
import subprocess
from dateutil.parser import parse as parse_date
from dateutil.tz import tzutc
from xml.etree import ElementTree as ET
from django_vcs_watch.utils import \
strip_timezone, \
guess_encoding, \
DiffProcessor
from django_vcs_watch.settings import \
REVISION_LIMIT... |
import subprocess
import re
from datetime import datetime
import time
ipfixRequired = [
"started-time", "ended-time", "vxlan", "total-bytes",
"obytes", "ibytes", "latency", "dur", "src-switch-port",
"dst-switch-port", "vlan", "ether-type", "src-ip", "dst-ip",
"src-port", "dst-port", "src-mac", "dst-mac... |
import logging
import os
import unittest
import sys
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s %(levelname)-8s %(name)s %(message)s'
)
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)),
'fixtures'))
class ModulesTestCase(unittest.TestC... |
"""Tests for eafm config flow."""
import pytest
from voluptuous.error import MultipleInvalid
from homeassistant.components.eafm import const
from tests.async_mock import patch
async def test_flow_no_discovered_stations(hass, mock_get_stations):
"""Test config flow discovers no station."""
mock_get_stations.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
https://github.com/VidereResearch/Python
Upload a single file to an AWS S3 bucket
'''
__author__ = "Videre Research, LLC"
__license__ = "GNU GPL V3"
__version__ = "1.0.1"
# I M P O R T S #####################################################... |
"""This module contains an object that represents a Telegram
UserProfilePhotos."""
from telegram import PhotoSize, TelegramObject
class UserProfilePhotos(TelegramObject):
"""This object represents a Telegram UserProfilePhotos.
Attributes:
total_count (int):
photos (List[List[:class:`telegram... |
"""Create user metadata table.
Revision ID: 534e20be9964
Revises: 2f178b0bf762
Create Date: 2015-07-03 13:26:29.138416
"""
# revision identifiers, used by Alembic.
revision = '534e20be9964'
down_revision = '2f178b0bf762'
MYSQL_CHARSET = 'utf8'
from alembic import op
import sqlalchemy as sa
def upgrade():
"""U... |
"""
MudderyNPC is NPC's base class.
"""
import json
from django.conf import settings
from django.db.models.loading import get_model
from muddery.typeclasses.characters import MudderyCharacter
from muddery.utils.dialogue_handler import DIALOGUE_HANDLER
class MudderyNPC(MudderyCharacter):
"""
Default NPC.
... |
"""Save and load Small OBjects to and from files, using various formats.
API Stability: unstable
Maintainer: U{Moshe Zadka<mailto:<EMAIL>>}
"""
import os, md5, sys
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import cStringIO as StringIO
except ImportError:
import StringIO
fro... |
#! /usr/bin/env python
# This script will replace instance's ports with the same settings.
# It will have a network downtime for the instance.
#
# usage: nova_interface_reset.py [-h] [-k] uuid
# positional arguments:
# uuid instance uuid
# optional arguments:
# -h, --help show this help message and ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
from tensorflow.contrib.distributions.python.ops import poisson as poisson_lib
from tensorflow.python.framework import constant_op
from tensorflow.python.framework imp... |
import requests
import fanart
from fanart.errors import RequestFanartError, ResponseFanartError
class Request(object):
def __init__(self, apikey, id, ws, type=None, sort=None, limit=None):
self._apikey = apikey
self._id = id
self._ws = ws
self._type = type or fanart.TYPE.ALL
... |
from repose.managers import Manager
from repose.resources import Resource
from hueclient import fields
from hueclient.decoders import IndexedByIdDecoder
from hueclient.monitor import MonitorMixin
class Sensor(Resource):
pass
class TapSwitchConfig(MonitorMixin, Resource):
on = fields.Boolean()
class Met... |
from manila.api import common
class ViewBuilder(common.ViewBuilder):
"""Model a server API response as a python dictionary."""
_collection_name = 'shares'
_detail_version_modifiers = [
"add_snapshot_support_field",
"add_consistency_group_fields",
"add_task_state_field",
"m... |
# coding: utf-8
from __future__ import unicode_literals
import unittest
import responses
import requests
from tapioca.exceptions import (
ClientError, ServerError, ResponseProcessException,
TapiocaException)
from tapioca.tapioca import TapiocaClient
from tests.client import TesterClient, TesterClientAdapte... |
"""Miscellaneous tasks that don't fit into one of the other groupings."""
import pkgutil
import zipfile
import paver.deps.six as six
from os.path import join, dirname, exists, abspath
from paver.easy import dry, task
from paver.tasks import VERSION, cmdopts
_docsdir = join(dirname(__file__), "docs")
if exists(_docsdir... |
from flask import *
from flask_socketio import *
app = Flask(__name__)
socketio = SocketIO(app)
class Shell:
cmd_queque = []
output = ""
shells = {"__server_log__": Shell()}
def server_log(msg):
global shells
msg += "\n"
socketio.emit("output", (msg, "__server_log__"), broadcast=T... |
"""
Utilities related to API views
"""
from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExist, ValidationError
from django.http import Http404
from django.utils.translation import ugettext as _
from edx_rest_framework_extensions.authentication import JwtAuthentication
from rest_framework import status
... |
#!/usr/bin/env python
"""
These macros are actually taken from the T1 font encoding package, but
I figure that it wouldn't hurt to put them all in by default.
"""
from plasTeX import Command
class ding(Command):
args = 'self'
values = {}
@property
def unicode(self):
if int(self.textContent.... |
#$Id$#
from books.util.ZohoHttpClient import ZohoHttpClient
from books.parser.RecurringInvoiceParser import RecurringInvoiceParser
from Api import Api
from json import dumps
base_url = Api().base_url + 'recurringinvoices/'
parser = RecurringInvoiceParser()
zoho_http_client = ZohoHttpClient()
class RecurringInvoices... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_sequence_solver
----------------------------------
Tests for `sequence_solver` module.
"""
import sys
import unittest
from sequence_solver import strategies
class TestSequence_solver(unittest.TestCase):
def setUp(self):
pass
def tearDown(sel... |
import copy
import datetime
from oslo.config import cfg
from heat.common import exception
from heat.common import template_format
from heat.engine import clients
from heat.engine import resource
from heat.engine import scheduler
from heat.openstack.common import timeutils
from heat.tests.common import HeatTestCase
fr... |
# -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.automate.explorer.domain import DomainCollection
from cfme.automate.simulation import simulate
from cfme.common.provider import cleanup_vm
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme... |
import tp
import mm
def thing_init(t):
return
def landrock_init(name):
x = tp.Tp(name)
x.set_short_name("Rock")
x.set_is_movement_blocking(True)
x.set_is_landrock(True)
x.set_is_solid_ground(True)
x.set_z_depth(mm.Z_DEPTH_WALL)
x.set_is_shadow_caster(True)
x.set_is_world_item(Tru... |
from __future__ import absolute_import
from __future__ import print_function
import os, re
import db.corpora as cp
from proc.general_utils import writeFileText
from proc.nlp_functions import tokenizeText
from scidoc.render_content import SciDocRenderer
from scidoc.reference_formatting import formatCitation
from colle... |
from __future__ import unicode_literals
import frappe
from frappe import throw, _
class ItemPriceDuplicateItem(frappe.ValidationError): pass
from frappe.model.document import Document
class ItemPrice(Document):
def validate(self):
self.validate_item()
self.validate_price_list()
self.check_duplicate_item()
... |
#!/usr/bin/env python
'''
Adam Bowen - Jan 2016
This script configures the delphix_admin user after domain0 is configured
Will come back and properly throw this with logging, etc
'''
VERSION="v.2.3.002"
CONTENTDIR="/u02/app/content"
import getopt
import logging
from os.path import basename
import signal
import sys
imp... |
"""
Softlayer driver
"""
import time
from libcloud.common.base import ConnectionUserAndKey
from libcloud.common.xmlrpc import XMLRPCResponse, XMLRPCConnection
from libcloud.common.types import InvalidCredsError, LibcloudError
from libcloud.compute.types import Provider, NodeState
from libcloud.compute.base import Nod... |
"""diagram objects
"""
import astroid
from pylint.pyreverse.utils import is_interface, FilterMixIn
from pylint.checkers.utils import decorated_with_property
class Figure:
"""base class for counter handling"""
class Relationship(Figure):
"""a relation ship from an object in the diagram to another
"""
... |
"""Correctness tests for tf.keras using DistributionStrategy."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
from absl.testing import parameterized
import numpy as np
import six
from tensorflow.contrib.distribute.python import combinati... |
import sigrokdecode as srd
MAX_DATA_LEN = 128
# Command ID -> name, short description
META = {
0x00: {'name': 'NOP ', 'desc': 'No operation'},
0x01: {'name': 'SWRESET', 'desc': 'Software reset'},
0x04: {'name': 'RDDID ', 'desc': 'Read display ID'},
0x09: {'name': 'RDDST ', 'desc': 'Read display s... |
# -*- coding: utf-8 -*-
import os
import re
import urllib2
import json
import pickle
# srcDir = os.path.dirname(os.path.abspath(__file__))
# print("Change workind directory to:", srcDir)
# os.chdir( srcDir )
def download_url(url):
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like ... |
from gtk.glade import XML
from kiwi.log import Logger
log = Logger('libgladeloader')
class LibgladeWidgetTree(XML):
def __init__(self, view, gladefile, domain=None):
self._view = view
self._gladefile = gladefile
XML.__init__(self, gladefile, domain)
self._widgets = [w.get_name() f... |
import select
class TestKuryr(object):
def test_exceptions(self):
import pyroute2
assert issubclass(pyroute2.NetlinkError, Exception)
assert issubclass(pyroute2.CreateException, Exception)
assert issubclass(pyroute2.CommitException, Exception)
class TestLnst(object):
def te... |
#
# Thierry Parmentelat - INRIA
#
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Filter import Filter
from PLC.Auth import Auth
from PLC.NodeTags import NodeTag, NodeTags
from PLC.Sites import Site, Sites
from PLC.Nodes import Node, Nodes
class GetNodeTags(M... |
#!/usr/bin/env python
import sys
import django
from os.path import dirname, abspath
from django.conf import settings
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
INSTALLED_APPS=[
'django.co... |
"""Test all functions related to the basic accessory implementation.
This includes tests for all mock object types.
"""
from datetime import datetime, timedelta
from unittest.mock import patch, Mock
import pytest
from homeassistant.components.homekit.accessories import (
debounce,
HomeAccessory,
HomeBrid... |
"""Test cases for Zinnia's mixins"""
from datetime import date
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from zinnia.managers import PUBLISHED
from zinnia.models.author import Author
from zinnia.models.category import Category... |
# -*- coding: utf-8 -*-
import re
class MountEntry(object):
"""
Represents a mount entry (device file, mount point and file system type)
"""
def __init__(self, dev, point, fstype, options):
self.dev = dev
self.point = point
self.fstype = fstype
self.options = options.s... |
from __future__ import unicode_literals
from __future__ import absolute_import
import os
from fig.cli.log_printer import LogPrinter
from .. import unittest
class LogPrinterTest(unittest.TestCase):
def get_default_output(self, monochrome=False):
def reader(*args, **kwargs):
yield "hello\nworld... |
"""private_mkt will be populated from puppet and placed in this directory"""
from lib.settings_base import *
from mkt.settings import *
from settings_base import *
import private_mkt
DOMAIN = 'marketplace.allizom.org'
SERVER_EMAIL = '<EMAIL>'
DOMAIN = "marketplace.allizom.org"
SITE_URL = 'https://marketplace.allizo... |
"""
Routes for the REST API are defined here.
routes are are of the form :
'/api/1'/<module>/<function>
example the route '/api/1/users/signup'
is defined in the module
api/users.py
and is handled by the function 'def signup()'
"""
from apiserver import app,auth
from flask import request
from apiserve... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
---------------------------------------------------------------------------------------------------
esp_data
mantém as informações sobre o dicionário de procedimento de esperas
This program is free software: you can redistribute it and/or modify
it under the terms of ... |
"""Python file with valid syntax, used by scripts/linters/
python_linter_test.py. This is a valid test file.
"""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
import python_utils
class FakeClass(python_uti... |
from __future__ import unicode_literals
import base64
import json
import re
from .common import InfoExtractor
from .theplatform import ThePlatformIE
from .adobepass import AdobePassIE
from ..compat import compat_urllib_parse_unquote
from ..utils import (
smuggle_url,
update_url_query,
int_or_none,
)
cla... |
import codecs
import os
import json
from collections import (
OrderedDict,
defaultdict
)
from nbconvert.exporters.html import HTMLExporter
from .base import (
APP_ROOT,
STANDALONE_ASSETS,
NB_ASSETS
)
class PresentExporter(HTMLExporter):
def __init__(self, *args, **kwargs):
# TODO: t... |
#!/usr/bin/pyhton
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, neighbors, linear_model
from sklearn import svm
from sklearn import metrics
from sklearn.cross_validation import train_test_split
from sklearn.ensemble import RandomForestClassifier
from mpl_toolkits.mplot3d import Axes... |
'''
Entry point module (keep at root):
Used to run with tests with unittest/pytest/nose.
'''
import os
try:
xrange
except:
xrange = range
def main():
import sys
# Separate the nose params and the pydev params.
pydev_params = []
other_test_framework_params = []
found_other_test_framewor... |
"""The tests for the sun automation."""
from datetime import datetime
from unittest.mock import patch
import pytest
from homeassistant.components import sun
import homeassistant.components.automation as automation
from homeassistant.const import (
ATTR_ENTITY_ID,
ENTITY_MATCH_ALL,
SERVICE_TURN_OFF,
SE... |
"""
Test common module of pyramoid_sacrud
"""
import unittest
import colander
from pyramid import testing
from pyramid_sacrud.breadcrumbs import breadcrumbs, get_crumb
from pyramid_sacrud.common import (get_settings_param, get_table,
get_table_verbose_name, import_from_string,
... |
import os
from os.path import join as pjoin, splitext, split as psplit
from distutils.command.install_scripts import install_scripts
from distutils import log
from setuptools import setup, find_packages
# See: https://matthew-brett.github.io/pydagogue/installing_scripts.html
BAT_TEMPLATE = \
r"""@echo off
REM wrapper ... |
import logging
import webapp2
from google.appengine.api import channel
from google.appengine.ext import db
from cosmopolite.lib import auth
from cosmopolite.lib import models
from cosmopolite.lib import security
from cosmopolite.lib import session
from cosmopolite.lib import utils
import config
def CreateChannel(g... |
#!/usr/bin/env python
experiment_dir = '/Users/eija/Documents/FinnBrain/pipelinedata'
DTIprep_protocol = '/Users/eija/Documents/FinnBrain/scripts/default.xml'
#
# Moves file to results folder, overwriting the existing file
#
# filename - file to be moved
# out_prefix - subject specific prefix
#
def move_to_results... |
import logging
import urllib2
import re
import time
import socket
import gevent
import util
from Config import config
from FileRequest import FileRequest
from Site import SiteManager
from Debug import Debug
from Connection import ConnectionServer
from util import UpnpPunch
class FileServer(ConnectionServer):
d... |
#!/usr/bin/python
"""Import contributions from EasyTithe to BreezeChMS.
Logs into your EasyTithe account and imports contributions into BreezeChMS using
the Python Breeze API.
Usage:
python easytithe_importer.py \\
--username <EMAIL> \\
--password easytithe_password \\
--breeze_url https://demo.breezech... |
'''
[Advanced] [In-development]
import a file exported with `chalmers export`
'''
from __future__ import unicode_literals, print_function
from argparse import FileType
import logging
from os import path
import os
import yaml
from chalmers import config, errors
from chalmers.program import Program
log = logging.... |
from __future__ import absolute_import, division, print_function
from nacl._lib import lib
from nacl.exceptions import BadSignatureError, CryptoError
crypto_sign_BYTES = lib.crypto_sign_bytes()
# crypto_sign_SEEDBYTES = lib.crypto_sign_seedbytes()
crypto_sign_SEEDBYTES = lib.crypto_sign_secretkeybytes() // 2
crypto_... |
# This module is for compatibility only. All functions are defined elsewhere.
__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle',
'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort',
'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud',
... |
# (c) 2016, Hao Feng <<EMAIL>>
from urllib.parse import unquote
import cherrypy
from .utils import *
from .consts import *
from .handler import EndpointHandler
from exe.runner import ExecuteRunner
@cherrypy.expose
class ExecuteHandler(EndpointHandler):
""" Endpoint Handler: ``/execute``. """
__RUNNER__ =... |
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
from m5.util import addToPath, fatal
import MemConfig
addToPath('../topologies')
def define_options(parser):
# By default, ruby uses the simple timing cpu
parser.set_defaults(cpu_type="timing")
parser.add_option("--ruby-clock"... |
"""Unit tests for layout functions."""
import sys
from nose import SkipTest
from nose.tools import assert_equal, assert_false, assert_raises
import networkx as nx
class TestLayout(object):
numpy = 1 # nosetests attribute, use nosetests -a 'not numpy' to skip test
@classmethod
def setupClass(cls):
... |
#!/usr/bin/env python2.7
import zipfile
import string
import pystache
def read_docx(filepath):
# todo: Add test to make sure it's a docx
zfile = zipfile.ZipFile(filepath)
# return the xml
return zfile.read("word/document.xml")
def replace_hash(kp, input_string):
outstring = input_string
for key, v... |
"""Test Z-Wave node entity."""
import asyncio
import unittest
from unittest.mock import patch, MagicMock
import tests.mock.zwave as mock_zwave
import pytest
from homeassistant.components.zwave import node_entity, const
from homeassistant.const import ATTR_ENTITY_ID
@asyncio.coroutine
def test_maybe_schedule_update(ha... |
from __future__ import absolute_import, print_function, unicode_literals
# Stdlib Imports
import fnmatch
import os
import re
# Third Party Imports
import six
# First Party Imports
import sickbeard
from sickchill.helper.encoding import ek
# Local Folder Imports
from . import common, logger
from .name_parser.parser i... |
from .visualize import MODALITY_ORDER
n_events = 'Number of alternative events'
def tidify_modalities(modality_assignments, name='event_id'):
modalities_tidy = modality_assignments.stack().reset_index()
modalities_tidy = modalities_tidy.rename(
columns={'level_1': name, 0: "modality"})
return mod... |
################################################################################
## Sorting out my shoot folders
## Problem description:
## I have my shoots and processed outcomes in the same folder.
## Sometimes the folder has RAW as well Camera JPEGs.
## I would like to separate the RAW and JPEGS into separate parall... |
"""
The `models` module for :mod:`lino_welfare.modlib.notes`.
"""
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from lino.api import dd, rt
from lino_xl.lib.notes.models import *
from lino.modlib.office.roles import OfficeUser, Offi... |
import numpy
import matplotlib as mpl
from matplotlib.figure import Figure
# fix issue of negative numbers rendering incorrectly with default font
mpl.rcParams['axes.unicode_minus'] = False
from ginga.util import iqcalc
from ginga.misc import Callback
class Plot(Callback.Callbacks):
def __init__(self, figure=Non... |
"""gh_issues.py is a module that contains the classes and functions used
by the gh-issues script.
CLASSES:
ConfigData - holds configuration information for the run
FUNCTIONS:
calc_moving_avgs
day_ctr
date_str2csv_date
gen_datestr
gen_datestr
gen_datetime
get_config_data
get_issue_p... |
from keystoneclient.auth.identity import v3
try:
from oauthlib import oauth1
except ImportError:
oauth1 = None
class OAuthMethod(v3.AuthMethod):
"""OAuth based authentication method.
:param string consumer_key: Consumer key.
:param string consumer_secret: Consumer secret.
:param string acces... |
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QMainWindow):
def __init__(self): #Runs everytime we make a window object
super(Window, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle("PyQT tuts!")
self.setWindowIcon(QtGui.QIcon('pythonlogo.png... |
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import Paginator, InvalidPage
from django.http import Http404
from django.template import (
Context,
Library,
Node,
TemplateSyntaxError,
Variable,
loader,
)
try:
from django.t... |
from prediction import predictions
import pandas as pd
import numpy as np
def compute_r_squared(data, predictions):
# Write a function that, given two input numpy arrays, 'data', and 'predictions,'
# returns the coefficient of determination, R^2, for the model that produced
# predictions.
#
# Nu... |
'''
Created on Sep 28, 2012
@author: JC_Macbook
'''
import os, time
from math import *
'''
Checking for ints and strings to pass to the other functions. I could have used one function here and split them using .isdigit()
'''
def check_int():
while True:
try:
value = input('----> ')
... |
import time, re # time.sleep, re.split
import sys # some prints
from selenium import webdriver # for running the driver on websites
from datetime import datetime ... |
'''
Created by: Sean Comer
License: "Free to share / creative commons / give credit where credit is due..."
'''
import math
import maya.cmds as cmds
import maya.api.OpenMaya as OpenMayaAPI
import maya.OpenMaya as OpenMaya
from rgbTools.utils.scene import get_fdata
def getMatrix(node):
selection = OpenMayaAPI.MSel... |
#!/usr/bin/python
"""
MAP Client, a program to generate detailed musculoskeletal models for OpenSim.
Copyright (C) 2012 University of Auckland
This file is part of MAP Client. (http://launchpad.net/mapclient)
MAP Client is free software: you can redistribute it and/or modify
it under the terms of the... |
#
# Solution to Project Euler problem 13
# by Project Nayuki
#
# https://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
#
# We do a straightforward sum thanks to Python's built-in arbitrary precision integer type.
def compute():
return str(sum(NUMBERS))[ : 10]
NUM... |
import datetime
import uuid
import mock
from oslo_config import cfg
from oslo_serialization import base64
from oslo_serialization import jsonutils
from nova.api.openstack.compute import servers
from nova.api.openstack.compute import user_data
from nova.compute import flavors
from nova import exception
from nova.netwo... |
'''
Created on Sep 25, 2011
@author: hampt
'''
import collections
import random
mfRoot = "GO:0003674"
bpRoot = "GO:0008150"
def parseGOAnnotations(goTreeFilePath,closureFilePath,ontology,annotationFilePath=""):
print "parsing go annotation"
goConfig = GOConfig()
goConfig.setTreeFilePath(goTreeFilePath)
goConfi... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
import json
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.plugins.cache import BaseCacheModule
try:
from redis import StrictRedis
except ImportError:
raise AnsibleErro... |
"""
Cat program:
IR
Hello World:
"Hello World"R
Add 2 user input numbers:
iig+r
Decrement number until 0:
im0`0P11-<j5r
Multiply 10 numbers:
P110ic0>j4m0`0mC`1*cC>9j14r
Only int && char, no float.
Dictonary of chars:
C=counter, useable for almost any variable
p=push to top of ram
ex:
p232 -... |
#!/usr/bin/env python2
# vim:fileencoding=utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import textwrap
from future_builtins import map
# from lxml.etree import El... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=8, path_list=[
[TestAction.create_vm, 'vm1', ],
[TestAction.create_volume, 'volume1', 'flag=scsi'],
[TestAction.attach_volume, 'vm1', 'volume1'],
... |
#!/usr/bin/env python
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_numbers('../data/fm_train_real.dat')
testdat = lm.load_numbers('../data/fm_test_real.dat')
parameter_list = [[traindat,testdat,1.5,10],[traindat,testdat,1.5,10]]
from shogun import Math_init_random;
Math_init_random(12345);
d... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 10:59:34 2016
@author: Riley Rustad <<EMAIL>>
This Script is designed to scrape data from Multnomah County apartment ads
from Craigslist.
"""
# =============================================================================
# Imports
import numpy as np
import os.path... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.