text stringlengths 3.07k 12.6k |
|---|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
#!/usr/bin/env python3
# This file is part of the Printrun suite.
#
# Printrun 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 3 of the License, or
# (at your option) any later version.
#
# Prin... |
import datetime
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from scheduler.models import *
from django.views import generic
from django.contrib.auth.mixins im... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# coding: utf-8
from django.test import TestCase
from diffapp.diffimport import make_commit_sequence, make_diff
from diffapp.models import CommitSequence, Commit, Diff
EXAMPLE_GIT_SHOW_OUTPUT = u"""commit c28e535f1024e3b22ec05574aa2287aa5338e3dc
Author: <NAME> <<EMAIL>>
Date: Wed Feb 20 21:35:38 2013 +0400
Ок... |
##
# Copyright (c) 2013-2016 Apple 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 by applicable l... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
import pandas as pd
import nltk
import tamil
import re
import os
import glob
from nltk.tokenize import sent_tokenize, word_tokenize
from string import punctuation
nltk.download('punkt')
# In[ ]:
# Symbols list that nee... |
#-*- coding: utf-8 -*-
from __future__ import unicode_literals
from bs4 import BeautifulSoup, NavigableString
from django.forms.models import modelform_factory
from django.test import TestCase as DjangoTestCase
from django.utils.html import conditional_escape
from wysihtml5.tests.models import ModelTest
from wysihtm... |
"""
An Implementation of the 2048 game
"""
from random import randrange
from numpy import array_equal
from Tile import *
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1, ... |
from celery import current_app as celery_app
from celery import schedules
from celery.beat import ScheduleEntry
from celery.beat import Scheduler
from celery.utils.encoding import safe_str
from celery.utils.encoding import safe_repr
from celery.utils.log import get_logger
from flask import current_app
import pytz
from... |
# -*- coding: utf-8 -*-
import mimetypes
import re
from os.path import splitext
from django.core.exceptions import ValidationError
from django.core.validators import EMPTY_VALUES
from django.template.defaultfilters import filesizeformat
from django.utils.deconstruct import deconstructible
from django.utils.translatio... |
from portra.component.tags import *
from portra.component.xmp import has_metadata
from portra.component.xmp import get_tonecurve
from portra.component.xmp import xmp_get_lr_settings
from portra.utils import tc_format_js
### Adobe Lightroom values that are stored as arrays.
LR_ARRAY_TAGS = {
'ToneCurvePV2... |
import numpy as _np
import numba as _numba
from ..util import rotation as _rotation
def get_kernel(Natoms, Ndet, pixelsize, detz, k, detangles=(0, 0), nodist=True, nf=False):
"""
returns a cpu implementation of the wavefield, used internally
Natoms: Number of atoms
Ndet: detector pixels
pixelsize:... |
import time
from __init__ import print_msg_box
def counting_sort(array, unit):
n = len(array)
output = [0]*n
count = [0]*10
for i in array:
pos = (i/unit)
count[int(pos%10)] +=1
for i in range(1, 10):
count[i] += count[i-1]
for i in range(n-1, -1, -1):
p... |
import pandas as pd
import numpy as np
import os
# acquire
from pydataset import data
from datetime import date
from scipy import stats
# turn off pink warning boxes
import warnings
warnings.filterwarnings("ignore")
import sklearn
from sklearn.model_selection import train_test_split
# Train/Split the data~~~~~~... |
import numpy as np
from typing import Tuple
from IMLearn.metalearners.adaboost import AdaBoost
from IMLearn.learners.classifiers import DecisionStump
from utils import *
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from IMLearn.metrics import misclassification_error
COLOR_SCALE = ["yello... |
import websockets
import json
import regex
import string
import random
import asyncio
from tenacity import AsyncRetrying, retry, wait_fixed, stop_after_attempt, retry_if_exception_type, stop_after_delay
from .schemas import *
json_rgx = regex.compile(r'''
(?(DEFINE)
(?P<json>(\s*(?&object)\s*|\s*(?&array)\s*))
(?P<obj... |
"""
News crawler classes
"""
__all__ = ["News", "HistoricalNews"]
import sys
from os.path import dirname, join, realpath, basename
from typing import List, Dict
from json import load, loads
import asyncio
from aiohttp import ClientSession
from bs4 import BeautifulSoup
from bs4.element import Tag
from .utils.ipython i... |
# -*- ecoding: utf-8 -*-
# @ModuleName: pridict
# @Function:
# @Author: <NAME>
# @Time: 2021/9/1 15:22
import os
import cv2
import keras
import numpy as np
import segmentation_models as sm
import albumentations as A
#DATA_DIR = 'C:/Users/ZhangYe/Desktop/core_segmentation0828/pr_imgs_2/'
dir = 'C:/Users/...... |
import logging
import torch.utils.data
import dtoolcore
import numpy as np
from PIL import Image
class WrappedDataSet(torch.utils.data.Dataset):
"""Subclass of pytorch Dataset that provides dtool DataSet methods.
This class mostly provides methods that consumers of DataSets require, and
passes those m... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 14:42:15 2018
@author: <NAME> et <NAME>
"""
import time
import math
import numpy as np
import matplotlib.pyplot as plt
import random
import csv
#création d'arbres et d'instances :
def CalculArbreComplet(hauteur):
arbre = []
arbre.append(0... |
"""
:copyright: 2017 H2O.ai, Inc.
:license: Apache License Version 2.0 (see LICENSE for details)
"""
import time
import copy
import sys
import os
import numpy as np
import pandas as pd
import logging
print(sys.path)
from h2o4gpu.util.testing_utils import find_file, run_glm
logging.basicConfig(level=logging.DEBUG)... |
"""
Diags package.
This package contains the Diagnostics class, which implements the rover diagnostics.
"""
from __future__ import print_function
import rospy
import time
import os
import subprocess
import re
import textwrap
from std_msgs.msg import String, Float32MultiArray, UInt8
from diagnostics.watcher i... |
import os
import json
import logging
from cv2 import cv2
import multiprocessing as mp
from time import strftime
# CONST
ICON_APP = os.path.abspath("./data/icons/mcv_icon.png")
TITLE_STR = "Minimalist Cam View"
MCVCFG_PATH = os.path.abspath("./data/config")
DEF_RECORD_FOLDER = os.path.abspath("./Recordings")
MCVCFG_NA... |
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import cv2
import os
import random
import numpy as np
# CHAR_POSSIBILITIES = "0123456789abcdefghijklmnopqrstuvwxyz"
CHAR_POSSIBILITIES = "2345678abcdefgmnpwxy"
CHAR_COUNT = 5
ALL_LINES = [
[(30, 48), (34, 25), (76, 15), (259, 23)],
[(30,... |
from apps.common.func.CommonFunc import *
from apps.common.func.LanguageFunc import *
from django.shortcuts import render, HttpResponse
from urllib import parse
from apps.common.config import commonWebConfig
from apps.common.func.WebFunc import *
from apps.ui_globals.services.global_textService import global_textServic... |
import streamlit as st
import pandas as pd
import numpy as np
from textblob import TextBlob
import seaborn as sns
from nlp import NLPNaive
# Create space betwwen two context
def space():
st.markdown("<br>", unsafe_allow_html=True)
# Heading
st.markdown("<h1 style='text-align: center; color: #3f3f44'>NLP - Na... |
from itertools import repeat
from typing import Any, Tuple, Optional, List, Union
import numpy as np
from needlestack.apis import tensors_pb2
from needlestack.apis import indices_pb2
from needlestack.exceptions import SerializationError, DeserializationError
TYPE_TO_ENUM = {
"float16": tensors_pb2.NDArray.FLOAT... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 6 16:55:49 2020
@author: <NAME>
"""
# Package Area
import numpy as np
import matplotlib.pyplot as plt
from testCases import *
import sklearn
import sklearn.datasets
import sklearn.linear_model
from planar_utils import plot_decision_boundary, sigmo... |
import time
import random
# **************** Added for robot file execution ***************** #
import sys
import os
sys.path.insert(0, os.path.join(os.path.abspath(__file__), '../../'))
# **************** ****************************** ***************** #
import common
from common import ConditionCheckFailure
from uti... |
# Copyright 2015 PerfKitBenchmarker 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 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/LICEN... |
import argparse
import lief
import os
import subprocess
from Crypto.Cipher import AES
def align(x, al):
# Return <x> aligned to <al>
if x % al == 0:
return x
else:
return x - (x % al) + al
def pad_data(data, al):
# Return <data> padded with 0 to a size aligned with <al>
return dat... |
import tensorflow as tf
import h5py
import numpy as np
#load data
full_data = None
full_label = None
with h5py.File('/mnt/disk1/bole.h5', 'r') as hf:
full_data = np.array(hf.get('data'))
full_label = np.array(hf.get('label'))
#data
data = full_data[:40]
label = full_label[:40]
test_data = full_data[40:]
tes... |
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... |
from PyQt5.QtCore import Qt, QAbstractTableModel, QSortFilterProxyModel, QDateTime
from PyQt5.QtWidgets import QWidget, QLabel, QMessageBox, QStyledItemDelegate, QStyleOptionViewItem, QStyledItemDelegate
from PyQt5.QtGui import QIcon, QColor
from forms.ui_paymentsPage import Ui_PaymentsPage
from utils import timeout_b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import datetime as dt
import json
import re
from typing import Any, Dict, Final, Optional
from pydicom import DataElement
from .tags import Tag
from .types import Dicom
LINE_PATTERN = re.compile(r"^\((\d{4}), (\d{4})\)\s*(.*\S).*([A-Z]{2}):\s*(.*)$")
GROUP... |
from uint import Uint6, UintN
asm_ref_sheet = """Commands:
FIRST: return the first input
SECOND: return the second input
ADD: return sum of inputs
SUB: return difference of inputs
JMP: jump to line no. by first input
JMPZERO: JMP, if second input is 0
PUSH: push first input onto stack
POP: remove... |
#from ..items import DarkWebScrapingItem
#from items import DarkWebScrapingItem
from collections import Counter
import lxml.html.clean
from string import punctuation
import logging
import scrapy
from scrapy.utils.log import configure_logging
from nltk.corpus import stopwords
from nltk import PorterStemmer
f... |
# Copyright Collab 2012-2016
# See LICENSE for details.
"""
Utilities.
"""
from __future__ import unicode_literals
import os
import logging
import binascii
from base64 import b64decode
from tempfile import NamedTemporaryFile
from django.core.files.base import ContentFile
from django.utils.text import get_valid_file... |
import time
import board
import neopixel
import adafruit_fancyled.adafruit_fancyled as fancy
import random
# On CircuitPlayground Express, and boards with built in status NeoPixel -> board.NEOPIXEL
# Otherwise choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D1
pixel_pin = board.D0
# On ... |
"""
Geographic coordinate conversion.
"""
import numpy as np
from . import get_ellipsoid
def geodetic_to_spherical(longitude, latitude, height):
"""
Convert from geodetic to geocentric spherical coordinates.
The geodetic datum is defined by the default :class:`harmonica.ReferenceEllipsoid`
set by th... |
import time
import os.path as osp
import itertools
import argparse
import wget
import torch
from scipy.io import loadmat
from torch_scatter import scatter_add
from torch_sparse.tensor import SparseTensor
short_rows = [
('DIMACS10', 'citationCiteseer'),
('SNAP', 'web-Stanford'),
]
long_rows = [
('Janna', ... |
##
## 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... |
import time
import torch
from model import TextClassificationModel, summary
from torchtext.datasets import AG_NEWS
from torchtext.data.utils import get_tokenizer
from collections import Counter
from torchtext.vocab import Vocab
from torch.utils.data import DataLoader
from torch.utils.data.dataset import random_split
... |
import json
from pprint import pprint
from movie_data import MovieData,Chat
import pickle
data=''
with open('train_data.json') as f:
data = json.load(f)
key=''
movie={}
tot=0
document_keys=['plot','review','comments']
other_keys=['movie_name','spans','chat']
w2i={}
i2w={}
dic_freq={}
w2i['<PAD>']=0... |
import math
import torch
from torch import nn
import torch.distributed as dist
import deepspeed
from deepspeed.utils import log_dist
from fairseq import tasks, distributed_utils
from fairseq.logging import metrics
from examples.training.deepspeed.ds_fairseq_data import BatchIterator
from examples.training.deepspeed.d... |
"""
A Python library to interface with FastFEC.
This library provides methods to
* parse a .fec file line by line, yieling a parsed result
* parse a .fec file into parsed output .csv files
"""
import contextlib
import os
import pathlib
from ctypes import CDLL, c_char_p, c_int, c_void_p
from queue import Queue
fro... |
import cv2
import numpy as np
import os
import glob
def calibrate():
CHECKERBOARD = (6,9)
subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW
objp = np.... |
import sys
import re
import requests
import os
import dateutil.parser
from colors import *
from caching import get_cached_user_list, get_cached_repo_list, cache_user_list, cache_repo_list, CACHING_ACTIVE
MAX_PAGES = 5
user_url = 'https://api.github.com/users/{user}'
usr_repos_url = 'https://api.github.com/users/{use... |
# -*- coding: future_fstrings -*-
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# This file is part of Salus
# (see https://github.com/SymbioticLab/Salus).
#
# 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 Lice... |
#! /bin/env python
import sys, os
import PIL
import numpy as np
from scipy import ndimage, misc
from copy import copy
from matplotlib.pyplot import plot, show
# Module to compute the area of an irregulare, closed, convex polygon.
# The x and y vectors are the vertices ; the last should equal the first
def poly_area(... |
# # @package elementpropertiesvalidation
# This module exists to pair with element.py and validate anything that is
# being attempted to set as a value for one of an Element's properties
from . import content_options as content
# used for tuplifying
import string
import ast
# # A listing of the available options fo... |
'''
Menus in the IM window.
'''
import traceback
import wx
from common import pref
import gui.toolbox
from gui import clipboard
# Create all the menu items for each button in the capabilities bar.
buttons = [('info', _('Buddy Info')),
('im', _('Send IM')),
('files', _('Send File')),... |
from typing import Optional
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.db.models import Case, Count, IntegerField, Prefetch, Value, When
from recruitment.filters import InstructorRecruitmentFilter
from recruitment.forms import InstructorRecruitmentCreat... |
"""Credit to <NAME>:
https://github.com/MilesCranmer/easy_normalizing_flow/blob/master/flow.py
"""
import torch
from torch import nn, optim
from torch.functional import F
import numpy as np
####
# From Karpathy's MADE implementation
####
DEBUG = False
class MaskedLinear(nn.Linear):
""" same as Linear except has... |
#!/usr/bin/env python3
"""
Run a command after assuming an IAM role.
Your own credentials must have authorization to obtain temporary tokens
from the AWS Security Token Service (STS) for the given role.
"""
from os import environ
from typing import Dict, List, TypedDict, cast
# IAM roles always allow at least one ho... |
# Problem 2.0
class Planet:
"""Representation of a planet.
Attributes:
url (str): identifier/locator
name (str): planet name
rotation_period (int): rotation period
orbital_period (int): orbital period
diameter (int): diameter of the planet
climate (list): climate ... |
#!/usr/bin/python3
'''
ZBLL Case Sorter
Sorts all ZBLL cases for the last layer of a Rubik's cube.
Created on 03 Mar 2015
Copyright (c) 2015 <NAME> and Sylvermyst Technologies
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files ... |
# Copyright (c) 2015-2021, <NAME>
# License: MIT License
from typing import Dict, List, Sequence, Tuple
from ezdxf.math import Vec2
from ._iso_pattern import ISO_PATTERN
# Predefined hatch pattern prior to ezdxf v0.11 were scaled for imperial units,
# and were too small for ISO units by a factor of 1/25.4, to replicat... |
from abc import abstractmethod
from copy import deepcopy
from dataclasses import dataclass
from datetime import datetime
from typing import Dict, List, Mapping
from objects.order import Order
# random.seed(1234)
# np.random.seed(1234)
# torch.manual_seed(1234)
# torch.cuda.manual_seed_all(1234)
# torch.backends.cudn... |
"""Unit tests for simple helpers should go here."""
import os
import pytest
from scripts.get_version import strip_dep_version
from scripts.build_wheel import (
collect_setup_entries,
sort_by_dependency,
transitive_deps,
strip_types_prefix,
BuildData,
SUFFIX,
PY2_SUFFIX,
)
def test_strip_t... |
import itertools
import math
class Point(object):
def __init__(self, *args):
if len(args) == 2:
self.x = args[0]
self.y = args[1]
elif len(args) == 1:
if isinstance(args[0], Point):
self.x = args[0].x
self.y = args[0].y
... |
from sqlite3 import Connection
from tempfile import TemporaryDirectory
from typing import Dict, Any, Tuple, List
from .const import GET_VOICES_BY_LANGUAGE, INIT_DATABASE, INLINE_OPTION
import json
def get_payload(voice: Tuple[str, str, str, int], text):
retval1 = (
("Language", voice[1]),
("Voice"... |
from matplotlib import pyplot as plt
from CHECLabPy.utils.mapping import get_tm_mapping, get_clp_mapping_from_version
from CHECLabPy.plotting.camera import CameraImage
from matplotlib.patches import Rectangle, Circle
from matplotlib.collections import PatchCollection
import numpy as np
from ctapipe.image.toymodel impor... |
import numpy as np
import configparser, os
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.decomposition import PCA
from pdb import set_trace
from utmLib import utils
from utmLib.ml.potential import CLG
from transforms import *
def pca_analysis(data, percentiles):
D = data.s... |
#!/usr/bin/env python
import os
#os.chdir('/home/travis/build/erdc/proteus/air-water-vv/2d/caissonBreakwater/sliding')
import pytest
from proteus.iproteus import *
from proteus import Comm
comm = Comm.get()
#import tank_so
#import tank
import numpy as np
import collections as cll
import csv
from proteus.test_utils imp... |
import numpy as np
from vg.compat import v2 as vg
__all__ = [
"rectangular_prism",
"cube",
"triangular_prism",
]
def _maybe_flatten(vertices, faces, ret_unique_vertices_and_faces):
if ret_unique_vertices_and_faces:
return vertices, faces
else:
return vertices[faces]
def rectangu... |
import math
import random
import numpy as np
from util.data_util import pad_seq, pad_char_seq, pad_video_seq
class TrainLoader:
def __init__(self, dataset, visual_features, configs):
super(TrainLoader, self).__init__()
self.dataset = dataset
self.visual_feats = visual_features
self... |
"""A collection of web-service-related helper/utility functions.
"""
import logging
import os.path
import traceback
import xml.etree.ElementTree as ET
from urllib.error import HTTPError
from urllib.request import urlopen
import tensorflow as tf
from .. import constants
from ..saber import Saber
from ..utils import ge... |
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from ecg_classify.constants import FEATURE_NUM
from ecg_classify.gen_data import gen_label,... |
"""
对模型各个部分的一个调用工厂模块
"""
import torch
from .backbones import resnet_dcn
from .backbones import mnet
from .backbones import hrfeatnet
from .headers import common
from .framework import fairmot
from .framework import hrfairmot
_backbone_model_factory = {
"resdcn": resnet_dcn.get_pose_net,
"gridnet... |
"""@file cluster_toolkit.py
Modeling using cluster_toolkit
"""
# Functions to model halo profiles
import numpy as np
import cluster_toolkit as ct
from . import func_layer
from . func_layer import *
from .parent_class import CLMModeling
from .. utils import _patch_rho_crit_to_cd2018
from .. cosmology.cluster_toolki... |
import paddle.fluid.dataloader as data
import paddle
from PIL import Image
import os
import os.path
import numpy as np
import random
from numpy.random import randint
from opts import parser
args = parser.parse_args()
class VideoRecord(object):
def __init__(self, row):
self._data = row
@property
d... |
# URL database management. Shared among all the sources and the
# scraper controller.
#
# Copyright © 2014 <NAME>
#
# 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/lice... |
# *****************************************************************
# Copyright 2013 MIT Lincoln Laboratory
# Project: SPAR
# Authors: jch
# Description: Tests for spar_variables.py
#
# Modifications:
# Date Name Modification
# ---- ---- ---... |
import json as JSON
import codecs
from argparse import ArgumentParser
from sys import stdout,stdin,stderr
scriptArgs = ArgumentParser()
scriptArgs.add_argument("--inputs",nargs='*',help="File containing a JSON list of JSON annotation objects.")
scriptArgs.add_argument("--output",help="Output file which will hav... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/12 17:10
# @Author : 云帆
# @Site :
# @File : train_seq2seq.py
# @Software: PyCharm
import dataset
import argparse
from seq2seq import EncoderLayer, DecoderLayer, AttentionLayer, Seq2Seq
import torch
import torch.optim as optim
import torch.nn as... |
"""Implement some video clip transformation."""
import random
import math
from PIL import Image
import numpy as np
from .utils import crop, resize
from mindspore.dataset.vision import py_transforms as VPT, Inter
# from mindspore.dataset.transforms import py_transforms as TPT
class Compose:
def __init__(self, tran... |
from data_facility_admin.models import Dataset, DataProvider, Category, Keyword
from collections import namedtuple
import json
import logging
logger = logging.getLogger(__name__)
FieldMapping = namedtuple('FieldMapping', ['dataset', 'gmeta', 'to_model', 'to_json'])
DATA_CLASSIFICATION_MAPPING = [
FieldMapping(Da... |
import pandas as pd
import streamlit as st
from keras.models import load_model
from embeddings import One_Hot_Encoder
from PIL import Image
import pickle
import xgboost as xgb
categorical_columns = [
"Country",
"Sector",
"Activity",
"Local Currency",
]
low_risk_image = Image.open('images/lowrisk.JPG')
... |
'''Functional graph analysis tools
'''
from pathlib import Path
import json
import hashlib
import logging
import re
import abc
import types
import typing as T
import pprint
import networkx as nx
from pymaybe import Nothing
from .. import toolz as _
from .. import logging
log = logging.new_log(__name__)
class _grap... |
# encoding: utf-8
'''
组合策略测试
'''
import sys
sys.path.append('../../')
from vnpy.app.cta_strategy.strategies.strategyMulti import MultiStrategy
import argparse
import pandas as pd
import numpy as np
from datetime import datetime
from setup_logger import setup_logger
setup_logger(filename='logsBackTest/vnpy_{0}.log'.fo... |
# COMP3620/6320 Artificial Intelligence
# The Australian National University - 2018
# <NAME>, <NAME>, <NAME> ({<EMAIL>,<EMAIL>)
""" This file defines the class Encoding, which all encodings in the system
will extend. This contains methods for adding clauses and variables
to the encoding, generating CNF files f... |
import logging
import time
import requests
import json
import collections
from flair_api import make_client, EmptyBodyException, ApiError
from flair.structures.structure import Structure
from flair.vents.vent import Vent
from flair.pucks.puck import Puck
from flair.rooms.room import Room
from flair.hvac_units.hvac_uni... |
#This file plots the positivity rate (=true positives) and the frequency in each class in a boxplot and a histogram after platt scaling.
import sparsechem as sc
import numpy as np
import argparse
import scipy
import pandas as pd
import matplotlib.pyplot as plt
import math
import scipy.stats as sci
import matplotlib.gr... |
import numpy as np
import torch
from baselines.common.vec_env import VecEnvWrapper
from gym import spaces, ActionWrapper
from envs.ImageObsVecEnvWrapper import get_image_obs_wrapper
from envs.ResidualVecEnvWrapper import get_residual_layers
from pose_estimator.utils import unnormalise_y
class PoseEstimatorVecEnvWrap... |
# -*- coding: utf-8 -*-
"""
Convert a Python expression in a LaTeX formula
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import ast
import sys
import six
try:
from woc.latexcore import LatexVisitor, preprocessing, simplify, \
uprint, replace_scientific
from ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 3 17:58:37 2018
@author: Basil
"""
import matplotlib.pyplot as plt
import gc
import numpy
import scipy.special
from LightPipes import cm, mm, nm
import PropogationFunctions
import PlotFunctions
import namedtuplesAxiconTF
import SaveLoad
def Normalized(v, n = 0):
... |
#!/usr/bin/env python3
# Controlling my Govee H6002, Bluetooth name of "ihoment_H6002_A18B"
# TODO support more than one light, if I ever get another one
import datetime
import logging
import sys
import time
from functools import reduce
from operator import xor
import astral
import click
import pexpect
LIGHT = "7C:A6... |
import logging
import torch
import torch.cuda.amp as amp
import torch.distributed as dist
from torchkit.util.utils import AverageMeter, Timer
from torchkit.util.utils import adjust_learning_rate, warm_up_lr
from torchkit.util.utils import accuracy_dist
from torchkit.util.distributed_functions import AllGather
from tor... |
from enum import Enum
import numpy as np
from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate
from qiskit.circuit import Gate
from qiskit.circuit import QuantumRegister
def gen_predefined_payoffs(game_name: str, num_players: int, payoff_input: dict):
"""Generate... |
from django.db import models
from projectmanagent.models.general import ProjectManager
from jsonfield import JSONField
# Create your models here.
class InterfaceModule(models.Model):
"""
项目模块的模型
"""
name = models.CharField(max_length=20, verbose_name="name", help_text="模块名")
top = m... |
import sys, os, glob, argparse
import pkg_resources
import snakemake
from . import _program
import yaml, json
logo = """
_______ _______ _______ _______
| || _ || || |
|_ _|| |_| || || _ |
| | | || || | | |
| | | || _|| |_| |
| | | ... |
import re
import os
import json
from . import normalizer, parser, spec, typescript, makestubs
def run(source_dir, out_dir, version):
r = _Runner(source_dir, out_dir, version)
r.run()
##
class _Runner:
def __init__(self, source_dir, out_dir, version):
self.source_dir = source_dir
self.ou... |
"""
This file is part of the package FUNtoFEM for coupled aeroelastic simulation
and design optimization.
Copyright (C) 2015 Georgia Tech Research Corporation.
Additional copyright (C) 2015 <NAME>, <NAME> and <NAME>.
All rights reserved.
FUNtoFEM is licensed under the Apache License, Version 2.0 (the "License");
you ... |
#-*- coding:utf-8 -*-
import numpy as np
import spiceminer as sm
def _stamp_angles_falloff(angles, falloff, resolution):
falloff = np.vectorize(falloff, otypes=[float])
m, n = resolution
d_phi = 2 * np.pi / float(m)
d_theta = np.pi / float(n)
stamp_shape = [
int(angles[1] / d_theta) * 2 ... |
"""Utility script to mock models for testing."""
from typing import List
import sclblonnx as so
from onnx import helper as xhelp
import sclblonnx._globals as glob
import numpy as np
import click
def create_stub_onnx_model(
onnx_model_path: str, output_path: str, dynamic_shape_values: dict
):
"""Cr... |
import boto3
from datetime import datetime
import hashlib
import json
import os
import random
import time
def get_value_from_ssm(env_var:str) -> str:
return ssm_client.get_parameter(Name=os.getenv(env_var, None))['Parameter']['Value']
# Boto3 Clients
s3_client = boto3.client('s3')
sns_client = boto3.client('sns')... |
import sys
from decimal import *
import codecs
tag_set = set()
word_set = set()
def parse_traindata():
fin = "model/hmmmodel.txt"
output_file = "outputs/hmmmoutput.txt"
transition_prob = {}
emission_prob = {}
tag_list = []
tag_count ={}
global tag_set
try:
input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.