text stringlengths 3.07k 12.6k |
|---|
# 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
# distributed ... |
import numpy as np
import os, sys, glob, pickle
from pathlib import Path
from os.path import join, exists, dirname, abspath
import random
from plyfile import PlyData, PlyElement
from sklearn.neighbors import KDTree
from tqdm import tqdm
import logging
from .base_dataset import BaseDataset
from ..utils import make_dir,... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018, 2019, 2020 <NAME>.
#
# Invenio-S3 is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""S3 file storage interface."""
from __future__ import absolute_import, division, print_function
from fu... |
# -*- coding: utf-8 -*-
import io
import logging
from azure.storage.blob import BlobClient
from azure.core.exceptions import ResourceNotFoundError
DEFAULT_BUFFER_SIZE = 4 * 1024 ** 2
WHENCE_START = 0
WHENCE_CURRENT = 1
WHENCE_END = 2
WHENCE_CHOICES = (WHENCE_START, WHENCE_CURRENT, WHENCE_END)
logger = logging.getLo... |
"""
PACKAGE FOR PRINTING SPECIFIC PARTS OF THE HAMILTONIAN.
"""
def H_nxy_as000110_print(sys,par,n_xystart,printtype):
"""
Function printing particular blocks of the Hamiltonian depending in the input printtype.
Parameters
----------
n_xystart = [to_sites,from_sites] for H00==H_n_xystart.
printtype = off-di... |
"""
Advent of code 2021
Day 23: Amphipod
I really need to take time to comment this up: it's rather nasty code… although it did prove very handy for
calculating part 2 which I would have had problems doing had I stuck to working on a paper solution at first!
"""
from functools import cache
from aoc.loader import Loade... |
'''
This code is to undistort image given intrinsic calibration.
Reference 1: https://github.com/vwvw/opencv_live_distortion
Reference 2: https://docs.opencv.org/3.4.15/dc/dbb/tutorial_py_calibration.html
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt
def create_camera_matrix(fx, fy, cx, cy, k1, k2,... |
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
import pandas as pd
SEED = 71 # 1337, 131, 71
np.random.seed(SEED) # for reproducibility
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.layers.normalization import ... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... |
# this is not a place of honour
def convert_sequence(s):
"""Convert arguments to qmmlpack format"""
if isinstance(s, (str, type(None), float, int)):
return s
else:
if len(s) == 1:
return s[0]
elif len(s) == 2:
if isinstance(s[1], (tuple, list)):
... |
# -*- test-case-name: twisted.test.test_lockfile -*-
# Copyright (c) 2005 Divmod, Inc.
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Filesystem-based interprocess mutex.
"""
import errno
import os
from time import time as _uniquefloat
from twisted.python.runtime import platform
def ... |
# Created by yongxinwang at 2019-10-21 02:55
from Learner import face_learner
from config import get_config
import os
import os.path as osp
import argparse
from PIL import Image
import numpy as np
import torch
from mtcnn_pytorch.src.align_trans import warp_and_crop_face, get_reference_facial_points
def construct_fa... |
import os
import time
import random
import datetime
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
from openpyxl import load_workbook
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
# 开启无头模式
chrome_options.add_argument("--headless")
# 不加载图片,提高效率
prefs = {"profile.... |
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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 req... |
# -*- coding: utf-8 -*-
class LegacyAnalytics(object):
"""Legacy analytics from toomore/grs"""
def cal_continue(self, list_data):
""" 計算持續天數
:rtype: int
:returns: 向量數值:正數向上、負數向下。
"""
diff_data = []
for i in range(1, len(list_data)):
if list... |
from threading import local
from urllib.parse import urlsplit, urlunsplit
from django.utils.encoding import iri_to_uri
from django.utils.functional import lazy
from django.utils.translation import override
from .exceptions import NoReverseMatch, Resolver404
from .resolvers import get_ns_resolver, get_resolver
from .u... |
import logging
import os
from collections import defaultdict
from typing import Dict, List
from dvc.exceptions import PathMissingError
from dvc.repo import locked
from dvc.repo.experiments.utils import fix_exp_head
logger = logging.getLogger(__name__)
@locked
def diff(self, a_rev="HEAD", b_rev=None, targets=None):
... |
import cv2
import os
import numpy as np
# <editor-fold desc=" TODO: Create a Load & ProcessImage Class">
IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS = 66, 200, 3
INPUT_SHAPE = (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS)
def load_image(data_dir, image_file): # 3 Function calls @ batch_generat... |
import os
import sys
import glob
import time
import torch
import scipy.io
import argparse
import numpy as np
from PIL import Image
from itertools import count
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from DQNet import DQNet
from replayMemory import ReplayMemory
from environment import Environmen... |
import pandas as pd
from tqdm import tqdm
from collections import defaultdict
import math
import time
def get_sim_item(df_, user_col, item_col, use_iif=False):
df = df_.copy()
user_item_ = df.groupby(user_col)[item_col].agg(list).reset_index()
user_item_dict = dict(zip(user_item_[user_col], us... |
"""
Dataviz routines
All credits for the implementation and suggestions go to sega_sai (stackoverflow):
http://stackoverflow.com/questions/10439961/efficiently-create-a-density-plot-for-high-density-regions-points-for-sparse-re
"""
# from scipy.sparse import lil_matrix, triu
# from bioflow.utils.linalg_routines impor... |
"""GenBank parser."""
import re
from collections import defaultdict
from pathlib import Path
from g2j.classes import Organism, Scaffold, Feature, Location, Interval
PATTERNS = {
"scaffold": re.compile(r"LOCUS\s+?(?P<accession>\b[\w.-]+?)\s.+?\n//", re.DOTALL),
"organism": re.compile(r"ORGANISM\s+?(?P<orga... |
#! /usr/bin/env python
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2013-2015, Michigan State University.
# Copyright (C) 2015-2016, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitte... |
import datetime
import importlib
import re
import warnings
from typing import List, Set, Union, Dict
from commonmark import commonmark
from federation.entities.activitypub.enums import ActivityType
# TODO someday, rewrite entities as dataclasses or attr's
class BaseEntity:
_allowed_children: tuple = ()
_chi... |
##
# @file
# This file is part of SeisSol.
#
# @author <NAME> (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)
#
# @section LICENSE
# Copyright (c) 2015, SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permit... |
"""Handle network ranges
Tools for validating, parsing, and comparing network address ranges,
and for querying whether a given address is within a set of ranges.
AddressRange is a general construct for specifying a contiguous block
of addresses, and does not connote a structure. Subnet adds CIDR
structure. AddressRan... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import collections
import csv
import numpy as np
import six
from reagent.preprocessing import identify_types
from reagent.preprocessing.normalization import (
BOX_COX_MARGIN,
MAX_FEATURE_VALUE,
MIN_FEATURE_VALUE... |
import numpy as np
class Buffer(object):
# gets obs, actions, rewards, mu's, (states, masks), dones
def __init__(self, env, nsteps, size=50000):
self.nenv = env.num_envs
self.nsteps = nsteps
# self.nh, self.nw, self.nc = env.observation_space.shape
self.obs_shape = env.observati... |
from itertools import product
from pathlib import Path
import re
import sys
from flask import request, g
from flask.ctx import has_request_context
from pythonjsonlogger.jsonlogger import JsonFormatter as BaseJSONFormatter
from time import monotonic
import logging
import logging.handlers
LOG_FORMAT = '%(asctime)s %(a... |
import os
import sys
import numpy as np
from .layers import Layer
if sys.version_info[0] < 3:
FileNotFoundError = IOError
else:
long = int
def to_numpy(data):
if isinstance(data, np.ndarray):
return data
if hasattr(data, 'asnumpy'):
return data.asnumpy()
if hasattr(data, 'numpy'):... |
"""
========================================================================
PrintWavePass.py
========================================================================
Print single bit signal in wave form and multi-bit signal by showing
least significant bits.
To use, call top.print_wave()
Inspired by PyRTL's state ma... |
#!/usr/bin/env python
# Copyright 2017 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... |
import itertools
import parasail
from . import common
from .genome import Interval
from . import cigar as cigar_
class Weights:
def __init__(self, mismatch=4, open_gap=6, extend_gap=1):
self._mismatch = 4
self._open_gap = 6
self._extend_gap = 1
self._matrix = parasail.matrix_creat... |
#!/usr/bin/env python3
"""
Polyglot v3 node server Example 1
Copyright (C) 2021 <NAME>
MIT License
"""
import udi_interface
import sys
import time
import xml.etree.ElementTree as ET
LOGGER = udi_interface.LOGGER
Custom = udi_interface.Custom
ISY = udi_interface.ISY
polyglot = None
Parameters = None
n_queue = []
count... |
#!/usr/bin/env python3
import sys
import json
import uuid
import re
import base64
from lxml.etree import Element, SubElement, ProcessingInstruction, HTMLParser, tostring
def font_size_norm(x):
"""the web font size is different from the game client's - try to
approximate how it would look without having to kn... |
import bs4
fakeReq = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
import requests
import lxml
isNode = {'node',
'node-teaser',
'node-product-book',
'node-product-book-teaser',
... |
# Copyright 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 the rights
# to use, copy, modify, merge, publish, distribute, subl... |
import sys
import os
import time
import re
from jumpscale import j
logger = j.core.logger.get('Jumpscale.core.logger')
_LOCKDICTIONARY = dict()
JSBASE = j.application.jsbase_get_class()
class LockException(Exception, JSBASE):
def __init__(self, message='Failed to get lock', innerException=None):
JSBASE.... |
from django.shortcuts import render
from .models import Exhibitor
from event.models import Details
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.core.mail import send_mass_mail
from django.contrib.auth.decorators import login_r... |
import numpy as np
import cv2
import torch
import scipy.ndimage as sp
methods = ["cv2.TM_CCOEFF_NORMED"]
def get_mask(inp, span=15):
instance_id, instance_num = sp.label(inp)
mask = np.zeros((inp.shape[0], inp.shape[1]))
for i in range(instance_num):
x, y = np.where(instance_id == i + 1)
m... |
# 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... |
# Command line tool for using the library for preimage and collision
# attacks on implemented hash functions.
#
# Run with --help for instructions. Refer to thesis text for more details.
from library.instance import *
from hashes import *
import click
from subprocess import Popen, PIPE, call
import random
hash_functi... |
import numpy as np
import catboost as cb
import vaex.ml.catboost
import vaex.ml.datasets
# the parameters of the model
params_multiclass = {
'leaf_estimation_method': 'Gradient',
'learning_rate': 0.1,
'max_depth': 3,
'bootstrap_type': 'Bernoulli',
'subsample': 0.8,
'sampling_frequency': 'PerTr... |
#!/usr/bin/env python
# coding: utf-8
#
# Copyright (c) 2015, PAL Team.
# All rights reserved. See LICENSE for details.
#
# A service for the Carleton directory
import re
from api.directory.models import Building
from api.directory.directory_api import Directory
from pal.services.base_service import Service
from pal.... |
import re
from functools import reduce
import operator
from django.db.models import Q
from rest_framework.filters import BaseFilterBackend
from .utils import get_param
def is_valid_regex(regex):
"""helper function that checks regex for validity"""
try:
re.compile(regex)
return True
exce... |
from timeit import default_timer as timer
from typing import Dict, Generator, Tuple, Union
from netqasm.backend.network_stack import Address, BaseNetworkStack
from netqasm.qlink_compat import LinkLayerCreate, LinkLayerRecv, request_to_qlink_1_0
from netsquid.nodes.node import Node as NetSquidNode
from netsquid_magic.l... |
import os
import scipy
import numpy as np
import tensorflow as tf
def load_mnist(batch_size, is_training=True):
path = os.path.join('data', 'mnist')
if is_training:
fd = open(os.path.join(path, 'train-images-idx3-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
# trainX = loaded[... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
import warnings
from typing import Optional
from urllib.parse import quote
import sanic.app # noqa
from sanic.compat import Header
from sanic.exceptions import ServerError
from sanic.models.asgi import ASGIReceive, ASGIScope, ASGISend, MockTransport
from sanic.request import Request
from sanic.server import ConnInf... |
__package__ = 'archivebox.core'
import uuid
from django.db import models, transaction
from django.utils.functional import cached_property
from django.utils.text import slugify
from django.db.models import Case, When, Value, IntegerField
from ..util import parse_date
from ..index.schema import Link
from ..extractors ... |
import asyncio
import functools
import threading
from queue import Queue
from .client import Future, default_client
from .protocol import to_serialize
from .utils import iscoroutinefunction, thread_state, sync
from .utils_comm import WrappedKey
from .worker import get_worker
class Actor(WrappedKey):
"""Controls ... |
import os, sys
from collections import OrderedDict
import numpy as np
import paddle
# paddle.enable_static()
import paddle.fluid as fluid
import torch
from paddle import ParamAttr
import paddle.nn as nn
import paddle.nn.functional as F
SEED = 666
INPUT_SIZE = (1, 3, 488, 488)
IN_CHANNELS = INPUT_SIZE[1]
OUT_CHANNELS ... |
#!/usr/bin/env python3
import unittest
from typing import Callable, List, Union
import torch
import torch.nn as nn
from captum.insights import AttributionVisualizer, Batch
from captum.insights.attr_vis.app import FilterConfig
from captum.insights.attr_vis.features import BaseFeature, FeatureOutput, ImageFeature
from... |
import glob
import os
import time
import imageio
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
tfe = tf.contrib.eager
plt.rcParams['figure.max_open_warning'] = 60
class CVAE(keras.Model):
def __init__(self, l... |
from flask import Flask, request, jsonify, Response
import logging
import subprocess
import json
import os
import yaml
from multiprocessing import cpu_count
from urllib.parse import unquote
from azure.storage.filedatalake import DataLakeServiceClient, DataLakeFileClient
from datetime import datetime
from uuid import uu... |
#!/usr/bin/env python
from argparse import ArgumentParser
import sys
import logging
import inspect
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
from flask import Flask, request, abort, g, jsonify
from views.view_base import ViewBase
from flask_sqlalchemy import SQLAlchemy
from werkzeu... |
import asyncio
import logging
from caldera_agent import agent_protocol
from caldera_agent import foster3 as foster
from caldera_agent import utils
import win32ts
import win32security
import re
# Add module name to log messages
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
log.setLevel(loggin... |
#!/usr/bin/env python
import argparse
import os
from Bio import SeqIO
from Bio.Restriction import Restriction_Dictionary, RestrictionBatch
import csv
import sqlite3
import sys
import pandas as pd
def digest_genome(
genome_fp,
restriction_enzyme,
output_dir,
linear=False):
base_fp ... |
from typing import Union, Any, List, Tuple, Dict
from dataclasses import dataclass, field
@dataclass
class pmdpyTypeLoadVertex():
ver: Tuple[float, float, float] = field(init=False)
nor: Tuple[float, float, float] = field(init=False)
uv: Tuple[float, float] = field(init=False)
bone_id: Tuple[int, int]... |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... |
# Copyright (c) 2010-2013, Regents of the University of California.
# All rights reserved.
#
# Released under the BSD 3-Clause license as published at the link below.
# https://openwsn.atlassian.net/wiki/display/OW/License
import logging
import os
import sys
import threading
from openvisualizer.opentun.opentun import... |
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
def sample_mean(x, n):
return 1.0/n * sum(x[0:n])
def sample_var(x, n, mean = None):
assert(n >= 2)
if mean is None:
mean = sample_mean(x, n)
sample_var = 1.0/(n) * sum([(x[i] - mean)**2 for i in range(n)])
... |
import json
import sys, os.path
import os
storage = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..\..')) + '\\storageManager')
sys.path.append(storage)
error_path = (os.path.abspath(os.path.join(os.path.dirname(__file__), '..\..')) + '\\ERROR')
sys.path.append(error_path)
response_path = (os.path.abspa... |
import pytest, torch
from fastai.gen_doc import gen_notebooks
from fastai.gen_doc import nbdoc
def assert_link(docstr, expected, nb_cells=None, modules=None, msg=''):
if modules is None: modules = gen_notebooks.get_imported_modules(nb_cells or [])
linked = nbdoc.link_docstring(modules, docstr)
assert linke... |
#!/usr/bin/env python3
# encoding: utf-8
'''
s3tools.S3Utils -- shortdesc
s3tools.S3Utils is a description
@copyright: 2020 Collins Aerospace. All rights reserved.
@license: BSD 3-Clause License
'''
import boto3
import logging
import os
import pathlib
import tempfile
from botocore.exceptions import ClientErro... |
# Copyright 2017-2020 The GPflow Contributors. 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Decorators
----------
to DRY out our code...
Listen to this guy https://www.youtube.com/watch?v=wFUkKgT8tFQ
...with the decorator from http://flask.pocoo.org/snippets/70/
Rate Limiting Decorator with Redis
++++++++++++++++++++++++++++++++++
http://flask.pocoo.org/sni... |
import logging
import urllib
import requests
import base64
import voluptuous as vol
from datetime import timedelta
from homeassistant.helpers.discovery import load_platform
import homeassistant.helpers.config_validation as cv
from homeassistant.const import CONF_USERNAME, CONF_PASSWORD, CONF_HOST
from homeassistant.h... |
# Copyright 2017-2020 TensorHub, 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
'''
This script fetch the latest list of packages and their descriptions
from CTAN at https://ctan.org/pkg and save the result as a json file.
The result is used to generate usepackage and documentclass
intellisense for LaTeX Workshop.
'''
from pathlib import Path
import json
from sys import argv
import requests
CHE... |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import asyncio
import functools
import logging
import os
import signal
import sys
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from multiprocessing import Process
from pathlib import Path
from time import time
from typing import Any, Awaitable, Callable, Dict, Optional, Set, Tuple, Ty... |
import struct
import datetime
import hashlib
import crcmod.predefined
from binascii import unhexlify
def transfer(str):
if type(str) == bytes:
data = str
else:
data = bytes.fromhex(str)
data = data.replace(bytes.fromhex("5a"), bytes.fromhex("5a02"))
data = data.replace... |
#!/usr/bin/env python3
import matplotlib.ticker as mticker
"""
(c) 2018, D.D.Land <<EMAIL>>
Module om figuren weer te geven zoals aangegeven in het Rapportage document
van de afdeling Technische Natuurkunde van de Haagse Hogeschool.
versie: 1.1
20190323: docstrings aangepast aan eisen programmeren.
20180317: hersch... |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import glob
import logging
import os
import re
import shutil
import string
import subprocess
from collections import defaultdict, namedtuple
import requests
from packaging.version import parse as parse_... |
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
from datetime import datetime
import morepath
from onegov.core.elements import Link
from onegov.core.utils import Bunch
from onegov.page import Page
from onegov.town6 import TownApp
from onegov.town6.layout import DefaultLayout, PageLayout, EventBaseLayout
import onegov.core
import onegov.org
import more.transaction
... |
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import PIL
import PIL.Image
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import load_model, Model
from keras.callbacks import TensorBoard, ModelCheckpoint, EarlyStopp... |
#!/usr/bin/env python
#
# Author: <NAME>
# Code Author: <NAME>
# Affil.: L. L. Thurstone Psychometric Laboratory in the
# Dept. of Psychology and Neuroscience, UNC-Chapel Hill
# E-mail: <EMAIL>
#
# Purpose: Functions for conducting simulations.
#
#################################################################... |
#!python
"""
TralahTek LLC Git Repository Code Documentation ToolKit
Making Code Documentation Less of a Pain in the Ass.
"""
import glob
import os
from argparse import ArgumentParser
from random import choice
from docrepotek import templates
def resolve_key(lang: str) -> str:
if lang in templates.LanguageColorMa... |
# This Python file uses the following encoding: utf-8
# Copyright (c) 2020 Science and Technology Facilities Council.
#
# All rights reserved.
#
# Modifications made as part of the fparser project are distributed
# under the following license:
#
# Redistribution and use in source and binary forms, with or without
# mod... |
from enum import Enum
from random import choices
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1 import make_axes_locatable
class Direction(Enum):
Up = 1
Right = 2
Down = 3
Left = 4
class Position():
x = 0
y = 0
direction = ... |
# 28 available tiles with smallest value first
available_tiles = ((0, 0),
(0, 1), (1, 1),
(0, 2), (1, 2), (2, 2),
(0, 3), (1, 3), (2, 3), (3, 3),
(0, 4), (1, 4), (2, 4), (3, 4), (4, 4),
(0, 5), (1, 5), (2, 5), (3, 5), (4, 5),... |
# -*- coding: utf-8 -*-
#
# Copyright © 2016 The Spyder development team
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
# Local imports
import imp
import os
import os.path as osp
import sys
import uuid
# Third party imports
from qtpy.QtCore import (QObject, QProcess, QProcessE... |
import tkinter as tk
from PIL import Image, ImageTk
from connectedComponentsMethod import ConnectedComponentMethod
from MotionDetection import motion_detection
import EndScreen, cv2, keyboardInput
# Connect to the camera selected
def connectToCamera():
# 0 = Internal, 1 = External computer camera
cap = cv2.Vi... |
import asyncio
import json
from time import time
from typing import Optional
import pytest
from slack_sdk.oauth.installation_store.async_installation_store import (
AsyncInstallationStore,
)
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web.async_client import AsyncWebClient
from slack_bolt.app... |
"""
Copyright (c) 2021, Stanford Neuromuscular Biomechanics Laboratory
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 li... |
#
# The Python Imaging Library.
# $Id$
#
# SGI image file handling
#
# See "The SGI Image File Format (Draft version 0.97)", <NAME>.
# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
#
#
# History:
# 2017-22-07 mb Add RLE decompression
# 2016-16-10 mb Add save method without compression
# 1995-09-10 fl Created
#
# Copy... |
# Under MIT License, see LICENSE.txt
import logging
from datetime import datetime, timedelta
__author__ = 'RoboCupULaval'
def recorder_checker(func):
def check_installed(*args, **kwargs):
if RecorderModel.is_installed:
return func(*args, **kwargs)
else:
... |
# Code generated by moonworm : https://github.com/bugout-dev/moonworm
# Moonworm version : 0.1.14
import argparse
import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from brownie import Contract, network, project
from brownie.network.contract import ContractContainer
fro... |
# coding=utf-8
# Copyright 2019 The Tensor2Tensor 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... |
import logging
import re
from collections import defaultdict
from functools import lru_cache
from pathlib import Path
from typing import Callable, Dict, Iterator, List, Optional, Set, Tuple
from shapely.geometry import base, polygon, shape
from ....core.airspace import (
Airspace,
AirspaceInfo,
ExtrudedPo... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2021-present VincentRPS
# 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... |
from __future__ import unicode_literals, division, absolute_import
import urllib2
import time
import logging
from datetime import timedelta, datetime
from urlparse import urlparse
import requests
# Allow some request objects to be imported from here instead of requests
from requests import RequestException, HTTPError
... |
import numpy as np
import tensorflow as tf
from keras_htr import binarize
from scipy import ndimage
import networkx as nx
import subprocess
class ConnectedComponent:
def __init__(self, points):
self.points = points
self.y = [y for y, x in points]
self.x = [x for y, x in points]
s... |
import os
import pickle
details_list=[]
l2=[]
G = []
def file_save():
NAME_PRO = details_list[0]
ADDRESS_PRO = details_list[1]
MOBILE_NO_PRO = details_list[2]
ROOM_NO_PRO = details_list[3]
PRICE_PRO = details_list[4]
f = open("hotel.dat", "ab")
a=save(NAME_PRO,ADDRESS_PRO,MOBIL... |
import urllib.parse
import requests
import datetime
import xml.etree.ElementTree as ET
from .resource import Bill, EDM, Division, Member, parse_data, MemberList
from .parties import Parties
class Parliament(object):
LDA_ENDPOINT = "http://lda.data.parliament.uk/"
MEMBERS_NAMES_ENDPOINT = (
"http://da... |
import unittest
import warnings
import torch
from tqdm import tqdm
from data.utils import get_db_container, get_db_info
from utils import get_dataloader, get_train_val_test_datasets
dataset_names = ('acquirevaluedshopperschallenge',
'homecreditdefaultrisk',
'kddcup2014')
class Tes... |
"""
conftest.py
Contains global/common pytest fixtures
"""
import os
from unittest.mock import AsyncMock
from typing import Callable
from httpx import AsyncClient, Response
import pytest
from confluent_kafka import Producer
from fastapi.testclient import TestClient
from connect.main import get_app
from nats.aio.client ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.