code
stringlengths
1
199k
import os import six from aleph.util import checksum class Archive(object): def _get_file_path(self, meta): ch = meta.content_hash if ch is None: raise ValueError("No content hash available.") path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch) file_name = 'data' if...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('voximplant', '0008_auto_20160514_0800'), ] operations = [ migrations.RemoveField( model_name='calllist', name='completed', ...
""" Created on Mon Aug 15 20:55:19 2016 @author: ajaver """ import json import os from collections import OrderedDict import zipfile import numpy as np import pandas as pd import tables from tierpsy.helper.misc import print_flush from tierpsy.analysis.feat_create.obtainFeaturesHelper import WormStats from tierpsy.helpe...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
''' ΪÁËÈÃÄãµÄ´úÂ뾡¿ÉÄÜ¿ì, µ«Í¬Ê±±£Ö¤¼æÈݵͰ汾µÄ Python ,Äã¿ÉÒÔʹÓÃÒ»¸öС¼¼ÇÉÔÚ cStringIO ²»¿ÉÓÃʱÆôÓà StringIO Ä£¿é, Èç ÏÂÀý Ëùʾ. ''' try: import cStringIO StringIO = cStringIO except ImportError: import StringIO print StringIO
from __future__ import absolute_import from django.conf.urls import url from oauth2_provider import views from .views import CoffeestatsApplicationRegistration, \ CoffeestatsApplicationDetail, \ CoffeestatsApplicationApproval, \ CoffeestatsApplicationRejection, \ CoffeestatsApplicationFullList urlpatter...
from ComssServiceDevelopment.connectors.tcp.msg_stream_connector import InputMessageConnector, OutputMessageConnector from ComssServiceDevelopment.service import Service, ServiceController import cv2 #import modułu biblioteki OpenCV import numpy as np #import modułu biblioteki Numpy import os import threading from time...
from flask import request from structlog import get_logger from ghinbox import app from ghinbox.tasks import create_issue logger = get_logger() @app.route('/hooks/postmark', methods=['POST']) def postmark_incomming_hook(): # TODO #2 HTTP Basic Auth inbound = request.json if not inbound: return 'ERR'...
from zope import schema from sparc.entity import IEntity from sparc.organization import ICompany from sparc.organization import IOrganizableEntity class IAddress(IEntity): """A generic address""" address = schema.Text( title = u'Address', description = u'The entity address', ...
import os from cpenv import api, paths from cpenv.cli import core from cpenv.module import parse_module_path class Create(core.CLI): '''Create a new Module.''' def setup_parser(self, parser): parser.add_argument( 'where', help='Path to new module', ) def run(self, arg...
""" Created on Sat Feb 22 12:07:53 2014 @author: Gouthaman Balaraman """ import requests import pandas as pd from bs4 import BeautifulSoup import re import numpy as np import os _curdir= os.path.abspath(os.path.curdir) _posdat = re.compile('(\w+):(\d+)px') _topdat = re.compile('top:(\d+)px') _leftdat = re.compile('top:...
from django.utils.translation import ugettext_lazy as _ from appconf import AppConf trans_app_label = _('Core') class OppsCoreConf(AppConf): DEFAULT_URLS = ('127.0.0.1', 'localhost',) SHORT = 'googl' SHORT_URL = 'googl.short.GooglUrlShort' CHANNEL_CONF = {} VIEWS_LIMIT = None PAGINATE_BY = 10 ...
from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponseBadRequest, HttpResponse from bootcamp.tasks.models import Task from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from bootcamp.tasks.forms import TaskForm from django.contrib.auth.decorators impo...
class Node: # Constructor to initialise node def __init__(self, data): self.data = data self.left = None self.right = None class BST: def __init__(self): self.root = None def insert_node(self, data): if self.root is None: self.root = Node(data) ...
import random from decimal import Decimal, ROUND_HALF_UP from django.test import TestCase from django.core.validators import ValidationError from .models import * def setup(): """ Create dummy data """ Status.objects.create( name="Hero", overdraft="0" ) Status.objects.create( ...
""" Initialize the module. Author: Panagiotis Tsilifis Date: 5/22/2014 """ from _forward_model_dmnless import *
"""TestCases for multi-threaded access to a DB. """ import os import sys import time import errno from random import random DASH = '-' try: WindowsError except NameError: class WindowsError(Exception): pass import unittest from test_all import db, dbutils, test_support, verbose, have_threads, \ ...
import os import sys import asyncio from pathlib import Path import pendulum sys.path.append(str(Path(__file__).absolute().parent.parent.parent)) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") from django.core.wsgi import get_wsgi_application # noqa application = get_wsgi_application() from autoba...
''' 冒泡排序(bubble sort):每个回合都从第一个元素开始和它后面的元素比较, 如果比它后面的元素更大的话就交换,一直重复,直到这个元素到了它能到达的位置。 每次遍历都将剩下的元素中最大的那个放到了序列的“最后”(除去了前面已经排好的那些元素)。 注意检测是否已经完成了排序,如果已完成就可以退出了。时间复杂度O(n2) ''' def short_bubble_sort(a_list): exchange = True pass_num = len(a_list) - 1 while pass_num > 0 and exchange: exchange = False ...
import urllib from cyclone.web import asynchronous from twisted.python import log from sockjs.cyclone import proto from sockjs.cyclone.transports import pollingbase class JSONPTransport(pollingbase.PollingTransportBase): name = 'jsonp' @asynchronous def get(self, session_id): # Start response ...
import py, os, cffi, re import _cffi_backend def getlines(): try: f = open(os.path.join(os.path.dirname(cffi.__file__), '..', 'c', 'commontypes.c')) except IOError: py.test.skip("cannot find ../c/commontypes.c") lines = [line for line in f.readlines() if line.st...
"""Main entry point """ from pyramid.config import Configurator def main(global_config, **settings): config = Configurator(settings=settings) config.include("cornice") config.scan("pyramidSparkBot.views") return config.make_wsgi_app()
import requests headers = { 'foo': 'bar', } response = requests.get('http://example.com/', headers=headers)
from __future__ import unicode_literals from wtforms import validators from jinja2 import Markup from studio.core.engines import db from riitc.models import NaviModel, ChannelModel from .base import BaseView from .forms import CKTextAreaField class Navi(BaseView): column_labels = {'name': '名称', 'channels': '频道列表'} ...
import logging log = logging.getLogger(__name__) def has_bin(arg): """ Helper function checks whether args contains binary data :param args: list | tuple | bytearray | dict :return: (bool) """ if type(arg) is list or type(arg) is tuple: return reduce(lambda has_binary, item: has_binary o...
import csv import numpy as np import matplotlib.pyplot as plt childin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/scripts/WIPS2015/importData/child_attack_rate.txt','r') child=csv.reader(childin, delimiter=' ') adultin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/scripts/WIPS201...
from microbit_stub import * while True: if button_a.is_pressed(): for i in range(5): if display.get_pixel(i, 0): display.set_pixel(i, 0, 0) sleep(10) else: display.set_pixel(i, 0, 9) sleep(200) break ...
import sys, os, subprocess, tempfile, shlex, glob result = None d = None def format_msg(message, headline): msg = "Line {0}:\n {1}\n{2}:\n{3}"\ .format(PARAMS["lineno"], PARAMS["source"], headline, message) return msg try: #print("RUN", PARAMS["source"]) d = tempfile.mkdtemp(dir="/dev/shm") ...
import copy from zope.interface import implementer from .interfaces import ( IExecutor, ISchemaValidation, IDataValidation, ICreate, IDelete, IEdit ) from alchemyjsonschema.dictify import ( normalize, validate_all, ErrorFound ) from jsonschema import FormatChecker from jsonschema.val...
import sys import time import os.path from collections import Counter from vial import vfunc, vim, dref from vial.utils import redraw, focus_window from vial.widgets import make_scratch collector = None def get_collector(): global collector if not collector: collector = ResultCollector() return coll...
import csv import unittest from datetime import datetime, timedelta from hackertracker import event from hackertracker.database import Model, Session from sqlalchemy import create_engine class TestEvents(unittest.TestCase): def setUp(self): engine = create_engine('sqlite:///:memory:', echo=True) Mod...
import pandas as pd from pandas.io import gbq def test_sepsis3_one_row_per_stay_id(dataset, project_id): """Verifies one stay_id per row of sepsis-3""" query = f""" SELECT COUNT(*) AS n FROM ( SELECT stay_id FROM {dataset}.sepsis3 GROUP BY 1 HAVING COUNT(*) > 1 ) s """ df = g...
"""signal handlers registered by the imager_profile app""" from __future__ import unicode_literals from django.conf import settings from django.db.models.signals import post_save from django.db.models.signals import pre_delete from django.dispatch import receiver from imager_profile.models import ImagerProfile import l...
from django import forms from . import models from apps.utils import forms as utils, constants from django.forms import models as models_form from apps.personas import models as persona_models class VacanteForm(utils.BaseFormAllFields): title = 'Vacante' fecha = forms.DateField(input_formats=constants.INPUT_FOR...
from collidable import * from math_3d import * class PixelCollidable( Collidable ) : def __init__(self) : self.spm = None self.r = None
class Solution: def maxArea(self, height): """ :type height: List[int] :rtype: int """ i, j = 0, len(height)-1 l, r = height[i], height[j] maxArea = (j - i) * min(l, r) while j > i: if l < r: while height[i] <= l: ...
from __future__ import absolute_import, division, print_function, unicode_literals from prompt_toolkit.completion import Completer, Completion import azclishell.configuration from azclishell.argfinder import ArgsFinder from azclishell.command_tree import in_tree from azclishell.layout import get_scope from azclishell.u...
__author__ = 'yuanchun' """ Analyze dynamically Android applications This script allows you to analyze dynamically Android applications. It installs, runs, and analyzes Android applications. At the end of each analysis, it outputs the Android application's characteristics in JSON. Please keep in mind that all data rece...
import os.path import logging _logger = logging.getLogger(__name__) from operator import itemgetter from tornado.web import Application, RequestHandler, StaticFileHandler from tornado.ioloop import IOLoop config = { 'DEBUG': True, 'PORT' : 5000 } HANDLERS = [] ROOT_DIR = os.path.abspath(os.path.join(os.path.spl...
""" The Jaccard similarity coefficient is a commonly used indicator of the similarity between two sets. Let U be a set and A and B be subsets of U, then the Jaccard index/similarity is defined to be the ratio of the number of elements of their intersection and the number of elements of their union. Inspired from Wikipe...
import MySQLdb def connect(id,name,gender,region,status,date,inter): try: conn = MySQLdb.connect(host='localhost',user='root',passwd=' ',port=3306) cur = conn.cursor() # cur.execute('create database if not exists PythonDB') conn.select_db('Facebook') # cur.execute('create tab...
from sys import platform import unittest import checksieve class TestVariables(unittest.TestCase): def test_set(self): sieve = ''' require "variables"; set "honorific" "Mr"; ''' self.assertFalse(checksieve.parse_string(sieve, False)) def test_mod_length(self): sie...
from spacyThrift import SpacyThrift from spacyThrift.ttypes import Token from spacy.en import English from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer import logging class Handler: def __init__(self, nlp): ...
import os.path path_to_script = os.path.dirname(os.path.abspath(__file__)) import unittest import numpy as np import os from imtools import qmisc from imtools import misc class QmiscTest(unittest.TestCase): interactivetTest = False # interactivetTest = True # @unittest.skip("waiting for implementation") ...
from django.contrib import admin from django import forms from django.contrib.auth.models import User from sample.models import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup, Scan) class searchDoctor(admin.ModelAdmin): list_display = ['user_first_name', 'user_last_name', 'ge...
import _plotly_utils.basevalidators class WidthValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="width", parent_name="violin", **kwargs): super(WidthValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_ty...
from classifier import Classifier from itertools import combinations from datetime import datetime import sys import os open_path = "PatternDumps/open" closed_path = "PatternDumps/closed" monitored_sites = ["cbsnews.com", "google.com", "nrk.no", "vimeo.com", "wikipedia.org", "youtube.com"] per_burst_weight = 1 total_ce...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Alloy', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,...
from django import forms from django.conf import settings from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ import urllib2, urllib VERIFY_SERVER="http://api-verify.recaptcha.net/verify" class RecaptchaWidget(forms.Widget): def render(self, name, value, attrs=None): ...
from typing import List """ 31. Next Permutation https://leetcode.com/problems/next-permutation/ """ class Solution: def nextPermutation(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ best = None for i in range(len(nums) - 1): ...
from __future__ import print_function import linecache import sys import numpy from six import iteritems from theano import config from theano.compat import OrderedDict, PY3 def simple_extract_stack(f=None, limit=None, skips=[]): """This is traceback.extract_stack from python 2.7 with this change: - Comment the...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline i...
''' TD_Sequence in class. ''' import numpy as np import pandas as pd import json import pandas.io.data as web from datetime import date, datetime, timedelta from collections import defaultdict class TDSequence(object): def __init__(self, data): self.data = data def sequence(self): setup = self.d...
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class User(Base): """docstring for User""" __tablename__ = 'users' id = Column(Integer, ...
from ..base import ShopifyResource class GiftCardAdjustment(ShopifyResource): _prefix_source = "/admin/gift_cards/$gift_card_id/" _plural = "adjustments" _singular = "adjustment"
from libraries.dijkstra import * def getSingleValue(src, dst, edgeCostHash): return edgeCostHash[(src*100000)+dst] def getPathTotal(start, end, edgeCostHash, networkDict): #get shortest path between start and end shortPathList = shortestPath(networkDict, start, end) print "WE PINGING SHAWTY", shortPathList
import _plotly_utils.basevalidators class SmoothingValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="smoothing", parent_name="contourcarpet.line", **kwargs ): super(SmoothingValidator, self).__init__( plotly_name=plotly_name, parent...
import sys class outPip(object): def __init__(self, fileDir): self.fileDir = fileDir self.console = sys.stdout def write(self, s): self.console.write(s) with open(self.fileDir, 'a') as f: f.write(s) def flush(self): self.console.flush() new_input = input def inPip(fil...
__all__ = ["wordlists", "roles", "bnc", "processes", "verbs", "uktous", "tagtoclass", "queries", "mergetags"] from corpkit.dictionaries.bnc import _get_bnc from corpkit.dictionaries.process_types import processes from corpkit.dictionaries.process_types import verbs from corpkit.dictionaries.roles import role...
class SpellPickerController: def render(self): pass _controller_class = SpellPickerController
"""Template""" from os import path import jinja2 from jinja2 import FileSystemLoader, ChoiceLoader from jinja2.exceptions import TemplateNotFound import peanut from peanut.utils import get_resource class SmartLoader(FileSystemLoader): """A smart template loader""" available_extension = ['.html', '.xml'] def...
from optparse import OptionParser import simplejson as json import spotify_client import datatype import datetime import time import calendar import wiki import omni_redis def migrate_v1(path_in, path_out): client = spotify_client.Client() uris = [] with open(path_in, 'rb') as f: for line in f: ...
import json from PIL import Image import collections with open('../config/nodes.json') as data_file: nodes = json.load(data_file) ordered_nodes = [None] * len(nodes) for i, pos in nodes.items(): ordered_nodes[int(i)] = [pos['x'], pos['y']] filename = "04_rgb_vertical_lines" im = Image.open("../gif_generators/outp...
from __future__ import unicode_literals import frappe from frappe.model.document import Document class GoogleAppSetup(Document): pass
from node import Node from fern.ast.tools import simplify, ItemStream from fern.primitives import Undefined class List(Node): def __init__(self): Node.__init__(self) self.children = [] self.value = None def put(self, thingy): if isinstance(thingy, ItemStream): for it ...
from __future__ import print_function import warnings import numpy import pytest import sympy from dolfin import ( MPI, Constant, DirichletBC, Expression, FunctionSpace, UnitSquareMesh, errornorm, pi, triangle, ) import helpers import matplotlib.pyplot as plt from maelstrom import he...
class Solution(object): def combinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ def recurhelper(nums,res,path,target,start): if target==0: res.append(path) ...
"""Converts the .ics/.ical file into a FullCalendar compatiable JSON file FullCalendar uses a specific JSON format similar to iCalendar format. This script creates a JSON file containing renamed event components. Only the title, description, start/end time, and url data are used. Does not support repeating events. """ ...
from __future__ import absolute_import, unicode_literals from django.core.paginator import Paginator from django.core import urlresolvers from django.utils.html import mark_safe, escape import django_tables2 as tables from django_tables2.tables import Table from django_tables2.utils import Accessor as A, AttributeDict ...
import copy from ruamel.yaml import YAML from six import iteritems _required = ['server'] class Config(object): def __init__(self, configFile): self.configFile = configFile self._configData = {} self.yaml = YAML() self._inBaseConfig = [] def loadConfig(self): configData =...
"""Requirements specific to SQLAlchemy's own unit tests. """ from sqlalchemy import util import sys from sqlalchemy.testing.requirements import SuiteRequirements from sqlalchemy.testing import exclusions from sqlalchemy.testing.exclusions import \ skip, \ skip_if,\ only_if,\ only_on,\ fails_on_...
from io import StringIO class TOKEN_TYPE: OPERATOR = 0 STRING = 1 NUMBER = 2 BOOLEAN = 3 NULL = 4 class __TOKENIZER_STATE: WHITESPACE = 0 INTEGER_0 = 1 INTEGER_SIGN = 2 INTEGER = 3 INTEGER_EXP = 4 INTEGER_EXP_0 = 5 FLOATING_POINT_0 = 6 FLOATING_POINT = 8 STRING = ...
from .base import Base import re from deoplete.util import ( convert2list, parse_buffer_pattern, set_pattern, getlines) class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = 'member' self.mark = '[M]' self.min_pattern_length = 0 self._object_patte...
from __future__ import print_function import sys import time import numpy as np from pyqtgraph import PlotWindow from six.moves import zip sys.path.append('../../util') sys.path.append('../..') from .nidaq import NiDAQ from pyqtgraph.functions import mkPen, mkColor pw = PlotWindow() time.clock() sr = 100000 dur = 2.0 d...
__author__ = 'Exter, 0xBADDCAFE' import wx class FTDropTarget(wx.DropTarget): """ Implements drop target functionality to receive files and text receiver - any WX class that can bind to events evt - class that comes from wx.lib.newevent.NewCommandEvent call class variable ID_DROP_FILE class vari...
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test', } } ROOT_URLCONF = 'urls' SITE_ID = 1 INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessio...
"""Test energy_profiler module.""" import unittest from physalia.energy_profiler import AndroidUseCase class TestEnergyProfiler(unittest.TestCase): def test_empty_android_use_case(self): # pylint: disable=no-self-use use_case = AndroidUseCase( name="Test", app_apk="no/path", ...
def fib(): a, b = 1, 1 while True: yield b a, b = b, a + b def pares(seq): for n in seq: if n % 2 == 0: yield n def menores_4M(seq): for n in seq: if n > 4000000: break yield n print (sum(pares(menores_4M(fib()))))
from core.rule_core import * from core import yapi from core.config_loader import cur_conf class YunoModule: name = "ores" cfg_ver = None ores_api = yapi.ORES config = [ { "models": { "damaging": {"max_false": 0.15, "min_true": 0.8}, "goodfaith": {"min...
from .record import Record,RecordSet,QueryValue from .heysqlware import *
import pytz from pendulum import _safe_timezone from pendulum.tz.timezone import Timezone def test_safe_timezone_with_tzinfo_objects(): tz = _safe_timezone(pytz.timezone("Europe/Paris")) assert isinstance(tz, Timezone) assert "Europe/Paris" == tz.name
sandwich_orders = ['Bacon','Bacon, egg and cheese','Bagel toast','pastrami','pastrami','pastrami'] print ('pastrami sandwich was sold out') finished_sandwiches = [] while 'pastrami' in sandwich_orders: sandwich_orders.remove('pastrami') print(sandwich_orders)
import pytest from parglare import Parser, Grammar from parglare.exceptions import GrammarError, ParseError, RRConflicts def test_repeatable_zero_or_more(): """ Tests zero or more repeatable operator. """ grammar = """ S: "2" b* "3"; terminals b: "1"; """ g = Grammar.from_string(gram...
"""CMS view for static pages""" from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from boski.mixins import LoginRequiredMixin from...
import random from authorize import Customer, Transaction from authorize import AuthorizeResponseError from datetime import date from nose.plugins.attrib import attr from unittest import TestCase FULL_CUSTOMER = { 'email': 'vincent@vincentcatalano.com', 'description': 'Cool web developer guy', 'customer_typ...
try: from collections import defaultdict except: class defaultdict(dict): def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not hasattr(default_factory, '__call__')): raise TypeError('first argument must be callable') ...
import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit def lsq(x, y): assert len(x) == len(y), 'Array dimensions do not match' n = float(len(x)) # Don't lose precision with int * float multiplication # compute covariance matrix and correlation coefficient of data cov = ...
from bson import ObjectId from . import repeating_schedule from state_change import StateChange class StateChangeRepeating(StateChange): def __init__(self, seconds_into_week, AC_target, heater_target, fan, id=None): self.id = id self.seconds_into_week = seconds_into_week self.AC_target = AC_...
import os, sys import datetime from glob import glob import json import numpy as np import pandas from skimage.morphology import binary_erosion from nitime.timeseries import TimeSeries from nitime.analysis import SpectralAnalyzer, FilterAnalyzer import nibabel import nipype.interfaces.spm as spm from nipype.interfaces....
from .resnet_preact import resnet18_preact from .resnet_preact_bin import resnet18_preact_bin import torch, torch.nn as nn _model_factory = { "resnet18_preact":resnet18_preact, "resnet18_preact_bin":resnet18_preact_bin } class Classifier(torch.nn.Module): def __init__(self, feat_extractor,num_classes=None):...
from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GLUT.freeglut import * import GlutWrapper import math ESCAPE = b'\033' class GlutViewController(GlutWrapper.GlutWrapper): """docstring for GlutViewController""" def __init__(self): super(GlutViewController, self).__in...
import locale import csv import os from PIL import Image import re from collections import Counter def scanDir(path): # scan the path and collect media data for copy process while os.path.exists(path) and os.path.isdir(path): photos_dataset, totalsize, folder_count, videos_dataset = listphotos(path) ...
''' Wrap some important functions in sqlite3 so we can instrument them. ''' from xrayvision.monkeypatch import mark_patched, is_patched _old_connect = sqlite3.connect def patch(module): module
from lxml import etree import os from BeautifulSoup import BeautifulSoup from itertools import chain def replacements(text): text = text.replace('&gt;', '\\textgreater ') text = text.replace('&lt;', '\\textless ') text = text.replace('&', '\&') text = text.replace('_', '\_') text = text.replace('%',...
import pytest from mock import Mock from sigopt.orchestrate.services.aws_provider_bag import AwsProviderServiceBag class TestOrchestrateServiceBag(object): @pytest.fixture def orchestrate_services(self): return Mock() def test_orchestrate_service_bag(self, orchestrate_services): services = AwsProviderServ...
fa_icons = { 'fa-glass': u"\uf000", 'fa-music': u"\uf001", 'fa-search': u"\uf002", 'fa-envelope-o': u"\uf003", 'fa-heart': u"\uf004", 'fa-star': u"\uf005", 'fa-star-o': u"\uf006", 'fa-user': u"\uf007", 'fa-film': u"\uf008", 'fa-th-large': u"\uf009", 'fa-th': u"\uf00a", 'f...
"""*.h5 の値の最小・最大などを確認するスクリプト。""" import argparse import pathlib import sys import h5py import numpy as np try: import pytoolkit as tk except ImportError: sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent.parent)) import pytoolkit as tk logger = tk.log.get(__name__) def main(): tk.uti...
from __future__ import absolute_import import theano import theano.tensor as T from theano.tensor.signal import downsample from .. import activations, initializations from ..utils.theano_utils import shared_zeros from ..layers.core import Layer class Convolution1D(Layer): def __init__(self, nb_filter, stack_size, f...
import os import sys import time import subprocess import yaml import pathlib class ClusterLauncher: def __init__(self, config_yaml): self.Config = config_yaml def Launch(self): #read config with open(self.Config, 'r') as yf: config = yaml.safe_load(yf) #launch he...
from django.utils.translation import ugettext_lazy as _ from django import forms from django.conf import settings from django.forms.utils import ValidationError from os import chmod import hashlib from io import BytesIO try: import pyclamd except Exception: pass class yatsFileField(forms.FileField): default...