content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'Page.phone'
db.alter_column(u'facebook_pages_page', 'p... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.eos.eos import load_config, run_commands
from ansible.module_utils.network.eos.eos import eos_... |
#!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
# Program Parameters
#
import os
import s... |
"""
Tests for the Course Outline view and supporting views.
"""
import datetime
from mock import patch
import json
from django.core.urlresolvers import reverse
from courseware.tests.factories import StaffFactory
from student.models import CourseEnrollment
from student.tests.factories import UserFactory
from xmodule.m... |
import sys
# This function adds a link between 2 substrings. If they did not exist, it creates
# the entry.
def addlink(key1, key2, dict):
if key1 not in dict: # Create entry if it didn't exist.
dict[key1] = 0
dict[key1] += 1 # Increment it.
if key2 not in dict: # Same as above.
dict[key2] = 0
dict[key2] +=... |
import fnmatch
import json
import re
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
DEFAULT_ALGORITHM = 'literal'
DEFAULT_PRIORITY = 'first_match'
def make_regex(pattern: str, algorithm: str) -> str:
... |
import unittest
import thread_cert
import mle
LEADER_1_2 = 1
ROUTER_1_1 = 2
REED_1_2 = 3
ROUTER_1_2 = 4
REED_1_1 = 5
MED_1_1 = 6
MED_1_2 = 7
# Topology
# (lq:2) (pp:1)
# REED_1_2 ----- ROUTER_1_2
# | \ / | \
# | \/ REED_1_1 \
# (lq:2) | / \ / `rou... |
import copy
import logging
import optparse
import os
import shlex
import socket
import sys
from telemetry.core import platform
from telemetry.core import util
from telemetry.internal.browser import browser_finder
from telemetry.internal.browser import browser_finder_exceptions
from telemetry.internal.browser import pr... |
"""
Tests for class dashboard (Metrics tab in instructor dashboard)
"""
import json
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from mock import patch
from nose.plugins.attrib import attr
from six import text_type
from capa.tests.response_xml_factory import StringRespon... |
import random
from environment import Agent, Environment
from planner import RoutePlanner
from simulator import Simulator
import numpy as np
import collections
from sets import Set
class State(object):
def __init__(self, actions_enabled, heading, delta):
self.actions_enabled = actions_enabled
self... |
from os import path
import numpy as np
from numpy.testing import *
class TestFromrecords(TestCase):
def test_fromrecords(self):
r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]],
names='col1,col2,col3')
assert_equal(r[0].item(), (456, 'dbe', 1.2))
def test_... |
"""
sentry.coreapi
~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# TODO: We should make the API a class, and UDP/HTTP just inherit from it
# This will make it so we can more easily control logging with various
# m... |
import re
def _disable_module(module):
name = module.params['name']
a2dismod_binary = module.get_bin_path("a2dismod")
if a2dismod_binary is None:
module.fail_json(msg="a2dismod not found. Perhaps this system does not use a2dismod to manage apache")
result, stdout, stderr = module.run_command(... |
"""Tests covering edX API utilities."""
# pylint: disable=missing-docstring
import json
import httpretty
import mock
from django.core.cache import cache
from nose.plugins.attrib import attr
from openedx.core.djangoapps.catalog.models import CatalogIntegration
from openedx.core.djangoapps.catalog.tests.mixins import C... |
"""
.. autoclass:: Context
:members:
"""
from .functions import dig, draw, expand, normalize_context, solve
class Context:
"""
Represents a contextual space for solving dependencies
:Parameters:
context : dict | iterable
A set of dependents to be used in place of those already
... |
import logging
from multiprocessing import Pool
from ..utils.misc import worker_init, elliptics_create_node, dump_keys
from ..range import IdRange
from ..etime import Time
from ..iterator import Iterator, MergeData, KeyInfo, IteratorResult
import os
import cPickle as pickle
import traceback
import elliptics
log = lo... |
from casper.tests import CasperTestCase
import os.path
from django.utils import unittest
class JavascriptTest(CasperTestCase):
@unittest.skip("Does not work on Jenkins yet")
def test_tests(self):
self.assertTrue(self.casper(
os.path.join(os.path.dirname(__file__), 'casper-tests/test.js'))... |
import Kamaelia.Visualisation.PhysicsGraph
from Kamaelia.Visualisation.PhysicsGraph.TopologyViewer import TopologyViewer as _TopologyViewer
_TopologyViewerServer = Kamaelia.Visualisation.PhysicsGraph.TopologyViewerServer
from PComponent import PComponent
from IconComponent import IconComponent
from PPostbox import PP... |
# coding=utf-8
import unittest
"""860. Lemonade Change
https://leetcode.com/problems/lemonade-change/description/
At a lemonade stand, each lemonade costs `$5`.
Customers are standing in a queue to buy from you, and order one at a time (in
the order specified by `bills`).
Each customer will only buy one lemonade an... |
try:
import kerberos
except ImportError:
import kerberos_sspi as kerberos
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
logger = logging.getLogger(__name__)
class KrbBackend(ModelBackend):
"""
Djan... |
import math
import cv2
class ARtag(object):
def __init__(self, outer, inner, scale):
"""Create a ARTag object, based on its inner contour,
outer contour and the scale of the image processed as
related to the image that was processed to extract them
:param outer:
The outer contour (Assumed to have 4 side... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import pyglet
from .ui import WindowState
from .game import Game
class MenuState(WindowState):
"""
Main menu state. This state displays the main menu and allows the player
to change settings, start a new game, see the credits, or quit.
... |
# -*- coding: utf-8 -*-
"""
Módulo de Usuarios
Autor: Jorge Toro [<EMAIL>]
"""
import web
import sys
from common import Sesion
from view import render
from config import DB
urls = (
"", "re",
"/", "monitoreo",
"/eventos", "eventos",
"/reporte", "reporte",
"/updateevent", "updateevent",
"/reportday... |
from __future__ import print_function
from __future__ import division
from sklearn.datasets import make_classification
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.svm import SVC
from bayes_opt import BayesianOptimization
# Load data set... |
#!/usr/bin/env python
import os, subprocess, signal
train_dir = os.path.dirname(os.path.realpath(__file__))
enclosed_dir = os.path.normpath(os.path.join(train_dir, '../../'))
caffe_dir = os.path.abspath(os.path.join(train_dir, '../../../../deps/simnets'))
subprocess.check_call('%s/generate_norb_small.py --aug_data y' ... |
#!/usr/bin/env python
import datetime
import re
import threading
import config
import db_helper
from infra import gerrit
import logger
import users
class GerritCIListener():
def __init__(self):
self.ci_user_names = []
self.cfg = config.Config()
self.db = db_helper.DBHelper(self.cfg).get(... |
import os
from gettext import gettext as _
from gi.repository import Gio
_zone_tab = '/usr/share/zoneinfo/zone.tab'
def _initialize():
"""Initialize the docstring of the set function"""
if set_timezone.__doc__ is None:
# when running under 'python -OO', all __doc__ fields are None,
# so += wo... |
import pytest
from cfme import test_requirements
from cfme.utils.appliance.implementations.ui import navigate_to
pytestmark = [
test_requirements.report,
pytest.mark.tier(3)
]
PROPERTY_MAPPING = {
"cpu": "Allocated Virtual CPUs",
"memory": "Allocated Memory in GB",
"storage": "Allocated Storage i... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from django.contrib.auth.signals import user_logged_in, user_logged_out
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .conf import settings
... |
# load libraries
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
from sklearn.cluster import KMeans
import urllib.request
from pylab import rcParams
rcParams['figure.figsize... |
import json
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.template.defaultfilters import slugify
from django.shortcuts import redirect
from .forms import NewLayerForm
from .utils import create_layer
@login_required
def layer_create(request, template='creat... |
'''
This script uses Pattern's sentiment analysis to find the average polarity and subjectivity of collected tweets about presidential candidates
by Ziyu (Selina) Wang
last modified: September 28, 2015
'''
from pattern.en import * # Importing Patern to be utilized later
# Creating a list with all the candidates names
c... |
import pygame
import math
from random import randrange as rr
import utils
class LinesMode(object):
def __init__(self, assets_path):
self.assets_path = assets_path
self.todraw = []
self.index = 0
def circle_points_generator(self, center, radius, n_points, offset=0):
while True:... |
"""
Cobra's distributed code module capable of allowing
serialization of code from one system to another.
Particularly useful for clustering and workunit stuff.
"""
import os
import sys
import logging
import importlib
import cobra
logger = logging.getLogger(__name__)
class DcodeServer:
def getPythonModule(s... |
"""
Tests for Snappy Bouncer Application
"""
from uuid import UUID
from tastypie.test import ResourceTestCase
from django.test import TestCase
from django.test.utils import override_settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core import management
fro... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'Subscribe', fields ['email']
db.create_uni... |
import csv
import simplejson as json
from six import StringIO, BytesIO, text_type
from django.http import HttpResponse
from .....exceptions import ImproperlyConfigured
from .....helpers import safe_text
from .settings import CSV_DELIMITER, CSV_QUOTECHAR
XLWT_INSTALLED = False
try:
import xlwt
XLWT_INSTALL... |
import django
from django.conf.urls import include, url
from django.conf import settings
from django.views.generic import TemplateView
from django.contrib import admin
from rest_framework import routers
#router = routers.DefaultRouter()
urlpatterns = [
#url(r'^', include(router.urls)),
url(r'^api/', include('... |
#
# Validator for "simplestream" Test
#
from pscheduler import json_validate
def spec_is_valid(json):
schema = {
"local": {
"SimplestreamTestSpecification_V1" : {
"type": "object",
"properties": {
"schema": {" type": "integer", "enum... |
from .context import revas
from revas import UnauthorizedToken
import os
import mock
import pytest
@pytest.fixture()
def assigner():
os.environ['UDACITY_AUTH_TOKEN'] = 'some auth token'
yield revas.Assigner()
@mock.patch('revas.reviewsapi.ReviewsAPI.certifications')
def test_retrieve_certifications_list(moc... |
from PyQt5.QtCore import Qt, QT_TRANSLATE_NOOP
from PyQt5.QtWidgets import QGroupBox, QVBoxLayout, QComboBox, QGridLayout, QLabel
from lisp.modules import check_module
from lisp.modules.midi.midi_input import MIDIInput
from lisp.modules.midi.midi_output import MIDIOutput
from lisp.modules.midi.midi_utils import mido_b... |
""" Compute HalsteadMetric Metrics.
HalsteadMetric metrics, created by Maurice H. HalsteadMetric in 1977, consist
of a number of measures, including:
Program length (N): N = N1 + N2
Program vocabulary (n): n = n1 + n2
Volume (V): V = N * LOG2(n)
Difficulty (D): D = (n1/2) * (N2/n2)
Effort (E... |
#!/usr/bin/env python
from setuptools import setup
def readme():
with open('README.rst', 'r', encoding='utf-8') as f:
return f.read()
def requirements():
with open('requirements.txt', 'r') as fh:
return [line.strip() for line in fh]
setup(name='match',
version='0.3.0',
descrip... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
__all__ = (
"StatService",
)
from .service import Service
class StatService(Service):
_fields = ['base_url', 'http_headers']
def __init__(self, *args, **kargs):
super(StatService, self).__init__(*args, **kargs)
def disable_ssl_cert_validation(self):
self.restclient.disable_ssl_cert_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb as mdb
import sys
import re
import utils
SENTENCES_PER_DOCUMENT = 200
DOCUMENT_NAME = 'jayasiP converbs'
DOCUMENT_OWNER = 3 #kstronski
DOCUMENT_LANGUAGE = 3 #awadhi
DOCUMENT_FOLDER = 7
con = mdb.connect('localhost', 'webuser', 'tialof', 'taggingdb');
wi... |
import numpy as np
import random
import unittest
class Item(object):
"""Class representing an item. See VotingGraph for general comments."""
def __init__(self, id, true_value=None, is_testing=False, inertia=1.0):
"""
Initializes an item.
:param known_value: None if we don't know the ... |
import logging
from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to
from swat.lib.base import BaseController, render
from swat.lib.helpers import SwatMessages
from pylons.i18n.translation import _
log = logging.getLogger(__name__)
class Authenticat... |
from __future__ import unicode_literals
import mock
import unittest
import json
import socket
import time
import gobject
gobject.threads_init()
try:
import evdev
except ImportError:
evdev = False
if evdev:
from mopidy_evtdev import agent
from mopidy.core import PlaybackState
context = gobject.MainLoop... |
from neutron.extensions import portbindings
from neutron.tests.unit import _test_extension_portbindings as test_bindings
from neutron.tests.unit import test_db_plugin as test_plugin
from neutron.tests.unit import test_security_groups_rpc as test_sg_rpc
PLUGIN_NAME = ('neutron.plugins.linuxbridge.'
'lb_... |
import os
import os.path
import sys
class FilePath(str):
"""A class based on unicode to handle filepaths on various OS platforms.
Extends:
unicode
"""
def __new__(cls, path):
"""Create new unicode file path in POSIX format. Windows paths will be
converted to forward slashes.
... |
# -*- coding: utf-8 -*-
from query import Query
class SearchKoska(Query):
def __init__(self):
Query.__init__(self)
self.words=[u"koska"]
self.query_fields=[u"!tags_N",u"!tags_CASE_Nom",u"d_govs_cop",u"govs"]
def match(self,t):
"""
koska < (N+Nom !>cop _)
"""
... |
import os
import asyncio
from bson.codec_options import CodecOptions
from bson.binary import STANDARD
from motor.motor_asyncio import (AsyncIOMotorClient,
AsyncIOMotorClientEncryption)
from pymongo.encryption import Algorithm
from pymongo.encryption_options import AutoEncryptionOpts
f... |
#!/usr/bin/python
"""
emailfilter.py -- Email tickets to Trac.
A simple MTA filter to create Trac tickets from inbound emails.
Copyright 2005, Daniel Lundin <<EMAIL>>
Copyright 2005, Edgewall Software
Please note:
This is only a starting point. See
* http://trac.edgewall.org/ticket/5327 and
* http://trac-hacks.o... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import modelcluster.fields
import modelcluster.contrib.taggit
class Migration(migrations.Migration):
dependencies = [
('taggit', '0001_initial'),
('cms_pages', '0007_auto_20150721_2318'),
... |
"""
Test TorrentProvider
"""
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickb... |
# coding: utf-8
from django.db import models
from django.utils.translation import ugettext_lazy as _
# http://www.unece.org/cefact/locode/service/location.html
COUNTRIES = (
('AF', _('Afghanistan')),
('AL', _('Albania')),
('DZ', _('Algeria')),
('AS', _('American Samoa')),
('AD', _('Andorra')),
... |
'''
Copyright (c) 2012 Alexander Abbott
This file is part of the Cheshire Cyber Defense Scoring Engine (henceforth
referred to as Cheshire).
Cheshire is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the
Free Sof... |
'''
"run" plugin for cocos command line tool
'''
__docformat__ = 'restructuredtext'
import sys
import os
import cocos
import BaseHTTPServer
import webbrowser
import threading
class CCPluginRun(cocos.CCPlugin):
"""
Compiles a project and runs it on the target
"""
@staticmethod
def depends_on():
... |
# -*- coding: utf-8 -*-
"""
moduleregistry
--------------
allows to extend given module by simply registeing classes using "register" method.
Usage::
>>> import moduleregistry
>>>
>>> import mymodule
>>> import othermodule
>>>
>>> assert not hasattr(mymodule, 'OtherClass') # True
>>>
>>> reg... |
#!/usr/bin/env python
import pathlib
import sys
from setuptools import find_packages, setup
import versioneer
LONG_DESCRIPTION = """
Ibis is a productivity-centric Python big data framework.
See http://docs.ibis-project.org
"""
VERSION = sys.version_info.major, sys.version_info.minor
impala_requires = ['hdfs>=2.... |
"""
Test function :func:`iris.fileformats._pyke_rules.compiled_krb.\
fc_rules_cf_fc.build_dimension_coordinate`.
"""
# import iris tests first so that some things can be initialised before
# importing anything else
import iris.tests as tests
import warnings
import numpy as np
import mock
from iris.coords import Au... |
import csv
import logging
import os
import re
# MUGQIC Modules
from sample import *
log = logging.getLogger(__name__)
class Contrast:
def __init__(self, name):
self._name = name
self._controls = []
self._treatments = []
@property
def name(self):
return self._name
@p... |
# -*- coding: utf-8 -*-
from os import makedirs
from os.path import abspath, basename, dirname, join, exists, getsize
from shutil import rmtree
from zipfile import is_zipfile, ZipFile
from tarfile import is_tarfile, TarFile
from tempfile import NamedTemporaryFile
from compare import expect
from django.test import Te... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 24 21:02:49 2016
@author: Michy
@name: Quick .csv plot
@description: Plot a csv as quickly as possible from cmd line
@example: example of use from terminal (or cmd): python plot_csv.py file1.csv x y
@notes:
1. Default path is current working directory
2. Default f... |
__title__ = "Solver elmer FEM unit tests"
__author__ = "Bernd Hahnebach"
__url__ = "https://www.freecadweb.org"
import sys
import unittest
from os.path import join
import FreeCAD
import femsolver.run
from . import support_utils as testtools
from .support_utils import fcc_print
from .support_utils import get_namefrom... |
"""Cepstral Features for speaker recognition"""
import numpy
import bob
from .. import utils
import struct
class SPROFeatures:
"""Extracts Cepstral coefficents"""
def __init__(self, config):
self.m_config = config
def normalize_features(self, params):
#########################
## Initialisation p... |
import mock
import six
from dci.common import utils
from dci.stores.swift import Swift
SWIFT = 'dci.stores.swift.Swift'
# team_user_id is subscribing to topic_user_id
def test_topics_export_control_true(user, epm, team_user_id, topic_user_id):
topic = epm.get('/api/v1/topics/%s' % topic_user_id).data['topic']
... |
""" Unit tests for the ninja.py file. """
import gyp.generator.ninja as ninja
import unittest
import sys
class TestPrefixesAndSuffixes(unittest.TestCase):
def test_BinaryNamesWindows(self):
# These cannot run on non-Windows as they require a VS installation to
# correctly handle variable expansion.
if ... |
from ._abstract import AbstractScraper
from ._utils import get_minutes, get_yields, normalize_string
class TwoPeasAndTheirPod(AbstractScraper):
@classmethod
def host(cls):
return "twopeasandtheirpod.com"
def title(self):
return self.soup.find("h2", {"class": "wprm-recipe-name"}).get_text(... |
from ase.atoms import string2symbols
abinitio_energies = {
'CO_gas': -626.611970497,
'H2_gas': -32.9625308725,
'CH4_gas': -231.60983421,
'H2O_gas': -496.411394229,
'CO_111': -115390.445596,
'C_111': -114926.212205,
'O_111': -115225.106527,
'H_111': -1... |
from flask_sqlalchemy import SQLAlchemy
from flask import current_app, url_for
import pywebpush
import json
import datetime
import os
import uuid
import requests
from shutil import copyfileobj
from .socketio import socketio
db = SQLAlchemy()
class PhoneNumber(db.Model):
"""Represents a phone number that we cont... |
'''Модуль справки'''
license_of_software = '''\
\rThe MIT License (MIT)
\rCopyright (c) 2016 Tuzhilkin Ivan
\rPermission 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, inc... |
"""Base classes for API tests.
"""
from oslo_config import cfg
from oslo_config import fixture as fixture_config
from oslo_policy import opts
import pecan
import pecan.testing
from ceilometer.tests import db as db_test_base
OPT_GROUP_NAME = 'keystone_authtoken'
cfg.CONF.import_group(OPT_GROUP_NAME, "keystonemiddlewa... |
# Customising the graph
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import urllib
def convert_date(date_format, encoding='utf-8'):
string_converter = mdates.strpdate2num(date_format)
def bytes_converter(b):
s = b.decode(encoding)
return string_convert... |
__all__ = ['CryptoKey']
import os, binascii
from Crypto.Hash import MD5
from Crypto.PublicKey import RSA
class CryptoKey(object):
def __init__(my):
my.key = None
my.private_key = None
my.public_key = None
def generate(my, size=1024):
my.key = RSA.generate(size, os.urandom)
... |
"""Generates an email with the National Mesonet Program contact status
Requires: iem property `nmp_monthly_email_list`
Period of performance is previous month 7th thru this month 6th
Run on the 7th from `RUN_2AM.sh`
"""
import datetime
import smtplib
from email.mime.text import MIMEText
from pandas.io.sql import r... |
__author__ = ['dmorina', 'shirish']
import uuid
from rest_framework.exceptions import AuthenticationFailed
from django.utils.translation import ugettext_lazy as _
from crowdsourcing import models
from datetime import datetime
from rest_framework import serializers
import json, hashlib, random, re
from rest_framework.... |
"""Abstract base class for things sampling quantum circuits."""
from typing import List, Optional, TYPE_CHECKING, Union
import abc
import pandas as pd
from cirq import study
if TYPE_CHECKING:
import cirq
class Sampler(metaclass=abc.ABCMeta):
"""Something capable of sampling quantum circuits. Simulator or ... |
#! /usr/bin/python3
# -- loads correctly: count=113, offsetToW=20, offsetToD=134 [20 + 113 = 133 (nextBit = offsetToD)]
from math import ceil
class Drw1Header:
size = 20
def __init__(self): # GENERATED!
pass
def LoadData(self, br):
self.tag = br.ReadFixedLengthString(4)
self... |
from odoo import models, fields, api, _
class AeatModelExportConfigLine(models.Model):
_name = 'aeat.model.export.config.line'
_order = 'sequence'
_description = 'AEAT export configuration line'
sequence = fields.Integer(string="Sequence")
export_config_id = fields.Many2one(
comodel_name=... |
class PywavefrontException(Exception):
"""Generic exception for this package to separate from common ones"""
pass |
from toscaparser.common import exception
from toscaparser.tests.base import TestCase
from toscaparser.utils.gettextutils import _
class ExceptionTest(TestCase):
def setUp(self):
super(TestCase, self).setUp()
exception.TOSCAException.set_fatal_format_exception(False)
def test_message(self):
... |
#!/usr/bin/env python3
# encoding: utf-8
from os import walk
from os import path
from setuptools import setup
from setuptools import find_packages
entry_points = {
'console_scripts': [
'folios = folios:main',
]
}
# Generate requirements
with open('requirements.txt') as fd:
requires = map(str.stri... |
"""
This scripts reads a bag file containing RGBD data, adds the corresponding
PointCloud2 messages, and saves it again into a bag file. Optional arguments
allow to select only a portion of the original bag file.
"""
import argparse
import sys
import os
if __name__ == '__main__':
# parse command line
par... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='mmeowlink',
version='0.8.5',
description='Driver layer for communicating with Medtronic pumps over a variety of radios',
packages=find_packages(),
include_package_data=True,
author='Oskar Pearson',
author_email... |
from wand.image import Image
def get_repeated_frames(input_filename):
with Image(filename=input_filename) as gif:
frames = {}
image_index = 0
images_size = len(gif.sequence) - 1
while image_index <= images_size:
current_frame = gif.sequence[image_index]
ne... |
# -*- coding: utf-8 -*-
import requests
import xmltodict
from bs4 import BeautifulSoup
#Ná í öll mál
def get_mal(session):
url = 'https://www.althingi.is/altext/xml/thingmalalisti/?lthing=' +str(session)
response = requests.get(url)
data = xmltodict.parse(response.text)
mal = []
for m in data[u'málaskrá'][u'mál'... |
# -*- coding: utf8 -*-
DEBUG = False
USE_SQLITE = False
ABAKUS_TOKEN = 'token'
try:
from .local import USE_SQLITE
except ImportError:
pass
if USE_SQLITE:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
else:
DAT... |
import unittest
from tests.fixtures import Fixture
import capnp
class SchemasTest(Fixture):
def test_load_from_file(self):
# This is just a smoking test.
with self.using_temp_file(self.compile('test-1.capnp')) as path:
with capnp.SchemaLoader() as loader:
loader.load... |
import pandas as pd
import sys
import os
from sklearn.model_selection import train_test_split
from copy_images import copy_images
PATH_TO_DATA = '.' if not len(sys.argv) == 2 else sys.argv[1]
IMG_FOLDER = '{}/IMG'.format(PATH_TO_DATA)
PATH_TO_DRIVING_LOG = '{}/driving_log.csv'.format(PATH_TO_DATA)
driving_log_df = ... |
"""SCons.Tool.nasm
Tool-specific initialization for nasm, the famous Netwide Assembler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import locale
import os
from ConfigParser import ConfigParser
from .reswork import loadResFile
class MyLocale:
def __init__(self):
"""Locale chooser for PowerOff Tool"""
self.main_dic = {'timerid1': '', 'timerid2': '', 'timespin': '', 'label1': '',
... |
import sys
import json
import calendar
from urllib2 import urlopen
from datetime import datetime, date, timedelta
from BeautifulSoup import BeautifulSoup
from dateutil.parser import parse
from icalendar import Calendar
from icalendar import Event as icalendarEvent
from optparse import make_option
from HTMLParser impor... |
from spack import *
class RNetwork(RPackage):
"""Tools to create and modify network objects. The network class can
represent a range of relational data types, and supports
arbitrary vertex/edge/graph attributes."""
homepage = "https://statnet.org"
url = "https://cran.r-project.org/src/... |
#-*- coding: utf-8 -*-
"""
#---------------------------------------------
filename: ex_runTFmatmul_placeholder.py
- Construct a computational graph which calculate
a matrix multiplication in Tensorflow
- Use tf.constant() in a matrix form
Written by Jaewook Kang
2017 Aug.
#-------------------------------... |
# -*- coding: utf-8 -*-
__author__ = 'boonya'
from flask import Blueprint
from ...utils.request import Request
from ...utils.response import Response
from ...utils.fs import Fs
from ...utils.fs.exception import NotExistsException
from .post import Post
from .post import PostSerializer
from werkzeug.exceptions import N... |
from __future__ import division
from numpy import log, zeros, float64, int32, array, sqrt, dot, diag, where
from numpy.linalg import det, norm, inv
from cogent import DNA, RNA, LoadTable
from cogent.util.progress_display import display_wrap
__author__ = "Gavin Huttley and Yicheng Zhu"
__copyright__ = "Copyright 2007-... |
#!/usr/bin/env python
"""Implementation of artifact types."""
from grr.lib import artifact_lib
from grr.lib import artifact_registry
from grr.lib import rdfvalue
from grr.lib.rdfvalues import structs
from grr.proto import artifact_pb2
from grr.proto import flows_pb2
class ArtifactCollectorFlowArgs(rdfvalue.RDFProtoS... |
"""Implements a character based lcd connected via PCF8574 on i2c."""
from lcd import LcdApi
import smbus
import time
DEFAULT_I2C_ADDR = 0x27
# Defines shifts or masks for the various LCD line attached to the PCF8574
MASK_RS = 0x01
MASK_RW = 0x02
MASK_E = 0x04
SHIFT_BACKLIGHT = 3
SHIFT_DATA = 4
class I2cLcd(LcdApi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.