text stringlengths 3.07k 12.6k |
|---|
import numpy as np
from numpy import *
import tensorflow as tf
import os
import re
import pickle
import nltk
from utils import *
def vectorize_data(data, word2idx, memory_size, sentence_size):
S = []
Q = []
domains = []
word_len = []
sentence_len = []
for review, domain, label in data:
... |
import argparse
import json
import logging
import multiprocessing
import numpy as np
import os
import pathlib
import sys
import tifffile
import tqdm
from .scan import Scanner, AverageDrift
from .volume import VExtent
def parse_args(args=sys.argv[1:]):
parser = argparse.ArgumentParser()
parser.add_argument("-... |
from __future__ import print_function
import os
import matplotlib
import numpy as np
from cartopy.mpl.ticker import LatitudeFormatter
from e3sm_diags.driver.utils.general import get_output_dir
from e3sm_diags.plot import get_colormap
matplotlib.use("Agg")
import matplotlib.colors as colors # isort:skip # noqa: E4... |
# Copyright 2018-2019 CRS4
#
# 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, softwa... |
import datetime
import os
import time
import torch
import torch.utils.data
import torchvision
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
from data.apple_dataset import AppleDataset
from utility.engine import train_one_epo... |
# -*- coding: utf-8 -*-
# 2020/11/19
# create by: snower
import time
import pickle
import json
from ..utils import human_repr_object
from .database import QueryBuilder, InsertBuilder, UpdateBuilder, DeleteBuilder, DataBase
class StringSerialize(object):
def loads(self, data):
return str(da... |
"""
Generic tests for all BoltArrays
"""
from __future__ import print_function
from numpy import dtype
from bolt.utils import allclose
import pytest
def map_suite(arr, b):
"""
A set of tests for the map operator
Parameters
----------
arr: `ndarray`
A 2D array used in the construction of `b... |
import pytest
from tensora import Tensor, evaluate
def assert_same_as_dense(expression, format_out, **tensor_pairs):
tensors_in_format = {name: Tensor.from_lol(data, format=format) for name, (data, format) in tensor_pairs.items()}
tensors_as_dense = {name: Tensor.from_lol(data) for name, (data, _) in tensor_... |
import os
import argparse
import datetime
import time
import os.path as osp
import numpy as np
import torch
import torch.nn as nn
from torch.optim import lr_scheduler
from datasets import Dataset
from samplecnn import ZHNET
from torch.utils import data
from utils import *
from center_loss import CenterLoss
from datetim... |
#! /usr/bin/env python
# encoding: UTF-8
# <NAME> 2009
"""
ported from waf 1.5:
TODO: tabs vs spaces
"""
from waflib import Task, Utils, Errors, Logs
from waflib.TaskGen import feature
VALADOC_STR = '${VALADOC}'
class valadoc(Task.Task):
vars = ['VALADOC', 'VALADOCFLAGS']
color = 'BLUE'
after = ['cprogram', 'cs... |
# greaseweazle/codec/amiga/amigados.py
#
# Written & released by <NAME> <<EMAIL>>
#
# This is free and unencumbered software released into the public domain.
# See the file COPYING for more details, or visit <http://unlicense.org>.
import struct
import itertools as it
from bitarray import bitarray
from greaseweazle.t... |
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten, Softmax
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.callbacks import Re... |
# -*- coding: utf-8 -*-
"""
This script implements infinite-horizon and finite-horizon value iteration.
The infinite-horizon value iteration code is adapted from <NAME>. See:
https://github.com/dennybritz/reinforcement-learning/blob/master/DP/Value%20Iteration%20Solution.ipynb
http://www.wildml.com/2016/10/lea... |
#Energy Stats V0.0.0
#Author: <NAME>
#Curtin University, Bently, Western Australia
#ID 18091649
import io
import Appliances
from pathlib import Path
from Appliances import Appliance
class ApplianceOwner():
"""
Appliance owners are objects that can own an appliance, and therefore has an instance field that i... |
#!/usr/bin/env python
import sys
import subprocess as sp
# This was just to check compatibiity with some old runs
RUN_GDEVAL=False
def Usage(err):
if not err is None:
print(err)
print(
"Usage: <qrel file> <trec-format output file> <optional prefix of report files> <optional label (mandatory if... |
import pygame
import queue
from tkinter import *
from tkinter import messagebox
import random
def makeObstacle(surface, s, cell_num, pos):
dist = s//cell_num
lX = 0
lY = 0
for p in range(cell_num):
for q in range(cell_num):
area = pygame.Rect(lX, lY, dist, dist)
if a... |
from django.contrib import admin, messages
from django.db.transaction import atomic
from import_export.admin import ExportActionMixin
from import_export.fields import Field
from import_export.resources import ModelResource
from reversion.admin import VersionAdmin
from logs.logic.attempt_import import reprocess_attempt... |
import io
import os
from os.path import join
import re
import utils
yearRe = re.compile("[0-9]{3,}")
def clean(rootFileName, outputPath):
"""
Chrono triggers data is split by each location so
it is processed a little different. Each section
is processed. To avoid too much file fragmentation,
... |
import shutil
import subprocess
def make_debug(pkg, f, relf):
if not pkg.rparent.options["debug"] or not pkg.rparent.build_dbg:
return
dfile = pkg.destdir / "usr/lib/debug" / relf
cfile = pkg.chroot_destdir / "usr/lib/debug" / relf
dfile.parent.mkdir(parents = True, exist_ok = True)
try:
... |
import click
import numpy as np
import pandas as pd
from scipy import stats
from typing import NamedTuple, Union, List, Tuple
from pathlib import Path
from loguru import logger
from vivarium.framework.randomness import get_hash
from vivarium_public_health.risks.data_transformations import pivot_categorical
from vivar... |
"""Contains the base expression plugins in a single module to speed Pavilion
loading."""
import math
import random
import re
from typing import List
from .base import FunctionPlugin, num
from .common import FunctionPluginError, FunctionArgError
class CoreFunctionPlugin(FunctionPlugin):
"""A function plugin that... |
from application import db, NEIGHBORHOODS, ROOM_TYPES
import datetime as dt
import re
from flask import flash, abort
from sqlalchemy.orm import validates
from sqlalchemy.sql.expression import column
from sqlalchemy.exc import IntegrityError
class Entry(db.Model):
"""
Entry class represents a prediction made a... |
import objc
from Foundation import NSBundle
# Predefine some opaque types
DASessionRef = objc.createOpaquePointerType('DASessionRef', '^{__DASession=}', None)
DADiskRef = objc.createOpaquePointerType('DADiskRef', '^{__DADisk=}', None)
# Load DiskManagement framework classes
DiskManagment = objc.loadBundle('D... |
#!/usr/bin/env python3
'''Script for ARP spoofing'''
import time, os, sys
from framebuilder import eth, ipv4, tcp, tools, errors
def print_err(msg):
arg_str = 'interface left_ip right_ip'
print('Error:', msg)
print(f'Usage: {sys.argv[0]} {arg_str}')
def check_args():
if len(sys.argv) < 4:
... |
#!/usr/bin/env python3
#
# select_shapelets_min_max.py: given a set of extracted shapelets,
# potentially separated into blocks, pools all of them and selects
# a number of shapelets based on maximizing the dissimilarity.
#
# More precisely, the accuracy induced by the split of each shapelet is
# calculated and all sha... |
"""
@Date: 2021/10/06
@description: Use the approach proposed by DuLa-Net
"""
import cv2
import numpy as np
import math
import matplotlib.pyplot as plt
from visualization.floorplan import draw_floorplan
def merge_near(lst, diag):
group = [[0, ]]
for i in range(1, len(lst)):
if lst[i] - np.mean(group... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect 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... |
'''
Made by: <NAME>
Created on: 01/03/2022;
'''
from plotly.subplots import make_subplots
import plotly.express as px
import plotly.offline as pof
import pandas as pd
import warnings
import requests
import subprocess
import json
import sys
import os
warnings.filterwarnings("ignore")
def extract_json(dict):
user=... |
#!/usr/bin/env python
__copyright__ = "Copyright (C) 2020 <NAME>"
__license__ = """
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... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import os
import re
import llnl.util.tty as tty
from spack.paths import build_env_path
from spack.util.executable import w... |
from tempfile import tempdir
import torch as t
import numpy as np
import torch
import pandas as pd
import torch.nn.functional as F
from torch.utils.data import DataLoader
from utils.config import Config
from models.my_net import EfficientNet_B2, EfficientNet_B3, SEResNet50, ResNet101
from models.other_model import HR... |
import os
from pathlib import Path
import joblib
import hashlib
import zipfile
import shutil
from mega import Mega
DATA_DUMP_NAME = 'data.joblib'
DATA_HOME_FOLDER_NAME = 'pyadlml_data_home'
def set_data_home(path_to_folder):
"""
Sets the global variable ``data_home`` and creates the according folder.
All ... |
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#
#modification, are permitted provided that the following conditions are
#met:
#
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem.snowball import SnowballStemmer
from services.nlp import nlp
from conf import settings
log = logging.getLogger()
log.setLevel(level=logging.DEBUG)
_ENTITIES = 'entities'
_METADATA = 'meta... |
from collections import defaultdict
from math import sqrt
from typing import Mapping, DefaultDict, Dict, Set, Optional, List
from texttable import Texttable
from zenalyzer.parser import Category
from zenalyzer.sums import Sum, MultiCurrencySum, MultiCurrencySumEvaluator, format_currency
PerCategorySums = Mapping[Cat... |
import sys
import logging
import urllib
import requests
from os import environ
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from gitlabform.configuration.core import ConfigurationCore, KeyNotFoundException
s = requests.Session()
retries = Retry(total=3,
... |
import numpy as np
from utils.load_data import Load_data
import tensorflow as tf
from configuration import conf
class Baseline_loader(object):
def __init__(self):
try:
load_func = getattr(load_data,'load_'+ conf.dataset_name)
self.data = load_func(conf.is_conv)
except:
assert ValueError('Dataset is not ... |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... |
import json
import logging
from functools import wraps
from django.contrib import messages
from django.core.cache import cache
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.http import require_P... |
# -*- coding: utf-8 -*-
#
# This file is part of Karesansui.
#
# Copyright (C) 2009-2012 HDE, Inc.
#
# 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 lim... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
import torch
class BaseMasked(torch.nn.Module):
"""The base class for linear layers that should have fixed sparsity
pattern.
Attributes
----------
is_sparse : bool, read-only
Indicates if the instance has a valid usable mask.
mask : torch.Tensor
The current mask used for the ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# 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 Li... |
import numpy as np
from pyecore.resources import ResourceSet, URI
from pymoo.util.normalization import normalize
from pymoo.visualization.scatter import Scatter
from pymoo.factory import get_decision_making
from pymoo.configuration import get_pymoo
from pyallocation.problem import AllocationProblem
from pyallocation.ut... |
import gzip
# Read or generate p2h, a dictionary of image name to image id (picture to hash)
import pickle
import platform
import random
# Suppress annoying stderr output when importing keras.
import sys
from lap import lapjv
from math import sqrt
# Determine the size of each image
from os.path import isfile
import ma... |
# Hastily made script to read WPS intermediate files
from __future__ import print_function
import struct
import numpy as np
# Number of bytes used at the start and end of a fortran record to
# indicate the record size
SIZE_BYTES = 4
class WPSData(object):
def __init__(self, ifv=None, hdate=None, xfcst=None, map... |
#!/usr/bin/env python3
"""for collecting the analog data as it arrives."""
import sys, signal
import csv
import usb.core
import struct
import time
import argparse
import numpy as np
from gr.pygr import mlab
# Summary:
# Unpack the data from the transferred USB Packets. Alert on dropped packets.
# Store data in a FI... |
import struct
import collections
from .exceptions import UnsupportedMessageEncodingError, MessageTooLargeError
class ByteBuffer:
def __init__(self):
self._deque = collections.deque()
self._size = 0
self._flow_controlled_length = 0
def append(self, data, flow_controlled_length=None):
... |
from collections import OrderedDict
import tensorflow as tf
import tensorflow_estimator as tfe
from tensorflow.python.estimator.export.export_output import PredictOutput
from tensorflow.python.saved_model import signature_constants
from tfnlp.common import constants
from tfnlp.common.config import train_op_from_confi... |
# encoding: utf-8
import torch
from torch import nn
import torch.nn.functional as F
from .backbones.resnet import ResNet, BasicBlock, Bottleneck
from .backbones.resnet_NL import ResNet_NL
from .backbones.ResNet import C2D_Axial_ResNet50
def weights_init_kaiming(m):
classname = m.__class__.__name__
if classna... |
#!/usr/bin/env python3
'''
This script takes two <.rtsc> along with the base <.fasta> to calculate the reactivity
scores of each nucelotide of each transcript. If used without a <.scale> file, the script will generate
a <.scale> to be used with this script when calculating any additinonal reactvities from other sampl... |
from django.utils import timezone
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.views.decorators.http import require_http_methods
from django.db import IntegrityErro... |
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... |
from __future__ import absolute_import, division, print_function
import click
import cv2
import matplotlib.cm as cm
import numpy as np
import yaml
from addict import Dict
# ---- added for writing csv
import os
import datetime
import csv
import operator
# ---------------------------
import glob
# sort dict
from oper... |
from flask import Flask, render_template, url_for, request, redirect, session, flash, Response
from model import db, Player
import cv2
from HandTrackingModule import handDetector
from choiceClass import Choice
import utils
app = Flask(__name__)
app.secret_key = "super secret key :)"
app.config["SQLALCHEMY_DATABASE_URI... |
#!/usr/bin/env python
# Copyright 2017 Citrix Systems
#
# 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... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from typing import Callable, List, Optional, Tuple
import click
import numpy as np
import torch
from tt... |
import numpy as np
import tensorflow as tf
import requests
#NLP
import spacy
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from pattern.en import pluralize, singularize
#universal sentence encoder
import tensorflow_hub as hub
import pickle
from sklearn.neighbors import KNeighborsClassifier... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This script creates new items on Wikidata based on certain criteria.
* When was the (Wikipedia) page created?
* When was the last edit on the page?
* Does the page contain interwikis?
This script understands various command-line arguments:
-lastedit The minimum n... |
import functools
import operator
import os
import os.path
import re
import sys
import numpy as np
import google.protobuf.text_format
import pytest
from os.path import abspath, dirname, join, realpath
import tools
import shutil
# Local files
current_file = os.path.realpath(__file__)
current_dir = os.path.dirname(curren... |
"""
@author: <NAME>, <NAME>
@date: 20201012
@contact: <EMAIL>
"""
# based on:
# https://github.com/deepinsight/insightface/blob/master/Evaluation/Megaface/remove_noises.py
# for 1M test, remove facescrub noise 25, megaface noise 686.
import os
import yaml
import numpy as np
import argparse
import shutil
import loggi... |
from __future__ import annotations
import asyncio
import itertools
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast
from ....utils.async_event import async_tasking_event_iterator
from ....utils.logging import LoggingDescriptor
from ....utils.uri import Uri
... |
################################################################
# zopyx.smartprintng.lite
# (C) 2009, ZOPYX Limited & Co. KG, D-72070 Tuebingen, Germany
################################################################
""" HTML transformation classes (based on BeautifulSoup) """
import os
import re
import copy
impor... |
#!/usr/bin/env python3
import os
import time
import matplotlib
matplotlib.use('Agg')
import numpy as np
import chainer
import chainer.functions as F
import chainer.links as L
import matplotlib.pyplot as plt
import yaml
from util import calc_reward, makedir, output_graph, output_distribution, load_conf
class MLP(ch... |
import numpy as np
import pandas as pd
import random
random.seed(123)
np.random.seed(123)
path= "/Users/ericchou/Desktop/PyCharm/Data Mining HW PROGRAM/Boston_Housing.csv"
with open(path, "r") as file:
database= pd.read_csv(file)
def shuffle(x):
list_= list(np.arange(0, len(x)).astype(int))
random.shuffle... |
"""
Download the daymet data for camels-basins outside of the boundary of downloaded xarray dataset using nldi shapfile
"""
import argparse
import os
import sys
from collections import OrderedDict
import numpy as np
import pandas as pd
import xarray as xr
from tqdm import tqdm
sys.path.append(os.path.join("..", ".."... |
#!/usr/bin/env python
# Copyright 2015 <NAME> <<EMAIL>>
#
# 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 la... |
# Methods for loading data.
#
# https://github.com/stefanvanberkum/CD-ABSC
#
# Adapted from Trusca, Wassenberg, Frasincar and Dekker (2020).
# https://github.com/mtrusca/HAABSA_PLUS_PLUS
#
# <NAME>., <NAME>., <NAME>., <NAME>. (2020) A Hybrid Approach for Aspect-Based Sentiment Analysis Using
# Deep Contextual Word Embe... |
from labelbox.utils import camel_case
from typing import List, Optional, Union
from pydantic import BaseModel, Field
from ...annotation_types.annotation import (ClassificationAnnotation,
ObjectAnnotation,
VideoClassificationAnnota... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os.path import join
import click
from .utils import pretty_print_item, pretty_print_key
from ..lib.api import API
from ..lib.config import Config
from ..lib.gpg import GPG
from ..lib.vault import Item, Key
class Context(object):
def __init__(self):
s... |
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import keras
from keras import Input, Model
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras.layers import Flatten, Dense, BatchNormalization, Dropout, Lambda, GlobalAveragePooling2D, Glo... |
from dataclasses import dataclass
from enum import Enum, auto
from re import compile as re_comp
from string import ascii_lowercase, ascii_uppercase
from typing import List, Optional
from .errors import error
class TokenType(Enum):
IDENTIFIER = auto()
NUMBER = auto()
STRING = auto()
LPAR = auto()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
from PIL import Image as PILImage
def normalise(im):
"""Normalize an image matrix from 0 - 255 to 0... |
from __future__ import print_function
import time
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd.gradcheck import zero_gradients
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
import os
import argpa... |
"""
To test the performance of Fine Tuned ResNet-50
"""
from __future__ import print_function
#To reduce verbosity
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']= '3'
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils
from keras.callbacks import ReduceLROnPlateau, CSVLogger, Earl... |
from __future__ import absolute_import, division, print_function
import sys
from libtbx import easy_pickle
from libtbx.utils import Sorry
import libtbx.load_env
from libtbx import smart_open
import os
import csv
import requests
web_urls = {"rcsb": (
"https://data.rcsb.org/graphql", """
{{
entries(entry_ids: {... |
import io
from urllib.request import urlopen
import base64
from liquer.commands import command, first_command
from liquer.parser import encode, decode
from liquer.state_types import encode_state_data
from liquer.cache import get_cache
from liquer.constants import Status
@command
def let(state, name, value):
"""Se... |
import mushroom
import datetime
import utils
import soil
from numba import jit
def tree_value(mushroom, tree_type: str):
com_fac = 1
if mushroom.attr['commonness'] == "Selten":
com_fac = 0.33
hardwood = 0
if tree_type == "Mischwaelder" or tree_type == "Laubwaelder":
hardwood = 1
so... |
import requests
import json
import urllib
import sys
import locale
import babel.numbers
import decimal
import dateutil.parser
import datetime
key = "{key goes here}"
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8', 'Authorization': 'Bearer ' + key}
def call(url, payload):
r = requests.ge... |
# created by <NAME> at Dec 4 15:22:58 CST 2021
# ResNet --jupyter version
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from config_training import config
batch_size = config['batch_size']... |
from django.shortcuts import render
from django.contrib.auth.models import User
from django.core.mail import send_mail
from .models import *
from .forms import ContactForm
# Create your views here.
def base(request):
return render(request, "/base.html")
def login(request):
target_page = "./registration/logi... |
import configparser
import flask
import hashlib
import hmac
import os
from committee.config import ConfigLoader
from committee.logic import Committee, CommitteeResult, GitHubClient
ENVVAR_CONFIG = 'COMMITTEE_CONFIG'
def load_config_web(app):
if ENVVAR_CONFIG not in os.environ:
app.logger.critical(f'Con... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2012 New Dream Network, LLC (DreamHost)
#
# 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
#
# Unles... |
from urllib.parse import urlparse
from discord.ext import commands
from .utils import utils
import collections
import traceback
import functools
import discord
import inspect
import logging
import asyncio
import datetime
log = logging.getLogger(__name__)
"""
Credit to Danny(Rapptz) for example of custom commands
It w... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__... |
#!/usr/bin/env python
# MIT License
#
# Copyright (c) 2020-2022, <NAME>
#
# 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 u... |
import msgpack
import imageio
import os
import sys
import re
import argparse
import numpy as np
import cv2
import time
import json
import multiprocessing as mp
import random
import logging
def parse_args():
parser = argparse.ArgumentParser(description="")
parser.add_argument("-v", "--verbose", action="... |
from typing import Union, Any, Iterable, Optional
import logging
from abc import ABC, abstractmethod
import datetime
import discord
from google.cloud import firestore
# Set up logging
logger = logging.getLogger(__name__)
class InvalidKeyError(BaseException):
def __init__(self, key: str):
self._key = ke... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import functools
import importlib
import logging
import os
from collections import namedtuple
from d2go.utils.helper import get_dir_path
from d2go.utils.oss_helper import fb_overwritable
from detectron2.data import DatasetC... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.http import Http404, HttpRe... |
import multiprocessing
from scipy.sparse.linalg import iterative
from stats_arrays.random import MCRandomNumberGenerator
from . import prepare_lca_inputs, spsolve
from .lca import LCA
class MonteCarloLCA(LCA):
"""Normal ``LCA`` class now supports Monte Carlo and iterative use. You normally want to use it instea... |
from ikpy.chain import Chain
import numpy as np
from scipy.spatial.transform import Rotation as R
import math
def wrap_to_pi(degree):
if(degree > math.pi):
return degree - math.pi*2
elif(degree < -math.pi):
return degree + math.pi*2
else:
return degree
def check_valid(state, bounds):
for i in range(6):
i... |
"""Authentication views"""
from urllib.parse import quote, urlencode, urljoin, urlparse
import requests
from anymail.message import AnymailMessage
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.views import LogoutView
from django.core import mail as django_mail... |
# Copyright 2009-2017 <NAME>.
# This program is distributed under the MIT license.
import operator
import itertools
from python_toolbox.logic_tools import all_equivalent
def test():
_check(False)
_check(True)
def _check(assume_transitive):
assert all_equivalent([1, 1, 1, 1], assume_transitive=assume_t... |
"""
This file provides functions needed to parse the configurations and initialise the experiment
"""
import sys
from datetime import datetime
from pathlib import Path
from types import SimpleNamespace
import torch
import torch.nn as nn
import yaml
from models.CopulaVAE import GaussianCopulaVAE, LaplaceCopulaVAE... |
from flask import Blueprint
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext import admin
from flask.ext.admin.contrib import sqla
from flask.ext.admin import Admin, BaseView, expose
from flask.ext.admin.base import MenuLink
from flask.ext.admin.babel import gettext, ngettext, lazy_gettext
from flask.ext.admi... |
import tvm
from tvm import relay
import type_utils
def check_instantiate(start, mapping, expected):
new_type = type_utils.instantiate(start, mapping)
return tvm.ir.structural_equal(new_type, expected)
def check_mapping(mapping, expected):
hash_mapping = {
tvm.ir.structural_hash(tv): ty
fo... |
from sys import stderr
from Main.HTML.HTML import *
from Main.Parser.Parser import *
import argparse
from Main.Parser.TemplateCreator import *
from Main.DB.DatabaseMerger import *
def _str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
... |
import numpy as np
import sqlalchemy
import datetime as dt
from sqlalchemy.ext.automap import automap_base, name_for_collection_relationship
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
##########################################################
# Databa... |
from __future__ import print_function
import sys
import os
import math
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
import copy
# Import helper functions
from mlfromscratch.utils.data_manipulation import train_test_split, categorical_to_binary, normalize, binary_to_categorical
from m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.