text stringlengths 3.07k 22.1k |
|---|
from datetime import datetime, timedelta, date
import logging
import sys
from pyspark.sql.functions import percent_rank
from pyspark.sql import Window
import holidays
def get_holidays_dataset(nyear):
""" This methods will give the bank holidays for a specific year
Args:
nyear (int): the year
Ret... |
import df
import tl
import wt
import os
import sys
import codecs
import re
import hashlib
from pathlib import Path
import json
import emoji
import random
import string
from datetime import date
from datetime import datetime
from datetime import timedelta
import time
from rich import print
from rich.pretty import pprint... |
import discord, aiohttp, asyncio
from discord.ext import commands, tasks
from discord.ext.commands import Cog, command
from discord import Embed
from datetime import datetime
import datetime as dt
class Rates2(Cog):
def __init__(self, bot):
self.bot = bot
async def rates(self):
blo... |
#!/usr/bin/env python
# -*- coding = utf-8 -*-
import os
import numpy as np
import pandas as pd
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatch
from deeptoolkit.evaluation import concat_training_logs
# Construct the complete training log.
... |
"""
Basic pipeline
Count kmers (full-length barcode seqs)
Threshold them (use vasilis approach, including pitfalls)
Assign reads to thresholded kmers by Lev or Ham dist
"""
import numpy as np
import sys
from sircel.Split_reads import *
from sircel import IO_utils
from sircel import Plot_utils
from sircel.Sircel_mast... |
from __future__ import print_function
import numpy as np
import networkx as nx
import scipy.sparse as sp
import tensorflow as tf
import dill
from utils.utilities import run_random_walks_n2v
flags = tf.app.flags
FLAGS = flags.FLAGS
np.random.seed(123)
def load_graphs(dataset_str):
"""Load graph snapshots given t... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
import numpy as np
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn.functional as F
from mnist import MNIST
# input 1x784 (28x28) image
INPUT_SIZE = 784
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
def calc_accuracy(model, loader):
model.eval(... |
from datetime import timedelta
import logging
import os
import re
import time
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.utils.crypto import get_random_string
from django.utils.timezone import now
from django.utils.translation import gettext_lazy as _
impo... |
from PyQt5.QtCore import QObject
import datetime
import numpy as np
from queue import Empty
import pandas as pd
import json
class Accumulator:
"""Abstract class for accumulating streams of data.
It is use to save or plot in real time data from stimulus logs or
behaviour tracking. Data is stored in a list... |
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Place all public programs into their own context.
Create Date: 2013-12-06 00:20:15.108809
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-nam... |
"""
################################################################################
PyDemos.pyw
Programming Python, 2nd, 3rd, and 4th Editions (PP4E), 2001--2006--2010
Version 2.1 (4E), April '10: updated to run under Python 3.X, and spawn
local web servers for web demos only on first demo button selection.
Version ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from abc import ABC
from dataclasses import dataclass
from pants.backend.docker.package_types import BuiltDockerImage
from pants.backend... |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from paddle import fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.initializer import Normal
from paddle.fluid.regularizer import L2Decay
__all__ = ['AnchorGenerator', 'RPN... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 4 16:33:46 2017
@author: nberliner
"""
import numpy as np
import pandas as pd
from data.data import load_submissions, load_nest_counts
#from features.features import add_features
from utils.utils import get_ts_steps
### Fit the model
def fit_model(df_train, model, v... |
import logging
import math
from datetime import datetime, timedelta
from schemareader import Schema, SchemaReader
from pbreader import ProtobufReader, RawReader, unixtime
import geo
# Top level object. original ObfInfo, proto OsmAndStructure. Loader ObfReader_P::readInfo
class Map:
def __init__(self):
self... |
# import argparse
import json
import os
import random
from datetime import datetime
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import... |
# =============================================================================
# IMPORTS
# =============================================================================
import hou
import inspect
import exceptions
import os
import datetime
from shutil import copyfile
from LaidlawFX import log
from LaidlawFX impo... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, transaction
from django.contrib.postgres.fields import Array... |
import os
from flask import Flask,redirect,render_template,request
import urllib
import datetime
import json
import ibm_db
import geocoder
import geopy.distance
from config import *
import time
import pandas as pd
app = Flask(__name__)
if 'VCAP_SERVICES' in os.environ:
db2info = json.loads(os.environ['VCAP_SERVIC... |
#!/usr/bin/env python
# coding: utf-8
# In[31]:
import glob
import random
import time
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import tensorflow as tf
from music21 import chord, converter, instrument, note, stream
sns.set()
# In[2]:
def get_notes():
notes = []
for file ... |
from __future__ import unicode_literals
import calendar
import datetime
import os
import struct
import sys
import time
import uuid
__all__ = [
'encode_ulid_base32',
'decode_ulid_base32',
'get_ulid_time',
'generate_binary_ulid',
'generate_ulid_as_uuid',
'generate_ulid_as_base32',
'ulid_to_b... |
from __future__ import annotations
import collections.abc as abstract_collections
import contextlib
from collections import defaultdict, deque
from collections.abc import Callable as CallableBase
from itertools import chain, islice
from typing import Any, Sequence, TypeVar, Union
from records.fillers.builtin_fillers.... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure.core.pipeline.policies import SansIOHTTPPolicy
from azure.identity import UsernamePasswordCredential
from azure.identity._internal.user_agent import USER_AGEN... |
"""Module providing functions to load and save logs from the *CARWatch* app."""
import json
import re
import warnings
import zipfile
from pathlib import Path
from typing import Dict, Optional, Sequence, Union
import pandas as pd
from tqdm.auto import tqdm
from biopsykit.carwatch_logs import LogData
from biopsykit.uti... |
#!/usr/bin/python3
## @file build_image_tuxml.py
# @author <NAME>
# @copyright Apache License 2.0
# @brief Script use to simplified creation and uses of Docker images.
# @details This script id design to help members of the TuxML project to easily
# use Docker, without any knowledge require other than what a Docker im... |
import numpy as np
from fenics import *
from fenics_adjoint import *
import math as m
class interpolant(UserExpression):
def __init__(self, bbox, values, **kwargs):
super().__init__()
self.bbox = bbox
self.values = values
self.nx = int(values.shape[0])
self.ny = int(values.shape[1])
self.dx... |
# Task 3
import random
import src.conditional_probability_estimation as prob_estimate
from collections import OrderedDict as odict
from itertools import product
# Recursively find child nodes such that nodes first in the ordering have no more unvisited children.
def topologicalSortRec(G, v, ordering, visited):
v... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from numpy import gradient, shape, asarray, meshgrid, arange, ones_like, zeros, compress
from numpy import sum as asum
from numpy.linalg import norm
try:
from matplotlib.pyplot import quiver
matplotlib_flag = True
except ImportError:
matplotlib_flag = False
from warnin... |
from __future__ import absolute_import
from builtins import str
from builtins import range
import itertools
import tensorflow as tf
from collections import OrderedDict
import deep_architect.helpers.tensorflow_eager_support as htfe
import deep_architect.modules as mo
import deep_architect.contrib.misc.search_spaces.te... |
import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_c... |
# Copyright 2019 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
TokenExchangeAuthenticator - a custom GenericOAuthenticator extension.
"""
import json
import time
from urllib import request, parse
from urllib.error import HTTPError
import jwt
from jupyterhub.handlers import BaseHandler
from jwt.algorithms import RSAAlgorithm
from oauthenticator.generic import GenericOAuthentic... |
import time
from typing import List, Optional
import pytest
import pythonbible as bible
from pythonbible.formatter import BookTitles
def test_format_scripture_references(
normalized_references_complex: List[bible.NormalizedReference],
formatted_reference: str,
) -> None:
# Given a list of normalized ref... |
import numpy as np
import pyro
import pyro.distributions as dist
import torch
from pyro.ops.stats import quantile
import forecast
import pyro_model.helper
def gumbel_softmax(logits, dim=-1, temperature=0.1, eps=1e-9):
# get gumbel noise
noise = torch.rand(logits.size(), dtype=logits.dtype, device=logits.devi... |
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
fr... |
import logging
from datagateway_api.src.common.config import config
from datagateway_api.src.common.exceptions import FilterError
from datagateway_api.src.common.filters import (
DistinctFieldFilter,
IncludeFilter,
LimitFilter,
OrderFilter,
SkipFilter,
WhereFilter,
)
from datagateway_api.src.co... |
'''
Integration Test Suite for Backend Client API Library.
You should be running the API service on http://localhost:8081 to run this test
suite. Of course, the service must be fully configured as follows:
- The gateway server must have at least one agent.
An example sequence to run both manager & agent locally... |
# Time: O(nlogn)
# Space: O(n)
# 850
# We are given a list of (axis-aligned) rectangles.
# Each rectangle[i] = [x1, y1, x2, y2] ,
# where (x1, y1) are the coordinates of the bottom-left corner,
# and (x2, y2) are the coordinates of the top-right corner of
# the ith rectangle.
#
# Find the total area covered by all re... |
from enum import Enum
from queue import PriorityQueue
import numpy as np
from itertools import cycle
def getOrigin(filename):
"""
returns a tuple of lat0 and lon0)
"""
with open("data/colliders.csv") as f:
data0 = f.readline()
data0 = data0[0:-2]
data0 = data0.split(', ')
lat0 = ... |
import re
import sys
import json
import torch
import logging
import argparse
import mysql.connector
from dialogparser import get_intents
from connector import request_db
from deanonymization import anonymization
from telegram import Update
from telegram.ext import (
Updater, CommandHandler, MessageHandler, Filters,... |
# Copyright 2022 Tiernan8r
#
# 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, so... |
# MIT License
#
# Copyright (c) 2016 <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 use, copy, modify, merge, pub... |
import os.path as osp
import pickle
from tqdm import tqdm
from PIL import Image
from typing import Any, Callable, Optional, Tuple, List
from torch import Tensor, nn
import numpy as np
import cv2
import torch
import torchvision.transforms as T
import albumentations as A
from torchvision.datasets import CIFAR1... |
"""
Session context for commands. This provides singular state mgmt for a tree
of commands as well as the implementation for interactive mode.
"""
import ast
import configparser
import contextlib
import os.path
import pdb
import readline
import shutil
import sys
import traceback
from . import eventing, rendering
de... |
from Tkinter import *
import tkMessageBox
global_window_background_colour = '#880000'
class variable_displayer_maker:
def __init__(self, text_file, mode = 'normal', close_command = "close"):
self.window_initializations()
self.line_number = 0
self.close_command = close_command
self... |
import logging
import h5py as h5
import numpy as np
import dfcs_vipa
log = logging.getLogger(__name__)
# * Collect arrays and comb teeth intensities
def collect_h5(path, path_dc):
"""Return all data from HDF5 DC measurements.
Subtracts dark current from the signal measurements.
Args:
- path, path_d... |
# import file_helper
from fnmatch import fnmatch
from typing import AnyStr
import io
import shutil
import cv2
import os
import shapely.wkt
import numpy as np
# import file_helper
def delete_dir(path_to_dir):
shutil.rmtree(path_to_dir)
def create_dir(dir_name, parents=True, exist_ok=True):
from pathlib ... |
import re
from flair.models import FlairType
"""A set of functions for turning strings to recognised flair emoji"""
def colon_emoji_strip(string):
"""Takes string and removes ALL :emoji: from the front in ':' text ':' format."""
if string is None:
return '' # If empty or None return empty string
... |
# -*- coding: utf-8 -*-
"""
Adapted by:
<NAME>, <NAME> and <NAME>
part of GNC subteam, group 1, GDP AVDC 2020-2021
email:
<EMAIL>
<EMAIL>
<EMAIL>
Based on a code by:
author: <NAME>
email: <EMAIL>
github: https://github.com/bobzwik/Quadcopter_SimCon
license: MIT
Please feel free to use and modify this, but keep the a... |
import tensorflow as tf
import pathlib
import cv2
import numpy as np
import os
import math
from tensorflow.python.tools import freeze_graph
from tensorflow.python.tools import optimize_for_inference_lib
from tensorflow.tools.graph_transforms import TransformGraph
import ESPCN
import utils
def training(ARGS):
""... |
import altair as alt
import pandas as pd
from sys import argv
correlationfile = pd.read_csv(argv[1])
coordinates = pd.read_csv(argv[2])
f_reference = pd.read_csv(argv[5], keep_default_na=False)
bonferroni_cutoff = argv[3]
coordinates = coordinates[['code', 'x', 'y']]
df = correlationfile.set_index('code').join(coordin... |
import json
import uuid
from updater.broker.exceptions import TransactionTypeException
def get_asset_type_from_broker_type(broker_asset_type: str) -> str | None:
broker_asset_types_map = {
'Bond': 'bond',
'Stock': 'stock',
'Etf': 'etf',
'Currency': 'currency'
}
if broker_as... |
"""
@license: MIT
@repository: https://github.com/artineering-io/maya-anim-coop
@summary: Sets animation environment according to user preferences
@run: import animEnvironment.py
animEnvironment.set_hotkeys('default')
|| animEnvironment.set_hotkeys('alt')
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 8 21:56:19 2020
@author: naraysa & akshitac8
"""
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import model as model
import uti... |
# pylint:disable-msg=E0611,I1101
"""
All functions related to XML generation, processing and validation.
"""
## This file is available from https://github.com/adbar/trafilatura
## under GNU GPL v3 license
import json
import logging
import pickle
from io import StringIO
from lxml import etree
import pkg_resources
f... |
#!/usr/bin/env python
import argparse
import datetime
import fnmatch
import logging
import logging.handlers
import multiprocessing
import os
import pwd
import random
import shutil
import subprocess
import sys
import tarfile
import time
import yaml
from glob import glob
from multiprocessing import Pool, TimeoutError
f... |
import boto3
import logging
import os
import json
from huit_public_compliance_utils import get_handles
from huit_public_compliance_remediate import remediate_and_notify
from huit_public_compliance_utils import const_resource_type_ec2
from huit_public_compliance_utils import const_resource_type_rds
from huit_public_co... |
"""
TONAS Loader
.. admonition:: Dataset Info
:class: dropdown
This dataset contains a music collection of 72 sung excerpts representative of three a cappella singing styles
(Deblas, and two variants of Martinete). It has been developed within the COFLA research project context.
The distribution is as... |
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from typing import Any, Callable, Dict, Union, List
from functools import wraps
import os
import boto3
import re
import json
from datetime import date, datetime
import uuid
from .storage import AuthorS3Storage
from .publish import StoryPublishe... |
import numpy as np
import pytest
from lumicks.pylake import File
from lumicks.pylake.fdcurve import FdCurve
from lumicks.pylake.channel import Slice, TimeSeries
def make_mock_fd(force, distance, start=0, file=None):
"""Mock FD curve which is not attached to an actual file, timestamps start at `start`"""
asse... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 - <NAME>
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... |
import asyncio
from unittest import mock
import asynctest
import pytest
from aioredis_cluster.pooler import Pooler
from aioredis_cluster.structs import Address
def create_pool_mock():
mocked = mock.NonCallableMock()
mocked.closed = False
mocked.wait_closed = asynctest.CoroutineMock()
return mocked
... |
"""Import geologic units for Hawaii"""
import csv
import locale
import json
import os
import re
import time
from datetime import date
import fiona
import util
work_path = util.make_work_dir(os.path.realpath(__file__))
os.chdir(work_path)
# NAD83 / UTM zone 4N, EPSG:26904
SRS = "+proj=utm +zone=4 +datum=NAD83 +units=m ... |
# -*- coding: utf-8 -*-
# Copyright 2019, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Advanced Clifford operations needed for randomized benchmarking
"""
import numpy as np
import qiskit
from . import Clif... |
#!/usr/bin/env python3
##############################################################################
# EVOLIFE http://evolife.telecom-paris.fr <NAME> #
# Telecom Paris 2021 www.dessalles.fr #
# ------------------------------------------------------------------------... |
import json
from collections import OrderedDict
from urllib.parse import urlencode
from antlr4 import IllegalStateException
from snovault import TYPES
from pyramid.httpexceptions import HTTPBadRequest
from lucenequery import dialects
from lucenequery.prefixfields import prefixfields
default_filter_exclusion = [
't... |
#!/usr/bin/env python3
from bottle import Bottle, request, response, static_file, run, abort
import bottle_mysql
import csv
import os
import sys
from datetime import datetime
import csv
from zipfile import ZipFile, ZIP_DEFLATED
import time
import json
import pandas as pd
from gevent.pywsgi import WSGIServer
from geve... |
print(f'Loading {__file__}...')
import sys
from ophyd.areadetector import (AreaDetector, ImagePlugin,
TIFFPlugin, StatsPlugin,
ROIPlugin, TransformPlugin,
OverlayPlugin, ProcessPlugin)
from ophyd.areadetector.filestore_mix... |
import tensorflow as tf
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from images import read_image_data
from images import get_image_file_paths_from
from images import apply_edge_detection
from images import resize_and_normalize
from tensorflow.keras import layers, models
import random
import os.... |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
#!/usr/bin/env python3
import sys
import os
import shutil
import cv2
from ament_index_python import get_package_share_directory
import yaml
import numpy as np
from transforms3d.euler import euler2mat, mat2euler
from subprocess import check_output, run
from copy import deepcopy
import xacro
from urdf_parser_py.urdf imp... |
# Copyright (c) 2016-2020, University of Idaho
# All rights reserved.
#
# <NAME> (<EMAIL>)
#
# The project described was supported by NSF award number IIA-1301792
# from the NSF Idaho EPSCoR Program and by the National Science Foundation.
import os
from os.path import join as _join
from os.path import exists as _exis... |
from MinesweeperKB import KnowledgeBase, Predicate
from MinesweeperGame import MinesweeperGame
from copy import deepcopy
import random
from enum import Enum
import queue
class GameType(Enum):
human = 1
cpu = 2
none = 3
pass
class MineSweeperAgent:
def __init__(self):
self.game_type = Game... |
from __future__ import division
from Tkinter import *
from pyo import *
from generalDicts import *
import os
import threading
import time
from changeFunctions import *
# Contains framework for recording, playing, and pausing loops.
def convertBPMToTime(data):
secondsPerBeat = 60/data.BPM
return secondsPerBe... |
from collections import defaultdict
from typing import Any, Iterable, Dict, List, Tuple, Union
from numpy import ndenumerate, ndarray
from py4j.java_collections import JavaList
from py4j.java_gateway import java_import, JavaObject
from keanu.algorithm._proposal_distribution import ProposalDistribution
from keanu.cont... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
json IO utility module.
useful method:
- :func:`load`
- :func:`dump`
- :func:`safe_dump`
- :func:`pprint`
"""
from __future__ import print_function, unicode_literals
import time
import os
import shutil
from json import encoder
try:
from bson import json_util a... |
import pickle
import hashlib
import datetime
import logging
from django.db import models
from django.db.models import Q
from django.db.models import Max, Min
from django_pgjson.fields import JsonField
from core.utilities import check_domain_valid, get_base_domain
from pivoteer.records import RecordType, RecordSource
L... |
import numpy as np
import pyro
import pyro.distributions as dist
import torch
import transforms3d as tf3d
from generation.ArticulatedObjs import ArticulatedObject
from generation.utils import sample_quat, sample_pose, make_string, make_single_string, make_quat_string, get_cam_relative_params2, angle_to_quat, get_cam_p... |
import argparse
import csv
import os
import subprocess
import sys
import ray
import traceback
from collections import namedtuple
from itertools import groupby
import pygments
import whatthepatch
from lexer import build_lexer
from more_itertools import consecutive_groups
from utils import is_a_code_line, contains_a_com... |
# multi.py
# <NAME>
# June 10, 2017
# python3
"""
Code for multiple contests & multiple jurisdictions.
"""
import random
random.seed(1) # for reproducibility
##############################################################################
## Gamma distribution
######################################################... |
"""models.py
Implemented models:
1. MobileNetV2 ('mobilenet_v2')
2. ResNet50 ('resnet50')
3. GoogLeNetBN ('googlenet_bn')
4. InceptionV2 ('inception_v2')
5. EfficientNetB0_224x224 ('efficientnet_b0')
6. EfficientNetB1_224x224 ('efficientnet_b1')
7. EfficientNetB4_224x224 ('efficientnet_b4')... |
"""Helper functions to make data handling and conversions easier
# Figures 0.3.13 - Defining scope of this module
The purpose of this module is to provide conveniece methods around commonly
executed statements. These convenience methods should serve as shorthand for
code we would repeatedly execute which don't yet ha... |
import logging
import urllib.request
import random
from PIL import Image, UnidentifiedImageError
import math
import requests
import typing as t
import discord
import discord.ext.commands as commands
from bot.consts import Colors
import bot.extensions as ext
log = logging.getLogger(__name__)
ASCIIYDOTS = 4
ASCIIXDOTS ... |
# Copyright 2020 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, ... |
from .scorers import Scorer
from .clusteringactions import RelabelNode, Aggregate, Flatten
import networkx as nx
import itertools as it
from collections import defaultdict
from copy import deepcopy
import numpy as np
def euclidean_distance(x_vb, x_vv, x_v, x_b, N):
return (x_vv + x_b - 2 * x_vb) ** 0.5
# Assumi... |
# Copyright (c) 2020 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... |
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QFrame, QLabel, QGridLayout, QGroupBox, QDoubleSpinBox, QComboBox, QScrollArea, QWidget, QSizePolicy
from EGGS_labrad.clients.Widgets import TextChangingButton, Lockswitch
SHELL_FONT = 'MS Shell Dlg 2'
LABEL_FONT = QFont(SHELL_FONT,... |
# -*- coding: utf-8 -*-
# !/usr/bin/python
from .calculator import Calculator
from scipy.stats import norm
from ..util import convert_dataset, eval_pdf
import numpy as np
class AsymptoticCalculator(Calculator):
"""
Class for for asymptotic calculators. Can be used only with one parameter
of interest.
... |
"""Module that generates report graphs."""
from bokeh.plotting import figure
from bokeh.embed import components
from bokeh.models import DatetimeTickFormatter, NumeralTickFormatter
from bokeh.palettes import Category20, Category20b, Category10
from flask import session
from flask_login import current_user
from .databas... |
#!/usr/bin/env python
"""
Read in setting values from ini file and then run s3 sync between local folder
and specified S3 bucket. Send results to local logfile & notify slack channel.
Use:
python s3_sync.py -i <settings_file.ini>
"""
import argparse
import os
import re
import subprocess
import sys
from configparser... |
import cv2
import numpy as np
from ipcv.motion_tracking.histogram_based_motion_tracking.grid_window import Window
## Helper functions
def is_num(s):
# Attempts to cast the input to a float. If an exception occurs, it can be
# safely assumed that the input is not a datatype that is conventionally
... |
import numpy as np
# Conditional import machinery for vtk
from dipy.utils.optpkg import optional_package
# Allow import, but disable doctests if we don't have vtk
vtk, have_vtk, setup_module = optional_package('vtk')
cm, have_matplotlib, _ = optional_package('matplotlib.cm')
if have_matplotlib:
get_cmap = cm.get... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016 Mag. <NAME> All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. <EMAIL>
# #*** <License> ************************************************************#
# This module is part of the package GTW.OMP.PAP.
#
# This module is licensed under the terms of the BSD 3-Clause... |
import numpy as np
from itertools import product
from sklearn.model_selection import train_test_split
def get_mask(pairs, shape, row_g2i, col_g2i, sym=True):
'''
Convert a list of pairs, into a boolean indicator matrix, m, where
(a,b) in pairs, is indexed into m[ai, bj] and m[bi, aj] where possible.
... |
from typing import Any, Callable, Dict, Iterable, List, Optional, Set
import pyarrow as pa
from fugue.column.expressions import (
ColumnExpr,
_BinaryOpExpr,
_FuncExpr,
_LiteralColumnExpr,
_NamedColumnExpr,
_UnaryOpExpr,
col,
lit,
)
from fugue.column.functions import is_agg
from fugue.ex... |
# NOQA
import random
import asyncio
from datetime import datetime, date
import requests
from discord.ext import commands
ORDMAX = date(2100, 12, 31).toordinal()
ORDMIN = date(0, 1, 1).toordinal()
class General:
"""Commands that don't fit anywhere else."""
def __init__(self, bot):
"""Cog constructor."... |
#!/usr/bin/env python
# Parameter Vector Generator
# <NAME> 2017-10-25
#
# Run like:
# parvec tst.yml -o tst.out
# OR
# cat tst.yml | parvec - > tst.out
#
# Dollars in name are substituted with *init* lists/ranges.
# Value is chosen randomly from the *last* list/range.
# Format dict may be at any location.
#
... |
"""
American Gut ENA data extraction.
Copyright (C) 2014 PersonalGenomes.org
This software is shared under the "MIT License" license (aka "Expat License"),
see LICENSE.TXT for full license text.
"""
import json
import logging
import os
import re
import shutil
import arrow
from bs4 import BeautifulSoup
import reques... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Integration tests - Neo4j and mongo-connector"""
import base64
import os
import sys
import time
from py2neo import Graph, authenticate
from pymongo import MongoClient
from gridfs import GridFS
from tests import neo4j_pair
sys.path[0:0] = [""]
from tests.setup_cluster... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.