text stringlengths 3.07k 12.6k |
|---|
import email.message
import email.utils
import json
from email.charset import Charset
from typing import Tuple, Dict, Union
from django.core.mail.backends.base import BaseEmailBackend
from django.db import models
class AbstractBaseEmailMessage(models.Model):
"""
Abstract base class for email messages allowin... |
import os
import torch
import torchvision
import torchvision.transforms as transforms
SHUFFLE_ONE_CLASS = False
class Transforms:
class CIFAR10:
class VGG:
train = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomCrop(32, padding=4),
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import tensorflow as tf
from abc import abstractmethod
from rl.core.function_approximators.normalizers import NormalizerStd, Normalizer
from rl.core.oracles.oracle import Oracle
from rl.core.utils.tf2_utils... |
# Copyright (c) 2018 Intel Corp. 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... |
from __future__ import print_function
import sys
import os
import datetime
import time
from PyQt5 import QtCore, QtWidgets
import rtmidi
from PyQt5.QtWidgets import *
from zeroconf import ServiceBrowser, Zeroconf
from rtmidi.midiutil import open_midiinput
from rtmidi.midiutil import open_midioutput
from subprocess imp... |
import os
import time
import datetime as dt
import requests
import json
config_path = '/config/config.json'
# config_path = 'kube/secrets/config.json'
mailgun_api_key = os.environ['MAILGUN_API_KEY']
with open(config_path) as json_data:
config = json.load(json_data,)
categories = []
class alarms... |
# -*- coding: utf-8 -*-
# landportal-data-access-api
# Copyright (c)2014, WESO, Web Semantics Oviedo.
# Written by <NAME>.
# This file is part of landportal-data-access-api.
#
# landportal-data-access-api is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as... |
"""Helper classes for dealing with local file operations."""
import os
import errno
import logging
import shutil
import re
import hashlib
class FileCopy(object):
def __init__(
self,
source=None,
destination=None,
link=False,
remove_source=False):
... |
import io
import os
from datetime import datetime, date
from sqlalchemy import (create_engine, Boolean, Column,
Date, DateTime, Integer, BigInteger,
Float, String, Text, func,
Table, ForeignKey, Index)
from sqlalchemy.exc import IntegrityError
from... |
import io
from io import BytesIO
try:
import pandas as pd
except:
print("No library named pandas, please run \"pip install pandas\" in your command line")
quit()
try:
import numpy as np
except:
print("No library named numpy, please run \"pip install numpy\" in your command line")
quit... |
# Copyright (C) 2020, 2021, 2022 GreenWaves Technologies, SAS
# 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 the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
... |
from getpass import getuser
import os
import posixpath
import pysftp
import pytest
from airflow_fs.hooks import SftpHook
from airflow_fs.testing import MockConnection
@pytest.fixture
def sftp_conn(mocker):
conn = MockConnection(
host="localhost", login="root", extra={"ignore_hostkey_verification": True}... |
from .parse import process_expression_string, serialize
from .dependency import DependencyCollector
from ..utils.collections import subdict
from ..schema.actions import RollbackAction, TerminateAction, PrimaryAction, CompositeAction, SimulatorAction
from .builtins import ordered_builtins, global_builtins
from .exprgrap... |
# meta classes in python
# part 3
# problem solving with metaclass.
# Problem: inherited docstrings aren't perticularly informative in python.
# here we have two simple class (A and B) and B is the subclass of A
class A:
def func(self):
"""Doc_String of class A"""
pass
class B(A):
pass
# pri... |
import numpy
from numpy import cov
from numpy import trace
from numpy import iscomplexobj
from numpy import asarray
from numpy.random import randint
from scipy.linalg import sqrtm
from keras.applications.inception_v3 import InceptionV3
from keras.applications.inception_v3 import preprocess_input
from keras.datasets.mni... |
"""Requests used to support the namex API
TODO: Fill in a larger description once the API is defined for V1
"""
from flask import make_response, jsonify
from flask_restplus import Namespace, Resource, cors
from flask_jwt_oidc import AuthError
from namex.utils.auth import cors_preflight
from namex.utils.api_resource ... |
#!/usr/bin/env python3
import importlib
import os
import unittest
x86_feature_check = importlib.import_module('x86-feature-check')
importlib.invalidate_caches()
def get_resource(filename):
"""Returns the content of a resource with the given filename."""
dirname = os.path.dirname(__file__)
resource_path ... |
"""
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key
exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already... |
# coding: utf-8
from __future__ import unicode_literals, print_function
from contextlib import closing
from multiprocessing import Pool
import pandas as pd
import torch
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, random_split
from tqdm import ... |
import datetime
import json
import humanize
from Bio.SeqUtils import seq3
import pandas as pd
from markupsafe import Markup
from werkzeug.urls import url_encode
from biophi.common.utils.formatting import aa_name
from flask import Flask, url_for, request, render_template
import os
from biophi.common.utils.scheduler imp... |
class SladerBook:
""" Represents a book in slader
"""
def __init__(self, isbn="", name=""):
self.book = (isbn, name)
self.exercise_type = None
self.page = None
self.q_num = None
def set_name(self, name):
self.book = (self.book[0], name)
return self
d... |
#!/home/ssm-user/canvas/.env/bin/python
import boto3
import sys
import json
import signal
import time
from flatten_json import flatten
from hashlib import sha512
from bs4 import BeautifulSoup
import unicodedata
import warnings
from urlextract import URLExtract
from phonenumbers import PhoneNumberMatcher
# Create SQS... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import collections
import os
import re
import time
import typing
import kubernetes
import rq
from base import BaseObject
from base import RedisClient
from taskadmin.core.svc import BatchStage
class KubeStatus(BaseObject):
@staticmethod
def is_api_available():... |
"""Support for Eight smart mattress covers and mattresses."""
from __future__ import annotations
from datetime import timedelta
import logging
from pyeight.eight import EightSleep
from pyeight.user import EightUser
import voluptuous as vol
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_BINARY_SENSORS... |
from __future__ import print_function
import numpy as np
import random
import json
import sys
import os
import pickle as pkl
import networkx as nx
from networkx.readwrite import json_graph
version_info = list(map(int, nx.__version__.split('.')))
major = version_info[0]
import scipy.sparse as sp
minor = version_info[1... |
"""Script for feature extraction from OLE files.
The script contains functionalities extracted from the dike's modules. It is
platform-independent (the required classes are already included) and runs
without other files.
The script is meant to be imported (via pybind11 module, for example). The
process_file() functio... |
#!/usr/bin/env python
import difflib
import optparse
import sys
def process(original, corrected):
"""
Returns a list of violations that are found
"""
original_lines = []
corrected_lines = []
gen = difflib.unified_diff(original, corrected, n=0)
try:
# Skip the first 2 lines of the... |
##
## Copyright (c) 2016-2019 Genomics England Ltd.
##
## This file is part of PanelApp
## (see https://panelapp.genomicsengland.co.uk).
##
## Licensed to the Apache Software Foundation (ASF) under one
## or more contributor license agreements. See the NOTICE file
## distributed with this work for additional informati... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
import time
import itertools
from queue import PriorityQueue
import argparse
from copy import deepcopy
from collections import OrderedDict
import string, random, math
from datetime import datetime
import sys
import pickle
import libs.definition as df
import subprocess
def execute_in_shell(command... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Converts from histogram.proto JSON to histogram JSON.
This code is here as a stepping stone between the new histogram.proto format
(introduced early 2020)... |
"""
Copyright (c) 2018 iCyP
Released under the MIT license
https://opensource.org/licenses/mit-license.php
"""
import json
import os
import re
from collections import OrderedDict
from typing import Set
import bpy
from .. import vrm_types
from .make_armature import ICYP_OT_MAKE_ARMATURE
class Bones_rename(bpy.types... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import numpy as np
from numpy import linalg
import cvxopt
import cvxopt.solvers
import pylab as pl
def gaussian_kernel(x, y, sigma=5.0):
return np.exp(-linalg.norm(x-y)**2 / (2 * (sigma ** 2)))
def data_generator(nSamples):
zl_mean1 = [-1, 2]
zl_mean2 = [1, 1... |
"""
Making numbers readable and dimensional one order of magnitude at a time
"""
__all__ = 'nice_size nice_duration MemorySize Duration'.split()
from .debug import show
from .iteration import sample, nopes
orders = {
0: 'mono',
1: 'deca',
2: 'hecto',
3: 'kilo',
6: 'mega',
9: 'g... |
import networkx as nx
from datetime import datetime
import pydot
from networkx.drawing.nx_pydot import write_dot
def printTimeStamp(tag):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time," at :",tag)
#==================
# Tools (isoNode)
#=================... |
import torch
from torch.autograd import Variable
import numpy as np
import random
from torch.nn import functional as F
import torch.nn as nn
import util.comm_util as comm_util
def pcl_loss(args, rewards, values, log_probs, R):
#TODO: Make version in which agents don't share reward
next_values = values[1:] + ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
from __future__ import unicode_literals
from django.db import models
import logging
from django.utils.translation import ugettext_lazy as _
from . import IDC, AssetGroup, AdminUser, SystemUser
__all__ = ['Asset']
logger = logging.getLogger(__name__)
def get_default... |
from django.http import HttpResponse
from django.shortcuts import render,redirect
from django.contrib.auth import login, authenticate
from django.contrib import messages
from django.shortcuts import render
from .forms import SignupForm,NewHoodForm,ProfileForm,BusinessForm,CreatePostForm
from django.contrib.sites.short... |
'''
This modules is where we define the business logic of the dynamic versioning
options.
'''
# core libraries
import importlib.machinery
import importlib.util
import logging
import re
import subprocess
# configuration
from . import configuration
VERSIONING_OPTIONS = [
("new-version=", None, "The value to be u... |
from django import http
from django.shortcuts import get_object_or_404
from django.utils.functional import cached_property
from django.core.exceptions import ImproperlyConfigured
from django.views.generic import ListView, CreateView, DetailView, UpdateView
from django.contrib.auth.mixins import UserPassesTestMixin
fro... |
from dataclasses import dataclass
from typing import List
import numpy as np
import pandas as pd
from finx_option_pricer.option import Option
MARKET_DAYS_PER_YEAR = 252
@dataclass
class OptionPosition:
option: Option
quantity: int
end_sigma: float = None
SHORT = "short"
LONG = "long"
@pro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author : richardchien
@Date : 2020-04-14 22:10:53
@LastEditors: yanyongyu
@LastEditTime: 2020-04-14 22:21:30
@Description : None
@GitHub : https://github.com/richardchien
"""
__author__ = "richardchien"
import re
import math
from datetime... |
import logging
import sys
import os
import requests as req
from collections import OrderedDict
import cartosql
import lxml
from xmljson import parker as xml2json
from dateutil import parser
import requests
import datetime
### Constants
SOURCE_URL = "http://volcano.si.edu/news/WeeklyVolcanoRSS.xml"
DATETIME_FORMAT = '... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
"""
Deeper Multi-Layer Pecptron with XAVIER Init
Xavier init from {Project: https://github.com/aymericdamien/TensorFlow-Examples/}
@<NAME> (<EMAIL>)
"""
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnis... |
# coding: utf-8
import ui, console, time, motion
import threading, queue
from contextlib import closing
from datetime import datetime
import re, urllib.request, socket
import urllib
import os
from flask import Flask, request, Response, abort
from flask import send_from_directory
import mimetypes
import wkwebview... |
#!/bin/python3
import zlib
import bitstring
import os
import sys
import socket
import struct
import random
import threading
import time
import math
FLAG_APID = 100
FLAG_INTERVAL = 4.0
CMD_APID = 108
PAYLOAD_APID = 110
PAYLOAD_INTERVAL = 2.0
HK_APID = 106
# class to put a lock around the socket so that multiple thre... |
import numpy as np
import pygame
def nonlin(x, deriv=False):
if deriv:
return x*(1-x) # sigmoid deriv
return 1/(1+np.exp(-x)) # sigmoid
class NeuralNetwork():
def __init__(self, l0_size, l1_size, l2_size):
# init synapses
np.random.seed(1)
self.network_shape = (l0_size, l1_size, l2_size)
self.syn0 = 2*... |
# encoding=utf-8
# -*- coding: utf-8 -*-
'''
Author: <NAME> (<EMAIL>)
-----
Last Modified: Tuesday, 6th April 2021 11:52:31 am
Modified By: <NAME> (<EMAIL>)
-----
Copyright (c) 2021 IceWould Information Technology Co., Ltd.
'''
import csv # 用来处理 csv 文件
########################
### Section 1 Starts ###
def read_csv(f... |
# -*- coding:utf-8 -*- #
import collections
import configparser
import logging
import numpy as np
from numba import njit
config = configparser.ConfigParser(delimiters=":")
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(name)s:%(levelname)s: %(message)s")
def write_ini_file(file_name, layer_name, par... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import pytest
@pytest.fixture
def config():
configs_dir = os.path.abspath(os.path.join("tests", "configs"))
return os.path.join(configs_dir, "baseline.conf")
@pytest.fixture
def baseline():
config = """version 15.0
no service pad
service tcp-keepa... |
import argparse
import json
from re import U
import numpy as np
import os
from scipy.spatial.distance import cdist
from torch import gt
def parse_args():
parser = argparse.ArgumentParser(description="Line_Eval")
parser.add_argument("--preds_bar", dest="preds_bar", help="predictions for bar", default="../save/... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .elastic import Paper as PaperText, Fragments
from .table import Table, read_tables
from .json import load_gql_dump
from pathlib import Path
import re
import pickle
from joblib import Parallel, delayed
from collections import UserList
from ..... |
"""All the messages with a header between 0-49.
Mostly from RFC 4253: SSH Transport Layer Protocol
"""
from __future__ import print_function, division, absolute_import
from __future__ import unicode_literals
import os
from pyssh.base_types import (Byte, Boolean, String, UInt32, NameList, MPInt,
... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : articles_spider.py
@Time : 2020/10/21 20:12:29
@Author : EvilRecluse
@Contact : <EMAIL>
@Desc : 知乎文章爬虫
'''
# here put the import lib
import requests
import execjs
import time
import logging
# 用于保持人性
_SUCCESS_SLEEP = 10
def _get_x_zse_86... |
# -*- coding: utf-8 -*-
"""
=========================================================================
Helper functions for string manipulation (:mod:`sknano.core._strings`)
=========================================================================
.. currentmodule:: sknano.core._strings
"""
from __future__ import abso... |
import os
import gzip
import json
import math
import random
import pickle
import pprint
import argparse
from preprocess import convert_unique_idx, split_train_test, create_pair
from util_origin import load_model, get_args, get_device, set_env
import numpy as np
import pandas as pd
import train
import torch
from race_... |
from model_wrappers.base_wrapper import Base_Wrappepr
import os
import torch
import numpy as np
import tqdm
from tqdm import tqdm
import lib.metrics as M
import torch.nn.functional as F
import cv2
import logging
def get_models_name(exp_root):
"""
ret:
- model_cpt{dict[name: state_dict]}
"""
mode... |
from django.test import TestCase
from django.contrib.auth import get_user_model
User = get_user_model()
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import (
Post,
Tag
)
from post.serializers import (
PostSerializer,
PostDetailS... |
import pandas as pd
import numpy as np
import random
import sys
from tabulate import tabulate
'''
Reads the .csv file into a Pandas dataframe.
'''
def read_csv_into_dataframe(filename):
return pd.read_csv(filename)
'''
Takes in a dictionary correlating first names with "M" (if the name is
commonly a male name), an... |
from abc import ABC, abstractmethod
from gemmforge import constructs
from .abstract_loader import AbstractShrMemLoader
from gemmforge.symbol_table import SymbolType, DataView
from copy import deepcopy
def _find_next_prime(number):
factor = 2
return _find_prime_in_range(number, factor * number)
def _find_prime_i... |
"""This file provides functionality for sampling constraint parameters for
2d-polytopes randomly located around a specific landmark. This sampling procedure
can be specified via the option constr_para_generator = 'opts2lm_polytope_rand'.
The generated constraint parameter for a 2d-polytope with n vertices consist of 2*... |
#!/usr/bin/env python
"""Implements a glipmse sensor and a glimpse network
Implements a glipmse sensor as described in
https://arxiv.org/pdf/1406.6247v1.pdf
"""
import cv2
import numpy as np
import tensorflow as tf
__author__ = "<NAME>"
__copyright__ = "Copyright 2016 - 2017, The RAM project for steering \
pr... |
import json
import os
import os.path
from uuid import uuid4
from datetime import datetime, timedelta
from dateutil import tz
import numpy as np
from pynwb import NWBFile, TimeSeries
from pynwb import NWBHDF5IO
from hdmf.data_utils import AbstractDataChunkIterator, DataChunk
from hdmf.backends.hdf5.h5_utils import H5D... |
import os
import capnp
import image_capnp
import time
from math import *
from numbers import Number
import random as __random
class ImageBuffer:
def __init__(self, name):
self.message = image_capnp.Image.new_message(shortname=name, id=0)
self.commands = []
def addCommand(self, cmd, values):
... |
import random
import time
import pytest
from helpers.client import QueryRuntimeException
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
cluster = ClickHouseCluster(__file__)
s0r0 = cluster.add_instance(
's0r0',
main_configs=['configs/remote_servers.xml', 'configs/merge_tree... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
whois.py - A CLI for WhoisXMLAPI
Usage:
whois.py balances
whois.py [-d | --debug] [--verbose] <domain> [-o | --output=<output_file>]
whois.py bulk [-d | --debug] <input_file> [--csv] [ -o | --output=<output_file>]
whois.py reverse [-d | --debug] [-p | --purc... |
import random
from xml.dom import minidom
import collections
class Botlib:
class Directory:
jokes = 'reddit-top-2.5-million/data/3amjokes.csv'
quotes = 'reddit-top-2.5-million/data/quotes.csv'
notes = 'data/notes.xml'
catpictures = 'reddit-top-2.5-million/data/catpictures.csv'
... |
import numpy as np
import copy
from math import pi, sin, exp
import scipy.constants as sp
class FDTD:
def __init__(self, mesh, pulse, time):
self.mesh=mesh
self.pulse=pulse
self.time=time
def boundarymur(self, ex, ex_old):
ncells, ddx= self.mesh.ncells, self.mesh.ddx
... |
from django.core.servers.basehttp import FileWrapper
from django.db.models import Avg, Count
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.utils import simplejson
from ... |
# -*- coding: utf-8 -*-
# Copyright 2018 University of Groningen
#
# 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 torch.utils.data import Dataset
import numpy as np
import random
import cv2
from glob import glob
import torch
from torchvision.transforms import functional as F
from torchvision import transforms
from PIL import Image
class MattingDataset(Dataset):
def __init__(self,
dataset_root_dir='src/d... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 16:29:17 2019
@author: amarmore
"""
# Defining current plotting functions.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import musicae.autosimilarity_segmentation as as_seg
from sklearn.decomposition import PCA
def plot_me_this_spect... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017, 2018, <NAME> <<EMAIL>>
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
import ast
import astor
import irtypes as ir
def ensure_float(node):
if node.type == ir.Type.Float: return ... |
#!/usr/bin/env python
"""Creates the pin file for the nRF5."""
from __future__ import print_function
import argparse
import sys
import csv
def parse_port_pin(name_str):
"""Parses a string and returns a (port-num, pin-num) tuple."""
if len(name_str) < 4:
raise ValueError("Expecting pin name to be at ... |
# Copyright 2021 Sony Semiconductors Israel, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pathlib import PurePath
from textwrap import dedent
import pytest
from pants.backend.project_info.list_roots import all_roots
from pants.backend.python.dependency_inference.module_m... |
import math
from math import pi
from typing import NewType, Union
from krpc.client import Client
from scripts.utils.execute_node import execute_next_node
from scripts.utils.status_dialog import StatusDialog
from scripts.utils.utils import clamp_2pi
# TODO: type hint for kRPC remote objects may need to be separated
V... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
from alphacast import Alphacast
from dotenv import dotenv_values
API_KEY = dotenv_values(".env").get("API_KEY")
alphacast = Alphacast(API_KEY)
# In[2]:
def fix_date(df):
df = df[df.index.notnull()]
df["Date"] = df.ind... |
import csv
import json
import pdb
import numpy as np
import torch
from tqdm import tqdm
def check_k(queries):
return len(queries[0]["mentions"][0]["candidates"])
def evaluate_topk_acc(data):
"""
evaluate acc@1~acc@k
"""
queries = data["queries"]
k = check_k(queries)
for i in range(0, k... |
# Copyright (C) 2018 Swift Navigation Inc.
# Contact: Swift Navigation <<EMAIL>>
#
# This source is subject to the license found in the file 'LICENSE' which must
# be be distributed together with this source. All other rights reserved.
#
# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# EI... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der angewandten Forschung e.V.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provid... |
from pathlib import Path
import os
import time
import cv2
import numpy as np
import argparse
import depthai as dai
from utils import *
print("Creating pipeline...")
pipeline = dai.Pipeline()
print("Creating 2D Face Detection Network...")
fd_in = pipeline.createXLinkIn()
fd_in.setStreamName("fd_in")
fd_nn = pipeline.c... |
#
from django.shortcuts import render
#엘리먼트를 가져오고 method를 관리하는 멋진 클래스이다.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from . import models, serializers
from nomadgram.notification import views as notification_views
from faker import Faker
impo... |
import logging
import datetime
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.template import loader
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Count
... |
from itertools import product
import numpy as np
import pytest
import tensorflow as tf
from tensorflow.keras.models import load_model
from performer.networks.linear_attention import Performer
INPUT_SHAPES = [([1, 18, 16], [1, 4, 12], [1, 4, 12], (1,)),
([1, 5, 3, 16], [1, 5, 4, 16], [1, 5, 4, 12], (1... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2012 <NAME>, Opera Software ASA
#
# 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
#
# Unl... |
"""Device class"""
from binascii import hexlify
import logging
import math
import queue
from .exceptions import ZerprocException
_LOGGER = logging.getLogger(__name__)
CHARACTERISTIC_COMMAND_WRITE = "0000ffe9-0000-1000-8000-00805f9b34fb"
CHARACTERISTIC_NOTIFY_VALUE = "0000ffe4-0000-1000-8000-00805f9b34fb"
NOTIFICATI... |
# -*- coding: utf-8 -*-
"""
description : Test that nonlinear sir operators evolves to its theoretical threshold
author : bveitch
version : 1.0
project : EpidPy (epidemic modelling in python)
Note:
In simple cases (SIR, SEIR, SIRS) this is straightforward
SIR and SEIR:
(at threshold) r -... |
"""A DataCollectionService is a service that communicates with a DtssHost and stores data to the DtssHost according
to a set of ts_ids, timespans and intervals."""
import logging
from typing import Sequence, Union, Optional
from abc import ABC, abstractmethod
import shyft.time_series as st
from weather.data_sources.h... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
import os
import os.path as osp
import json
import cv2
import numpy as np
import time
from progress.bar import Bar
import torch
import pycocotools._mask as _mask
import cvtools
from externa... |
import logging
import os
import os.path
import time
from decimal import ROUND_HALF_UP, Decimal
from pickle import dump, load
from typing import Any, Dict, List, Optional
import cv2
import sklearn
from pdf2image import convert_from_path
BILLYS_WORKSPACE_NAME = '.billys'
def identity(x):
return x
def get_data_h... |
"""Entry point to evolving the neural network. Start here."""
import logging
from optimizer import Optimizer
from utils import network_to_json, json_to_model
from train import train_and_score
from sklearn.model_selection import StratifiedKFold
from keras.utils.np_utils import to_categorical
import random
def train_net... |
from pprint import pprint
from telepot.loop import MessageLoop
import telepot
import time
import datetime
import pymysql
import json
import threading
import logging
import sys
db = pymysql.connect(
host="localhost",
user="root",
passwd="",
db='siparma_db'
)
cursor = db.cursor()
# auth
bot = telepot.Bo... |
"""Calculates a multiple linear regression recursively adding variables,
until the score is under a threshold
For more information, see :ref:`Multiple Linear Regression`.
"""
from numpy import array, std
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_err... |
# -*- coding: utf-8 -*-
#
from __future__ import print_function
import numpy
import pytest
import sympy
import quadpy
from quadpy.hexahedron import Product
from helpers import check_degree
def _integrate_exact(f, hexa):
xi = sympy.DeferredVector("xi")
pxi = (
+hexa[0] * 0.125 * (1.0 - xi[0]) * (1.0... |
#!/usr/local/bin/python3
"""Script to generate a fixture of a box falling on a saw."""
import argparse
import json
import pathlib
import sys
import numpy
import shapely.geometry
from shapely.geometry import Polygon
from shapely.ops import cascaded_union
from fixture_utils import *
COG_SCENES = ["line", "loop", "lar... |
import concurrent.futures
import copy
import csv
import hashlib
import itertools
import tarfile
from io import BytesIO
from pathlib import Path
from shutil import copyfileobj
from tempfile import SpooledTemporaryFile
import boto3
from smart_open import open
from smart_open.s3 import parse_uri
from s3mothball.settings... |
from __future__ import print_function
from config import cfg, cfg_from_file
from datasets import TextDataset
from datasets import prepare_data
from model import CNN_ENCODER
import os
import sys
import time
import random
import argparse
import numpy as np
import pprint
import torch
from torch.auto... |
#!/usr/bin/env python3
# http://adventofcode.com/2017/day/10
import functools
import operator
import sys
DATA_SIZE = 5
DATA_SIZE = 256
# Data is all on one line
def load_input(datafile):
with open(datafile, 'rb') as f:
return f.read().rstrip()
def insert(data, pos, length, sub_data):
data_len = l... |
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.