content
stringlengths
4
20k
from collections import Counter class Tags(): tag_list = [] count = None table = None ndim = 0 _delim = None _col = None def __init__(self, table, col='tags', min_count=0, ban_tags=[], filter=False): count = Counter() self.table = table self._col = col self._ban_tags = ban_tags for ...
import uuid from sahara.conductor import objects from sahara import context import sahara.utils.files as files def unique_list(iterable, mapper=lambda i: i): result = [] for item in iterable: value = mapper(item) if value not in result: result.append(value) return result d...
from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.core.context_processors import csrf #from django.views.generic import ListView from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import UserProfile f...
import aurora as au import aurora.autodiff as ad import numpy as np import numpy.testing as npt from aurora.ndarray import ndarray, gpu_op def test_identity(): x2 = ad.Variable(name='x2') y = x2 grad_x2, = ad.gradients(y, [x2]) executor = ad.Executor([y, grad_x2], use_gpu=True) x2_val = 2 * np.o...
""" WSGI config for sensible_explorer project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPL...
"""Test correctness of vdW-DF potential.""" import os from math import pi from gpaw.grid_descriptor import GridDescriptor import numpy as np from gpaw.test import equal from gpaw.xc import XC from gpaw.mpi import world N = 8 a = 2.0 gd = GridDescriptor((N, N, N), (a, a, a)) # Spin paired: def paired(): xc = XC('v...
from typing import Any, Dict, List, Optional, Union, Iterable MAX_PAYLOAD_SIZE = 4096 class PayloadAlert(object): def __init__( self, title: Optional[str] = None, title_localized_key: Optional[str] = None, title_localized_args: Optional[List[str]] = None, ...
""" tests for the models """ import json from datetime import datetime, timedelta import ddt from pytz import utc from common.djangoapps.student.roles import CourseCcxCoachRole from common.djangoapps.student.tests.factories import AdminFactory from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODUL...
import bpy from bpy.types import Panel class PHYSICS_PT_rigidbody_constraint_panel: bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "physics" class PHYSICS_PT_rigid_body_constraint(PHYSICS_PT_rigidbody_constraint_panel, Panel): bl_label = "Rigid Body Constraint" @classmethod...
from netforce.model import Model, fields, get_model class PurchaseRequestLine(Model): _name = "purchase.request.line" _fields = { "request_id": fields.Many2One("purchase.request", "Purchase Request", required=True, on_delete="cascade"), "product_id": fields.Many2One("product", "Product"), ...
''' Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. ''' # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # s...
import os.path import re from threading import Lock from .LocalStatus import LocalStatusFolder try: import sqlite3 as sqlite except: pass #fail only if needed later on, not on import class LocalStatusSQLiteFolder(LocalStatusFolder): """LocalStatus backend implemented with an SQLite database As python...
from sqlalchemy import Index, MetaData, Table from oslo_log import log as logging LOG = logging.getLogger(__name__) meta = MetaData() def index_exists(index): table = index[1]._get_table() cols = sorted([str(x).split('.')[1] for x in index[1:]]) for idx in table.indexes: if sorted(idx.columns.k...
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import Asyn...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, validators from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo from flask_wtf.recaptcha import RecaptchaField from ..models import User class LoginForm(FlaskForm): email ...
from .constants.system import SYSTEM_SPECIFIC_INSTALLER from .utils import ( current_system_name, system_specific_name, ) # ========================== # UTILITIES (COMMAND STRING) # ========================== def in_nvm(command, version='node'): return '. ~/.nvm/nvm.sh && nvm use {} && ({})'.format(versi...
from code import Code from model import PropertyType import cpp_util from json_parse import OrderedDict import schema_util class _TypeDependency(object): """Contains information about a dependency a namespace has on a type: the type's model, and whether that dependency is "hard" meaning that it cannot be forward...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import re from datetime import datetime import matplotlib.pyplot as plt logfile_live = "./android-live.logcat" logfile_app = "./android-app.logcat" TIMEFORMAT = "\d{2}-\d{2} (?P<datetime>\d{2}:\d{2}:\d{2}\.\d{3})" re_keyevent = re.compile(TIMEFORMAT + ".*action=0x0, flag...
from yoda.adapter import Abstract class Bzr(Abstract): """Bzr Adapter.""" executable = "bzr" def status(self): """Show bzr status.""" return self.exec_on_path("%s status" % self.executable) def update(self): """Update repository.""" return self.exec_on_path("%s pull" ...
"""Tests for letsencrypt.acme.jose.b64.""" import unittest # https://en.wikipedia.org/wiki/Base64#Examples B64_PADDING_EXAMPLES = { 'any carnal pleasure.': ('YW55IGNhcm5hbCBwbGVhc3VyZS4', '='), 'any carnal pleasure': ('YW55IGNhcm5hbCBwbGVhc3VyZQ', '=='), 'any carnal pleasur': ('YW55IGNhcm5hbCBwbGVhc3Vy', ...
import errno import os.path import re import shutil import sys import tempfile import textwrap import unittest import pyperf from pyperf import tests from pyperf._timeit import Timer PERF_TIMEIT = (sys.executable, '-m', 'pyperf', 'timeit') # We only need a statement taking longer than 0 nanosecond FAST_BENCH_ARGS = ...
from .resource import Resource class VirtualMachine(Resource): """Describes a Virtual Machine. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resou...
from twisted.spread import flavors from twisted.python.reflect import qual class Identity(flavors.Copyable, flavors.RemoteCopy): def __init__(self, identifier): self._identifier = identifier def getStateToCopyFor(self, perspective): return {"identifier": self._identifier} def setCopyabl...
from setuptools import setup, find_packages from codecs import open from os import path __version__ = '0.0.5' here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() # get the dependen...
import numpy as np import keras as ks from keras import layers def reweight_dist(org_dist, temp=0.5): dist = np.log(org_dist) / temp dist = np.exp(dist) return dist / np.sum(dist) path = ks.utils.get_file( 'nietzsche.txt', origin='http://s3.amazonaws.com/text-datasets/nietzsche.txt') text=open(path...
''' Common functions ''' import os import sys import time import gzip import cPickle as pickle from optparse import OptionGroup from jobTree.scriptTree.target import Target from sonLib.bioio import system from sonLib.bioio import logger import aimseqtk.lib.common as libcommon import aimseqtk.lib.drawcommon as drawco...
from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from typing import List, Optional, Set from zerver.decorator import require_realm_admin, require_member_or_admin from zerver.lib.actions import do_invite_users, do_revoke_user_invite, \ do_revoke_multi_use_invite, ...
from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, InvalidPage from django.core.urlresolvers import reverse as url_reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from quest.decorators import is_snippetown...
""" Django settings for MQTT_Secure project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import o...
from flask import render_template, redirect, request, url_for, flash from flask.ext.login import login_user, logout_user, login_required, \ current_user from . import auth from .. import db from ..models import User from ..email import send_email from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\ ...
from positive_alert_test_case import PositiveAlertTestCase from negative_alert_test_case import NegativeAlertTestCase from alert_test_suite import AlertTestSuite class TestSSHLateral(AlertTestSuite): alert_filename = 'ssh_lateral' alert_classname = 'SshLateral' # This event is the default positive event...
# vim:fileencoding=utf-8:sw=4:et:syntax=python path = require("path") fs = require("fs") net = require("net") dnsproxy = require("./dns-proxy") reversesogouproxy = require("./reverse-sogou-proxy") lutils = require("./lutils") log = lutils.logger appname = "ub.uku.droxy" def load_resolv_conf(): """Parse /etc/res...
""" pyDash.py - Waits for sim to launch and then starts appropriate Dash app by Dan Allongo (<EMAIL>) Release History: 2016-06-26: Add support for Formula Truck and Copa Petrobras de Marcas 2016-05-30: Add multiple instance detection 2016-05-29: Add timestamp to each log message 2016-05-28: Clear display after exiting...
#!/usr/bin/python """ skeleton code for k-means clustering mini-project """ import pickle import numpy import matplotlib.pyplot as plt import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_n...
# -*- coding: utf-8 -*- from module.common.json_layer import json_loads from module.plugins.internal.MultiHoster import MultiHoster class SmoozedCom(MultiHoster): __name__ = "SmoozedCom" __type__ = "hoster" __version__ = "0.08" __status__ = "testing" __pattern__ = r'^unmatchable$' #: Sin...
from Tkinter import * class Chat(Toplevel): def __init__(self, root, send, title, username='me'): Toplevel.__init__(self, root) self.send = send self.root = root self.username = username self.title(title) self.frame1 = Frame(self, border=3, relief=RAISED,...
""" Unit tests for :func:`iris.fileformats.name_loaders.__calc_integration_period`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa # Import iris.tests first so that some things can be initialised before # importing anything else. ...
import json import logging import math import numpy import pytest import torch import _jsonnet from allennlp.nn import InitializerApplicator, Initializer from allennlp.nn.initializers import block_orthogonal, uniform_unit_scaling from allennlp.common.checks import ConfigurationError from allennlp.common.testing impor...
#!/usr/bin/env python import os, sys package = 'clone_github' main = 'clone_github' alias = 'clone-github' version = '0.15' target_path = '/usr/local/bin' if len(sys.argv) == 1 else sys.argv[1] print '' confirm = raw_input('Install ' + package +' (' + version + ') to \'' + target_path + '\' ? (y/n):') if confirm == ...
__author__ = "Stacy Smith" __credits__ = "Jeremy Schulman, Nitin Kumar" import unittest2 as unittest from nose.plugins.attrib import attr from jnpr.junos.facts.swver import version_info, get_facts @attr('unit') class TestVersionInfo(unittest.TestCase): def test_version_info_after_type_len_else(self): s...
""" Fixes Hardcoded tray icons in Linux. Author : Bilal Elmoussaoui (<EMAIL>) Contributors : Andreas Angerer, Joshua Fogg Website : https://github.com/bil-elmoussaoui/Hardcode-Tray Licence : The script is released under GPL, uses a modified script form Chromium project released under BSD license This file is part...
# -*- coding: utf-8 -*- from django.conf import settings import string ## set the default shorturl chars DEFAULT_SHORTURL_CHARS = string.uppercase DEFAULT_SHORTURL_CHARS += string.lowercase DEFAULT_SHORTURL_CHARS += string.digits ## allow user to configure a different chars chain SHORTIM_SHORTURL_CHARS = getattr(set...
#!/usr/bin/env python import os import unittest from mi.logging import log from mi.dataset.parser.camhd_a import CamhdAParser from mi.dataset.driver.camhd_a.resource import RESOURCE_PATH from mi.dataset.driver.camhd_a.camhd_a_telemetered_driver import parse from mi.dataset.dataset_driver import ParticleDataHandler _...
# -*- coding: utf-8 -*- """ Override sphinx_gallery's treatment of groups (folders) with cartopy's ``__tags__`` semantics. This is tightly bound to the sphinx_gallery implementation, hence the explicit version checking. This code was modified from sphinx-gallery: Copyright (c) 2015, Óscar Nájera All rights reserved. ...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 9 _modified_time = 1396982073.255995 _enable_loop = True _template_filename = 'C:\\app\\catalog\\templates/checkout.html' _template_uri = 'checkout.html' _sou...
"""Run all demos.""" # Copyright (C) 2008-2014 Ilmar Wilbers, 2016 Jan Blechta # # This file is part of FENaPack based on the file from DOLFIN. # # FENaPack is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundati...
"""Keras hashing preprocessing layer.""" # pylint: disable=g-classes-have-attributes from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import o...
''' Flask server code for production use as WSGI with Apache ''' import json import os import sys sys.path.append(os.getcwd()) from tukey_middleware.api import nova, glance, utils from flask import Flask from tukey_middleware.cloud_driver.registry import CloudRegistry from tukey_middleware.modules.instance_metadata ...
#!/usr/bin/python import argparse import os import sys from os.path import join, dirname, realpath import evdev # enable server.core imports by adding the root of the aenea project to path sys.path.append(realpath(join(dirname(__file__), '../../'))) import config from server.core import AeneaServer from evdevImpl imp...
from .utils import NamespacedClient, query_params, _make_path class ClusterClient(NamespacedClient): @query_params('level', 'local', 'master_timeout', 'timeout', 'wait_for_active_shards', 'wait_for_nodes', 'wait_for_relocating_shards', 'wait_for_status') def health(self, index=None, params=None...
### Part of this code is due to the MatConvNet team and is used to load the parameters of the pretrained VGG19 model in the notebook ### import os import sys import scipy.io import scipy.misc import matplotlib.pyplot as plt from matplotlib.pyplot import imshow from PIL import Image import numpy as np import tensorflo...
"""Setup script for Pympler. To build, install and test Pympler and to try Pympler before building and installing it. The HTML documention is in the doc/ directory. Point your browser to the ./doc/html/index.html file. """ import sys import pympler.metadata as metadata def _not_supported(why): print('NotImple...
import os import logging import numpy as np import h5py from .elem_translation import _VTK2MED, _MED2MED, _GMSH2MED _LOGGER = logging.getLogger('pyMEDio.reader') class MEDWriter(object): def __init__(self, med_file, input_format="MED"): """ MEDWriter __init__ method which create a new MED file or...
import pytest from cfme import test_requirements from cfme.configure.settings import DefaultView from cfme.services.service_catalogs import ServiceCatalogs from cfme.services.myservice import MyService from cfme.services.catalogs.catalog_item import CatalogItem from cfme.utils import testgen from cfme.utils.log impor...
import sys import traceback from vPiP.vPiP import Vpip, ConstrainDrawingRectangle from vPiP.renderers.svg import renderSVG filename = "../testImages/Vulcan.svg" with Vpip() as p: # p.setShowDrawing(True) # p.setPlotting(False) try: renderSVG(filename, 300, 200, 600, p) renderSVG(filename, 2...
#!/usr/bin/env python # import argparse, re from marsyas import * from math import sqrt from os import path ################################################################################ # Parse Command-line Arguments # parser = argparse.ArgumentParser(description='Process .wav files to estimate tuning frequency re...
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.select import Select from selenium.common.exceptions import NoSuchElementException from organization.utils.tests_front im...
#!/usr/bin/python import twitter from learning import * from time import sleep from datetime import datetime, timedelta import sys, traceback import MySQLdb as db from re import sub import ConfigParser NB = naivebayes() NB.load_brain() con = db.connect(config.get('mysql','address'), config.get('mysql','user'), ...
import time import json import requests #"eyJ1c2VyX2F1dGhlbnRpY2F0aW9uX2lkIjo0fQ:1Y2YOj:bA5J-vvdbJWRxJb4vLwdLcameU8" print time.time() def post(): data = {"username":"admin","password":"123123","type":"normal"} headers = {"Content-Type": "application/json; charset=UTF-8"} body = json.dumps(da...
""" Django forms for accounts """ from __future__ import absolute_import from django import forms from django.core.exceptions import ValidationError from openedx.core.djangoapps.user_api.accounts.utils import generate_password class RetirementQueueDeletionForm(forms.Form): """ Admin form to facilitate lear...
from utility import DBConnectivity from classes.hotel_detail import Hotel def get_hotels(location): try: con=DBConnectivity.create_connection() cur=DBConnectivity.create_cursor(con) list_of_hotels=[] cur.execute("select hotelid, hotelname, location, efare, dfare from hotel where loca...
import pandas as pd import pandas.testing as tm import pyspark import pytest import ibis import ibis.common.exceptions as com import ibis.expr.datatypes as dt import ibis.expr.types as ir from ibis.backends.spark.tests.conftest import TestConf as SparkTest from ..udf import udf pytestmark = [pytest.mark.spark, pytes...
# -*- coding: utf-8 -*- """ Website-context rendering needs to add some metadata to rendered fields, as well as render a few fields differently. Also, adds methods to convert values back to openerp models. """ import cStringIO import datetime import itertools import logging import os import urllib2 import urlparse im...
from Parser import * from Utils import * from Do import do import string from functools import reduce, partial from operator import neg, mul from AST import AST # Language whitespace spaces = many(oneof(" \n\r")) def token(p): return p << spaces def reserved(word): return token(match(word)) # Boolean literal parser ...
# -*- coding: utf-8 -*- import time from datetime import datetime, timedelta from StringIO import StringIO from django.conf import settings from django.core.handlers.modpython import ModPythonRequest from django.core.exceptions import SuspiciousOperation from django.core.handlers.wsgi import WSGIRequest, LimitedStream...
from __future__ import unicode_literals, division, absolute_import import urllib2 import time import logging from datetime import timedelta, datetime from urlparse import urlparse import requests # Allow some request objects to be imported from here instead of requests from requests import RequestException, HTTPError ...
from rest_framework import serializers from rest_framework.validators import UniqueTogetherValidator from django.contrib.auth.models import User from django.contrib.auth import get_user_model from core.models import Applications, BillingContact, Projects, ProjectUsers, STATUS_CHOICES, USER_STATUS_CHOICES UserModel = g...
''' Created on Jun 23, 2016 @author: 463188 ''' from time import mktime from dateutil import parser from ....core.BaseAgent import BaseAgent class RundeckAgent(BaseAgent): @BaseAgent.timed def process(self): self.baseLogger.info('Inside process') getProjects = self.config.get("baseEndPoint", ...
#!/usr/bin/env python3 """ This file runs the forestfire_model. """ import indra.prop_args2 as props import os MODEL_NM = "forestfire" def run(prop_dict=None): pa = props.PropArgs.create_props(MODEL_NM, prop_dict) import indra.utils as utils import models.forestfire as fm (prog_file, log_file, prop_...
from flumotion.common import componentui from flumotion.common import testsuite from flumotion.twisted.defer import defer_generator_method class FakeObject: pass class FakeAdmin(testsuite.TestAdmin): pass class FakeWorker(testsuite.TestWorker): def remote_getState(self): if not hasattr(self, ...
"""Support for hunter douglas shades.""" import asyncio import logging from aiopvapi.helpers.constants import ATTR_POSITION1, ATTR_POSITION_DATA from aiopvapi.resources.shade import ( ATTR_POSKIND1, MAX_POSITION, MIN_POSITION, factory as PvShade, ) import async_timeout from homeassistant.components.co...
""" An enumeration type used to describe the format of a given glyph image. Note that this version of FreeType only supports two image formats, even though future font drivers will be able to register their own format. FT_GLYPH_FORMAT_NONE The value 0 is reserved. FT_GLYPH_FORMAT_COMPOSITE The glyph image is a ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. module:: reader.py :platform: Unix, Windows :synopsis: Ulyxes - an open source project to drive total stations and publish observation results. GPL v2.0 license Copyright (C) 2010- Zoltan Siki <<EMAIL>> .. moduleauthor:: Zoltan...
from indico.core.db.sqlalchemy import db _reviewed_for_tracks = db.Table( 'reviewed_for_tracks', db.metadata, db.Column( 'abstract_id', db.Integer, db.ForeignKey('event_abstracts.abstracts.id'), primary_key=True, autoincrement=False, index=True ), db...
import datetime import logging import random import requests import time import re from nest.storage.luxalert.entity.Apartment import Apartment from nest.storage.luxalert.entity.ApartmentSnapshot import ApartmentSnapshot from luxweb.api_spiders.AbstractAPISpider import AbstractAPISpider class AvalonSpider(AbstractAP...
import json import six from bson.objectid import ObjectId, InvalidId from girder import logger from girder.api import access from girder.api.describe import Description, describeRoute from girder.api.rest import Resource, RestException, loadmodel from girder.constants import AccessType from girder.models.model_base im...
def first_login(): auth_set = db(db.auth_settings.user_id==auth.user.id).select(db.auth_settings.user_id, db.auth_settings.user_alias).first() if auth_set == None: # # Create table settings # import unicode...
""" KeepNote Color picker for the toolbar """ # # KeepNote # Copyright (c) 2008-2009 Matt Rasmussen # # 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; version 2 of the License. # # T...
from test import unit import unittest import mock import os import time from shutil import rmtree from hashlib import md5 from tempfile import mkdtemp from test.unit import FakeLogger from swift.obj import auditor from swift.obj.diskfile import DiskFile, write_metadata, invalidate_hash from swift.obj.server import DATA...
""" MissileV3.py By Ibrahim Sardar """ #load import pygame, random, math from FollowBlock import FollowBlock from FlameV2 import FlameV2 from Bomb import Bomb #init pygame.init() #color YELLOW = (255, 255, 0) #pics BOMB_SMALL = "Graphics\Bomb01.png" #MissileV3 class MissileV3(FollowBlock): def setUpd...
#! /usr/bin/env python # $Header$ '''Typecodes for dates and times. ''' from pysphere.ZSI import _floattypes, _inttypes, EvaluateException from pysphere.ZSI.TC import SimpleType from pysphere.ZSI.wstools.Namespaces import SCHEMA import operator, re, time as _time from time import mktime as _mktime, localtime as _local...
from __future__ import division import numpy as np # standard parameters standard_parameters = { 'practice': 0, 'nr_slow_warning': 6, 'ratio_empty_trials': 0.3, 'empty_trial_duration': 4.0, ...
from functools import wraps import logging import os import sys import types import unittest from telemetry.internal.browser import browser_finder from telemetry.internal.util import path from telemetry.testing import options_for_unittests current_browser_options = None current_browser = None class _MetaBrowserTest...
""" This example demonstrates how to make a graphical interface which contains an image plotting tab, and uses a random number generator to simulate data so that it does not require an instrument to use. Run the program by changing to the directory containing this file and calling: python image_gui.py """ ...
''' Taken from http://www.djangosnippets.org/snippets/214/ WTForm (What The Form) ====================== WTForm is an extension to the django forms library allowing the developer, in a very flexible way, to layout the form fields using <fieldset>s and columns WTForm was built with the well-documented YUI Grid CSS[1]...
from cms.toolbar_pool import toolbar_pool from cms.extensions.toolbar import ExtensionToolbar from django.utils.translation import ugettext_lazy as _ from .models import IconNameExtension, RatingExtension, SocialMediaExtension # http://docs.django-cms.org/en/support-3.1.x/how_to/extending_page_title.html#simplified-t...
""" pytelemeter parser using the data for the telemeter flash graphs """ import re import urllib import urllib2 import datetime from xml.dom import minidom from pytelemeter.parser import * # constants URL_LOGIN='https://www.telenet.be/sys/sso/signon.jsp' URL_VALIDATE='https://www.telenet.be/sys/sso/checksession.j...
""" .. module:: listener :platform: Linux :synopsis: A packet listener using raw sockets """ import netifaces import socket import time class Listener(): def __init__(self, iface): """ Initialization of the class :param iface: interface on which the packets should be sniffed ...
# markov algorithm import os import django import sys from elasticsearch import Elasticsearch pro_dir = os.getcwd() sys.path.append(pro_dir) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BioDesigner.settings") from design.models import parts def cal_probability(data_set): '''calculate transition ...
from collections import OrderedDict import astropy.coordinates as coord import astropy.units as u import matplotlib.pyplot as plt #import mpl_toolkits.basemap as bm import numpy as np import spherical_geometry.polygon as sp from astropy.table import Table import astropy.time as time from .gbm_detector import BGO0, BG...
#!/usr/bin/python """ A command line program wrapper to slimmer """ from slimmer import * from slimmer import run import CommandLineApp class slimit(CommandLineApp.CommandLineApp): """ whitespace trip HTML, XHTML, Javascript and CSS """ EXAMPLES_DESCRIPTION = """ To slim a html file: $ slimit /home...
import os import numpy as np import shutil import sys from gtrackcore.preprocess.PreProcMetaDataCollector import PreProcMetaDataCollector from gtrackcore.track.memmap.CommonMemmapFunctions import createMemmapFileFn, parseMemmapFileFn, findEmptyVal from gtrackcore.track.memmap.TrackSource import TrackSource from gtrack...
from ...requests import Session, __build__ as requests_version from ...requests.adapters import HTTPAdapter from ...requests.exceptions import RequestException try: from requests.packages.urllib3.util import Timeout TIMEOUT_ADAPTER_NEEDED = requests_version < 0x020300 except ImportError: TIMEOUT_ADAPTER_NE...
from burrito.cmdsprovider import CmdsProvider from burrito.utils import reply_to_user, prettier_date from datetime import datetime import shelve ENROUTE_CMDS = ['->', '=>'] LOCATION_CMDS = ['@'] NOLOC = ['none', 'nul', 'null', 'remove', 'nowhere', 'awesome'] class LocatorCmds(CmdsProvider): loc_file = 'location...
import numpy as np import unittest from nupic.algorithms.KNNClassifier import KNNClassifier class KNNClassifierTest(unittest.TestCase): def testSparsifyVector(self): classifier = KNNClassifier(distanceMethod="norm", distanceNorm=2.0) inputPattern = np.array([0, 1, 3, 7, 11], dtype=np.int32) # Each ...
# -*- coding: utf-8 -*- """ /*************************************************************************** Common Plugins settings NextGIS ------------------- begin : 2014-10-31 git sha : $Format:%H$ copyright : (C) 2014 by Nex...
from spack import * class FontAdobe100dpi(Package): """X.org adobe-100dpi font.""" homepage = "http://cgit.freedesktop.org/xorg/font/adobe-100dpi" url = "https://www.x.org/archive/individual/font/font-adobe-100dpi-1.0.3.tar.gz" version('1.0.3', 'ba61e7953f4f5cec5a8e69c262bbc7f9') depends_o...
from pytestqt.exceptions import capture_exceptions, format_captured_exceptions import pytest import sys @pytest.mark.parametrize('raise_error', [False, True]) def test_catch_exceptions_in_virtual_methods(testdir, raise_error): """ Catch exceptions that happen inside Qt virtual methods and make the tests f...
#coding=utf-8 ''' ÈÎÎñ Èç¹û°´ÕÕ·ÖÊý»®¶¨½á¹û£º 90·Ö»òÒÔÉÏ£ºexcellent 80·Ö»òÒÔÉÏ£ºgood 60·Ö»òÒÔÉÏ£ºpassed 60·ÖÒÔÏ£ºfailed Çë±àд³ÌÐò¸ù¾Ý·ÖÊý´òÓ¡½á¹û¡£ ''' #´úÂë score = 85 if score>=90: print 'excellent' elif score>=80: print 'good' elif score>=60: print 'passed' else: print 'faile...
import proxy.commands as commands import proxy.tokenizer as tokenizer import proxy.balance as lb import proxy.auto_config as auto_config class rwsplit_config(object): def __init__(self, value=None): if type(value) == dict: for k, v in value.items(): setattr(self, k, v) def check_rwsplit_config(fun): # He...