content
string
# -*- coding: utf-8 -*- from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.md'...
import numbers import functools from . import ifcopenshell_wrapper from .entity_instance import entity_instance class file(object): def __init__(self, f=None): self.wrapped_data = f or ifcopenshell_wrapper.file(True) def create_entity(self,type,*args,**kwargs): e = entity_instance(ifcopenshell...
from .resource import Resource class ExpressRouteCircuit(Resource): """ExpressRouteCircuit resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type:...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Broadcast radiation levels to Twitter. Require the twython packages: https://github.com/ryanmcgrath/twython You'll also need a Twitter application credentials: https://apps.twitter.com Released under MIT License. See LICENSE file. By Yoan Tournade <<EMAIL>> "...
from solumclient.openstack.common.apiclient import exceptions from solumclient.openstack.common.apiclient import fake_client from solumclient.tests import base from solumclient.v1 import client as sclient from solumclient.v1 import component component_list = [ { 'uri': 'http://example.com/v1/components/c1...
# Say that two strings s_1 and s_2 can be merged into a third # string s_3 if s_3 is obtained from s_1 by inserting # arbitrarily in s_1 the characters in s_2, respecting their # order. For instance, the two strings ab and cd can be merged # into abcd, or cabd, or cdab, or acbd, or acdb..., but not into # adbc nor into...
from a10sdk.common.A10BaseClass import A10BaseClass class Debug(A10BaseClass): """ :param info: {"default": 0, "optional": true, "type": "number", "description": "Information component", "format": "flag"} :param daemon: {"default": 0, "optional": true, "type": "number", "description": "Daemon componen...
import uuid from flask import Flask, request from flask_sqlalchemy import SQLAlchemy from flump import FlumpView, FlumpBlueprint, OrmIntegration, Fetcher from marshmallow import fields, Schema from werkzeug.exceptions import Unauthorized from werkzeug.security import generate_password_hash, check_password_hash # Crea...
"""Utilities to find and use cocotb""" """ Changes: 09/08/2013: Initial Commit """ __author__ = '<EMAIL> (Dave McCoy)' import os #DEFAULT_POSIX_COCOTB = "/usr/local" DEFAULT_POSIX_COCOTB = "/home/cospan/Projects" DEFAULT_WINDOWS_COCOTB = "C:\\Program Files\\" class CocotbWarning(Exception): pass class Coc...
from horizon import tables as horizon_tables from horizon import tabs as horizon_tabs from dlux.api import get_client from dlux.dashboards.network.nodes import tables from dlux.dashboards.network.nodes import tabs class IndexView(horizon_tables.DataTableView): template_name = "network/nodes/index.html" table...
from test_base import BaseTestCase from search_rex.recommendations.data_model.case_based import\ InMemoryQueryDataModel from search_rex.recommendations.data_model.case_based import\ PersistentQueryDataModel from search_rex.recommendations.neighbourhood.case_based import\ ThresholdQueryNeighbourhood from sea...
from config import * class Keyboard: def __init__(self): self.keys = None self.left = pygame.K_LEFT self.right = pygame.K_RIGHT self.jump = pygame.K_UP self.hit_left = pygame.K_a self.hit_right = pygame.K_d self.hit_up = pygame.K_w if GCW_ZERO: ...
# standard libraries import os import abc import collections import copy import io import gzip import mimetypes import datetime # third party libraries import numpy import werkzeug # first party libraries from . import (surly, utils, headers, cookies, ) __where__ = os.path.dirname(os.path.abspath(__file__)) mimetyp...
""" Creating and plotting unstructured triangular grids. """ import matplotlib.pyplot as plt import matplotlib.tri as tri import numpy as np import math # Creating a Triangulation without specifying the triangles results in the # Delaunay triangulation of the points. # First create the x and y coordinates of the poin...
""" A script to plot signals """ import sys import os import getopt import json import matplotlib.pyplot as plt CMD_USAGE = """ """ MAX_PLOT_SIZE = 5000 def plot_signal(signal): with open(signal, "rb") as json_file: json_data = json.load(json_file) beacons = json_data['interestedBeacons'] ...
__author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith' from handler.BaseHandler import * class LoginHandler(BaseHandler): def __init__(self, request=None, response=None): super(LoginHandler, self).__init__() self.initialize(request, response) self.page_name = "login" def get(self)...
from django.core.exceptions import ValidationError from django.db import models from django.db.models import Sum from django.db.models import DateField, TimeField, CharField, PositiveSmallIntegerField from django.db.models import ManyToManyField, ForeignKey, OneToOneField, DateTimeField, TextField from django.utils.tra...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import requests import json import jwt import time if len(sys.argv) < 2: print "ファイル名が指定されていません" sys.exit(1) time.sleep(5) # 画像ファイルが出来上がるまで、5秒待つ # 引数から画像ファイルをオープン image = open(sys.argv[1], 'rb') # Endorse Tokenの取得 print "- SORACOM Endorse にアクセスして token...
# -*- coding: utf-8 -*- """ sphinx.builders.manpage ~~~~~~~~~~~~~~~~~~~~~~~ Manual pages builder. :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ from os import path from six import string_types from docutils.io import FileOutput from ...
from calvin.actor.actor import Actor, ActionResult, manage, condition, guard from calvin.runtime.north.calvin_token import EOSToken, ExceptionToken class FileNotFoundHandler(Actor): """ Scan tokens for Exceptions other than EOS. Any non-exception or EOS is simply passed on. Exceptions are replaced with ...
from slacker import Slacker from datetime import date import requests import keys import re calendar_api = "https://www.googleapis.com/calendar/v3/calendars/g.rit.edu_61hmcjev3u2m4q98ooa5h1v5sk%40group." \ "calendar.google.com/events?alwaysIncludeEmail=false&maxResults=1&orderBy=startTime&showDeleted=fa...
"""filterbyreceipt.py - read in a bufr file, copy a subset of bufr data with receipt time later than specified time to a new file. version 1.0: Jeff Whitaker 20190811 """ from __future__ import print_function import ncepbufr, sys, os, argparse import numpy as np # Parse command line args ap = argparse.ArgumentParser(...
from .settings_saver import save as settings_save, load as settings_load from .connections import Connection from keyring import set_password, get_password import string import random KEY = 'connections' SECRET_FIELDS = ['remote_password', 'mysql_password'] KEYRING_SYSTEM_NAME = 'pysql_browser' def save(connections)...
import time from typing import TYPE_CHECKING, Dict, Any from azure.core.pipeline.policies import SansIOHTTPPolicy from ._generated import ContainerRegistry from ._helpers import _parse_challenge, _parse_exp_time from ._user_agent import USER_AGENT if TYPE_CHECKING: from azure.core.credentials import TokenCredent...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys # import os from pymongo.errors import ConnectionFailure from pymongo import Connection # from ConfigParser import SafeConfigParser #from pymongo.son_manipulator import AutoReference,NamespaceInjector #from pymongo.code import Code #config stuff host= "localhos...
from .sub_resource import SubResource class ApplicationGatewayFrontendIPConfiguration(SubResource): """Frontend IP configuration of an application gateway. :param id: Resource ID. :type id: str :param private_ip_address: PrivateIPAddress of the network interface IP Configuration. :type priva...
from setuptools import setup, find_packages version = open('pyopenapi/VERSION', 'r').readline().strip() setup( name = 'pyopenapi', packages = find_packages(exclude=['*.tests.*']), version = version, description = 'Library for developing backward-compatible tools on OpenAPI', author = 'Mission Liao...
import sys import os from time import sleep files = sys.argv[1] # read in a string of file names seperated by ", " # e.g. "Default_Protein_Report.txt, Default_Protein_Report_2.txt" #bait = sys.argv[2] # SAINT formatted bait file # still need a way to match files to bait identifiers # or they can just be required to be...
# -*- coding: utf-8 -*- from __future__ import with_statement import os import time from module.plugins.internal.Plugin import Plugin from module.plugins.internal.misc import encode class Captcha(Plugin): __name__ = "Captcha" __type__ = "captcha" __version__ = "0.52" __status__ = "stable" ...
# -*- coding: cp1252 -*- cadena = 'oaxaca' comp = 'oaxaccra' coincide = '' minimo_coinc = 85 if cadena == comp: print 'OK' else: start = 0 end = 1 needle = list(cadena)[0] while end < len(cadena) and start < len(cadena): print '\nAvanza caracter' end = 1 while comp.find(nee...
from __future__ import with_statement from weboob.tools.browser import BrowserUnavailable from weboob.capabilities.dating import Optimization from weboob.capabilities.contact import QueryError from weboob.tools.log import getLogger __all__ = ['QueriesQueue'] class QueriesQueue(Optimization): def __init__(self,...
#!/usr/bin/env python ''' Exercise 8 - Class 8 - Thread connection to each device and run the command Gleydson Mazioli <<EMAIL>> ''' from net_system.models import NetworkDevice import netmiko import django import time from multiprocessing import Process, Queue def get_cred_type(l_credentials, l_type): ''' Get...
from datetime import date from django import forms from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from profile.models import AbstractAvatarProfile, AbstractProfileBase, \ AbstractLocationProfile, AbstractContactProfile, \ AbstractPersonalProfile, AbstractSub...
#!/usr/bin/env python """view.py: Reversi Game User Interface Code. This program provides several classes related to reversi game user interface. It uses Tkinter module to provide the graphical view of the game and capture the user button-press or key-press events. The program also communicates with "model.py"...
""" TrackingHistogramWidget :Authors: Berend Klein Haneveld """ from PySide.QtGui import * from PySide.QtCore import * from HistogramWidget import HistogramWidget from TrackingNodeItem import TrackingNodeItem from ui.widgets import Style class TrackingHistogramWidget(HistogramWidget): """ TrackingHistogramWidget ...
from game import falldown import Q_network import numpy as np from keras.optimizers import Adam import os.path # initialize the neural network if os.path.isfile("model.h5"): model = Q_network.construct_model() model.load_weights("model.h5") adam = Adam(lr=1e-6) model.compile(loss='mse', optimizer=adam)...
import random from collections import defaultdict from graph_diff.nirvana_object_model.workflow import Workflow from .standard_workflow_generator import StandardWorkflowGenerator from .workflow_generator import WorkflowGenerator class SimilarWorkflowGenerator(WorkflowGenerator): """Class that generates workflow ...
import argparse, os, sys, getpass, base64, shutil from encryptRSA import * from decryptRSA import * from encryptDecryptFile import * from hashbrown import * from encodeDecode import * from rand import * parser = argparse.ArgumentParser(description = "Implementation of Pycrypt0_v1 package") parser.add_argument...
""" start tunneled remote server for selected package Usage: python tunneled_pathos_server.py [hostname] [server] [hostname] - name of the host on which to run the server [server] - name of the RPC server (assumed to be already installed) """ from pathos.core import * from pathos.hosts import get_profile, re...
from setuptools import setup, find_packages import os from os.path import dirname, realpath from taggit_templatetags2 import __version__ as VERSION __dir__ = realpath(dirname(__file__)) TESTS_REQUIRE = ['tox >= 1.7'] setup( name='django-taggit-templatetags2', version=".".join([str(v) for v in VERSION]), ...
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('marking', '0001_initial'), ('grades', '0001_initial'), ('coredata', '0001_initial'), ('groups', '0001_initial'), ] operations = [ migration...
from setuptools import setup, find_packages classifiers = """\ Development Status :: 2 - Pre-Alpha License :: OSI Approved :: GNU General Public License (GPL) Intended Audience :: Developers Intended Audience :: End Users/Desktop Intended Audience :: Science/Research Topic :: Scientific/Engineering :: Artificial Intel...
class Changer (object): """ Data descriptor that allows you to have a value that executes a function or function-like object (i.e. a signal) whenever it is modified. The function object will be called with two parameters, the first one being the object whose this descriptor belongs to, and then ...
# -*- coding: utf-8 from yade import ymport,utils,pack,export,qt,bodiesHandling import gts,os # for plotting from math import * from yade import plot ############################ ### DEFINING PARAMETERS ### ############################ #GEOMETRIC :dimension of the rectangular box a=.2 # side dimension h=.1 # he...
""" =================================== Column Transformer with Mixed Types =================================== .. currentmodule:: sklearn This example illustrates how to apply different preprocessing and feature extraction pipelines to different subsets of features, using :class:`~compose.ColumnTransformer`. This is...
""" A location for various structs/class bases """ class Singleton(type): """ A basic singleton to be used as a metaclass Credit goes to: http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python Used as a metaclass, not a base class: class MyClass(object): __metacl...
""" :mod:`defines` --- Constants ============================ Contains constant definitions used throughout the codebase. """ # Stdlib import os #: SCION protocol version SCION_PROTO_VERSION = 0 #: Max TTL of a PathSegment in realtime seconds. # TODO(shitz): This value should be externally configurable. The problem i...
''' anitya tests for the custom backend. ''' import unittest import anitya.lib.backends.github as backend import anitya.lib.model as model from anitya.lib.exceptions import AnityaPluginException from anitya.tests.base import Modeltests, create_distro, skip_jenkins BACKEND = 'GitHub' class GithubBackendtests(Model...
#!/usr/bin/env python """ Author: Henrik Kentsson (<EMAIL>, @Kentsson) Python 2.7.4 UNIX_DES_encrypter A UNIX password encryption tool with DES Username can be 32 characters maximum and A-Z, a-z. Allowed characters in password : ./ 0-9 A-Z a-z Only two characters allowed in salt. Windows requires https://code.googl...
from django.test import TestCase from login.models import Users from login.models import User_Profiles from login import oauth from login import auth from login import google import random import string class UUIDTestCase(TestCase): def pesudo_random_string_generator(self): return ''.join(random.SystemRand...
import logging, os, re from autotest_lib.client.common_lib import error import kvm_subprocess, kvm_utils, rss_file_transfer def run_whql_submission(test, params, env): """ WHQL submission test: 1) Log into the client machines and into a DTM server machine 2) Copy the automation program binary (dsso_te...
from typing import List from datetime import datetime import regex from recognizers_text import RegExpUtility from ..base_merged import BaseMergedExtractor from ..utilities import DateTimeOptions, ExtractResult from .merged_extractor_config import ChineseMergedExtractorConfiguration class ChineseMergedExtractor(Base...
# -*- coding: utf-8 -*- __copyright__ = """ Copyright (C) 2007, Karl Hasselström <<EMAIL>> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it ...
import os from string import Template exec(open(os.path.join( os.environ['OPENSHIFT_REPO_DIR'], 'openshift', 'virtualenv.py' )).read()) def application(environ, start_response): ctype = 'text/html' response_body = Template('''<!doctype html> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" c...
import config import re import conn_handle import db_handle import urllib.request import urllib.error import json import main def points_add(user, channel, messageList, response): isMod = re.search(r"(mod=)(.*?);",response).group(2) # grabs for mod status from raw message if isMod == "1": main.chat("Points were ad...
import logging import os import threading import requests from giftwrap.gerrit import GerritReview from stevedore.driver import DriverManager from stevedore.extension import ExtensionManager from abc import abstractmethod, ABCMeta BUILDER_DRIVER_NAMESPACE = 'giftwrap.builder.drivers' LOG = logging.getLogger(__name_...
from unittest import TestCase from identityprovider.templatetags.google_analytics import expand_ga_commands from identityprovider.templatetags.static_url import static_url from identityprovider.tests.utils import patch_settings SNIPPETS = [ None, '', 'not valid json' '"); alert("gotcha!"); //' '\...
import json from typing import Dict import cherrypy from girder.api.rest import Resource from girder.exceptions import RestException class IsicResource(Resource): def _decodeParams(self, params: Dict) -> Dict: """ Decode POSTed or PUTed JSON parameters. Supports either "application/x-ww...
from gnuradio import gr, gr_unittest import ofdm_swig as ofdm class qa_suppress_erasure_decision (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): # set up fg self.tb.run () # check data ...
# -*- coding: utf-8 -*- import os import sys import xbmc import xbmcaddon if sys.version_info >= (2, 7): import json else: import simplejson as json # Import the common settings from resources.lib.settings import log ADDON = xbmcaddon.Addon(id='screensaver.weather') CWD = ADDON.getAddonInfo('p...
""" I am the support module for creating mail servers with twistd """ import os import warnings from twisted.mail import mail from twisted.mail import maildir from twisted.mail import relay from twisted.mail import relaymanager from twisted.mail import alias from twisted.internet import endpoints from twisted.pytho...
def extractLightNovelswithMisachan(item): """ 'Light Novels with Misa-chan~' """ if item['title'].startswith("Protected:"): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title...
import os import unittest from netjsonconfig import OpenWrt from netjsonconfig.exceptions import ParseError from netjsonconfig.utils import _TabsMixin class TestParser(unittest.TestCase, _TabsMixin): maxDiff = None _system_uci = """package system config system system option custom_setting 1 option ...
# -*coding: utf-8-*- from ...models import DBSession from ...models.resource import Resource from ...models.employee import Employee from ...models.subaccount import Subaccount from ...lib.factories import SubaccountFactory class EmployeeSubaccountFactory(SubaccountFactory): @classmethod def query_list(cls)...
#!/usr/bin/env python import vtk, numpy, os from pymicro.crystal.microstructure import Orientation, Grain from pymicro.crystal.texture import PoleFigure from pymicro.view.scene3d import Scene3D from pymicro.view.vtk_utils import pole_figure_3d, axes_actor, setup_camera ''' Create a 3d scene with a cubic crystal lattic...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fileencoding=utf-8 """Calculate basic statistics on the RESULTS.node.score.csv output file from quartet_sampling """ import os import sys import argparse import numpy as np LICENSE = """ This file is part of 'quartetsampling'. 'quartetsampling' is free ...
"""RegionControllerProcess object.""" from django.db.models import CASCADE, ForeignKey, IntegerField from maasserver import DefaultMeta from maasserver.models.cleansave import CleanSave from maasserver.models.node import Node from maasserver.models.timestampedmodel import TimestampedModel class RegionControllerPro...
import json from django.db import models from django.contrib.auth import authenticate from django.contrib.sites.models import Site import allauth.app_settings from allauth.account import app_settings as account_settings from allauth.utils import (get_login_redirect_url, valid_email_or_none)...
# Exercise 36: Designing and Debugging # Rules for If-Statements: # 1. Every 'if-statement' must have an 'else' # 2. If this 'else' should never run, beause it doesn't make sense, # then you must use a 'die' function in the 'else' that prints out an # error message and dies, just like we did in the last exercise. This...
import xmlrpclib # Launch import from 7.0 db = 'Barc' server = 'localhost' user = 'admin' password = 'admin' port = 8069 sock = xmlrpclib.ServerProxy( 'http://%s:%s/xmlrpc/common' % ( server, port, ), allow_none=True) uid = sock.login( db, user, password, )...
from questionanswering import bidictionnary from numpy import arange def process(question, query_builder): mapped_question = next(question) if ('inflation' in mapped_question) and ('rate' in mapped_question): inflation_rate = extract_inflation_rate(mapped_question) if ('between' in mapped_quest...
from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext.db import Model as DBModel from datetime import datetime from demisaucepy.django_helper import AggregatorMeta from demisaucepy.declarative import has_a, has_many, \ aggregator_callable, make_declarative from demisa...
import matplotlib if __name__ == '__main__': matplotlib.use('Agg') import numpy as np import pylab as plt import sys import fitsio from astrometry.util.plotutils import * from astrometry.util.fits import * ps = PlotSequence('rchi') def rchi_sim(): # simulations -- what is the false positive rate for the rch...
from __future__ import absolute_import, unicode_literals import gyp import gyp.msvs_emulation import sys import os import time import types import mozpack.path as mozpath from mozpack.files import FileFinder from .sandbox import alphabetical_sorted from .context import ( ObjDirPath, SourcePath, TemplateCon...
from optparse import make_option from django.core import exceptions from django.core.management import call_command from django.core.management.base import BaseCommand from django.utils.encoding import force_str from django.utils.six.moves import input from django.db.utils import IntegrityError from django_tenants.util...
from django.conf import settings from django.utils.translation import ugettext_lazy as _ import re TEMPLATES = getattr(settings, 'PAGES_TEMPLATES', (("page.html", _("Base template")),)) COLUMN_DEFAULT_VIEW = getattr(settings, 'COLUMN_DEFAULT_VIEW', 'xadrpy.contrib.entries.views.column') #DEFAULT_TEMPLATE = getattr(set...
import binascii import json import os from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.x509.oid import NameOID import pem import pytest from testtools.assertions import assert_that from testtools.matchers import ( AfterPreprocessing as After, Equals, Is, I...
from .charsetgroupprober import CharSetGroupProber from .hebrewprober import HebrewProber from .langbulgarianmodel import (ISO_8859_5_BULGARIAN_MODEL, WINDOWS_1251_BULGARIAN_MODEL) from .langgreekmodel import ISO_8859_7_GREEK_MODEL, WINDOWS_1253_GREEK_MODEL from .langhebrewmodel im...
"""script that converts a .po file to a UTF-8 encoded .dtd file as used by mozilla either done using a template or just using the .po file""" import warnings from translate.storage import dtd from translate.storage import po from translate.misc import quote from translate.convert import accesskey def getmixedentiti...
class ManagedObjectRepo(object): """Stores and manages KMIP managed objects. The KMIP specification details the managed objects that are stored by a KMIP server. This repository abstraction is an interface for KMIP servers to store managed objects. """ def __init__(self): pass def...
import os import sys import cgi import cgitb cgitb.enable() print '''Content-type: text/html <html> <head> </head> <body> test </body> '''
"""Controllers for the Oppia collection learner view.""" from core.controllers import base from core.domain import collection_services from core.domain import config_domain from core.domain import rights_manager from core.domain import summary_services from core.platform import models import feconf import utils (user...
""" Examples to demonstrate ops level randomization CS 20: "TensorFlow for Deep Learning Research" cs20.stanford.edu Chip Huyen (<EMAIL>) Lecture 05 """ import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf # Example 1: session keeps track of the random state c = tf.random_uniform([], -10, 10, seed...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models import signals import pyconde.accounts.utils as account_utils class SpeakerManager(models.Manager): use_for_related_fi...
from . import invoice from . import wizard from . import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import heap_sort import unittest class tc1 (unittest.TestCase): def test_already_max_heap(self): self.array = [3,2,1] self.assertEqual(heap_sort.max_heapify(self.array,0),self.array) def test_not_max_heap_before(self): self.array = [1,2,3] self.assertEqual(heap_sort.max_heapify...
from __future__ import unicode_literals import datetime from django import template from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware, utc, localtime from django.utils.translation import ugettext, ungettext_lazy register = template.Library() @register.filter def daysince(d, no...
#Stack using Linked List class Node(object): """docstring for Node""" def __init__(self, data): self.data = data self.next = None class Stack(object): """docstring for Stack""" def __init__(self, head=None): self.head = head def peek(self): if self.head != None: return self.head.data else: return...
import datetime import urllib2, urllib, json from flask import render_template from emonitor.widget.monitorwidget import MonitorWidget from emonitor.extensions import babel from emonitor.modules.settings.settings import Settings import logging import traceback __all__ = ['WeatherWidget'] babel.gettext('Mon') babel.ge...
""" Test the lldb disassemble command on each call frame when stopped on C's ctor. """ import os, time import unittest2 import lldb from lldbtest import * import lldbutil class IterateFrameAndDisassembleTestCase(TestBase): mydir = os.path.join("lang", "cpp", "class_types") failing_compilers = ['clang', 'gcc'...
import logging from odoo import api, fields, models, tools from odoo.http import request from odoo.addons.website.models import ir_http _logger = logging.getLogger(__name__) class Website(models.Model): _inherit = 'website' pricelist_id = fields.Many2one('product.pricelist', compute='_compute_pricelist_id...
import uuid import httpretty from django.urls import reverse from oscar.core.loading import get_model from ecommerce.extensions.test import factories from ecommerce.programs.benefits import PercentageDiscountBenefitWithoutRange from ecommerce.programs.custom import class_path from ecommerce.programs.tests.mixins impo...
try: from urllib.parse import quote, unquote except ImportError: from urllib import quote, unquote import pytest from multidimensional_urlencode import urlencode def test_basic(): """Verify that urlencode works with four levels.""" d = {"a": {"b": {"c": "d"}}} expected = quote("a[b][c]=d", safe...
from flask import Flask, request from twilio import twiml import json app = Flask(__name__) @app.route("/voice", methods=['GET', 'POST']) def call(): """Responds to incoming calls using Twilio Add-ons""" # Start our TwiML response response = twiml.Response() # Decode the JSON included in the 'AddOn...
""" Example how to spline B-spline to fake data. :requires: Python 2.5 or later (no 3.x compatible) :requires: NumPy :requires: SciPy TESTED: Python 2.5.1 NumPy: 1.4.0.dev7576 SciPy: 0.7.1 matplotlib 1.0.svn HISTORY: Created on November 26, 2009 :version: 0.1: test release (SMN) :author: Sami-Matias Niemi :contact...
"""Tests Hamming metrics.""" import numpy as np import tensorflow as tf from tensorflow.keras import layers from tensorflow_addons.metrics import HammingLoss, hamming_distance def test_config(): hl_obj = HammingLoss(mode="multilabel", threshold=0.8) assert hl_obj.name == "hamming_loss" assert hl_obj.dty...
{ 'name': 'Transportation', 'version': '0.1', 'category': 'Customer Relationship Management', 'description': """ Transportation ============== This module allows to add : * transportation notebook Contributors ------------ * Sandy Carter (<EMAIL>) * El Hadji Dem (<EMAIL>) """, 'author': "Savoir...
# 各組分別在各自的 .py 程式中建立應用程式 (第1步/總共3步) from flask import Blueprint, render_template # 利用 Blueprint建立 ag1, 並且 url 前綴為 /ag1, 並設定 template 存放目錄 scrum3_task40323222 = Blueprint('scrum3_task40323222', __name__, url_prefix='/bg10', template_folder='templates') # scrum1_task1 為完整可以單獨執行的繪圖程式 @scrum3_task40323222.route('/scrum3_...
from django.contrib.auth import get_user_model from django.urls import reverse from django.utils import timezone from ...test.ion_test import IonTestCase from ...utils.date import get_senior_graduation_year from ..announcements.models import Announcement from ..eighth.models import EighthActivity from ..events.models ...
import sys import numpy as np from OpenGL.GL import * #from OpenGL.raw.GL.ARB.vertex_array_object import glGenVertexArrays,glBindVertexArray from OpenGL.GL.shaders import * class JuMEG_TSV_OGL_VBO(object): """ Helper class for using GLSL shader programs """ def __init__(self): s...