text stringlengths 3.07k 12.6k |
|---|
"""Support for HLK-SW16 relay switches."""
import logging
from hlk_sw16 import create_hlk_sw16_connection
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_SWITCHES
from homeassistant.core import callback
import homeas... |
import numpy as np
import os
from tqdm import tqdm
import json
from scipy.misc import imresize
from imageio import imread
from collections import Counter
import random
import h5py
# This data loading file is derived from public kaggle kernel: https://www.kaggle.com/rohitag13/create-data-imagecaptioning
def process_im... |
"""
The MIT License (MIT)
Copyright (c) 2012-2018 Språkbanken, University of Gothenburg
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 right... |
# coding=utf-8
"""
EXAMPLE-PROJECTIONS
Projection example.
GLFW-TOOLBOX
Toolbox for GLFW Graphic Library.
MIT License
Copyright (c) 2019-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 Softw... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** 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
from ... import _utilities, _tables
from... |
from collections import defaultdict
from enum import Enum
from abc import abstractmethod, ABC
from pathlib import Path
from typing import (
Tuple,
Optional,
Union,
Dict,
)
import yaml
from keyboardlayout.layouts import (
LayoutName,
VerticalAnchor,
HorizontalAnchor,
LayoutConstant,
)
f... |
# coding: utf-8
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
from django.utils.decorators import method_decorator
import django_filters
from rest_framework import status
from rest_framework.gen... |
"""Support for media browsing."""
from __future__ import annotations
from collections.abc import Callable
from functools import partial
from urllib.parse import quote_plus
from homeassistant.components import media_source
from homeassistant.components.media_player import BrowseMedia
from homeassistant.components.medi... |
import codecs
import os
import pickle
from collections import (abc,
defaultdict,
deque)
from contextlib import contextmanager
from functools import singledispatch
from itertools import (chain,
starmap,
zip_longest)
from oper... |
from comet_ml import Experiment
from comet_ml import Optimizer
API_KEY = '<KEY>'
import numpy as np
from keras.models import Model
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization, Input
from keras.layers import Conv1D, MaxPooling1D, Conv2D, MaxPool2D
from keras.callbacks import Learni... |
# -*- coding: utf-8 -*-
"""Tools for canonicalizing a CURIE based on a priority list."""
from dataclasses import dataclass, field
from functools import lru_cache
from typing import Iterable, List, Mapping, Optional, Set, Tuple
import networkx as nx
import pandas as pd
from more_itertools import pairwise
from tqdm im... |
"""
使用说明:
1. 先启动redis服务器
2. 启动python app.py
3. 启动worker
python worker.py -h
python worker.py (PS: 默认不带参数运行,主机名hostname将作为消费组的名称,消费者名称随机uuid1)
python worker.py -C 'consumer_name' -G 'group_name'
目前:
支持多worker运行,支持master-slave分布式模式运行
一个worker 对应单个消费组并且只有一个消费者
TODO
一个worker 对应单个消费者并且对应多个消费者
一个w... |
# coding: utf-8
#
# Copyright 2017 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
from __future__ import absolute_import
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
import pdb
import numpy as np
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class KL_Loss(nn.Module):
def __init__(self,T=3):
# KL loss mod... |
# Copyright (c) 2015 Red Hat, 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 ... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import os
import time
import numpy as np
# import torch
# import tensorflow as tf
#######################
## working directory 변경 (for console)
#######################
import os, sys
cur_dir = os.getcwd()
os.chdir(os.path.join(cur_dir, './lectures/cs285/hw1/'))
sys.path.append(os.getcwd())
from cs285.infrastructur... |
import torch
import torch.nn.functional as F
import numpy as np
from torch import nn
import math
class SkipConnection(nn.Module):
def __init__(self, module):
super(SkipConnection, self).__init__()
self.module = module
def forward(self, input):
return input + self.module(input)
clas... |
# -*- encoding: utf-8 -*-
'''
Trubble Nova plugin for running arbitrary commands and checking the output of
those commands
This module is deprecated, and must be explicitly enabled in pillar/minion
config via the trubblestack:nova:enable_command_module (should be set to True
to enable this module). This allows nova to... |
from kapteyn import maputils, tabarray
import numpy
import sys
from matplotlib import pyplot as plt
__version__ = '1.91'
epsilon = 0.0000000001
def radians(a):
return a*numpy.pi/180.0
def degrees(a):
return a*180.0/numpy.pi
def cylrange():
X = numpy.arange(0,400.0,30.0);
# Replace last two (dummy) va... |
#!/usr/bin/env python3
import re
from telnetlib import Telnet
import time
__author__ = "<NAME>"
__copyright__ = "Copyright 2019 <NAME>"
_SWING_CHAR_TO_NAME = {
"-": None,
"0": None,
"a": "auto",
"h": "horizontal",
"3": "30",
"4": "45",
"6": "60",
"v": "vertical",
"x": "stop",
}
_... |
# flake8: noqa
from tempfile import TemporaryDirectory
from pytest import mark
import torch
from torch import nn
from torch.optim import Adam
from torch.utils.data import DataLoader
from catalyst import dl, utils
from catalyst.contrib.data import HardTripletsSampler
from catalyst.contrib.datasets import MNIST
from c... |
import torch
import pickle
from torchvision import transforms
from PIL import Image
from pathlib import Path
from tqdm import tqdm
from time import time
from model import Encoder, RNNAttnDecoder
from collections import Counter
class CaptchaDataset(torch.utils.data.Dataset):
def __init__(self, cfg):
self... |
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import numpy
def isfloat(value):
'''
This function check input for float conversion
:param value: input value
:type value:str
:return: result as bool (true if input_value is a number and false otherwise)
'''
try:
fl... |
import os
import panda3d.core as pc
from direct.directtools.DirectUtil import ROUND_TO
from p3d.functions import (
FloatTuple2Str,
Mat42Str,
Str2Bool,
Str2Mat4,
Str2Point3,
Str2Vec2,
Str2Vec3,
Str2Vec4,
)
def Relpath(target, base=os.curdir):
"""
Return a relative path to the ... |
# misc helpers
import argparse
import glob
import pathlib
import shutil
import sys
# GUI
import PIL.Image, PIL.ImageDraw, PIL.ImageTk
from tkinter import *
from tkinter import ttk
# number of pixels to the left and right of the supposed bar
BAR_CONTEXT = 10
# number of pixels to draw the supposed barline
NUM_PIXELS =... |
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from migen.fhdl.specials import Keep
from litex.soc.integration.soc_core import mem_decoder
from litex.soc.integration.soc_sdram import *
from litex.soc.integration.builder import *
from litex.soc.cores.uart import UARTWishboneBridge
from l... |
from prime import *
from util import *
from md5 import md5
from time import time
from pathlib import Path
import os
import re
#================================
P = Q = A1 = A2 = X = Y = W = 0
HOME = str(Path.home())
DIR = ".cramershoup"
PUBKEY = "id_cramer_pub"
... |
"""Wrapper module on top of pyluos Robot object."""
import time
import logging
from glob import glob
from pyluos import Device as LuosDevice
from pyluos.modules import DynamixelMotor
from ..error import LuosModuleNotFoundError, LuosGateNotFoundError
from .io import IO
logger = logging.getLogger(__name__)
def atte... |
import envi
import envi.bits as e_bits
from vivisect.const import *
class EmulationMonitor:
"""
Emulation monitors may be passed into functions like
runFunction() to track and hook the emulator.
"""
def __init__(self):
# FIXME make this a dict and re-plumb for VaSet
self.emuanom = ... |
from __future__ import annotations
import numpy as np
from pandas._typing import (
ArrayLike,
Scalar,
npt,
)
from pandas.compat.numpy import np_percentile_argname
from pandas.core.dtypes.missing import (
isna,
na_value_for_dtype,
)
def quantile_compat(
values: ArrayLike, qs: npt.NDArray[np.... |
# Copyright 2022 The Brax 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 law or agreed to in wri... |
"""
Copyright (c) 2019 Intel Corporation
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 writin... |
import os
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import ElementNotInteractableException
from selenium.common.exceptions import NoSuchElementException
from bs4 import BeautifulSoup
from openpyxl import load_workbook
#######... |
import curses
from functools import partial
from itertools import islice
from typing import Optional
from loguru import logger
from ContextUtils import get_text, get_cursor_index, get_x, get_selected_index
from PrintItem import PrintItem
def print_empty_line(screen, y):
pass
def print_line(x, text, screen, y):
... |
import decimal
import math
import contextlib
from parsy import string, regex, seq, generate, eof
WS = regex(r'\s*')
PLUS = string('+') << WS
MINUS = string('-') << WS
STAR = string('*') << WS
SLASH = string('/') << WS
LBRACKET = string('(') << WS
RBRACKET = string(')') << WS
LSQUARE = string('[') << WS
RSQUARE = stri... |
"""Doctest support"""
load("@bazel_skylib//lib:dicts.bzl", "dicts")
load(":cc.bzl", "cc_interop_info")
load(":private/context.bzl", "haskell_context", "render_env")
load(":private/path_utils.bzl", "link_libraries")
load(":private/set.bzl", "set")
load(
"@rules_haskell//haskell:providers.bzl",
"HaskellInfo",
... |
import os
import json
from torchblocks.metrics import Accuracy
from torchblocks.callback import TrainLogger
from torchblocks.trainer import TextClassifierTrainer
from torchblocks.processor import TextClassifierProcessor, InputExample
from torchblocks.utils import seed_everything, dict_to_text, build_argparse
fro... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
import re
import sys
import csv
import os
import pandas as pd
base_url = "https://shop.greattree.com.tw/greattree/"
output_csv = "tree.csv"
output_xls = "tree.xls"
myitems = []
#大樹
def getinfo():
# his = ["/item/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%A... |
import os
import numpy as np
from numpy.linalg import svd
# ----- BEGIN USER INPUT -----
#data_dir = "~/path/to/data/dir"
#data_dir = "/Users/wayneisaacuy/Desktop/NYU/2021/adeimdom/perform/examples/contact_surface/unsteady_field_results"
data_dir = "/Users/wayneisaacuy/Desktop/NYU/2021/adeimdom/perform/examples/sta... |
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Defines a Revision model for storing snapshots."""
import sqlalchemy as sa
from sqlalchemy.orm import validates
from ggrc import db
from ggrc.models import inflector
from ggrc.models import mixins
from ... |
#fun_zone_bot.py
import os
import random
import xlrd #Excel File read library for Rules of Acquisition
from google_images_search import GoogleImagesSearch #Google Images API
import discord
#Apig routine
async def apig_message(message):
if '... |
import sys
import logging
import threading
import time
import socket
import os
from importlib import import_module, reload
from gradient_utils import metrics
logger = logging.getLogger(__name__)
if os.getenv("PAPERSPACE_DEBUG"):
reload(logging)
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s'... |
from typing import Tuple
import pygame
from pygame.locals import *
from sys import exit
from random import randint
from time import sleep
pygame.init()
pygame.mixer.init()
pygame.mixer.music.set_volume(0.1)
musica_de_fundo = pygame.mixer.music.load('sons/Tec-Pix.wav')
pygame.mixer.music.play(-1)
"""barulh... |
#!/usr/bin/python3
import serial
import io
import traceback
from flask import Flask, jsonify, g, request
import time
from time import localtime, strftime, sleep
import sys
import threading
import os
import re
from pprint import pprint
# Init
app = Flask(__name__)
if os.path.exists('/dev/ttyACM0'):
ser = serial.s... |
import numpy as np
from scipy import sparse as sp
from scipy import stats
import pytest
from sklearn.svm._bounds import l1_min_c
from sklearn.svm import LinearSVC
from sklearn.linear_model import LogisticRegression
from sklearn.svm._newrand import set_seed_wrap, bounded_rand_int_wrap
from sklearn.utils._t... |
import time
from hashlib import sha256
import random
import pandas as pd
import logging
import os
import gnupg
from tempfile import TemporaryDirectory
from datetime import datetime
CSV_SEPARATOR = ";"
SECONDS_IN_DAY = 86400
MAX_DAYS_BACK = 3
TRANSACTION_FILE_EXTENSION = ".csv"
ENCRYPTED_FILE_EXTENSION = ".pgp"
APPLI... |
#!/usr/bin/env python
import mlflow
import optuna
import os
import pdb
import tempfile
from optuna import Trial, samplers
from ssltsc.callbacks import TuneCallback
from ssltsc.data import load_dataloaders
from ssltsc.architectures.utils import backbone_factory
from ssltsc.experiments import update_config, get_experime... |
"""Generic methods for splitting strings"""
import re
from typing import Any
from typing import List
from typing import Optional
from typing import Tuple
from pysyte.types.literals import punctuation
from pysyte.types.literals import nones
def _default_separator() -> str:
"""The default separator used by all me... |
#
# Copyright (c) 2022 TUM Department of Electrical and Computer Engineering.
#
# This file is part of MLonMCU.
# See https://github.com/tum-ei-eda/mlonmcu.git for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You m... |
#coding: utf-8
import unittest
from StringIO import StringIO
from tempfile import NamedTemporaryFile
from lxml import etree, isoschematron
from packtools import stylechecker
# valid: <a><b></b></a>
# invalid: anything else
sample_xsd = StringIO('''\
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:ele... |
"""
.. module: lemur.auth.service
:platform: Unix
:synopsis: This module contains all of the authentication duties for
lemur
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import jwt
import json
impor... |
# Copyright 2020 Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import os
import tempfile
from pathlib import Path
from unittest import TestCase
import pyarrow as pa
import pytest
from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, ReadInstruction
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by <NAME>.
MIT Licensed.
Contact at www.sinclair.bio
"""
# Built-in modules #
from collections import defaultdict
# Internal modules #
from pacmill.taxonomy.taxa_graphs import TaxaBarstack, TaxaLegend
# First party modules #
from plumbing.cache import prope... |
#!/usr/bin/env python3
"""This module fits a single model and logs results into MLflow.
Command line arguments can be used to control selected hyperparameters.
See python model.py --help for details
"""
from pathlib import Path
import click
import funkybob
from imageio import imread
import mlflow
from mlflow.tensorfl... |
# encoding: utf-8
"""
leuvenmapmatching.matcher.newsonkrumm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Methods similar to Newson Krumm 2009 for comparison purposes.
<NAME> and <NAME>. Hidden markov map matching through noise and sparseness.
In Proceedings of the 17th ACM SIGSPATIAL international conference on adva... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tools associated with data reduction and image handling
"""
import os
import numpy as np
from astropy import units as u
import ccdproc
from astropy.extern import six
default_headers = ['FILENAME', 'OBJECT', 'IMAGETYP', 'TIME-OBS', 'RA', 'DEC', 'EX... |
from flask import (
abort, Blueprint, current_app, redirect,
render_template, request, Response, url_for
)
# http://flask-sqlalchemy-session.readthedocs.org/en/v1.1/
from flask_caching import make_template_fragment_key
from flask_sqlalchemy_session import current_session
import ghdiff
from flask_security import... |
"""
Utils files for functions not directly playing a role in the classification pipeline.
"""
import numpy as np
import matplotlib.pyplot as plt
import os
from torch import Tensor
def store_results(imgs, path, filename="result_"):
"""
Stores the result of a task in a specific folder.
Note: The input to be... |
import json
import logging
import time
from datetime import datetime
from typing import Any, List, Optional
import click
from click.exceptions import UsageError
from requests import Response
from termcolor import colored
import datahub.cli.cli_utils
from datahub.emitter.mce_builder import dataset_urn_to_key, schema_f... |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from mptt.models import MPTTModel, TreeForeignKey
# Create your models here.
class Competence(MPTTModel):
competence_name = models.CharField(max_length=256)
name = models.CharField(max_length=256, unique=... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import unittest
import numpy as np
from skfem import BilinearForm, InteriorBasis, LinearForm, asm, solve
from skfem.element import (ElementTetP0, ElementTetRT0, ElementTriP0,
ElementTriRT0)
from skfem.mesh import MeshTet, MeshTri
class ConvergenceRaviartThomas(unittest.TestCase):
rate... |
import os, sys
from astropy.io import fits
import astropy.io.ascii as at
import numpy as np
from scipy.interpolate import interp1d
import matplotlib
matplotlib.use("AGG")
import matplotlib.pyplot as plt
# blaze functions are different on each chip
# 1-120 on one, 121-240 on the other (except 0 indexed instead)
def rea... |
import argparse
import os
import sys
import platform
import shutil
import subprocess
from typing import Dict, Iterable, Iterator, List, Optional, Sequence, TextIO, Type, Tuple, Union
cmakip_build_type = "Release"
class CmdLineParser:
def __init__(self):
self.parser = argparse.ArgumentParser(description... |
import re
from django import forms
from django.forms.models import fields_for_model
from utilities.querysets import RestrictedQuerySet
from .constants import *
__all__ = (
'add_blank_choice',
'expand_alphanumeric_pattern',
'expand_ipaddress_pattern',
'form_from_model',
'parse_alphanumeric_range',... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
# modified from https://github.com/tristandeleu/pytorch-meta/blob/master/examples/maml/utils.py
import torch
from collections import OrderedDict
from tqdm import tqdm
from metal.common.cmd_args import cmd_args... |
import os
from porcupine import tabs
def test_filetab_path_gets_resolved(tmp_path, tabmanager):
(tmp_path / "dir1").mkdir()
(tmp_path / "dir2").mkdir()
(tmp_path / "file1").touch()
(tmp_path / "file2").touch()
funny1 = tmp_path / "dir1" / ".." / "file1"
funny2 = tmp_path / "dir2" / ".." / "fi... |
import random as r
from algosdk import account, encoding, mnemonic,transaction
from algosdk.future.transaction import AssetTransferTxn, PaymentTxn
from algosdk.v2client import algod
#This is an Algogenous Smart Contract for a guessing game where if the user wins he/she gets a reward of a particular amount of a token... |
import tensorflow as tf
import numpy as np
import random
import matplotlib.pyplot as plt
import matplotlib.mlab
import pickle
from os import listdir
from os.path import isfile, join, isdir
from scipy.io import wavfile
def variable_summaries(var):
'''Helper class for attaching summaries to a Tensor
(for TensorB... |
"""
I KNOW, I KNOW, Code redundancy, I know this is not pythonic, but I'm seeing double and running out of time
Promise I'll fix it .. someday
"""
import argparse
import os
import cv2
import librosa
import numpy as np
import soundfile as sf
import torch
from tqdm import tqdm
from lib import dataset
from lib import n... |
"""
https://vlight.me/2018/06/25/OpenCV-Recipes-Genometric-Transformations/
"""
import cv2
import numpy as np
import math
from PIL import ImageDraw, Image, ImageFont
def draw_four_vectors(img, line, color=(0, 255, 0)):
"""
:param line: [[x1,y1],[x2,y2],[x3,y3],[x4,y4]]
矩形四点坐标的顺序: left-to... |
import argparse
import logging
import sys
import yaml
import os
import pkg_resources
from . import constants
from .colors import MessageColors
from .exceptions import DefinitionError
from .main import AnsibleBuilder
from .introspect import process, simple_combine, base_collections_path
from .requirements import sanit... |
import torch
import random
import math
import torch.nn.functional as F
import os.path as osp
import numpy as np
import torch_geometric.transforms as T
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch.autograd import Variable
from torch.nn import Parameter
from torch.nn import Linear
from torch_geometri... |
import json
import os
import codecs
import random
from collections import namedtuple
# Required to properly identify imports in Streamlabs
import sys
sys.path.append('.\Services\Scripts\PokerBot')
sys.path.append(os.path.join(os.path.dirname(__file__), "lib")) #point at lib folder for classes / references
import cl... |
# Tests for solving edges
from .compat import unittest
from pprint import pprint as pp
from semantic_version import base
from semantic_version import edge
from sortedcontainers import SortedDict
from sortedcontainers import SortedSet
def parse_ex(version_req_str):
"""Helper function to parse with partial=False.""... |
from __future__ import print_function
import http.client as httplib
import json
import logging
from abc import ABCMeta, abstractmethod
import oandapyV20
import oandapyV20.endpoints.orders as orders
from oandapyV20.contrib.requests import MarketOrderRequest
from broker.fxcm.constants import get_fxcm_symbol
from broke... |
# Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. 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
#
# ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.urls import reverse_lazy
from django.views import generic
from django import forms
from django.contrib import messages
try:
from django_select2.forms import Select2Widget
_select2 = True
except ImportError:
_select2 = False
from ... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import socket
import subprocess
import sys
import time
from contextlib import contextmanager
from errno import ECONNREFUSED
import pytest
import six
from ephemeral_port_reserve import reserve... |
""" Unit tests for Order views (see views.py) """
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from InvenTree.status_codes import OrderStatus
from .models import PurchaseOrder, PurchaseOrderLineItem
import json
class OrderViewTestCase(TestCase):
... |
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
import unittest
from cla.controllers.github import webhook_secret_validation, webhook_secret_failed_email, \
webhook_secret_failed_email_content
from cla.utils import get_comment_badge, get_comment_body
import ... |
import logging
from typing import Any, Optional
import appdirs
import determined as det
from determined import core, tensorboard
from determined.common import constants, storage
from determined.common.api import certs
from determined.common.experimental.session import Session, get_max_retries_config
logger = logging... |
# ------------------------------------------------------------------------------
#
# MIT License
#
# Copyright (c) 2017 <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 restri... |
'''
Design and implement a data structure for a Least Frequently Used (LFU) cache.
Implement the LFUCache class:
LFUCache(int capacity) Initializes the object with the capacity of the data structure.
int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1.
void put(int key, in... |
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------#
# Name: MatEstimateGradient
# Purpose: OD-matrix estimation with least squares formulation, solution method is with gradient method. See Spi... |
from itertools import filterfalse, tee
from .vector2 import vector2
class polygon:
def __init__(self, coords):
"""[summary]
Args:
coords ([type]): [description]
"""
self._origin = coords[0]
self._vecs = list(c - coords[0] for c in coords[1:])
def __iadd__... |
#!/usr/bin/python
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# 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... |
# Python
import os
import logging
# Genie
from genie.utils import Dq
from genie.utils.timeout import Timeout
from genie.metaparser.util.exceptions import SchemaEmptyParserError
# pyATS
from pyats.utils.objects import R, find
# PLATFORM
from genie.libs.sdk.apis.iosxe.platform.get import get_diffs_platform
# Logger
l... |
'''
Turtle Game v4.0
<NAME>, 3/12/18
Player 1 = Arrow Keys (Kappa)
Player 2 = WASD (Mario)
Collect the coin together then go to the star to move on to the next level!
'''
from turtle import *
from random import *
from wall import *
guardmove = 1
joescore = 0
willscore = 0
turn_speed = 5
forward_speed = 7
speed = 1
scre... |
from timeit import default_timer as timer
from os.path import exists, join, dirname
from os import makedirs
from time import sleep
from mycroft.backend.settings import DATA_PATH, STT_CONFIG
from mycroft.backend.utils import download, untar
try:
from deepspeech import Model
except ImportError:
print("could not ... |
"""
A miscellaneous utility for sequential labeling.
Copyright 2010,2011 <NAME>.
"""
import optparse
import sys
def apply_templates0(X, templates):
"""
Generate features for an item sequence by applying feature templates.
A feature template consists of a tuple of (name, offset) pairs,
where name and o... |
print("[ > BOT BY: Jonathan < ] \n")
import os
import colorama
from colorama import Fore
import discord
import asyncio
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
###########SETUP###############
prefix = "!"
token =... |
#########################################################################################
# Name: <NAME>
# Student ID: 64180008
# Department: Computer Engineering
#
# Assignment ID: A8
#########################################################################################
###################... |
import bpy
import numpy
import bmesh
# This operator adds vertices to a stroke using the start of a line.
"""
def get_ordered_verts(self, bm, selected_object):
edges = [i for i in bm.edges if i.select]
edge = edges[0]
start_vert = edge.verts[0]
edges.remove(edge)
ordered_... |
# -*- coding: utf-8 -*-
import timeit
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from aw_nas.objective.base import BaseObjective
from aw_nas.utils.torch_utils import accuracy
class OFAClassificationObjective(BaseObjective):
NAME = "ofa_classification"
SCHEDULABLE_A... |
import requests
import twitter
import re
import time
import json
from twitter.twitter_utils import enf_type
import atexit
import string
from langdetect import detect
from langdetect.lang_detect_exception import LangDetectException
from datetime import datetime
import sys
start = 2238300 #Input this every time
filte... |
import os
import json
import torch
import pandas as pd
import warnings
from utils import load_embeddings
from collections import Counter
from config import Config
warnings.filterwarnings("ignore")
pd.options.mode.chained_assignment = None # default='warn'
def labeling(sentiment_value, pivot=0.4):
if sentiment_v... |
import numpy as np
from radiobear.constituents import parameters
GHz = 29.9792458 # conversion from cm^-1 to GHz
def alpha(freq, T, P, cloud, cloud_dict, other_dict, **kwargs):
"""
Adapted from Imke's code, but used Ulaby, Moore and Fung (see e.g. p310).
'fraction' below scales the absorption ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.