text stringlengths 3.07k 22.1k |
|---|
import copy
from abc import ABCMeta, abstractmethod
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
import sklearn.metrics
from sklearn.utils.multiclass import type_of_target
from smac.utils.constants import MAXINT
from autosklearn.constants import REGR... |
#!/usr/bin/env python3
# coding: utf-8
# Usage:
# PYTHONPATH=src ./train --dataset <file|directory|glob>
import argparse
import json
import os
import numpy as np
import tensorflow as tf
import time
import tqdm
from tensorflow.core.protobuf import rewriter_config_pb2
import model, sample, encoder
from load_dataset im... |
"""Handles persistent state for an experiment.
Based on a `HierarchicalOrderedDict`, the `State` singleton handles
global, persistent state, allowing to save and load state from h5f
files. Numpy arrays are saved in native h5f format so that they can be
loaded by other programs, other python objects are saved in pickle... |
import numpy as np
import os
import time
import sys
from tqdm import tqdm
import cv2
import torch
from torch.utils.data import Dataset, DataLoader
from albumentations.pytorch import ToTensor, ToTensorV2
from albumentations import (
Compose, HorizontalFlip, CLAHE, HueSaturationValue, Normalize, RandomBrightnessContr... |
import datetime
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.backend as K
import lib_stylegan
from . import generator
from . import discriminator
from . import seed
def apply_EMA(trained_model, ema_model, beta):
for trained_layer, ema_layer in zip(trained_... |
#!/usr/bin/env python
import sys
import os.path
import os
import imp
import shutil
import platform
import urllib.parse
import json
import warnings
import multiprocessing
from subprocess import Popen, PIPE
COMMON_LIB = os.path.dirname(__file__)
COMMON_CACHE = os.path.join(COMMON_LIB, "..", "pkgcache")
COMMON_CACHE = os... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2016 F5 Networks Inc.
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, or
# ... |
import argparse
from io import open
import random
import time
import os
import os.path as osp
from pathlib import Path
import numpy as np
from ruamel.yaml import YAML
from easydict import EasyDict as edict
import torch
import torch.nn as nn
from torch import optim
from torch.utils.data import DataLoader
from dataset... |
import json
# from django.shortcuts import render
from django.contrib import messages
from .models import Comment
from .forms import CommentForm
from django.views.generic import DetailView, DeleteView, FormView, View, RedirectView
from django.core import serializers
from ..core.models import ModelFormFailureHistory
fro... |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
"""
This module evaluates the Discrete Voter Model for ecological inference and
King's Ecological Inference.
"""
import logging
import numpy as np
import pandas as pd
import pymc3 as pm
import time
from tqdm.autonotebook import trange, tqdm
import dvm
import elect
import kings_ei as kei
import phc
import tools
# Sup... |
import random
from collections import deque
import torch.nn as nn
from utils.utils import *
device = get_default_device()
# sample from N(0, 1)
def reparameterization(z_mean, z_sigma):
epsilon = torch.randn(z_mean.size()).to(device)
res = z_mean + torch.exp(z_sigma / 2) * epsilon
return res
def rando... |
from __future__ import absolute_import, division, print_function, with_statement
import pytest
from tornado import concurrent
import tornado.gen
import tornado.testing
import scope
# def test_low_level_api():
# scope = scope.Scope()
# current_user = object()
#
# def get_current_user():
# get_cu... |
# Copyright 2018 Xanadu Quantum Technologies 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 agre... |
import pandas as pd
import matplotlib.pyplot as plt
import re
import random
import string
from collections import OrderedDict
import numpy as np
from farasa.segmenter import FarasaSegmenter
## ------------------- STATICS ---------------------------------------------- ##
#remove arabic formal clitics from tweets.
s... |
import math
import copy
import random
# 'phi' == 'angle'
def polar_2_car(phi_list):
d_last = math.cos(math.radians(phi_list[-1]))
d_list = []
for i in range(len(phi_list)):
tmp_d = 1.0
# Calculate the cosine part
for c in range(i):
tmp_d *= math.cos(math.radians(phi_list... |
import os, json
import numpy as np
from typing import List
from datasets import load_metric
from bert_score import score as bscore
import scipy.stats
import syllables
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import RidgeClassifie... |
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from scripts import selenium_browser
from scripts.file_management import append_to_statistics, write_to_last_run
from scripts.settings import W... |
## TODO .log/12327 speaker 2, 3, 6, 7, 8, 9, 10 threw errors while processing audio. 2 is not available, 8 had some unicode error and 3, 6, 7, 9, 10 had some intervals missing (i.e. videos missing)
'''
Preprocess audio files
Run it for all speakers
```sh
python data/audio.py -path2data ../dataset/groot/data -path2outda... |
# 3) Resample the 10 data SPL sets so that they have equal time spacing (e.g. remove duplicates, fill missing data with linear interpolation).
# 4) Redo 1) and 2). Compare the RMSE plots for both cases.
from calendar import c
from datetime import date
from multiprocessing.sharedctypes import Value
import numpy as np
im... |
# Copyright 2021 The Layout Parser team. 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... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
##network analysis functions for TF-STAR
from __future__ import division, with_statement
import pandas as pd
import numpy as np
import re
import os
import sys
import random
import time
from collections import defaultdict
import matplotlib.pyplot as plt
import itertools
impo... |
from pathlib import Path
from theme_installer.constants import *
import re
import shutil
import logging
from theme_installer.loaders import BaseLoader
from theme_installer.utils import *
#logger = logging.getLogger('ThemeInstaller')
logger = logging.getLogger('')
logger.info = print
class ThemeInstaller:
"""
... |
# %% [markdown]
# #
import os
import colorcet as cc
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import urllib.request
from graph_tool import load_graph
from graph_tool.inference import minimize_blockmodel_dl
from joblib import Parallel, delayed
... |
#!/usr/bin/python3
import Caffe_AlexNet as C
import argparse
import os
import h5_analysis_jitterer as h
import csv
from collections import OrderedDict
import set_up_caffe_net as s
FLAGS = None
image = None
net = None
transformer = None
image_directory = '/storage/data/imagenet_2012'
correct_class_filename = ''
caffe... |
import matplotlib.pyplot as plt
import numpy as np
from simulations.analysis_sql_data import parse_request_data_from_sql, calc_throughput, get_gen_latencies, \
parse_table_data_from_sql, parse_raw_queue_data
# NOTE!! THIS IS A TEMPORARY FILE FOR PRODUCING PLOTS
# SHOULD NOT BE SEEN AS A GENERAL USE SCRIPT
# EDIT T... |
# Copyright (c) 2020 <NAME>
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... |
"""
Saucebrush Emitters are filters that instead of modifying the record, output
it in some manner.
"""
from __future__ import unicode_literals
from saucebrush.filters import Filter
class Emitter(Filter):
""" ABC for emitters
All derived emitters must provide an emit_record(self, record) that
... |
"""Data model definitions for Kubernetes-related resources"""
from copy import deepcopy
from enum import Enum, auto
from dataclasses import field
from typing import List, Dict
from datetime import datetime
from marshmallow import ValidationError
from kubernetes_asyncio.config.kube_config import KubeConfigLoader
from ku... |
"""this is the main module for the routing algorithm project"""
from argparse import ArgumentParser
import socket
from threading import Thread, Lock
import time
import pickle
import math
# global objects
SOCKET1 = socket.socket(type=socket.SOCK_DGRAM)
PRINT_LOCK = Lock()
# each neighbor is stored as a list with route... |
import os
import numpy as np
import pandas as pd
import glob as glob
import matplotlib.pyplot as plt
# import scipy.stats
# import seaborn as sns
# from sklearn import metrics as skm
import math
from collections import Counter
import networkx as nx
import matplotlib.lines as mlines
from itertools import combinations
im... |
import argparse
import json
import os
import sys
import time
from collections import OrderedDict
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
from haco.utils.config import baseline_eval_config, baseline_train_config
from haco.utils.human_in_the_loop_env import HumanInTheLoopEnv
sys.p... |
#!/usr/bin/env python
""" Copyright (C) 2018 github.com/volskaya
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,... |
import random; random.seed(2019)
import pandas as pd
import numpy as np
from collections import Counter
from models.core import CartModel
import torch
from torch import optim, nn
from torch.nn import functional as F
def flatten(t):
return [item for sublist in t for item in sublist]
def sample2(src, n_smpl, n_ct... |
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
########################################################################################################################
# =======================... |
import os
import synapseclient
from ..base_adapter import BaseAdapter
from .synapse_remote_entity import SynapseRemoteEntity
from ...data_uri import DataUri
from ...sys_path import SysPath
from ...env import Env
from ...utils import Utils
class SynapseAdapter(BaseAdapter):
"""Data Adapter for Synapse."""
DAT... |
import numpy as np
import pandas as pd
import h5py
import os
import scipy.sparse
import warnings
import thimbles as tmb
from thimbles.modeling import Model
from thimbles import resource_dir
from .profiles import convolved_stark
from .spectrum import Spectrum
from thimbles.tasks import task
from thimbles.sqlaimports imp... |
import numpy as np
import moderngl
import logging
from copper.core.vmath import Matrix4
from copper.core.vmath import Matrix4, normalize_v3
from copper.ui.context_manager import ContextManager
from pyrr import Matrix44 # using it temporarily
from .shaders import SURFACE
logger = logging.getLogger(__name__)
class D... |
#!/usr/bin/env python
import logging
import numpy as np
from scipy import linalg
from timeit import default_timer as timer
from os.path import isfile
from os import remove
from tools import get_input, latex_float
from hamiltonian import main as hamiltonian
from plots import bar_plot, histogram
def readH(format):
... |
#!python
# -*- coding: utf8 -*-
# hzau_ddns api based on alidns python sdk
# this script is developed and maintained by <NAME>.
# GitHub: https://github.com/YaoYinYing
import traceback
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs... |
import json
from ..db.models import Datum, Action, ActionType
from .utils import make_datum, make_object_datum, make_object_datum_dict
def test_can_create_datum(client, user, datum_dict):
assert len(user.data) == 0
resp = client.post('/data', headers=user.auth_headers, json=datum_dict)
resp_data = dict(
... |
#!/usr/bin/env python3
# JIRA version sorter
# Copyright 2020 <NAME>
# See README.md and LICENSE.md for details.
from functools import cmp_to_key
import re
import sys
import time
from getpass import getpass
import requests
import json
import config
rest_session = requests.Session()
auth = None
DEBUG = '-d' in sys.a... |
from __future__ import division
from scipy import stats
import argparse
import csv
"""
input (file) format:
project;bugID;ALG;ALG-2;...
time;1;RANK;RANK;...
time;2;RANK;RANK;...
...
lang;1;RANK;RANK;...
...
"""
def arg_parser():
parser = argparse.ArgumentParser(description='calc. Wilcoxon test')
parser.add_a... |
"""
Code for training and testing of transformer.
<NAME>
March 2022
"""
import argparse
import torch
import time
import io
import os
import pickle
import torch.nn as nn
import torch.optim as optim
from torchtext.data import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from datasets import load_... |
# Fast BVH file format reader and writer.
# Has minimal dependencies.
import numpy as np
def _write_indented(ostream, level, line):
if level > 0:
ostream.write(" "*level)
ostream.write(line + "\n")
def _strs_to_floats(lst):
return [float(item) for item in lst]
def _floats_to_strs(lst):
... |
import collections
import contextlib
import json
import os
import pty
import subprocess
import time
import six
from dcos import http, util
from six.moves import urllib
def exec_command(cmd, env=None, stdin=None):
"""Execute CLI command
:param cmd: Program and arguments
:type cmd: [str]
:param env: ... |
import aipy, uvtools
import numpy as np
import pylab as plt
from hera_sim import foregrounds, noise, sigchain, rfi
import datetime
import random
import pickle
from tqdm import tqdm
import pandas as pd
from preprocessor import preprocessor
fqs = np.linspace(.1,.2,64,endpoint=False)
lsts = np.linspace(0,2*np.pi,256, end... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from math import atan, tan, pi
import itertools
def weights_normal_init(model, dev=0.001):
if isinstance(model, list):
for m in model:
weights_normal_init(m, dev)
else:
for m in model.modules():
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016, French National Center for Scientific Research (CNRS)
# Distributed under the (new) BSD License. See LICENSE for more info.
from copy import copy
import time
import numpy as np
import zmq
import ctypes
ctx = zmq.Context()
sock1 = ctx.socket(zmq.PAIR)
sock2 = ctx.socket(z... |
# coding=utf-8
from __future__ import with_statement
import os
import datetime
import time
import socket
import tempfile
import shutil
import stat
import sys
import json
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from util import format_datetime, short_hostname
from .logge... |
#!/usr/bin/python3
import sys, os, time
import json
sys.path.append(os.getcwd())
sys.path.append(f"..")
import web3
from web3 import Web3
class vlsmproofdatasslot():
def __init__(self, contract, name = "vlsmproofdatas"):
self._contract = contract
self._name = name
self._functions = contr... |
"""
Definition of the :class:`FilterSet` subclass that will be assigned to the
:class:`~django_dicom.views.series.SeriesViewSet`\'s
:attr:`~django_dicom.views.series.SeriesViewSet.filter_class` attribute value.
"""
import json
import operator
from functools import reduce
from dicom_parser.utils.code_strings import (
... |
from __future__ import absolute_import
import inspect
import os
import weakref
import flask
import pathlib
from werkzeug.utils import import_string
from keg.extensions import lazy_gettext as _
_signature_cache = weakref.WeakKeyDictionary()
# sentinal object
class NotGiven(object):
pass
def ensure_dirs(newdi... |
# -*- coding: utf-8 -*-
__author__="<NAME> <<EMAIL>>"
__date__ ="$27.11.2014 18:05:15$"
# Copyright 2009-2019 WWPASS Corporation
#
# 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://... |
import logging
from itertools import chain
from typing import List
import aenum
import numpy as np
import onnx
import dace
from dace.dtypes import typeclass
from daceml.onnx.converters import convert_onnx_proto, onnx_type_str_to_typeclass, get_proto_attr
from dace.properties import make_properties, Property, DictProp... |
#!/usr/bin/env python3
#rdfa.deps="[python3]"
import os,sys,requests,configparser
from os.path import dirname
from subprocess import Popen, PIPE
sys.path.append(dirname(__file__))
cpe_ip = '192.168.1.1' #until we move to [ipv6]
# SFR_functions
"""
helper functions
"""
def pwd():
abspath = os.path.dirname(os.path.... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import ubelt as ub
# import utool
import numpy as np
from numpy.random import randint
from vtool_ibeis._pyflann_backend import FLANN_CLS
"""
remove_points does not currently have bindings
nn_radius has incorrect binindgs
class FLAN... |
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.metrics import pairwise_distances
# TODO: rewrite the `[]` (__getitem__) operator to replace the cumbersome `distances` function
class DistanceMatrix(object):
def __init__(self, C, F, dist_mat=None):
"""
Mimic a distance matrix: it may comput... |
# coding=utf-8
import base64
import inspect
import json
import logging
import sys
import time
import warnings
from typing import List
from urllib.parse import unquote
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptojwt.jwt import JWT
from oidcop.exception import FailedAuthentication
from oid... |
from __future__ import division
# Provides some universal statistical utilities and stats comparison tools
from past.utils import old_div
from builtins import object
from math import sqrt
import numpy as np
import pandas as pd
import scipy.interpolate
import scipy.stats
import warnings
from scipy.special import erfin... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from frontera.settings import Settings
from frontera.contrib.messagebus.zeromq import MessageBus as ZeroMQMessageBus
from frontera.contrib.messagebus.kafkabus import MessageBus as KafkaMessageBus, Consumer as KafkaConsumer
from frontera.utils.fingerprint im... |
from typing import AnyStr
def armstrong(x: int) -> bool:
"""
This function determines whether the number given as input is `Armstrong` or not.
If a number passes `Armstrong` test this function returns `True` else `False`
Args: This function takes exactly one argument.
`x:int` : x should be an int... |
import copy
import os
import socket
import sys
# TODO: consider / add dot_env and load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
try:
hostname = socket.gethostname()
except:
hostname = 'unknown'
def _ensure_dir_exists(dirname):
os.makedirs(dirname, exist_ok=True)
return dirname
d... |
"""value_error.py
Collection of functions useful in parsing ValueError messages and
providing a more detailed explanation.
"""
import inspect
import re
from ..my_gettext import current_lang
from .. import info_variables
from .. import token_utils
from .. import utils
convert_type = info_variables.convert_type
parse... |
#!/usr/bin/env python3
import re # for regular expressions
import os
import sys
import csv
import datetime
import math
#import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
# Chec... |
# Copyright 2017 IBM
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... |
from typing import Tuple
import torch
from torch import Tensor
from torch.nn import Linear, Sequential, ReLU
from torch_sparse import SparseTensor
from torch_geometric.nn import to_hetero
from torch_geometric.nn import SAGEConv, GINEConv, RGCNConv
from torch_geometric.nn import Linear as LazyLinear, MessagePassing
c... |
"""Implementations of MCMC algorithms targetting discrete target distributions
MCMC algorithms design for targetting the latent variables z. Random walk
Metropolis-Hastings is implemented in ZRwmh. Slice sampling is implemented
in ZSlice, see <NAME>. (2003). Slice sampling. The Annals of
Statistics, 31(3):... |
"""Will check all the lidar returned
"""
from pathlib import Path
from os import listdir
from os.path import isfile, join
from functools import partial
import argparse
import time
import yaml
# import matplotlib.pyplot as plt
from rich import print as rprint
import numpy as np
from shapely.geometry import shape, Polyg... |
# -*- coding: utf-8 -*-
"""Tools for loading, shuffling, and batching ANI datasets"""
from torch.utils.data import Dataset
from os.path import join, isfile, isdir
import os
from ._pyanitools import anidataloader
import torch
from .. import utils, neurochem, aev
import pickle
default_device = 'cuda' if torch.cuda.is_a... |
import logging
import cv2
import numpy as np
import yaml
class Transformer:
def __init__(self):
"""
Base class for transofrmer
"""
pass
def tune(self, img):
pass
def transform(self, img):
pass
def load_config(self, cfg_name):
pass
class Per... |
import sys, os
from torch.utils import tensorboard
sys.path.append(os.path.abspath(os.path.join('./models')))
sys.path.append(os.path.abspath(os.path.join('./Data_Loaders')))
sys.path.append(os.path.abspath(os.path.join('./Loss_Functions')))
"""
This file defines the core research contribution
"""
import pytorch_ligh... |
import struct
from amqpsfw.exceptions import SfwException
class AmqpType:
def __init__(self, data):
self.encoded = b''
self.decoded_value = data
@classmethod
def decode(cls, binary_data):
raise NotImplementedError
def __add__(self, other):
result = AmqpType('')
... |
# - Coding UTF8 -
#
# Networked Decision Making
# Development Sites (source code):
# http://code.google.com/p/global-decision-making-system/
# http://github.com/NewGlobalStrategy/NetDecisionMaking
#
# Demo Sites (Google App Engine)
# http://netdecisionmaking.appspot.com
# http://globaldecisionmaking.appspot.com
... |
import operator
from dataclasses import dataclass
import numpy as np
from scipy.special import ndtri
from ._common import ConfidenceInterval
def _validate_int(n, bound, name):
msg = f'{name} must be an integer not less than {bound}, but got {n!r}'
try:
n = operator.index(n)
except TypeError:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017, The University of Oxford
# 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 ab... |
"""
<Started>
June 2013
<Author>
<NAME> <<EMAIL>>
<NAME> <<EMAIL>>
<Purpose>
Parse the definition of a system call into a SyscallManual object.
Read the man page of a system call and extract its definition. If a definition
with the exact system call name is not found then pick one with a similar name
i... |
import sys
from pathlib import Path
from itertools import chain
from typing import List
import numpy as np
import pandas as pd
import pandas_flavor as pf
from janitor import clean_names
sys.path.append(str(Path.cwd()))
from config import root_dir # noqa E402
from utils import ( # noqa: E402
get_module_purpose,
... |
import os
import re
from __init__ import PlexLogAdapter
from __init__ import XBMCLogAdapter
from __init__ import preferences
from __init__ import log
def process_subtitle_files(part):
"""
Search for related subtitle files and add them to the media item.
This function searches for subtitle files related ... |
"""
Module for snow masking
"""
import logging
import numpy as np
from PIL import Image
from skimage.morphology import disk, dilation
from eolearn.core import EOTask, FeatureType
LOGGER = logging.getLogger(__name__)
class SnowMask(EOTask):
"""
The task calculates the snow mask using the given thresholds.... |
import json
from typing import Any, Dict, List, Optional, Tuple, Union
import dash_bootstrap_components as dbc
from dash import ALL, Dash, Input, Output, State, callback_context, dcc, html
from dash.development.base_component import Component
from envinorma.models import Annotations, ArreteMinisteriel, StructuredText
... |
# Modelling spread of disease
# https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model
import random
import numpy as np
import matplotlib.pyplot as plt
from random import uniform
def w_choice(seq):
"""
Takes an input on the form of [('A', 30), ('B', ... |
"""write_json.py"""
__author__ = "<NAME>"
import json
import logging
import pathlib
from collections import Counter
from typing import Dict, List, Optional, Union
import numpy
import pandas as pd
from collect_stata.types import Categories, Numeric, Variable
def get_categorical_frequencies(elem: Variable, data: pd.... |
# Copyright (c) 2021 Mira Geoscience Ltd.
#
# This file is part of geoapps.
#
# geoapps is distributed under the terms and conditions of the MIT License
# (see LICENSE file at the root of this source code package).
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from geo... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
import argparse
import logging
import os
import subprocess
import sys
import psycopg2
import yaml
from .utils import get_in
DEFAULT_PK_COLUMN_NAME = 'id'
NULL_ANONYMIZE = lambda column, pk_name: 'NULL'
ANONYMIZE_DATA_TYPE = {
'timestamp with time zone': "'1111-11-11 11:11:11.111111+00'",
'date': "'1111-1... |
# -*- coding:utf-8 -*-
import sys
import copy
import tccli.services as Services
import tccli.options_define as Options_define
from collections import OrderedDict
from tccli.utils import Utils
from tccli.argument import CLIArgument, CustomArgument, ListArgument, BooleanArgument
from tccli.exceptions import UnknownArgum... |
import numpy as np
from scipy.sparse import csr_matrix
from mathematics.manilearn import matrix_density
class Analyzer:
"""Abstract class for Parent Analyzers"""
def __init__(self, provider=None, child_analyzer=None):
"""
Creates an instance that uses a specific problem type and an
... |
import numpy as np
# from silx.opencl.common import pyopencl as cl
import pyopencl.array as parray
from ..utils import get_opencl_srcfile
from .common import OpenclCorrelator
class EventCorrelator(OpenclCorrelator):
kernel_files = ["evtcorrelator.cl"]
"""
A class to compute the correlation function for s... |
import sys
import django
from django.core.exceptions import ImproperlyConfigured
from django.template import Context, Node, TemplateSyntaxError
from django.template.base import Parser, Template
from django.template.loader import get_template, select_template
from django.utils.itercompat import is_iterable
from tag_pa... |
import cv2
import math
import numpy as np
# set up a basic canvas here
img = np.zeros(shape=(512, 512, 3), dtype=np.int8)
# ------ constants -------
RED = (0, 0, 255)
# DEBUG_GREEN = (130, 229, 122)
# BLUE = (238, 97, 67)
DEBUG_GREEN = (238, 97, 67)
BLUE = (130, 229, 122) # changed to green colour for visibility
LI... |
from __future__ import print_function, division
import time, os, sys
sys.path.append(os.path.dirname(sys.path[0]))
from copy import copy
try:
import cPickle as pickle
except ImportError:
import pickle
import numpy as np
from scipy.interpolate import interpn
from matplotlib import pyplot as plt
... |
import ast
import hashlib
import logging
import os
import re
from collections import namedtuple
from difflib import SequenceMatcher
from functools import lru_cache
from glob import glob
from pathlib import Path
from shutil import copyfile
from typing import Any, List, Optional, Union
from ruamel.yaml import YAML
from ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 OpenStack Foundation
#
# 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
#
# Unle... |
from helpers import *
from mobject.vectorized_mobject import VGroup, VMobject, VectorizedPoint
from topics.geometry import Square, Line
from scene import Scene
from camera import Camera
from animation.continual_animation import AmbientMovement
from animation.transform import ApplyMethod
class CameraWithPerspective(C... |
# Copyright 2018 Lawrence Livermore National Security, LLC and other
# sonar-driver Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from pyspark.sql.functions import lead, lag
from pyspark.sql.window import Window
from pyspark.sql.functions import udf,... |
import pygame
import settings
import math
from vector import Vector2D
from animation import Animation, OneTimeAnimation
# http://www.gamasutra.com/view/feature/3938/the_pacman_dossier.php?print=1
class Player(pygame.sprite.Sprite):
def __init__(self, position=(0, 0)):
super(Player, self).__init__()
... |
"""Sudoku Solver
"""
class SudoKu():
def __init__(self,sudo_ku_data):
if not isinstance(sudo_ku_data,list):
raise TypeError(f'sudo_ku_data params must a list, but {sudo_ku_data} is a {type(sudo_ku_data)}')
if len(sudo_ku_data) != 9 or len(sudo_ku_data[0]) != 9:
raise TypeErr... |
#
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... |
from mamba import ast
from .constraint import Constraint
from .symbol import dot_symbol
from . import exc
from . import types
class ConstraintInferer(ast.Visitor):
"""Static analysis pass that infers the types of all nodes in the AST."""
def __init__(self):
self.errors = []
self.constraints ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.