text
stringlengths
3.07k
22.1k
# # Copyright 2018 the original author or authors. # # 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...
# import ## batteries import re import os import sys import gzip import tempfile import multiprocessing import argparse import logging import urllib import tarfile ## 3rd party import pandas as pd ## package from leylab_pipelines import Utils # logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s...
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merg...
from __future__ import annotations import functools from copy import copy, deepcopy from typing import Callable, Dict, List, Union import numpy as np from joblib import Parallel, delayed from scipy.stats import rankdata from sklearn.decomposition import PCA from sklearn.metrics import mean_absolute_percentage_error, ...
''' Some entities are composed of other ones. For the user, it can be a pain if you simply display the form. Consider applying for a job. Yes we want to record the date but critically we need to know the position and the company. This program presents composite entities in sequence. In this example, we first ask for t...
#docker run --rm -it -v D:\Informacion\Documents\Repositorios\Id_random_generation:/home ocr_server2 python /home/txt_generation.py -i /home/colombian_id.png -n 1000 # -*- coding: utf-8 -*- import time import copy start = time.time() import cv2 import argparse import shutil import os from PIL import ImageFont, ImageDra...
"""A local scheme example for the Knapsack Problem. Usage: Generate the instances: python3 knapsack.py -a generator -i instance Run the algorithm on an instance: python3 knapsack.py -i instance_100.json -a iterated_local_search -c sol.json """ import localsearchsolverpy import json import random random.seed(0) ...
import math from functools import reduce from matplotlib import cm from matplotlib.colors import Normalize import numpy as np L = 1.000001 OVERFLOW = 10**20 quadabs = lambda z: z.real * z.real + z.imag * z.imag def differentiate(p): n = len(p) - 1 return [(n - i) * an for (i, an) in enumerate(p[:-1])] def h...
import cv2 as cv import numpy as np from Algorithm.propagationLabel import getEdgesFromLabel, evaluateMeritForEdge from skimage.measure import label import matplotlib.pyplot as plt from skimage import feature,morphology import time import os def meanGray(gray, threshold): lowSum = 0.0 lowNum = 0 highNum = ...
import datetime import logging from uuid import uuid4 from django.conf import settings from django.contrib import messages from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.core.mail import send_mail from django.core.exceptions import ValidationError fr...
import os import json import re import subprocess from common.checks import ( SVC_EXPR_TEMPLATES, DPKGVersionCompare, ) from common.cli_helpers import CLIHelper, get_ps_axo_flags_available from common.searchtools import ( FileSearcher, SearchDef, SequenceSearchDef, ) from common.issue_types import...
#!/usr/bin/env python3 import argparse import asyncio import json import logging import os import pprint import requests import socket import sys import threading import time import urllib3 import websockets from datetime import datetime, timedelta from python_graphql_client import GraphqlClient from prometheus_client...
# -*- coding: utf-8 -*- """ Created on Fri Oct 13 15:37:55 2017 @author: ekrupczak on LaVision Import file run list in human-readable text file (which has some specific extra tabs for lines of different widths) and save as a csv that can be read by eg Excel """ import pandas as pd import os import re def read_runfil...
""" A module which implements Boolean model logic, mainly process_query() function. dataset_names() and publish_file_for_5_minutes_and_return_url() are aux function for smooth runnning. """ from typing import Dict, List, Set, Union import logging import os import re import time import aiobotocore import nltk import ...
### Theorem proving on the Peano axioms import heapq as hp from utils import * ## Proof algorithm # estims memoizes heuristics and updates them through landmarks # since default arguments refer to one object, the memoization will be carried over across multiple calls to proof def prove(stmt, epsilon = 1, estims = {}...
""" Main project source file. """ from typing import List, Tuple from actor import Actor from data_plotting import plot_accumulated_actor_graph, plot_accumulated_edges_graphs from simulator import Simulator from graph import RoadGraph from queue import PriorityQueue from utils import softmax_travel_times, compute_aver...
import math import torch from torch import nn from torch.autograd import Variable from torch.nn import LSTMCell from torch.nn import Parameter class LSTMCell(nn.Module): r"""A long short-term memory (LSTM) cell. .. math:: \begin{array}{ll} i = \mathrm{sigmoid}(W_{ii} x + b_{ii} + W_{hi} h +...
#!/usr/bin/env python '''Farmware Tools: Web App.''' from __future__ import print_function import os import sys import time import json import base64 import requests from .aux2 import Color COLOR = Color() def _get_required_info(): 'Get the info required to send an HTTP request to the FarmBot Web App.' toke...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 """SageMaker configuration parsing for Amazon Textract LayoutLM """ # Python Built-Ins: from dataclasses import dataclass, field import os import tarfile from typing import Optional # External Dependencies: from tran...
from docx.api import Document from collections import defaultdict import win32com.client as win32 from time import sleep #define um periodo de tempo entre uma ação e outra from tqdm import tqdm #adiciona uma barra de "loading" import glob import csv import os import pandas as pd import re resultado = pd.Dat...
import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import os import numpy as np import datetime from statsmodels.tsa.vector_ar.var_model import VAR from sklearn import linear_model from libs import utils, metrics, data_common, graph_common import time import sys def main(args): for i in range(a...
"""Contains training loops.""" import os import tensorflow as tf import numpy as np from tqdm import tqdm from args import TrainArgParser from util import DiceVAELoss, DiceCoefficient, ScheduledOptim from model import Model def prepare_dataset(loc, batch_size, prepro_size, crop_size, out_ch, shuffle=True, data_forma...
import unittest import itertools class DirectionCode: NorthWest, NorthEast, SouthWest, SouthEast = 1, 2, 3, 4 class ImagePrecompute: def __init__( self, imagePixels ): rows, cols = len( imagePixels ), len( imagePixels[ 0 ] ) assert rows > 0 and cols > 0 precomputeList = [ [ 0 for _ in range( cols ) ] for _ i...
import os import json import time import numpy as np from nbconvert.preprocessors import (ExecutePreprocessor, CellExecutionError, ClearOutputPreprocessor) from nbconvert.exporters import RSTExporter from nbconvert.writers import FilesWriter import nbformat import re impor...
""" Johns Hopkins University Center for Systems Science and Engineering (JHU CSSE) """ import dateutil.parser from .request_jhu import Request_JHU from datetime import datetime, timedelta from cachetools import cached, TTLCache from app.helpers import sorted_history_date, formated_date, data_country_by_province from ap...
""" Tip: in your editor, set a ruler at 80 characters. """ import inspect from textwrap import dedent from typing import Optional import click import pytest from cloup import HelpFormatter from cloup.typing import Possibly from cloup.formatting import HelpSection, unstyled_len from cloup.formatting.sep import ( H...
############################################################################## # # Copyright (c) 2002, 2015 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED...
import sys import os import re import shutil import time import xml.etree.ElementTree as et import logging # Logging logging.basicConfig(stream=sys.stderr, level=logging.INFO) # RELEASE # logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) # DEBUG def pause_exit(): ## DEBUG os.system('pause') #DE...
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # 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 applicab...
#SBaaS base from SBaaS_base.postgresql_orm_base import * class data_stage03_quantification_dG0_f(Base): __tablename__ = 'data_stage03_quantification_dG0_f' id = Column(Integer, Sequence('data_stage03_quantification_dG0_f_id_seq'), primary_key=True) reference_id = Column(String(100)) met_name = Column(St...
import numpy as np try: import cairo except: import cairocffi as cairo from enum import Enum import copy from animlib.utils.points import convertToPoints, sliceBezier from animlib.utils.colors import convertToColor, ColorComponent class Center(Enum): BY_POINTS = 0 BY_OUTLINE = 1 class Direction(Enum)...
from configparser import ConfigParser from datetime import datetime from os import name, system from os.path import isfile from pathlib import Path from colorama import Fore, Style from app.__version__ import __version__ w = Style.BRIGHT + Fore.WHITE BAD = f" {w}[{Fore.RED}x{w}]" GOOD = f" {w}[{Fore.GREEN}+{w}]" INF...
import json import os import traceback from datetime import datetime import time import pandas as pd from tqdm import tqdm from wikidataintegrator import wdi_core, wdi_helpers from scheduled_bots.interpro import remove_deprecated_statements from scheduled_bots.interpro.IPRTerm import IPRTerm from wikidataintegrator.r...
#!/usr/bin/env python3 import sys import time import numpy as np import subprocess as sp from pdfflow.configflow import DTYPEINT as pint import tensorflow as tf from vegasflow.vflow import vegas_wrapper from pdfflow.pflow import mkPDF from vegasflow.configflow import DTYPE, DTYPEINT, float_me from pdfflow.configflow im...
# -*- coding: utf-8 -*- """ Solar utilities based on `SOLPOS <http://rredc.nrel.gov/solar/codesandalgorithms/solpos/>`_ and `SPECTRL2 <http://rredc.nrel.gov/solar/models/spectral/>`_ from `NREL RREDC Solar Resource Models and Tools <http://www.nrel.gov/rredc/models_tools.html>`_ 2013, 2019 SunPower Corp. """ import c...
import random from intbitset import intbitset from sqlite3 import IntegrityError from typing import Iterable, List, Set, Tuple, Union from core.questions import Question, get_questions from core.songs import Song from core.users import User from util import io from util.db.db import ApplicationDatabase, ApplicationDa...
# Copyright (c) 2021 PaddlePaddle 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 applic...
import datetime import json import tempfile import uuid from collections import Mapping from urllib.parse import urlparse import redis from hestia.auth import AuthenticationTypes from mock import patch from rest_framework import status from rest_framework.authtoken.models import Token from django.conf import settin...
"""Handle Leica experiment.""" import re from itertools import chain from pathlib import Path from typing import List, Mapping, Optional, Union from dataclasses import dataclass _SLIDE = "slide" _CHAMBER = "chamber" _FIELD = "field" _IMAGE = "image" _ADDITIONAL_DATA = "AdditionalData" _SCANNING_TEMPLATE = r"{Scanning...
"""#### GUI Module gathers all functions, classes and methods necessary to create GUI. Its parts are divided for separate blocks represented by classes `Search`, `Form`, `Buttons` and `Image` where each of them extends `tkinter.Frame`. `Searchbox` is extended `tkinter.Combobox` class to application needs. `Gui` connec...
from re import S from time import sleep import mouse import pygetwindow import logging import pyautogui import datetime # --------------------------------------------------- # Properties # --------------------------------------------------- KEEP_ALIVE_SEC = 300 FARM_CICLE = 10 WAIT_SEC = 1.5 WAIT_SIGN_IN = 10 SCROLL_...
# coding=utf-8 # Copyleft 2019 project LXRT. import os import collections import random import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader from tqdm import tqdm from param import args from pretrain.qa_answer_table import load_lxmert_qa from tasks.vqa_model import VQAModel from task...
""" Created by <NAME> on September 23, 2019 Display performance of Sammut et. al. benchmark """ import torch import sys import torch.nn as nn import torch.nn.functional as F sys.path.insert(0, '/home/Anonymous/PycharmProjects/bayesian_prolo') import numpy as np from torch.autograd import Variable from utils.naive_ut...
# Copyright (c) 2017 Adafruit Industries # Author: <NAME> & <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, cop...
__author__ = 'qchasserieau' import pandas as pd from tqdm import tqdm def print_if_debug(to_print, debug): if debug: print(to_print) def build_connection_dicts( link_array, origin_column, destination_column, start=0, first_only=True, connection_time=False, footpath_list=froz...
from typing import List from dataclasses import dataclass from board import BoardConfig, Stone @dataclass class EndCheck: is_end: bool is_tie: bool class Referee: def __init__(self): # direction: / self.direction_positive = [ lambda x, y: (x + 1, y + 1), lambda x,...
#!/usr/env/bin python3 """ build custom reference with plasmid and spike-in RNA sequences, for Nocturnin overexpression sequencing analysis. The custom reference includes: New custom reference GTF: 1) pFC3F GST plasmid exon-intron features, from customized file: overexpression.gtf 2) pFC3F NOCT del 2-15 plasmid exon...
# Copyright (c) 2020 Software AG, # Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, # and/or its subsidiaries and/or its affiliates and/or their licensors. # Use, reproduction, transfer, publication or disclosure is prohibited except # as specifically provided for in your License Agreement with Softwar...
import gym from gym import spaces from gym.utils import seeding import numpy as np from enum import Enum import matplotlib.pyplot as plt import logging class Actions(Enum): """List of possible actions""" Sell = 0 Buy = 1 class MyStocksEnv(gym.Env): """Class for trading""" def __init__(self, df...
from freezegun import freeze_time from app.dao import dao_create_record from app.models import MAGAZINE, TICKET_STATUS_UNUSED, OrderError from app.utils.time import get_local_time from tests.db import ( create_article, create_book, create_event, create_email, create_fee, create_order, creat...
import logging import random from types import CodeType, new_class import uuid import os from flask import Blueprint, jsonify, session, request, current_app from datetime import datetime, timedelta from decimal import Decimal from sqlalchemy.sql.expression import null from app.models.model import Class, StuCls, Studen...
# Read the output of video mining: txt file with predictions in fddb format and convert to a json import re import os import sys import cv2 import json import time import random import pickle import imutils import tempfile import subprocess import numpy as np import multiprocessing import _init_paths from utils.face_...
""" repo.py contains code to control the local cache for umpire. It is not a module. """ #TODO: Add support for tbz/tar.bz import os, shutil, time, traceback import configparser import maestro.tools.path import maestro.tools.file import maestro.core.module from . import unpack from maestro.tools.os_tools import check_...
"""Handles scaling of EC2 instances within an ECS cluster.""" import logging from typing import List, Tuple from . import ecs_client, asg_client from .exceptions import ClusterARNError, ASGGroupError, MissingResourceValueError from .services import Service logger = logging.getLogger() logger.setLevel(logging.INFO) ...
from operator import itemgetter import pytest import nltk.ccg.lexicon as lex from nltk.ccg.api import Direction, FunctionalCategory, PrimitiveCategory from nltk.ccg.lexicon_builder import LexiconBuilder from nltk.sem.logic import ConstantExpression, IndividualVariableExpression, LambdaExpression, Variable # TODO: tes...
"""A restricted Hartree-Fock script using the Psi4NumPy formalism that accounts for molecular symmetry using symmetrized orbitals. References: - SCF Algorithm taken from [Szabo:1996] (pp. 146) - SCF Equations taken from [Szabo:1996] - Symmetry-specific details taken from https://github.com/CrawfordGroup/ProgrammingPro...
import numpy as np from error import exit_w_error from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from scipy.stats import multivariate_normal def bayes_classifier(RangeX1=None): """ ARGS: RangeX1 = [min, max] RETURN: A list of points that are approx equal to the oran...
""" ============================================================================== A simple parsing script Author: <NAME> create a excel document with [File | Function name | Locale | line number] ============================================================================== """ # imports import datetime ...
# Copyright Amazon.com Inc. or its affiliates. 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. A copy of the # License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanyin...
#!/usr/bin/env python # Copyright (c) 2014 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Scan online binary packages to produce new package index. This script is indended to be run periodically and the results ch...
from cleverhans.attacks import FastGradientMethod from cleverhans.attacks_tf import fgm import tensorflow as tf import cleverhans.utils as utils import cleverhans.utils_tf as utils_tf import collections from cleverhans.model import Model, CallableModelWrapper import numpy as np class MyFastGradientMethod(FastGradient...
#!/usr/bin/env python # -*- coding: utf-8 -*- __ver_major__ = 0 __ver_minor__ = 2 __ver_patch__ = 1 __ver_sub__ = "" __version__ = "%d.%d.%d" % (__ver_major__, __ver_minor__, __ver_patch__) """ Extremely-fast parser for HTTP headers and some tools. This module contains: 1. Fast parser for http headers from file-lik...
import oci import pytz import json # def get_metric_data(compartment,namespace,query,starttime,endtime, monitoring_client): summarize_metrics_data_response = monitoring_client.summarize_metrics_data( compartment_id=compartment, summarize_metrics_data_details=oci.monitoring.models.SummarizeMetricsDa...
import os import re import types import string import django django.setup() from decimal import Decimal as D from django.template import Context, Template from django.test.client import Client from django.test.utils import setup_databases, teardown_databases from django.urls import reverse from django.utils.translatio...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import accuracy_score class MaskedSoftmax(nn.Module): def __init__(self): super(MaskedSoftmax, self).__init__() self.softmax = nn.Softmax(1) def forward(self, x, mask=None): """ ...
from functools import partial from multiprocessing import Pool import numpy as np from scipy.stats import norm # for calculating normpdf, normcdf from scipy import optimize # for optimisation from pyDOE import lhs # Latin hypercube sampling #import scipydirect # for minimisation def EI( best_prev, mean_x, std_x, min_...
#!/usr/bin/env python from __future__ import print_function import cProfile import pstats import os import numpy as np from pddlstream.algorithms.downward import TOTAL_COST from pddlstream.algorithms.focused import solve_focused from pddlstream.utils import clear_dir, ensure_dir from examples.continuous_tamp.constr...
""" This example is meant to demonstrate how you can map complex functions using a single input and single output with polynomial synaptic weights """ import matplotlib.pyplot as plt import numpy as np import torch from torch.nn import functional as F from torch.utils.data import DataLoader, Dataset from pytorch_lightn...
import glob import json import logging import multiprocessing import os import pickle import numpy as np import pandas as pd from sklearn.model_selection import KFold import config import dzn_eval logger = logging.getLogger('combination-learning') def flatten(lst): flattened = [] if not isinstance(lst, (l...
''' This script contains generic functions for working with the ProofWriter dataset format. ''' from helper import * class Node: def __init__(self, head): self.head = head def __str__(self): return str(self.head) def get_proof_graph(proof_str): # The proof parsing function is taken from https://github.com/...
#! /usr/bin/python # -*- coding: utf-8 -*- import ast import pickle import numpy as np import os import socket import sys import importlib from datetime import datetime import theano as th import theanet.neuralnet as nn ################################ HELPER FUNCTIONS ############################ def share(data, d...
"""Network presence adapter for WebThings Gateway.""" import re import time import datetime #import dateutil.parser from gateway_addon import Device, Action from .presence_property import PresenceProperty class PresenceDevice(Device): """network presence device type.""" def __init__(self, adapter, _id, nam...
import io import os import sys import time from portalocker import LOCK_EX, lock, unlock from contextlib import contextmanager from secrets import randbits from logging.handlers import BaseRotatingHandler, TimedRotatingFileHandler from logging import FileHandler _MIDNIGHT = 24 * 60 * 60 # number of seconds in a da...
# from __future__ import absolute_import import sys sys.path.append('./') import argparse import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import os.path as osp import numpy as np import math import time import torch from torch import nn, optim from torch.backends import cudnn from torch.utils.data import DataLoad...
# -*- coding: utf-8 -*- # # rtk.gui.gtk.workviews.Revision.py is part of the RTK Project # # All rights reserved. # Copyright 2007 - 2017 <NAME> <EMAIL>rew.rowland <AT> reliaqual <DOT> com """Revision Work View.""" import locale from pubsub import pub # pylint: disable=E0401 # Import other RTK modules. from g...
import cv2 import time import glob import json import random import numpy as np import pandas as pd from pathlib import Path import torch from torch.utils.data import Dataset from src.folds import make_folds from src import config def load_pseudo_label(path): pseudo_label_dict = dict() if path is not None: ...
# # THE INVESTMENT GAME # VERSION 2.0 # # Programmer: <NAME> # Date: 25 April 2017 # # This program will simulate the stock and bond markets, and # shows how little an investor can make if they only keep their # money in the bank. # # Note: The bonds and stocks are based on real...
from challenge.agoda_cancellation_estimator import AgodaCancellationEstimator from sklearn import model_selection from sklearn.metrics import confusion_matrix, roc_curve, auc, roc_auc_score, accuracy_score import re import numpy as np import pandas as pd ID_COLS = ['h_booking_id', 'hotel_id', 'hotel_country_code', '...
# Copyright (c) 2019, CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribu...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
import collections import os import torch import tqdm import logging import numpy as np import torch.nn as nn from torch.utils.data import DataLoader, ConcatDataset, ChainDataset from uniter_model.data.loader import PrefetchLoader from dvl.data.itm import TxtTokLmdb, ItmFastDataset, ItmValDataset, itm_fast_collate fro...
import numpy as np import json import codecs import torch from tqdm import tqdm from others.utils import rouge_results_to_str, test_rouge, avg_rouge_f1 class ExtDecider: def __init__(self, logger): self.logger = logger self.labels = [] self.sel_scores = [] self.sel_ids = [] ...
from scapy.utils import RawPcapReader from scapy.all import PcapReader, Packet from scapy.layers.l2 import Ether from scapy.layers.inet import IP, TCP import scapy.contrib.modbus as mb from scapy.fields import ( ConditionalField, Emph, ) from scapy.config import conf, _version_checker from scapy.base_classes im...
# # Flattened Device Tree Parser # Interpret a compiled flattened-device-tree file (.dtb) # # Copyright 2014 - <NAME> <<EMAIL>> # import sys class FDTTags(object): BEGIN_NODE = 1 END_NODE = 2 PROP = 3 NOP = 4 END = 9 # textual names for the states name = [ '', 'BEGIN_NODE', 'END_NO...
# -*- coding: utf-8 -*- import operator import warnings from collections import Counter from os import environ, makedirs from os import system, popen from os.path import join, exists import re import keras.backend as K import matplotlib as mpl import numpy as np import pandas as pd from scipy.io import mmread import s...
# Copyright (c) 2021 Huayun Inc. # hostha is licensed under Mulan PSL v2. # You can use this software according to the terms and conditions of the # Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # http://license.coscl.org.cn/MulanPSL2 # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANT...
__package__ = 'puppytypes' VARID = 0 VARS = {} def initTypeVars(): global VARS VARS = {} def newTypeVar(): global VARID VARID += 1 return f'_{VARID}' def unique(t, a=newTypeVar(), b=newTypeVar()): if isinstance(t, tuple): return tuple([unique(x, a, b) for x in t]) elif isinsta...
# coding: utf-8 # In[1]: import math import random import numpy as np # In[2]: def get_input(x): temp = [] for i,v in enumerate(x): temp.append([v,i]) return temp def chainHash(InputList, Leafs): res = {} for tup in InputList: if tup[0] not in res: temp = [] ...
""" Alternating Least Squares for Collaborative Filtering """ # Author: <NAME> <<EMAIL>> # License: MIT import numpy as np import scipy.sparse as sp import six GOT_NUMBA = True try: from pyrecsys._polara.lib.hosvd import tucker_als except ImportError: GOT_NUMBA = False __all__ = ['ALS', ] #################...
import json from operator import itemgetter from mmif import Mmif import names from utils import compose_id from utils import flatten_paths, print_paths class Graph(object): """Graph implementation for a MMIF document. Each node contains an annotation or document. Alignments are stored separately. Edges be...
import os import json import tornado.ioloop import tornado.log import tornado.web from google.oauth2 import id_token from google.auth.transport import requests as google_requests import jwt import requests import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as plt...
# -*- coding: utf-8 -*- """ Created on Wed Apr 18 13:53:28 2018 @author: sreimond """ import os import numpy as np import csv from picasso.utils.dates_and_time import date_functions from PyQt5.QtWidgets import * from PyQt5.QtCore import QDate, QTime import logging def initialize_project_settings(): project_data ...
import warnings from random import sample from typing import List, Iterable, Optional, Union, Tuple import math import numpy as np import pandas as pd import torch import torch.utils.data from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from scipy.stats import stats as spstats from collections im...
import os import pickle import argparse from PIL import Image import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms from train import environment_loader import utilities as utilities from utilities.build_vocab i...
import sqlite3 import time from datetime import date connection = None cursor = None answer_id = '1001' vote_number = 1001 def connect(path): global connection, cursor connection = sqlite3.connect(path) cursor = connection.cursor() cursor.execute(' PRAGMA foreign_keys=ON; ') co...
import torch from torch.functional import Tensor import torch.nn as nn import torch.nn.functional as F from utils.algorithms import SLE, FLE import numpy as np def build_ESN(H=200, d=3, lambda_coeff=0.4, dym_sys=3, sigma_in=0.15, activation="Tanh", output_size="3", device="cpu"): model = ESN() model.build_mode...
from datetime import timezone from functools import lru_cache, wraps from typing import List, Optional import numpy as np from pandas import Index, MultiIndex, Series, set_option from pandas.core import algorithms from pandas.core.arrays import DatetimeArray, datetimes from pandas.core.arrays.datetimelike import Datet...
""" This class holds the basic ui class for a session ui """ import os import imp from os.path import expanduser from PySide2 import QtWidgets, QtCore, QtGui import session from ui.workFile import session_form import env_config from ui.helperWidgets import pathWidget class SessionUi(QtWidgets.QMainWindow, session_f...
import logging from django.conf import settings from django.test import TestCase from django.test import Client from mezzanine.blog.models import BlogCategory from mezzanine.blog.models import BlogPost from mezzanine.core.models import CONTENT_STATUS_PUBLISHED, CONTENT_STATUS_DRAFT from mezzanine.pages.models import ...
import sys sys.path.append('../or-tools-6.7.2-customized/ortools/gen') import csv, datetime, glob, os, shutil, time from random import randint import RBGenerator import solverConstructor_RBGenerator from ortools.constraint_solver import pywrapcp # Config training_pool_size = 1000 testing_pool_size = 200 warmup_insta...