text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
#
# Copyright (C) 2018 <NAME> <<EMAIL>>
# Copyright (C) 2019-2021 <NAME> <<EMAIL>>
#
# 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 witho... |
from manimlib.imports import *
class CodeLine(Text):
CONFIG = {
't2c': {
'RIGHT': ORANGE,
'LEFT': ORANGE,
'DOWN': ORANGE,
'UP': ORANGE,
'UR': ORANGE,
'UL': ORANGE,
'DR': ORANGE,
'DL': ORANGE,
'ORIGI... |
import kvenjoy.gap
import kvenjoy.gfont
from kvenjoy.graph import *
def variable_to_json(var):
"""Converts a Variable object to dict/json struct"""
o = {}
o['x'] = var.x
o['y'] = var.y
o['name'] = var.name
return o
def variable_from_json(jo):
"""Converts a dict/json struct to a Variable o... |
import os
def gaff(path_coord, path_output, res_name="UNK", generate_charges='bcc'):
"""
Starting from a mol2 file (other file formats available) containing ONE molecule it generates a GAFF forcefield
and perform non-periodical energy minimization of the isolated molecule.
:param path_coord: path of t... |
'''Main tkinter gui'''
import io
import os
import platform
import queue
import sys
import threading
import time
import tkinter
from tkinter import *
from tkinter.ttk import *
import surgeo
class StdoutRedirect(threading.Thread):
'''This shunts stdout data to a queue that feeds a tkinter.Text window.'''
de... |
# coding=UTF-8
from pygramadan.attributes import Mutation, VPPerson, VPPolarity, VPShape
from pygramadan.attributes import VPTense, VerbDependency, VerbMood
from pygramadan.attributes import VerbPerson, VerbTense
from pygramadan.verb import init_moods, init_tenses, Verb, get_example
from pygramadan.forms import Form
fr... |
#! encoding = utf-8
import os
import time
import visa
class InstrumentErrorException(Exception):
def __init__(self, errors):
# Call the base class constructor with the parameters it needs
message = ''
if errors is not None and len(errors) > 0:
message = ''.join(errors)
... |
import discord
from discord.ext import commands
import aiohttp
orange=discord.Color.orange()
class Info(commands.Cog):
def __init__(self,bot):
self.bot=bot
@commands.command()
async def avatar(self, ctx, user: discord.Member = None):
if user is None:
user = ctx.author
embed = discord.Embed(ti... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Instalog plugin base.
Defines plugin classes (buffer, input, output), and a PluginAPI interface for
plugins to access.
"""
import inspect
import logg... |
import collections
import logging
from typing import Dict, Iterable
import click
import spectrum_utils.spectrum as sus
import tqdm
import ms_io
import selector
logger = logging.getLogger('cluster_representative')
def get_cluster_spectra(spectra: Dict[str, sus.MsmsSpectrum]) \
-> Iterable[Dict[str, sus.Msm... |
from nose.tools import eq_
from nose.tools import raises
import unittest
def test_cache_control_object_max_age_None():
from webob.cachecontrol import CacheControl
cc = CacheControl({}, 'a')
cc.properties['max-age'] = None
eq_(cc.max_age, -1)
class TestUpdateDict(unittest.TestCase):
def setUp(se... |
import argparse
import os
import time
import numpy as np
from mypath import Path
from dataloaders import make_data_loader
from utils.loss import SegmentationLosses
from utils.calculate_weights import calculate_weigths_labels
from utils.lr_scheduler import LR_Scheduler
from utils.saver import Saver
from utils.summarie... |
"""
--- Day 25: Sea Cucumber ---
This is it: the bottom of the ocean trench, the last place the sleigh keys
could be. Your submarine's experimental antenna still isn't boosted enough
to detect the keys, but they must be here. All you need to do is reach the
seafloor and find them.
At least, you'd touch down on the se... |
import numpy as np
# input: coeff with shape [1,257]
def Split_coeff(coeff):
id_coeff = coeff[:, :80] # identity(shape) coeff of dim 80
ex_coeff = coeff[:, 80:144] # expression coeff of dim 64
tex_coeff = coeff[:, 144:224] # texture(albedo) coeff of dim 80
angles = coeff[:, 224:227] # ruler angles(x,y,z) ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 12:11:00 2020
@author: Rob
"""
# Imports
import pandas as pd
import matplotlib.pyplot as plt
from pandas_profiling import ProfileReport
import numpy as np
from scipy import stats
# Scientific colormaps: https://cmasher.readthedocs.io/user/usage.html
import cmasher a... |
#!/usr/bin/env python
# coding: utf-8
# In[41]:
import numpy as np
import cv2
import imageio
from PIL import Image
import matplotlib.pyplot as plt
import time
import math
import glob
import matplotlib.colors as colors
from skimage import color, io, exposure
from scipy.ndimage import morphology as morph
from skimage.... |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... |
import pathlib
import os
import io
import sys
import logging
import collections
import json
import re
import itertools
#from IPython import embed
from collections import deque
from ..cell_fabric.pdk import Pdk
from .render_placement import dump_blocks
from .db import hierNode
from .checkers import gen_viewer_json, g... |
import os
from requests.models import Response
import yaml
import json
import requests
import todoist
import string
import tempfile
import sys
# easywebdav python3 hack
import easywebdav.client
from datetime import date, datetime, timezone
from dateutil.parser import parse
import humanize
import re
import pprint
easy... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import contextlib
import numpy as np
@torch.no_grad()
def mixup_data(X, y, alpha=0.2):
"""Returns mixed inputs, pairs of targets, and lambda
"""
if alpha > 0:
lam = np.random.beta(alpha, alpha)
... |
from six import iteritems
import hashlib
import os
import operator
import random
import Qt.QtCore as QtCore
import Qt.QtWidgets as QtWidgets
import Qt.QtGui as QtGui
import nomenclate.settings as settings
APPLICATIONS = ['Maya', 'Nuke', 'Python']
ALPHANUMERIC_VALIDATOR = QtCore.QRegExp('[A-Za-z0-9_]*')
TOKEN_VALUE_VA... |
'''
<NAME>
AI HW1
Disjoint pattern Generator
'''
import copy
from collections import deque
import pickle as p
if __name__ == '__main__':
# print('Dimensions:')
# dim = int(input())
dim = 4
class Node: # Node is the state
def __init__(self, n, data, parent, blank,cost=0):
self.n = n
sel... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
import numpy as np
import os
class Loss_Synonymy(nn.Module):
"""
This class contains a loss function that uses the sum of ReLu loss to make predictions for the encoded embeddings
in the synonym subspace. A lower and hi... |
def port_from_preset(p):
pr = getattr(presets['ports'], p, None)
if not pr:
raise Exception('Did not find port for %s in presets' % p)
return pr
# ----------------------------------------------------------------------------
from urllib.parse import urlsplit, parse_qsl
def parse_via(url, props=No... |
import os
import urllib
import geojson
import bike2books
import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
from geopy.distance import vincenty
def _get_dat_path():
base_path = os.path.split(bike2books.__file__)[0]
data_path = os.path.join(base_path, "data")
... |
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import ast
import json
import re
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
import seaborn as sns
import statistics
import warnings
from scipy.stats import pearsonr
warnings.filterwarnings('ignore')
from itertools import co... |
import argparse
import json
import random
import time
import ai2thor.controller
import cv2
import evdev
import h5py
import numpy as np
from evdev import InputDevice, categorize, ecodes
from tqdm import tqdm
from agent.environment.ai2thor_file import \
THORDiscreteEnvironment as THORDiscreteEnvironmentFile
from ag... |
import json
logic = """
{
"and": [
{
"or": [
{"==": [{"var": "dataset.name"}, "/PromptReco/Collisions2018A/DQM"]},
{"==": [{"var": "dataset.name"}, "/PromptReco/Collisions2018B/DQM"]},
{"==": [{"var": "dataset.name"}, "/PromptReco/Collisions2018C... |
import ast
import os
from optparse import make_option
from django.core.management.base import BaseCommand
from django.template import Template
from symmetric.management.functions import get_api_properties
from symmetric.management.generatemodels import GenerateModelsCommand
class ApiPropertyGetMethodTransformer(ast... |
from common.commons import *
DATA_PATH = os.environ["DATA_PATH"]
ROOT = os.environ["ROOT_DIR"]
INNER_DATA_PATH = join(ROOT,'data')
PROJECT_TYPE = os.environ["PROJECT_TYPE"]
REDIS_PORT = os.environ["REDIS_PORT"]
def importTokens():
# global dbDir, portInner, redis_db, pairs, pair, split, shapeName, shapeSize, clus... |
# coding: utf-8
import bron_kerbosch1a
import bron_kerbosch1b
import bron_kerbosch2a_gp
import bron_kerbosch2b_gp
import bron_kerbosch2b_gpx
import bron_kerbosch3_gp
import bron_kerbosch3_gpx
from data import NEIGHBORS as SAMPLE_ADJACENCY_LIST
from graph import UndirectedGraph as Graph, Vertex
from random_graph import... |
import numpy as np
import tensorflow as tf
import librosa
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
import sys
import json
import glob
from Input import Input
import Models.UnetAudioSeparator
import Models.UnetSpectrogramSepara... |
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... |
# Copyright 2021 Google LLC
#
# 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, ... |
# Author of Aqsa: <NAME>
from aqsa_apps.wallet_tag_etc import currencies
from . import forms as f
import csv
# <Wallet_Tag_etc
def csv_row_for_wallet_form(row_of_csv):
return {
'name': row_of_csv[0],
'currency': currencies.currency_title_to_code(row_of_csv[1]),
'description': row_of_csv[2]... |
from dbkcore.core import BaseObject, trace, Log
from pyspark.sql.dataframe import DataFrame as PyDataFrame
import pyspark.sql.functions as F
from pyspark.sql import SparkSession
from pyspark.sql.utils import AnalysisException
from enum import Enum
# from abc import ABC, abstractmethod
from abc import abstractmethod
imp... |
"""Interpolation module."""
from matplotlib.path import Path
import numpy as np
from scipy.interpolate import griddata
from .img import rgb, rgba
def _linspace(x0, x1, res):
"""Interpolation linspace.
Parameters
----------
x0: float
Start point value.
x1: float
End point value... |
import torch
import torch.nn as nn
# from SpaNet import BCR, denselayer
import numpy as np
import torch.nn.functional as f
class SwishImplementation(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * torch.sigmoid(i)
ctx.save_for_backward(i)
return result... |
#! -*- coding: utf-8 -*-
# Keras implement of NICE (Non-linear Independent Components Estimation)
# https://arxiv.org/abs/1410.8516
from keras.layers import *
from keras.models import Model
from keras.datasets import mnist
from keras import backend as K
from keras.callbacks import ModelCheckpoint
import imageio
(x_t... |
#!/bin/python3
# -*- coding: utf-8 -*-
#==============================
# Author: <NAME>
# Last modified: 2018-06-29 14:48
# Filename: downloader.py
# Description:
#
#=============================#
# change from keras.utils
import hashlib
import os
import gzip
import tarfile
import zipfile
import gzip
... |
"""
Kø<NAME> fillæser med testdata
"""
import math
import warnings
from pathlib import Path
import pytest
from fire.io.bernese import BerneseSolution, Kovarians
ADDNEQ1273 = Path("test/data/ADDNEQ2_1273")
CRD1273 = Path("test/data/COMB1273.CRD")
ADDNEQ1886 = Path("test/data/ADDNEQ2_1886")
CRD1886 = Path("test/data... |
import re
import numpy
with open('input20.txt') as f:
tiles_raw = f.read().split('\n\n')
tiles = {}
for t in tiles_raw:
tid, tile = t.split(':')
tid = int(tid.replace('Tile ',''))
tile = [list(t) for t in tile.strip().split('\n')]
tiles[tid] = tile
def read_side(tile, side):... |
#!/usr/bin/env python
"""
Very simple HTTP server in python.
Usage::
./dummy-web-server.py [<port>]
Send a GET request::
curl http://localhost
Send a HEAD request::
curl -I http://localhost
Send a POST request::
curl -d "foo=bar&bin=baz" http://localhost
"""
from http.server import BaseHTTPRequestH... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" :py:mod:`weblayer.utils` provides a set of utility functions for
converting and encoding.
"""
__all__ = [
'encode_to_utf8',
'decode_to_unicode',
'xhtml_escape',
'url_escape',
'unicode_urlencode',
'json_encode',
'json_decode',
'generat... |
"""Time-series Generative Adversarial Networks (TimeGAN) Codebase.
Reference: <NAME>, <NAME>, <NAME>,
"Time-series Generative Adversarial Networks,"
Neural Information Processing Systems (NeurIPS), 2019.
Paper link: https://papers.nips.cc/paper/8789-time-series-generative-adversarial-networks
Last updated Date: April... |
import argparse
import os
import glob
import numpy as np
import re
import json
import matplotlib
import setproctitle
import functools
import multiprocessing as mp
import matplotlib.pyplot as plt
import sys
sys.path.append('/') # Input your own project directory
from net.run_SiamRPN import run_SiamRPN
from tqdm import... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def go_back(apps, schema_editor):
Provider = apps.get_model("core", "Provider")
ProviderTrait = apps.get_model("core", "Trait")
for provider in Provider.objects.all():
if provider.dns_server_i... |
#!/usr/bin/env python
"""
Audio file converter.
"""
import argparse
import multiprocessing as mp
import os
import re
import subprocess as sp
import sys
import mutagen
from mutagen.mp3 import MP3
from mutagen.easyid3 import EasyID3, EasyID3KeyError
VERSION = '1.0'
def match_file(path):
"""Get all wav files from... |
import nextcord, re, datetime
from nextcord.ext import commands
from a import checks
from a.funcs import f
import a.constants as tt
re_tag = re.compile("^[a-z0-9_-]*$")
reserved = ['tag','view','create','c','edit','e','delete','d','transfer','forceedit','forcetransfer','forceremove','info','random']
def tname(tag):
... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
from src.util.utils import *
from operator import itemgetter
def getSortNodeList(graph) :
# sort nodes V base on degree descendingly; value1 node name, value2 node degree
sorted_V = sorted(graph.degree, key=lambda x: x[1], reverse=T... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Mul(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x1,x2):
diffY = x2.size()[2] - x1.size()[2]
diffX = x2.size()[3] - x1.size()[3]
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
... |
import logging
import random
from pathlib import PurePath
from typing import Callable, Generator, List, Tuple
from pygame.transform import scale
from project.constants import (
BIOME_WIDTH,
CITY_BGS,
Color,
DESERT_BGS,
FOREST_BGS,
PLAINS_BGS,
TILES_CITY,
TILES_DESERT,
TILES_GRASS,
... |
from hwt.hdl.constants import DIRECTION
from hwt.interfaces.std import VectSignal, Signal
from hwt.synthesizer.param import Param
from hwtLib.amba.axi3Lite import Axi3Lite_addr, Axi3Lite, Axi3Lite_r, Axi3Lite_b,\
IP_Axi3Lite
from hwtLib.amba.axi_intf_common import AxiMap, Axi_id, Axi_hs, Axi_strb
from hwtLib.amba.a... |
""" Streaming Estimators Module """
import traceback
import warnings
from enum import Enum, auto
from typing import Any, Iterable, List, Tuple
import numpy
import torch
from torch import nn
from torch import cat as tensor_concat # pylint: disable=no-name-in-module
from torch import from_numpy # pylint: disable=no-n... |
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from check_in.github_api import GithubClient
import cherrypy
from cherrypy.process.plugins import Monitor, SimplePlugin
import github
import requests
from .config import APP_ID, PRIVATE_KEY, USER_AGENT
from .workers import ... |
import logging
import os
import time
import timeit
import numpy as np
import matplotlib.pyplot as plt
from argparse import ArgumentParser
import paddle
import paddle.nn as nn
# user
from builders.model_builder import build_model
from builders.dataset_builder import build_dataset_train
from utils.utils import setup_s... |
from soc_modules.helpers import getval
from datetime import datetime
import json
class ItemDoesNotExist(Exception):
pass
class CommonLogic:
def __init__(self):
pass
@staticmethod
def prepare_keys_for_deleting(rule):
keys_for_del = ['num_matches', 'num_hits', '_type', '_index', '_id'... |
from typing import Union, Type, List
from avishan.descriptor import Project
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management import BaseCommand
# WARNING: no import from avishan here
class AvishanConfigure:
@staticmethod
def command_line_c... |
"""Process Markdown document.
This module allows to manipulate Markdown document:
- create a navigable Markdown object from a text,
- add, remove child nodes to a Markdown object,
- extend a Markdown document with another Markdown document,
- provide utility methods to construct toc.
"""
import re
import unicodedata
f... |
from dispy.types.User import User
import asyncio
class Guild:
# no support for threads
def __init__(self, args: dict) -> None:
self.id = int(args['id'])
self.name = args['name']
self.icon = args.get('icon', None)
self.icon_hash = args.get('icon_hash', None)
self.splash... |
from pyproj import Proj, transform
from SPARQLWrapper import SPARQLWrapper, JSON
import rdflib
import json
import sys
import os
# caresjpsutilPath = os.path.abspath(os.path.join(os.getcwd(), '../caresjpsutil'))
# sys.path.insert(0, caresjpsutilPath)
from caresjpsutil import returnExceptionToJava, returnResult... |
'''
gwd commands - gwd stands for google drive working directory
This functionality is similar to the current working directory capability in Linux (i.e. the local VM)
Since this functionality is between the current working directory in the local VM
and the google drive, we need a method to track the folder on the
... |
#!/usr/bin/env python
"""
Copyright (c) 2016 <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, copy, modify, merge, publ... |
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
import datetime
import pandas as pd
import time
from collections import defaultdict
from utility.dat... |
"""Unit tests for the Azure Devops Server (formerly Team Foundation Server) source."""
from dateutil.parser import parse
from collector_utilities.functions import days_ago
from ..source_collector_test_case import SourceCollectorTestCase
class AzureDevopsTestCase(SourceCollectorTestCase):
"""Base class for test... |
#!/usr/bin/env python3
# Randomized Binary Search Tree
# derived from https://qiita.com/drken/items/1b7e6e459c24a83bb7fd
import numpy as np
import time
def dp(*x): # debugprint
if RBST.debug:
print(*x)
try:
profile
except:
def profile(f): return f
SUM_UNITY = 0
class Node:
"""
... |
import copy
import glob
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import vrep
from arguments import get_args
from kfac import KFACOptimizer
from model import MLPPolicy
from storage import RolloutStorage
from visualize im... |
import copy
import ctypes
import functools
import numpy
import cepton_sdk.common.c
import cepton_util.common
_all_builder = cepton_util.common.AllBuilder(__name__)
from cepton_util.common import AllBuilder, SimpleTimer # noqa isort:skip
def static_vars(**kwargs):
"""Add static variables to function.
"""
... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
#
# TITLE :
# AUTHOR :
# PROJECT :
#
# ----------------------------------------------------------------------------
# Docstring
"""**DOCSTRING**.
description
Routine Listings
----------------
plotRotcurve
plotK... |
import numpy as np
import tensorflow.compat.v1 as tf
def shape(tensor):
s = tensor.get_shape()
return tuple([s[i].value for i in range(0, len(s))])
def get_im2col_indices_tf(x_shape, field_height, field_width, padding=1, stride=1):
# First figure out what the size of the output should be
N, C, H, W = ... |
import pandas as pd
import numpy as np
import sys
import os
import psutil
import scipy.sparse as sp
import scipy.sparse.linalg
import inspect
#from cvxpy import*
from scipy.sparse import csr_matrix, rand
from scipy.misc import imsave
from struct import unpack, calcsize
from numpy.linalg import inv
from numpy.linalg imp... |
# -*- coding: utf-8 -*-
import json
import django
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.forms.models import model_to... |
from tqdm import tqdm
import torch.nn.functional as F
import ujson as json
import os
import pickle
import numpy as np
import torch
def process_long_input(model, input_ids, attention_mask, start_tokens, end_tokens):
# Split the input to 2 overlapping chunks. Now BERT can encode inputs of which the length... |
import struct
from skyhookdmclient.skyhook_common import *
import awkward
class SkyhookDM:
def __init__(self):
self.client = None
self.addr = None
def connect(self, ip, ceph_pool_name):
addr = ip+':8786'
self.addr = addr
client = Client(addr)
self.client = clien... |
from pathlib import Path
import pandas as pd
import numpy as np
from tqdm import tqdm
import pickle, argparse, re, pdb
from sklearn.model_selection import KFold
emo_map_dict = {'N': 'neu', 'S': 'sad', 'H': 'hap', 'A': 'ang'}
speaker_id_arr_dict = {'msp-improv': np.arange(0, 12, 1),
'crema-d': ... |
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License 2.0;
# 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, sof... |
import math
import numpy as np
from matplotlib import animation
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from .signals import get_samples, get_samples_and_rate, get_both_samples
def sine_approx(signal, samplerate=None, include_cosines=False, controls=True, min_freq=0, figsize=(12, 6),... |
import os
from optparse import make_option
from uliweb.core.commands import Command, get_input, get_answer
from uliweb.core.template import template_file
def camel_to_cap(s):
import re
return re.sub('^\w|_\w', lambda x:x.group()[-1].upper(), s)
class GenericCommand(Command):
name = 'generic'
... |
#!/usr/bin/env python
# Computes the matrix of similarities between structures in a xyz file
# by first getting SOAP descriptors for all environments, finding the best
# match between environments using the Hungarian algorithm, and finally
# summing up the environment distances.
# Supports periodic systems, matching be... |
"""
Classes that implement the Optimizable abstract class present in
base_classes.py. These are used to show how the AdaGeo optimization framework
can be used.
<NAME>, Machine Learning Research Group, University of Oxford
January 2018
"""
# Libraries
from adageo.base_classes import Optimizable
import numpy as np
fro... |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 12:50:02 2019
@author: jn135
"""
# Required imports
import pygame, sys, math
import json
from qiskit.providers.aer.noise import NoiseModel
from qiskit.providers.aer import noise
from qiskit import *
from qiskit.visualization import plot_histogram
# Basic... |
class Reporte:
def __init__(self, nombre_eq1, nombre_eq2) -> None:
self._eq2 = nombre_eq2
self._eq1 = nombre_eq1
self._goles = {self._eq1: 0, self._eq2: 0}
self._remates = {self._eq1: 0, self._eq2: 0}
self._tiros_de_esquina = {self._eq1: 0, self._eq2: 0}
self._pases ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import networkx as nx
import heapq as hp
import time
import matplotlib.pyplot as plt
#1
#IMPORT FROM LOCALFILE
#file_data=open("/Users/Zilbu/Documents/Studio/Algorithmic Methods/H4/reduced_dblp.json",'r')
file_data=open("/Users/Zilbu/Documents/Studio/Algorit... |
"""
Copyright 2020 MPI-SWS
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, software
distri... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Actuator_array.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPainter, QPen, QBrush, QColor
from Py... |
"""Superconducting transition temperature analysis"""
from numpy.polynomial.chebyshev import chebfit, chebroots
import numpy as np
from scipy.optimize import curve_fit, least_squares
def _slanted_step(x, u):
"""Slanted step function.
Sectioned function:
a1(u-b1) if u < (a1b1-a2b2)/(a1-a2)
a3(u... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class SpectralGraphConv(nn.Module):
def __init__(self, in_features, out_features, bias=True):
"""
(<NAME>, 2017)'s graph convolution layer from (https://arxiv.org/abs/1609.02907).
Args:
in_features (int): Numbe... |
"""Code for performing requests"""
import logging
import urllib.request
import zlib
from urllib.error import HTTPError
from xml.etree import ElementTree
import requests
from scout.constants import CHROMOSOMES
from scout.utils.ensembl_rest_clients import EnsemblBiomartClient
LOG = logging.getLogger(__name__)
HPO_UR... |
# -*- coding: utf-8 -*-
# =================================================================
# Licensed Materials - Property of IBM
#
# (c) Copyright IBM Corp. 2019, 2019 All Rights Reserved
#
# US Government Users Restricted Rights - Use, duplication or
# disclosure restricted by GSA ADP Schedule Contract with IBM Cor... |
import os
import warnings
import numpy as np
from pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm
from pandas import DataFrame, read_hdf
from copy import deepcopy
class CustomGOA(CGSGeneticAlgorithm):
def eval_fitness(self, target: list, **kwargs):
# define simulation conditions
wor... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import argparse
import re
import sys
import numpy as np
from scipy.sparse import hstack
from sklearn.feature_extraction import DictVectorizer
from custom_logistic import ... |
import copy
from glob import glob
import cv2
import os
import sys
import yaml
import matplotlib as mpl
import numpy as np
from skimage.io import imread
import matplotlib.pyplot as plt
from ellipses import LSqEllipse # The code is pulled from https://github.com/bdhammel/least-squares-ellipse-fitting
import time
from ma... |
# wcsremap by <NAME> script
# wcsremap -template template.fits -source input.fits -outIm input_remapped.fits
# usage : python wcsremap.py 'Calibrated*.fits' ref.fits
# <NAME> 2017/6/28
# multi processing perfomance is not good as expected, so use single cpu run 'for' script part
import glob
import os,sys
from multi... |
import random
import shutil
import itertools
import colorsys
from PIL import Image, ImageDraw
__all__ = [
"STANDARD_MODES",
"SPECIAL_MODES",
"ALL_MODES",
"hex_to_rgb",
"hex_to_rgba",
"rgb_to_hex",
"rgba_to_hex",
"random_color",
"iter_pixels",
"color_distance",
"rough_color_d... |
import os
import struct
import collections
import imageio
import numpy as np
from shutil import copyfile
root = "/work/eva0856121/datasets/NeRF/nerf_llff_data/"
dis = "/work/eva0856121/datasets/srn_data/llff_train/"
intrinsic = {
"fern" : [3260.5263328805895, 2016.0, 1512.0, 0.019750463822896944],
"flower" :... |
#!/usr/bin/env python3
import numpy as np
import scipy.linalg
try:
import lib.metrics as metrics
except ModuleNotFoundError:
import metrics
__all__ = ["OLSRegression", "RidgeRegression", "LassoRegression"]
class __RegBackend:
"""Backend class in case we want to run with either scipy, numpy
(or somet... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""ResNe(X)t models."""
from core.config import cfg
from models.blocks import (
activation,
conv2d,
con... |
import argparse
from argparse import ArgumentDefaultsHelpFormatter as Formatter
import numpy as np
import os
from matplotlib.ticker import MultipleLocator
from CHECLabPy.plotting.waveform import WaveformPlotter
from CHECLabPy.plotting.setup import Plotter
from CHECLabPy.waveform_reducers.cross_correlation import Cros... |
"""
Some utility functions for dealing with perturbative expansions numerically.
"""
import parafermions.ParafermionUtils as pf
import parafermions.ParafermionUtilsCython as pfcy
import time
import numpy as np
import scipy.sparse as sps
# define a function that gets the U operator to the nth order for given operators... |
import os
import shlex
import string
from unidecode import unidecode
__version__ = '0.2.3'
pprint_key_sort_order = ["size", "part_type", "uuid", "label", "mounted", "mountpoint", "mount_opts"]
def get_uuids_and_labels():
"""
Returns a list of available partitions. Each partition is a dictionary with "uuid... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.