text
stringlengths
3.07k
12.6k
import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.ops import GraphConv from pytorch3d.io import load_objs_as_meshes from pytorch3d.renderer import Textures class STN3d(nn.Module): def __init__(self): super(STN3d, self).__init__() self.conv1 = GraphConv(3, 64) ...
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015, 2016 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as publish...
######################################CONSTANTS###################################### DEFAULT_RC = { 'lines.markersize': 2, 'font.size': 6, 'font.family': 'serif', 'font.serif': ['Times'], # 'text.usetex': True, 'axes.titlesize': 6, 'axes.labelsize': 5, 'legend.fontsize': 5, 'legend....
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/6/5 17:36 # @Author : CoderCharm # @File : __init__.py.py # @Software: PyCharm # @Desc : """ 模仿flask 工厂模式目录结构 """ import traceback import app.api.v1.profile from fastapi import FastAPI, Request, status from fastapi.encoders import jsonable_encod...
""" .. module:: proxy.py :synopsis: Transparent access to Redis as a data structure server .. moduleauthor:: <NAME> <http://github.com/atl> Rather than use the native redis-py's methods for getitem/setitem as simple key-value storage, use item access as a means to obtain proxy objects for structures in the redis st...
import os import logging from lxml import etree logger = logging.getLogger(__name__) class Report(object): def __init__(self): self.reporters = [] def test_name(self, name): for reporter in self.reporters: reporter.change_test(name) def test_file(self, name): for rep...
# @Author: AshishKingdom(<NAME>) #help files parser related functions import requests def getRawDataFromQB64Wiki(keyword): #return the raw wiki data from http://qb64.org/wiki if it succeed #otherwise, we will be using data from the stored help files r = requests.get("http://wiki.qb64.org/wiki/inde...
from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict as _OrderedDict import warnings import six import warnings as _warnings import os as _os import sys from tempfile import mkdtemp try: if six.PY3: from threading import get_ident as _get_id...
#!/usr/bin/env python ''' ''' from abc import abstractmethod import numpy as np import pyorb from ..controller import Tracker from .scheduler import Scheduler from ..passes import equidistant_sampling, select_simultaneous_passes class Tracking(Scheduler): ''' ''' def __init__(self, radar,...
''' Scanned pages are upside-down PDFs. Convention: We work convert everything to 8-bit grayscale images. ''' import glob, os, re, subprocess, tempfile, shutil from math import pi import warnings import numpy as np import scipy.misc import imageio import skimage, skimage.filters, skimage.transform, skimage.morpholog...
# 2022-01-23 00:20:21.888849 from alembic import op import sqlalchemy as sa revision = '6ee0702a3d64' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('game_ranking', sa.Column('id', sa.Integer(), autoi...
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
## interaction3 / arrays / foldable_constant_spiral.py import numpy as np from interaction3.abstract import * from interaction3 import util # default parameters defaults = {} # membrane properties defaults['length'] = [35e-6, 35e-6] defaults['electrode'] = [35e-6, 35e-6] defaults['nnodes'] = [9, 9] defaults['thick...
#Creating a node for doubly linked list class Node(object): #Constructor to create a new node def __init__(self,key,data, next=None, prev=None): self.next = next # reference to next node in DLL self.prev = prev # reference to previous node in DLL self.data = data #data of the node ...
# -*- coding: utf-8 -*- # Copyright (c) 2022, Compiler Explorer Authors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright not...
#!/usr/bin/python # ***************************************************************************** # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The A...
import random; import numpy as np; import os; from itertools import chain; from learnedevolution.algorithm import Algorithm; from learnedevolution.targets.mean import *; from learnedevolution.targets.covariance import *; from learnedevolution.convergence import CovarianceConvergence; from learnedevolution.rewards impo...
class Debts(object): def __init__(self): self.debts = [] self.participants = [] def addTransactions(self, transactions): for transaction in transactions.transactions: self.addParticipant(transaction.buyer) for participant in transaction.participants: ...
from django.core.urlresolvers import reverse_lazy from django.http import Http404, HttpResponseRedirect from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404, redirect from django.views.generic import (ListView, DetailView, ...
# -*- coding: UTF-8 -*- # Copyright (C) 2019, <NAME> <<EMAIL>> # All rights reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, t...
import tempfile from datetime import datetime import logging import os import gzip import json from fastapi import BackgroundTasks, FastAPI from common.clients.google_storage_client import GoogleStorageClient from common.customized_logging import configure_logging from inflation.config import settings from inflation....
import csv import inspect import re from io import StringIO from docutils import nodes from docutils.statemachine import StringList from sphinx.domains import Domain from sphinx.util import import_object from sphinx.util.docutils import SphinxDirective def build_function_directive(name, aliases, func): """Build ...
# Copyright @2018 # # GERCOM - Federal University of Pará - Brazil # # 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 require...
from django.urls import reverse,resolve from django.test import TestCase from .views import home, board_topics, new_topic, board_redirect from .models import Board, Topic, Post from django.test import Client, TestCase from django.contrib.auth.models import User from .forms import NewTopicForm class HomeTests(TestCase...
""" This file contains classes responsible for describing various permutations. @author: <NAME> """ from logic_simplifier.expr import Variable, Negation, Operator, TrueVal class Permutation(object): "An immutable class representing a permutation." def __init__(self, val): self._val = val.copy() ...
#!/usr/bin/python3 from flask import Flask, request, render_template, url_for import json, os, random from PIL import Image TITLE = "VotePhoMe.johanv.xyz - Vote for a Photo" #site title, used in the title bar and the heading within the page app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 ...
import json import re def processed_specs(product): return _parse_computer_specs(product) def _parse_computer_specs(product): details = _cleaned_dict(product["parsed_details"]) cpu = details.get("Процессор", "") cpu = cpu.lower() gpu = details.get("Видеопроцессор", details.get("Видеокарта")) ...
from PyQt5 import QtWidgets, QtSql, QtCore, QtGui from .window import Window from ..database import Database from .. import logger class _ImportExport: def __init__(self, main_window: Window, database_file: str): """ Args: main_window Window: The instance of the main window ""...
#!/usr/bin/env python # coding: utf-8 # In[317]: # Modules import import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt from pprint import pprint from sklearn.model_selection import ( train_test_split, GridSearchCV, ) from sklearn.metrics import ( classification_report, ...
import enum from enum import auto import os import pygame import random import animation import locations _surfaces = {} class Surfaces(enum.Enum): VIM = auto() ATOM = auto() EMACS = auto() INTELLIJ = auto() NANO = auto() VSCODE = auto() RANDOM = auto() BUG_RED_1 = auto() BUG_R...
import os import sys import logging import functools from collections import OrderedDict logging.basicConfig() logger = logging.getLogger(__name__) def check_prerequisites(func): @functools.wraps(func) def wrap(self, *args, **kwargs): if func.__name__ == 'write': if not self.results: ...
from . import deezer_service from flask import ( session, render_template, redirect, request, url_for, current_app, jsonify ) from .view_decorators import login_required, logout_required from . import models from .models import DEEZER_APP_ID, DEEZER_REDIRECT_URI from ..util import (get_random_str, send_file) im...
import argparse import copy import subprocess COMMON_CONFIG = { "--subsample_testset": 1000, "--max_paraphrases": 50, "--task": "attack", "--target_classifier": "transformer", "--transformer_clf_model_init": "bert-base" } DEFENSE_CONFIG = { "none": {}, "lmag": { "--defense_strategy...
import copy from numpy import array as na, array_equal as na_eq import unittest from src import univar_polyops as upo TEST_CASES_UNARY = { upo.degree: [ (-1, []), (-1, [0]), ( 0, [1]), ( 1, [1,1]), ( 2, [0,0,-1]) ], upo.normalize: [ ([], []), ([], [0]), ([1], [1,0]), ([0,-1], [0,-1,0,0]) ] } TE...
# -*- coding: utf-8 -*- """ Utilities """ import json as jsonlib import logging import os.path import platform import re import socket import sys from contextlib import closing from .exceptions import BadResponseError, ServerConnectionError try: from urllib import parse as urlparse from urllib import request...
# -*- coding: utf-8 -*- """ HikeBooklet author: georand source: https://github.com/georand/hikebooklet date: 2021 """ import io,zipfile,struct,logging import requests import numpy as np from PIL import Image, ImageDraw, ImageColor from config import * logger=logging.getLogger(__name__) class SessionWithHeaderR...
# coding: utf-8 # # Display features detected by SIFT, SURF and ORB # In[11]: import cv2 import numpy as np import cv2 # Surf and Sift are under patient but orb is opensource def Surf_Sift_Orb(img_path, algo=None): img = cv2.imread(img_path , cv2.IMREAD_GRAYSCALE) if algo == "SIFT": sift = cv2.xf...
import logging from typing import Optional, List from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS, ATTR_TEMPERATURE from homeassistant.core import HomeAssistant from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import...
import logging import pew.options as options def check_platforms(): errors = {} platforms = [] try: import console import ui platforms.append('ios') except Exception as e: # Note that there is a strange issue in packaged apps where a global traceback # import is...
# coding: utf-8 # In[ ]: import argparse parser = argparse.ArgumentParser("cDCGAN") parser.add_argument('--dataset_dir', type=str, default='../celeba') parser.add_argument('--result_dir', type=str, default='./celeba_result') parser.add_argument('--condition_file', type=str, default='./list_attr_celeba.txt') pars...
"""Growing Tree Animation Boring a boring tree. """ from cs1graphics import * from time import sleep paper_from = Color((30, 29, 29)) paper_to = Color('white') paper = Canvas(500, 500, title='School of Hacking, 케이MIT') paper.setBackgroundColor(paper_from) from math import cos, sin, degrees, radians def gradien...
from builtins import zip import numpy as np from rubin_sim.maf.metrics.baseMetric import BaseMetric from scipy.optimize import curve_fit from rubin_sim.maf.utils import m52snr import warnings __all__ = ['periodicStar', 'PeriodicStarMetric'] class periodicStar(object): def __init__(self, filternames): sel...
# -*- coding: utf-8 -*- from icemac.addressbook.testing import pyTestAddressBookFixture, site from icemac.addressbook.testing import pyTestEmptyZodbFixture, DateTimeClass from icemac.addressbook.testing import pyTestStackDemoStorage import gocept.country.db import icemac.addressbook import icemac.addressbook.browser.in...
#!/usr/bin/env python import sys from termcolor import colored import colorama import re from collections import Counter import warnings from typing import Dict, Tuple, List, Iterable, Mapping FormulaType = str colorama.init() ATOM_REGEX = r"([A-Z][a-z]*)(\d*)" OPENERS = r"({[" CLOSERS = r")}]" def is_balanced(...
from enum import Enum import numpy as np from actions import Direction class Car(): def __init__(self, car): self.x = int(car['x']) self.y = int(car['y']) self.health = int(car['health']) self.resources = int(car['resources']) self.collided = bool(car['collided']) s...
import argparse from components import * import time import sys def setup_args(): parser = argparse.ArgumentParser() parser.add_argument('-l', action='store', dest='llvm_bc_out', help='Destination directory where all the generated bitcode files should be stored.') parser.add_argu...
# coding=utf-8 from copy import deepcopy from resources.internal.router import route, path_for, resolve from resources.internal import player from resources import kinoman_api @route("/") def root(): menu_items = [] for label, query in kinoman_api.list_categories_video_menu(): menu_items.append( ...
from dataclasses import dataclass from typing import Callable, Dict, List, Set from .parser import ParseError class State: def __init__(self, name: str): self.epsilon: List[State] = [] # epsilon-closure self.transitions: Dict[str, State] = {} self.name: str = name self.is_end: boo...
""" This module contains unit tests for the schedules used by the CEA. The schedule code is tested against data in the file `test_schedules.config` that can be created by running this file. Note, however, that this will overwrite the test data - you should only do this if you are sure that the new data is correct. """ ...
from gpt_gen import * from Config import Config import sys def _is_chinese_char(char): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # ...
""" Older commands, now deprecated. """ @cli.command() @click.argument('login') def foo(login): from playhouse.migrate import * from google.models import db init_user_database(login) migrator = SqliteMigrator(db) status_field = IntegerField(null=True) with db.transaction(): migrate( ...
from rpi_ws281x import Color, PixelStrip, ws import time import argparse import tkinter as tk from ttkthemes import ThemedTk from utils.moodlights import Moodlights from utils.gui import GUI # LED strip configuration: LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) LED_DMA = 10 # DM...
import numpy as np import pandas as pd from bs4 import BeautifulSoup import os, re from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.layers import Input, Embedding, GRU, Dense, Dot from keras.models import Model from keras.layers.core import * from keras i...
from datetime import datetime, timezone import configparser import praw import praw.config import praw.exceptions import praw.models.reddit.more import prawcore.exceptions import requests from praw.models import MoreComments from pathlib import Path import os __author__ = '<NAME>' __version__ = '1.0.' __email__ = '<...
__author__ = 'sulantha' import pandas as pd import numpy from matplotlib import pyplot as plt from sklearn.metrics import roc_curve, auc, confusion_matrix from Python.RUSRandomForest import RUSRandomForestClassifier from Python.RUSRandomForest import Config from multiprocessing import Pool def writeSensAndSpec(fpr, t...
# shoveltest.py # Copyright (c)2017 <NAME> <<EMAIL>> # from __future__ import print_function import arcpy import os, sys import math # You can run this script from the command line, if you want. def usage(): print("""usage: shoveltest.py baselinefc templatefc outputpoly outputpt [width height] Generates polygon ...
import pytest import mock from hcloud.servers.client import BoundServer from hcloud.servers.domain import Server from hcloud.floating_ips.client import BoundFloatingIP from hcloud.floating_ips.domain import FloatingIP class TestBoundFloatingIPs(object): @pytest.fixture() def bound_floating_ip(self, hetzner_...
from math import radians, cos, sin, asin, sqrt, pi import numpy as np from scipy.spatial.distance import euclidean as euclidean_dist from sklearn.metrics import pairwise_distances from scipy.spatial.distance import cdist from scipy.sparse import coo_matrix # todo: calculate distance matrix #def distance_matrix(): # p...
# Importing stock libraries from pathlib import Path from typing import Dict import warnings import torch from torch.utils.data import Dataset from kogito.core.knowledge import GEN_TOKEN, EOS_TOKEN from kogito.core.utils import encode_line, trim_batch, SortishSampler class KnowledgeDataset(Dataset): def __init__...
# class student: # def __init__(self, n, a): # self.full_name = n # self.age = a # def get_age(self): # return self.age import nclib from bitstring import BitArray import math import binascii import struct class Writer: def __init__(self, ip, port): self.ip = ip se...
# -*- coding: utf-8 -*- """ Author: <NAME> Last Modified: 20/10/19 Version: 2.0 """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader import torchvision import multiprocessing import matplotlib.pyplot as pl...
""" Testing hook for verifying correctness of initial sync. """ from __future__ import absolute_import import os.path import random import bson import pymongo import pymongo.errors from . import cleanup from . import jsfile from ..fixtures import replicaset from ... import errors from ... import utils class Backg...
#!/usr/bin/python # # Copyright 2013 Google 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...
from collections import defaultdict import glob import os from matplotlib import pyplot as plt import matplotlib import numpy as np import pandas as pd from analysis.utils import ORDER, order_columns_of_df, savefig import seaborn as sns sns.set_theme() from scipy.stats import pearsonr, linregress save_dir = '../analysi...
import sys import pytest import logging import logging.config from uuid import uuid4 from io import StringIO from unittest.mock import patch, Mock, call import deprecation from nicfit.logger import getLogger, FileConfig, DictConfig from nicfit import logger from nicfit import ArgumentParser def test_log(): # No h...
""" Creates a EfficientNetV1 Model as defined in: EfficientNetV1: Self-training with Noisy Student improves ImageNet classification. arXiv preprint arXiv:1911.04252. """ import math import copy from keras_cv_attention_models.efficientnet.efficientnet_v2 import EfficientNetV2 BLOCK_CONFIGS = { "base": { # width 1....
# see iotbx/pdb/common_residue_names.h; additionally here only: U I from __future__ import absolute_import, division, print_function ad_hoc_single_metal_residue_element_types = """\ ZN CA MG NA MN K FE CU CD HG NI CO SR CS PT BA TL PB SM AU RB YB LI MO LU CR OS GD TB LA AG HO GA CE W RU RE PR IR EU AL V PD U SB SE TE ...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB ...
DEFAULT_ROWS_COUNT = 6 DEFAULT_COLUMNS_COUNT = 7 DEFAULT_WIN_CONDITION_COUNT = 4 def create_board(rows_count=DEFAULT_ROWS_COUNT, columns_count=DEFAULT_COLUMNS_COUNT): return [[0] * columns_count for _ in range(rows_count)] def get_player_choice_func(is_test=False): def get_player_choice(player): pri...
import pickle import pprint import discord import asyncio from discord.ext import commands from lib import obot pp = pprint.PrettyPrinter(indent=2) bot = commands.Bot(command_prefix='k!relay ') RELAYFILE = 'important/relay.pickle' CREATE_MESSAGE = ("**Created relay data for the server `{ctx.guild.name}`**\n" ...
import arcade from settings import ( FONTSIZE, FPS, LINETHICKNESS, PADDLEHEIGHT, PADDLEOFFSET, WHITE, WINDOWHEIGHT, WINDOWTITLE, WINDOWWIDTH, ) class Vector2: def __init__(self, x: float, y: float): self.x = x self.y = y def __getitem__(self, key): ...
from abc import ABC, abstractmethod import numpy as np from sklearn.cluster import KMeans from pymoo.factory import get_performance_indicator from pymoo.algorithms.nsga2 import calc_crowding_distance ''' Selection methods for new batch of samples to evaluate on real problem ''' class Selection(ABC): ''' Base ...
"""imports""" import copy import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash_apps.shared_styles import * from dash_apps.apps.myapp import app # https://stackoverflow.com/questions/62732631/how-to-collapsed-sidebar-in-dash-plotly-dash-bootstrap-compo...
import sys from asldro.containers.image import NiftiImageContainer import numpy as np import json import os from asldro.filters.json_loader import JsonLoaderFilter from asldro.filters.nifti_loader import NiftiLoaderFilter from asldro.filters.transform_resample_image_filter import TransformResampleImageFilter import pyt...
import json import os class Modifier: """An Object containing all relevant information about one skin tone Modifier""" def __init__(self, name: str, colors: dict, extension: str, tolerance: int = 16, *args, **kwargs): """ Creates a new skin tone modifier :param name: The name of this ...
# -*- coding: utf-8 -*- """The profiler classes.""" from __future__ import unicode_literals import abc import os import time try: from guppy import hpy except ImportError: hpy = None class CPUTimeMeasurements(object): """The CPU time measurements. Attributes: number_of_samples (int): number of samples...
#!/usr/bin/env python from __future__ import division try: import matplotlib MATPLOTLIB_LOADED = True matplotlib.use('Agg') import matplotlib.pyplot as plt except ImportError: MATPLOTLIB_LOADED = False import sys, time import numpy as np from numpy import polyfit from megaman.geometry.adjacency i...
import pytest import os from src.model.user import User from src.model.course import Course from src.dao.dao import DAO from src.dao.database import DataBaseHandler from src.api.app import InitFlaskApp from utils.configuration_utils import ConfigurationsUtils @pytest.fixture(scope='session', name='init_sqlite3_db') d...
#------------------------------------------------------------------------------------------# # This file is part of Pyccel which is released under MIT License. See the LICENSE file or # # go to https://github.com/pyccel/pyccel/blob/master/LICENSE for full license details. # #----------------------------------------...
import math import numpy as np import time from ui_GUI import * from Tools import ToolsManager from HUD import HUDManager from PySide2.QtCore import Signal class CanvasMover(): def __init__(self , whiteboard): self.startPoint = (0,0) self.isUsed = False self.whiteboard = white...
# # meter.py # # Author(s): # <NAME> <<EMAIL>> # # Copyright (c) 2020-2021 ETH Zurich. # # 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 # #...
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" ----------------------------------------------------------------------------------- # Author: <NAME> # DoC: 2021.01.5 # email: <EMAIL> ----------------------------------------------------------------------------------- # Description: Training script for Semantic Head """ import argparse import torch import torch.op...
import os import numpy as np import torch import torch.utils.data import pickle as pkl from torch import nn, optim from tqdm import tqdm from networks import HSICClassifier, MLP2Layer from EEG.datasets import create_kfoldcv_loaders from EEG.train_utils import get_device, calc_save_perf_metrics, run_params # Experiment...
import pathlib import shlex from textwrap import dedent import click import pytest from click.testing import CliRunner from linesieve.cli import cli from linesieve.cli import split_field_slices ROOT = pathlib.Path(__file__).parent def load_data(root): for path in sorted(root.glob('data/*.in')): with p...
""" Dimcli general purpose utilities for working with data. NOTE: these functions are attached to the top level ``dimcli.utils`` module. So you can import them as follows: >>> from dimcli.utils import * """ import click import sys import subprocess import os import re import webbrowser from itertools import islic...
# coding=utf-8 __author__ = '<NAME>' import idaapi from idc import * from idautils import * from lib.Register import get_reg_class, get_reg_by_size ### ARCHITECTURE AND REGISTER FUNCTIONALITY ### # IDA PRO execution context layouts 64 ctx_layout_64 = {'st':['ST0', 'ST1', 'ST2', 'ST3', 'ST4', 'ST5', 'ST6', 'ST7'], ...
import json import os import glob from collections import namedtuple import zipfile from torchvision.datasets.utils import extract_archive, verify_str_arg, iterable_to_str from .vision import VisionDataset, ConcatVisionDataset, StackVisionDataset from .cityscapes import CityscapesInfo, Cityscapes__, Cityscapes_, Citys...
# This file is part of the Blockchain Data Trading Simulator # https://gitlab.com/MatthiasLohr/bdtsim # # Copyright 2020 <NAME> <<EMAIL>> # # 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 # ...
#!/usr/bin/env python # # # import argparse import logging import numpy as np from scipy import sparse # A B C D E F A B C D E F # A 0 1 0 0 0 0 A 0 1 1 1 1 1 # B 0 0 1 1 0 0 B 0 0 1 1 1 1 # C 0 0 0 0 1 0 --> C 0 0 0 0 1 1 # D 0 0 0 0 1 0 ...
import c3d import unittest import test.verify as verify from test.base import Base from test.zipload import Zipload class FormatTest(): ''' Test to evaluate INTEL, DEC and SGI/MIPS processor formats using a set of identical files. INTEL: IEEE standard floating points and little endian. DEC: Non...
#!/usr/bin/env python # -*- coding:utf-8 -*- # # Author : XueWeiHan # E-mail : <EMAIL> # Date : 16/3/17 下午5:35 # Desc : 文章模块 import markdown2 from model.models import Article, User from app import BaseHandler, AdminHandler from utilities import tool, escape class ShowArticlesHandler(BaseHand...
import pickle import numpy as np #from .config import flags as config from hls_data_types import * #reduce_x_features = config.w_network == 'textcnn' reduce_x_features = False seq_len = 25 def load_data(fname, num_load=None): print('Loading from ', fname) with open(fname, 'rb') as f: x = pickle.load...
import numpy as np from scipy import integrate from reactorPhysics import reactorSystem from reactorPhysics import qFuel from reactorPhysics import rho #import matplotlib.pyplot as pl import time class LegoReactor(object): """ Provides methods to interact with the point kenetics model. The reactor system ...
#!/usr/bin/env python3 # Copyright 2021, Collabora, Ltd. # SPDX-License-Identifier: BSL-1.0 import numpy as np import pandas as pd from scipy import interpolate, signal RESAMPLE_RESOLUTION_MICROSECONDS = 10 def _rescale(x): half_range = (x.max() - x.min())/2 middle = x.min() + half_range return (x - mid...
from matplotlib import pyplot as plt from matplotlib import animation from matplotlib import cm as cm import math import random import cmath def create_circle(r): if r == None: r = 0.05 circle = plt.Circle((0,0), r) return circle def update_radius(i, circle): circle.radius = i*0.5 return c...
import os, sys import logging import argparse import apyfal import shutil import json import csv import re SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) LOG_FMT_DBG = "%(levelname)-8s: %(message)s" TMPDIR = "/dev/shm/sha3_benchmark" CSV_...
""" Code for application of feature aware normalization to digital pathology images Depending on your preference, there are two ways to build the network: ``` python ``` and ``` python ``` """ import os, pickle from collections import OrderedDict import numpy as np import theano import theano.tensor as T import ...
# Copyright 2021 IBM 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 applicable law or agreed t...
import argparse import csv import os import numpy as np import scipy as sc import loompy def generate_col_attr(qc_paths): """Converts the QC of Smart Seq2 gene file pipeline outputs to loom file Args: qc_path (str): path to the QCs csv """ # read the QC values qc_path = [p for p in qc_paths...