content
stringlengths
4
20k
from abc import ABCMeta, abstractmethod class URLsQueryDriver(object, metaclass=ABCMeta): """Relatively abstract class for URLs querying, useful when support for other drivers is added""" @abstractmethod def query_urls( self, exclude=None, include=None, versioned=None, ...
import numpy as np from PIL import Image import h5py import random as rng import matplotlib.pyplot as plt from PIL import ExifTags import scipy.misc class Patcher(): def __init__(self, _img_arr, _lbl_arr, _dim, _stride=(4,4), _patches=None, _labels=None): self.img_arr = _img_arr if _lb...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from gaebusiness.business import CommandExecutionException from tekton.gae.middleware.json_middleware import JsonResponse from gaepermission.decorator import login_required from jogo_app import jogo_facade from arcos import Autor from gaeg...
from SimpleCV.base import * from SimpleCV.ImageClass import Image, ImageSet from SimpleCV.DrawingLayer import * from SimpleCV.Features import FeatureExtractorBase """ This class is encapsulates almost everything needed to train, test, and deploy a multiclass support vector machine for an image classifier. Training data...
from __future__ import absolute_import from django.forms import CheckboxSelectMultiple, IntegerField, ValidationError from django.utils.encoding import force_text from bitfield.types import BitHandler class BitFieldCheckboxSelectMultiple(CheckboxSelectMultiple): def render(self, name, value, attrs=None, choice...
# -*- coding: utf-8 -*- from django.test import TestCase from accounts.models import User from dailyreport.models import Daily, Comment # 6 tests class CommentModelsTest(TestCase): def create_comment(self, username='', password='', title='', comment=''): user = User(username=username) user.set_pa...
import inspect from unittest import mock import tooz.coordination import tooz.locking from cinder import coordination from cinder.tests.unit import test class Locked(Exception): pass class MockToozLock(tooz.locking.Lock): active_locks = set() def acquire(self, blocking=True): if self.name not...
# -*- coding: utf-8 -*- ''' Created on Jul 11, 2013 @author: Carl, Aaron ''' import os import subprocess import web, config from logger import MBLogger from mb.config import DB_INITED ''' 创建/连接数据库对象: db = web.database(dbn='mysql', user='user', pw='pass', db='dbname') 查询: users = db.query('select * from user where ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from lxml import etree raiz = etree.parse('./mondial-3.0.xml').getroot() encontrado = False while not encontrado: paispedido = raw_input('Dime un país: ') for pais in raiz.iter('country'): if pais.attrib['name'].lower() == paispedido.lower(): ...
import urllib,re,sys,os import xbmc, xbmcgui, xbmcaddon, xbmcplugin from resources.libs import main #Mash Up - by Mash2k3 2012. addon_id = 'plugin.video.movie25' selfAddon = xbmcaddon.Addon(id=addon_id) art = main.art prettyName = 'Sceper' def MAINSCEPER(): main.GA("Plugin","Sceper") main.addDir('Sea...
""" This is where the ManifestView class is stored and all related variables. """ import json from django.views.generic import TemplateView from data_services.manifestPreproc import manifest_preprocessor from django.shortcuts import get_object_or_404 from data_services.models import DimRun from django.http import Http...
from .parse_defines import parse_defines from .parse_selectors import parse_selectors from .parse_properties import parse_properties from .strip_comments import strip_comments from .ParseFile import * from .ParseError import * import pgmapcss.renderer import copy from pkg_resources import * import pgmapcss.defaults de...
## Automatically adapted for scipy Oct 21, 2005 by convertcode.py import scipy.special from numpy import logical_and, asarray, pi, zeros_like, \ piecewise, array, arctan2, tan, zeros, arange, floor from numpy.core.umath import sqrt, exp, greater, less, cos, add, sin, \ less_equal, greater_equal from spline i...
# -*- coding: latin-1 -*- "HTML Renderer for FPDF.py" __author__ = "Mariano Reingart <<EMAIL>>" __copyright__ = "Copyright (C) 2010 Mariano Reingart" __license__ = "LGPL 3.0" # Inspired by tuto5.py and several examples from fpdf.org, html2fpdf, etc. from .fpdf import FPDF from .py3k import PY3K, basestring, unicode...
"""Tests for learning.genomics.deepvariant.modeling.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys if 'google' in sys.modules and 'google.protobuf' not in sys.modules: del sys.modules['google'] from absl.testing import absltest from abs...
import os from unittest import TestCase, main, skip from datetime import datetime from pybook import Book from pybook import BookConfig from pybook.utils import BookError file_path = os.path.dirname(__file__) test_path = os.path.join(file_path, 'example') class BookConfigTest(TestCase): def setUp(self): ...
""" The Wave Protocol Loose XMPP wrapper around operations and their events. """ import xmpp from pyofwave.core import opdev, operation class WaveProtocol(xmpp.ServerCore): def __init__(self, stream): self.events = None super(WaveProtocol, self).__init__(stream, jid="serverjid") # XXX: hardcoded J...
import os import numpy as np from mock import patch, MagicMock from matplotlib.colors import ColorConverter from glue import custom_viewer from glue.core import HubListener, Application, Data, DataCollection from glue.core.message import SettingsChangeMessage from qtpy import QtWidgets from glue.app.qt.preferences im...
"""Etcd Transport module for Kombu. It uses Etcd as a store to transport messages in Queues It uses python-etcd for talking to Etcd's HTTP API Features ======== * Type: Virtual * Supports Direct: *Unreviewed* * Supports Topic: *Unreviewed* * Supports Fanout: *Unreviewed* * Supports Priority: *Unreviewed* * Supports ...
# deceleration_init.py - sets up the IronPython environment ready for scripting # the deceleration control software. import clr import sys from System.IO import Path # Import the edm control software assemblies into IronPython sys.path.append(Path.GetFullPath("..\\ScanMaster\\bin\\Debug\\")) clr.AddReferenceToFile("S...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import re import argparse import getpass def prepare_config(dns_names=[]): with open("/etc/ssl/openssl.cnf", 'r') as openssl_config: config = openssl_config.read() lines = config.splitlines() req_regex = re.compile('\s*\[\s*req\s*\]\s*') fo...
import tests import gtk import pango from zim.notebook import Path from zim.notebook.index import Index from zim.notebook.index.tags import MyTreeIter, IS_PAGE, IS_TAG from zim.gui.pageindex import FGCOLOR_COL, \ EMPTY_COL, NAME_COL, PATH_COL, STYLE_COL # Explicitly don't import * from pageindex, make clear what we...
import urllib2, cookielib, ClientForm import re import time from cStringIO import StringIO class Browser() : def __init__(self): self.html='' self.silent=False self.view='view.html' #private self._currentUrl='' self._redir=r'<body onload="document\..*...
from socket import * from json import * from Test import Test test = Test() s1 = socket(AF_INET, SOCK_STREAM) s1.connect(("0.0.0.0", 20000)) data = test.send(s1, '{"op":"start","params":["single","None","None"]}') data = loads(data) gameid = data['gameid'] print gameid test.send(s1, '{"op":"play","params":["setde...
#!/usr/bin/env python """Data store proxy for a data server.""" import base64 import functools import os import threading import time import uuid import logging from grr.lib import access_control from grr.lib import config_lib from grr.lib import data_store from grr.lib import utils from grr.lib.data_stores import...
"""Everything needed for being able to create a virtual filesystem.""" import typing from abc import ABC, abstractmethod, abstractproperty from pathlib import Path from operating_system import FakeOperatingSystem, FakeUnix, FakeWindows from fakeuser import FakeUser, Root class FakeFileLikeObject(ABC): """I am wh...
from __future__ import absolute_import import gobject from solfege import abstract from solfege import gu from solfege import lessonfile from solfege import mpd from solfege import soundcard from solfege import statistics from solfege import statisticsviewer from solfege.specialwidgets import QuestionNameButtonTable,...
import sys import os import logging import pwd import grp import datetime import click from flask import Flask import time import psutil import sqlalchemy import subprocess import daemon import daemon.pidfile import models # set up logging start_time = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f%z') logger ...
#!/bin/env python from distutils.core import setup from distutils.command.install_data import install_data from distutils.command.install import INSTALL_SCHEMES import os import sys class osx_install_data(install_data): def finalize_options(self): self.set_undefined_options('install', ('install_lib', 'ins...
import tarfile from gzip import GzipFile from subprocess import call from boto import connect_s3 from ConfigParser import SafeConfigParser, RawConfigParser from datetime import datetime from optparse import OptionParser import os from os.path import expanduser from os import unlink, fdopen from psycopg2 import connect...
import unittest from fmrest.record import Record class RecordTestCase(unittest.TestCase): """Record test suite""" def setUp(self) -> None: pass def test_key_value_mismatch_handling(self) -> None: """Test that Record cannot be initialized with a key-value length mismatch.""" with se...
"""Start Home Assistant.""" from __future__ import annotations import argparse import os import platform import subprocess import sys import threading from homeassistant.const import REQUIRED_PYTHON_VER, RESTART_EXIT_CODE, __version__ def validate_python() -> None: """Validate that the right Python version is r...
from pymel.all import * import maya.cmds as cmds SCENE_FILE_NAME_REGEX = r'[a-z]{2}[A-Z]{1}[a-zA-Z]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}' SCENE_FILE_TOP_NODE_REGEX = r'([a-z]{2}[A-Z]{1}[a-zA-Z]+[A-Z]{1})(_)' def get_top_node(show_warnings=False): def warning(str): if show_warnings: cmds.warning(str...
import sys import os from Algorithmia.errors import AlgorithmException # look in ../ BEFORE trying to import Algorithmia. If you append to the # you will load the version installed on the computer. sys.path = ['../'] + sys.path import unittest import Algorithmia class AlgoTest(unittest.TestCase): def setUp(self...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging import sys from contextlib import closing, contextmanager import pytest import py from pytest_catchlog.common import catching_logs # Let the fixtures be discoverable by pytest. from pytest_catchlog.fixture import...
#DEPRECATED def general(sentence = "header", accuracy = 4, dictionary = {}): #USES ALL WORDS feature_prefix = "all" if sentence == "header": #output header @ATTRIBUTE line return [feature_prefix+"-"+str(accuracy)+"-"+str(room) for room in range(accuracy+1)] else: #create dictionary of features for the given s...
import six import warnings from murano.dsl import exceptions from murano.tests.unit.dsl.foundation import object_model as om from murano.tests.unit.dsl.foundation import test_case class TestFindClass(test_case.DslTestCase): def setUp(self): super(TestFindClass, self).setUp() self._runner = self....
# project/models.py import datetime from project import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String, unique=True, nullable=False) password = db.Column(db.String, nullable=False) registered_on = db.Column(db....
""" Kmeans clustering algorithm for colour detection in images Initialise a kmeans object and then use the run() method. Several debugging methods are available which can help to show you the results of the algorithm. """ import Image import random import numpy class Cluster(object): def __init__(self): ...
"""Invenio Circulation base transitions.""" import copy from datetime import datetime import arrow from flask import current_app, has_request_context from invenio_db import db from ..api import Loan, is_item_available_for_checkout from ..errors import DocumentDoNotMatchError, DocumentNotAvailableError, \ Invalid...
""" Please refer to top-level LICENSE file for copyright information """ import logging import time from src.libs.testFramework import classicTest logging.basicConfig(level=logging.INFO) log = logging.getLogger('SerialTest') class ParallelTest(classicTest.TestInstance): def __init__(self, sleep=0): sup...
""" this file is the test module for the log module """ from logging import CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARNING from easywall.log import Log from easywall.utility import delete_file_if_exists from tests import unittest class TestLog(unittest.TestCase): """ this class contains all test functions for...
import pytest import numpy as np import nnabla.functions as F from nbla_test_utils import list_context, function_tester ctxs = list_context('MulN') def ref_function(*inputs, **params): y = 1 for i in range(len(inputs)): y *= inputs[i] return y @pytest.mark.parametrize("ctx, func_name", ctxs) @p...
try: import httplib # Python 2 except ImportError: import http.client as httplib # Python 3 try: from urllib import urlencode # Python 2 except ImportError: from urllib.parse import urlencode # Python 3 import json from flask.ext.babel import gettext from config import MS_TRANSLATOR_CLIENT_ID, MS_TR...
# encoding: utf-8 import 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 'Feed.owner' db.alter_column('planet_feed', 'owner_id', self.gf('django.db.models.fields....
import socket checkhost = "google.com" checkport = 80 class Discoverable(): ''' discover local host listening on giver port ''' def get_local_ip_address(): ''' Returns the ip address running the python interpreter ''' # connecting to a UDP address doesn't send packets s = socket.socket(soc...
import random import math import numpy as np from operator import itemgetter class Dataset(object): def __init__(self,id,x,y,meta={}): self.id=id self.x=x self.y=y self.meta=meta def classes(self): return max(self.y)+1 def remove_classes_with_few_examples(self,min_...
import csv import logging import time from bccf.models import Event from django.shortcuts import redirect log = logging.getLogger(__name__) from django.http import HttpResponse, Http404 from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.decorators import login_required from formable.build...
from __future__ import print_function from os import path from io import open as io_open # Allow for environments without setuptools try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages # ...
from spack import * class Sabre(MakefilePackage): """Sabre is a tool that will demultiplex barcoded reads into separate files. It will work on both single-end and paired-end data in fastq format. It simply compares the provided barcodes with each read and separates the read into its appropria...
from shapely import geometry import ConfigParser import zmq from threading import Thread, Event from navitiacommon import type_pb2, request_pb2, models import glob from jormungandr.singleton import singleton import logging from jormungandr.protobuf_to_dict import protobuf_to_dict from jormungandr.exceptions import ApiN...
r"""Evaluation on per-frame labels for few-shot classification. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl import flags from absl import logging import concurrent.futures as cf import numpy as np import scipy.stats as st import tensorfl...
""" wldownload -- CLI to download and mangle remote wordlists. """ from __future__ import unicode_literals, print_function import argparse import logging import os import sys from diceware_list import __version__ from diceware_list.libwordlist import AndroidWordList, logger try: BrokenPipeError is not None # Pyth...
import logging from quepy import settings from quepy.encodingpolicy import assert_valid_encoding logger = logging.getLogger("quepy.tagger") PENN_TAGSET = set(u"$ `` '' ( ) , -- . : CC CD DT EX FW IN JJ JJR JJS LS MD " "NN NNP NNPS NNS PDT POS PRP PRP$ RB RBR RBS RP SYM TO UH " "VB V...
import sys # ETS imports from traits.etsconfig.api import ETSConfig def _init_toolkit(): """ Initialise the current toolkit. """ # Force Traits to decide on its toolkit if it hasn't already from traitsui.toolkit import toolkit as traits_toolkit traits_toolkit() # Import the selected backend...
#!/usr/bin/env python import random import sys def main(): with open('/tmp/randy.log', 'w') as logfile: log = lambda line: logfile.write(line + '\n') for _ in range(201): id_line = sys.stdin.readline().rstrip().split(' ') assert id_line[0] == 'Y' my_id = id_lin...
import logging import pyrat import numpy as np from osgeo import gdal from osgeo.gdalconst import * from osgeo import gdal_array class TSX(pyrat.LayerWorker): def __init__(self, filename=None, *args, **kwargs): self.ds = gdal.Open(filename, GA_ReadOnly) if self.ds is None: logging.erro...
#!/usr/bin/env python from Queue import Queue import subprocess, threading, time import os, os.path import MySQLdb import shutil import cStringIO import fileinput ms_dbname = "" ms_dbhost = "" ms_dbuser = "" ms_password = "" noOfEasy, noOfMed, noOfHard = 0, 0, 0 ptsEasy, ptsMed, ptsHard = 0, 0, 0 noOfInThreads, noOf...
""" It's possible to throttle the number of requests sent to Bambu API by using or defining a request logger. These loggers take note of the numbers of requests within a given timeframe by a specific app, and validate incoming requests against that value. """ from django.utils.timezone import get_current_timezone, now...
from odoo import models, fields, api, _ class HrSocialMedia(models.Model): _name = 'hr.social.media' _description = 'HR Social Media' name = fields.Char( required=True, ) social_url = fields.Char( string='Website', ) class HrSocialMediaAccount(models.Model): _name = 'hr....
""" Expect Series 0 0 1 1 2 2 3 3 4 4 Name: new_series, dtype: int64 """ import numpy as np import pandas as pd from numba import njit @njit def series_rename(): s = pd.Series(np.arange(5)) s.rename("new_series") return s print(series_rename())
"""Test configs for transpose_conv.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf from tensorflow.lite.testing.zip_test_utils import create_tensor_data from tensorflow.lite.testing.zip_test_utils impo...
#coding utf8 # ------------------------------------------------------------------------------ import os import sys import errno import logging import contextlib import paramiko # pip install paramiko # ------------------------------------------------------------------------------ class SFTPSession(object): # ------...
import netaddr import six from nova.compute import api as compute from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from paxes_nova.scheduler import filters LOG = logging.getLogger(__name__) class AffinityFilter(filters.BaseHostFilter): def __init__(self): ...
import json from corehq import toggles from corehq.apps.commtrack.models import CommtrackConfig from corehq.apps.commtrack.views import BaseCommTrackManageView from corehq.apps.domain.decorators import cls_require_superuser_or_developer from corehq.apps.domain.views import BaseDomainView from corehq.apps.sms.mixin impo...
#!/usr/bin/python3 from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import psycopg2 import numpy as np import pandas as pd _RESTAURANTS_DIR = '../data/restaurants/' password = os.environ['LETTUCEEATS_PSQL_PW'] dbname = 'menus' username = 'jparrent' engine = create_e...
""" Query construction tests. """ from hamcrest import assert_that, is_, equal_to from influxdbnagiosplugin.query import ExplicitQueryBuilder, SingleMeasurementQueryBuilder def test_explicit_query(): query = ExplicitQueryBuilder("SHOW MEASUREMENTS") assert_that(query().query, is_(equal_to( "SHOW MEAS...
from os import chdir, getcwd from os.path import dirname, basename, realpath from unittest import TestCase from nose.tools import eq_ from nose.util import src from noseprogressive.utils import human_path, index_of_test_frame class DummyCase(TestCase): """A mock test to be thrown at ``index_of_test_frame()`` ...
""" """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import fabric import math from processors.sdc.parse_proto_sdc import * from processors.sdc.image_processing_sdc import * from processors.sdc.mu_law import * from fabric.image_pro...
from utils import * class MandelbrotSet(Window, ComplexPlane): def __init__(self, window_size, max_iter=69): Window.__init__(self, window_size) self.max_iter = float(max_iter) self.color_vector = np.vectorize(grayscale_color_factory(self.max_iter)) self.color_vector = np.vectorize(g...
"""Tests for tensorflow.python.client.session.Session's ClusterSpec Propagation. These tests exercise the ClusterSpec Propagation capabilities of distributed Sessions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.c...
import urllib, urllib2, sys, re, os, time, string, commands, socket timeout = 5 socket.setdefaulttimeout(timeout) counter = 10 maxcount = 20 d = [] LFN = [] finaloutput = 'finalsql.txt' tmpdir = 'tmp' currentdir = os.getcwd() os.mkdir(tmpdir) mailadr = '@gmail.com' intext2 = 'Password' filetype = 'sql' ...
import calendar from timeFormat import unformat_time def format_entry_as_date(current_date, entry, entry_value, show_days=True): """Formats the value in a Gtk entry to a date of MM/DD/YYYY or MM/YYYY from a time formatted as a tuple of (DD, MM, YYYY)""" # Get the current date tuple da...
""" Filter to add support for Trusted Computing Pools. Filter that only schedules tasks on a host if the integrity (trust) of that host matches the trust requested in the `extra_specs' for the flavor. The `extra_specs' will contain a key/value pair where the key is `trust'. The value of this pair (`trusted'/`untrust...
""" E-commerce Tab Instructor Dashboard Coupons Operations views """ import datetime import logging import pytz from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.utils.translation import ugettext as _ from django.views.decorators.http import req...
from Screens.Screen import Screen from Components.Sources.List import List from Components.Button import Button from Components.Label import Label from Components.ActionMap import ActionMap from Screens.InputBox import InputBox from Components.Input import Input from Components.MultiContent import MultiContentEntryText...
from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase, override_settings import django_cache_url from mock import patch from time import sleep import sys # @override_settings(BROWSE_RATE_LIMIT='10/5m') # couldn't get this to work @override_settings( CACHE...
######################################### # Calculate the Hamiltonian # ######################################### # # Teacher's scrypt wrote in Java and translated # to python which calculate the hamiltonian # of a Central elastic potencial # # Required floats: - mass\ m ...
from __future__ import division import numpy as np import pandas as pd from toolz import merge import toolz.curried.operator as op from zipline.data.bundles import ingest, load, bundles from zipline.data.bundles.quandl import ( format_wiki_url, format_metadata_url, ) from zipline.lib.adjustment import Float64...
from Cryptodome.Util.py3compat import bord from Cryptodome.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, SmartPointer, create_string_buffer, get_raw_buffer, c_size_t, ...
#!/usr/bin/env python import hashlib import json import logging import os import sys import urllib from functools import wraps import bcrypt import sqlite3 from flask import Flask, session, request, redirect, render_template, g, abort from flask import make_response import db import settings app = Flask(__name__) ap...
import numpy as np class UnboundedArray(np.ndarray): COLUMN = (-1, 1) LINE = (1, -1) def __new__(cls, input_array, *args, **kwargs): return np.asarray(input_array).view(cls) def __init__(self, input_array, *, padding='zero'): if self.ndim > 2: raise NotImplementedError('3...
"""TIR specific function pass support.""" import inspect import types import functools import tvm._ffi from tvm.ir.transform import Pass, PassInfo from . import _ffi_api @tvm._ffi.register_object("tir.PrimFuncPass") class PrimFuncPass(Pass): """A pass that works on each :py:func:`tvm.tir.PrimFunc` in a module. ...
# python imports import datetime from urlparse import urlparse # django imports from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.shortcuts import get_ob...
""" get_irs_soi_data.py -- download IRS SOI Exempt Organization data files by state Version 0.1 CPB 2014-10-13 -- Initial version. """ __author__ = "Christopher P. Barnes, <EMAIL>" __copyright__ = "Copyright 2014" __license__ = "BSD 3-Clause license" __version__ = "0.1" import os #names...
#!/usr/bin/python3 """Module / command line tool to handle the naming of OTRKEYs and AVIs""" import re import os import sys import logging from argparse import ArgumentParser logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) if sys.version_info.major < 3: def str(s): if isins...
from mock import patch from nose.tools import assert_equal, assert_raises from lemma import secret from tests import SECRET_KEY def test_initialize(): # setup secret.initialize(SECRET_KEY) # check assert_equal(secret.SECRET_KEY, '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' ...
import warnings import numpy as np def precision_recall_curve(expected, predicted, scores): # Sort predictions by decreasing score desc_score_indices = np.argsort(scores, kind="mergesort")[::-1] expected = np.array(expected)[desc_score_indices] predicted = np.array(predicted)[desc_score_indices] s...
# via http://pastebin.com/H1XikJFd # -*- Mode: Python -*- # This is a combination of http://pastebin.com/bQtdDzHx and # https://github.com/Bitmessage/PyBitmessage/blob/master/src/pyelliptic/openssl.py # that doesn't crash on OSX. # Long message bug fixed by ZeroNet import ctypes import ctypes.util import _ctypes impo...
from Tkinter import * import Tkinter as tk TITLE_FONT = ("Helvetica", 24, "bold") class AdminLogin(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Graphic Era Bank", font=("Helvetica", 24,...
import random import re from pyGBot import log from pyGBot.BasePlugin import BasePlugin class Roll(BasePlugin): __plugintype__ = "active" def __init__(self, bot, options): BasePlugin.__init__(self, bot, options) self.activeGame = False self.output = True self....
""" Test the heartbeat """ import json from django.core.urlresolvers import reverse from django.db.utils import DatabaseError from django.test.client import Client from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from mock import patch from xmodule.exceptions import HeartbeatFailure class Hear...
# # Handler library for Linux IaaS # # Copyright 2014 Microsoft 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://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
# no unicode literals from __future__ import absolute_import, division, print_function import atexit import errno import os import shutil import sys import tempfile import time import path_utils as path import pywatchman global_temp_dir = None class TempDir(object): """ This is a helper for locating a rea...
import top import theano import numpy as np from theano import tensor as T from pylearn2.utils import sharedX from pylearn2.space import VectorSpace, Conv2DSpace class SC(object): def __init__(self, model, hidden_size, input_space, steps=100): self.model = model bsize = self.model.batch_s...
import sys import astroid from astroid.node_classes import NodeNG from graphviz import Graph from typing import * from typing import ForwardRef from python_ta.typecheck.base import _TNode, TypeFail from python_ta.transforms.type_inference_visitor import TypeInferer from tests.custom_hypothesis_support import _parse_tex...
#! /usr/bin/env python # Format du output in a tree shape import os, string, sys, errno def main(): p = os.popen('du ' + string.join(sys.argv[1:]), 'r') total, d = None, {} for line in p.readlines(): i = 0 while line[i] in '0123456789': i = i+1 size = eval(line[:i]) while line[i] in ' \t': i = i+1 file =...
#!/usr/bin/env python import re from typing import Any from typing import Callable from typing import Dict from paasta_tools.utils import paasta_print ConstraintState = Dict[str, Dict[str, Any]] ConstraintOp = Callable[[str, str, str, ConstraintState], bool] def max_per(constraint_value, offer_value, attribute, st...
""" Django settings for Flashcard project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import ...
from __future__ import absolute_import import os from twisted.internet import defer, utils, threads from twisted.python import log, failure from buildbot.buildslave.base import AbstractBuildSlave, AbstractLatentBuildSlave from buildbot.util.eventual import eventually from buildbot import config try: import libvir...