text
stringlengths
3.07k
22.1k
# Code adapted from https://github.com/google-research/google-research/tree/master/flax_models/cifar # Original copyright statement: # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ...
import argparse import json import time import sys,os, copy import tensorflow as tf import numpy as np # sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from competitor.common.paths import RESULTS_DIR from competitor.models.loader import load_model, load_env from competitor.heurist...
from lib import log from lib.log import exception, warning from version import VERSION_FOR_BUG_REPORTS from paths import CLIENT_LOG_PATH log.set_version(VERSION_FOR_BUG_REPORTS) log.add_secure_file_handler(CLIENT_LOG_PATH, "w") log.add_http_handler("http://jlpo.free.fr/soundrts/metaserver") log.add_console_handler() i...
from django.contrib.gis import admin from .models import (Photographer, PhotoSubcategory, Photo, PhotoFlag, PhotoCategory) from django.utils.safestring import mark_safe from django.contrib.admin import SimpleListFilter from django.contrib.gis.db import models from django.urls.base import reverse fr...
"""This module provides classes for performing syntactic aggregation. For example, 'Roman is programming.' and 'Roman is singing' can be put together to create 'Roman is programming and singing.' """ import logging from copy import deepcopy from nlglib.features import NUMBER, category from nlglib.macroplanning imp...
#!/usr/bin/env python3 # Copyright 2018 The MLPerf 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 ...
from django.shortcuts import get_object_or_404, get_list_or_404 from django.http import Http404 from django.db.models import Q from django.contrib.postgres.search import SearchQuery from django.utils import timezone from rest_framework.views import APIView from rest_framework.response import Response from rest_framewo...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create the data for the LSTM. """ import os import sys import argparse import numpy as np import h5py import itertools from collections import defaultdict class Indexer: def __init__(self, symbols = ["<blank>","<unk>","<s>","</s>"]): self.vocab = defaultdi...
"""functions related to sampling handful of functions here, related to sampling and checking whether you're sampling correctly, in order to avoid aliasing when doing something like strided convolution or using the pooling windows from plenoptic, you want to make sure you're sampling the image appropriately, in order ...
""" /*************************************************************************** Plugin Installer module Plugin version comparison functions ------------------- Date : 2008-11-24 Copyright : (C) 2008 by <NAME...
import urllib.request from bs4 import BeautifulSoup from django.core.exceptions import ObjectDoesNotExist import re from standard.models import * from projects.models import * dwc_url = 'http://rs.tdwg.org/dwc/terms/' simple_dwc_url ='http://rs.tdwg.org/dwc/terms/simple/' def get_dwc_html(url=dwc_url): opener = ...
""" Specification for objects to be accessed, for the purpose of dataframe interchange between libraries, via the ``__dataframe__`` method on a libraries' data frame object. For guiding requirements, see https://github.com/data-apis/dataframe-api/pull/35 Concepts in this design ----------------------- 1. A `Buffer`...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Copyright (c) 2021 # # See the LICENSE file for details # see the AUTHORS file for authors # ---------------------------------------------------------------------- #-------------------- # System wide imports # ----------...
#!/usr/bin/env python3 import argparse import copy from collections import defaultdict from pathlib import Path import os import sys import time import numpy as np import pandas as pd from sklearn.metrics import f1_score, precision_recall_fscore_support, log_loss, average_precision_score import torch import torch.opt...
import json import platform import subprocess import time import requests from ._version import __version__ # noqa: F401 class NotificationError(Exception): '''Notification Error''' pass class BaseNotification: '''Notification Superclass''' def set_typed_variable(self, value, specified_type): ...
import re import collections import xml.etree.ElementTree as ET import itertools from . import DEFAULT_CP2K_INPUT_XML class GeneratorError(Exception): pass class SectionNotFoundError(Exception): pass class KeywordNotFoundError(Exception): pass class SectionParametersNotFoundError(Exception): pa...
import os import numpy as np import cv2 import sys import argparse import pathlib import glob import time sys.path.append('../../') from util import env, inverse, project_so, make_dirs from mesh import Mesh import scipy.io as sio """ Draw a 3 by n point cloud using open3d library """ def draw(vertex): import o...
import time import os import gym import gym_panda import reflexxes import pybullet as p import math import numpy as np import cv2 import pandas as pd class MovementData: def __init__(self, id): self.mov_id=id self.currentPosition = [0.0, 0.0, 0.0]*2 self.currentVelocity = [0.0, 0.0, 0.0]*2 ...
from pathlib import Path import numpy as np import pandas as pd import nibabel as nib import matplotlib.pyplot as plt import matplotlib.ticker as mtick color_tables_dir = Path(__file__).parent class Parcellation: def __init__(self, parcellation_path): self.parcellation_path = Path(parcellation_path) ...
# -*- coding: utf-8 -*- import os import asyncio from hashlib import md5 from pathlib import Path from tempfile import mkstemp from base64 import b64decode, b64encode from collections import namedtuple from lxml import etree from .. import getLogger from ..errors import (BadRequestStanzaError, XmppError, ...
#!/usr/bin/python from jinja2 import Template, Environment, FileSystemLoader import json import autopep8 import os import re import sys def replaceSpecialChars(str): return str.replace('-', '_').replace('.', '_').replace('+', 'plus') def getModuleName(path, name): return replaceSpecialChars(path.lower()) + "...
#!/usr/bin/env python # coding: utf-8 import os import dash import dash_core_components as dcc import dash_html_components as html import dash_table as dt import plotly as py import plotly.graph_objects as go import pandas as pd import numpy as np # init dash app from dash.dependencies import Input, Output from src....
#!/usr/bin/env python3 import itertools from os.path import join, exists from os import mkdir from sys import stderr import argparse # command for finding the best configuration from log*.err files # for X in log.*.err ; do cat $X | grep acc | sed "s/\(epoch [^ ]*\)\(.* acc: \)\([^ ]*\).*/\3 \1 $X/" ; done | sort -n...
import datetime import django from django import db from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.shortcuts import _get_queryset from django.utils import six from django.utils.text import slugify try: from django.utils import timezone except ImportError: t...
# mypy: allow-untyped-defs, no-strict-optional import pytest from advpipe.language_model.label_classification import OrganismLabelClassifier @pytest.fixture def organism_label_classifier(): return OrganismLabelClassifier() organism_labels = [ 'Arctic Wolf', 'Basilisk', 'Black panther', 'Bobolin...
import csv import numpy as np from lightfm import LightFM import scipy.sparse from sklearn.metrics import label_ranking_average_precision_score import math import random import pickle def loadUserFeatures(i_file, n_users): print('Loading user graph...') A = scipy.sparse.lil_matrix((n_users, n_users), dtype=in...
#!/usr/bin/env python2 import cv2 import sys, random, socket, struct import numpy as np from math import sqrt, sin, cos, pi, atan2, fmod ################# # Choose camera # ################# camera = ' '.join(sys.argv[1:]) try: v = int(camera) camera = v except ValueError: pass if camera == '': camera = 0 #####...
# vim: expandtab:ts=4:sw=4 import numpy as np import scipy.linalg import pdb """ Table for the 0.95 quantile of the chi-square distribution with N degrees of freedom (contains values for N=1, ..., 9). Taken from MATLAB/Octave's chi2inv function and used as Mahalanobis gating threshold. """ chi2inv95 = { 1: 3.8415,...
# Authors: <NAME> <<EMAIL>> # + All contributors to <https://github.com/smarie/python-odsclient> # # License: 3-clause BSD, <https://github.com/smarie/python-odsclient/blob/master/LICENSE> from subprocess import call try: import click except ImportError as e: raise Exception("`click` is required f...
# Copyright (c) 2022 Serum # 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, distribute, su...
"""Implementation of custom session system. Credit for this can go to the warehouse project where I find how to implement custom session system with redis. Differences are noted: - Warehouse use it's own implementation for the TimestampSigner and BadSignature - The factory session does not initialize Redis exac...
#!/usr/bin/env python """Wrapper script with bjobs functionality.""" from __future__ import print_function import sys import re import argparse from utility import color from useraliases import lookupalias from shortcuts import ejobsshortcuts from readjobs import readjobs from printjobs import printjobs from groupj...
# Look for #IMPLEMENT tags in this file. These tags indicate what has # to be implemented to complete the warehouse domain. # You may add only standard python imports---i.e., ones that are automatically # available on TEACH.CS # You may not remove any imports. # You may not import or otherwise source any o...
"""Components for searching for taxa""" from logging import getLogger from typing import Optional from pyinaturalist import RANKS, IconPhoto, Taxon from PySide6.QtCore import QSize, Qt, Signal, Slot from PySide6.QtGui import QIcon from PySide6.QtWidgets import QApplication, QComboBox, QLabel, QPushButton, QWidget fro...
# -*-coding:utf-8 -*- ''' @File : test_helper.py @Author : <NAME> @Date : 2020/8/2 @Desc : ''' import tensorflow as tf import numpy as np from QuestionAnswerSummaryAndReasoning.seq2seq_tf2.batcher import output_to_words from tqdm import tqdm def greedy_decode(model, dataset, vocab, params): ...
from typing import NamedTuple, Tuple, Dict, List, Any from .quiche_tree import QuicheTree from .rewrite import Rule class EClassID: def __init__(self, id, parent: "EClassID" = None): self.id = id self.parent = parent # List of tuples of (ENode, EClassID) of enodes that use this EClassID ...
# -*- coding: utf-8 -*- from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient from serial_data import SerialData import logging import pika import argparse import time import json LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.g...
"""Bloch contiuous rotation experiment""" import importlib as imp import os,numpy as np from subprocess import Popen from typing import TYPE_CHECKING, Dict, Iterable, Optional, Sequence, Union from utils import displayStandards as dsp #;imp.reload(dsp) from EDutils import display as EDdisp #;imp.reload(EDdisp) ...
# Author of Aqsa: <NAME> from aqsa_apps.wallet_tag_etc import models as wte_m from aqsa_apps import sql_custom as sql from . import models as m from django.contrib.auth.mixins import LoginRequiredMixin from aqsa_apps import mixins as mix from django.utils.translation import ugettext as _ from django.views.generic.edit ...
import asyncio import logging import re import socket import warnings from asyncio import AbstractEventLoop from ipaddress import ip_address, IPv4Network from abc import ABCMeta from abc import abstractmethod from typing import Callable from typing import List from typing import Optional from typing import Tuple M...
#!/usr/bin/env python3 ################################################################################ # parse arguments first import argparse parser = argparse.ArgumentParser() parser.add_argument('--min_2d_power', type=int, default=3) parser.add_argument('--max_2d_power', type=int, default=15) parser.add_argument...
"""Author: <NAME> Email: <EMAIL> network.py is a basic implementation of a one layer linear neural network, to examine an implementation of backpropagation. It is based on the basic model of the Perceptron. Information on that can be found at: https://en.wikipedia.org/wiki/Perceptron The intent of this specific ...
# model class structure adapted from <NAME> # https://danijar.com/structuring-your-tensorflow-models/ # https://gist.github.com/danijar/8663d3bbfd586bffecf6a0094cd116f2 from math import ceil import functools from collections import namedtuple import tensorflow as tf def doublewrap(function): """ A decorator ...
#!/usr/bin/env python3 """ Cronjob to copy Novogene fastq data from GIS to NSCC """ # standard library imports import logging import sys import os import argparse import subprocess import glob #--- third party imports # import pymongo import yaml import requests # project specific imports # # add lib dir for this pip...
from functools import reduce import networkx as nx def identity(*args): if len(args) == 1: return args[0] return args def er(e): """ This function returns the reverse of an edge represented as a tuple """ s, d = e return (d, s) def cer(e): """ Canonica...
import os import numpy as np from sklearn.model_selection import train_test_split from tensorflow.keras import backend as K # 这里目的是使用后端tensorflow from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.layers import Input, Dense, Lambda from tensorflow.keras.models import Model, Sequential from te...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import sys import os from lifelines.utils import concordance_index from sklearn.metrics import r2_score from torch.utils.data import DataLoader, TensorDataset from torchcontrib.optim import SWA from pytorch_lightning import Trainer, s...
# Copyright (c) 2018-2022, <NAME> # 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 following disclaimer. # * ...
def calculate_line_diff(): # SAME LINE line1_start = (41.88695, -87.63248) line1_end = (41.88692, -87.63539) line2_start = (41.88695, -87.62951) line2_end = (41.88695, -87.63248) # NOT THE SAME LINE # line1_start = (41.87523, -87.64807) # line1_end = (41.8777, -87.64545) # line2_start = (41.87437, -87.642...
import os import time import tensorflow as tf from tensorflow.python.client import timeline from tensorflow.python.framework import meta_graph batch_size = 32 num_bathes = 100 def print_tensor_info(tensor): print("tensor name:", tensor.op.name, "-tensor shape:", tensor.get_shape().as_list()) def inference(imag...
""" """ __version__ = '0.1.0' __author__ = 'Morteza' import os try: import understand as und except ModuleNotFoundError: # Error handling pass from antlr4 import * from antlr4.TokenStreamRewriter import TokenStreamRewriter from gen.java.JavaParser import JavaParser from gen.javaLabeled.JavaLexer import...
""" The following Python implementation of Shamir's Secret Sharing is released into the Public Domain under the terms of CC0 and OWFa: https://creativecommons.org/publicdomain/zero/1.0/ http://www.openwebfoundation.org/legal/the-owf-1-0-agreements/owfa-1-0 See the bottom few lines for usage. Tested on Python 2 and 3. ...
#!/usr/bin/python import os import subprocess import argparse ## no exception handling yet, to be added. Logging to be added too (in progress, needs to be detailed) def find_filenames(dir_path): file_name_list = [] file_path_list = [] files_dict = {} for root, dirs, files in os.walk(dir_path): ...
########## # Determine the Lowest Common Ancestor (LCA) of a set of taxonomic IDs ########## import pandas as pd import numpy as np from ete3 import NCBITaxa import boto3 import tempfile import subprocess import os import io import re import time import json import pdb, traceback, sys # NCBI Entrez functions from Bi...
#!/opt/anaconda/envs/env_hazard_index/bin/python import atexit import cioppy ciop = cioppy.Cioppy() import xarray as xr import numpy as np import pandas as pd import geopandas as gpd import datetime import sys import gdal from urllib.parse import urlparse import os SUCCESS = 0 ERR_RESOLUTION = 10 ERR_STAGEIN = 20 ERR...
# SPDX-FileCopyrightText: : 2017-2020 The PyPSA-Eur Authors # # SPDX-License-Identifier: GPL-3.0-or-later # coding: utf-8 """ Adds extra extendable components to the clustered and simplified network. Relevant Settings ----------------- .. code:: yaml costs: year: USD2013_to_EUR2013: dico...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================== # # x11 - Module for Python X lib (X11) functions # # ============================================================================== # noinspection SpellCheckingInspection """ To so...
import yaml import sys import argparse import copy section_labels_list = [ 'Get Data', 'Send Data', 'Collection Operations', 'Expression Tools', 'Text Manipulation', 'Filter and Sort', 'Join, Subtract and Group', 'Convert Formats', 'FASTA/FASTQ', 'FASTQ Quality Control', 'SAM/BAM', 'BED', 'VCF/BCF', 'Nanop...
#!/usr/bin/env python # # Camlistore uploader client for Python. # # Copyright 2010 The Perkeep 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/...
#!/usr/bin/env python """ Handle and move files from the receiver(s) to Overwatch sites and EOS. This simple module is responsible for moving data which is provided by the receiver to other sites. It will retry a few times if sites are unavailable. We take a simple approach of determine which files to transfer, and ...
from datetime import datetime import os import math import logging import warnings from visnav.algo.tools import PositioningException warnings.filterwarnings("ignore", module='quaternion', lineno=21) import numpy as np import cv2 import sys from visnav.render.render import RenderEngine from visnav.al...
"""Defines `TraderAccount` and supporting classes.""" __copyright__ = 'Copyright © 2019, <NAME>, <NAME>, and <NAME>' __license__ = 'MIT' import collections import typing import dispatch # Local package imports duplicated at end of file to resolve circular dependencies if typing.TYPE_CHECKING: from model.stock...
import operator, msgpack, nltk, math, sys, os from nltk.corpus import stopwords from datetime import datetime from tqdm import tqdm from argparse import ArgumentParser import numpy as np import dateutil.parser from utils import settings, liwc_keys, lsm_keys, open_for_write, DEFAULT_TIMEZONE from normalizer import e...
import json import logging import os import urllib import requests from lxml import etree alma_api_base_url = 'https://api-eu.hosted.exlibrisgroup.com/almaws/v1/' def get_item(mms_id, item_id, holding_id='ALL'): api_key = os.environ['ALMA_SCRIPT_API_KEY'] url = '{}bibs/{}/holdings/{}/items/{}?apikey={}'.for...
########################################## # AI # 2019-12-26 14:08:16 # class hl_dtoken_converter: # Translate programmer friendly dtokens into hardware-level dtokens # RF(WE) -> RF(LWE, HWE) # IMMED(0xFF) -> JUMP(0xFF,0), BUS(IMMED) # # class *_translator: # do translate work # when hl_dtoken_co...
from __future__ import print_function, unicode_literals, absolute_import, division from six.moves import range, zip, map, reduce, filter import numpy as np import warnings from zipfile import ZipFile, ZIP_DEFLATED from scipy.ndimage.morphology import distance_transform_edt, binary_fill_holes from scipy.ndimage.measure...
""" Created on Tue Jul 28 12:19:11 2020 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt import time import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import RMSprop from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPoo...
#%% [markdown] # # Contrastive Hebbian Learning # # Contrastive Hebbian Learning (CHL) is an algorithm that can be used to perform supervised learning in a neural network. It unites the power of backpropagation with the plausibility of Hebbian learning, and is thus a favorite of researchers in computational neuroscien...
''' XlPy/Link_Finder/search/single ______________________________ Checks if a sequenced peptide matches back to an unsequenced, theoretical peptide massfingerprint. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details....
from __future__ import print_function import numpy import collections from typing import Mapping, Union, Sequence, MutableSequence, Tuple, Any from typing import Optional, Callable, TypeVar, Iterable, List, cast InitialState = Union[MutableSequence[complex], int, numpy.ndarray] # This should be Anything subscriptable...
from __future__ import print_function import argparse import os # from torchvision.datasets import ImageFolder import myDataset import networks import numpy as np import torch import torch.backends.cudnn as cudnn import torch.nn as nn import torch.optim as optim import torchvision.transforms as transforms from PIL imp...
import json #La clave es el lexema (lo que lee del programa) y el valor es el token #ejemplo lexema: = ; toquen: operador asignacion #aqui en el token en vez de que se repita lo mismo a parte podria ir una descripcion #ejemplo 'ari': 'ari / condicional if' #Faltan varias fijense en la tablita y agregenlas porfaa rese...
import numpy as np from scipy.io import loadmat from utils.dataset import load_label_files, load_labels, load_weights from data_loader.util import load_challenge_data import torch import torch.nn.functional as F class ChallengeMetric(): def __init__(self, input_directory, alphas): # challengeMetric init...
import numpy as np import lsst.afw.table as afwTable import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.geom as geom import lsst.sphgeom as sphgeom from lsst.meas.base.forcedPhotCcd import ForcedPhotCcdTask, ForcedPhotCcdConfig from .forcedPhotDia import DiaReferencesTask __all__ = ("...
""" OpenSwap main public messaging """ import time from html import escape try: # python 3.6 + from secrets import token_bytes except ImportError: from os import urandom as token_bytes from electroncash.i18n import _ from electroncash.address import Address import electroncash.web as web from PyQt5.QtCo...
from server.models.postgis.mapping_issues import MappingIssueCategory from server.models.postgis.task import TaskMappingIssue, TaskHistory, Task from server.models.postgis.user import User from server.models.postgis.project import Project from server.models.postgis.statuses import TaskStatus from server.models.dtos.map...
#!/usr/bin/python3 import sys import requests import json import subprocess import csv import os import hashlib from datetime import datetime import configparser from random import randint import collections import time def getDigest(input): print(input) block_size = 65536 sha256 = hashlib.sha256() sh...
import json import wml_utils as wmlu import numpy as np import os import cv2 as cv import sys import random from iotoolkit.labelme_toolkit import get_labels_and_bboxes def get_files(dir_path, sub_dir_name): img_dir = os.path.join(dir_path, sub_dir_name,'images') label_dir = os.path.join(dir_path, sub_dir_name...
import requests import time from requests.adapters import HTTPAdapter from requests.exceptions import ConnectionError import pandas as pd import sqlite3 from pgs_harmonizer.harmonize import reversecomplement class VariationResult: """Class to parse the 'mapping 'information from ENSEMBL Variation""" def __ini...
import os import pandas as pd import mygene from util_path import get_path from util_dei import filter_dei res_dir = get_path("resource/Entrez") gene_dir = get_path("vertex/gene") mg = mygene.MyGeneInfo() def read_gene2ensembl(): global res_dir g2e_df = pd.read_csv(os.path.join(res_dir, "gene2ensembl_9606.t...
# NOTE : The API / Client couple here is DUAL to rest (because most of it is callback, not callforward) # => the API is what the user should use directly (and not the client like for REST) import asyncio import typing from aiokraken.rest import AssetPairs from aiokraken.websockets.channelstream import SubStream f...
#! /usr/bin/env python import rospy import sys # Brings in the SimpleActionClient import actionlib import math import tf2_ros from geometry_msgs.msg import * from std_srvs.srv import * import time """Reference Path""" #x = [1.5, 3.5, 5.5, 7, 5.5, 3.5, 1.5, 0, 1.5] #y = [0.5, 0.5, 0.5, 2, 3.5, 3.5, 3.5, 2, 0.5] #theta ...
import re import sys reload(sys) sys.setdefaultencoding('utf-8') # this list of stopwords is a merge of multiple lists found in the web stops = set(['[closed]', '[duplicate]', 'i', 'me', 'sometime', 'been', 'mostly', 'don\'t', 'don', 'hasnt', 'couldn\'t', 'couldn', '\'t', 't', 'don', 'your'...
#3_Laes_InsertDB_2019M.py from app.models import Klub, Konkurrence, Medlemmer, Deltager, Grunddata, Baner, PostBaner, deltager_strak from app import db import json from operator import itemgetter def find_medlemID(medlem): ''' Finder medlems ID ''' temp1 = db.session.query(Medlemmer).filter(Medlemmer.navn == ...
# coding=utf-8 # Copyright 2022 The Google Research 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 by applicab...
import logging import re class Grade: def __init__(self, grade): self.grade = grade def to_dict(self): return { "grade": self.grade, "sort_index": self.index() } def index(self): pass class YDS(Grade): static_indexes = ["3rd", "4th", "Easy 5th"] single_digit_mplier = 3 ...
# -*- coding: utf-8 -*- # # Copyright (C) 2019 <NAME>, CESNET. # # oarepo-references is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """OArepo module for tracking and updating references in Invenio records.""" import abc import typing ...
import tensorflow_probability as tfp import tensorflow as tf from .settings import float_type class ConstrainedBijector(tfp.bijectors.Chain): def __init__(self,a,b,validate_args=False): """ Create a bijector that constrains the value to (a,b) :param a: float scalar ...
""" Demo code To run our method, you need a bounding box around the person. The person needs to be centered inside the bounding box and the bounding box should be relatively tight. You can either supply the bounding box directly or provide an [OpenPose](https://github.com/CMU-Perceptual-Computing-Lab/openpose) detecti...
#!/usr/bin/env python from direct.showbase.ShowBase import ShowBase from panda3d.core import CollisionTraverser, CollisionNode from panda3d.core import CollisionHandlerQueue, CollisionRay from panda3d.core import Filename, AmbientLight, DirectionalLight from panda3d.core import PandaNode, NodePath, Camera, TextNode fr...
# # # Copyright 2019 Asylo 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 by applicable law or agreed to in wri...
#!/usr/bin/env python """ The Monty Hall problem simulator parameterizable with soops. https://en.wikipedia.org/wiki/Monty_Hall_problem Examples -------- - Direct runs:: python examples/monty_hall.py -h python examples/monty_hall.py output python examples/monty_hall.py --switch output python examples/monty_...
from django.db import models from .base_workflow import Ticket, TicketHistory class ServiceRequest(Ticket): AC_STATUS = ( ('aog', 'AOG'), ('mtx', 'Scheduled Maintenance'), ('other', 'Other (Provide in Description)') ) CERTS = ( ('far91', 'FAR 91'), ('far121', 'F...
"""Sets a consistent plotting settings across the project. Example: Usage with simple plots:: from src.plot_settings import ( ps_defaults, label_subplots, get_dim, set_dim, PALETTE, STD_CLR_LIST, CAM_BLUE, BRIC...
from __future__ import print_function import json import random as rd def read_dict(filename): f = open(filename, "r") rs = f.read() if rs.find("\n") >= 0: rules = rs.split("\n") else: rules = rs.split("\r") out_rule = [] for rule in rules: if len(rule) < 1: continue details = rule.split("|") flat_...
import json import random from argparse import ArgumentParser from collections import Counter, defaultdict import itertools import os import sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from datasets import utils from datasets.wsd_dataset import SemCorWSDDataset def shuffle_list...
version = '5.0' import math import pygame import random import time from pygame.locals import Rect from math import pi import vectores from vectores import Vector2 SIZE = WIDTH, HEIGHT = 800, 600 # Tamaño de pantalla CENTER = (WIDTH//2, HEIGHT//2) BLACK = (0, 0, 0) # Colores WHITE = (255, 255, 255) ...
### Code Adapted From <NAME> Kaggle Submission: https://www.kaggle.com/shayantaherian/nfl-training-fasterrcnn # Import Packages import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib import patches import imageio from tqdm import tqdm_notebook as tqdm from tqdm import tqdm from ...
import simplematch as sm def test_readme_example_opener(): assert sm.match("He* {planet}!", "Hello World!") == {"planet": "World"} assert sm.match("It* {temp:float}°C *", "It's -10.2°C outside!") == {"temp": -10.2} def test_readme_example_basic_usage(): result = sm.match( pattern="Invoice*_{year...
import numpy as np import torch as torch import numpy as np import torch as torch from scipy.interpolate import griddata import torch.nn.functional as F import torch.nn as nn # import audtorch import piq def calculate_CC_metrics(pred, gt): """ Calculate CC Metrics :param pred: :param gt: :return: ...