content
stringlengths
5
1.05M
from data_utils.clean_text import clean_text from data_utils.constants import (B_TOKEN, CHARACTER_SEPARATOR, CLASSES, I_TOKEN, SPLIT_TOKEN, TAGS, WORD_TAG_SEPARATOR) def transform_data(data, word_tokenizer, char_tokenizer): """ Args: da...
# -*- coding: utf-8 -*- import random import Vertex import numpy as np class Tree(): size_of_v = 0 size_of_e = 0 V = np.array([], Vertex.Vertex) E = None origin = 0 max_deg_v = None # Vertex type # Random Tree Generator: def __init__(self, size): if size == 0: r...
from urllib.request import urlopen from urllib.error import HTTPError import json import pandas as pd BASE_URL = "https://financialmodelingprep.com/api" def download(URL): try: response = urlopen(URL) data = json.loads(response.read().decode("utf-8")) except HTTPError: raise ValueError...
# Classes and methods whitelist core = {'': ['absdiff', 'add', 'addWeighted', 'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'cartToPolar',\ 'compare', 'convertScaleAbs', 'copyMakeBorder', 'countNonZero', 'determinant', 'dft', 'divide', 'eigen', \ 'exp', 'flip', 'getOptimalDFTSize'...
import json from datetime import datetime import inspect import json from .logger import logger def pretty(x): return print(json.dumps(x, indent=4, default=str)) def prettify(x): return json.dumps(x, indent=4, default=str) def function_name(): return inspect.stack()[1][3] def dumps(x, indent=0): string =...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2019 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. try: import pplog except: import logging as pplog import datetime from pandapower.io_utils import JSONSerializableClas...
"""Generate the gradient graphs for reverse mode. The J transform on a graph produces two graphs, the forward graph (fprop) and the backpropagator graph (bprop). The former returns the result of the computation and the bprop graph, and the latter takes output sensitivities and returns input sensitivities. For each nod...
from torch2trt.torch2trt import * from .ReLU import * @tensorrt_converter('torch.nn.functional.relu') def convert_relu(ctx): ctx.method_args = (torch.nn.ReLU(),) + ctx.method_args convert_ReLU(ctx)
# coding=utf-8 import datetime from django import template register = template.Library() @register.filter def attr_from_domain_id(attrs, domain_id): attrs = attrs.filter(domain_id=domain_id) return attrs.first() if attrs else None
from unittest import TestCase, main from requests.exceptions import Timeout from unittest.mock import Mock, patch from src.mytest.mocking.my_calendar import requests, protocol from src.mytest.mocking.my_calendar import get_holidays target_url = 'http://localhost/api/holidays' def log_request(obj): print(f"Makin...
from django.http import HttpRequest, HttpResponse from hermes.forms.models import Form, Site, Submission from hermes.hooks.mail.email import render_submission_body def debug_submission_email(request: HttpRequest, *args, **kwargs) -> HttpResponse: (site, _) = Site.objects.get_or_create( name="test site", ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- import math import colossalai import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from colossalai.context.parallel_mode import ParallelMode from colossalai.core import global_context as gpc from colossalai.nn.layer.parallel...
from setuptools import setup, find_namespace_packages from tethys_apps.app_installation import find_resource_files ### Apps Definition ### app_package = 'embalses' release_package = 'tethysapp-' + app_package # -- Get Resource File -- # resource_files = find_resource_files('tethysapp/' + app_package + '/templates', '...
import json import logging import random import time from typing import Callable, Optional, Union, cast from requests import Response, Session from requests.exceptions import ConnectionError from jira.exceptions import JIRAError logging.getLogger("jira").addHandler(logging.NullHandler()) def raise_on_error(r: Opti...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Sonos-GUI-URI This is the first attempt to create a window to stream a URI to the Sonos Speakers. Author: Jim Scherer """ import Tkinter as tk import ttk # from ttk import Frame, Style, Label, Button, Entry import tkMessageBox as mbox import time import soco as sonosLib...
from django.contrib import admin from security.models import PasswordExpiry, CspReport admin.site.register(PasswordExpiry) admin.site.register(CspReport)
Full_length = input("Enter the sequence of your protein, in single letter code, here: ") protein = Full_length.upper() dict = { 'G' : 57.052, 'A' : 71.079, 'S' : 87.078, 'P' : 97.117, 'V' : 99.133, 'T' : 101.105, 'C' : 103.144, 'I' : 113.160, 'L' : 113.160, 'N' : 114.104, 'D' : 115.089, 'Q' : 128.131, 'K' : 128.174, ...
"""Config flow for AMD GPU integration.""" import logging import voluptuous as vol from homeassistant import config_entries from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from . import find_resources_in_config_entry from .const import ( CONF_RESOURCES, DOMAIN, ...
from django import forms class UrbanAcroForm(forms.Form): name = forms.CharField(required=True) address = forms.CharField(required=True) phone = forms.CharField(required=True) email = forms.EmailField(required=True) option = forms.CharField(required=False) comment = forms.CharField(required=Fa...
import base64 import os mpesa_express_business_shortcode = os.getenv( "MPESA_EXPRESS_BUSINESS_SHORTCODE") assert(mpesa_express_business_shortcode != None), "missing mpesa_express_business_shortcode" lipa_na_mpesa_passkey = os.getenv("LIPA_NA_MPESA_PASSKEY") assert(lipa_na_mpesa_passkey != None), "Missing li...
from agent import Qnet from agent import ReplayBuffer from agent import train q = Qnet() q_target = Qnet() q_target.load_state_dict(q.state_dict()) memory = ReplayBuffer() print_interval = 20 score = 0.0 optimizer = optim.Adam(q.parameters(), lr=learning_rate) score_history= [] for n_epi in range(30...
r''' Source file for merge_dats_logs() ''' from os import chdir, getcwd, listdir, remove, rename PREFIX = "_c_" DEBUGGING = False DATLNFMT = '{:>4s} {:>12s} {:>12s} {:>12s} {:>12s} {:>9s} {:>12s} {:>12s}' \ + '{:>4s} {:>12s} {:>5s} {:>9s}\n' def merge_dats_logs(arg_h5: str, arg_dir: str, arg_type: str,...
dummy_compute = False dummy_mun_codes = [147,151,153,165,400] dummy_mun_codes_4char = [f'0{m}' for m in dummy_mun_codes] cell_label = 'DDKNm100' years_num = list(range(2010,2020)) years = [str(y) for y in years_num] years_hh = [f'{y}_hh' for y in years] years_pers = [f'{y}_pers' for y in years] mean_cols = ['mean_pe...
# modified into a class import socket from IPy import IP from termcolor import colored class PortScan(): banners = [] open_ports = [] def __init__(self, target, port_num): self.target = target self.port_num = port_num def scan(self): for port in range(1, 100): se...
import logging from tornado.ioloop import IOLoop from tornado.gen import coroutine from tornado import autoreload from django.conf import settings from .workers import (TickerWatcher, TransactionsWatcher, OrdersWatcher, Monitoring) log = logging.getLogger(__name__) @coroutine def main_loop()...
from integrations.new_relic.new_relic import NewRelicWrapper, EVENTS_API_URI def test_new_relic_initialized_correctly(): # Given api_key = "123key" app_id = "123id" base_url = "http://test.com" # When initialized new_relic = NewRelicWrapper(base_url=base_url, api_key=api_key, app_id=app_id) ...
from django.db import models from django.contrib.auth.models import User from PIL import Image import io from django.core.files.storage import default_storage as storage from phonenumber_field.modelfields import PhoneNumberField class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASC...
from django.urls import reverse def test_sales_dashboard_index(superuser_authenticated_client): """ VERY basic test to check that the index page loads. """ # Given url = reverse("sales_dashboard:index") # When response = superuser_authenticated_client.get(url) # Then assert resp...
# Copyright 2019 Red Hat, Inc. # # 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 required by applicable law or agreed to in writing...
import requests import json def main(): noSpaces = '' noSpaces = input('Do you want the words with spaces?(y/n)\n').strip().lower() while(True): if noSpaces == 'n': noSpaces = True break elif noSpaces == 'y': noSpaces = False break el...
# -*- coding: utf-8 -*- import os import sys import time import numpy as np import models from keras.utils import generic_utils import general_utils from data_utils import * from image_history_buffer import * from IPython import display from models import * from additional_models import * from collections import deque ...
from sklearn.base import BaseEstimator, TransformerMixin import lightgbm as lgb import numpy as np import pandas as pd class NonstationaryFeatureRemover(BaseEstimator, TransformerMixin): def __init__(self, remove_count=None, remove_ratio=None): if remove_count and remove_ratio: raise Exception(...
# %% import multyscale import RHS_filters import numpy as np import matplotlib.pyplot as plt # %% RHS bank rhs_bank = RHS_filters.filterbank() # %% Parameters of image shape = (1024, 1024) # filtershape in pixels # visual extent, same convention as pyplot: visextent = np.array([-0.5, 0.5, -0.5, 0.5]) * (1023 / 32) ...
# A simple Ping Pong game using Python 3 Programming language and the module called turtle #By Edna Sawe Kite #Import the required modules import turtle import winsound import flask from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') ...
from google.cloud import storage import json import logging import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split def complete_hp_tuning(x_train_part, y_train_part, project_id, bucket_name, num_iterations): # perform hyperpa...
# # author: Jungtaek Kim ([email protected]) # last updated: December 29, 2020 # """These files are for implementing Student-:math:`t` process regression. It is implemented, based on the following article: (i) Rasmussen, C. E., & Williams, C. K. (2006). Gaussian Process Regression for Machine Learning. MIT Press. (...
""" tests.py Automated tests that are written here are run with the manage.py test command. Included is an automated Selenium test written by Jaimes Subroto. """ from django.test import TestCase # Create your tests here. # -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by impor...
from sqlalchemy import MetaData, Table, Column, Integer, NVARCHAR meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table( "journal", meta, Column("id", Integer, primary_key=True), Column("name", NVARCHAR(500), index=True), ) t.create() ...
""" Open datasets """ from .base import Openset, ImagesOpenset from .mnist import MNIST from .cifar import CIFAR10, CIFAR100
from abc import ABCMeta, abstractmethod class AnalysisBase(metaclass=ABCMeta): @abstractmethod def run(self, user_request): pass
import os from appconf import AppConf from django.conf import settings class XMLAppConf(AppConf): class Meta: prefix = "xml"
import sympy.physics.mechanics as _me import sympy as _sm import math as m import numpy as _np x, y = _me.dynamicsymbols('x y') a, b, r = _sm.symbols('a b r', real=True) eqn = _sm.Matrix([[0]]) eqn[0] = a*x**3+b*y**2-r eqn = eqn.row_insert(eqn.shape[0], _sm.Matrix([[0]])) eqn[eqn.shape[0]-1] = a*_sm.sin(x)**...
""" Tests for the custom serialization code used by the API application. Copyright (C) 2020 Nicholas H.Tollervey. "Commons Clause" License Condition v1.0: The Software is provided to you by the Licensor under the License, as defined below, subject to the following condition. Without limiting other conditions in th...
# -*- coding:UTF-8 -*- # select parameters to output DBN model import numpy as np np.random.seed(1337) # for reproducibility from sklearn.datasets import load_boston from sklearn.cross_validation import train_test_split from sklearn.metrics.regression import r2_score, mean_squared_error from sklearn.preprocessing imp...
f1 = open('A-large.in','r') f2 = open('output','w') t = int(f1.readline()) for i in range(1,t+1): a = int(f1.readline()) if a == 0: f2.write("Case #"+str(i)+": INSOMNIA\n") else: digithash = [0] * 10 remaining_digits = 10 no = 1 while True: temp = no*a ...
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config 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...
""" Created on 2 Mar. 2018 @author: oliver """ class ClassifiedLine(object): """ classdocs """ def __init__(self, filename, line_number, classification): """ Constructor """ self.filename = filename self.line_number = line_number self.classification = ...
import matplotlib.pyplot as plt import numpy as np import wave import sys from scipy import signal def visualize_wave(path, step, target): spf = wave.open(path + str(step) + "k_steps_"+ str(target) + "_target_pcm.wav", "r") # Extract Raw Audio from Wav File signal = spf.readframes(-1) sample_freq...
#coding: latin1 def matrix_product0(A: "matrix", B: "matrix") -> "matrix": #[intro0 p, q, r = len(A), len(A[0]), len(B[0]) C = [[0] * r for i in range(p)] for i in range(p): for j in range(r): for k in range(q): C[i][j] += A[i][k]*B[k][j] return C #]intro0 ...
import os import shutil import time from django import forms from django.conf import settings from django.core.cache import cache from django.core.files.uploadedfile import SimpleUploadedFile from django.test import Client, TestCase, override_settings from django.urls import reverse from posts.models import Group, Po...
class BinarySearch: def __init__(self, arr, target): self.arr = arr self.target = target def binary_search(self): lo, hi = 0, len(self.arr) while lo<hi: mid = lo + (hi-lo)//2 # dont use (lo+hi)//2. Integer overflow. # https://en.wikipedia.or...
# -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020-2021, Yoel Cortes-Pena <[email protected]> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for license details...
''' Password reset Model ''' from api.models import db class PasswordReset(db.Model): '''assword reset Model class''' __tablename__ = "password_reset_tokens" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) reset_token = db.C...
#!/usr/bin/python # import packages import Tkinter as tk # for the GUI import ttk # for nicer GUI widgets import tkMessageBox # for GUI testbox import serial # for communication with serial port import time # for time stuff import threading # for parallel computing imp...
""" # ------------------------------------------------------------------------------- # Name: JSON Schema Validation # Purpose: Shared JSON Schema Validation for Input JSONS # # # Author: Moe Maysami # # Created: Nov 2019 # Licence: See Git # ------------------------------------------------...
import graphene from graphene import relay from graphene_django.filter import DjangoFilterConnectionField from graphql_jwt.decorators import login_required from .models import Item, Picture, Storage from .mutations import ( AddConsumableMutation, AddItemMutation, AddPictureMutation, AddStorageMutation,...
from py2neo import Graph graph = Graph("http://192.168.50.52:7475/db/data/") graph.cypher.execute("MATCH (n:_Network_Node)-[:Edge]-(x) WITH n, count(DISTINCT x) as degree SET n.degree = degree") # for record in res: # print record;
meters_that_will_be_landscaped = float(input()) the_price_for_landsacping = meters_that_will_be_landscaped * 7.61 discount = the_price_for_landsacping * 0.18 total_price = the_price_for_landsacping - discount print(f"the total price is {total_price}") print(f"discount is {discount}")
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-12-01 11:21 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migratio...
from boundingbox import BoundingBox import cv2 import numpy as np def preprocess(img, input_shape, letter_box=False): """Preprocess an image before TRT YOLO inferencing. # Args img: int8 numpy array of shape (img_h, img_w, 3) input_shape: a tuple of (H, W) letter_box: boolean, specifie...
import boto3 import pprint pp = pprint.PrettyPrinter() client = boto3.client('ec2') ec2 = boto3.resource('ec2') def get_all_vpcs(): return client.describe_vpcs()['Vpcs'] def get_vpc_by_name(vpc_name): matched_vpc = None vpcs = get_all_vpcs() for vpc in vpcs: names = [tag['Value'] for tag i...
from django.contrib import admin from .models import * class DoctorAdmin(admin.ModelAdmin): list_display = ('id', 'last_name', 'name', 'middle_name', 'image') search_fields = ('last_name',) class TitleAdmin(admin.ModelAdmin): list_display = ('id', 'title') admin.site.register(Title, TitleAdmin) admin....
data_path = "../data"
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE from awkward._v2.operations.structure.copy import copy # noqa: F401 from awkward._v2.operations.structure.mask import mask # noqa: F401 from awkward._v2.operations.structure.num import num # noqa: F401 from awkward._v2.operation...
from pathlib import PosixPath import numpy from osgeo import gdal from osgeo import osr from .image_output import SimpleImageOutput from .resampler import get_resampler from .utils import ensure_dir_exists, gdal_write class GDAL2Tiles: def __init__( self, source_path, output_dir, ...
from rest_framework import serializers from .models import Institute, Student, Batch, Paper, Section, Question, Exam, Result, AttemptedQuestion, BaseUser from django.contrib.auth.models import Group class BaseUserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BaseUser fie...
#!/usr/bin/env python3 import argparse from .generator import Generator def standalone(): """Standalone command for generating header and body input files """ parser = argparse.ArgumentParser( description="Generate header and body files for WF Dispatcher" ) parser.add_argument( "-b...
import helper class SHA256: msg = None chunks = None message_length = None def __init__(self, message): self.hasher = helper.Helper(message) self.msg = message self.message_length = len(message) def preprocess(self): self.hasher.pre_process() self.msg = s...
# Copyright (C) 2017 Zhixian MA <[email protected]> """ Get samples to train CNN Totally 21 samples, in which 17 are for training and 5 for test. """ import os import argparse import numpy as np import scipy.io as sio def main(): """The main function""" # Init parser = argparse.ArgumentParser(descripti...
""" Add something like this to your settings ANALYSIS_TIME_FRAME_TASKS = { "thermometer": { "name": "Thermometer", "frame_class_path": "twitter_feels.apps.thermometer.models.TimeFrame", }, "other": { "name": "Something Else", "frame_class_path": "some.other.OtherTimeFrame", ...
import numpy as np from typing import Any from typing import Dict from typing import List from typing import Type from typing import Tuple from typing import Union from typing import Callable from typing import Optional from cftool.misc import register_core from cftool.misc import shallow_copy_dict from cftool.misc im...
class PSPException(Exception): pass
# from https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetNPUsers.py # https://troopers.de/downloads/troopers19/TROOPERS19_AD_Fun_With_LDAP.pdf import requests import logging import configparser from binascii import b2a_hex, unhexlify, hexlify from cme.connection import * from cme.helpers.logger import...
""" Soak test for transport layer """ from logging import DEBUG, FileHandler from random import randrange from struct import unpack from time import time from min import MINTransportSerial, min_logger MIN_PORT = '/dev/tty.usbmodem1421' def bytes_to_int32(data: bytes, big_endian=True) -> int: if len(data) != 4:...
# Copyright 2019-2020 Alexander Polishchuk # # 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 required by applicable law or agreed t...
# -*- coding: utf-8 -*- """Basic unshare for udocker maintenance""" import os import ctypes import subprocess from udocker.msg import Msg from udocker.helper.hostinfo import HostInfo from udocker.helper.nixauth import NixAuthentication class Unshare(object): """Place a process in a namespace""" CLONE_NEWNS ...
''' Amresh Tripathy ''' import flask print ('Hello world')
#Find the average of keys of dictionary dic={1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} sum=0 count=0 for i in dic.keys(): sum+=i count+=1 print('Average is',sum/count)
from io import BytesIO import numpy as np from taichi.core import ti_core as _ti_core import taichi as ti def cook_image_to_bytes(img): """ Takes a NumPy array or Taichi field of any type. Returns a NumPy array of uint8. This is used by ti.imwrite and ti.imdisplay. """ if not isinstance(img,...
from functools import partial import json import responses from tamr_unify_client import Client from tamr_unify_client.auth import UsernamePasswordAuth project_config = { "name": "Project 1", "description": "Mastering Project", "type": "DEDUP", "unifiedDatasetName": "Project 1 - Unified Dataset", ...
correct = [[1, 2, 3], [2, 3, 1], [3, 1, 2]] incorrect = [[1, 2, 3, 4], [2, 3, 1, 3], [3, 1, 2, 3], [4, 4, 4, 4]] incorrect2 = [[1, 2, 3, 4], [2, 3, 1, 4], [4, 1, 2, 3], [3, 4, 1, 2]] incorrect3 = [[1, 2, 3, 4, 5], ...
from unittest import TestCase import networkx from six import StringIO from gtfspy.routing.connection import Connection from gtfspy.routing.label import min_arrival_time_target, LabelTimeWithBoardingsCount, LabelTime from gtfspy.routing.multi_objective_pseudo_connection_scan_profiler import MultiObjectivePseudoCSAPro...
import HAWC2_TCP def test_something(): assert 4 == 4
# coding=utf-8 """Write multidimensional data line by line""" from abc import ABCMeta, abstractmethod from copy import deepcopy import itertools import numpy as np from imagesplit.utils.utilities import to_rgb from imagesplit.image.image_wrapper import ImageWrapper, ImageStorage from imagesplit.utils.utilities import...
import requests import time import json from datetime import datetime import urllib.parse as urlparse from urllib.parse import parse_qs # import webhook_settings # import product_settings from threading import Thread from selenium import webdriver from chromedriver_py import binary_path as driver_path from lxml import ...
import time import board import neopixel pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.2, auto_write=False) rainbow_cycle_demo = 1 def colorwheel(pos): if pos < 0 or pos > 255: return (0, 0, 0) if pos < 85: return (255 - pos * 3, pos * 3, 0) ...
''' @Author: zm @Date and Time: 2019/8/8 15:14 @File: train.py ''' import math import numpy as np import tensorflow as tf from keras import backend as K from keras.layers import Input from keras import Model from keras.optimizers import Adam from keras.callbacks import Callback from Loss import Loss f...
""" Callables What are callables? Any obje """
# -*- coding: utf-8 -*- # (c) Copyright 2020 Sensirion AG, Switzerland ############################################################################## ############################################################################## # _____ _ _ _______ _____ ____ _ _ # / ____| ...
import logging.config import logging.handlers import os from pathlib import Path def get_logs_directory(): return Path(os.path.split(__file__)[0] + '/logs') def configure_logging(): logs_directory = get_logs_directory() if not logs_directory.exists(): logs_directory.mkdir() logging.config.d...
""" Defines TestUGrid """ from __future__ import print_function import os import unittest import numpy as np import pyNastran from pyNastran.bdf.bdf import read_bdf from pyNastran.converters.nastran.nastran_to_ugrid import nastran_to_ugrid from pyNastran.converters.nastran.nastran_to_ugrid3d import merge_ugrid3d_and_b...
import sys def get_logger_traceback(): # noqa """ Returns a traceback object for a log event. A traceback object is only available when an exception has been thrown. To get one for a log event we throw an exception and then wrap it in our own Traceback proxy that hides parts of the stack trace l...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # 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 required by applica...
import time import numpy as np from ezmodel.core.transformation import NoNormalization from ezmodel.util.misc import is_duplicate, at_least2d class Model: def __init__(self, norm_X=NoNormalization(), norm_y=NoNormalization(), active_dims=None, ...
# -*- coding: utf-8 -*- # A Survey on Negative Transfer # https://github.com/chamwen/NT-Benchmark import os.path as osp from datetime import datetime from datetime import timedelta, timezone from utils.utils import create_folder class LogRecord: def __init__(self, args): self.args = args ...
# -*- coding: utf-8 -*- from flask import Flask from flask_wtf.csrf import CSRFProtect from config import config # from vision import BoF import for_html # bof = BoF() # instantiate for_html for_html_real = for_html.for_html() csrf = CSRFProtect() def create_app(config_name): app = Flask(__name__) app.conf...
import psycopg2.extras import time import csvMaker connection = psycopg2.connect( host="localhost", port="5432", database="project1", user="dgy", password='xtny38206', ) connection.autocommit = True cursor = connection.cursor() def pre_process(file_name): start_time = time.time() supply...
import itertools import collections import time # Check to see if d1 matches d2 or any circular rotation of d2 def foo(d1,d2): for i in range(len(d1)): if d1==d2: return(True) d2.reverse() if d1==d2: return(True) d2.reverse() d2.rotate() return(Fa...
import csv import requests from bs4 import BeautifulSoup import re def get_html(url): r = requests.get(url) return r.text def write_csv(data): with open('cmc.csv', 'a') as f: writer = csv.writer(f) writer.writerow(( data['name'], data['url'], data['pric...
import subprocess import os import sys import os import argparse print "Downloading our Model" os.system("cd model ; wget https://www.dropbox.com/s/szpt9smob7mk8s4/model_id.t7?dl=0") parser = argparse.ArgumentParser() parser.add_argument("-imf", "--image_folder", help="Folder containing the images") parser.add_argu...