text stringlengths 3.07k 12.6k |
|---|
# encoding: utf-8
import platform
import os
import sys
import subprocess
import re
import multiprocessing
import glob
class QtCiUtilError(Exception):
"""
Custom Exception for Qt Ci Util.
"""
pass
def common_cmd(env_name, cmd_name):
"""
Get command path based on environment variable name and command name.... |
from pathlib import Path
import os
import pandas as pd
import matplotlib.pyplot as plt
from configuration import config
from configuration.model_config import Model_Config
from util.files_operations import load_pickle
from visuals.visualize import violin_plot, treatment_plot
def analyze_results(res):
pass
#... |
#
# Global configuration
#
# Developer(s): <NAME>
# <NAME>
#
# CK entry to keep client configuration info
CK_CFG_REPO_UOA="local"
CK_CFG_DATA_UOA="cbench"
CK_CFG_MODULE_UID="b34231a3467566f8" # ck info module:cfg
CK_CFG_MODULE_REPO_UOA="befd7892b0d469e9" # CK module UOA for REPO
CR_DEFAULT_SERVER="http... |
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from matplotlib.patches import Circle, Arrow
from math import sin, cos
import math
from random import randint, random, choice
from typing import Dict
import cmath
import sys
from tqdm import tqdm
def compute_term(n, coffi, i):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from abc import ABCMeta, abstractmethod
import numpy
import numpy.random
import matplotlib.pyplot as pyplot
class LinearRegression:
"""
Abstract class for linear regression with regularization.
"""
__metaclass__ = ABC... |
import importlib
import pathlib
import sys
from types import ModuleType
from typing import Any, Dict, Optional, Tuple, List
import click
import yaml
from comeback import config
from comeback import paths
from comeback import plugins
exit = sys.exit
IS_VERBOSE = False
def verbose_echo(msg: str) -> None:
if IS_... |
import time
import torch
from lib.utils import AverageMeter, get_train_labels, accuracy
def NN(net, lemniscate, trainloader, testloader, recompute_memory=0):
net.eval()
net_time = AverageMeter()
cls_time = AverageMeter()
correct = 0.
total = 0
testsize = testloader.dataset.__len__()
tra... |
"""
MIT License
Copyright (c) 2021 proguy914629
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, ... |
from collections import deque
class BinaryTreeNode:
def __init__(self, key) -> None:
self.key = key
self.left = self.right = None
class BinaryTree:
def __init__(self, root: BinaryTreeNode):
self.root = root
def bfs(self, use_iteration=True):
def _bfs_iterative():
... |
# This program is public domain
# Author <NAME>
"""
2-D correlation histograms
Generate 2-D correlation histograms and display them in a figure.
Uses false color plots of density.
"""
__all__ = ['Corr2d']
import numpy as np
from numpy import inf
from matplotlib import cm, colors, image, artist
from matplotlib.font_... |
SIZE_PROPERTIES = [
"scale",
"width",
"length",
"unit_dz",
"period",
"fraction",
"area",
"n_xy",
"nz",
"q",
"indexer"
]
class NanowireSizeCompound:
"""
A size container that combines one or more NanowireSize objects
"""
def __init__(self, **kwargs):
... |
#!/usr/bin/env python3
"""
Combine data from all analyses into a summary table. Input tables are those output
by the other sections of the pipeline
"""
from sys import stdout
import argparse
import pandas as pd
COVID_UNIPROT = ['P0DTD1', 'P0DTC1', 'P0DTC2', 'P0DTC3', 'P0DTC4', 'P0DTC5',
'P0DTC6', 'P0D... |
# -*- coding: utf-8 -*-
import os
import json, codecs
import torch
# Turn counts into IDx
def turn_count_to_idx(l):
final_dict = {}
for i in range(len(l)):
final_dict[l[i][0]] = i + 1
return final_dict
def define_dataset():
with codecs.open("dataset.json", encoding="utf-8") as f:
diva... |
from flask import Flask, request, render_template, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from views.forms import SignUp, SignIn
from flask_bootstrap import Bootstrap
from datetime import datetime
from sqlalchemy_utils import PhoneNumberType
... |
import json
import pkgutil
from ..util import is_int, class_for_name
from abc import ABC, abstractmethod
from json import JSONEncoder, JSONDecodeError
from random import Random
from sys import stderr
class JsonDataObjectEncoder(JSONEncoder):
"""JSON utility class to encode the object from the encode() method"""
... |
# amara3.uxml.xml
#import asyncio
from asyncio import coroutine
import xml.parsers.expat
from xml.sax.saxutils import escape #also quoteattr?
from amara3.uxml import tree
from amara3.uxml.parser import parse, parser, parsefrags, event
class expat_callbacks(object):
def __init__(self, handler, asyncio_based_hand... |
# ============================================================================
# The MIT License
#
# Copyright (c) 2018 Infineon Technologies AG
#
# 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 Sof... |
from .move_selection import get_move_options, batch_eval
from .testing_utilities import create_state
from .training import ProgressBar
from .utilities import lmap, join
from .utilities import Timer
from statistics import mean
from math import sqrt
import numpy as np
import torch
class Draw(Runtime... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import numpy.linalg as la
import h5py
import time
import copy
from random import randint
#Implementation of stochastic gradient descent algorithm
def sigmoid_function(z):
return np.maximum(z,0)
def sigmoid_function_der(z): #need to modify
z... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script to parse Apple Spotlight store database files."""
import argparse
import logging
import sys
from dfdatetime import cocoa_time as dfdatetime_cocoa_time
from dtformats import spotlight_storedb
from dtformats import output_writers
class TableView(object):
"""T... |
from roboschool.scene_abstract import SingleRobotEmptyScene
from roboschool.gym_mujoco_xml_env import RoboschoolMujocoXmlEnv
import gym, gym.spaces, gym.utils, gym.utils.seeding
import numpy as np
import os, sys
class RoboschoolInvertedDoublePendulum(RoboschoolMujocoXmlEnv):
def __init__(self):
RoboschoolM... |
"""
sentry.runner.commands.dsym
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import uuid
import json
import click
import warnings
import threading
from sentry.runner.decorator... |
import pathlib
import textwrap
FILE_BAGS = 'up', 'down', 'common', 'precheck'
class _ResourceData:
def __init__(self):
self.tags = set()
self.always_refresh = False
self.imports = {}
self.const = {}
self.exports = set()
self.mementos = set()
self.depends = ... |
"""
Finding common English words is this program main purpose.
This script will iterate through the user-supplied document (in .txt format only)
and will show 50 most common words sorted by decreasing frequency.
Program's Graphical User Interface (GUI) is made in the Tkinter library
as it is sufficiently robust and wi... |
#!/usr/bin/env python
import numpy as np
import cv2 as cv
# Class of
class symbol():
def __init__(self, name, img):
self.img = img
self.name = name
def orderCorners( corners ):
# Empty rectangle for our results
rect = np.zeros((4,2), dtype = "float32")
# Our convert our su... |
#**********************************************************************
# Copyright 2020 Advanced Micro Devices, 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.o... |
# -*- coding: utf-8 -*-
"""
Littlefinger
Performing calculations on personal financial transactions
Reports:
"""
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from dateutil.parser import parse
import seaborn as sns
import matplotlib.pyplot as plt
from pandas.tseries.offsets impo... |
#!python3
import sys
sys.path.append('../decoder/ubuntu/output/')
sys.path.append('../../connection/network/')
import threading
import time
import numpy as np
import libh264decoder
import signal
from PIL import Image as PImage
import cv2
import opus_decoder
import pyaudio
import robot_connection
import enum
import qu... |
import os
import cv2
import json
import torch
import logging
import detectron2
import numpy as np
from detectron2.structures import ImageList
from detectron2.modeling.poolers import ROIPooler
from sklearn.metrics.pairwise import cosine_similarity
from defrcn.dataloader import build_detection_test_loader
from defrcn.eva... |
import discord
from discord.ext import commands #discord.ext seems to be a different thing entirely from discord
from commands_backend import set_alias, find4tc, get_submissions, get_leaderboard, submit4tc, create_hastebin_link
token = '<KEY>'
ownerId = 482762949958696980
bot = commands.Bot(command_prefix='!', intent... |
#!/usr/bin/python
# Copyright (c) 2017 <NAME>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: external_gateway
short_descriptio... |
import argparse
import logging
import sys
import time
import os
from shutil import copyfile
import numpy as np
import pandas as pd
from keras import models, layers, optimizers, regularizers
from keras.layers import Dense, Dropout
import keras
from sklearn.metrics import confusion_matrix
import seaborn as sns
import m... |
"""
ACME client for Let's Encrypt.
See RFC-8555.
"""
import base64
import hashlib
import math
import json
import time
from typing import Optional, List, Set
import requests
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cr... |
#! /home/znfs/pyenv_pyrobot_python2/bin/python
from pyrobot import Robot
import numpy as np
import time
import math
from pyrobot.utils.util import MoveitObjectHandler
from robot_utils import *
robot = Robot('sawyer', use_base=False, use_camera=False)
def joint_position_control():
robot.arm.go_home()
target_... |
from urllib.parse import parse_qs, quote_plus, urlparse
import sublime
import sublime_plugin
from .base import BaseBlame
from .templates import blame_phantom_css, blame_phantom_html_template
# @todo Make a command to open the latest diff ("CommitDescription") for the current line in a single keystroke.
# @body Curre... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import abc
from dataclasses import dataclass
import math
import torch
from .basedist import ExponentialFamily
from .basedist import ConjugateLikelihood
__all__ = ['NormalFullCovariance', 'NormalFullCovarianceStdParams']
@dataclass(init=False, eq=False, unsafe_hash=True)
class NormalFullCovarianceStdParams(torch.nn.... |
import xenaPython as xena
import pandas as pd
GENES = ['FOXM1', 'TP53']
def get_codes(host, dataset, fields, data):
"get codes for enumerations"
codes = xena.field_codes(host, dataset, fields)
codes_idx = dict([(x['name'],
x['code'].split('\t')) for x in codes if x['code'] is not N... |
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
#!/usr/bin/python3
from functools import total_ordering
import os
import re
import shutil
import sys
import tempfile
DIVIDER = 'Tasks Completed'
@total_ordering
class TaskItem(object):
"""A class for tasks that's nestable."""
re_detab = re.compile(r'^\t')
def __init__(self, task, *tasks):
self.t... |
"""The shipper scheduler."""
import contextlib
import json
import multiprocessing
import os
import random
import shutil
import traceback
from abc import ABC, abstractmethod
from typing import List, Optional
from .config import Config
class Job:
"""A representation of an autograding job.
Contains the path ... |
"""
.. currentmodule:: neet.draw
Utilities for drawing Neet objects and graph representations.
"""
import networkx as nx
import pygraphviz # noqa
import tempfile
import os
@nx.utils.open_file(5, 'w+b')
def view_pygraphviz(G, edgelabel=None, prog='dot', args='',
suffix='', path=None, display_imag... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 applic... |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
def get_values(result_names, path_to_file):
data = pd.read_excel(path_to_file)
results = {result: [] for result in result_names}
for col in data.columns:
if col.split("_epoch_")[0] ... |
import torch
from transformers.modeling_bert import BertModel, BertPreTrainedModel
from torch import nn
from itertools import chain
from torch.nn import MSELoss, CrossEntropyLoss
from cleantext import clean
from num2words import num2words
import re
def number_to_words(num):
try:
return num2words(re.sub(","... |
from .products import BncsProduct
import enum
# Event ID constants (EID)
EID_SHOWUSER = 0x01
EID_JOIN = 0x02
EID_LEAVE = 0x03
EID_WHISPER = 0x04
EID_TALK = 0x05
EID_BROADCAST = 0x06
EID_CHANNEL = 0x07
EID_USERFLAGS = 0x09
EID_WHISPERSENT = 0x0A
EID_CHANNELFULL = 0x0D
EID_CHANNELDOESNOTEXIST = 0x0E
EID_CHANNELRESTRIC... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 09:01:47 2019
@author: yoelr
"""
import biosteam as bst
from .other_utils import strtuple
__all__ = ('_add_upstream_neighbors', '_add_downstream_neighbors',
'Thread', 'build_network')
def _add_upstream_neighbors(unit, set):
"""Add upsteam neighboring u... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import argparse
import glob
import numpy as np
import os
import shutil
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from sklearn.model_selection imp... |
import os
import logging
import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, List, Tuple
from core.common.drivers.base import BaseDriverConfiguration
from core.common.drivers.factory import load_config
import core.common.events as events
from cli.utils.files import file_find
import cli.... |
#!/usr/bin/env python3
"""Tiny script to deactivate account on an ACME server."""
import sys
import argparse
import subprocess
import json
import base64
import binascii
import re
import copy
import logging
import requests
LOGGER = logging.getLogger("acme_account_deactivate")
LOGGER.addHandler(logging.StreamHandler())
... |
"""
Prepare data to be used in Weka or LSTM network.
Return: Save a file with data formated
COMPILE WITH: $ python3 generate_arff.py [useFor] [rate] [user] [getText]
[useFor]: Identifies if the dataset will be used with Weka or LSTM
[rate]: Minimum value of engagement rate to consider a tweet as popular
[user]:... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
import os
import requests
from astropy.tests.helper import pytest
from astropy.table import Table
import astropy.coordinates as coord
import astropy.units as u
from ...utils.testing_tools import MockResponse
from ...... |
"""
template.py
Template for simulation class
Function definitions in this file:
- 'run' runs the model.
- 'calc_current' calculates the external current density (A/m2) from user inputs.
- 'setup_steps' Creates two python tuples. One lists the sequence of boundary condition steps, ... |
"""
Agentpy Sampling Module
Content: Sampling functions
"""
# TODO Latin Hypercube
# TODO Random distribution samples
# TODO Store meta-info for later analysis
import itertools
import random
import numpy as np
from SALib.sample import saltelli
from .tools import param_tuples_to_salib, InfoStr, AgentpyError
class R... |
import torch
import os
import numpy as np
from PIL import Image
from torchvision import transforms, datasets
import torch.nn as nn
import torch.nn.functional as F
import PIL
import matplotlib.pyplot as plt
import cv2 as cv2
import math
import pickle
import pandas as pd
import torch
''' #################################... |
#!/usr/bin/env python3
import requests
import sys
import argparse
from lcs import driver
from time import perf_counter as timer
import chunking
import dataset_utility
import fetch
import matplotlib.pyplot as plt
'''
EmThreat is a tool to help web admins notice spikes in phishing activity
for software that they use... |
""" Module containing the implementation of the map generation and storage. """
from abc import ABC, abstractmethod
from enum import Enum
from random import randrange
from itertools import product
from dataclasses import dataclass
from typing import List, Iterable
import random
@dataclass
class Position:
""" Cla... |
from django.db import models
import fnmatch
import os
from socket import gethostname
host = gethostname()
ori = ['LPS','RPI','RAS','LAI','PLI','PRS','ALS','ARI'] #X(>),Y(\/),Z(X).
orien = [str(x).replace('R','right-').replace('L','left-').replace('P','posterior-').replace('A','anterior-').replace('S','superior').repl... |
# ======================================================================
# Copyright CERFACS (October 2018)
# Contributor: <NAME> (<EMAIL>)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/or redistribute ... |
import json
from uuid import UUID
from twisted.internet import defer
from twisted.web import resource, server
class RecursiveResource(resource.Resource, object):
isLeaf = False
def getChild(self, name, request):
if name == '':
child = self
else:
try:
... |
#!/usr/bin/env python
"""
This script can be used to record videos (using a connected camera source) and save them on the system.
Usage:
video_capture.py --duration=DURATION
[--pre_recording_duration=PRE_RECORDING_DURATION]
[--num_videos=NUM_VIDEOS]
[--camera_... |
"""Implements the scientific extension.
https://github.com/stac-extensions/scientific
For a description of Digital Object Identifiers (DOIs), see the DOI Handbook:
https://doi.org/10.1000/182
"""
import copy
from typing import Any, Dict, Generic, List, Optional, Set, TypeVar, Union, cast
from urllib import parse
i... |
from typing import Union, Dict, Any, Tuple, List, Optional
from dataclasses import dataclass
from dataclasses_json import dataclass_json
import numpy as np
import abc
from tqdm import tqdm
from pathlib import Path
import wandb
import torch
import torch.nn as nn
from torch.optim.optimizer import Optimizer
from torch... |
#!/usr/bin/env python
"""
check_frontmatter.py
Author: <NAME>
Date: July 25, 2017
Usage:
python3 check_frontmatter.py [tests]
Implemented tests:
--skip=item1,item2 : Sets files to be skipped
- tags : Checks for valid tags in each post_vars
- feature-key : Checks that 'feature_image' key is set i... |
"""Test log.py"""
from typing import Any
import pandas as pd # type: ignore
import pytest
from leabra7 import events
from leabra7 import log
from leabra7 import specs
# Test log.DataFrameBuffer
def test_dataframebuffer_can_record_observations() -> None:
dfb = log.DataFrameBuffer()
dfb.append(pd.DataFrame({... |
import numpy as np
import utils
from modAL.models import ActiveLearner
from modAL.uncertainty import entropy_sampling
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from multiprocessing import Pool
import multiprocessing as mp
import pickle as pkl
import random
def... |
"""
Library for building and querying a simple SQLite3 database with fits headers.
"""
# Python 2 compatibility
from __future__ import print_function, unicode_literals
try:
input = raw_input
except NameError:
pass
import os
from datetime import datetime
import sqlite3
import astropy.io.fits as fits
__version... |
import sys
import logging
def calc_ticks(image, dz=1, dx=1):
"""
calculate axial and lateral mesh using image dimensions and input values
for axial and lateral sampling intervals
:param image: input image for display
:param dz: axial sampling interval
:param dx: lateral sampling interval
... |
# coding: utf-8
from datetime import datetime
import requests
from bs4 import BeautifulSoup
from entry import EntryManager, Entry
from scrape_details import get_class_text, get_rel_class
from utils import serialize_items, save_json_file, load_json_file
PAGINATE_SUFFIX = "?page="
LIST_PAGES = (
"http://veganistan... |
import requests
import os
import numpy as np
import gmshairfoil2d.__init__
LIB_DIR = os.path.dirname(gmshairfoil2d.__init__.__file__)
database_dir = os.path.join(LIB_DIR, os.path.dirname(LIB_DIR), "database")
def get_all_available_airfoil_names():
"""
Request the airfoil list available at m-selig.ae.illinoi... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 30 14:14:53 2019
@author: <NAME>
"""
import os
import numpy as np
import scipy.sparse as sp
from src.visual_func.visualize import visualize
from src.visual_func.table_image import create_table
from src.config import (
STEPS, LAMBDA_U, LAMBDA_V, FLAG_U, FLAG_V)
from u... |
from gamelib import event, level
from gamelib.util import resources
msges = {}
in_area = False
BEACON_1 = 2
BEACON_2 = 3
BEACON_3 = 109
BOTTOM_EDGE = 89
RIGHT_EDGE = 91
TARGET_IN = [88, 95]
TARGET_OUT = [90, 92, 93, 94] + [96, 97, 98, 99]
BEACON_PLANTED = 94
def enter_area():
global in_area
in_area = True
... |
import collections
import unittest
from aoc_utils.data import data_lines
class TestLandingArea(unittest.TestCase):
def test_starts_empty(self):
landing = WidestLandingArea()
self.assertEqual(0, landing.size())
def test_can_add_targets(self):
landing = WidestLandingArea()
land... |
import os
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Tuple
import numpy as np
import patoolib
from tqdm import tqdm
from common.settings import RESOURCES_DIR
from common.timeseries import Timeseries, TimeseriesBundle, TimeseriesLoader, Hour
from common.utils import d... |
import sys
import traceback
import requests
import json
import pprint
from pydblite import Base
import autoscaler.util as util
from collections import defaultdict
import autoscaler.conf.engine_config as eng
import autoscaler.network.network_util as net_util
import autoscaler.network.qos_rest as rest_qos
import logging
... |
# encoding: utf-8
# Copyright 2012 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
from zope.component import getUtility
from plone.app.viewletmanager.interfaces import IViewletSettingsStorage
from Products.CMFCore.utils import getToolByName
_ipda_theme = u'IPDA Th... |
# Copyright 2017 Google
#
# 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 os
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
from PIL import Image
import random
import torchio as tio
import numpy as np
import nibabel as nib
import torch.nn.functional as nnf
import torch
import matplotlib.pyplot as plt
import SimpleITK as sitk
def s... |
#!/usr/bin/python
from PyQt4.QtCore import * # Qt core
from PyQt4.QtGui import * # Qt GUI interface
from PyQt4.uic import * # ui files realizer
from PyQt4 import QtGui, uic
from HBPSerial import *
from mash import *
from functools import *
from Program import *
from matplotlib.backends import qt_compat
use_pyside... |
import argparse
import random
import cv2
import numpy as np
import pickle
import math
from sklearn import preprocessing
from collections import OrderedDict
class ClassifierANN(object):
def __init__(self, feature_vector_size, label_words):
self.ann = cv2.ml.ANN_MLP_create()
# Number of centroids use... |
# %%
import glob
from typing import List, Tuple
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from netCDF4 import Dataset
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import DBSCAN
from sklearn.metrics import da... |
# Copyright 2017 <NAME>, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# Copyright (c) 2018 NVIDIA Corporation
import argparse
import runpy
import os
import sys
import pandas as pd
sys.path.insert(0, "../")
from milano.exec_utils import ExecutionManager
from milano.backends import AzkabanBackend
def gen_bench_funcs(bench_type):
funcs_dict = {
"bbob": (prepare_bbob, finalize_bbob)... |
# Add Observation(s) for current time
# When an observation is added
# an adjacency is created between previous observation and current
# if current prediction is similar to predictions, adjacencies are created betwen prediction predecessors and current
# when a observation is added all closely similar nodes and nod... |
from typing import List
import hid
import mystic_why.common.const as const
from mystic_why.common.enums import LightArea
from mystic_why.common.exception import DeviceNotFound, AreaNotFound
class Color:
@staticmethod
def create_by_hex(hex_value):
hex_value = hex_value.lstrip('#')
return Colo... |
from eternal.libirc import (
parse_message, parse_received, parse_message_tags, parse_message_params,
parse_message_source, Source, parse_capabilities_ls, get_sasl_plain_payload,
Message, IRCClient, Member, User, parse_supported, parse_chanmodes,
parse_member_prefixes
)
def test_parse_received():
... |
import json
import dataset, sqlalchemy
import telepot
import time, arrow
import exceptions, traceback
import subprocess
import logging, logging.handlers
from urllib2 import urlopen
from commands import _start, _stop, _log, _subs, _yell
from chanapi import Board
def get_msg(msg):
with open('messages/{0}'.format(ms... |
import pyxel
BORDER_OFFSETS = [(-1, 0), (1, 0), (0, -1), (0, 1)]
BG_COLOR = 5
def pset_with_border(image, x, y, col, bcol):
for x_offset, y_offset in BORDER_OFFSETS:
image.pset(x + x_offset, y + y_offset, bcol)
image.pset(x, y, col)
def line_with_border(image, x1, y1, x2, y2, col, bcol):
for x_... |
import h5py
import numpy as np
from pathlib import Path
import warnings
"""
Code to transform the original dataset into a form that has faster data IO.
This is especially important for non-SSD storage.
For most systems, File I/O is the bottleneck for training speed.
"""
def check_chunk_size(data, chunk, file):
... |
"""This module contains a monte carlo example that illustrates the advantages of the grmpy estima-
tion strategy. For this purpose data and the associated parameterization from Cainero 2011 are
used. Additionally the module creates two different figures for the reliability section of the
documentation.
"""
import matpl... |
import copy
import io
import json
import tarfile
import tempfile
from typing import Tuple
from jinja2 import Template
from rest_framework import generics, status
from rest_framework.exceptions import ParseError
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.response import Response
... |
import pandas as pd
from astropy.table import Table
from astropy.coordinates import SkyCoord, Distance
from astropy.time import Time
import astropy.units as u
from astropy.units import dimensionless_angles
import math
class OpenData:
"""Class to open and manipulate data"""
def __init__(self, fpath: str = Non... |
import pytest
from commands.drive_encoder_counts import DriveEncoderCounts
from subsystems.drivetrain import Drivetrain
"""
hal_data['pwm'] looks like this:
[{
'zero_latch': False,
'initialized': False,
'raw_value': 0,
'value': 0,
'period_scale': None,
'type': None
}, {
'zero_latch': True,... |
# -*- coding: utf-8 -*-
# pylint: disable-msg=E1101, E0102, E0202, C0103
"""
Created on Fri Jun 1 10:44:33 2012
This module contains the definition of the base class for all the domain
observables.
@author: <NAME>
"""
from .FreezableObject import FreezableObject
from .constraint_network import Variable
from .interva... |
#!/usr/bin/python3
'''
定义:
+ free block of length i, starting from 0 to (i-1)
+ its corresponding suffix is reprented by lx[i:] (with 1 subtracted)
分析:
+ bits string set can be seperated into several disjoint sets (DS)
+ the number of disjoint sets = number of 1 in bitstring (x+1)
+ one special DS is the one with no pr... |
# (c) Copyright [2015] Hewlett Packard Enterprise Development LP
#
# 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 r... |
"""
The base class for RL Agent for FL server.
"""
import asyncio
import logging
import os
import pickle
import sys
from abc import abstractmethod
import socketio
from plato.config import Config
class RLAgentEvents(socketio.AsyncClientNamespace):
""" A custom namespace for socketio.AsyncServer. """
def __i... |
# Python Module for import Date : 2017-07-09
# vim: set fileencoding=utf-8 ff=unix tw=78 ai syn=python : per Python PEP 0263
'''
_______________| test_boltzmann : Test fecon235 ys_prtf_boltzmann module.
Doctests display at lower precision since equality test becomes fuzzy across
differe... |
"""
Copyright 2015 Rackspace
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
dist... |
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, UpSampling2D,Conv2DTranspose, Concatenate
from tensorflow.keras import Model, regularizers
import csv
import numpy as np
import matplotl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.