content string |
|---|
#!/usr/bin/env python
"""
This module prints three FedEx Express shipping labels for the label
certification process. See your FedEx Label Developer Tool Kit documentation
for more details.
"""
import logging
from cert_config import CONFIG_OBJ, SHIPPER_CONTACT_INFO, SHIPPER_ADDRESS, LABEL_SPECIFICATION
from cert_confi... |
import pygame
from core import prepare
from core.components.menu import Menu
class HpBar(object):
def __init__(self, screen, monster=None, x=0, y=0,
width=48, height=3, color=(112,248,168),
bar_position=(16,2), image="resources/gfx/ui/monster/hp_bar.png"):
self.screen =... |
"""The test for the Template sensor platform."""
import blumate.components.sensor as sensor
from tests.common import get_test_home_assistant
class TestTemplateSensor:
"""Test the Template sensor."""
def setup_method(self, method):
"""Setup things to be run when tests are started."""
self.has... |
import basicKVstore as t
from os import makedirs, path
from shutil import rmtree
def prep_folder(conf=False):
"""prepare a temporary folder
conf: is it a configuration folder ? else it is just a normal folder
"""
try:
rmtree('/tmp/test')
except:
pass
if conf:
makedirs('... |
"""
This is a Pure Python module to hyphenate text.
It is inspired by Ruby's Text::Hyphen, but currently reads standard *.dic files,
that must be installed separately.
In the future it's maybe nice if dictionaries could be distributed together with
this module, in a slightly prepared form, like in Ruby's Text::Hyphe... |
import unittest
import numpy as np
from op_test import OpTest
class TestAccuracyOp(OpTest):
def setUp(self):
self.op_type = "accuracy"
n = 8192
infer = np.random.random((n, 1)).astype("float32")
indices = np.random.randint(0, 2, (n, 1))
label = np.random.randint(0, 2, (n, 1... |
"""
An example of an XML-RPC server in Twisted.
Usage:
$ python xmlrpc.py
An example session (assuming the server is running):
>>> import xmlrpclib
>>> s = xmlrpclib.Server('http://localhost:7080/')
>>> s.echo("lala")
['lala']
>>> s.echo("lala", 1)
['lala', 1]
>>> s.echo("lala", 4)
... |
#!/usr/bin/env python
import os
import rdflib
import sulu
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestSerializeRdf(unittest.TestCase):
def setUp(self):
self.update_graph = rdflib.Graph().parse('test/update.rdf')
self.signing_rdf = open('test/signing.txt'... |
"""Awx helper module."""
from tower_cli.conf import settings
from . import __name__ as __awx_name__
from .base import LoggerMixin
from .commands.ad_hoc import AwxAdHoc
from .commands.config import AwxConfig
from .commands.credential import AwxCredential
from .commands.group import AwxGroup
from .commands.host import A... |
# -*- coding: utf-8 -*-
import os, re,sys
import subprocess
import time, os, sched,shlex,threading
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics import renderPDF
def now_time():
localtim... |
#!/usr/bin/env python
"""Base test classes for API renderers tests."""
import abc
import json
import os
import urlparse
from grr import gui
from grr.gui import api_auth_manager
from grr.gui import api_call_renderers
from grr.gui import http_api
from grr.lib import test_lib
from grr.lib import utils
DOCUMENT_ROOT ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
with open('otwrapy/__init__.py') as fid:
for line in fid:
if line.startswith('__version__'):
version = line.strip().split()[-1][... |
from rest_framework import serializers
from data_models.models import Article, ArticleVersion, Category, Member
class ArticleVersionSerializer(serializers.HyperlinkedModelSerializer):
diff = serializers.JSONField()
class Meta:
model = ArticleVersion
fields = ('id', 'url', 'content', 'access'... |
#!/usr/local/bin/python
"""
## QUEUE USING STACK and STACK USING QUEUE
QUEUE using a stack
+ Implement queue algorithm using 2 stacks and implement a queue class
with test inputs.
STACK using a queue
+ Implement stack algorithm using 2 queues and implement a stack class
with test inputs.
STACK ... |
import os
import sys
import re
from datetime import date
sys.path.append(os.path.abspath('.'))
sys.path.append(os.path.abspath('..'))
os.environ['DJANGO_SETTINGS_MODULE'] = 'gstudiodocs_settings'
import gstudio
# -- General configuration -----------------------------------------------------
# If your documentation ... |
import platform
import sys
import warnings
try:
# Use setuptools if available, for install_requires (among other things).
import setuptools
from setuptools import setup
except ImportError:
setuptools = None
from distutils.core import setup
from distutils.core import Extension
# The following code... |
import datetime
from django.conf import settings
from django.contrib.sites.models import get_current_site
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.http import HttpResponse, Http404
from django.template import loader, Template, TemplateDoesNotExist, RequestContext
from djan... |
# -*- coding: utf-8 -*-
"""
jbmst_search_jsp.py
Created on 2013/06/28
Copyright (C) 2011-2013 Nippon Telegraph and Telephone Corporation
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:/... |
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import (
BooleanField, CharField, ChoiceField, DateField, DateTimeField,
DecimalField, EmailField, FileField, FloatField, Form,
GenericIPAddressField, IntegerField, ModelChoiceField,
ModelMultipleChoiceField, MultipleChoiceF... |
from __future__ import absolute_import
import json
import logging
import datetime as dt
import calendar
import decimal
import numpy as np
try:
import pandas as pd
is_pandas = True
except ImportError:
is_pandas = False
try:
from dateutil.relativedelta import relativedelta
is_dateutil = True
excep... |
# -*- coding: utf-8 -*-
from datetime import datetime
from django.db import models
from sigi.apps.casas.models import CasaLegislativa
from sigi.apps.utils import SearchField
from sigi.apps.utils.email import enviar_email
from eav.models import BaseChoice, BaseEntity, BaseSchema, BaseAttribute
class Diagnostico(BaseE... |
from nose.tools import *
from libpepper.pepperoptions import PepperOptions
from libpepper.usererrorexception import PepUserErrorException
@raises( PepUserErrorException )
def test_no_args():
PepperOptions( [ "progname" ] )
def test_one_arg():
opts = PepperOptions( [ "progname", "infile.pepper" ] )
asse... |
"""Implementation of compile_html based on odfpy.
You will need, of course, to install odfpy
"""
import os
import io
import shutil
import lxml.etree as etree
from nikola.plugin_categories import PageCompiler
from nikola.utils import makedirs, req_missing
try:
from odf.odf2xhtml import ODF2XHTML
except ImportE... |
import xml.etree.ElementTree as et
import logging
class Feedback():
"""Feeback used by Alfred Script Filter
Usage:
fb = Feedback()
fb.add_item('Hello', 'World')
fb.add_item('Foo', 'Bar')
print fb
"""
def __init__(self):
self.feedback = et.Element('items')
... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Assemble.py
# Prepares Arrows Plus to be distributed by packaging the mod
# archive and source archives.
#
# This file, both in source code form or as a compiled binary, is free and
# released into the public domai... |
from . import process_grammar
class TryStatement:
"""Process a 'try' statement in the stage packages grammar.
For example:
>>> import tempfile
>>> from snapcraft import repo, ProjectOptions
>>> with tempfile.TemporaryDirectory() as cache_dir:
... repo_instance = repo.Repo(cache_dir)
.... |
from array import array
from collections import namedtuple
from .usb_ids import FAUX_MFR, FAKE_VDR, SCALE, OTHER
MockEndpoint = namedtuple(
"MockEndpoint", ["bEndpointAddress", "wMaxPacketSize"]
)
class MockCtx(object):
"""Simulates the _ctx property expected by usb.util.dispose_resources"""
def dispose(... |
from __future__ import absolute_import
from bgpfu.irr import IRRBase
from bgpfu.prefixlist import SimplePrefixList as PrefixList
from bgpfu.io import select, socket, Queue, Empty
import gevent
import logging
from pkg_resources import get_distribution
import re
class IRRClient(IRRBase):
"""
IRR client, uses p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from translate.storage import qm, test_base
class TestQtUnit(test_base.TestTranslationUnit):
UnitClass = qm.qmunit
class TestQtFile(test_base.TestTranslationStore):
StoreClass = qm.qmfile
def test_parse(self):
# self.reparse relies o... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
# Is this a triangle题目地址:https://www.codewars.com/kata/56606694ec01347ce800001b/train/python
'''
import unittest
class TestCases(unittest.TestCase):
def test1(self):self.assertEqual(is_triangle(1, 2, 2), True, "didn't work when sides were 1, 2, 2")
def test2(self... |
#!/usr/bin/python
import os, sys
sys.path.append(os.path.join(os.getcwd(), "soccer_night"))
import soccer_night
from getpass import getpass
def main():
if os.path.isfile("config.json"):
import simplejson as json
config = json.loads(open("config.json").read())
id = config['id']
pvp ... |
#!/usr/bin/env python
# coding=utf-8
#
##############################################################################
### NZBGET POST-PROCESSING SCRIPT ###
# Post-Process to Mylar.
#
# This script sends the download to your automated media management servers.
#
# NOTE: This scr... |
""" Generate a GeoJSON of 7 AM precip data """
import datetime
import json
import memcache
import psycopg2.extras
import pytz
from paste.request import parse_formvars
from pyiem.reference import TRACE_VALUE
from pyiem.util import get_dbconn, html_escape
def p(val, precision=2):
"""see if we can round values bett... |
from texttable import Texttable
from ussclicore.argumentParser import ArgumentParser, ArgumentParserError
from ussclicore.cmd import Cmd, CoreGlobal
from ussclicore.utils import generics_utils, printer, progressbar_widget, download_utils
from hammr.utils import *
from uforge.objects.uforge import *
from hammr.utils.ham... |
import numpy as np
import requests
import pandas as pd
import plotly.graph_objects as go
from IPython.display import Markdown, display
def getFeatures(X, cmap):
return pd.DataFrame(X).replace(cmap).values.squeeze().tolist()
def predict(X, name, ds, svc_hostname, cluster_ip):
formData = {
'instances'... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class AppendRow(Choreography):
def __init__(self, temboo_session):
"""
Create a new... |
#!/usr/bin/python3
# Unit-tests for simple fixed-point Python module
# RW Penney, January 2006
import math, sys, unittest
sys.path.insert(0, '..')
from FixedPoint import FXfamily, FXnum, \
FXoverflowError, FXdomainError, FXfamilyError
class FixedPointTest(unittest.TestCase):
def setUp(self):
pass... |
import os
def test_list_command(script, data):
"""
Test default behavior of list command.
"""
script.pip(
'install', '-f', data.find_links, '--no-index', 'simple==1.0',
'simple2==3.0',
)
result = script.pip('list')
assert 'simple (1.0)' in result.stdout, str(result)
as... |
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
class EvernoteWindow(QtGui.QMainWindow):
def __init__(self,url="https://evernote.com/"):
"""
Initialize a Window with the Evernote log in screen
"""
QtGui.QMainWindow.__init__(self)
self.resize(500,500)
self.... |
"""
Resource class and its manager for hypervisors in Compute API v2
"""
from osclient2 import base
from osclient2 import mapper
from osclient2 import utils
ATTRIBUTE_MAPPING = [
('id', 'id', mapper.Noop),
('hostname', 'hypervisor_hostname', mapper.Noop),
('type', 'hypervisor_type', mapper.Noop),
('v... |
#-*- coding: utf8
from __future__ import division, print_function
from aflux import dataio
from _inter import gibbs
from collections import OrderedDict
def fit(trace_fpath, num_topics, alpha_zh, beta_zs, beta_zd, num_iter, \
burn_in):
'''
Learns the latent topics from a hypergraph trace.
Parame... |
from org.o3project.odenos.remoteobject.manager.component.event.component_changed\
import ComponentChanged
import unittest
class ComponentChangedTest(unittest.TestCase):
Prev_ObjectProperty = {"id": "Prev",
"super_type": "Network",
"type": "Network",
... |
from ..helpers.command import Command
from random import choice
@Command(['wai', 'why'])
def cmd(send, *_):
"""Gives a reason for something.
Syntax: {command}
"""
a = ["primary", "secondary", "tertiary", "hydraulic", "compressed",
"required", "pseudo", "intangible", "flux"]
b = ["compress... |
"""Script to test TF-TRT INT8 conversion without calibration on Mnist model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.compiler.tf2tensorrt.wrap_py_utils import get_linked_tensorrt_version
from tensorflow.compiler.tf2tensorrt.wrap_p... |
import os
from datetime import datetime, date, timedelta
from csv import DictReader
import re
import ftplib
import tempfile
from gips.core import SpatialExtent, TemporalExtent
from gips.data.core import Repository, Data
import gips.data.core
from gips.utils import settings, List2File
from gips import utils
from gipp... |
import copy
import locale
import logging
import re
import reportlab
import sys
if 'openerp-server' in sys.modules['__main__'].__file__:
from tools.safe_eval import safe_eval as eval
from tools import ustr
else:
def ustr(value):
if isinstance(value, unicode):
return value
if no... |
#!/usr/bin/env python
"""----------------------------------------------------------------------------
gsat.py:
Copyright (C) 2013-2020 Wilhelm Duembeg
This file is part of gsat. gsat is a cross-platform GCODE debug/step for
Grbl like GCODE interpreters. With features similar to software debuggers.
Feat... |
# -*- coding: utf-8 -*-
from distutils.core import setup
from setuptools import find_packages
setup(
name='django-versatileimagefield',
packages=find_packages(),
version='2.1',
author=u'Jonathan Ellenberger',
author_email='<EMAIL>',
url='http://github.com/respondcreate/django-versatileimagefiel... |
'''
@author: Yetian
'''
import os
import tempfile
import uuid
import time
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstacklib.utils.ssh as ssh
import zstackwoodpecker.operations.scenario_operations a... |
from datetime import date, timedelta
from dateutil.easter import easter
from dateutil.relativedelta import relativedelta as rd, SA, FR, MO
from holidays.constants import JAN, FEB, MAR, MAY, JUN, JUL, AUG, SEP, OCT, \
NOV, DEC
from holidays.constants import SUN
from holidays.holiday_base import HolidayBase
class... |
"""
A tool for identifying griefers.
.. note::
"blockinfo" must be AFTER "votekick" in the config script list
Commands
^^^^^^^^
* ``/griefcheck or /gc <player> <minutes>`` gives you when, how many and whos blocks a player destroyed *admin only*
Options
^^^^^^^
.. code-block:: guess
[blockinfo]
griefcheck_... |
import os
import sys
import logging
import openerp
import openerp.netsvc as netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID
from openerp im... |
"""
Tests for the Feature Provider
"""
import numpy as np
import os
import sys
import unittest
import warnings
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
sys.path.insert(0, path)
import senses.dataproviders.featureprovider as fp # pylint: disable=locally-disabled, import-error
class TestFeat... |
"""Models for manifest validator."""
import importlib
import json
import pathlib
from typing import Any, Dict, List, Optional
import attr
@attr.s
class Error:
"""Error validating an integration."""
plugin: str = attr.ib()
error: str = attr.ib()
fixable: bool = attr.ib(default=False)
def __str__... |
from __future__ import absolute_import
import inspect
import warnings
class RemovedInDjango20Warning(PendingDeprecationWarning):
pass
class RemovedInNextVersionWarning(DeprecationWarning):
pass
class warn_about_renamed_method(object):
def __init__(self, class_name, old_method_name, new... |
from __future__ import unicode_literals
from django.db.models import Manager, Q
from django.db.models.query import QuerySet
_TOOL_CACHE = {}
class ToolQuerySet(QuerySet):
def get(self, *args, **kwargs):
pk = kwargs.get('id__exact', None)
if pk is None:
return super(ToolQuerySet, se... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
from loguru import logger
import unittest
import os.path as op
import pytest
path_to_script = op.dirname(op.abspath(__file__))
import sys
sys.path.insert(0, op.abspath(op.join(path_to_script, "../../io3d")))
sys.path.insert(0, op.abspath(op.join(path_to_script, "../../imm... |
"""
This modules provides classes for evaluating distributions based on a fixed
set of points
"""
import logging
import numpy
import numpy.random
from pycbc import VARARGS_DELIM
class FixedSamples(object):
"""
A distribution consisting of a collection of a large number of fixed points.
Only these values ca... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsRasterFileWriter.
.. 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; either version 2 of the License, or
(at your option) any later version.
"... |
"""The tests for Alarm control panel device actions."""
import pytest
from homeassistant.components.alarm_control_panel import DOMAIN
import homeassistant.components.automation as automation
from homeassistant.const import (
CONF_PLATFORM,
STATE_ALARM_ARMED_AWAY,
STATE_ALARM_ARMED_HOME,
STATE_ALARM_ARM... |
# --------------- 1. Explicit Logging
def info(msg):
print("INFO - {}".format(msg))
# some business logic with logging
def do_something1(n):
info("do_something1 called with: n={}".format(n))
return n + 1
# --------------- 2 a) Logging with self-made decorator
def with_logging1(fun):
def wrapper(... |
import os
from flask import Flask, redirect, render_template_string, request, url_for
from flask_babel import Babel
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_user import confirm_email_required, current_user, login_required, UserManager, UserMixin, SQLAlchemyAdapter
# Use a Class-ba... |
#coding: latin-1
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
)
class ThisAVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?thisav\.com/video/(?P<id>[0-9]+)/.*'
_TEST = {
u"url": u"http://www.thisav.com/video/47734/%98%26sup1%3B%83%9E%83%82---just-fit.html... |
# py file to hold general math functions
# Contributors: Sushant Dinesh [:sushant94]
#
# Returns an array of upto 10^5 Continued fraction coeffs
def computeContinuedFractions(a, b):
cFracs = []
for i in range(10000):
n = a / b
r = a - (b * n)
a, b = b, r
cFracs.append(n)
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
TauDEMAlgorithm.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*********... |
import CommonWindow
import GameCheck
import GemRB
import GUICommonWindows
import GUISAVE
import GUIOPTControls
from GUIDefines import *
###################################################
GameOptionsWindow = None # not in PST
HelpTextArea = None
LoadMsgWindow = None
QuitMsgWindow = None
if GameCheck.IsBG1():
HelpTe... |
# -*- coding: utf-8 -*-
"""
oss2.xml_utils
~~~~~~~~~~~~~~
XML处理相关。
主要包括两类接口:
- parse_开头的函数:用来解析服务器端返回的XML
- to_开头的函数:用来生成发往服务器端的XML
"""
import xml.etree.ElementTree as ElementTree
from .models import (SimplifiedObjectInfo,
SimplifiedBucketInfo,
PartInfo,
... |
# 20171025 Init
import acm
import ael
ael_variables = [['asofdate', 'Date', 'string', [str(ael.date_today()), 'Today'], 'Today', 1, 0, 'Report Date', None, 1], \
['acq', 'Acquirer(s)', 'string', HTI_Util.getAllAcquirers(), 'HTIFS - EDD,HTISEC - EDD', 1, 1, 'Acquirer(s)', None, 1], \
['prd', 'Product Type(s)', ... |
import time
from gaiatest import GaiaTestCase
class TestVideoPlayer(GaiaTestCase):
# Video list/summary view
_video_items_locator = ('css selector', 'ul#thumbnails li[data-name]')
_video_name_locator = ('css selector', 'p.name')
# Video player fullscreen
_video_frame_locator = ('id', 'videoFram... |
import datetime
import sys
import os
__author__ = 'desmat'
class Logger(object):
def __init__(self, path = None):
"""Provide a simple, custom, logging capability for the toad pipeline.
The purpose of this class is to provide a simple, custom, logging capability for the toad
pipeline. Tha... |
"""Lithium's "crashesat" interestingness test to assess whether a binary crashes with a possibly-desired signature on
the stack.
Not merged into Lithium as it still relies on grab_crash_log.
"""
import argparse
import logging
from pathlib import Path
import lithium.interestingness.timed_run as timedrun
from lithium.... |
from socketio import has_bin
from socketio.event_emitter import EventEmitter
import socketio.parser as Parser
import logging
logger = logging.getLogger(__name__)
internal_events = {'connect', 'connect_error', 'connect_timeout', 'disconnect', 'error', 'reconnect',
'reconnect_attempt', 'reconnect_fai... |
"""Function validity module not meant for user access
Quantmod functions have checks against these sets below to guard
against bad input.
"""
# flake8: noqa
# Mandatory dict names for skeleton structure
VALID_BASE_COMPONENTS = {'base_colors', 'base_traces',
'base_additions', 'base_layout',}
... |
from utils.functions.models import GradeQtd
from utils.functions import arg_def
def sortimento(cursor, **kwargs):
def argdef(arg, default):
return arg_def(kwargs, arg, default)
pedido = argdef('pedido', None)
tipo_sort = argdef('tipo_sort', 'rc')
descr_sort = argdef('descr_sort', True)
m... |
# coding=utf-8
import unittest
"""174. Dungeon Game
https://leetcode.com/problems/dungeon-game/description/
The demons had captured the princess ( **P** ) and imprisoned her in the
bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out
in a 2D grid. Our valiant knight ( **K** ) was initially p... |
"""Unit tests for the text module."""
import io
import sys
import types
import typing
import unittest
from unittest import mock
from absl.testing import parameterized
import colorama
import openhtf
from openhtf.core import measurements
from openhtf.core import phase_descriptor
from openhtf.core import phase_executor
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Abinit Post Process Application
author: Martin Alexandre
last edited: May 2013
"""
import sys,os,commands
import string, math, shutil
from scipy.io import netcdf
import numpy as np
class writeHIST:
def __init__(self,pfile,pname,pni,pnf):
self.namefile = ... |
# feedback on the End User’s use of the Software (e.g., any bugs in
# the Software, the user experience, etc.). Harvard is permitted to
# use such information provided by End User in making changes and
# improvements to the Software without compensation or an accounting
# to End User.
#
# 6. NON ASSERT. End User ackn... |
import argparse
import multiprocessing
import subprocess
import sys
import threading
PASS_COLOR = '\033[92m'
FAIL_COLOR = '\033[31m'
ENDC_COLOR = '\033[0m'
class Task:
def __init__(self, name, cmd):
self.name = name
self.cmd = cmd
self.success = False
self.output = ""
def run_test... |
import http.client as http
import json
from urllib.parse import urlparse
from urllib.parse import urlencode
from base64 import b64encode
import hashlib
import socket
import shutil
import os
import binascii
import logging
from enum import Enum
logger = logging.getLogger('urbackup-server-python-api-wrapper')
... |
from myhdl import *
import numpy as np
from math import e, pi, log
import matplotlib.pyplot as plt
t_state = enum('INIT', 'DATA_IN', 'COMPUTE', 'COMPUTE_INDEX', 'COMPUTE_MULT', 'DATA_OUT')
#########################CHANGES NEEDED IF N!=8###############################
def FFT(clk, reset, start, data_valid,
... |
# encoding: utf-8
"""
Autocall capabilities for IPython.core.
Authors:
* Brian Granger
* Fernando Perez
* Thomas Kluyver
Notes
-----
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD... |
from __future__ import unicode_literals
from ironblogger.app import db
from ironblogger.tasks import import_bloggers, export_bloggers
from ironblogger.model import Blogger
from ironblogger.date import now
from six.moves import StringIO
from datetime import datetime
from random import Random
from tests.util import fresh... |
from __future__ import absolute_import, division, unicode_literals
from xml.sax.xmlreader import AttributesNSImpl
from ..constants import adjustForeignAttributes, unadjustForeignAttributes
prefix_mapping = {}
for prefix, localName, namespace in adjustForeignAttributes.values():
if prefix is not None:
... |
from datetime import date, datetime, timedelta
from couchforms.models import XFormInstance
from custom.opm.opm_reports.constants import CFU2_XMLNS, CHILDREN_FORMS, BIRTH_PREP_XMLNS, CFU1_XMLNS
from custom.opm.opm_reports.tests.case_reports import OPMCaseReportTestBase, OPMCase, MockCaseRow, \
get_relative_edd_from_... |
from Csmake.CsmakeModule import CsmakeModule
from CsmakeProviders.SwiftProvider import SwiftProvider
import os
import os.path
import fnmatch
import threading
import datetime
import swiftclient.exceptions
class SwiftPullArtefact(CsmakeModule):
"""Purpose: Pull an artefact from a swift container
Type: Module... |
import os
import sys
import time
from hashlib import md5
from buildbot.util import unicode2bytes
def tryserver(config):
jobdir = os.path.expanduser(config["jobdir"])
job = sys.stdin.read()
# now do a 'safecat'-style write to jobdir/tmp, then move atomically to
# jobdir/new . Rather than come up with ... |
from Monument import Monument, Dataset
import importer_utils as utils
import importer as importer
class PaEs(Monument):
def set_adm_location(self):
"""Set the Admin Location, using iso code of Province."""
self.set_from_dict_match(
lookup_dict=self.data_files["provinces"],
... |
# coding=utf-8
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from django.db.models.base import Model
from django.db.models.fields import CharField, TextField, DateTimeField, BooleanField, FloatField
from django.db.models.fields.related import ForeignKey
class Bas... |
import unittest
import logging
import os
import asyncio
import sqlite3
from hbmqtt.plugins.manager import BaseContext
from hbmqtt.plugins.persistence import SQLitePlugin
formatter = "[%(asctime)s] %(name)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
logging.basicConfig(level=logging.DEBUG, format=formatter)... |
import numpy as np
from scipy.stats import sem
import scipy.constants as const
from uncertainties import ufloat
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from PIL import Image
import... |
#!/usr/bin/env python
# encoding: utf-8
"""
This is a rather generic interface for building a settings view
from a GSettingsSchema, which is (usually) defined as XML File.
For shredder this file is `org.gnome.Shredder.gschema.xml` and contains a
description of all keys used by Shredder. Keys are typed in GSettings, ... |
# -*- coding: utf-8 -*-
"""
author : wanghe
company: LogInsight
email_ : <EMAIL>
file: user.py
time : 16/4/15 下午8:44
"""
from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.db import models
import warnings
from django.utils.translation import ugettext_lazy as _
from django.utils import ... |
import datetime
from django.db import models
from django.utils import timezone
from django import forms
from time import time
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', default=timezone.now())
def __unicode__(self): ... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import hashlib
import logging
from shadowsocks import common
from shadowsocks.obfsplugin import plain, http_simple, obfs_tls, verify, auth, auth_chain, simple_obfs_http, simple_obfs_tls
method_supported = {}
... |
#! /usr/bin/env python
import subprocess
import sys, threading, Queue
import os
import string
from time import gmtime, strftime
import urllib2
import urllib
import re, time
import optparse
from itertools import groupby
from operator import itemgetter
import urlparse
import os.path
#import extract
import imapfile
impo... |
#! /usr/bin/python3
'''
See: /usr/local/lib/python3.7/dist-packages/evdev/ecodes.py
Keys are defined here:
/usr/include/linux/input-event-codes.h
'''
import evdev
import threading
import sys
import time
class KDirect():
shift = False
ctrl = False
shift_keys = {'KEYS_CAPSLOCK': False} # create shift_k... |
# -*- coding:utf-8 -*-
from math import floor
class SuccesiveInterval(object):
"""Container that store values linked to closely wraped interval
One value is asigned to each interval.
the end of one interval is begining of the following one.
Therefore only one number is needed to indicate the end of an interval.
... |
"""
Copyright © Helicon Tech. All rights reserved.
Модуль, заведующий всеми общесистемными настройками. Все пути, константы и пр. должны быть заданы тут.
"""
import os
import os.path
import platform
import yaml
import logging
from new_core.version import VERSION
# главный фид, он не появляется в настрофках в морде... |
# -*- coding: utf-8 -*-
import os.path
import shlex
import sys
import unittest
import pycodestyle
from testsuite.support import ROOT_DIR, PseudoFile
E11 = os.path.join(ROOT_DIR, 'testsuite', 'E11.py')
class DummyChecker(object):
def __init__(self, tree, filename):
pass
def run(self):
if Fal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.