text stringlengths 3.07k 22.1k |
|---|
import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_cors import CORS
import json
from models import setup_db, Player, Match, Settings
from sqlalchemy.orm import relationship
from sqlalchemy import or_
from auth.auth import AuthE... |
# coding=utf8
from word import word
import Trie
class Tree(Trie.Tree):
def __init__(self, w):
super(Tree, self).__init__(w)
self.T = {}
# use a Static.Node as root
self.root = Node(word.epsilon, None)
def _insert_leaf(self, q, root):
new_node = super(Tree, self)._i... |
import json
import os
import random
import warnings
from typing import Optional, Tuple
from sklearn.metrics import mean_absolute_error
import numpy as np
import pandas as pd
from src.parser import make_df_base_from_train_engagement, make_df_base_from_test
class Environment:
def __init__(self,
d... |
# Copyright 2019-2019 the garnish authors. See copying.md for legal info.
import re
import sys
import subprocess
from pymol import cmd
# local imports
from .utils import get_gmx, update_recursive, clean_path
def parse_top(top_file):
"""
parses a topology file and returns useful information on the system
... |
#!/usr/bin/python
import sys,os
import idl
(TYPE_DEFBOOL, TYPE_BOOL, TYPE_INT, TYPE_UINT, TYPE_STRING, TYPE_ARRAY, TYPE_AGGREGATE) = range(7)
def py_type(ty):
if ty == idl.bool:
return TYPE_BOOL
if ty.typename == "libxl_defbool":
return TYPE_DEFBOOL
if isinstance(ty, idl.Enumeration):
... |
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class AccountTaxReport(models.Model):
_name = "account.tax.report"
_description = 'Account Tax Report'
_order = 'country_id, name'
name = fields.Char(string="Name", required=True, help="Name of... |
import torch
import sys
import os
from pathlib import Path
from copy import deepcopy
lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve()
if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir))
from utils.sotl_utils import analyze_grads, avg_state_dicts
def fo_grad_if_possible(args, fnetwork, c... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from lib.pspnet import PSPNet
from lib.utils import sample_rotations_12, sample_rotations_24, sample_rotations_60
psp_models = {
'resnet18': lambda: PSPNet(sizes=(1, 2, 3, 6), psp_size=512, deep_features_size=256, backend='resnet18'),
'resnet3... |
"""
Functions for preprocessing TCGA expression data and mutation status labels.
Most functions are adapted from:
https://github.com/greenelab/BioBombe/blob/master/9.tcga-classify/scripts/tcga_util.py
"""
import os
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.preprocessing import Stand... |
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from math import ceil, floor
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import ma... |
import torch
import torch.nn as nn
from copy import deepcopy
from xnas.spaces.OFA.ops import *
from xnas.spaces.OFA.utils import min_divisible_value
__all__ = ["WSConv_Network", "MobileNetV3", "MobileNetV3Large"]
class WSConv_Network(nn.Module):
"""Network with all Conv2d replaced by Weight Standard Conv2d."""... |
# coding: utf-8
"""
Collections that wrap multiple targets.
"""
__all__ = ["TargetCollection", "FileCollection", "SiblingFileCollection"]
import types
import random
from contextlib import contextmanager
import six
from law.target.base import Target
from law.target.file import FileSystemTarget, localize_file_targ... |
from abc import ABCMeta
from collections import OrderedDict
from datetime import datetime
from ..apis import API
from ..apis.parsers import JSONParser, Parser, XMLParser, parser_property
from ..exceptions import ObjectNotFound
from ..types import FrozenIDs, IDs, Serializable
class Field:
"""
A field on a cho... |
import re
ONSETS = {
'b': 'b',
'd': 'd',
'h': 'h',
'l': 'l',
'm': 'm',
'n': 'n',
'p': 'p',
'r': 'r',
's': 's',
't': 't',
'v': 'v',
'x': 'x',
'đ': 'dd',
'tr': 'tr',
'th': 'th',
'ch': 'ch',
'ph': 'ph',
'nh': 'nh',
'kh': 'kh',
'gi': 'gi',
... |
import argparse
import os
import os.path as path
import glob
import torch
import torch.nn as nn
import logging
from others.logging import set_logger, init_logger
import train_abstractive as train_abs
import models.data_loader as data_ldr
import models.model_builder as model_bld
import models.predictor as pred_abs
from ... |
# example of pix2pix gan for satellite to map image-to-image translation
import argparse
import os
import timeit
from numpy import load
from numpy import zeros
from numpy import ones
from numpy.random import randint
from tensorflow.keras.optimizers import Adam
from keras.initializers import RandomNormal
from keras.mode... |
import collections
import contextlib
import math
import typing as tp # NOQA
import numpy
import six
import torch
SCALAR = 100
IMAGE = 200
VIDEO = 300
TEXT = 400
class Reporter(object):
"""
reporter
See the following example::
>>> reporter = Reporter()
>>> with reporter.scope('loss'):
... |
#
# Copyright (c) 2019 Intel 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 to... |
# -*- coding: utf-8; -*-
"""Valentine's day card using the Navier-Stokes solver."""
from enum import IntEnum
import numpy as np
import matplotlib.pyplot as plt
from unpythonic import ETAEstimator
from fenics import (FunctionSpace, VectorFunctionSpace, DirichletBC,
Expression, Constant,
... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
This module provides class to deal with experiment batch operations.
AAB
"""
from StringIO import StringIO
from thelma.tools.semiconstants import ITEM_STATU... |
"""
Script containing various utilities related to model training, testing, and extraction of attention
weights.
"""
import logging
import torch
from data_utils import get_features
def binary_accuracy(y_pred, y_true):
"""Function to calculate binary accuracy per batch"""
y_pred_max = torch.argmax(y_pred, dim... |
from os import name
from django.db import models
from django.db.models.deletion import CASCADE
import xml.etree.ElementTree as ET
from lxml import etree
from django.utils import tree
# Before saving objects to the database, we put them in an array
# Because of the structure of the XML files we cant directly add
# T... |
# pylint: disable=bad-continuation # Black and pylint disagree on this
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
# pylint: disable=C0103
import ctypes
import io
import logging
import struct
from typing import Optional
from collecti... |
#!/usr/bin/env python3
import argparse
import random
import string
import time
import requests
import socket
import os
import json
from checklib import FlagAdderDown, MumbleService, CorruptedService
flag_adder = 'http://localhost:5000/?team_id={}&round_id={}'
PORT = 7777
RECV_SLEEP = 0.2
def get_flag(team_id, roun... |
import os
import urllib.request
import subprocess
import glob
import cv2
import math
import numpy as np
from config import get_args
def load_txt(file_path, mode='trainval'):
filename = 'ava_file_names_{}_v2.1.txt'.format(mode)
filename = os.path.join(file_path, filename)
with open(filename, 'r') as f:
... |
import copy
import numpy as np
from astropy import units as u
from astropy.modeling.models import Shift
from astropy.modeling.tabular import Tabular1D
from gwcs import WCS as GWCS
from gwcs import coordinate_frames as cf
def refraction_index(wavelength, method='Griesen2006', co2=None):
"""
Calculates the ind... |
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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 righ... |
########################################################
## IMPORT ##
########################################################
import torch
import torch.nn as nn
import torch_scatter
from torch_geometric.utils import softmax, degree
from torch_geometric.nn import MessagePass... |
import concurrent
import contextlib
import itertools
import logging
import os
import pickle
import statistics
import time
from abc import ABC, abstractmethod
from functools import wraps
import numpy as np
import scipy.fft as fft
import torch
from pyinsect.collector.NGramGraphCollector import (
ArrayGraph2DCollecto... |
import torch, time
import torch.nn as nn
import baseline_model_layers as bml
# B: batch size
# T: max sequence length
# E: word embedding size
# C: conn embeddings size
# H: hidden size
# Y: output size
# N_dir: num directions
# N_layer: num layers
# L_i: length of sequence i
class BiCondLSTMModel(torch.nn.Module)... |
import typing as t
import collections
import uuid
from odss.core.query import create_query
from .interfaces import (
IConfiguration,
IConfigurationStorage,
IConfigurationDirectory,
IConfigurationAdmin,
IConfigurationManaged,
IConfigurationManagedFactory,
TProperties,
)
from .consts import S... |
#!/usr/bin/env python
# coding: utf-8
# # Basics of Deep Learning
# In this notebook, we will cover the basics behind Deep Learning. I'm talking about building a brain....
#
# 
#
# Only kidding. Deep learning is a fascin... |
# coding:utf-8
from inspect import signature, Signature
from itertools import islice
from operator import attrgetter
from ..callables import bind
from ..simple_repr import set_simple_repr_init_args, set_simple_repr_class_attrs
from ..subclassing import SubclassMutatorMethod
class ScalaClass(type):
"""At import ti... |
"""
Defines the class Surface
includes function
"normal_vector" calculates the normal vectors in every point of the surface
"plot" which plots the surface
"write" which writes the surface points into a .srf file
"""
import numpy as np
#import init_surface as init
import matplotlib.pyplot as plt
import TestingSurfaces
... |
import cv2
import numpy as np
import collections
from ..utils import backend_utils as backend
# Structure to hold objects
DetectionObject = collections.namedtuple(
'DetectionObject', ['id', 'score', 'bbox'])
class BoundingBoxesNP:
"""Vectorized bounding boxes, harnessing the power of Numpy!
"""
... |
from __future__ import print_function
import argparse
import os
import engineml.torch as eml
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data.distributed
from PIL import Image
from tenacity import retry, stop_... |
""" 栈的应用2,迷宫求解,基于队列的迷宫求解 """
from stack_list import *
from queue_list import *
maze1 = [
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1],
[1,0,0,0,0,1,0,1,0,1,0,1,1,0,1,0,1,1,0,1],
[1,1,1,1,1,1,0,1,0,1,0,0,0,0,1,0,0,0,0,1],
[1,0,0,0,1,0,0,1,1,1,0,1,1,... |
import aiorwlock
import enum
import contextlib
import copy
import io
import logging
import numpy
import pathlib
import tensorflow as tf
import uuid
from abc import ABCMeta, abstractmethod
from datetime import datetime
from typing import Sequence, Union
from tensorcraft import errors
from tensorcraft import signal
fro... |
# -*- coding: utf-8 -*-
import datatype
import cvtype
class Function(object):
"""
Function consisting of declaration and a definition. For both, declaration
and definition a list of headers (e.g. ['"stromx/runtime/Matrix.h"',
'<sstream>']) can be given. The will be included in the respective files.
... |
#
# Copyright (c) 2021, Hyve Design Solutions Corporation.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shlex
import click
from clk.commandresolver import CommandResolver
from clk.config import config
from clk.core import get_ctx, run
from clk.decorators import pass_context
from clk.flow import clean_flow_arguments, flowdeps
from clk.lib import ordered_unique, quote... |
import csv
import glob
import os
from pathlib import Path
"""Code for "<NAME>, <NAME>, <NAME>, <NAME>, Open-source deep learning-based automatic segmentation of
mouse Schlemm’s canal in optical coherence tomography images. Experimental Eye Research, 108844 (2021)."
Link: https://www.sciencedirect.com/science/article/p... |
import numpy as np
import pandas as pd
import logomaker
import matplotlib.pyplot as plt
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
from tensorflow import keras
from tensorflow.keras import backend as K
import tensorflow.compat.v1.keras.backend as K1
import shap
def saliency(model, X, class_index=... |
# The following source code was originally obtained from:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/util/nest.py
# ==============================================================================
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache Li... |
# -*- coding: utf-8 -*-
from streak_crm_python import *
from keys import TEST_API_KEY
import unittest
import random
import string
import datetime
alphanumeric_range = string.ascii_lowercase + '1234567890'
supposed_endpoint = 'https://www.streak.com/api/v1/'
my_email = '<EMAIL>'
class TestStreakConnection(unittest.... |
# -*- coding: utf-8 -*-
import logging
import os
import re
import platform
import shutil
from jinja2 import Environment, FileSystemLoader
from cekit import tools
from cekit.config import Config
from cekit.descriptor import Env, Image, Label, Module, Overrides, Repository
from cekit.errors import CekitError
from ceki... |
"""
Complex Valued Google Inception From Scratch
Programmed by <NAME>
The Base Code Of Google Inception Has Been Taken From:
https://github.com/aladdinpersson
* MIT Licence
* 2022-02-15 Last Update
"""
import torch
from torch import nn
from complex_neural_net import *
class Complex_GoogLeNet(nn.Module):
... |
#!/usr/bin/env python3
# -*-coding: utf-8-*-
# Author : LiangjunFeng
# Blog : http://my.csdn.net/Liangjun_Feng
# GitHub : https://www.github.com/LiangjunFeng
# File : support_vector_machine.py
# Date : 2017/09/21 11:12
# Version: 0.1
# Description: support_vector_machine
import numpy
import cvxopt
import matplot... |
"""
models
"""
import numpy as np
import torch
import torch.nn as nn
from .config import *
class ImageEncoder(nn.Module):
"""
ImageEncoder
"""
def __init__(self, pretrained_model):
super(ImageEncoder, self).__init__()
self.features = nn.Sequential(*list(pretrained_model.children())[:-1]... |
"""
[LeetCode] 1730. Shortest Path to Get Food
# https://www.cnblogs.com/cnoodle/p/15645191.html
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.
You are given an m x n character matrix, grid, of these different types of cells:
'*' is ... |
##################################### The script for all data-manipulations
import os
import cv2
from constants import *
import shutil
import numpy as np
import math as math
import tensorflow.keras as keras
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
DATA_PATH = os.path.join("..", ... |
from ctypes import sizeof
from typing import *
from copy import copy
import numpy as np
from numpy import ndarray
from . import nodes
from . import tools
from . import dtypes
if TYPE_CHECKING:
from .base import BaseBackwardFunction
def _tensor(data, dtype, requires_grad=False, is_leaf=False):
data = np.array... |
#!/usr/bin/python
import os, sys, time, requests, thread, json
from flask import Flask, request
from threading import Thread
app = Flask(__name__)
ETCD_CMD_TEMPLATE = '/bin/etcd --data-dir /data --name %s --initial-advertise-peer-urls %s:2380 --listen-peer-urls http://0.0.0.0:2380 --listen-client-urls http://0.0.0.0... |
#
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subli... |
import struct
import traceback
from enum import IntEnum
from typing import List
import data
import sys
import fieldop
import numpy as np
from confluent_kafka import Consumer, KafkaError, Producer
from dataclasses import dataclass
import yaml
import datarequest as dreq
import socket
from datetime import datetime, timez... |
import math
import itertools
from datetime import datetime
from dateutil.parser import parse as datetime_parser
from bibchex.strutil import split_at_multiple
# Table shamelessly taken from
# https://stackoverflow.com/a/4580132/4694124
LATEX_ACCENTS = [
[u"à", "\\`a"], # Grave accent
[u"è", "\\`e"],
[u"ì... |
#!/usr/bin/env python3
import sys
if sys.version_info[0] != 3: # pragma: no cover
print("You must use Python 3 to run Seriously!")
exit()
import argparse
from ast import literal_eval
import atexit
import binascii
import collections
import hashlib
import os
import random
import re
import traceback
from . import... |
# Copyright 2018 Google LLC
#
# 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, s... |
import sys
import os
import time
import copy
import shutil
import numpy as np
import torch
import torch.optim as optim
import torch.utils.data as data
import torch.nn.functional as F
from torchvision import models
from models import net_vgg
from models import net_resnet
from dataset import VolumeDataset
# DISCLA... |
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from itertools import product
from typing import Any, Dict, List, Tuple, Type, Union
try:
from functools import cached_property
except:
from backports.cached_property import cached_property
import numpy as np
from s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 4 11:38:44 2020
@author: katsi578
"""
# import modules
import arcpy
import os
from arcpy.sa import*
# general parameters
masterfolder = r"U:\ThirdYear\SURV319\tutorials\Lab3\cities" #arcpy.GetParameterAsText(0)
geodatabase = arcpy.GetParameterAs... |
# Copyright 2019 Google Inc. 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 applicable law or agree... |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import PI, fftfreq
class AbstractFilter(nn.Module):
def __init__(self):
super(AbstractFilter, self).__init__()
def forward(self, x):
input_size = x.shape[2]
projection_size_padded = \
max(64, int... |
from django.http import (
HttpResponse,
HttpResponseBadRequest
)
from django.shortcuts import (
render,
get_object_or_404,
redirect
)
from django.urls import (
reverse,
reverse_lazy
)
from .models import (
SearchQuery,
User
)
from praw.exceptions import InvalidURL
from prawcore.e... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def get_pad(in_, ksize, stride, atrous=1):
out_ = np.ceil(float(in_)/stride)
return int(((out_ - 1) * stride + atrous*(ksize-1) + 1 - in_)/2)
class GatedConv2dWithActivation(nn.Module):
"""
Gated Convlution layer ... |
# -*- coding: utf-8 -*-
# 本檔案為正體中文教學文件,於部署環境使用請再三留意
""" 從 tfrecords 讀取資料,並透過 CNN 'LeNet5' 做訓練 """
###############################################################################
# 使用到的 TensorFlow 函式,若有不懂,請見 '末尾附註'
###############################################################################
im... |
"""
create
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import traceback
from PySide import QtCore, QtGui
from mcedit2.command import SimpleRevisionCommand
from mcedit2.editortools import EditorTool
from mcedit2.handles.boxhandle import BoxHandle
from mcedi... |
# python align.py --camera=nikon --focal_length=21
import argparse
import glob
import tqdm
import os
import os.path as op
import json
import rawpy
import numpy as np
import cv2
from skimage.exposure import match_histograms, equalize_hist
import skimage.filters
import datetime
import time
import copy
import pickle
... |
"""This file contains rules to preprocess files before bundling"""
def _update_links_impl(ctx):
"""Wrapper for the links-update command-line tool"""
dir_name = ctx.label.name
output_files = []
input_js_files = []
output_js_files = []
js_files_args = ctx.actions.args()
js_files_args.set_par... |
import torch
from torch.utils.data import DataLoader, TensorDataset
import tensorflow as tf
from sklearn.model_selection import train_test_split
import math
import unicodedata
import re
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from tqdm import tqdm
import sys
from collections import defaultdic... |
# This test includes unit tests for each element needed to formulate and solve
# the minimum violation planning problem.
# It also includes an integration test of minimum violation planning
# using the example from the EECI 2020 computer lab.
#
# * vectorcost_test(): a unit test for tulip.transys.cost module
# * wks_te... |
import math
import random
import torch
import torch.utils.data
import torchvision
import torchvision.transforms as T
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from augmentor import GeneticAugmentor, NeighborAugmentor, RandomAugmentor
from utils import cache_object
class RandomApply(... |
from kraken.core.maths import Vec3
from kraken.core.maths.xfo import Xfo
from kraken.core.objects.components.base_example_component import BaseExampleComponent
from kraken.core.objects.attributes.attribute_group import AttributeGroup
from kraken.core.objects.attributes.bool_attribute import BoolAttribute
from kraken.... |
"""apollon/aplot.py
General plotting routines.
Licensed under the terms of the BSD-3-Clause license.
Copyright (C) 2019 <NAME>
<EMAIL>
Functions:
fourplot Create a four plot of time a signal.
marginal_distr Plot the marginal distribution of a PoissonHMM.
onsets Plot onsets ov... |
import GoogleDriveSheets as gds
import DataChecks as dc
from io import BytesIO
import pandas as pd
import numpy as np
import os
def getAllFileIDs(handler):
"""
Gets all file IDs from the Google Drive folders (raw, clean, byHand)
returns: cleaned{"byHand":{{id:name}, {id:name}, ...}, "fromInst":... |
### IMPORTS
import requests
import json
import config
from datetime import date
import datetime
import os
import sys
from prettytable import PrettyTable
########################################
##### HELPER FUNCTIONS
########################################
def construct_project_data(projects, temp, proj_data):
p... |
from enum import IntEnum
class CTL0(IntEnum):
CKDIV = 0x3 << 8 # Clock division
ARSE = 0x1 << 7 # Auto-reload shadow enable
CAM = 0x3 << 5 # Counter aligns mode selection
DIR = 0x1 << 4 # Direction
SPM = 0x1 << 3 # Single pulse mode
UPS = 0x1 << 2 # Update source
UPDIS... |
import socket, json, re, os
from contextlib import suppress
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ
from functools import wraps
from collections import namedtuple, deque
from itertools import count
URL = namedtuple('URL', ['host', 'port', 'resource'])
# Fetcher class, unregister decorator an... |
"""Discord bot
- executes CLI commands and responds to chat commands
- monitors actity and sends messages to be written on Mumble
- displays messages coming from Mumble bot."""
import asyncio
import concurrent.futures
import discord
from discomblebot import confbot
from discomblebot import commonbot
from discom... |
def path_hack():
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
# print('path added:', sys.path[0])
path_hack()
import urllib.request
from urllib.request import url... |
"""
Foundation components for commands.
"""
import collections
import functools
import itertools
import shellish
from xml.dom import minidom
def toxml(data, root_tag='ecmcli'):
""" Convert python container tree to xml. """
dom = minidom.getDOMImplementation()
document = dom.createDocument(None, root_tag,... |
import pandas as pd
import numpy as np
import datetime
from bokeh.plotting import figure, show, gmap
from bokeh.models import CategoricalColorMapper, ColumnDataSource
from bokeh.models import CheckboxGroup, HoverTool, GMapOptions, Title
from bokeh.models import Legend, CDSView, FactorRange, GroupFilter
from bokeh.layo... |
import os,re
from waflib import Task,Errors,Node,TaskGen,Configure,Node
def configure(conf):
conf.load('brick_general')
"""This function gets called by waf upon loading of this module in a configure method"""
if not conf.env.BRICK_LOGFILES:
conf.env.BRICK_LOGFILES = './logfiles'
conf.env['PLANAHEAD'] = 'planAhe... |
""" learning_module.py
Python module for training and testing models
Developed as part of DeepThinking project
November 2020
"""
import sys
from dataclasses import dataclass
import torch
# Ignore statemenst for pylint:
# Too many branches (R0912), Too many statements (R0915), No member (E1101),
# ... |
# Copyright 2014 OpenStack Foundation
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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/LICENS... |
import numpy as np
import matplotlib.pyplot as plt
import time
from pystorm.hal import HAL
HAL = HAL()
from pystorm.hal.neuromorph import graph # to describe HAL/neuromorph network
from pystorm.PyDriver import bddriver as bd # expose Driver functions directly for debug (cool!)
np.random.seed(0)
###################... |
# coding: utf-8
"""
Australia AQI
Source: https://www.legislation.gov.au/Details/F2016C00215
https://www.environment.nsw.gov.au/topics/air/understanding-air-quality-data/air-quality-index
"""
from aqipy.utils import AQI_NOT_AVAILABLE, __get_aqi_texts, __round_down, __get_aqi_level
AU_AQI = ((0, 3... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import json
import os
import traceback
from datetime import datetime
from settings import Settings
from spark import Spark
import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.options import define, options, parse_command_li... |
import json, smooch, os, requests
from smooch.rest import ApiException
from pprint import pprint
origin_string = "smoochBYOC-sample"
def userMessage(event, context):
#print(locals()) # dev
#print("Headers: %s" % event['headers']) # dev
#print(... |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""The openclean engine maintains a collection of datasets. Each dataset is
identified by a unique name. D... |
""" functinos for new stuff like non-thermal and prompyt dissoc.
"""
import numpy
import automol
import mess_io
import mechanalyzer
from mechlib.amech_io import reader
def set_prod_density_param(rgts, pesgrp_num, pes_param_dct):
""" Figure out if densities should be calculated
"""
if pes_param_dct is not... |
#!/usr/bin/env python3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
from itertools import chain
import json
import sys
import pdl_cxx
def write_header(output):
output.write(
... |
import os
import requests
from urllib.request import urlretrieve, urlopen
from bs4 import BeautifulSoup
import pickle
import json
import re
from pprint import pprint
COOKIE_FILE = '/usr/local/info/ssruoz_rf.dat'
login_page = "https://readfree.me/auth/login/?next=/"
class Readfree:
def __init__(self, account_json=... |
import ast
from supervisor import gitlab, mattermost
from supervisor import config
from supervisor import condor, git
from supervisor.ini import RunConfiguration
import os, glob, datetime
import otter
server = gitlab.gitlab.Gitlab('https://git.ligo.org', private_token=config.get("gitlab", "token"))
repository = ser... |
#from yodel.errors import YodelError
from asyncio.exceptions import CancelledError
from json.decoder import JSONDecodeError
from types import FunctionType, LambdaType
from typing import Any, Callable, NoReturn, Dict
from websockets import exceptions
from websockets.exceptions import WebSocketException
from websockets.s... |
from typing import Tuple
import time
import traceback
import random
from termcolor import colored
from tqdm import tqdm
import numpy as np
import tvm
import tvm.testing
from tvm import tir
from . import report, error, seed, oracle
from .config import Config
from .pass_fuzz.pass_mutator import SimplePassMutator
from .... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
__author__ = '<NAME>'
__contact__ = '<EMAIL>'
__copyright__ = '(c) <NAME> 2016'
__license__ = 'MIT'
__date__ = 'Fri Jul 29 08:46:22 2016'
__version__ = '1.0'
__status__ = "initial release"
__url... |
import ipywidgets as widgets
import numpy as np
import plotly.graph_objects as go
import pynwb
import trimesh
from .base import df_to_hover_text
def make_cylinder_mesh(
radius, height, sections=32, position=(0, 0, 0), direction=(1, 0, 0), **kwargs
):
new_normal = direction / np.linalg.norm(direction)
cos... |
# %% [code]
import os
os.system('pip install -q efficientnet --quiet')
os.system('pip install -q image-classifiers --quiet')
from classification_models.tfkeras import Classifiers
import tensorflow as tf
from tensorflow.keras import layers,models
from efficientnet.tfkeras import EfficientNetB0, EfficientNetB3, Efficie... |
#print "and we begin"
from bs4 import BeautifulSoup
from datetime import date, time
import requests
def cleanup(str): #this function cleans up some of the useless html leftovers to characters we can actually use
str = str.replace("&", "&")
str = str.replace(" ", " ")
str = str.replace("–", "-")
str ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.