text
stringlengths
3.07k
12.6k
"""Internal GGA implementations.""" # List exported symbols for doc generation __all__ = ["x_pbe", "c_pbe"] from .functional import Functional from .lda import get_rs, _C_PW, SpinInterpolate1, SpinInterpolate3 import numpy as np import torch def x_pbe(sol: bool, scale_factor: float = 1.0) -> Functional: """Creat...
import enum import gzip import pickle from .base import Player from .map import Map class ActionType(enum.Enum): target = 0 clear_target = 1 stop = 2 class Command(object): '''a command received from a player {'id': '<uuid>', 'action': '<action-type>.name', 'target': '<uuid>' | {'posx': X, 'pos...
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 ~ 2012 Deepin, Inc. # 2012 smallevilbeast # # Author: smallevilbeast <<EMAIL>> # Maintainer: smallevilbeast <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pu...
# coding: utf8 """ weasyprint.html --------------- Specific handling for some HTML elements, especially replaced elements. Replaced elements (eg. <img> elements) are rendered externally and behave as an atomic opaque box in CSS. In general, they may or may not have intrinsic dimensions. But th...
__version__ = '0.1dev' import os, sys #from twyg.cairowrapper import context as ctx from twyg.common import calculate_margins, loadjson from twyg.config import (NODE_CONFIG, CONNECTION_CONFIG, LAYOUT_CONFIG, COLOR_CONFIG, STYLE, DEFAULT_LEVEL, Level, SectionLevel, Co...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt w = np.linspace(0,60,1000) def direction(velocity): # if unit_vector[1] == 0.0: # if unit_vector[0] > 0: # theta = 0.5 * np.pi # else: # theta = 1.5 * np.pi # else: theta = np.arctan2(velocit...
"""Module for ETL cancer hotspots data""" import logging from timeit import default_timer as timer from datetime import datetime from typing import Optional from pathlib import Path import requests import pandas as pd from variation.query import QueryHandler from evidence import DATA_DIR_PATH from evidence.data_sourc...
"""Auxiliary-function-based independent vector analysis.""" import numpy as np from .update_rules import update_spatial_model, update_covariance from .utils import demix eps = np.finfo(np.float64).eps def projection_back_frame(W, ref_mic=0): """ Perform projection-back technique for online AuxIVA algorithm....
from collections import abc import torch from torch._six import string_classes from torch.nn.parallel.scatter_gather import gather from torchdistill.common.module_util import check_if_wrapped, get_module def get_device_index(data): if isinstance(data, torch.Tensor): device = data.device return '...
#!/usr/bin/env python3 # See import_boost.py for usage. import argparse import json import re import urllib.request import os import os.path import shutil import bru import copy from collections import OrderedDict import pdb # only if you want to add pdb.set_trace() def get_library(): return bru.get_library() de...
from __future__ import division import math import pdfminer from collections import defaultdict import itertools from pdfminer.high_level import extract_pages,extract_text,extract_text_to_fp from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage fro...
from __future__ import print_function, division, absolute_import import atexit from datetime import timedelta import json import logging import os import shutil import socket from sys import argv, exit import sys from time import sleep import click from distributed import Nanny, Worker, rpc from distributed.nanny imp...
import numpy as np from skimage.exposure import rescale_intensity from hexrd.transforms.xfcapi import \ anglesToGVec, \ gvecToDetectorXY from hexrd import constants as cnst from hexrd.ui.hexrd_config import HexrdConfig from hexrd.ui.utils import run_snip1d, snip_width_pixels tvec_c = cnst.zeros_3 def s...
import os import sys cwd = os.getcwd() sys.path.insert(0, cwd+'/../..') from plot.box.utils_plot import * from plot.box.paths_puddle import * def top_param(): calibration = { "knn": pdrand_knn_5k, "knn(laplace)": pdrand_laplace_knn_test1_5k, # "network": pdrand_network_5k, # "networ...
# Originated from https://github.com/amdegroot/ssd.pytorch/issues/422 """Adapted from: @longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch @rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn Licensed under The MIT License """ import torch from torch.autograd impor...
import requests from bs4 import BeautifulSoup as bs from random import * from random import uniform, random, choice, sample from time import sleep import string import _thread from flask import Flask, render_template, request, redirect from datetime import datetime import logging import json import webbrowser from stri...
import sys from os.path import dirname, join as path_join sys.path.insert(0, path_join(dirname(__file__), "..")) sys.path.insert(0, path_join(dirname(__file__), "robo")) sys.path.insert(0, path_join(dirname(__file__), "pysgmcmc_development")) from pysgmcmc_experiments.experiment_wrapper import to_experiment import num...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ==================== # Set-up # ==================== # Import required modules import datetime import os import gc import glob import re from identities_tools.graph_tools import * __author__ = '<NAME>' __license__ = 'MIT License' __version__ = ...
import jsonlines import argparse import collections import json import numpy as np import os import re import string import sys from tqdm import tqdm import random import glob import pdb from lib.dbengine import DBEngine, DBEngineSqlite3 from lib.query import Query from lib.common import count_lines import multiproce...
from __future__ import annotations import asyncio import collections import dataclasses import inspect import re import typing as ty from vkquick.base.event import EventType from vkquick.chatbot.base.filter import BaseFilter from vkquick.chatbot.base.handler_container import HandlerMixin from vkquick.chatbot.command....
import pygame from typing import Optional, Type, Callable, Set, Tuple, Any, List from pyioc3 import StaticContainerBuilder, Container, ScopeEnum from .typing import IGame, IObjectFactory, ISystemManager, IEntityManager, PROVIDER_T from .system_manager import SystemManager from .entity_manager import EntityManagerOpts, ...
from math import * from model.Unit import Unit from model.HockeyistState import HockeyistState from model.HockeyistType import HockeyistType from CommonFunctions import * def dir(me: Unit): return 1 if abs(me.get_angle_to(me.x + me.speed_x, me.y + me.speed_y)) <= pi/2 else -1 def travel_time(start_dist, start_sp...
from copy import copy, deepcopy import torch from torch import nn from torch.optim import Adam from maddpg.trainer.replay_buffer import ReplayBuffer from maddpg.common.torch_utils import init_params @torch.no_grad() def make_update_exp(source, target, polyak=1e-2): for p, p_targ in zip(source.parameters(), targ...
import base64 import io import os.path import struct import urllib.request from functools import partial import bs4 import concurrent.futures from .lib.markdown2 import Markdown markdowner = Markdown(extras=["code-friendly", "fenced-code-blocks", "cuddled-lists"]) executor = concurrent.futures.ThreadPoolExecutor(max...
import math import numpy as np import spacy from gensim import models from gensim.corpora import Dictionary from gensim.matutils import sparse2full from gensim.models.tfidfmodel import TfidfModel # Text2Vec Class class Text2Vec: def __init__(self, doc_list): # Initialize self.doc_list = doc_list ...
from __future__ import print_function from collections import defaultdict from pcmdi_metrics.driver.pmp_parser import PMPParser import copy import collections import datetime import glob import os import sys import pcmdi_metrics import re def AddParserArgument(): P = PMPParser() # Includes all default options ...
import functools from ipaddress import IPv4Network import container import handle from dock import client class Net: def __init__(self, addr): self.reserved = set() self.net = IPv4Network(addr) def reserve(self, ip): self.reserved.add(ip) def free(self, ip): ...
import tensorflow as tf from builders.layers.helpers import build_mlp from builders.utils import gather class GraphTripleConvLayer(tf.keras.layers.Layer): def __init__(self, input_dim, attributes_dim=0, output_dim=None, hidden_dim=512, pooling='avg', mlp_normalization='none', a...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
import os import pickle class dataio: #TODO if we are REALLY paranoid we can open the file back up and check that it matches what we have in memory... """ class to manage input and output of data to disk this way we can retain a lock on the files for the duration of our program run time and not have nasty ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020 <NAME> # # This file is not for redistribution. """ Unit tests for mosa.DBInterface class. NOTE ON TEST DATABASE AND DUMMY USER. These tests run on a local database that has the same format as the one on biomec.uqam.ca. However, for the tests and tutor...
"""Modules for ResNet_Variant.""" import torch.nn as nn from mmdet.models.backbones.resnet import ResNet from mmdet.models.registry import BACKBONES from mmdet.models.utils import build_conv_layer, build_norm_layer from torch.nn.modules.batchnorm import _BatchNorm def make_res_layer(block, inplane...
# -*- coding: utf-8 -*- """stylecheck does style check of ken3 source code. check all header and source files are written in common style. """ from collections import namedtuple import glob import sys __author__ = 'toda' __version__ = '1.0.0' def pick_names(root_dir): """Pick hpp and cpp files from root_dir. ...
import io, struct def remove_photoshop_tiff_data(f): try: result = _remove_photoshop_tiff_data_inner(f) result.seek(0) return result except OSError: # If reading the file failed for some reason, just seek back and return it. f.seek(0) return f def _remove_photos...
import socket import struct import binascii STRING_ONE_TAB="\t" STRING_TWO_TAB="\t\t" STRING_THREE_TAB="\t\t\t" def get_mac_addr(mac_raw): byte_str = map('{:02x}'.format, mac_raw) mac_addr = ':'.join(byte_str).upper() return mac_addr class Ethernet(): """class for separate ethernet frame""" def...
from pylab import * from collections import namedtuple from .varifolds import Varifolds, Varifold from .currents import Currents, Current Cylinders = namedtuple('Cylinders', 'centers normals weights') Spherical = namedtuple('Spherical', 'points directions weights') class NormalCycle : def __init__(self, cylinders, ...
# -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020, <NAME> <<EMAIL>> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for license details. """ """ from .. import Uni...
# 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 ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from typing import Any, Union import asyncio from bleak import BleakClient, BleakScanner, discover as bleak_discover from bleak.exc import BleakError async def discover() -> list: """Discover BLE devices.""" devices = await bleak_discover() if devices: devices_list = [{d.name: d.address} for d in ...
import torch import argparse import json import os import yaml import numpy as np from tqdm import tqdm import time from numpyencoder import NumpyEncoder from src.training_manager import TrainPipeline from src.model_manager import flatten_grads, dist_grads_to_model device = torch.device("cuda" if torch.cuda.is_availa...
# coding:utf-8 ## based on https://github.com/dmlc/mxnet/issues/1302 ## Parses the model fit log file and generates a train/val vs epoch plot import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import numpy as np import re import argparse parser = argparse.ArgumentParser(d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Utility module for reading spikes, fluorescence, and true network scores from files. Created on Thu Aug 24 15:48:48 2017 @author: paul.herringer """ import numpy as np def read_spike_trains(files, timebin=20, data_type='sim', binning='no limit'): """Reads spik...
import numpy as np import math number_of_features = 0 number_of_classes = 0 dataset_size = 0 Processed_DataSet = {} class DataStore: def __init__(self, class_name): self.class_name = class_name self.features = [] self.mean = [] self.sd = [] self.transpose = [] self....
#!/usr/bin/env python3 from urllib.parse import urljoin, urlparse, quote, unquote from xml.dom import minidom import dateutil.parser import requests import urllib3 # configure package (disable warning for self-signed certificate) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # some consts HTTP_...
import argparse import os import numpy as np import tensorflow as tf import scipy.io as scio from model_f0 import CycleGAN as CycleGAN_f0 from model_mceps import CycleGAN as CycleGAN_mceps from preprocess import * from utils import get_lf0_cwt_norm,norm_scale,denormalize from utils import get_cont_lf0, get_lf0_cwt,in...
# TODO: Converters need to be on the application class so they have access to __author__ = 'Brian' from google.appengine.ext import db from google.appengine.api import datastore_types from dateutil import parser as date_parser import datetime from importlib import import_module FROM_PROPERTY = 0 TO_PROPERTY = 1 def ...
import os import os.path from PIL import Image import tkinter as tk import itertools import math import time import datetime import random def GetX(ptX : int, box=(-0.5, 0.0, 1.0)): return (box[0] + (float(ptX)-720.)/2./720.*4.0/box[2]) def GetY(ptY : int, box=(-0.5, 0.0, 1.0)): return (box[1] - (f...
# Copyright 2004-2014 <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 without limitation the rights to use, copy, modify, merge, # publish,...
import os import numpy as np from PIL import Image import torch.utils.data as data from torchvision import transforms import custom_transforms as tr import tifffile as tiff import torch class potsdam(data.Dataset): def __init__(self, base_dir='./data', state='train', mean_std=False): super(potsdam, self)....
"""Try to compare between the old and new OSC scripts. """ import copy import os from datetime import datetime import json from glob import glob import numpy as np from itertools import zip_longest OLD_REPO_DIR = '../sne/' NEW_REPO_DIR = './astrocats/supernovae/output/' LIMIT_TRIES = 20 FAILURE_LIMIT = 2 def main():...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # TODO: use logging module to log everything # TODO: show all downlable tv shows in a beautiful tab and select each one you want to download # TODO: use classes to define providers # TODO: move utils functions in an external module # TODO: define filters outside import r...
import json import re import pprint import os import argparse import pandas as pd import random import numpy as np from tqdm import tqdm SQUAD_TEST_HEADS = ['where were', 'what political', 'what religion', 'why did', 'what type', 'what language', 'who had', 'what percentage', 'what can', 'how much'] def strip(sent):...
import logging import os import pprint import tempfile from urlparse import urlparse, parse_qs from urllib import unquote from assemblyline.common.exceptions import get_stacktrace_info from assemblyline.common.net import get_hostip, get_hostname from assemblyline.al.common import forge from assemblyline.al.common.tra...
""" Generic DockCI utils """ import hashlib import hmac import logging import re import socket import struct import subprocess import json import datetime from contextlib import contextmanager from ipaddress import ip_address import docker.errors from flask import flash, request from yaml_model import ValidationErro...
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import os import logging import json import tempfile import shutil import hashlib from pathlib import Path from tqdm import tqdm from che...
import copy from functools import reduce import theano.tensor as T from neupy.core.properties import IntProperty, CallableProperty from neupy.exceptions import LayerConnectionError from neupy.utils import as_tuple, all_equal from .base import BaseLayer __all__ = ('Elementwise', 'Concatenate', 'GatedAverage') clas...
import sys import os import torch import torch.nn as nn import numpy as np import pandas as pd import time import torch.backends.cudnn as cudnn from my_dataset import SegmentationDataset, provider from meter import Meter from tqdm import tqdm from ranger import Ranger from lookahead import LookaheadAdam from loss impo...
import cv2 import numpy as np import math import serial from socket import * import time import threading import sys #se indica la direccion y puerto del servidor que recibe todo los datos #el puerto por defecto es el 3001 socketInfo = ["localhost", 3001] #funcion que estima el numero de dedos abiertos y cerrados en...
from pycsim import CSim import json import time SENSOR_RETRY = 40 SENSOR_RETRY_SLEEP = 0.01 class RobotModel: def __init__(self, name: str, api: CSim): self._api = api self._name = name self._sensors = None # some kind of collection class self._actuators = None # idem class...
"""Expression detection game component.""" import multiprocessing as mp from functools import partial from multiprocessing.connection import Connection import cv2 from fer import FER from numpy import ndarray from .enums import CommandEnum, ErrorEnum, EventEnum from .exceptions import CameraError from .types import ...
import torch import torch.nn as nn import math def conv_bn(inp, oup, stride): return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.ReLU6(inplace=True) ) def conv_1x1_bn(inp, oup): return nn.Sequential( nn.Conv2d(inp, oup, 1, 1, 0, b...
#!/usr/bin/env python3 # Copyright 2004-present Facebook. All Rights Reserved. import logging import argparse import json import numpy as np import os import torch import plyfile import sys import deep_sdf import deep_sdf.workspace as ws def save_to_ply(verts, verts_warped, faces, ply_filename_out): num_verts =...
from django.db import models from django.contrib.postgres.fields import ArrayField, JSONField import boto3 from django.core.mail import EmailMultiAlternatives from django.conf import settings from datetime import datetime SNS_ENABLED = settings.SNS_ENABLED or False SNS_ACCESS_KEY = settings.SNS_ACCESS_KEY or None SNS_...
import logging import statistics import typing import boto3 import click from boto3.dynamodb.conditions import Key import cdk_s3_sns_latency.cdk_s3_sns_latency_stack as stack BUCKET_WITH_LAMBDA: str = None BUCKET_WITH_SNS: str = None MEASUREMENT_TABLE_NAME: str = None GENERATOR_FUNCTION_NAME: str = None def get_c...
import argparse import os import batchgenerators.transforms as bg_tfm import matplotlib.pyplot as plt import numpy as np import torchio as tio import pymia.data.transformation as tfm import pymia.data.augmentation as augm import pymia.data.definition as defs import pymia.data.extraction as extr class Batchgenerator...
# coding=utf-8 # Copyright 2018 The Interval Bound Propagation Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required ...
from DeepNodes.layers import * from DeepNodes.types import * from DeepNodes.activations import * import torch import math from torch.nn import Parameter, init import torch.nn.functional as F from collections import namedtuple class _ConvNd(Layer): def __init__(self, n, name, input_shape, output_shape, kernel_siz...
import logging from copy import deepcopy class Bear(): def __init_subclass__(cls, **kwargs): # intercept the kwargs in the init_subclass call super().__init_subclass__() def __init__(self, **d): """Features: 0. Take in a list of keyword arguments in constructor, and assign t...
"""! This file contains some pair potentials. \ingroup lammpstools """ import lammpstools import dumpreader import numpy as np import math import sys # Curryable pair potentials: class pair_lj: """ !Pair potential for LJ. """ def __init__(self, epsilon, sigma ): self.epsilon = epsilon self....
# coding=utf-8 # Copyright 2021 The OneFlow Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
from typing import List, Union, Dict, Tuple, TYPE_CHECKING if TYPE_CHECKING: from codelets.adl.operation import Operation, Loop, Compute, Configure, Transfer from codelets.codelet_impl.codelet import Codelet from sympy import Basic, Idx TileConstraint = Dict[Tuple[str, str], Tuple[int, int]] def unroll(loo...
""" DSM module. Contains the DesignStructureMatrix, DomainMappingMatrix and MultipleDomainMatrix classes. """ from typing import List, Tuple from archan.errors import DesignStructureMatrixError, DomainMappingMatrixError, MatrixError, MultipleDomainMatrixError def validate_rows_length(data, length, message=None, ex...
import requests, re from bs4 import BeautifulSoup import pandas as pd import folium from folium.plugins import Draw r=requests.get("https://www.coronavirus2020.kz/ru") c=r.content soup=BeautifulSoup(c,"html.parser") all=soup.find_all("div",{"class":"city_cov"}) covid_19 = (all[0].text).replace('\t\t',' ').replace('\n...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\gsi_handlers\club_handlers.py # Compiled at: 2015-10-23 00:53:54 # Size of source mod 2**32: 6372 by...
#!/usr/bin/env python3 import base def tasks(): return [ RegionalDensities(), ] class RegionalDensities(base.Task): """ Calculates the global mutation density and the (absolute and relative) densities in specific regions and region types. """ def __init__(self): super(Reg...
import logging import xml.dom.minidom as minidom import hashlib, binascii from content import read_chunked, query_params, compress, decompress import qxml def is_signed(req): return 'X-ADP-Request-Digest' in req.headers def get_query_params(req): _, _, query = req.path.partition('?') if query: return query_par...
import os import sys import json import platform from os.path import expanduser from configparser import ConfigParser with open('lynx.json') as f: data = json.load(f) CURRENT_OS = platform.system() OS_HOME = expanduser("~") STEALTH_FLAG = 0 configur = ConfigParser() BASE_PATH = data['package']['profile'] DOWNLO...
from functools import partial from typing import Optional, Tuple, List import numpy from numpy.typing import ArrayLike from scipy.ndimage import gaussian_filter from aydin.it.classic_denoisers import _defaults from aydin.util.crop.rep_crop import representative_crop from aydin.util.j_invariance.j_invariance import ca...
import pyyed import random import yaml def readNetDefination(filePath) -> dict: with open(filePath, 'r') as stream: try: data= yaml.safe_load(stream) except yaml.YAMLError as exc: print(exc) return data def getRandomColor(): r = lambda: random.randint(105,255) color = (...
from threading import Thread, Event import importlib import atexit from time import sleep import Queue from helpers import read_config listener = None class CallbackException(Exception): def __init__(self, code=0, message=""): self.code = code self.message = message class InputListener(): """...
# -*- coding: utf-8 -*- import os import re import statistics import subprocess import tempfile import time from pyutils import env, log def run(command, **kwargs): if not command: raise ValueError('No command provided') log.info('Invoking', ' '.join(command)) start = time.time() try: ...
# -*- coding: utf-8 -*- """ Created on Mon Apr 6 19:11:27 2020 Information Retrieval Assignment 3 """ import pandas as pd import re from nltk.tokenize import word_tokenize from nltk.corpus import stopwords from nltk.stem import PorterStemmer from sklearn.model_selection import train_test_split from sklearn.metrics ...
# sqlvariant, allow defining 3 namespaces to override defaults from ..translate import ( SqlColumn, SqlColumnAgg, extend_base, SqlTranslator, sql_not_impl, win_cumul, win_agg, annotate, wrap_annotate ) from .base import base_nowin #from .postgresql import...
# Author: HereIronman7746 # License: MIT # Version: Alpha import requests from bs4 import BeautifulSoup import os import js2py from clint.textui import progress base = "https://vidembed.io" headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.39...
import torch import torch.nn as nn ########################################################## # Enhanced Deep (Residual Networks for) Super Resolution # ########################################################## class MeanShift(nn.Conv2d): """Mean Shift""" def __init__(self, rgb_mean, std, sign): sup...
#!/usr/bin/python -u # -*- coding: latin-1 -*- # # Killer Sudoku in Z3 # # http://en.wikipedia.org/wiki/Killer_Sudoku # ''' # Killer sudoku (also killer su doku, sumdoku, sum doku, addoku, or # samunamupure) is a puzzle that combines elements of sudoku and kakuro. # Despite the name, the simpler killer sudokus can be ...
import torch import numpy as np from .vitali import * from .utils import * # # def shapley(C, control_cutoff): # def adjust_for_external_ownership(ol, g): assert torch.min(ol) >= 0 and torch.max(ol) <= 1, "ol was outside bounds" C = g.ownership.clone() non_root_nodes = g.identify_controllable() # only non-r...
#!/usr/bin/python # Copyright (c) 2017, NVIDIA CORPORATION. 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 l...
import black import os from textwrap import dedent import pandas as pd import os.path from pathlib import Path import dash import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dash import no_update from dash.dependencies import Input, Output, State im...
#!/usr/bin/env python3 import json import os import re import subprocess from argparse import ArgumentParser from collections import defaultdict from tempfile import NamedTemporaryFile DOT_EXAMPLE = """ ```dot digraph mygraph { nodeA -> nodeB [label="AB edge-label"] nodeB -> nodeC [label="BC edge-label"] ...
#!/usr/bin/env python # coding=utf-8 """ Vagrant external inventory script. Automatically searches for Vagrant boxes under the configured directory and returns that inventory with SSH configuration and the contents of the hosts' var file for each host. Hosts will all be placed under the `vagrant' group and additionall...
""" The attr_computing.py provides two methods for computing channel Shapley and transform them to feature attributions. """ import numpy as np import tensorflow as tf import lucid.optvis.render as render from lucid.misc.gradient_override import gradient_override_map import re def compute_igsg(img, model, attr_class,...
# coding=utf-8 # __author__ = 'Mio' from math import ceil from os import remove from pathlib import Path from sqlalchemy import desc from sanic.exceptions import abort from sanic.response import json, file_stream from sanic.views import HTTPMethodView from sanic.log import logger as logging from schema import Schema, ...
import cv2 import yaml from tqdm import tqdm import os from dotmap import DotMap import numpy as np # Change the options below for each of the new submissions. config = yaml.safe_load(''' ########################################################################## # This is the main config file for your method. Please f...
import json from django.http import HttpResponse from django.shortcuts import render from UserAPP.models import User,UserLog from VoteAPP.models import Competitor, Vote #选手表、用户投票记录表 # Create your views here. ##########################################################################################################...
import copy import operator CURRENT_MATCH = 37 class Team: CSK = "CSK" SRH = "SRH" RCB = "RCB" MI = "MI" KXIP = "KXIP" DD = "DD" KKR = "KKR" RR = "RR" class Constants: MAX_FIXTURE = 56 points = {Team.CSK: 14, Team.SRH: 14, Team.RCB: 6, ...
""" Module for conversions between star and chain geometry coefficients """ import numpy as np from scipy.linalg import eigh_tridiagonal from math import fsum try: from mpmath import mp, eigsy except ImportError: print('WARNING: No installation of mpmath detected, this may result in inaccuracies in chain to...
import base64 import os import struct import six from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat...
import os from gym_pcgrl.envs.probs.zelda_prob import ZeldaProblem from gym_pcgrl.envs.reps.wide_rep import WideRepresentation from gym.envs.classic_control import rendering from gym_pcgrl.envs.reps import REPRESENTATIONS from gym_pcgrl.envs.pcgrl_env import PcgilOrderlessEnv as PcgrlEnv #PcgrlEnv from utils import T...
#!/usr/bin/env python # -*- coding: utf-8 -*- import time from string import Template import itertools import gevent from gevent.monkey import patch_socket patch_socket() import requests from bs4 import BeautifulSoup def find_hidden_inputs(html): """Returns input elements whose type are hidden. """ ...