text stringlengths 3.07k 22.1k |
|---|
# pylint: disable=no-name-in-module
# pylint: disable=no-self-argument
import datetime
import json
import logging
from typing import List, Optional
from flask import request, Response, make_response, jsonify
from sqlalchemy import and_, not_, or_
from anyway.app_and_db import db
from anyway.backend_constants impor... |
import csv
import time
import json
import requests
import pandas as pd
from datetime import datetime, timedelta
class data_row:
def __init__(self, date_time, ghi, dni, dhi, ta, ws):
self.date_time = date_time
self.ghi = ghi
self.dni = dni
self.dhi = dhi
self.ta = ta
... |
"""
A script to calculate accuracy, mAP, F1-score, etc. of transliterations
given the predictions and ground truth as JSONs.
USAGE:
Example 1: Predictions file format - JSON
<<script.py>> --gt-json EnHi_dev.json --pred-json Google/EnHi_dev.json [--save-output-csv scores.csv]
Example 2: Predictions file fo... |
from decimal import Decimal
from functools import total_ordering
import re
import itertools
from datetime import date
from dateutil.relativedelta import relativedelta
from helper import keyify, as_number
class Service:
EXPECTED_QUARTERS = [
# worked through oldest to newest to calculate %age changes
... |
"""
test_search
~~~~~~~~~~~
Test the search index builder.
:copyright: Copyright 2007-2022 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from collections import namedtuple
from io import BytesIO
import pytest
from docutils import frontend, utils
from docutils.parse... |
#! /usr/bin/env python
import os
import sys
import subprocess
import tempfile
import shutil
import xml.etree.ElementTree
import re
tmpdir = None
#######################################
# Utils
def cleanup():
if not tmpdir:
return
if options['nocleanup']:
print("Not cleaning up. Find the file... |
from torch.utils.data import Dataset
import torch
import numpy as np
import random
import torch.nn.functional as F
from torchvision import transforms
from torchvision.transforms.functional import normalize
import PIL
from PIL import Image
import os
from .transform import Compose, RandomCrop, RandomRotation, RandomVert... |
from utils import log
import resnetv2
import torch
import time
import torchvision as tv
import numpy as np
import argparse
from dataset import DatasetWithMeta
from utils.test_utils import get_measures
import os
from torch.autograd import Variable
from utils.mahalanobis_lib import sample_estimator, get_Mahalanobis_score... |
import numpy as np
from sklearn.metrics.cluster import adjusted_mutual_info_score
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics.cluster import completeness_score
from sklearn.metrics.cluster import contingency_matrix
from sklearn.metrics.cluster import entropy
from sklearn.metrics.cluste... |
import pytest
import json
import logging
import time
from datetime import datetime
from tests.common.utilities import wait_until
from tests.common import config_reload
from tests.common.helpers.assertions import pytest_assert
CRM_POLL_INTERVAL = 1
CRM_DEFAULT_POLL_INTERVAL = 300
pytestmark = [
pytest.mark.topolog... |
import csv
import random
import numpy as np
import matplotlib.pyplot as plt
import scipy.spatial as spatial
class LVQ():
def __init__(self, dataset):
"""
Construtor da classe
:param nome_arquivo: nome do arquivo csv que contem os dados
"""
self.dados = dataset
self.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
from scipy import misc
import src.align.detect_face as detect_face
import random
import src.facenet as facenet
from time import sleep
import shutil
class ... |
"""
Copyright 2018, Yahoo
Licensed under the terms of the Apache 2.0 license. See LICENSE file in project root for terms.
"""
import unittest
import logging
import requests
import subprocess
import json # why isn't the call below recognized?
from mock import patch, Mock
from mock import create_autospec
from requests... |
import copy
import re
import common_with_cwrap
import yaml
from collections import OrderedDict, defaultdict
try:
# use faster C loader if available
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
# matches `name`, `params` in `name(params)`
NAME_PARAM_REGEX = r'(\w+)\((.*)\... |
from ..db import models
from ..db.database import SessionLocal
from ..settings import Settings
import aiodocker
import docker
from docker.errors import APIError
import json
from fastapi import HTTPException
settings = Settings()
# For Deploy Form
# Input Format:
# [
# {
# 'cport': '53',
# 'hport'... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ------------------------------------------------------------------------------
import logging
import os
import time
import numpy as np
import num... |
import os
import sys
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
parent_dir_name = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(parent_dir_name)
from utils.iwe import purge_unfeasible, get_interpolation, interpolate
class EventWarping(nn.Mod... |
# Copyright 2019 TerraPower, 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 writi... |
# -*- coding: utf-8 -*-
#
# test_parrot_neuron.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the Lice... |
"""
EXPAND lemma with inflections from xml according to an fst and paradigm/layout files
"""
import csv
import json
from collections import defaultdict
from dataclasses import dataclass, asdict
from itertools import chain
from pathlib import Path
from string import Template
from typing import Dict, Iterable, List, Opt... |
"""ResNet model.
ResNet: Deep Residual Learning for Image Recognition
https://arxiv.org/pdf/1512.03385.pdf
Adapted from code contributed by <NAME>.
https://github.com/fchollet/deep-learning-models/blob/master/resnet50.py
"""
from keras import layers
from keras.models import Model
from keras.layers import Input
from ... |
import os
import yaml
import re
from sslib.fs_helpers import *
from sslib.rel import REL, RELSection, RELRelocation, RELRelocationType
ORIGINAL_FREE_SPACE_RAM_ADDRESS = 0x806782C0
ORIGINAL_DOL_SIZE = 0x57A680
def split_pointer_into_high_and_low_half_for_hardcoding(pointer):
high_halfword = (pointer & 0xFFFF0000) ... |
import difflib
import html
import re
from collections import defaultdict
from pyquery import PyQuery
from django.utils.encoding import force_str
from scripts.helpers import parse_xml, serialize_xml
### helpers
def split_string_and_insertions(string, pattern):
"""
Given a string and a regex pattern, ret... |
__author__ = '<NAME>'
import pandas as pd
import argparse
import operator
import pickle
import sys
from timeit import default_timer as timer
def get_arguments():
parser = argparse.ArgumentParser(description='Write csv files for crowd annotation')
parser.add_argument('--input_csv', '-i', type=str, dest='input_c... |
# -*- coding: utf-8 -*-
import os
import collections
import gensim
import numpy as np
import tensorflow as tf
# const int INFO = 0; // base_logging::INFO;
# const int WARNING = 1; // base_logging::WARNING;
# const int ERROR = 2; // base_logging::ERROR;
# const int FATAL = 3; // b... |
from pytrade.steam_enums import SteamUrls, ETradeOfferState
from pytrade.EconTradeOffer import TradeOffer, merge_item
from pytrade.EconItem import Item
from pytrade.confirmations import ConfManager
from steamid import SteamID
import aiohttp
from pyee import EventEmitter
import re
from copy import copy
from time import ... |
#!/bin/python3
"""Loose pong clone (Atari, 1972)
This script implements a loose clone of Atari's original pong.
To run the game simply run the script and then - to start a game - press enter.
Player 1 moves using the WASD keys
Player 2 moves using the directional keys
The game ends when one of the players ... |
import math
from ophyd import (Device, EpicsMotor, Signal, Component as Cpt,
PseudoSingle, PseudoPositioner, EpicsSignal)
from ophyd.pseudopos import (real_position_argument,
pseudo_position_argument)
from hxntools.device import NamedDevice
def remove_names_maybe(obj,... |
"""
:mod:`disco.ddfs` -- Client interface for Disco Distributed Filesystem
======================================================================
See also: :ref:`DDFS`.
.. note::
Parameters below which are indicated as tags can be specified as
a `tag://` URL, or the name of the tag.
"""
import os, re... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 ts=4 sts=4 sw=4 et tw=80 :
#
# Apply catalog offsets to FITS images to simplify visual inspection and
# subsequent processing. This program creates the 'nudge' imtype from 'clean'
# files and their corresponding 'clean' fcat catalogs.
#
# <NAME>
# Created: 2021-... |
import discord
import aiohttp
import datetime
import ast
from discord.ext import commands
screenshotchannel = 569979062513041408
class screenshotTwo(commands.Cog, name="Screenshot"):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, ctx):
guild = ctx.guil... |
import logging
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as opt
import torch.utils.data as data
import torchvision.transforms as T
import torch.nn.functional as F
import torchvision.datasets as datasets
from torchv... |
# -*- coding: utf-8 -*-
"""
Copyright 2021 Huawei Technologies Co., Ltd
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... |
"""
Run Experimental scenarios
Gets results for multiple agents and scenarios
- whether scenario was solved
- reward vs episode
- time vs episode
"""
import sys
from network_attack_simulator.envs.environment import NetworkAttackSimulator as Cyber
from network_attack_simulator.experiments.experiment_util im... |
from __future__ import print_function
from transcriptic_tools.utils import (ul, ml, get_cell_line_name, get_well_max_volume,
copy_cell_line_name, set_property, get_column_wells,
get_volume, get_well_dead_volume, floor_volume,
... |
'''
Created on Mar 7, 2011
@author: johnsalvatier
'''
from __future__ import division
import numpy as np
import scipy.linalg
import theano.tensor as tt
import theano
from .special import gammaln
from ..math import logdet as _logdet
from pymc3.theanof import floatX
c = - 0.5 * np.log(2 * np.pi)
def bound(logp, *co... |
"""Module using IndRNNCell to solve the Sequential MNIST problem
The approach is described in https://arxiv.org/abs/1803.04831. The
hyper-parameters are taken from that paper as well as from its author's
implementation: https://github.com/Sunnydreamrain/IndRNN_Theano_Lasagne
The main difference to the original implem... |
# 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
# distribu... |
import unittest
from igraph import Graph, Layout, BoundingBox
class LayoutTests(unittest.TestCase):
def testConstructor(self):
layout = Layout([(0,0,1), (0,1,0), (1,0,0)])
self.assertEqual(layout.dim, 3)
layout = Layout([(0,0,1), (0,1,0), (1,0,0)], 3)
self.assertEqual(layout.dim, 3... |
from datetime import datetime, timezone
# from itertools import zip_longest
from pprint import pprint
import unittest
from django.db.models import Model
from django.test import TestCase
from iterable_orm import QuerySet
from data_analysis.pattern_finders.frequency import FrequencyPatternFinder
from data_vis.models im... |
"""Date-related functionality.
Note:
Date ranges are always tuples (start, end) from the (inclusive) start date
to the (exclusive) end date.
"""
import datetime
import enum
import re
from typing import Iterator
from typing import NamedTuple
from typing import Optional
from typing import Tuple
from flask_babel... |
"""
Script with solutions for all workspace assignments in the Multivariate
Exploration of Data lesson.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
def encodings_solution_1():
"""
Solution for Question 1 in encodings practice: see if pokemon speed has a
... |
# Copyright (c) 2009-2022 The Regents of the University of Michigan.
# Part of HOOMD-blue, released under the BSD 3-Clause License.
"""Newtonain Event-Chain Integrators for Hard Particle Monte Carlo."""
from hoomd.hpmc.integrate import HPMCIntegrator
from hoomd.data.parameterdicts import TypeParameterDict, ParameterD... |
import pandas as pd
import numpy as np
from sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score
from sklearn.externals import joblib
import logging
import logging.config
logger = logging.getLogger('optimizer')
pandas_dataframe_styles = {
'font-family': 'monospace'... |
"""Tests the spec, using memoryfs"""
import contextlib
import os
import pickle
import tempfile
import fsspec
from fsspec.implementations.memory import MemoryFileSystem, MemoryFile
def test_idempotent():
MemoryFileSystem.clear_instance_cache()
fs = MemoryFileSystem()
fs2 = MemoryFileSystem()
assert fs... |
# copyright (c) 2021 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 applica... |
# pyre-ignore-all-errors
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
from copy import deepcopy
from datetime import datetime
from http import HTTPStatus
from typing import Optional
import pytest
from flask import Response
from werkzeug import Client
from diem_utils.types.currenc... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, Http404
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User
from django import forms
from .forms import NewUserForm, Data
from... |
import argparse
import datetime
import logging
import os
import sys
from datetime import datetime, timedelta
from traceback import print_stack
import config
EXTRACTED_FOLDER_NAME = 'extracted_gz'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
MINUTES_INTERVAL = 5
logging.basicConfig(
level=logging.DEBUG,
format='[%(a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, List
def focal_loss(logits, targets, alpha: float, gamma: float, normalizer):
"""Compute the focal loss between `logits` and the golden `target` values.
Focal loss = -(1-pt)^gamma * log(pt)
where pt is the pr... |
"""
_WMWorkloadTools_
Define some generic tools used by the StdSpecs and WMWorkload
to validate arguments that modify a WMWorkload and/or WMTask.
Created on Jun 13, 2013
@author: dballest
"""
from builtins import str, bytes
from future.utils import viewitems, viewvalues
import json
import re
import inspect
from Ut... |
import pygame
import os
import random
# ширина и высота игрового экрана
WIDTH = 640
HEIGHT = 480
# частота кадров
FPS = 60
# путь к изображениям
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, "images")
snd_folder = os.path.join(game_folder, "sound")
music_folder = os.path... |
"""Utilities directly related to the `generate` step of `cargo-bazel`."""
load(":common_utils.bzl", "CARGO_BAZEL_ISOLATED", "cargo_environ", "execute")
CARGO_BAZEL_GENERATOR_SHA256 = "CARGO_BAZEL_GENERATOR_SHA256"
CARGO_BAZEL_GENERATOR_URL = "CARGO_BAZEL_GENERATOR_URL"
CARGO_BAZEL_REPIN = "CARGO_BAZEL_REPIN"
REPIN = ... |
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models import Net
net = Net()
# net.to(device)
print(net)
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
# the dataset we created in Noteb... |
from typing import Dict, List
import numpy
from overrides import overrides
from deep_qa.data.instances.instance import TextInstance, IndexedInstance
from deep_qa.data.data_indexer import DataIndexer
from deep_qa.common.checks import ConfigurationError
class GraphAlignInstance(TextInstance):
"""
A ``Graph... |
import numpy as np
import pytest
from py_wake.examples.data.iea37._iea37 import IEA37_WindTurbines, IEA37Site
from py_wake import NOJ, Fuga
from py_wake.site._site import UniformSite
from py_wake.tests import npt
from py_wake.examples.data.hornsrev1 import HornsrevV80
from py_wake.tests.test_files.fuga import LUT_path_... |
"""
Quart 驱动适配
================
后端使用方法请参考: `Quart 文档`_
.. _Quart 文档:
https://pgjones.gitlab.io/quart/index.html
"""
import asyncio
from dataclasses import dataclass
from typing import List, TypeVar, Callable, Optional, Coroutine
import uvicorn
from pydantic import BaseSettings
from nonebot.config import Env
fr... |
#!/usr/bin/env python
"""
This file is part of TexText, an extension for the vector
illustration program Inkscape.
Copyright (c) 2006-2021 TexText developers.
TexText is released under the 3-Clause BSD license. See
file LICENSE.txt or go to https://github.com/textext/textext
for full license details.
"""
import argp... |
# Copyright (c) 2020, MeteoSwiss
# Authors: <NAME> <<EMAIL>>
#
# 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... |
from collections import Iterable
import io
import re
import subprocess
import cv2
softsub_path = "softsub.mkv"
hardsub_path = "hardsub.mp4"
subtitles_path = "subtitles.srt"
subtitles_lang = "fra"
align_on_hardsubs = False
align_frames = 5
align_from = 3*60 # seconds
softsub_video = cv2.VideoCapture(softsub_path)
har... |
# coding: utf-8
from urlparse import urlparse
from uuid import uuid4
import hashlib
import re
import unicodedata
import urllib
from google.appengine.datastore.datastore_query import Cursor
from google.appengine.ext import ndb
from webargs import fields as wf
from webargs.flaskparser import parser
import flask
import... |
# -*- coding: utf-8 -*-
import os
#import sys
import unittest
import numpy as np
import pyNastran
from pyNastran.utils import is_binary_file, object_methods, object_attributes, print_bad_path
from pyNastran.utils.dev import list_print
from pyNastran.utils.mathematics import (
get_abs_max, get_max_index, get_min_... |
import os
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
from scipy.optimize import minimize
def C_L_cutoff(C_L0, C_Lalpha, stall_angle):
'''Lift cutoff pri stall angle: rad'''
a = (C_L0 + C_Lalpha * stall_angle) / (1 * (stall_angle - np.pi / 2)**2)
def C_L(alpha):
... |
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Modified by <NAME> on 2018-10-01 to add support for ppc64el and s390x
#
# Copyright (C) 2015-2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# publ... |
from __future__ import annotations
import sys
from collections import namedtuple
from datetime import datetime
from textwrap import TextWrapper
from typing import List, Dict, Any, Union, Optional, Type
from colorama import Fore, Style, Back
from pandas import DataFrame, Series
from formulacli.banners import Banner, ... |
from typing import List, Union
from .. import math as lib_math
from .FaceULandmarks import FaceULandmarks
from .FaceURect import FaceURect
from .FacePose import FacePose
class _part_picklable_expandable:
def __getstate__(self):
return self.__dict__.copy()
def __setstate__(self, d):
self.__in... |
import os
from pathlib import Path
from random import shuffle
import numpy as np
import pandas as pd
from fashiondatasets.own.Quadruplets import Quadruplets
from fashiondatasets.own.helper.EntriesHelper import EntriesHelper
from fashiondatasets.own.helper.split_helper import SplitLoader
from fashiondatasets.utils.io i... |
"""Base class for resnet backbone that acts as a feature extractor."""
from pytorch_lightning.core.lightning import LightningModule
import torch
from torch import nn
from torch.optim import Adam
from torch.optim.lr_scheduler import ReduceLROnPlateau, StepLR, MultiStepLR
from torchtyping import TensorType, patch_typegu... |
# Copyright 2020, The TensorFlow Federated 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 o... |
# -*- coding: utf-8 -*-
"""Docs Italia theme"""
import os
import sys
import re
import yaml
import json
from . forum_italia import *
from docutils.nodes import figure
from docutils.nodes import table
from docutils.nodes import bullet_list
from docutils.nodes import list_item
from docutils.nodes import reference
from ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Finds submissions with chessboard images in them,
# use a tensorflow convolutional neural network to predict pieces and return
# a lichess analysis link and FEN diagram of chessboard
import praw
import collections
import os
import time
from datetime import datetime
from praw.... |
from django.contrib import admin
from django.http import HttpResponse
from .models import Occurrence, Biology, Locality, Taxon, TaxonRank
import unicodecsv
import os
import projects.admin
default_admin_fieldsets = (
('Curatorial', {
'fields': [('catalog_number',),
('cm_catalog_number',),... |
import time
import logging
from authlib.common.urls import urlparse
from authlib.consts import default_user_agent
from authlib.common.security import generate_token
from .errors import (
MismatchingStateError,
MissingRequestTokenError,
MissingTokenError,
)
log = logging.getLogger(__name__)
class BaseApp(... |
import win32com
from win32com.client import Dispatch,VARIANT
import pythoncom
import re
import datetime
import array
import time
import cad
AUTHOR = '黄金'
TODAY = datetime.date.isoformat(datetime.date.today())
PAT = ".+?\(G?\d{6}\)"
ATT = ("序号","代号","名称","数量","材料","单重","总重","品牌","备注","编码","单位")
def selec... |
import logging
from dataclasses import dataclass
from typing import List, Tuple, Union
import matplotlib.pyplot as plt
import meshio
import numpy as np
from skimage import measure, morphology
from nanomesh import Volume
from nanomesh.mesh_utils import simple_triangulate
from ._mesh_shared import BaseMesher
from .mes... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
"""
Inference with different ADC precisions
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch._jit_internal import weak_script_method
from .utee import wage_initializer,wage_quantizer
import numpy as np
from .quant_layer import *
from .quantizer import *
class Qconv2d(nn.Conv2d):
d... |
import argparse
import os
import random
import time
import pika
import config
import logger
import messaging
from mascoord.utils import time_since
log = logger.get_logger('Factory')
start_time = time.time()
def on_message(ch, method, properties, body):
msg = eval(body.decode('utf-8'))
from mascoord import... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import struct
import sys, re, os, signal
import traceback
if 'PYGMENTS_PATH' in os.environ:
sys.path.insert(0, os.environ['PYGMENTS_PATH'])
dirname = os.path.dirname
base_dir = dirname(dirname(dirname(os.path.abspath(__file__))))
sys.path.append(base_dir + "/vendor/... |
###################################################
## ##
## This file is part of the KinBot code v2.0 ##
## ##
## The contents are covered by the terms of the ##
## BSD 3-clause license included in the LICENSE ##
## file,... |
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as T
import PIL
import numpy as np
from .image_utils import SQUEEZENET_MEAN, SQUEEZENET_STD
dtype = torch.FloatTensor
# Uncomment out the following line if you're on a machine with a GPU set up for PyTorch!
#dtype = torch.cuda.FloatT... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
import os
import sys
import argparse
import numpy as np
import cv2
import face_recognition
import math
import dlib
from PIL import Image, ImageFile
"""
Script che permette l'aggiunta di una mascherina ad un immagine di un volto di cui ne è privo
Utilizza la libreria dlib per individuare i punti facciali e strecciare la... |
from abc import ABC, abstractmethod
import multiprocessing as mp
import threading
import queue
import platform
import traceback
import uuid
import time
from ditk import logging
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Union
from enum import Enum
@dataclass
class... |
#!/usr/bin/env python
# Copyright 2013 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 required ... |
__all__ = ('CustomIdBasedCommand', )
try:
# CPython
from re import Pattern
except ImportError:
# ChadPython (PyPy)
from re import _pattern_type as Pattern
from functools import partial as partial_func
from ...discord.interaction.components import COMPONENT_CUSTOM_ID_LENGTH_MAX
from ...discord.events... |
# Copyright 2020 The TensorFlow 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 applica... |
#!/usr/bin/env python3
# Copyright (C) 2017-2022 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... |
#Microbit Radio TxRx communication Test
#Test Cases:
# NoAck - one direction
# AckWithReTx - Re-transmittion
#
#LICENSE: MIT
#Author: <NAME>, <EMAIL>
#Document: https://paper.dropbox.com/doc/MbitBot--AWWwIfCnEicRuc7gSfO_tmcJAg-DG5SSj5zQhBv1CoAgDtAG
from microbit import *
import radio
import utime
#radio channel t... |
# django lib imports
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet, ViewSet
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_201_CREATED, HTTP_202_ACCEPTED, HTTP_200_OK, \
HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
from rest_framework.re... |
import cv2
import glob
import copy
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import nibabel.processing
from nibabel import load, save, Nifti1Image
def specify_value(syn_data, value_hub, mask_hub):
if value_hub is None:
gm_value = [10, 12] # k
wm_value = [4, ... |
import base64
import json
import os
import time
from peloton_helper import PelotonClientHelper, create_respool_for_new_peloton
from color_print import print_okblue, print_okgreen
from modules import Zookeeper, MesosMaster, MesosSlave, Cassandra, Peloton
DEFAULT_PELOTON_NUM_LOG_FILES = 10
class VCluster(object):
... |
# Find progenitors or descendants.
# progen_finder() inputs snapshots and Caesar catalog, reads in particle IDs for specified type, runs find_progens() then write_progens()
# find_progens() can also be run stand-alone, if you have a list of particle ID and caesar objects. Returns progenitor and second-most massive pro... |
# coding=utf-8
import argparse
import logging
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
import random
import numpy as np
import pandas as pd
import torch
from transformers import (BertConfig, BertForTokenClassification,
BertTokenizer)
from torch.utils.data import DataLoader
... |
import multiprocessing as mp
import os
import time
from typing import Any, Dict, List, Tuple
import numpy as np
from mava.utils.environments.RoboCup_env.robocup_utils.agent import ( # type: ignore # noqa: E501
Agent as basic_agent,
)
from mava.utils.environments.RoboCup_env.robocup_utils.trainer import ( # type... |
#!/usr/bin/env python
# coding: utf-8
"""
@author: ackar
Future edits:
- Could add argparse to edits params of ML2
depends on how we want to do it though
"""
import os
from MultiLevel2MC import MultiLevel2
import sys
from multiprocessing import Process
import time
import datetime
import numpy as np
... |
import argparse
import concurrent
import itertools
import logging
import os
import uuid
from abc import abstractmethod
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Callable, Generator, Iterable, List, Optional, Tuple, Type, Union
import numpy as np
from paralleldomain import Datas... |
import matplotlib.pylab as pylab
import math as m
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pdb
from pylab import rcParams
import matplotlib as mpl
mpl.use('AGG')
font = {'size': 40}
rcParams['figure.figsize'] = 10, 8
mpl.style.use('seaborn-paper')
rcParams['figure.figsize'] = 10, ... |
from bika.lims import _
from plone.supermodel import model
from plone import api
from plone.indexer import indexer
from zope import schema
from plone.dexterity.content import Item
from zope.interface import implements
from zope.schema.vocabulary import SimpleVocabulary
from Products.CMFCore.utils import getToolByName
f... |
# -*- coding: utf-8 -*-
import serial
import cv2
import numpy as np
import time
import datetime
import os
import json
import platform
import logging
import coloredlogs
from turbojpeg import TurboJPEG
DATAPATH = os.path.normpath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "./data/")
)
IS_NEW4K = True... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.