text
stringlengths
3.07k
12.6k
#------------------------------------------------------------------------------- # # Project: ngEO Browse Server <http://ngeo.eox.at> # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #------------------------------------------------------------------------------- # Copyright (C) 201...
"""Tests for models in the landingzones app""" from django.forms.models import model_to_dict from test_plus.test import TestCase # Projectroles dependency from projectroles.models import Role, SODAR_CONSTANTS from projectroles.tests.test_models import ProjectMixin, RoleAssignmentMixin # Samplesheets dependency from...
# -*- coding: utf-8 -*- import web from web.contrib import PyRSS2Gen import render_website import model import forms import logging from paginator import Paginator, PaginatorSearch from datetime import datetime from utils import break_string from google.appengine.api import mail urls = ( '', 'Index', '/', 'Inde...
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function import sys from hotline.command import Command from hotline.mode import Mode from hotline.constant import flags from hotline.contexts import best_context from hotline.widgets import Dialog from hotline.utils import execute_in_main_thread fro...
import torch from sklearn.model_selection import train_test_split from torch.utils.data import Dataset import numpy as np import os import pandas as pd from src.dataset.sampler import BalancedBatchSampler class CriteoDataset(Dataset): """ Custom dataset class for Criteo dataset in order to use efficient ...
import numpy as np import string import os import sys import operator from nltk import pos_tag, word_tokenize from datetime import datetime relative_path = '../../data/' def init_weight(Mi, Mo): """Initializes weights so that they are randomly distributed and have small enough values to prevent gradient desce...
import sys import cmd import types from inspect import signature from svm import stk_set, stk_get, dup, drop, swap, over, rot #TODO : unify interface using list of args. # combinators # Note how we apply only the immediate composition for B. def B(x, y, z): return x, y(z) def C(x, y, z): return x, z, y def ...
import numpy as np import pandas as pd from scipy import stats import pdb from ..utils import ClassUtils def default_params(): ''' :param n_bins: hard upper bound on the number of bins in the continuous component of the shmistogram :param prebin_maxbins: (int) pre-bin the points as you would in a...
from scipy.misc.pilutil import imresize import numpy as np __author__ = 'peter' def resize_while_preserving_aspect_ratio(im, x_dim=None, y_dim=None): """ Resize an image, while preserving the aspect ratio. For this you need to specify either x_dim or y_dim. :param im: The image: a 2D or 3D array. :p...
import json import os import random import re import shutil from string import ascii_lowercase, digits from typing import Optional, Dict import click from chino.cli.utils import touch from chino.io.fileio import load PAT = re.compile(r'^E(\d\d)(-.*|$)') # match Exx or Exx-xxxxx # entry point @click.group() def e...
import numpy as np import scipy.signal, scipy.linalg from .utils import * from .signal import * from .wavelets import * __all__ = ["allpass", "leja", "sfact", "selesnick_hwlet", "evenbly_white_hwlet"] def allpass(tau, L): """ Return the filter d[n] such that A(z) = z^{-L} D(1/z) / D(z) approximat...
import matplotlib.pyplot as plt import pickle import numpy as np from datetime import datetime from deap.tools.emo import sortNondominated # Functions for handling and analyzing # the population and logbook data def problemName(pop, logbook, stateName): n = pop[0].numberOfQubits NGEN = len(logbook.select...
# import SDF_module as sdf #legacy changed in (1/6/2021) import numpy as np import os import sys import matplotlib.pyplot as plt import csv import shutil #Alteration @ 1/6/2021 : Moved the SDF_module code here as i reckon it would be way #slower and more complicated to work with multiple modules and there was no point ...
# coding=utf-8 from flask_admin import expose from flask_babelex import gettext from flask_babelex import lazy_gettext from flask import url_for, request, flash, has_request_context from flask_admin._compat import as_unicode from flask_admin.contrib.sqla import ModelView from flask_admin.model.helpers import get_mdict...
import simpy import numpy as np def calculate_avg_original_time(num_robots, task_runtime_list, env): ''' Calculates the time required assuming all tasks are single-robot tasks. ''' num_tasks = len(task_runtime_list) total_time = 0 # First consider the case when there are at least as many robot...
from pathlib import PurePath from django.contrib.auth.mixins import LoginRequiredMixin from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.http import Http404 from django.shortcuts import redirect from django.views import generic from django.views.generic.base import ContextMixin...
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=missing-docstring """Test for the DAGCircuit object""" import unittest from qiskit.dagcircuit import DAG...
# Questo script e' il core del codice che faccimo girare sulle schede wifi con micropython # il sistema # import network as net import socket as sock # import machine import os import time # import ubinascii def log(message): print(message) # def get_ip_address(): # log('get local ip') # ip_address = '...
#!/usr/bin/env python3 import sys import re from subprocess import Popen, PIPE, DEVNULL PATCHRE = re.compile(r"patch ([\.a-z0-9_-]+)[ ]*:[ ]*(.*)", flags=re.IGNORECASE) def root(): cmd = ["git", "hash-object", "-t", "tree", "/dev/null"] r = b"" with Popen(cmd, stdout=PIPE, stderr=sys.stderr) as proc: ...
""" Video Classification with Channel-Separated Convolutional Networks ICCV 2019, https://arxiv.org/abs/1904.02811 Large-scale weakly-supervised pre-training for video action recognition CVPR 2019, https://arxiv.org/abs/1905.00561 """ # pylint: disable=missing-function-docstring, missing-class-docstring import torch im...
""" Module that contains the command line app. Why does this file exist, and why not put this in __main__? You might be tempted to import things from __main__ later, but that will cause problems: the code will get executed twice: - When you run `python -mpvct` python will execute ``__main__.py`` as a scrip...
from __future__ import annotations import os import re import subprocess from pathlib import Path from typing import List, Tuple import nox from nox.sessions import Session HERE = Path(__file__).parent POSARGS_PATTERN = re.compile(r"^(\w+)\[(.+)\]$") def get_posargs(name: str, session: Session) -> List[str]: ...
#!/usr/bin/env python ''' generate_db.py Author: <NAME> Helper script to generate databases for the knead_data.py pipeline Requires the BMTagger suite and NCBI BLAST. ''' import argparse import subprocess import shlex import os import sys import threading def exists(s_cmd): ''' Prints out error message with...
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b...
import time import datetime from rest_framework import viewsets, status from rest_framework.response import Response from django_filters.rest_framework import DjangoFilterBackend from .filters import SpecialtyFilter, DoctorFilter, AgendaFilter from .models import Specialty, Doctor, Agenda, MedicalAppointment from .s...
from . import Paper from Definitions import mm import Colour from graphics.cairo import Draw from graphics.cairo.Draw import LineStyle, FillStyle, TextStyle import Font class Stockmarket: margin = 10*mm def __init__(self, cells, has_par_box=False): self.game = None self.has_par_box = has_par_...
from typing import Dict import pytest from biome.text import Dataset from biome.text import Pipeline from biome.text import Trainer from biome.text import TrainerConfiguration from biome.text.modules.heads.task_prediction import Attribution @pytest.fixture def training_dataset() -> Dataset: """Creating the data...
# Copyright 2017-2020 <NAME> # # 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, ...
#!/usr/bin/env python3 from pylab import * from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np def load_var(dir, t, var, nx, ny, nz): x, y, n, dataRaw = np.loadtxt(dir + '/' + var + '_' + '{:.3f}'.format(t) + '.dat', unpack=True) data = np.reshape(dataRaw, (nx, ny, nz)) return squeez...
import argparse import datetime import functools import re import sys import traceback import typing import holidays import github class PennHolidays(holidays.UnitedStates): def _populate(self, year): super()._populate(year) # See https://github.com/greenelab/scrum/issues/114 for day in...
""" Support for OpenTherm Gateway devices. For more details about this component, please refer to the documentation at http://home-assistant.io/components/climate.opentherm_gw/ """ import logging import voluptuous as vol from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA, ...
#!/usr/bin/python3 # -*- coding:utf-8 -*- import RPi.GPIO as GPIO import time from datetime import datetime import logging # CONSTANTS LCD_WIDTH = 16 # Max line char width LCD_CHR = True LCD_CMD = False LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line LCD_LINE_2 = 0xC0 ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import colander from deform.widget import ( CheckboxWidget, SelectWidget, SequenceWidget, TextAreaWidget, TextInputWidget, ) from h import i18n from h.schemas import validators from h.models.group import ( GROUP_NAME_MIN_LENGTH, ...
import os import requests import string import sys # pip install beautifulsoup4 from bs4 import BeautifulSoup, NavigableString # pip install lxml from lxml import etree def format(str): return ' '.join(str.split()).replace('( ', '(').replace(' )', ')').replace(' .', '.').replace(' ,', ',').replace(' ;', ';').replace...
# this file for sync translation in github workflow import base64 import json import os import tempfile from operator import itemgetter from os import path, environ from string import ascii_uppercase from typing import List import gspread from gspread import Worksheet SHEET_URL = environ.get('SHEET_URL', ...
import os import json import argparse import re import logging logging.basicConfig( format="%(levelname)s - %(message)s" ) LOG = logging.getLogger() OS_EXCEPTIONS = { "macosx": "mac", "z/os": "zos", "sunos": "solaris", } ARCH_EXCEPTIONS = { "x64": "x86-64", "x86": "x86-32", } def transform_...
import os from typing import Optional from simplejson import OrderedDict import torch from torch import nn import numpy as np from einops import rearrange from typing import List from transformers import AutoModelForSequenceClassification from transformers.models.wav2vec2.feature_extraction_wav2vec2 import Wav2Vec2Feat...
import math from unittest.mock import MagicMock from cubelang.compiler.code_map import CodeMap from cubelang.compiler.parser import parser from cubelang.compiler.stack import Stack from cubelang.compiler.types import Integer, Function, Void, Real from cubelang.execution.executor import ExecutionContext, ITracebackWrit...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time import numpy as np import tensorflow as tf from tensorflow import flags from tensorflow import gfile from tensorflow import app from my_utils import mylog import my_utils #%% FLAGS = flags.FLAGS if __name__ == "__main__": flags.DEFINE_string("input_data_pat...
from pyteal import * def approval_program(): @Subroutine(TealType.none) def optinToken(asa: Int): return Seq( InnerTxnBuilder.Begin(), InnerTxnBuilder.SetFields( { TxnField.type_enum: TxnType.AssetTransfer, TxnField.xfer_a...
""" 2015-2016 <NAME> <EMAIL> """ import numpy as np import scipy as sp from scipy import sparse from lowrank_matrix import ManifoldElement from approximator_api import AbstractApproximator from manifold_functions import TangentVector, svd_retraction from manifold_functions import riemannian_grad_partial, delta_on_sigm...
__all__ = ["run", "sample"] import warnings from functools import partial from typing import List, Tuple import jax.numpy as jnp import numpy as np from jax import lax, local_device_count, pmap, random, vmap from jax._src.api import vmap from jax.tree_util import tree_flatten from rmhmc.base_types import Position, i...
#!/usr/bin/env python3 import argparse import os import os.path import tempfile import subprocess import signal import re import sys script_dir = os.path.realpath(sys.path[0]) logisim_location = os.path.join(script_dir, "logisim-evolution.jar") class LogisimTest(): """ Runs a circuit file and compares output aga...
import threading import multiprocessing from itertools import groupby import rethinkdb as r from bigchaindb import Bigchain import cryptoconditions as cc from server.lib.models.accounts import retrieve_accounts from server.lib.models.assets import escrow_asset, get_subcondition_indices_from_type, fulfill_escrow_asse...
import yaml import textwrap import sys from pathlib import Path import subprocess from src.common import * from src.nodes import Node, StructDefinitionNode from src import scope, typecheck def parse_additional(filename, include_path): # Directory of /serene/compiler/ compiler_dir = Path(__file__).parent.reso...
#!/usr/bin/env python3 import numpy as np from Core import RISM_Obj from dataclasses import dataclass, field import Util from scipy.special import spherical_jn @dataclass class DRISM(object): data_vv: RISM_Obj diel: float adbcor: float data_uv: RISM_Obj = None chi: np.ndarray = field(init=False) ...
import math import numpy as np import torch from sklearn.metrics import average_precision_score, roc_auc_score, f1_score def recall(node, rank, top_k): rank = rank[:, :top_k] recall = np.array([node[i] in a for i, a in enumerate(rank)]) recall = recall.sum() / recall.size return recall def MRR(node...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: <EMAIL> """ """ import yaml import os from enum import Enum from wush.common import constants from wush.common import utils from wush.common.files import FileUtils from wush.common.functions import load_module from wush.common.functions import super_function fro...
#!/usr/bin/env python """ Repartition a parquet file into tracts Author: <NAME> """ import os import multiprocessing as mp from argparse import ArgumentParser, RawTextHelpFormatter import numpy as np import pandas as pd from tqdm import tqdm import lsst.geom from lsst.daf.persistence import Butler import desc_dc2_dm...
# -*- coding: utf-8 -*- """ Read the Order details xlsx and extract data from it to the Order classes """ from openpyxl import load_workbook, Workbook from collections import OrderedDict ORDER_START_TOKEN = 'Line Item:' SIZE_BEGIN_TOKEN = 'Size' SIZE_END_TOKEN = 'Total Qty:' class StateError(Exception): def __i...
import tensorflow as tf import tempfile import pandas import os from tensorflow.python.framework import graph_util #tf.logging.set_verbosity(tf.logging.INFO) BASE_DIRECTORY = r"C:\Users\pshubham\Documents\IoT\liota-edge_intelligence\edge_intelligence_models" MODEL_BASE_DIRECTORY = os.path.join(BASE_DIRECTORY, 'saved...
#!/usr/bin/env python # -*- coding: utf-8 -*- # <EMAIL> # Standardization, cleaning, padding and embeddings - All Processing Functions import random import pandas import re import datetime import os import ujson as json import gensim from keras.preprocessing.text import text_to_word_sequence import datefi...
# LeetCode 663. Equal Tree Partition # # Given a binary tree with n nodes, your task is to check if it's possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree. # # Example 1: # # Input: # 5 # / \ # 10 10 # / \ # 2 3 # ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys from pathlib import Path import csv import html import re def list_func(func, iterator): for item in iterator: for res in func(item): yield res def parse_key(key_str): if not key_str: return [] en_p...
#!/usr/bin/env python3 #coding: utf-8 """ Copyright (c) 2021 Huawei Device Co., Ltd. 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 ...
''' Re-writing of solver for identical parallel machine with release dates, equal processing times and eligibility constraints Created in Feb 2nd. 2019 by JuneTech ''' import csv import datetime import os import timeit from tqdm import tqdm import greedy as grs import imr import lower_bound as lb import reader import...
#!/usr/bin/python import os import sys import getopt import shutil def printProgramBanner(): print("--------------------------------") print("Starting Python runtest script") print("--------------------------------") def printUsage(): print("test.py -h -g -v -G <gatesim_Type> -t <testn...
# coding:utf-8 import os.path import sys import re import os import json import tensorflow as tf import numpy as np from sklearn import preprocessing import pickle as pickle #python pkl 文件读写 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D class MyData(): def __init__(self): self....
from apispec import BasePlugin from apispec.exceptions import DuplicateComponentNameError from apispec.yaml_utils import load_operations_from_docstring from schematics.contrib.enum_type import EnumType from schematics.models import FieldDescriptor from schematics.types import ModelType, DictType, ListType, BooleanType,...
import os import pprint from collections import OrderedDict, defaultdict import numpy as np import torch from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.data import DataLoader from batch_engine import valid_trainer, batch_trainer from config import argument_parser from dataset.AttrDataset impo...
"""ROX applications should provide good drag-and-drop support. Use this module to allow drops onto widgets in your application.""" import rox from rox import g, alert, get_local_path, _ gdk = g.gdk TARGET_URILIST = 0 TARGET_RAW = 1 def extract_uris(data): """Convert a text/uri-list to a python list of (still escap...
#!/usr/bin/env python3 import os import sys import subprocess import re USAGE = """Usage: ./parallel_rsync <N> <from> <to> Documentation: <N> The number of transfers to perform in parallel <from>, <to> The directory to transfer from, or the output location to transfer to. E...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 13 14:51:29 2019 @author: nk7g14 This for some reason runs fine in the linux terminal but doesn't in the ipython one? https://heasarc.nasa.gov/ftools/caldb/help/uvotsource.html """ import logging import subprocess import glob from astropy.io import ...
# -*- coding: utf-8 -*- import time from odoo import models, api, fields from odoo.exceptions import UserError class HrLoanAcc(models.Model): _inherit = 'hr.loan' employee_account_id = fields.Many2one('account.account', string="Loan Account") treasury_account_id = fields.Many2one('account.account', strin...
""" Provides methods for serializing App Engine Datastore classes """ import calendar import datetime import time from google.appengine.api import users from google.appengine.ext import db, ndb, blobstore from google.appengine.datastore import entity_pb import json def parse(str): return json.loads(str, cls=Dat...
# __author__='ZHENGT' # -*- coding: utf-8 -*- import sys import requests import webbrowser import pandas as pd import urllib import json import csv import os import time import logging import traceback # reload(sys) # sys.setdefaultencoding('utf-8') # Python默认ascii,需要转成utf-8 # 39a9c50af2662024a1b11ccfd9384814 # 微信小...
from __future__ import print_function import collections import os import os.path import shutil from egnyte import exc, base, resources, audits, events class EgnyteClient(base.Session): """Main client objects. This should be the only object you have to manually create in standard API use.""" @property d...
import io import os import pickle as pk import shutil from pathlib import Path from pdb import set_trace import pandas as pd from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaIoBase...
import openpathsampling as paths from openpathsampling.ensemble import EnsembleCache def default_state_progress_report(n_steps, found_states, all_states, timestep=None): """ Default progress reporter for VisitAllStatesEnsemble. Note that it is assumed that all states have...
from Hidden_Markov_Model import * class DHMM_Model: def __init__(self,Train_ratio,Max_state,Iter,Feat,N,T,Data,N_symb): self.Train_ratio=Train_ratio self.Test_ratio=1-Train_ratio self.Max_state=Max_state self.Iter=Iter self.Model=[] self.Feat=Feat self.N=N ...
""" from hackerrank Given: non-empty arr of distinct integers And a target int Find all triplets in arr that sum up to target sum Return a 2D arr of all these triplets With each inner arr sorted in ascending order And triplets ordered in ascending order by first triplet el secondary: smallest 2nd el tertiary: smalle...
##################################### # <NAME> 2/28/18 # CSC 131-005 Lab 6 ##################################### # Semester GPA Calculation # Purpose: This program will calculate a student’s semester grade # by using the students previous credits/GPA and then asking the student ...
from django.shortcuts import render from django.db.models import Sum from pdl.models import Proyecto from pdl.models import Seguimientos from stats.models import ComisionCount from stats.models import Dispensed from stats.models import WithDictamenButNotVoted LEGISLATURE = 2016 def dame_sin_tramitar(numero_de_proy...
from collections import Counter, defaultdict import html import math from . import templates # Default configuration PLACEHOLDER = '~' # '~' is a placeholder for remaining characters TEXT0 = 'scrambled: <~>' # Text in HTML source TEXT1 = 'Email: <scrambled ~>' # Text shown in browser TEXT2 = 'Email: <EMAIL> <~>...
import argparse import os from pathlib import Path from GUM_Dispenser.GUM_Exceptions import InvalidSourcePathError, ConfigurationNotFoundError, PackageNotFoundError from GUM_Dispenser.GUM_Exceptions import SourceModuleNotFoundError, UserConfirmedInvalidSetup from GUM_Dispenser.GUM_setup_parser import parse_setup ...
from __future__ import division from __future__ import print_function import argparse parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100, help='Number of epochs to train.') parser.add_argument('--split',nargs='+', type=float, default=[0.9, 0.1, 0.], help="train, test, validation ...
from numba import jit import numpy as np import numbers from ectools.parallelization import parallel_wrapper # kernel definitions @jit(nopython=True) def norm_kernel(distances): """gaussian kernel""" # no gamma because bandwidth is calculated elsewhere return np.sqrt(np.pi / 2) * np.exp(-distances ** 2) ...
#!/usr/bin/env python3 # Copyright (c) 2018 <NAME> # All rights reserved. # Unauthorized redistribution prohibited. """SizeMatters: Maximize an image to the resolution limits imposed by Instagram. This script contains a single function to maximize an image based on Instagram's maximum resolution limitations (althoug...
import argparse import json import re from collections import defaultdict, Counter class HtmlWriter: def __init__(self, filepath): self.filepath = filepath self.html_header = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> <body>" self.html_colors = "<b...
import pdb import os import cv2 import time from glob import glob import torch import scipy import pandas as pd import numpy as np from tqdm import tqdm import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from argparse import ArgumentParser import albumentations from albumentations import torch...
#!/usr/bin/python2 """Management system for Cinch AI agents. The AI Manager itself blocks its thread after it is initialized. This is needed to maintain connection to a socket server, so AIManager should be started in a separate thread. The AI Manager provides two main functions: - It provides a list of available AI...
from zoomus import ZoomClient from lifeloopweb import ( config, exception as exc, logging) from lifeloopweb.db import models from lifeloopweb.helpers.base_helper import Helper MEETING_DRIVER = None CONF = config.CONF LOG = logging.get_logger(__name__) helper = Helper() class MeetingDriver(): def schedule_...
""" Simple Bitfinex Importer of trades BTC/USD 2020-05-24 45511322859 USD 44000 5 -176 """ # stdlib imports import dataclasses import typing import datetime from decimal import Decimal from collections import defaultdict # beancount imports from beancount.core import data, account from beancount.core.position import ...
# http://www.pymcu.com/PlayingSounds.html # rttl.py version 1.0.1 (ported version to pyS60) # import e32 import pitchy # RTTL variable to hold RTTL song #RTTL = 'Bond:d=4,o=5,b=50:32p,16c#6,32d#6,32d#6,16d#6,8d#6,16c#6,16c#6,16c#6,16c#6,32e6,32e6,16e6,8e6,16d#6,16d#6,16d#6,16c#6,32d#6,32d#6,16d#6,8d#6,16c#...
## # Copyright 2021 IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## from typing import Tuple, List, Union import torch import numpy as np from ..._utils import val_clamp from ..parameters.node import _NodeParameters """ Node level activation """ class _NodeActivation(_NodeParameters): ...
#! /usr/bin/env python # This file is part of khmer, https://github.com/dib-lab/khmer/, and is # Copyright (C) 2010-2015, Michigan State University. # Copyright (C) 2015-2016, The Regents of the University of California. # # Redistribution and use in source and binary forms, with or without # modification, are permitte...
import numpy as np import sympy as sp from scipy.integrate import ode, complex_ode from .qtools import Timer from .qstate import asQuantumState, QuantumStateError from .qoperator import asOperator, OperatorError, _t class QuantumSystem: """n-level quantum system""" def __init__(self, ham): self._H = a...
""" Recommender that uses ElasticSearch instead of mysql for searching. Based on mixed recommender. Still uses MySQL to find relations between the user and things such as: - topics, language and user subscriptions. """ from elasticsearch import Elasticsearch from zeeguu.core.model import ( Article, To...
""" MBD-LLBorder """ from functools import partial from itertools import combinations import numpy as np import pandas as pd from joblib import Parallel, delayed from ..base import BaseMiner, DiscovererMixin from ..itemsets.lcm import LCMMax from ..utils import _check_growth_rate, _check_min_supp, filter_maximal, fil...
from __future__ import unicode_literals import os import time import json import logging import requests from nose.tools import assert_equals, assert_true, assert_is_not_none, assert_is_none, assert_false RETRIES=100 TIMEOUT=3 def wait_for_automation_server(): logger.info('waiting for automation server') co...
#! /usr/bin/env python """Applies a ccbid model to new data """ import sys import numpy as np import pandas as pd import ccbid from ccbid import args from ccbid import prnt from sklearn.preprocessing import StandardScaler # set up the argument parser to read command line inputs def parse_args(): """Function to...
# # Copyright 2019 <NAME> # # 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, soft...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path.append('/storage/.kodi/addons/virtual.rpi-tools/lib') sys.path.append('/storage/.kodi/addons/script.module.pyserial/lib') import xbmcaddon import xbmcgui import subprocess import time import os import serial monitor = xbmc.Monitor() Cancel = False statu...
'Class for a Pyomo vector and a Spin object which is derived from PyomoVector' from __future__ import division from pyomo.environ import sqrt, value, cos, sin, acos, atan import numpy as np class PyomoVector(object): '''Generic vector object which stores both the Cartesian and Spherical components of the v...
import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from isab_pytorch import ISAB # helpers def exists(val): return val is not None def batched_index_select(values, indices): last_dim = values.shape[-1] return values.gather(1, indices[:, :, None...
# Copyright 2021 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...
''' extract_stats.py - extract and process tables from csvDB ======================================================== Purpose ------- Extract tables from sqlite databases and process Usage ----- .. Example use case Example:: python extract_stats.py Type:: python extract_stats.py --help for command line h...
#!/usr/bin/env python3 # # Compiles a bash command to read a file down to use only the following # characters: # []$<\_ # for the CTF puzzle at [1]. See bashell.bash for the output. # # Many techniques borrowed from [2]. # # [1] https://ctftime.org/task/12955 # [2] https://hack.more.systems/writeup/2017/12/30/34c3ct...
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """CFG file reader """ __version__ = '0.0.1' __date__ = '2021-06-19' __author__ = '<NAME>' __all__ = ['CFG', 'CFGProp'] ####################################################################################### from collections import namedtuple import io, os, re from ...
import json from glob import glob import numpy as np import pytorch_lightning as pl import torch from audio_processing import random_crop from prepare_data import get_id_from_path from pytorch_lightning.loggers import TensorBoardLogger from sklearn.model_selection import train_test_split from torch.nn import functiona...