text stringlengths 3.07k 12.6k |
|---|
"""Functional tests for `cutty link`."""
from pathlib import Path
import pytest
from cutty.projects.projectconfig import readprojectconfigfile
from cutty.util.git import Repository
from tests.functional.conftest import RunCutty
from tests.functional.conftest import RunCuttyError
from tests.functional.test_update impo... |
import os
os.add_dll_directory(r'C:\Program Files\VideoLAN\VLC')
import vlc
import glob
import time
import telebot
from telebot import *
API_KEY = "Your API KEY"
# globals
season_directory = ''
episode_number = ''
media = ''
bot = telebot.TeleBot(API_KEY, parse_mode=None)
def select_season(message):
... |
"""Alert"""
# pylint: disable=eval-used,bare-except,missing-function-docstring
import time
# import math
import voluptuous as vol # pylint: disable=import-error
APP_NAME = __name__.split('.')[-1]
MESSAGE_CONDITION = vol.Schema(
vol.Any(
{
vol.Optional('condition', default="True"): str,
... |
# Copyright (c) 2020, 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... |
"""
----------------------------------------------------------------------------------------
Copyright (c) 2020 - see AUTHORS file
This file is part of the ARTHuS software.
This program is free software: you can redistribute it and/or modify it under the terms
of the GNU Affero General Public License as published by... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
import logging
import re
import ijson
COMMENT_PATTERN_RE = re.compile(r'^\s*\-\-')
EMPTY_LINE_RE = re.compile(r'^\s*$')
_logger = logging.getLogger(__name__)
def split_statements(buf, remove_com... |
"""Custom BatchNorm operations.
BatchNorm is modified to handle temporal operations. Specifically, activation
statistics of each layer are changing over time, and to account for this we
add a time dimension to BatchNorm"s running mean and std. The operation now
accepts a time argument which must be passed in the forwa... |
import pytest
from django.db import connection
from usaspending_api.broker.helpers.get_business_categories import get_business_categories
from usaspending_api.common.helpers.business_categories_helper import get_business_category_display_names
def test_update_business_type_categories():
business_types = "P"
... |
"""
A module containing different learning rules for use with the SGD training
algorithm.
"""
import numpy as np
from theano import config
from theano import tensor as T
from theano.compat.python2x import OrderedDict
from pylearn2.space import NullSpace
from pylearn2.train_extensions import TrainExtension
from pylear... |
"""
Component that automatically arms the selected track.
"""
from itertools import ifilter
from _Framework.SubjectSlot import subject_slot, subject_slot_group
from _Framework.CompoundComponent import CompoundComponent
from _Framework.ModesComponent import LatchingBehaviour
from _Framework.Util import forward_property... |
"""
Copyright 2018 Lambda Labs. All Rights Reserved.
Licensed under
==========================================================================
"""
from __future__ import print_function
import sys
import time
import os
import matplotlib.pyplot as plt
import tensorflow as tf
class Runner(object):
def __init__(self... |
"""Functions shared by the EML utilities
"""
import argparse
import io
import logging
import os
import pathlib
import pprint
import shutil
import subprocess
import sys
import lxml.etree
block_set = set()
log = logging.getLogger(__name__)
# Max number of unique values we allow for the contents of an element before w... |
from enum import Enum
from itertools import chain
from src.independent.util import indent, todo_once, castid
from src.independent.util_for_str import mapjoin
from src.constants_and_defined_types import *
from src.independent.typing_imports import *
from src.model.Term import Term
T = TypeVar('T')
rule_param_to_ind_c... |
import random
import os
from PIL import Image, ImageDraw
# Funcion para crear una matriz de 5x5 y llenarla de W (Neutrales / Whites)
def create_matrix():
cols = 5
rows = 5
arr = [['W' for i in range(cols)] for j in range(rows)]
return arr
# Funcion auxiliar para representar una matriz
def show_matri... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torch.nn import init
from torch.utils.data import DataLoader, Dataset
class UNetConvBlock(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, acti... |
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(".../../MNIST_data/", one_hot=True)
def batch_gen(data, batch_n):
inds = range(data.shape[0])
np.random.shuffle(inds)
for i in range(data.shape[0] / batch_n):
ii ... |
import json
import os
import zipfile
import sys
from collections import Counter,OrderedDict
def read_zipped_json(filepath, filename):
archive = zipfile.ZipFile(filepath, 'r')
return json.load(archive.open(filename))
def da2triples(dialog_act):
triples = []
for intent, svs in dialog_act.items():
... |
"""
faces/train.py
"""
import os
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint
from keras.models import load_model
import numpy as np
import scipy.misc
from .instance import (
Emotion, RaFDInstances, YaleInstances, JAFFEInstances, NUM_YALE_POSES)
from .model... |
import random
import sys
import copy
random.seed(None)
class Node:
species = None
x = None
y = None
health = None
def __init__(self, spec=None):
if spec is not None:
self.species = spec
else:
self.species = 0
self.x = None
self.y = None
... |
from __future__ import annotations
from typing import IO, Any, Dict, Iterator, List, NamedTuple, Optional, TYPE_CHECKING, Tuple, TypeVar, Union, Iterable
import itertools
import string
import random
import re
from .files import File
from .utils import parse_http_data, CLRF
if TYPE_CHECKING:
from .app import Appl... |
"""
Testing the capabilities of Mango
- Test the domain space transformations
- Test the sampling capabilities
- Test the bayesian learning optimizer iterations
- Test the results of tuner for simple objective function
"""
import math
from mango.domain.domain_space import domain_space
from mango.optimizer.bayesian_lea... |
import yaml
import mlflow
import argparse
import numpy as np
import pandas as pd
from urllib.parse import urlparse
from sklearn.metrics import f1_score,recall_score,accuracy_score,precision_score,confusion_matrix,classification_report
from sklearn.metrics import *
from xgboost import XGBRegressor, XGBClassifier
from sk... |
from csv import DictWriter
from datetime import date
from unittest.mock import Mock
import pandas as pd
from dataactcore.models.domainModels import TAS_COMPONENTS, TASLookup
from dataactvalidator.scripts import loadTas
from tests.unit.dataactcore.factories.domain import TASFactory
def write_then_read_tas(tmpdir, *r... |
# **CHACHA20**
# LIBRARIES
import struct
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np
#-------------------------------------------------------------------------------
# CHACHA20 IMPLEMENTATION
def yield_chacha20_xor_stream(key, iv, position,met... |
from abc import ABCMeta
from core.config import Settings
from core.mixins import MsgMixin
from core import constants as K
from core.providers.aws.boto3.sts import get_aws_caller_identity
from core.providers.aws.boto3.sts import generate_temp_credentials
import uuid
class SystemInput(MsgMixin, metaclass=ABCMeta):
... |
#!/usr/bin/python
# coding=utf-8
from openstack import connection
username = "**********"
password = "**********"
userDomainId = "**********"
auth_url = "**********"
# create connection
conn = connection.Connection(
auth_url=auth_url,
user_domain_id=userDomainId,
domain_id=userDomainId,
username=user... |
from typing import Dict
from unittest.mock import MagicMock as Mock
from unittest.mock import NonCallableMock, call
import pytest
from givenergy_modbus.decoder import GivEnergyDecoder, GivEnergyRequestDecoder, GivEnergyResponseDecoder
class TestDecoder(GivEnergyDecoder):
"""Dummy factory implementation for test... |
from __future__ import division
import pandas as pd
from sklearn.cluster import KMeans
import numpy as np
import glob
import os
import cycifProcessingTools as cpt
def checkClusterOutliers(df,idxHi,idxLo,pRbHiCells, pRbLoCells):
#Handle outliers
#if one cluster ends up with a very small number of cells
... |
import names
import psqlfunctions as psqlf
#extract races with a given name
def exracebyn(races, race):
output = []
for ra in races:
if race == ra['racename']:
output.append(ra)
return(output)
#extract races that can live in a given set size
def exracebys(races, size):
output = []
size = int(size)
for ... |
#don't forget virtual enviornment!!
# py -m pip install --upgrade pip setuptools virtualenv
# py -m virtualenv kivy_venv
# kivy_venv\Scripts\activate
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.widget import Widget
from kivy.lang import ... |
# =================================================================
#
# Authors: <NAME> <<EMAIL>>
#
# Copyright (c) 2021 <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
# res... |
from typing import List
import math
def MAIN(DOY: List[int], TMAX: List[float], TMIN: List[float], SWFAC1: List[float],
SWFAC2: List[float], PD: List[float], EMP1: List[float], EMP2: List[float],
PT: List[float], sla: List[float], di: List[float], N: List[float],
nb: List[float], dN: List[f... |
"""Module containing mostly file operation related utility functions.
.. module:: util
:platform: Linux
:synopsis: Utility functions module.
.. moduleauthor:: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
"""
import os
import re
import shutil
import tempfile
from itertools import islice
from typing import Callable, Itera... |
# 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, ... |
# BSD 3-Clause License
#
# Copyright (c) 2019, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list o... |
# -*- coding: utf-8 -*-
"""Test getting conditional independencies (and related)."""
import unittest
from typing import Iterable, Set, Union
from ananke.graphs import ADMG, SG
from y0.algorithm.conditional_independencies import (
are_d_separated,
get_conditional_independencies,
get_moral_links,
)
from y... |
import magic
from urllib.parse import urlparse
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.forms import ModelForm
from django.utils.timezone import now, timedelta
from .models import Site, Category
from staff.models import Removal
from pubdash.models import SiteChange
class... |
"""Manages database file and has import filters."""
# pylint: disable=logging-format-interpolation
# pylint: disable=global-statement
import os
from pathlib import Path
import re
import sqlite3
import numpy as np
def parse_spectrum_file(fname):
"""Checks file extension and calls appropriate parsing method."""
... |
import numpy as np
import pandas as pd
import os
import datetime as dt
from flask import Flask,render_template,url_for,request,g, flash, redirect
from werkzeug.utils import secure_filename
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import current_user, LoginManager, log... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from compas.geometry import length_vector
__author__ = ['<NAME> <<EMAIL>>']
__copyright__ = 'Copyright 2020, Design Machine Group - University of Washington'
__license__ = 'MIT Lic... |
import os
import hail as hl
from hail.utils.java import Env
from hail.utils.misc import new_temp_file
from hail.vds.combiner import combine_variant_datasets, new_combiner, load_combiner, transform_gvcf
from ..helpers import startTestHailContext, stopTestHailContext, resource, fails_local_backend, fails_service_backen... |
import os
import numpy as np
import json
from PIL import Image
import cv2
import matplotlib.pyplot as plt
def expand_thresh(im, num_pixels):
ret = np.zeros(im.shape)
max_x = im.shape[0]
max_y = im.shape[1]
for i in range(im.shape[0]):
for j in range(im.shape[1]):
# If this pixel is ... |
class MyList:
def meth_print(meth_name, index=None, item=None):
log_message = "log message: called {module}.MyList.{method}".format(module=__name__, method=meth_name)
if index != None:
log_message += ', index = {0}'.format(index)
if item != None:
log_message += ', \ni... |
from collections import namedtuple
import csv
from datetime import datetime
from enum import Enum
from pathlib import Path
import re
from smrt_importer.models import File, Record
class FieldType(Enum):
HEADER = 'HEADR'
CONSUMPTION = 'CONSU'
TRAIL = 'TRAIL'
class Field:
"""Holds information about a ... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import cv2 as cv
import cmath
import matplotlib.pyplot as plt
# We apply a gaussian filter to smooth the image
def gaussian_blur(img):
sigmaX = 1.5
sigmaY = 1.5
ksizeX = 9
ksizeY = 9
return cv.GaussianBlur(img, (ksizeX, ksizeY), sigma... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 1 18:09:27 2021
@author: lukas
"""
import cv2
import dlib
import numpy as np
import timeit
import utils
from queue import Queue
import pathlib
import argparse
import time
def _create_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--descripto... |
from time import time
from platon import Web3
from platon.datastructures import AttributeDict
from platon_aide.module import Module
from platon_aide.utils import contract_transaction
class _ChainVersion(AttributeDict):
integer: int
major: int
minor: int
patch: int
class _BaseProposal(AttributeDict... |
from __future__ import print_function
import argparse
from bloom.git import branch_exists
from bloom.git import checkout
from bloom.git import create_branch
from bloom.git import ensure_clean_working_env
from bloom.git import ensure_git_root
from bloom.git import get_commit_hash
from bloom.git import get_current_bran... |
#!/usr/bin/env python3
__all__ = ['FrameGraph']
import numpy as np
import networkx as nx
import time
import itertools
import logging
import pickle
from typing import List, Dict, Any
from phonebot.core.common.serial import encode, decode
from phonebot.core.common.math.transform import Rotation, Position, Transform
f... |
"""
WHOIS Server Query module written in Python with asyncio support.
Copyright (c) 2020 <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 t... |
import sys
sys.path.append('..')
from common.core import *
from common.gfxutil import *
from kivy.graphics.instructions import InstructionGroup
from kivy.graphics import Color, Rectangle
class GuiKey(InstructionGroup):
'''
Key class, keys are drawn from the top down.
'''
activeColor = (.2,.3,.2,.5)
... |
# coding: utf-8
# # Annotations for the Sirajology Python NN Example
#
# This code comes from a demo NN program from the YouTube video https://youtu.be/h3l4qz76JhQ. The program creates an neural network that simulates the exclusive OR function with two inputs and one output.
#
#
# In[23]:
import numpy as np # Note:... |
#!/usr/bin/env python3
import argparse
from migen import *
from litex.gen.fhdl.utils import get_signals
from litex.build.generic_platform import *
from litex.build.sim import SimPlatform
from litex.build.sim.config import SimConfig
from litex.build.sim.verilator import verilator_build_args, verilator_build_argdict
... |
from decimal import Decimal
_UNDEFINED = object()
class BBSField(object):
def __init__(self, size=None, default=_UNDEFINED):
self.size = size
if default is not _UNDEFINED:
self.default = default
def pack(self, value):
""" Takes the value of a field and returns its binary... |
#!/usr/bin/env pytest-3
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2018, Nokia"
__license__ = "BSD-3"
from pybgl.graphviz import graph_to_html
from pybgl.property_map import make_assoc_property_map
from pybgl.node... |
import os
import sys
import json
from uuid import uuid4
from datetime import datetime
from pathlib import Path
import subprocess as sp
import xml.etree.ElementTree as ET
from flask import Flask, render_template, request, redirect
from flask import url_for, jsonify, flash
from flask_wtf import FlaskForm
from flask_code... |
import datetime
import os
import re
import shutil
import sys
from lki.config import LKIConfig
from lki.error import LKIError
from lki.utils import check_executable, check_file, is_windows, link, run
REGEX_GIT_URLS = (
re.compile(r"^git@([^:]+):(.*?)(.git)?$"),
re.compile(r"^http[s]?://([^/]+)/(.*?)(.git)?$"),... |
from six import PY2
from syn.five import xrange
from syn.types.a import Type, Numeric, Int, hashable, rstr, serialize, \
deserialize, estr, generate, TYPE_REGISTRY, Long, visit, find_ne, \
NotEqual, primitive_form
from syn.types.a import enumerate as enumerate_
from syn.base_utils import is_hashable, collection... |
import numpy as np
from pandas import DataFrame
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import glob
from sklearn.preprocessing import QuantileTransformer
import tensorflow as tf
def gen_dataset2(NUM_DATPOINTS, toLoad=False):
if toLoad:
return np.load("../data/2D_100000d... |
#!/usr/bin/env python
################################################################################
# Blob and blob group classes
################################################################################
import numpy as np
class Blob:
"""Class that defines a 'blob' in an image: the contour of a set of p... |
import sys
dataset = sys.argv[1]
# dataset = "https://apnews.com/article/pandemics-dallas-storms-coronavirus-pandemic-texas-7a04c04d40943e53ee17f7f946d3a7fa"
############################
###### OLD PROCESSING ######
############################
import pandas
import re
import nltk
from nltk.corpus import stopwords
from... |
from django.db.models.manager import Manager
from django.template import Context, Node, Variable
from django.template.loader import get_template
from django.db.models import FileField, URLField
class BaseModelBlockNode (Node):
def __init__(self, thing, resolved=True):
"""
thing -- The thing (probab... |
import requests
from bs4 import BeautifulSoup
from subprocess import call
import subprocess
import os
from functools import partial
from multiprocessing import Pool
import urllib.request
class Scrapper:
"""Scrapper use extractors and actors against web pages.
The Scrapper is an iterator that can be run re... |
import codecs
import logging
import os
import re
from os import path
import chardet
def get_files(
name: str,
file_pattern: str,
try_path: str,
regex_active: bool,
ext: str,
prefix: str,
) -> list[str]:
"""
Returns list of files matching the specified search parameters.
:param na... |
#!/usr/bin/env python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import sys
import dnf
import hawkey
import signal
import os
import json
base = None
def get_sack():
global base
if base is None:
base = dnf.Base()
conf = base.conf
conf.read()
conf.installroot = '/'
... |
#!/usr/bin/env python
"""
Entry point for running all data enrichment commands.
"""
import functools
import os
import pathlib
from typing import Optional
import airtable
import click
import dotenv
import geopandas as gpd
import requests
import shapely.geometry
DATA_DIR = pathlib.Path(__file__).parent / "data"
TRACT... |
import os
import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
import h5py
import pickle
dataset='miccai' #dataset to be used: miccai or mrnet or fastmri
mode='train' #train or test
save_path='/home/Co-VeGAN/'
def load_a(path, num):
f = os.listdir(path)
a = len(f)
data = []
#use i... |
#!/usr/bin/env python
#############################################################################
##
# This file is part of Taurus
##
# http://taurus-scada.org
##
# Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
# Taurus is free software: you can redistribute it and/or modify
# it under the terms of t... |
# Copyright 2021 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, ... |
import sublime_plugin
import sublime
from datetime import datetime as dt
import sys
from .periodicLogSaver import PeriodicLogSaver
import json
import urllib
import platform
import os
# define local variables
file_times_dict = {}
periodic_log_save_timeout = 10
periodic_log_save_on = True
user_id = ""
if platform.syste... |
from __future__ import print_function
import tensorflow as tf
import tensorflow.contrib.slim as slim
import os
import sys
from absl import flags
import numpy as np
npa = np.array
DEFAULT_IMAGE_SHAPE = (1, 299, 299, 1)
class Model(object):
def __init__(self, checkpoint_path, model_name, image=None, num_classes=10... |
import os
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import bson
from bson.json_util import dumps
from bson.objectid import ObjectId
from app.repository.requests.requests_service import RequestService as requestService
from app.repository.requests.requests_schema import Re... |
import time
from channelpy import BasicChannel, Channel, RabbitConnection
from channelpy.chan import checking_events
from channelpy.exceptions import ChannelClosedException, ChannelTimeoutException
import cloudpickle
import rabbitpy
from config import Config
class WorkerChannel(Channel):
"""Channel for communic... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# Details: SiamRPN training script
# Reference: SiamRPN [Li]
# ------------------------------------------------------------------------------
import... |
import chainer
from chainer.datasets import TransformDataset
from chainer.training import extensions
from chainercv import transforms
from chainercv.extensions.evaluator.instance_segmentation_voc_evaluator import InstanceSegmentationVOCEvaluator
from chainerui.utils import save_args
from chainerui.extensions import Com... |
from oculus_reader.FPS_counter import FPSCounter
from oculus_reader.buttons_parser import parse_buttons
import numpy as np
import threading
import time
import os
from ppadb.client import Client as AdbClient
import sys
def eprint(*args, **kwargs):
RED = "\033[1;31m"
sys.stderr.write(RED)
print(*args, file... |
"""Hug app"""
import hug
import mongoengine
from settings import settings
from auth import authenticated, api_key_auth, jwt_auth
from models import Dashboard, Job, Event, ApiKey
mongoengine.connect(host=settings.MONGODB_URI)
api = hug.API(__name__)
api.http.add_middleware(hug.middleware.CORSMiddleware(api, max_age='... |
# [323] https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/
# Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes),
# write a function to find the number of connected components in an undirected graph.
def countComponents(n: int, edges: 'Li... |
"""Generate plot."""
import click
import matplotlib.pyplot as plt
import pandas as pd
import scipy.constants
import seaborn as sns
from constants import CHARTS_DIRECTORY, MELTED_PATH
from pykeen.datasets import dataset_resolver
SIGIL = r"\mathcal{T}_{train}"
def _lookup_key(d):
return dataset_resolver.docdata(d... |
# coding=utf-8
# Copyright 2021 The init2winit Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import json
import sys
import random
import os
import shutil
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
import math
import configparser
from utils_ import *
from l... |
import logging
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.encoding import force_text
from django_otp.models import SideChannelDevice, ThrottlingMixin
from django_otp.util import hex_validator, random_hex
import messagebird
from .conf import settings
logge... |
#!/usr/bin/env python3
# coding: utf-8
__author__ = 'ChenyangGao <https://chenyanggao.github.io/>'
__version__ = (0, 0, 4)
import os, sys
from contextlib import contextmanager
from copy import copy as _copy, deepcopy as _deepcopy
from tempfile import NamedTemporaryFile, TemporaryDirectory
from typing import cast, C... |
import os
import subprocess
import zipfile
from datetime import datetime
import re
import asyncpg
import discord
from discord.ext import commands
from cogs.meta import DOWNLOAD_LINK
def get_prefix(bot, message):
try:
return ['ca.'] + (
[('!', ';')[bot.user.id == 376485072561504257]] if messa... |
from scipy.sparse import diags
import numpy as np
from yaglm.opt.base import Func
from yaglm.opt.utils import safe_data_mat_coef_dot, safe_data_mat_coef_mat_dot
from yaglm.opt.glm_loss.utils import safe_covar_mat_op_norm
# TODO how to handle loss kws
# currently pass them in as a dict but this seems wrong e.g.
# the... |
import gym
import math
import random
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from collections import namedtuple
from itertools import count
from tqdm import trange
from copy import deepcopy
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
# from PIL import Image
import torch
import torc... |
"""
Lab 4
"""
import re
from ngrams.ngram_trie import NGramTrie
def tokenize_by_sentence(text: str) -> tuple:
if not isinstance(text, str):
raise ValueError
if not text:
return ()
tokens = []
sentences = re.split(r'[.!?]', text)
for sentence in sentences:
splited_sent = ... |
"""
PostgreSQL accounts and databases for members and societies.
"""
from functools import wraps
from typing import Optional, List, Set, Tuple, Union
from psycopg2.extensions import connection as Connection, cursor as Cursor
from srcf.database import Member, Society
from srcf.database.queries import get_member, get_... |
import numpy as np
import pandas as pd
from typing import List
import functools
from tqdm import tqdm
class Equation():
"""
An Equation is a wrapper for a generic functions used in integration
"""
def __init__(self, function, parameters : List[str] = [], output_variable : str = None, string : str = '')... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# TODO: Add commentary.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import calendar
import datetime
from dateutil import relativedelta
import json
import os
_START_HOUR = 8
_END_HOUR = 17
_START_WEEKD... |
############################################################################
# Copyright (c) 2015-2017 Saint Petersburg State University
# Copyright (c) 2011-2015 Saint Petersburg Academic University
# All Rights Reserved
# See file LICENSE for details.
##################################################################... |
from collections import defaultdict
import itertools
import os
import requests
paginated_query='''
query NonPaginatedResources($username: String!, $first: Int, $after: String) {
user(login: $username) {
repositories(first: $first, after: $after, ownerAffiliations: [OWNER]) {
edges {
node {
... |
"""
Author: <NAME>
Python Version 3.8
"""
import logging
from pathlib import Path
import statistics
import plotly
import plotly.express as px
import pandas as pd
Path("../logs/").mkdir(parents=True, exist_ok=True)
logging.basicConfig(filename='../logs/side_by_side_plot.log',
level=0, filemode='w',... |
import pytest
import snappi
import utils as utl
import snappi_convergence
def pytest_exception_interact(node, call, report):
# end all pytests on first exception that is encountered
pytest.exit(call.excinfo.traceback[0])
def pytest_addoption(parser):
# called before running tests to register command lin... |
import cv2
import numpy as np
import blend_modes
from builtins import input
def apply_processing(frame):
#show_wait_destroy("captured frame", frame)
frame = blend(frame)
#frame = brightness(frame)
frame = adjust_gamma(frame)
frame = cv2.addWeighted(frame, 0.5, frame, 0.5, 0.0)
frame = desaturat... |
"""
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
def __relative_imports(number_of_descent):
file = __file__
for _ in range(number_of_descent):
file = os.path.dirname(file)
sys.path.append(file)
sys.path.appe... |
#!/usr/bin/env python3
'''Generates 2 reports about OpenBMC error logs:
1) Dumps every error defined in the errors.yaml files passed in
into a single JSON file that looks like:
{
"desc":"Callout IIC device",
"error":"xyz.openbmc_project.Common.Callout.Error.IIC",
"file":"... |
import pytest
import hypothesis
from decoder import decoder_utils
from decoder import bit_reader
from decoder import framing
from decoder import predictors
from decoder.tests import strategies
def _br(binary_data):
return bit_reader.BitReader(binary_data)
@hypothesis.given(length=hypothesis.strategies.integers... |
# Module to scrap fine-grain details associated with a given certificate id
from selenium import webdriver
from bs4 import BeautifulSoup
import csv
import os
import re
from dateutil.parser import parse
# Selenium Driver Handler
def load_driver(SELENIUM_EXECUTABLE_PATH=r'/mnt/c/Users/adity/Downloads/Chrome/gec... |
import matplotlib.pyplot as plt
import numpy as np
def _get_fret_number(string, note):
""" Returns the fret number of a given note on a given string """
pitches = [('A', 0), ('Bbb', 0), ('G##', 0),
('A#', 1), ('Bb', 1), ('Cbb', 1),
('B', 2), ('Cb', 2), ('A##', 2),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.