text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
# Copyright 2008-2018 Univa 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... |
import os, sys, time, shutil, argparse
from functools import partial
import pickle
sys.path.append('../')
import torch
import torch.nn as nn
from torch.autograd import Variable
from torchvision import datasets, transforms
#import torchvision.models as models
import torch.optim as optim
import torch.nn.parallel
import t... |
# -*- coding: utf-8 -*-
# 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... |
import requests as reqlib
import os
import re
import random
import time
import pickle
import abc
import hashlib
import threading
from urllib.parse import urlparse
from purifier import TEAgent
from purifier.logb import getLogger
from enum import IntEnum
from typing import Tuple, List, Dict, Optional
cl... |
"""
## ## ## ## ##
## ## ##
## ## ##
## ## ## ## ## ##
## ##
## ##
##
AUTHOR = <NAME> <<EMAIL>>
"""
import sys
import boto3
import click
import threading
from botocore.exceptions import ClientError
from secureaws import checkaws
from secureaws ... |
# ============================================================================
# FILE: kind.py
# AUTHOR: <NAME> <Shougo.Matsu at g<EMAIL>>
# License: MIT license
# ============================================================================
import json
import typing
from pathlib import Path
from defx.action import Ac... |
#!/usr/bin/python
# Copyright (c) 2018, 2019, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for ... |
from copy import deepcopy
from numba import jit,njit
import numpy as np
import pymctdh.opfactory as opfactory
from pymctdh.cy.sparsemat import CSRmat#,matvec
@njit(fastmath=True)
def matvec(nrows,IA,JA,data,vec,outvec):
"""
"""
d_ind = 0
for i in range(nrows):
ncol = IA[i+1]-IA[i]
for... |
# Copyright (c) 2020 DeNA Co., Ltd.
# Licensed under The MIT License [see LICENSE for details]
# kaggle_environments licensed under Copyright 2020 Kaggle Inc. and the Apache License, Version 2.0
# (see https://github.com/Kaggle/kaggle-environments/blob/master/LICENSE for details)
# wrapper of Hungry Geese environment... |
import csv
import sys
from pathlib import Path
from abc import abstractmethod
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import common.tf_utils as tf_utils
import metrics.manager as metric_manager
from common.model_loader import Ckpt
from common.utils import format_text
from common.utils import ... |
"""
All the data sources are scattered around the D drive, this script
organizes it and consolidates it into the "Data" subfolder in the
"Chapter 2 Dune Aspect Ratio" folder.
<NAME>, 5/6/2020
"""
import shutil as sh
import pandas as pd
import numpy as np
import os
# Set the data directory to save files ... |
import tensorflow as tf
import numpy as np
import unittest
from dnc.controller import BaseController
class DummyController(BaseController):
def network_vars(self):
self.W = tf.Variable(tf.truncated_normal([self.nn_input_size, 64]))
self.b = tf.Variable(tf.zeros([64]))
def network_op(self, X):... |
import json
import os
import shutil
import urllib.request
import traceback
import logging
import psutil
from collections import defaultdict
from typing import List, Dict, Tuple
from multiprocessing import Semaphore, Pool
from subprocess import Popen, PIPE
from datetime import datetime, timedelta
from lxml import etree... |
import inspect
import pytest
import numpy as np
from datar.core.backends.pandas import Categorical, DataFrame, Series
from datar.core.backends.pandas.testing import assert_frame_equal
from datar.core.backends.pandas.core.groupby import SeriesGroupBy
from datar.core.factory import func_factory
from datar.core.tibble im... |
import os
import rasterio
import argparse
from PIL import Image
import subprocess
import pathlib
import shutil
from glob import glob
from numba import njit, prange
from OpenVisus import *
### Configuration
ext_name = ".tif"
dtype = "uint8[3]"
limit = 1000
###--------------
@njit(parallel=True)
def... |
# 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... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# [0,0] = TN
# [1,1] = TP
# [0,1] = FP
# [1,0] = FN
# cm is a confusion matrix
# Accuracy: (TP + TN) / Total
def accuracy(cm: pd.DataFrame) -> float:
return (cm[0,0] + cm[1,1]) / cm.sum()
# Precision: TP / (TP + FP)
de... |
"""
color_scheme_matcher.
Licensed under MIT.
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... |
import math
import random
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from fmt.pythonfmt.doubleintegrator import filter_reachable, gen_trajectory, show_trajectory
from fmt.pythonfmt.world import World
def dist2(p, q):
return math.sqrt((p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2)
# FM... |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
import scipy
ROWS = 64
COLS = 64
CHANNELS = 3
TRAIN_DIR = 'Train_data/'
TEST_DIR = 'Test_data/'
train_images = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR)]
test_images = [TEST_DIR+i for i in os.listdir(TEST_DIR)]
def read_image(file_path):
... |
# 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, overload
from ... import _utilities
fro... |
##########################################################################
#
# Copyright (c) 2019, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... |
""" GLSL shader generation """
from utils import Stages, getHeader, getShader, getMacro, genFnCall, fsl_assert, get_whitespace
from utils import isArray, getArrayLen, getArrayBaseName, getMacroName, DescriptorSets, is_groupshared_decl
import os, sys, importlib, re
from shutil import copyfile
def pssl(fsl, dst, rootSi... |
import argparse
import json
import base64
import hashlib
import sys
import binascii
from optigatrust.util.types import *
from optigatrust.pk import *
from optigatrust.x509 import *
private_key_slot_map = {
'second': KeyId.ECC_KEY_E0F1,
'0xE0E1': KeyId.ECC_KEY_E0F1,
'0xE0F1': KeyId.ECC_KEY_E0F1... |
from getnear.config import Tagged, Untagged, Ignore
from getnear.logging import info
from lxml import etree
import re
import requests
import telnetlib
def connect(hostname, *args, **kwargs):
url = f'http://{hostname}/'
html = requests.get(url).text
doc = etree.HTML(html)
for title in doc.xpath('//titl... |
# encoding: utf-8
import os
import ssl
import sys
import csv
import json
import time
import base64
from datetime import datetime
from datetime import timedelta
try:
import pyodbc
except ImportError:
pass
# PYTHON 2 FALLBACK #
try:
from urllib.request import urlopen, Request
from urllib.parse import... |
import spacy
from spacy.lang.ro import Romanian
from typing import Dict, List, Iterable
from nltk import sent_tokenize
import re
# JSON Example localhost:8081/spacy application/json
# {
# "lang" : "en",
# "blocks" : ["După terminarea oficială a celui de-al doilea război mondial, în conformitate cu discursul lu... |
import sys,os
from torch.autograd import Variable
import torch.optim as optim
from tensorboardX import SummaryWriter
import torch
import time
import shutil
from torch.utils.data import DataLoader
import csv
from samp_net import EMDLoss, AttributeLoss, SAMPNet
from config import Config
from cadb_dataset import CADBData... |
# --- Day 17: Trick Shot ---
import math
import time
def get_puzzle_input(filepath):
with open(filepath) as f:
for line in f:
# target area: x=269..292, y =-68..-44
parts = line.rstrip().replace(',', '').split()
[x1, x2] = parts[2][2:].split("..")
[y1, y2] =... |
'''
Contains the extended FastAPI router, for simplified CRUD from a model
'''
from typing import Any, List, Optional, Sequence, Set, Type, Union
import fastapi
from fastapi import Depends, params
from pydantic import BaseModel, create_model
from odim import Odim, OkResponse, SearchResponse
from odim.dependencies imp... |
#!/usr/bin/python3
# I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import re
import time
import requests
import random
import argparse
from urllib.parse import urlparse
from functools import partial
from colored import fg, bg, attr
from multiprocessing.dummy import... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#%matplotlib inline
import codecs
import lightgbm as lgb
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
# Read data
image_file_path = './simulated_dpc_d... |
#!/usr/bin/env python3
"""awspfx
Usage:
awspfx.py <profile>
awspfx.py [(-c | --current) | (-l | --list) | (-s | --swap)]
awspfx.py token [(-p | --profile) <profile>]
awspfx.py sso [(login | token)] [(-p | --profile) <profile>]
awspfx.py -h | --help
awspfx.py --version
Examples:
awspfx.py ... |
# -*- test-case-name: vumi.blinkenlights.tests.test_metrics_workers -*-
import time
import random
import hashlib
from datetime import datetime
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from twisted.internet import reactor
from twisted.internet.task import LoopingCall
... |
import dgl
import torch as th
import numpy as np
import itertools
import time
from collections import *
Graph = namedtuple('Graph',
['g', 'src', 'tgt', 'tgt_y', 'nids', 'eids', 'nid_arr', 'n_nodes', 'n_edges', 'n_tokens', 'layer_eids'])
# We need to create new graph pools for relative position atte... |
# 获取学生所有的挑战题目信息
# 包括时间、结果、代码等
# 写入数据库stuoj的stuquestionbh表中
from selenium import webdriver
# from selenium.webdriver.common.by import By
import pymysql
import re
from bs4 import BeautifulSoup
import connsql
# import loginzznuoj
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support impo... |
"""Temporal VAE with gaussian margial and laplacian transition prior"""
import torch
import numpy as np
import ipdb as pdb
import torch.nn as nn
import pytorch_lightning as pl
import torch.distributions as D
from torch.nn import functional as F
from .components.beta import BetaVAE_MLP
from .metrics.correla... |
###############################################################################
#
# 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 fi... |
import os
import sys
import signal
import asyncio
import json
import time
import traceback
import typing
import socket
import re
import select
import websockets
if sys.platform != "win32":
import termios
import tty
else:
import msvcrt
import win32api
from .. import api
from ..shared import constants, ... |
""" Functions for ionospheric modelling: see SDP memo 97
"""
import astropy.units as u
import numpy
from astropy.coordinates import SkyCoord
from data_models.memory_data_models import BlockVisibility
from processing_components.calibration.operations import create_gaintable_from_blockvisibility, \
create_gaintabl... |
#!/usr/bin/env python3.9
"""Tasks file used by the *invoke* command.
This simplifies some common development tasks.
Run these tasks with the `invoke` tool.
"""
from __future__ import annotations
import sys
import os
import shutil
import getpass
from glob import glob
from pathlib import Path
import keyring
import s... |
# -*- coding: utf-8 -*-
# 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... |
import numpy as np
from scipy.special import factorial
from itertools import permutations, product
from pysat.solvers import Minisat22, Minicard
from pysat.pb import PBEnc
from clauses import build_clauses, build_max_min_clauses
from clauses import build_permutation_clauses
from clauses import build_cardinality_lits,... |
from collections import defaultdict
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Tuple, Union
import networkx as nx
import onnx
from . import graph_ir as g
from .onnx_attr import get_node_shape, node_attr_to_dict, node_to_shape
PathLike = Union[str, Path]
GraphT = onnx.GraphProto
NodeT... |
import pygame
import random
import os
import time
import neat
import visualize
import pickle
import bcolors as b
pygame.font.init()
SCORE_MAX = [0, 0, 0]
WIN_WIDTH = 600
WIN_HEIGHT = 800
FLOOR = 730
STAT_FONT = pygame.font.SysFont("comicsans", 50)
END_FONT = pygame.font.SysFont("comicsans", 70)
DRAW_LINES = False
WI... |
#!/usr/bin/python
# Copyright 2018 GRAIL, 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 agr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import glob
import os
import pygame
import random
import subprocess
import time
import maze_map
MIN_MARGIN = 32
PROGRESS_BAR_HEIGHT = 8
SELF_DIR = os.path.dirname(os.path.realpath(__file__))
class Game:
def __init__(self, map_size: int, maze: bool... |
from typing import Union, List, Optional, Tuple, Set
from hwt.hdl.operator import Operator
from hwt.hdl.operatorDefs import AllOps
from hwt.hdl.portItem import HdlPortItem
from hwt.hdl.statements.assignmentContainer import HdlAssignmentContainer
from hwt.hdl.statements.codeBlockContainer import HdlStmCodeBlockContaine... |
"""A wrapper env that handles multiple tasks from different envs.
Useful while training multi-task reinforcement learning algorithms.
It provides observations augmented with one-hot representation of tasks.
"""
import random
import akro
import gym
import numpy as np
def round_robin_strategy(num_tasks, last_task=No... |
import numpy as np
np.random.seed(10)
import matplotlib.pyplot as plt
from mpi4py import MPI
# For shared memory deployment: `export OPENBLAS_NUM_THREADS=1`
# Method of snapshots
def generate_right_vectors(A):
'''
A - Snapshot matrix - shape: NxS
returns V - truncated right singular vectors
'''
ne... |
import html
import json
import re
from datetime import date
from autoslug import AutoSlugField
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.validators import MinLengthValidator
from django.db.models.aggregates import Count
from django.db import models
fr... |
"""Classes for use with Yambo
Representation of a spectrum.
Main functionality is to read from Yambo output, o.qp files
and also netcdf databases.
"""
import re
import copy as cp
import numpy as np
import asetk.atomistic.fundamental as fu
import asetk.atomistic.constants as atc
from . import cube
class Dispersion:
... |
class Node:
"""
A node class used in A* Pathfinding.
parent: it is parent of current node
position: it is current position of node in the maze.
g: cost from start to current Node
h: heuristic based estimated cost for current Node to end Node
f: total cost of present n... |
import threading
import traceback
import socketserver
import struct
import time
import sys
import http.client
import json
import uuid
import config
import dns.rdatatype
import dns.rdataclass
args = config.args
QTYPES = {1:'A', 15: 'MX', 6: 'SOA'}
custom_mx = uuid.uuid4().hex
# https://github.com/shuque/pydig GNUv2... |
# 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/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import os
import re
import glob
import argparse
import pandas as pd
list_test = ['alexnet',
'inception3',
'inception4',
'resnet152',
'resnet50',
'vgg16']
# Naming convention
# Key: log name
# Value: ([num_gpus], [names])
# num_gpus: Since each log... |
import re
import subprocess
import shutil
import sys
import json
import argparse
from typing import List, NamedTuple, Optional, Sequence
PATTERN_IMPORT_TIME = re.compile(r"^import time:\s+(\d+) \|\s+(\d+) \|(\s+.*)")
class InvalidInput(Exception):
pass
class Import(dict):
def __init__(self, name: str, t_s... |
import csv
import collections
import pandas as pd
from random import shuffle
from tqdm import tqdm
def get_all_tokens_conll(conll_file):
"""
Reads a CoNLL-2011 file and returns all tokens with their annotations in a dataframe including the original
sentence identifiers from OntoNotes
"""
all_toke... |
import enum
from typing import Any, Dict
from jashin.dictattr import *
def test_dictattr() -> None:
class Test:
field1 = ItemAttr[str]()
field2 = ItemAttr[str](name="field_2")
field3 = ItemAttr[str](default="default_field3")
def __dictattr_get__(self) -> Dict[str, Any]:
... |
# Copyright 2022 Quantapix 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 applicable l... |
#! /usr/bin/env python3.5
# vim:ts=4:sw=4:ai:et:si:sts=4
import argparse
import json
import re
import os
import uuid
import shutil
import sys
import requests
filterRe = re.compile(r'(?P<block>^%=(?P<mode>.)?\s+(?P<label>.*?)\s+(?P<value>[^\s\n$]+)(?:\s*.*?)?^(?P<section>.*?)^=%.*?$)', re.M | re.S)
subItemRe = re.com... |
import numpy as np
import torch
from torch import optim
from torch.nn import functional
import torch.nn as nn
import torch.utils.data
from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,Sigmoid
from torch.nn import functional as F
from opendp.smartnoise.synthesizers.base import SDGYMB... |
from __future__ import annotations
import disnake
from disnake.ext import commands
from typing import TYPE_CHECKING
from src.utils.utils import EmbedFactory, ExitButton, SaveButton, add_lines, get_info
if TYPE_CHECKING:
from src.utils import File
def clear_codeblock(content: str):
content.strip("\n")
... |
import discord, sqlite3, asyncio, utils, re
from discord.ext import commands
from datetime import datetime
TIME_REGEX = re.compile("(?:(\d{1,5})\s?(h|hours|hrs|hour|hr|s|seconds|secs|sec|second|m|mins|minutes|minute|min|d|days|day))+?")
TIME_DICT = {"h": 3600, "s": 1, "m": 60, "d": 86400}
class TimeConverter... |
# Python script uses flask and SQL alchemy to create API requests for weather data from Hawaii.
# Import dependencies.
import numpy as np
import datetime as dt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask impo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2022 HalfMarble LLC
# Copyright 2019 <NAME> <<EMAIL>>
from hm_gerber_tool.cam import FileSettings
import hm_gerber_tool.rs274x
from hm_gerber_tool.gerber_statements import *
from hm_gerber_ex.gerber_statements import AMParamStmt, AMParamStmtEx, ADParamStmtEx
f... |
import numpy as np
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql as psql
from sqlalchemy.orm import relationship
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.schema import UniqueConstraint
from astropy import units as u
from .core import Base
from .constants import APER_KEY, A... |
"""
VKontakte OpenAPI and OAuth 2.0 support.
This contribution adds support for VKontakte OpenAPI and OAuth 2.0 service in the form
www.vkontakte.ru. Username is retrieved from the identity returned by server.
"""
from django.conf import settings
from django.contrib.auth import authenticate
from django.utils import s... |
from importlib import import_module
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from django.template import loader
from django.utils.text import slugify
from django.utils import timezone
from revers... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2020/5/27 21:18
# @author : Mo
# @function: 统计
from text_analysis.utils.text_common import txt_read, txt_write, load_json, save_json, get_all_dirs_files
from text_analysis.conf.path_log import logger
from collections import Counter
from typing import List, Dict... |
import ctypes
import threading
from functools import partial
from contextlib import nullcontext
from copy import deepcopy
import multiprocessing as mp
from itertools import zip_longest
from typing import Iterable
import torch
import torch.nn as nn
import torch.utils.data
import torch_xla.core.xla_model as xm
import to... |
import os
from contextlib import ExitStack
from pathlib import Path
import pytest
from synctogit.git_factory import GitError, git_factory
def remotes_dump(remote_name, remote):
# fmt: off
return (
"%(remote_name)s\t%(remote)s (fetch)\n"
"%(remote_name)s\t%(remote)s (push)"
) % locals()
... |
# Pathfinding algorithm.
import pygame
import random
class HotTile( object ):
def __init__( self ):
self.heat = 9999
self.cost = 0
self.block = False
class HotMap( object ):
DELTA8 = [ (-1,-1), (0,-1), (1,-1), (-1,0), (1,0), (-1,1), (0,1), (1,1) ]
EXPENSIVE = 9999
def __init__... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 3 17:20:06 2018
@author: chrispedder
A routine to crop sections from the images of different manuscripts in the two
datasets to the same size, and with the same magnification, so that the average
script size doesn't create a feature that the neura... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python3 -m pip install --force -U --user PlexAPI
"""
Metadata to be handled:
* Audiobooks
* Playlists -- https://github.com/pkkid/python-plexapi/issues/551
"""
import copy
import json
import time
import logging
import collections
from urllib.parse import urlparse
... |
import attr
import types
from typing import Union
from enum import Enum
import numpy as np
from scipy.optimize import differential_evolution
import pygmo as pg
class OptimizationMethod(Enum):
"""
Available optimization solvers.
"""
SCIPY_DE = 1
PYGMO_DE1220 = 2
@attr.s(auto_attribs=True)
class S... |
from sly import Lexer
from sly import Parser
import sys
#--------------------------
# While Loop
# Del Var
# Print stmt
# EQEQ, LEQ
#--------------------------
#=> This version has parenthesis precedence!
class BasicLexer(Lexer):
tokens = { NAME, NUMBER, STRING, IF, FOR, PRINT, CREATEFILE, WRITE, EQEQ,... |
#!/usr/bin/env python3
"""
dycall.exports
~~~~~~~~~~~~~~
Contains `ExportsFrame` and `ExportsTreeView`.
"""
from __future__ import annotations
import logging
import pathlib
from typing import TYPE_CHECKING
import ttkbootstrap as tk
from ttkbootstrap import ttk
from ttkbootstrap.dialogs import Messagebox
from ttkbo... |
"""
Author: <NAME> - <EMAIL>
Description: Transplant from "https://github.com/xunhuang1995/AdaIN-style/blob/master/train.lua"
"""
import functools
import os
from collections import OrderedDict
import torch
import torch.nn as nn
from torchvision.models import vgg19
from datasets.utils import denorm
from mo... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from skimage import draw
from skimage import measure
from astropy.io import fits
from astropy import units as u
from astropy import wcs, coordinates
from scipy.ndimage.filters impor... |
"""Calculate pixel errors for a single run or all runs in an experiment dir."""
import torch
import itertools
import numpy as np
import imageio
import argparse
import os
import glob
from model.main import main as restore_model
from model.utils.utils import bw_transform
os.environ["CUDA_VISIBLE_DEVICES"] = '-1'
def... |
"""
Module that defines Corpus and DocumentSource/DocumentDestination classes which access documents
as lines or parts in a file.
"""
import json
from gatenlp.urlfileutils import yield_lines_from
from gatenlp.document import Document
from gatenlp.corpora.base import DocumentSource, DocumentDestination
from gatenlp.cor... |
import copy
from configuration.configuration import QuestionnaireConfiguration
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import F
from django.template.loader import render_to_string
from configuration.models import Configuration, Key, Value, Translati... |
#coding=utf-8
import matplotlib
matplotlib.use("Agg")
import tensorflow as tf
import argparse
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,MaxPooling2D,UpSampling2D,BatchNormalization,Reshape,Permute,Activation
from tensorflow.keras.utils imp... |
""" Support matrices generation.
radmtx module contains two class objects: sender and receiver, representing
the ray sender and receiver in the rfluxmtx operation. sender object is can
be instantiated as a surface, a list of points, or a view, and these are
typical forms of a sender. Similarly, a receiver object can b... |
import os
import json
from collections import OrderedDict
import pandas as pd
def write_json_to_file(json_data, json_file_path):
parsed = json.loads(json_data)
parsed = json.dumps(parsed, indent=4, sort_keys=True)
obj = open(json_file_path, 'w')
obj.write(parsed)
obj.close()
# replace " with ' ... |
#!/usr/bin/env python3
import sys
import os
import argparse
from string import Template
import re
# Patch site-packages to find numpy
import jinja2
if sys.platform.startswith("win"):
site_packages_path = os.path.abspath(os.path.join(os.path.dirname(jinja2.__file__), "../../../ext-site-packages"))
else:
site_packa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import argparse
import cv2 as cv
import numpy as np
import mediapipe as mp
from utils import CvFpsCalc
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--device", type=int, default=0)
parser.add_argument("--width", help='c... |
"""
Clip rendering helpers.
"""
import vapoursynth as vs
from enum import Enum
from threading import Condition
from typing import BinaryIO, Callable, Dict, List, Optional, TextIO, Union
from concurrent.futures import Future
from functools import partial
from .progress import Progress, BarColumn, FPSColumn, TextColumn... |
"""
A set of functions for extracting header information from PSG objects
Typically only used internally in from unet.io.header.header_extractors
Each function takes some PSG or header-like object and returns a dictionary with at least
the following keys:
{
'n_channels': int,
'channel_names': list of strings,... |
# -*- coding: utf-8 -*-
# Copyright (c) 2011,2014 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import io
import onnx
import torch
import torch.onnx.symbolic_helper as sym_help
import torch.onnx.symbo... |
#!/usr/bin/env python
import rospy as rp
import numpy as np
import math as math
from geometry_msgs.msg import PoseStamped, TwistStamped
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
from std_msgs.msg import Int32
'''
This node will publish waypoints from the car's current position to some... |
"""Test the module SMOTE ENN."""
# Authors: <NAME> <<EMAIL>>
# <NAME>
# License: MIT
import pytest
import numpy as np
from sklearn.utils.testing import assert_allclose, assert_array_equal
from imblearn.combine import SMOTEENN
from imblearn.under_sampling import EditedNearestNeighbours
from imblearn.over_sam... |
# =========================================================================== #
# DATA EXPLORER #
# =========================================================================== #
# =========================================================================== #
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-1728-Cat-and-Mouse-II.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-05-10
==================================... |
# vim:ts=4 sw=4 expandtab softtabstop=4
from jsonmerge.exceptions import HeadInstanceError, \
BaseInstanceError, \
SchemaError
import jsonschema
import re
class Strategy(object):
"""Base class for merge strategies.
"""
def merge(self, walk,... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import numpy as np
import scipy.sparse as sparse
import defenses
import upper_bounds
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import integrate, optimize
from scipy.signal import savgol_filter
from dane import population as popu
dias_restar = 4 # Los últimos días de información que no se tienen en cuenta
dias_pred = 31 # Días sobre los cuáles se hará la predic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.