text
stringlengths
3.07k
22.1k
import pkg_resources import re import requests import numpy as np import scipy as sp import scipy.sparse import scipy.sparse.linalg from . import index __all__ = ['PowerNetwork', 'load_case'] class PowerNetwork: def __init__(self, basemva, bus=None, gen=None, gencost=None, branch=None, perunit=True): i...
import argparse from contextlib import contextmanager from ipaddress import ip_network import logging import sys from typing import Generator, Optional from greensim import Simulator, Signal, advance, local, now, Process, add from greensim.logging import Filter from greensim.random import VarRandom, constant, normal, ...
import torch import torch.nn as nn from torch.nn import Parameter import torch.nn.functional as F import numpy as np class Identity(torch.nn.Module): def __init__(self): super(Identity, self).__init__() def forward(self, x): return x class Flatten(nn.Module): def forward(self, input): ...
import torch from torch.utils.data import Dataset, DataLoader import torchvision from torchvision import transforms import torch.nn as nn import os import glob import numpy as np import time import cv2 from einops import rearrange, reduce, repeat from PIL import Image #from utils.augmentations import SSDAugmentation,...
import json import pathlib from datetime import datetime, timezone from typing import Union, List from dateutil.parser import isoparse from discord.ext.commands import Context, Cog, Bot, command from discord.ext import tasks from discord import ( Embed, Colour, File, Member, User, Role, Gui...
from .ray import * from numpy import * import matplotlib.pyplot as plt import pickle import time import os """ A group of rays kept as a list, to be used as a starting point (i.e. an object) or as a cumulative detector (i.e. at an image or output plane) for ImagingPath, MatrixGroup or any tracing function. Subclasses ...
import re import sys import os import json import argparse from collections import OrderedDict class TestJobResult: def __init__(self, status, job_url, step_failed): self.job_url = job_url self.status = status self.step_failed = step_failed def summarize_test(): return '' ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obt...
""" File Backends ------------------ Provides backends that deal with local filesystem access. """ import collections import hashlib import io import os import pickle import tempfile import time from shutil import copyfileobj from dogpile.cache.api import CacheBackend, NO_VALUE, CachedValue from . import registry ...
import copy import math from connectfour.agents.computer_player import RandomAgent def close_to_win(board, id): score = 0 board_cp = copy.deepcopy(board) for i in range(board_cp.width): if board_cp.try_move(i) == -1: continue sub_board = board_cp.next_state(id, i) if s...
from PIL import Image, ImageDraw, ImageFont import json import base64 import math from io import BytesIO import sys tile_images = Image.open('./mahjong_tiles/tiles.png') xsize, ysize = tile_images.size tile_width = xsize // 10 tile_height = ysize // 4 tile_names = ['1m','2m','3m','4m','5m','6m','7m','8m','9m','0m', ...
import matplotlib.pyplot as plt import numpy as np import numpy.random as rng import scipy.special as scp import os import writer import main #Same as above, but random def random_airfoil_eval(n,param,boundary,control,forces_control): #Random stuff par={'n':n, 'deg':int(rng.rand(1)*10), 'N1':rng.rand(1), 'N2':rng.r...
# Problem Set 4C # Name: <NAME> # Collaborators: # Start: 27.12.2020 14:50 # End: 29.12.2020 18:15 # EncryptedSubMessage decrypt_message() returns words that are not necessarily the original, though they are valid # To run unit tests, type pytest in the terminal import string from ps4a import get_permutations ### HEL...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Dec 10 11:15:49 2018 # Congo basin tree fraction using 2018 dataset with gain @author: earjba """ import numpy as np import importlib import iris import iris.quickplot as qplt import matplotlib.pyplot as plt from datetime import datetime, timedelta fro...
import json import logging import re from typing import Dict from bs4 import BeautifulSoup LOG = logging.getLogger('scrapper.macrotrends.Parser') class ParserError(Exception): def __init__(self, error, parsing_content): self.message = f'failed to parse: {error}' LOG.exception(self.message) ...
"""Sample API Client.""" import json from datetime import datetime, timedelta import asyncio import logging import socket import aiohttp import async_timeout from custom_components.wellbeing.const import SENSOR, FAN, BINARY_SENSOR from homeassistant.components.binary_sensor import DEVICE_CLASS_CONNECTIVITY from home...
import math import numpy as np import torch from torch import nn import copy import random import concurrent.futures ## Distributions def generate_gaussian_parity(n, cov_scale=1, angle_params=None, k=1, acorn=None): """ Generate Gaussian XOR, a mixture of four Gaussians elonging to two classes. Class 0 cons...
from nnet.models.srl import * from nnet.run.runner import * from nnet.ml.voc import * from nnet.run.srl.run import * from nnet.run.srl.util import * from nnet.run.srl.decoder import * from functools import partial from nnet.run.srl.read_dependency import get_adj import nnet.run.srl.conll09_evaluation.eval def make_l...
import time from datetime import date, datetime, timedelta import base64 import requests import urllib.parse import hashlib import hmac import sys import os import csv from dotenv import load_dotenv load_dotenv() api_key = os.environ.get("API_KEY") api_secret = os.environ.get("API_SECRET") token_pair = os.environ.get...
# 1. Only add your code inside the function (including newly improted packages). # You can design a new function and call the new function in the given functions. # 2. For bonus: Give your own picturs. If you have N pictures, name your pictures such as ["t3_1.png", "t3_2.png", ..., "t3_N.png"], and put them inside t...
import requests import os import json import re class ReadmeApi(object): def __init__(self): super().__init__() self.doc_version = None def authenticate(self, api_key): r = requests.get('https://dash.readme.com/api/v1', auth=(api_key, '')) if r.status_code != 200: r...
import json import requests import os import time from enum import Enum from config import Config as cfg import mod_gamesense_logger as logger class Mode(Enum): COUNT = "count" PERCENT = "percent" COLOR = "color" CONTEXTCOLOR = "context-color" class JsonBase(): de...
#-*- coding: utf-8 -*- #!/usr/bin/python3 """ Copyright (c) 2020 LG Electronics Inc. SPDX-License-Identifier: MIT """ import pytest def test_core_image_minimal_do_report(test_build): o = test_build.shell.execute("bitbake core-image-minimal -c report") assert o.stderr.contains("ERROR: Task do_report does not...
# -*- coding: UTF-8 -*- import numpy as np import pandas as pd import itertools import csv import gensim import re import nltk.data import tensorflow from nltk.tokenize import WordPunctTokenizer from collections import Counter from keras.models import Sequential, Graph from keras.layers.core import Dense, Dropout, Acti...
#!/usr/bin/env python3 import os import csv from itertools import dropwhile, takewhile import re # https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json # /offers/v1.0/aws/AmazonEC2/current/index.json # /offers/v1.0/aws/AmazonEC2/current/region_index.json # /offers/v1.0/aws/AmazonEC2/20190612230233/ap-sou...
import random import torch import os import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.utils.data import RandomSampler, BatchSampler from .utils import calculate_accuracy, Cutout, calculate_accuracy_by_labels, calculate_FP, calculate_FP_Max from .newtrainer import Trainer...
import unittest from unittest.mock import MagicMock, patch from collections import Counter, deque from PyQt5.QtWidgets import QMainWindow from extra_foam.logger import logger from extra_foam.gui import mkQApp from extra_foam.gui.windows import ( BinningWindow, CorrelationWindow, HistogramWindow, PumpProbeWindow, ...
import unittest from typing import TypeVar, List, Type from xrpc.abstract import BinaryQueue, Queue, HeapQueue, KeyedQueue A1 = [1, 2, 2, 3, 3, 3] A2 = [1, 2, 3, 3, 3] A3 = [] A4 = [1] T = TypeVar('T') def ex(q: Queue[T]) -> List[T]: r = [] while True: try: r.append(q.pop()) ex...
#!/usr/bin/python # API Gateway Ansible Modules # # Modules in this project allow management of the AWS API Gateway service. # # Authors: # - <NAME> <github: bjfelton> # - <NAME> <github: mestudd> # # apigw_api_key # Manage creation, update, and removal of API Gateway ApiKey resources # # MIT License # # Copyrig...
# Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
# Copyright (c) 2020 Software AG, # Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, # and/or its subsidiaries and/or its affiliates and/or their licensors. # Use, reproduction, transfer, publication or disclosure is prohibited except # as specifically provided for in your License Agreement with Softwar...
# /usr/bin/env python import os import fire import webbrowser from nexinfosys.bin.cli_script import set_log_level_from_cli_param, prepare_base_state, print_issues from enbios.common.helper import list_to_dataframe, generate_workbook from enbios.input.data_preparation.lci_to_nis import SpoldToNIS from enbios.input.dat...
# coding: utf-8 # # Extract NECOFS data using NetCDF4-Python and analyze/visualize with Pandas # In[1]: # Plot forecast water levels from NECOFS model from list of lon,lat locations # (uses the nearest point, no interpolation) import netCDF4 import datetime as dt import pandas as pd import numpy as np import matplo...
''' Assigning values to the grid The grid will look like this: 0,0 | 0,1 | 0,2 | 0,3 | 0,4 | 0,5 | 0,6 1,0 | 1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6 2,0 | 2,1 | 2,2 | 2,3 | 2,4 | 2,5 | 2,6 3,0 | 3,1 | 3,2 | 3,3 | 3,4 | 3,5 | 3,6 4,0 | 4,1 | 4,2 | 4,3 | 4,4 | 4,5 | 4,6 5,0 | 5,1 | 5,2 | 5,3 | 5,4 | 5,5 | 5,6 ''' N...
#!/usr/bin/python import os, sys, signal, datetime, calendar, json, appdirs PROGRESS_BAR_LENGTH = 50 USER_DATA_DIR = appdirs.user_data_dir("eventoftheday", "tedski999") API_URL = "https://en.wikipedia.org/api/rest_v1/feed/onthisday/all" EVENT_CATEGORIES = { "births" : "Birthday wishes to {0}", "deaths" : "Res...
"""Defines metrics used to evaluate uncertainty.""" import numpy as np from scipy.stats import norm from utils.util import to_one_hot def gaussian_nll(y, mu, var): """Calculates the negative log likelihood of Gaussian distribution. Args: y: numpy array, shape [batch_size], the true labels. ...
import os import abc import sys import time import datetime import logging import shutil import oommfc as oc import subprocess as sp import ubermagutil as uu import micromagneticmodel as mm log = logging.getLogger(__name__) _cached_oommf_runner = None class OOMMFRunner(metaclass=abc.ABCMeta): """Abstract class f...
from collections import namedtuple import matplotlib.pyplot as plt import numpy as np import pandas as pd import ray import stats Configuration = namedtuple('Configuration', ['banditCount']) Observation = namedtuple('Observation', ['step', 'reward', 'agentIndex', 'lastActions']) def smoke_test(agent): config =...
import os import sys from datetime import datetime, timedelta import numpy as np quick_hist = False quick_bar = True #quick_bar = False def d4_computation_time_nparray( top='' ): dirs = [ f.name for f in os.scandir( top ) ] #if f.is_file() ] path_l = [] ftimes = [] ctimes = [] # Prepare file p...
from __future__ import print_function import os import json import time import re import logging from kutils.json_min_db import JsonMinConnexion from wunderous.config import WEEK_OFFSET, DAY, WEEK, MONTHES, CSV_HEADER, config from wunderous.drive import get_sheet_values, get_sheet_metadata, get_sheet_value, update_she...
import torch.nn as nn import torch import math class NoSkipBertSelfOutput(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.drop...
import sys sys.path.append('../../src') import argparse from collections import defaultdict import datetime import functools import logging import operator import os from pyschedule import Scenario, solvers, plotters, alt class NoSolutionError(RuntimeError): pass class AnlagenDescriptor(object): def __init...
from flask_sqlalchemy import SQLAlchemy from flask import jsonify from flask_migrate import Migrate from flask import render_template from flask import Flask, session, redirect, url_for, request import datetime from flask_login import LoginManager,login_user,UserMixin from sqlalchemy import create_engine engine = creat...
# -*- coding: utf-8 -*- """ Created on Wed Jan 2 16:14:47 2019 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt from lbl_ir.data_objects.ir_map import sample_info, ir_map def lorentzian(x,x0,gamma=10): return 1/(np.power((x-x0)/gamma,2)+1) def gaussian(x,x0=0,sigma=10): return 1/...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as sts from pprint import pprint import os from mnkutil import * sns.set_style('white') sns.set_style('white') sns.set_context('poster') sns.set_palette(['#E97F02', '#490A3D', '#BD1550']) def get_computer_se...
# -*- encoding: utf-8 -*- from sqlalchemy import func import random from datetime import datetime from datetime import timedelta from app.main.repository.interface.user_tbls import (PersonalDetailsRepository ,ReviewerProfileRepository ...
import pygame as pg import math from math import sqrt def crop_image(image, image_rect, crop_rect): '''Receives a surface, it's rect, and the rect of image to be cropped. Returns a surface.''' ix, iy, iw, ih = image_rect cx, cy, cw, ch = crop_rect #Trim from topleft of image to topleft of crop...
import networkx as nx import community import demon import numpy as np import pandas as pd import matplotlib.pyplot as plt import pickle import random import re from collections import Counter def prune_pages(links, categories): '''Remove pages dedicated to numbers and identifiers. Parameters: dict links:...
# Copyright (c) 2015 Mirantis, 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 requir...
__author__ = 'Mikhail' def add_line(line_one, line_two): """ >>> line_one = [1, 2, 3] >>> line_two = [1, 2, 3] >>> add_line(line_one, line_two) >>> line_one [2, 4, 6] >>> line_two [1, 2, 3] >>> add_line(line_two, line_one) >>> line_one [2, 4, 6] >>> line_two [3, 6, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ manage ~~~~~~ Open Schools Kenya management script Usage: build everything: ./manage.py build all build templates: ./manage.py build html build statics: ./manage.py build static [type] [--no-filters] ...
""" Based on https://github.com/nshepperd/gpt-2/blob/finetuning/train.py """ import json from pathlib import Path import sys import shutil from typing import List, Tuple import fire import numpy as np import matplotlib.pyplot as plt import sentencepiece as spm import tensorflow as tf import tqdm from . import model, ...
# # Copyright 2020 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...
from __future__ import print_function import readline import shlex import six import sys from .exceptions import JSHError class JSH(object): section = None def __init__( self, layout, prompt='> ', section_delims=('(', ')'), ignore_case=False, complete_on_spac...
""" pyaud.config ============ Includes constants, functions, and singleton for Toml config parsing. ``toml`` can be used with the external API for retrieving parsed config. Configs are parsed in the following order: | ~/.config/pyaud/pyaud.toml | ~/.pyaudrc | .pyaudrc | pyproject....
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # pte_sieve.py # # Sieving algorithm to find twin smooth integers using PTE solutions. import sys, time, datetime import ctypes from math import log, ceil from pathlib import Path from primes.parse import read_primes from sieve import sieve, c_lo...
import numpy as np from scipy import interpolate from .gps_jax import sample_gp, rbf_kernel class NHGPS(): """ This class is used for data generation from the NH-GPS model. """ def __init__(self, intensity_bound, time_bound, hypers, num_trials=1): """ This method initializes the mode...
# TensorFlow library import tensorflow.compat.v1 as tf # Keras library from tensorflow import keras # Pytorch library import torch from torchsummary import summary # Config import config as cfg # data # Channel: TensorFlow and Pytorch is channel last, but Keras is channel first n_inputs = 9 n_timesteps = 128 n_classes...
import json import logging import collections import h5py import sys sys.path.append('/Users/mishamesarcik/Workspace/phd/Workspace/lofar-dev/cluster_tools') import lofarReadSnippet from stations import stations logger = logging.getLogger(__name__) class ObservationDao(object): @staticmethod def read_sap_...
from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt from scipy.integrate import trapz import multiprocessing as mp import h5py def airy_func(wavelength, cos_th, d, F): Q = (2. * F / np.pi)**2 airy = 1.0 / (1.0 + Q * np.sin(np.pi * 2.e6 * d * cos_th / wavelength)**...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os.path as osp import logging, subprocess, os, shutil, re, pprint, csv from .termcolor import colored import svjgenprod logger = logging.getLogger('root') subprocess_logger = logging.getLogger('subprocess') class switchdir(ob...
from mycv.utils.general import disable_multithreads disable_multithreads() import os import time from pathlib import Path import argparse from tqdm import tqdm from collections import defaultdict import wandb import cv2 import torch import torch.cuda.amp as amp from torch.optim.lr_scheduler import LambdaLR from mycv.d...
#!/usr/bin/env python3 import sys import os import argparse import configparser import shutil import pandas as pd import subprocess as sp from qc import * from mapping import * from baseCalling import base_calling def get_parser(): parser = argparse.ArgumentParser(description='A Pipeline to process fast5.') r...
#!/usr/bin/python3 -B """ A convenience wrapper for Matplotlib. """ import sys # built-in module import time # built-in module import inspect # built-in module import warnings # built-in module import numpy as np # pip install...
#!/bin/env python3 import csv import json import yaml def import_HC_data(node_file, interaction_file, xref_source_file, xref_matrix_file, xref_i_file): SalmoNet = {"node": {}, "interaction": {}, "groups": {}, "strains": []} #lode xrefs xref = {"source": {}, "matrix": {}} with open(xref_source_file) as...
from collections import deque from threading import Thread from time import sleep from typing import Dict import numpy as np from core.data.command import Command from core.device.abstract import Connector from core.device.manager import DeviceManager from core.task.abstract import BaseTask from core.task.manager imp...
# -*- coding: utf-8 -*- """ minion.py - last updated 2021-05-27 Read MINION-formatted configuration data. ============================== Copyright 2021 <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 cop...
""" Pix2Surf Multi-View Version """ from .modelbase_v2 import ModelBase from .modelbase_v2 import Network as NetBase from core.models.utils import * from core.net_bank.pix2surf_cnn import SegNetGroup from core.net_bank.mlp import NOCS_AMP_MLP from core.net_bank.loss import MaskL2Loss import os import torch from torch ...
#!/usr/bin/env python ''' Analyzer for iPhone backup made by Apple iTunes (C)opyright 2011 <NAME> <<EMAIL>> Released under MIT licence smswindow.py provides the code to show a TK window to browse through the SQLite file which holds the SMS data in the iPhone Backup. ''' # IMPORTS -----------------------------...
"""Central module of the nodal package. Provides, among others, the classes meant for external usage: * Netlist: reads .csv files * Circuit: provides solve() method to compute electrical variables * Solution: printable object storing the computation results Example use case: from nodal import Circuit,...
# Imports import argparse import json import numpy as np import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models # Define network class class Network(nn.Module): def __init__(self, input_size, output_size, hidden_layers, drop_p=...
# -*- coding: utf-8 -*- """ Created on Sat Oct 27 11:58:26 2018 file_utils @author: GEO """ import os import sys import torch import shutil from datetime import datetime import pandas as pd from matplotlib import pyplot as plt def init_folders(base_output_dir, model_name, resume, logging): output_dir = os.path.j...
''' Scan through PDB and find helices at protein interfaces where the majority of the helix is part of the interface, with the idea that this means the helix will be laying mostly flat along the protein, maximizing its contact surface area. Usage: build_interface_list.py <num> [options] build_interface_list.p...
from __future__ import annotations import re from enum import Enum from epcpy.epc_schemes.base_scheme import EPCScheme, GS1Keyed, TagEncodable from epcpy.utils.common import ( ConvertException, binary_to_int, calculate_checksum, decode_partition_table, decode_string, encode_partition_table, ...
#This program provides a serial interface for a Superconductor Technologies Superlink cryocooler, returning the cold finger temperature, #rejection temperature, and power drawn. It also allows you to switch the cryocooler between auto and manual shutdown modes #I haven't used Python in ages, I'm sure there's goofs so...
#!/usr/bin/env python3 # coding=utf-8 from math import ceil, floor import librosa from librosa import display import numpy as np import pandas as pd import soundfile as sf from collections import namedtuple import re def load_csv(filename: str, sep=',') -> pd.DataFrame: # print('- loading %s' % filename) cs...
import json from typing import Any, Dict, List, TextIO from src import sv_vote from src import util FILENAME = 'sbb.txt' # Define SBB headings used to later parse the SBB during proof. BALLOT_RECEIPTS = 'ballot_receipts' ORIGINAL_ORDER_COMMITMENTS = 'original_order_commitments' MIXNET_VOTE_COMMITMENT_LIST = 'mixnet_...
import numpy as np from numba import jit import tensorflow as tf cB = np.array((0, 0, 0), dtype=np.float32) # --------- BOUNDARY c0 = np.array((255, 255, 255), dtype=np.float32) # --- STREET c1 = np.array((0, 0, 255), dtype=np.float32) # ------- HOUSE c2 = np.array((0, 255, 255), dtype=np.float32) # ----- LOW VEGE...
''' (c) University of Liverpool 2020 All rights reserved. @author: neilswainston ''' # pylint: disable=invalid-name # pylint: disable=no-member from ast import literal_eval as make_tuple import collections from functools import partial import json import sys from rdkit import Chem import matplotlib.pyplot as plt im...
#!/usr/bin/env python import math,operator,random,sys import numpy as np ####### #Probability Tools for DNA sequence analysis ####### def snr(observed,expected): return observed/expected def zscore(observed,expected): return (observed-expected)/math.sqrt(expected) def which_bin(bins, x, safe=0): """ ...
import socket import os import time import json import traceback, sys import csv #import pandas as pd List_of_files = 'C:\\Internet_Protocols\\List_of_files' csv_receivedlist = 'C:\\Internet_Protocols\\Received_list\\csv_receivedlist.csv' peer_list = [] Port_RS = 23475 Host_RS = '192.168.0.161' hostname = socke...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.template import loader from django.shortcuts import render from django.views.static import serve from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from django.conf import settings from django.forms.models imp...
import os from sqlalchemy import * from sqlalchemy.orm import create_session, relationship from sqlalchemy.ext.declarative import declarative_base uri = 'mysql://root@localhost/chembl_25' if 'CHEMBL_URI' in os.environ: uri = os.environ['CHEMBL_URI'] Base = declarative_base() engine = create_engine(uri) metadata =...
import pandas as pd pd.options.display.max_rows = 999 import numpy as np import poly_brute_force as poly def constraint_hamiltonian(qubo, num_problem_qubits, num_qubo_qubits): # construct constraint equations # auxiliary qubit a_ij = b_i b_j is enforced by # b_i b_j - 2 b_i a_ij - 2 b_j a_ij + 3 a_ij ...
#!/usr/bin/python import os, sys import json import numpy as np import re # GITHUB location: https://github.com/minogud2/ARC/blob/master/src/manual_solve.py ### YOUR CODE HERE: write at least three functions which solve ### specific tasks by transforming the input x and returning the ### result. Name them according ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow as tf import cv2 from utils.misc import get_center Rectangle = collections.namedtuple('Rectangle', ['x', 'y', 'width', 'height']) def get_gauss_filter...
from __future__ import absolute_import, division, print_function import cv2 import numpy as np import six def figure(fnum=None, pnum=(1, 1, 1), title=None, figtitle=None, doclf=False, docla=False, projection=None, **kwargs): """ http://matplotlib.org/users/gridspec.html Args: fnum (int...
class GraphNode(object): def __init__(self, val): self.value = val self.children = [] def add_child(self, new_node): self.children.append(new_node) def remove_child(self, del_node): if del_node in self.children: self.children.remove(del_node) class...
import mimetypes from typing import List from requests import RequestException from dothttp import DotHttpException, Config, HttpDef, Allhttp, BaseModelProcessor, UndefinedHttpToExtend from dothttp.request_base import CurlCompiler, RequestCompiler, HttpFileFormatter, dothttp_model from . import logger from ..models i...
# -*- coding: UTF-8 -*- import re import json import datetime import multiprocessing from django.db.models import Q from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect f...
import numpy as np import pandas as pd import os import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.ticker import LinearLocator import seaborn as sns from operator import itemgetter import matplotlib.ticker as ticker import math import matplotlib.patches as patches #run correla...
# type: ignore __all__ = [ "meshc", "barh", "trisurf", "compass", "isonormals", "plotutils", "ezcontour", "streamslice", "scatter", "rgb2ind", "usev6plotapi", "quiver", "streamline", "triplot", "tetramesh", "rose", "patch", "comet", "voronoi",...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
# coding=utf-8 from base.wrapper import DB, doc, Transaction from base.exeption import ElemNotFound from math import pi import logging from . import my_features, my_axles from base import exeption as ex class MyView: """ My view class with features: - crop view by CurveLoop - rotate view about z axi...
# pylint disable=anomalous-backslash-in-string import re import os from glob import glob from unidecode import unidecode from itertools import chain from nltk.tokenize import word_tokenize from nltk import FreqDist from nltk.downloader import download as nltk_download nltk_download("stopwords") nltk_download("punkt...
import unittest import os import datetime as dt import netCDF4 import numpy as np from forest import (eida50, satellite, navigate) from forest.exceptions import FileNotFound, IndexNotFound class TestLocator(unittest.TestCase): def setUp(self): self.paths = [] self.pattern = "test-eida50*.nc" ...
import torch from torch import nn from torch import optim # Take any network, train it on the training data, test it on the testing data, return the final errors def train_model(model, crit, optimizer, n_epochs, btch_size, train_i, train_t, train_c, test_i, test_t, test_c): # Go through the training set for sev...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
"""Module containing functions used to trace API calls end to end. All functions in the module use OpenTracing framework in conjuction with a Jaeger server to provide comprehensice API Tracing Capabilites""" import logging import json import datetime import sys import opentracing import requests import bottle import...
from botocore.exceptions import ClientError from unittest.mock import MagicMock from senza.aws import (get_security_group, resolve_security_groups, get_account_id, get_account_alias, list_kms_keys, encrypt, get_vpc_attribute, resolve_referenced_resource, ...