text stringlengths 3.07k 22.1k |
|---|
"""Module containing functions dealing with target input files."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load(":collections.bzl", "flatten", "set_if_true")
load(":files.bzl", "file_path", "file_path_to_dto", "join_paths_ignoring_empty", "parsed_file_path")
load(":logging.bzl", "warn")
load(":output_group_map.b... |
import tkinter as tk
from tkinter import ttk
from tkinter import *
from PIL import Image
from PIL import ImageTk
from itertools import count
import pandas as pd
#from cartopy import config
#import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanva... |
import datetime as std_datetime
from fractions import Fraction
_YS_PER_S = 10 ** 24
_YS_PER_US = 10 ** 18
_YS_PER_FS = 10 ** 9
_YS_PER_DAY = 60 * 60 * 24 * _YS_PER_S
_US_PER_DAY = 24 * 60 * 60 * 1000 * 1000
_US_PER_WEEK = 7 * _US_PER_DAY
_NS_PER_HOUR = 60 * 60 * (10 ** 9)
_PS_PER_MINUTE = 60 * (10 ** 12)
_FIELD_NAME... |
import os
import re
from itertools import chain
from .. import mopack, pkg_config
from ... import log, shell
from .compiler import CcCompiler, CcPchCompiler
from .linker import CcExecutableLinker, CcSharedLibraryLinker
from .rc import CcRcBuilder # noqa: F401
from ..ar import ArLinker
from ..common import Builder, ch... |
# -*- coding: utf-8 -*-
import numpy as np
from datetime import datetime
class ALSData(object):
""" A data class container for ALS data"""
vardef = ["time", "longitude", "latitude", "elevation"]
def __init__(self, time, lon, lat, elev, segment_window=None):
"""
Data container for ALS ... |
import portalUtilities as portalUtil#several misc functions that are unrelated to functionality or not specific to AI
from portalUtilities import SpaceType, fireTurnMap
def checkBombAffectedCoords(x,y,bombPierce,bombRange,board,gameState):
"""get a list of all coords that will be hit by the bomb at position x,y
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import os
import torch
import numpy as np
from pathlib import Path
from collections import deque
import matplotlib.pyplot as plt
from tqdm import tqdm, trange
from unityagents import UnityEnvironment
from agent import Agent
def set_seed(seed):
"""Set t... |
import os
import pytest
import nbformat
import numpy as np
from nbconvert.preprocessors import ExecutePreprocessor
from glue.core import Data
from glue.core.autolinking import find_possible_links
import glue_jupyter as gj
DATA = os.path.join(os.path.dirname(__file__), 'data')
def test_default_components(app, data... |
#!usr/bin/env python3
# -*- coding:utf-8 -*-
# @time : 2021/1/27 17:21
# @author : <NAME>
import csv
import os
import numpy as np
import h5py
from rdkit import Chem
from rdkit import DataStructs
from rdkit import RDLogger
from rdkit.Chem import AllChem, Descriptors, Fragments
RDLogger.DisableLog('rdApp.*')
class m... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 27 16:22:01 2018
@author: cenv0574
"""
import geopandas as gpd
import pandas as pd
import os
import networkx as nx
import numpy as np
import json
from geopy.distance import vincenty
from boltons.iterutils import pairwise
def main():
# Define current directory and... |
# topological.py
# Copyright (C) 2005, 2006, 2007, 2008, 2009 <NAME> <EMAIL>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Topological sorting algorithms.
The topological sort is an algorithm that receives this list of
dependencies... |
import torch
import torch.nn as nn
import cv2
import sys
import pickle
import datetime
import functools
import numpy as np
import os
import glob
import tempfile
import matplotlib
import matplotlib.pyplot as plt
import signal
import pkgutil
import importlib
import operator
def restore_most_recent(path):
most_recen... |
"""
This module is the perturbation to matrix.
"""
import numpy as np
from scipy.linalg import eigh
class Pert():
def __init__(self, H0=None, evals=None, evecs=None):
if evals is not None and evecs is not None:
self.evals, self.evecs = evals, evecs
elif H0 is not None:
self... |
#!/usr/bin/env python
#
# SubDomain TakeOver - SubDomain takeover vulnerability scanner
# Coded by Nishit (nishitm)
from __future__ import print_function
import getopt
import os
import re
import sys
import time
import requests
import urllib3
try:
import urlparse
except ImportError:
import urllib.parse as ur... |
"""Module containing implementation of the Chlorine algorithm."""
from collections import defaultdict
from itertools import chain
from ...utils.benchmark import time_snap
from ...results.detected_clone import DetectedClone
from ...results.detection_result import DetectionResult
import os
# Minimum weight of a single ... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
import os
import subprocess
import sys
import tempfile
from copy import copy
from typing import Type, Dict, List
import yaml
UserId = str
RepoId = str
class User(object):
def __init__(self, user_id: UserId, name: str, email: str):
self.user_id = user_id
self.name = name
self.email = ema... |
"""
Copyright (c) 2021 <NAME> as part of Airlab Amsterdam
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 applic... |
import ntpath
from enum import Enum
from functools import lru_cache
from io import BytesIO
from typing import Any, AnyStr, AsyncIterable, Callable, Union
from essentials.json import FriendlyEncoder, dumps as friendly_dumps
from blacksheep import Content, JSONContent, Response, StreamedContent, TextContent
from blacks... |
import argparse, os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.distributions import kl_divergence, Normal
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from MAD_VAE import *
from ut... |
import os
import sys
import re
import argparse
import json
import tensorflow as tf
import numpy as np
import csv
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import sklearn.metrics
import torch
import logging
from mlio.pipeline import Pipeline, Dataset
from py... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def cross_entropy2d(input, target, weight=None, size_average=True):
n, c, h, w = input.size()
nt, ht, wt = target.size()
# Handle inconsistent size between input and target
if h > ... |
# Copyright (c) 2003-2005 <NAME>. All rights reserved.
# Copyright (c) 2006-2015 Sippy Software, Inc. All rights reserved.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions ... |
import time
from pytesseract import Output
from services.image_helper import *
from services.models import OcrResult
from multiprocessing import Process, Queue
import pytesseract
allowed_tuples = ('1C', '7A', '55', 'BD', 'E9', 'FF')
allowed_characters = ('1', '7', '5', '9', 'A', 'B', 'C', 'D', 'E')
# Only characters ... |
import discord, asyncio, uuid
from discord.ext import commands, tasks
from collections import deque
from datetime import datetime, timedelta
from .. import utils
class RollSort(commands.Cog, name = "Roll Sorting"):
VARIANTS = (
("Market", "market", "\U0001F4B8"),
("Artist Gallery", "artist", "\U0001F3A8"),
("Ro... |
import logging
from collections import defaultdict
from csv import DictReader, DictWriter
from datetime import datetime
from pathlib import Path
from typing import IO, Any, Dict, List, Optional, cast
import click
from requests import HTTPError
from contxt.cli.clients import Clients
from contxt.cli.utils import LAST_W... |
import streamlit as st
import SessionState
st.set_option('deprecation.showfileUploaderEncoding', False)
import matplotlib.pyplot as plt
import plotly.express as px
import plotly.figure_factory as ff
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import datetime
import sklearn as sk
import pylab ... |
#!/usr/bin/env python
import csv
import glob
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
BLACKHOLE_3_3 = "results.0.3.0.3.blackhole.csv"
BLACKHOLE_5_5 = "results.0.5.0.5.blackhole.csv"
DEFLECTION_3_3 = "results.0.3.0.3.deflection.csv"
DEFLECTION_5_5 = "results.0.5.0.5.deflection.csv"
BOTH... |
#!/usr/bin/env python
# coding: utf-8
import argparse
import os.path as osp
from pathlib import Path
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.nn.functional as F
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator
from torch_geometric.data import NeighborSampler
from torch_geom... |
#librerie usate per l'analisi
import numpy as np
import pandas as pd
import datetime
from datetime import datetime
import csv
import os
from os import listdir
import json
import csv
import sys
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import tensorflow as... |
"""
home-credit-default-competition repository
Functions for preprocessing and extracting features from
POS_CASH_balance.csv, installments_payments.csv and
credit_card_balance.csv files.
"""
import os
import gc
import pandas as pd
from functools import partial
import utils
import config
def get_pos_cash(path, num_r... |
# %%
import yaml
import pprint as pp
import csv
import logging
import os
from datetime import datetime as dt
# %%
def find_sources_root(tree_root='csse332'):
"""
Find the root directory containing the sources for the website.
:return: Returns the real path of the sources root.
:rtype: str
"""
... |
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010, 2degrees Limited <<EMAIL>>.
# All Rights Reserved.
#
# This file is part of sorethumb,
# which is subject to the provisions of the BSD at
# <http://dev.2degreesnetwork.com/p/2degrees-license.ht... |
from os.path import join, abspath, exists
import json
import pandas as pd
class Silhouette:
"""
Interface to a FlyEye Silhouette file.
Attributes:
path (str) - path to Silhouette file
feed (dict) - feed file containing layer IDs
feud (dict) - feud file containing cell type lab... |
#!/usr/bin/env python
u"""
reanalysis_monthly_pressure.py
Written by <NAME> (10/2021)
Reads daily atmospheric pressure fields from reanalysis and outputs monthly averages
INPUTS:
Reanalysis model to run
NCEP-DOE-2: https://www.esrl.noaa.gov/psd/data/gridded/data.ncep.reanalysis2.html
COMMAND LINE OPTIONS:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from PyQt5.QtWidgets import *
from model import Student, Score, Subject, Standard, Assesment
NAME_COL = 0
HAKBUN_COL = 1
SUBJECTA_COL = 2
SUBJECTB_COL = 3
SCORE_CHANGE_COL = 4
ASSES_COL = 5
global scoreChangeAssesments
scoreChangeAssesments = []
def resi... |
# Copyright 2020 Superb AI, 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 writi... |
import numpy as np
import numpy as np
import brevitas
import torch
import onnx
from onnx import numpy_helper
from onnx.tools.update_model_dims import update_inputs_outputs_dims
from finn.custom_op.registry import getCustomOp
from finn.util.basic import get_by_name
def set_batch_size(model, batch_size):
input_dims ... |
# Copyright (c) 2015 The New Mexico Consortium
#
# {{{NMC-LICENSE
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice... |
# -*- coding: UTF-8 -*-
from ckan.tests.helpers import FunctionalTestBase, call_action
from ckan.tests import factories
import ckan.lib.search as search
from ckan.lib.create_test_data import CreateTestData
import ckan.model as model
from ckan.plugins.toolkit import Invalid
from ckanapi import LocalCKAN, ValidationErro... |
"""
PyTorch interface for computing PR.
"""
import os
import random
import time
import numpy as np
import tensorflow as tf
import torch
from diagan.datasets.image_loader_with_attr import get_dataset_images_with_attr
from torch_mimicry.metrics.inception_model import inception_utils
from diagan.trainer.compute_pr impo... |
import discord
from discord.errors import DiscordException
from discord.ext import commands, tasks
import typing
import datetime
import platform
if platform.system() == "Linux":
from utils.util import *
elif platform.system() == "Windows":
from .utils.util import *
class Mod(commands.Cog):
def... |
# Copyright 2015 The TensorFlow 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 applica... |
#
# cogs/welcome/alert.py
#
# futaba - A Discord Mod bot for the Programming server
# Copyright (c) 2017-2020 <NAME>, <NAME>, jackylam5
#
# futaba is available free of charge under the terms of the MIT
# License. You are free to redistribute and/or modify it under those
# terms. It is distributed in the hopes that it w... |
# coding=utf-8
import os
import urllib
import six
import shutil
try:
from urllib.parse import urljoin, urlsplit, urlunsplit
except ImportError:
from urlparse import urljoin
from datetime import datetime
from django.core.files import File
from django.core.exceptions import ImproperlyConfigured, SuspiciousOpe... |
import csv
import json
# Agency Name,State Name,Agency ID - NCES Assigned,County Number ,ANSI/FIPS State Code ,Web Site URL ,Agency Level
import os
import census
import geojson
import geopandas as gp
import numpy
import us
from Loading import c, HISPANIC, HISPANIC_ADULT, BLACK_NOT_HISPANIC, BLACK_NOT_HISPANIC_ADULT, ... |
from __future__ import annotations
import collections
import datetime
import os.path
from typing import Counter
from typing import Match
import aiosqlite
from bot.config import Config
from bot.data import bits_handler
from bot.data import command
from bot.data import esc
from bot.data import format_msg
from bot.data... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import string
import itertools
from django.forms import widgets
from django.core.exceptions import ValidationError
from django.utils.html import format_html, format_html_join
from django.utils.encoding import force_text
from django.utils.translation import... |
import sys
import re
import pandas as pd
import numpy as np
import linecache
def main():
args = sys.argv
"""args[1] : threshold number of word """
threshold = int(args[1])
cancer_type_list = ['adrenal_gland', 'biliary_tract', 'bone', 'breast', 'central_nervous_system', 'cervix', 'endometrium',\
... |
import asyncio
import itertools
import logging
import typing
from hat import aio
from hat.drivers import tcp
from hat.drivers.iec60870.apci import common
from hat.drivers.iec60870.apci import encoder
mlog: logging.Logger = logging.getLogger(__name__)
"""Module logger"""
ConnectionCb = aio.AsyncCallable[['Connectio... |
import logging
from IsoNet.preprocessing.cubes import prepare_cubes
from IsoNet.preprocessing.img_processing import normalize
from IsoNet.preprocessing.prepare import prepare_first_iter,get_cubes_list,get_noise_level
from IsoNet.util.dict2attr import save_args_json,load_args_from_json
import glob
import mrcfile
import ... |
from __future__ import print_function, division
from typing import Optional, List, Union, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
class DiceLoss(nn.Module):
"""DICE loss.
"""
# https://lars76.github.io/neural-networks/object-detection/losses-for-segmentation/
def __i... |
import pandas as pd
from keras.preprocessing.text import text_to_word_sequence
from nltk import SnowballStemmer, re, downloader
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import classification_report
from sklearn.model_selection i... |
__author__ = '<NAME>'
from srcs.cyber_network.synthesis.action_set import ActionSet
from srcs.cyber_network.synthesis.action_set import Action
class Instruction:
def __init__(self, sw, instruction_json):
self.instruction_json = instruction_json
self.instruction_type = None
self.sw = sw
... |
""" Class definition for Inlet."""
import openmdao.api as om
from pycycle.constants import g_c
from pycycle.thermo.cea import species_data
from pycycle.thermo.thermo import Thermo
from pycycle.flow_in import FlowIn
from pycycle.passthrough import PassThrough
from pycycle.element_base import Element
#from pycycle.e... |
#To activate env in cmd type in workspace directory:
#ImageApp\Scripts\activate
import sys
import time
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import pathlib
#from skimage import data
#from skimage import filters
#from skimage import exposure
#defaultImagePath = "express-app/public/p... |
from functools import partial
import json
import os
import numpy as np
import tensorflow as tf
from dataset import create_images_dataset, add_noise
import settings
from settings import (LOSS_FUNCTION, EPOCHS_NO, LEARNING_RATE, BATCH_SIZE,
ADD_NOISE, BATCHES_NUMBER, RAMP_DOWN_PERC, DECAY_STEPS,
... |
# https://github.com/pratogab/batch-transforms
from subprocess import Popen, PIPE
from scipy.io import wavfile
from torch.utils.data import Dataset #, DataLoader
import os, io
import numpy as np
import kaldiio
import torch
import json
from kymatio.torch import Scattering1D
import pickle
from collections import namedtu... |
'''
Credits:
https://github.com/sksq96/pytorch-summary
https://stackoverflow.com/questions/42480111/model-summary-in-pytorch
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import deeptensor as dt
import torch
import torch.nn as nn
from torch.autograd ... |
from django.shortcuts import render, get_object_or_404
from Blog.models import BlogsInfo
from Organizer.models import EventDetails, SponsorShip, OrganiseEvent, Event_Location
from django.contrib.auth.models import User
from django.utils import timezone
from django.core.mail import send_mail
from django.utils.datastruct... |
import json
import glob
import os
import string
from pathlib import Path
from typing import Dict, List, Union, BinaryIO, Optional
from io import BufferedIOBase
from ..utilities import load_json_file
from elpis.transformer import make_importer, DataTransformer, DataTransformerAbstractFactory
from elpis.engines.common.... |
"""Image utilities ported from Compass."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import logging
import mimetypes
import os.path
import six
from six.moves import xrange
from . import CompassExtension
from .helpers import add_cache_buster
f... |
'''
Terminal input handling (based on bpytop).
'''
import fcntl
import logging
import os
from select import select
import signal
import sys
import termios
import threading
import tty
from typing import List, Set, Dict, Tuple, Optional, Union, Any, Callable, ContextManager, Iterable, Type, NamedTuple
errlog = logging.g... |
import numpy as np
import torch
from PIL import Image,ImageOps
import random
from skimage import exposure
from skimage.util import random_noise
from skimage.transform import warp
from transforms3d.euler import euler2mat
from transforms3d.affines import compose
import cv2
from scipy.ndimage.interpolation import map_coo... |
########################################################################
## File name: generate_readme.py ##
## Author: <NAME> ##
## Date created: 2016-04-14 ##
## Date last modified: 2016-11-10 ... |
import abc
import torch
from utils import rend_util
class RaySampler(metaclass=abc.ABCMeta):
def __init__(self,near, far):
self.near = near
self.far = far
@abc.abstractmethod
def get_z_vals(self, ray_dirs, cam_loc, model):
pass
class UniformSampler(RaySampler):
def __init__(s... |
import glob
import json
import os.path as op
import pkg_resources
import sys
from collections import OrderedDict
from itertools import islice
from pathlib import Path
from six import text_type
from typing import Dict, List, Union
from datalad.distribution.dataset import (
Dataset,
require_dataset,
resolve_... |
"""Support for executing Docker containers using the Singularity 2.x engine."""
from __future__ import absolute_import
import os
import os.path
import re
import shutil
import tempfile
import sys
from distutils import spawn
from io import open # pylint: disable=redefined-builtin
from typing import Dict, List, MutableM... |
# Copyright 2011-2013 <NAME>
# Copyright 2011-2013 <NAME>
# Copyright 2012-2013 <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 copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
"""Classes for representing speaker turns and interacting with RTTM files."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from intervaltree import Interval, IntervalTree
from .six import python_2_unicode_compatible
from .uem import UEM
... |
"""
This is an implimentation of the structured bayesian optimisation approach based on
BOAT: Building Auto-Tuners with Structured Bayesian Optimization
<NAME>, <NAME>, <NAME>
"""
import copy
import numpy as np
import torch
import torch.nn as nn
from torch.distributions import constraints, transform_to
import torch.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2018 University of Groningen
#
# 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
#
# U... |
import os
import chess.engine
import backoff
import subprocess
import logging
from enum import Enum
logger = logging.getLogger(__name__)
@backoff.on_exception(backoff.expo, BaseException, max_time=120)
def create_engine(config):
cfg = config["engine"]
engine_path = os.path.join(cfg["dir"], cfg["name"])
e... |
import datetime
import copy
import re
import logging
from .base import BaseModel
_logger = logging.getLogger('whois-api-client-models')
re_timezone_offset = re.compile(r'([-+])(\d\d)(:)?(\d\d)$')
re_coordinated_utc = re.compile(r'(T\d\d:\d\d:\d\dZ)$')
re_milliseconds_and_timezone_name = re.compile(
r'(\.\d\d\d)?... |
#!/usr/bin/env python
import rospy
import math
import sys
import tf
from geometry_msgs.msg import Twist, Point
from nav_msgs.msg import Odometry
from sensor_msgs.msg import LaserScan
from tf.transformations import euler_from_quaternion
# initialize node, publisher and msg type
rospy.init_node("move_robot")
pub = rosp... |
'''
Cache of per-well block of per-cell feature data.
Example usage as a script (builds cache and precomputes normalizations):
$ python -m cpa.profiling.cache CDP2.properties /imaging/analysis/2008_12_04_Imaging_CDRP_for_MLPCN/CDP2/cache "Image_Metadata_ASSAY_WELL_ROLE = 'mock'"
Example usage as module:
>>> import ... |
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
#
# THIS SOFTWARE IS PR... |
#-
# ==========================================================================
# Copyright (C) 1995 - 2006 Autodesk, Inc. and/or its licensors. All
# rights reserved.
#
# The coded instructions, statements, computer programs, and/or related
# material (collectively the "Data") in these files contain unpublished
# ... |
import ply.lex as lex
import sys
keywords = {
'BREAK', 'CASE', 'CHAN', 'CONST', 'CONTINUE', 'DEFAULT',
'DEFER', 'ELSE', 'FALLTHROUGH', 'FOR', 'FUNC', 'GO', 'GOTO',
'IF', 'IMPORT', 'INTERFACE', 'MAP', 'PACKAGE', 'RANGE',
'RETURN', 'SELECT', 'STRUCT', 'SWITCH', 'TYPE', 'VAR' }
operators = {
'ADD', # +
'SUB', ... |
import numpy as np
from sklearn.cluster import AffinityPropagation
#import pydotplus as pydot
from collections import Counter
from distance_utils import time_series_twed
import pandas as pd
from scipy.spatial.distance import squareform
import time
class BottomUpSubsequenceTree:
def __init__(self, max_level, prot... |
"""
Extracts data from an mzML file and uses the matplotlib animation class to create an animation of the mass spectrum
and the abundance traces for a highlighted region.
The left subplot is a mass spectrum at the current time
The right subplot is a chart of intensity traces leading up to the current time
Some modific... |
import os
import numpy as np
from keras.utils import to_categorical
from keras.models import Model, load_model
from keras.layers import Input, Conv2D, Dense, Flatten, MaxPooling2D, Dropout, BatchNormalization
from keras.optimizers import Adam, SGD
from keras.regularizers import l2
from keras.preprocessing.image import... |
import copy
import json
import re
from .paradigm import Paradigm
def deriv_for_paradigm(g, paradigm):
"""
Generate a Derivation object for the given paradigm.
"""
derivLinks = {} # recurs_class -> set of Derivation names
maxRecursClass = 0
for derivLink in paradigm.derivLinks:
recu... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import six
... |
import argparse
import os
import json
import glob
import gzip
import sys
import pathlib
import uuid
from shutil import rmtree
from typing import List, NamedTuple, Dict, Any, Iterator, Tuple
import numpy as np
from elasticsearch import Elasticsearch
from google.cloud import storage, bigquery
from pyClickModels import D... |
"""
In this example, we solve the classic generalised profiling problem for inference of a deterministic SIR model
The objective function can be expressed as
H(c, p | s0, s1, y) = 1/(s0)^2 ||y - g(Phi c)||^2 + 1/(s1)^2 || D(Phi c) - f(Phi c, p) ||
for the SIR model
Dx = f(x, p)
and the observation model
y = g(x) ... |
'''
Implements a cache for Curry-to-ICurry and JSON-to-Python conversions.
This cache supplements the filesystem caching in .curry files so that
interactive statements can also be cached. This exists because the conversions
can be extremely slow depending on the Curry system used and its configuration.
Caching can b... |
'''
Author: teamo1998
Date: 2021-05-03 15:12:57
LastEditTime: 2021-05-03 21:10:05
LastEditors: Please set LastEditors
Description: 本代码是为了完成ISS特征点检测
FilePath: /Point-cloud-process/第7章:3D Feature Detection/ISS.py
'''
import pandas as pd
import open3d as o3d
import argparse
import numpy as np
import heapq
import Utils
i... |
'''
@author enerve
'''
from __future__ import division
import logging
import math
import numpy as np
import ml_lib.util as util
import ml_lib.data_util as data_util
import ml_lib.helper as helper
import ml_lib.cmd_line as cmd_line
import ml_lib.log as log
# Draw histograms for each column
def draw_classes_histogram(... |
from datetime import datetime, timezone
import numpy as np
import xarray as xr
from scipy import optimize
from scipy.ndimage import gaussian_filter1d
import carbonplan_trace.v1.glas_height_metrics as ht
import carbonplan_trace.v1.utils as utils
SPEED_OF_LIGHT = 299792458 # m/s
SECONDS_IN_NANOSECONDS = 10 ** -9
de... |
#!/usr/bin/python
from ocpmodels.preprocessing import AtomsToGraphs
from ocpmodels.datasets import SinglePointLmdbDataset
from ocpmodels.custom import *
# import ocpmodels.custom.plot_and_filter import
import numpy as np
import pandas as pd
import sys
import os
import re
import time
from contextlib im... |
import torch, torchvision
import detectron2
from detectron2.utils.logger import setup_logger
setup_logger()
# import some common detectron2 utilities
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer,... |
#!/usr/bin/env python
import rospy
from cv_bridge import CvBridge
from std_msgs.msg import String, Float64
from sensor_msgs.msg import NavSatFix, Image, PointCloud2
from mavros_msgs.srv import CommandTOL, SetMode, CommandBool
from geometry_msgs.msg import PoseStamped, Pose, Point, Twist
from time import sleep
import cv... |
# %% [markdown]
# # Detecting spouse mentions in sentences
# %% [markdown]
# In this tutorial, we will see how Snorkel can be used for Information Extraction. We will walk through an example text classification task for information extraction, where we use labeling functions involving keywords and distant supervision.... |
# 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... |
#!/usr/bin/env python
import sys
from pathlib import Path
from random import randint
from socket import gethostname
import luigi
from ftarc.task.controller import PrepareFastqs
from .core import RnasaTask
class DownloadReferenceFiles(RnasaTask):
src_urls = luigi.ListParameter()
dest_dir_path = luigi.Parame... |
"""Generate a hindcast for a given salient's submodel and a given deadline date
Example:
$ python src/models/salient/predict_keras_hindcasts.py -d 20100107 -sn salient_fri_hindcasts_2010 -r contest
Named args:
--deadline_date (-d): official contest deadline for submission.
--submodel_name (-sn):... |
'''
hi_rct_agent.py
=== Description ===
Agent recommender system that learns actor IECs and makes
hi-regret minimizing choice suggestions based on trials in
a dynamic, HI-MABUC experiment
=== Parameters ===
- training_model: the HI-RCT model trained on the data from
a HI-RCT
- actors: a list o... |
import torch.utils.data
from torchvision import transforms
import os.path
import glob
import numpy as np
from collections import namedtuple
from PIL import Image
import viso2
from .. import transforms as custom_transforms
CameraIntrinsics = namedtuple('CameraIntrinsics', 'fu, fv, cu, cv')
intrinsics_full = CameraI... |
#TODO(Jon) This module will require online components for production, but will be locally implemented in this package
import os
import json
MATCH_TEMPLATE = {'win': 0, 'was_skunked': 0, 'was_dbl_skunked': 0, 'skunked_opponent': 0, 'dbl_skunked_opponent': 0}
DIFFICULTY_MAP = {'beginner': 1, 'intermediate': 2, 'expert':... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.