text stringlengths 3.07k 22.1k |
|---|
#-*- coding: utf-8 -*-
import html
import json
import re
import os
from urllib import parse
from Doraemon.Requests import requests_dora
from tqdm import tqdm
def get_album_list(sin, ein):
url = "https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg"
header = {
"user-agent": "Mozilla/5.0 (Windows... |
# Copyright 2021 NVIDIA 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 writi... |
import math
import random
import torch
from torch.nn import Parameter, ParameterList
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from IPython.core.debugger import set_trace
ZONEOUT = 0.01
DEVICES = ["CPU", "GPU"]
RNN_TYPES = ["LSTM",... |
#用例加载
# 1、完成从数据库用例用例数据
# 2、添加基础测试项
# 3、格式化用例到yml格式文件
from django.core.exceptions import ObjectDoesNotExist
from ApiManager.models import TestCaseInfo
import ast,os,re,copy
def load_case_data(index, base_url):
config = {
'config': {
'name': '',
'request': {
'base_ur... |
from flask import Flask, request, jsonify, make_response
from flask_restplus import Api, Resource, fields
import csv
import os
import torch.nn as nn
import torch
import numpy as np
from nltk.corpus import stopwords
import string
import sys
csv.field_size_limit(sys.maxsize)
#-------------------------------------flas... |
#!/usr/bin/env python
# coding: utf-8
# Author: <NAME>
# # Data preparation
# In[3]:
import math
import random
import h5py
import copy
import numpy as np
from matplotlib import pyplot
from pandas import read_csv
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils import shuffle
from sklearn.preproce... |
import unittest
from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
from pymatgen.core.tensors import Tensor
from pymatgen.analysis.elasticity.strain import Strain, Deformation, \
convert_strain_to_deformation, DeformedStructureSet
from pymatgen.util.testing import PymatgenTest
... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
bool_or_none,
ExtractorError,
dict_get,
float_or_none,
int_or_none,
remove_end,
str_or_none,
try_get,
url_or_none,
urljoin,
)
class GettrBaseIE(InfoExtractor):
_... |
import os
import sys
import argparse
import logging
import functools
import struct
import service
import toolbox
import components.simplecache
import riscv.execute
import riscv.syscall.linux
def fetch_block(service, state, addr):
_blockaddr = state.get('l1dc').blockaddr(addr)
_blocksize = state.get('l1dc').nb... |
#!/usr/bin/python
# coding: utf-8 -*-
# (c) 2013, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = '''
---
module: subnet
short_description: Add/Remove subnet to an OpenStack network
author: OpenStack Ansible SIG
description:
- Add or Rem... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
import clr
import time
# Needed for the use of Decimal class of c#. Requires clr to import System in
# this way.
from System import Decimal
clr.AddReference("System")
clr.AddReference("./libs/kinesis/Thorlabs.MotionControl.De... |
import examples.tree_search as ts
import examples.tree_search.evaluation_scenarios as scenarios
import gym
import numpy as np
import pytest
from botbowl import Square, Action, ActionType, botbowl
from examples.tree_search import hashmap
from more_itertools import first
from pytest import approx
from tests.util import g... |
#Documentation: https://sefiks.com/2019/02/13/apparent-age-and-gender-prediction-in-keras/
import numpy as np
import cv2
from keras.models import Model, Sequential
from keras.layers import Input, Convolution2D, ZeroPadding2D, MaxPooling2D, Flatten, Dense, Dropout, Activation
from PIL import Image
from keras.pre... |
import math
from modules.graph_data import GraphData
from modules.gas_table_data import TableData
import modules.graph_save_data as gs
def add_variables(f):
for i in range(1, f.v["i_int"] + 2):
f.add_variable("pt1F_" + s(i), 1.0, "")
f.add_variable("pt1D_ср" + s(i), 1.0, "")
f.add_variable... |
#-*-coding:utf-8-*-
import sys
# sys.path.append('..')
from readcard import *
from code_generate_model import *
from resolve_data import *
#from model.python_gen.code_generate_model import code_gen_model as gen_func
#from model.python_var.code_generate_model import code_gen_model as gen_var
import os
import tensorflow ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 6 14:09:32 2020
@author: <NAME>
@email: <EMAIL>
File to do a scatter plot of the tautomerization energy.
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy import stats
import pandas as pd
file_QM9 = pd... |
import json
import requests
import logging
import base64
from docxtpl import DocxTemplate
from bs4 import BeautifulSoup
from Queue import Queue
from threading import Thread
from xml.sax.saxutils import escape
import argparse
#try:
# from http.client import HTTPConnection # py3
#except ImportError:
# from httplib... |
import os
import pygame
from player import Ball
from world import World, load_level
from texts import Text, Message
from button import Button, LevelButton
pygame.init()
WIDTH, HEIGHT = 192, 212
win = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
pygame.display.set_caption('Bounce')
clock = pygame.time.Clo... |
# -*- test-case-name: twext.who.test.test_expression -*-
##
# Copyright (c) 2013-2017 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... |
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition, ScreenManagerException
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.behaviors import ToggleButtonBehavior, FocusBehavior
from kivy.properties import (ObjectProperty,
... |
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. =
# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ful... |
## Centurion;
## Copyright (c) <NAME>, NitroSquare Gaming;
import math
from resources import *
from jukebox import *
from constants import *
from pie.physics import *
from pie.color import *
WEAPON_DESC = {'M3 Photon Pistol' : ['pistol', [[['Fires blasts of hard-light energy.',
'Reverse engineered from c... |
from pyon.public import Container, log, IonObject
from interface.objects import CouchStorage, ProcessDefinition
from pyon.ion.stream import StandaloneStreamSubscriber
from ion.services.dm.utility.granule_utils import time_series_domain
from seawater.gibbs import SP_from_cndr
from seawater.gibbs import cte
from numpy.t... |
#!/usr/bin/python
# Copyright: (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: bluecat_dnszone
shor... |
import matplotlib.pyplot as plt
import h5py
import wfdb
import numpy as np
import csv
import platform
import os
import glob
import numpy as np
import pandas as pd
from os.path import join
from biosppy.signals import ecg
from Helpers.Physionet import LoadFile, PhysionetConstants
from Helpers.Metrices import *
import Hel... |
import numpy as np
import pandas as pd
import descarteslabs as dl
LS = "landsat:LC08:01:RT:TOAR"
S2 = "sentinel-2:L1C"
def get_bands_from_platform(platform):
if platform == S2:
bands=["blue","green","red", "red-edge-2","nir","water-vapor","ndvi", "alpha"]
scales=[[0, 10000, 0, 1],
... |
"""Ralph CLI entrypoint"""
import json
import logging
import re
import sys
from inspect import signature
import click
from click_option_group import optgroup
from ralph.backends import BackendTypes
from ralph.defaults import (
CONVERTER_EDX_XAPI_UUID_NAMESPACE,
DEFAULT_BACKEND_CHUNK_SIZE,
ENVVAR_PREFIX,
... |
from django.apps import apps
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import connection
from protector.query import Query
ADD_PERMISSION_PERMISSION = 'add_permission'
VIEW_RESTRICTED_OBJECTS = 'view_restric... |
import argparse
import datetime
import os
import time
import paddle
import paddle.distributed as dist
import json
from pathlib import Path
from engine import train_one_epoch, evaluate
import utils
from dataset import CycleMLPdataset, build_transfrom
from losses import DistillationLoss, SoftTargetCrossEntro... |
"""
experimental hierarchical classifier using random forest in multiclass setting with feature selection
very similar to the hierarchical_learn.py script but with feature selection using feature importance
"""
from __future__ import print_function
import itertools
from time import time
import numpy as np
impor... |
#!/usr/bin/env python
from __future__ import print_function,division
import urllib2, json, argparse, sys
from collections import OrderedDict, defaultdict
from itertools import izip
def getAlleles(url):
"""
Sends a series of get-allele requests to the server url specified by the user, starting
with an allele id of 0... |
# -*- coding: utf-8 -*-
# Copyright FMR LLC <<EMAIL>>
# SPDX-License-Identifier: Apache-2.0
from enum import Enum
from typing import List, Optional, Tuple
from spock.backend.typed import SavePath
from spock.config import spock
class StrChoice(Enum):
option_1 = "option_1"
option_2 = "option_2"
class Faile... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# multiprocess SNMP poller and graphite sender
from multiprocessing import Process, Queue
import socket
import sys
import logging
import re
from fastsnmp import snmp_poller
from time import time, sleep
from collections import defaultdict
import urllib.parse
import urllib.requ... |
from pathlib import Path
import os
import socket
import sys
import sqlalchemy
from sqlalchemy import orm
from sqlalchemy.sql import func as sqlfunc
from sqlalchemy.orm import Session
import sqlalchemy.ext.declarative
from datetime import datetime
from typing import Optional, Callable, List
SqlAlchemyBase = sqlalchemy... |
from __future__ import print_function
import tensorflow as tf
from keras.datasets import cifar10
import image
from image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dropout, Activation, Conv2D, GlobalAveragePooling2D, merge, BatchNormalization
from keras.utils import np_utils
... |
import sys
import os
import traceback
from multiprocessing import connection
import _multiprocessing
import select
import subprocess
import time
from uitools.qt import Qt, QtCore, QtGui
from . import utils
NotSet = object()
INITED = 'INITED'
QUEUED = 'QUEUED'
BLOCKED = 'BLOCKED'
DEPENDENCY_FAILED = 'DEPENDENCY_FAI... |
import ctypes as C
import enum
from typing import Final
from astruct import typed_struct
from astruct.type_hints import *
from utils import CountedTable
from .fusioncompat import fusion_compat_name_for_id
@enum.unique
class ClassStatIndex(enum.IntEnum):
"""The indexes into various ClassOrItem arrays that corres... |
#!/usr/local/bin/python3.6
# vim: expandtab shiftwidth=4
# Copyright (C) 2019 National Institute of Informatics
#
# 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 own... |
"""
This module contains the implementation of block norms, i.e.
l1/l*, linf/l* norms. These are used in multiresponse LASSOs.
"""
from __future__ import print_function, division, absolute_import
import warnings
from copy import copy
import numpy as np
from . import seminorms
from ..identity_quadratic import identi... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os, errno
import xml.etree.ElementTree as ET
import tensorflow as tf
import copy
import cv2
from moviepy.editor import VideoFileClip
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
... |
#!/usr/bin/env python3
#
## @file
# edkrepo_cli.py
#
# Copyright (c) 2017 - 2020, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
import argparse
from operator import itemgetter
import sys
import traceback
import pkg_resources
import time
import json
import ... |
#!/usr/bin/env python3
"""
Supporting module for :mod:`esgfsearch`.
This class holds and maintains search result of ESGF dataset obtained
via RESTful API issued by :meth:`esgfsearch.ESGFSearch.doSearch`
method.
One instance of this class corresponds to one search result, and a
list of instances is set as the :attr:`e... |
#!/usr/bin/env python3
#
# PHP Exploitable Functions/Vars Scanner
# bl4de | github.com/bl4de | hackerone.com/bl4de
#
# pylint: disable=C0103
# //TODO:
# - allow to scan folder without subdirs
# - allow to scan files by pattern, eg. *.php
# - exclude 'echo' lines without HTML tags
"""
pef.py - PHP source code advanc... |
from pprint import pprint
import copy
import os.path
import pickle
import random
import time
import numpy
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import ShuffleSplit, Grid... |
## Import Module
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import io
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score
################################################################
## This is used to... |
import collections
import enum
import functools
import logging
import operator
import os
import requests
import tempfile
import typing
import numpy as np
from astropy.io import fits
from astropy.table import Table as Astropy_Table
from cloud_fits import exceptions
from cloud_fits.auth import aws as aws_auth
from clo... |
from copy import deepcopy
from random import shuffle, choice, seed
from ...classes import action, entity
from ...handlers import action_handler as ah, filehandler
last_stag_gen = -1
# Function assigns entities to one of the four mating pools based on thier
# fitness score.
# Also used to determine if a master has be... |
#! /usr/bin/eny python3
# coding: utf-8
import re
import requests
import http.cookiejar
from PIL import Image
import time, json,threading
from bs4 import BeautifulSoup
import mysql.connector
# 提交头数据
headers = {
"User-Agent": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0',
... |
from __future__ import absolute_import, division, print_function
from cctbx import xray
from cctbx.development import random_structure
from cctbx.development import debug_utils
from cctbx.array_family import flex
import sys, random
from six.moves import range
def shift_u_iso(structure, shift):
for sc in structure.sc... |
# preprocess the arctic database
# - extract 1st channel of the dual-channel audio, which contains meaningful sound
# - normalize the audio
# - trim the silence at the beginning and at the end based on alignment info
#
# <NAME>, 2021-05-19
import os
import argparse
import glob
import numpy as np
# change working d... |
# This file is part of the MapProxy project.
# Copyright (C) 2010-2012 Omniscale <http://omniscale.de>
#
# 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/LI... |
#!/usr/bin/env python
# author: d.koch
# coding: utf-8
# naming: pep-0008
# typing: pep-0484
# docstring: pep-0257
# indentation: tabulation
""" canp_enum.py
Enums for CANette
"""
# --- IMPORT ---
# Standard libraries (installed with python)
import enum
import logging
import os
import sys
sys.path.append(os.path... |
#!/usr/biin/env python3
"""
MIT License
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, modif... |
"""Parse the energies from Turner, 2004 to rna.py."""
from os import path
DIR = path.dirname(path.realpath(__file__))
DIR_DATA = path.join(DIR, "..", "data")
DE = path.join(DIR_DATA, "rna.dangle.txt") # input files
DE_DH = path.join(DIR_DATA, "rna.dangle.dh.txt")
LOOP = path.join(DIR_DATA, "rna.loop.txt"... |
#!/usr/bin/env python3
#
# Cross Platform and Multi Architecture Advanced Binary Emulation Framework
#
from qiling.const import *
from qiling.os.const import *
from qiling.os.uefi.const import EFI_SUCCESS, EFI_NOT_FOUND, EFI_OUT_OF_RESOURCES, EFI_INVALID_PARAMETER
from qiling.os.uefi.utils import *
from qiling.os.ue... |
import math
from approximate_string_matching import distance
def naive_edit_distance(t, w, n, m, k):
D = distance.distance_row(
w, t, m, n, distance.EDIT_DISTANCE, distance.FirstRow.ZEROS)
for i, v in enumerate(D[1:]):
if v <= k:
yield i + 1
def _next_possible_occurence(t, n, m, k, BM_k, BAD, j):... |
from nbt import nbt
from PIL import Image,ImageDraw,ImageFont
from os import path
from functools import partial
from . import constants
fontpath = path.join(path.dirname(__file__), "minecraftia", "Minecraftia.ttf")
class ColorError(Exception):
def __init__(self,color):
self.color = color
self.msg... |
#!/usr/bin/env python
# Copyright 2018 The Closure Rules 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
#
# Un... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import int
from builtins import str
from future import standard_library
standard_library.install_aliases()
import os
import sys
import json
import backoff
... |
# flake8: noqa
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Union
from pandas.tseries.frequencies import to_offset
import numpy as np
import pandas as pd
import timely_beliefs as tb
def filter_seasonalities(
df: tb.BeliefsDataFrame,
seasonalities: Dict[... |
import os
import cv2
import time
import numpy as np
import imgaug as ia
from imgaug import augmenters as iaa
from yolo.detector import YOLO
from compare.net.dtfd import dtfd
hand = YOLO(weights='../weights/yolo.h5', threshold=0.5)
fingertip = dtfd()
fingertip.load_weights('weights/dtfd.h5')
def classify(img):
""... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains implementations of the old compound model interfaces that
are now deprecated.
The classes exported by this module should be imported from `astropy.modeling`
rather than from `astropy.modeling.core` or from this module directly.
"... |
"""
Copyright (c) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
# import dependencies
from ctypes import windll
import pandas as pd
from pandas.core.frame import DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import re
import os
import utils
## function to read data
## check for data quality issues
def read_and_qa(pth_str):
# check if path ... |
# Copyright 2019 The TensorFlow Probability 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... |
import xml.etree.ElementTree as ET
import json, os
import numpy as np
from collections import Counter
import nltk
import argparse
import string
import re
parser = argparse.ArgumentParser(description='Extract novel data.')
parser.add_argument('--txt', type=str, help='path to the txt file')
parser.add_argument('--xml', ... |
import time
from ctypes import *
import numpy as np
import scipy.stats as sps
from matplotlib import pyplot as pypl
# =========================测试数据设置=========================
# 正态分布均值
MU = 0
# 正态分布标准差
SIGMA = 1
# 正态分布随机数生成数量
TOTAL_COUNT = 10000
# 分桶计数时每个桶计数区间的大小
BUCKET_SIZE = 2
# 分桶数量
BUCKET_COUNT = 50
# 耗时测试中生成随机数的... |
"""Detect file changes through the windows api
"""
from .head import *
ACTIONS = {
1 : "created",
2 : "deleted",
3 : "updated",
4 : "rename_old",
5 : "rename_new",
}
FILE_LIST_DIRECTORY = 0x0001
l = asyncio.Lock()
master_lock = l
check_lock = asyncio.Lock()
PID = os.getpid(... |
#
# Copyright (c) 2014, Arista Networks, 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:
#
# Redistributions of source code must retain the above copyright notice,
# this list of condit... |
# coding=utf-8
import datetime
import json
import os
import shutil
import socket
import stat
import subprocess # nosec
import sys
import tempfile
import time
from io import StringIO
from typing import Any, List, Optional, TextIO, cast
from ..Monitors.monitor import Monitor
from ..util import format_datetime, short_ho... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
from locintel.core.datamodel.testing import *
from tests.fixtures.testing import *
import pytest
from unittest.mock import Mock, mock_open, patch, call
@pytest.fixture()
def mock_routes():
return {
expected_provider["name"]: Mock(Route),
expected_provider_google["name"]: Mock(Route),
}
clas... |
import os
import requests
import logging
import model
class WebTranslateItRequest(object):
_default_url = 'https://webtranslateit.com/api/projects/{}/{}'
_project_url = 'https://webtranslateit.com/api/projects/{}.json'
_file_url = 'https://webtranslateit.com/api/projects/{}/files/...?file_path={}'
d... |
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime
import json
from math import log10
import os
from pathlib import Path
import wget
import shutil
"""
Python module that contains utily functions for the Anritsu MS2830A Signal Source Analyzer and measurements
"... |
from collections import defaultdict
import torch
import numpy as np
import random
import math
import copy
import cv2
import torchvision.transforms as T
from lib.sincurlimg import SincurlImage
from lib.floodfill import FloodFill
class RandomErasing(object):
""" Randomly selects a rectangle region in an image and e... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
#------------------------------------------------------------------------------#
#Mish
class Mish(nn.Module):
def __init__(self):
super(Mish, self).__init__()
def forward(self, x):
return ... |
# !pip install PipelineHelper
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler, MaxAbsScaler, MinMaxScaler
from sklearn.svm import SVC
from sklearn.ensemble im... |
"""
model
~~~~~
Data objects to used to construct an image.
Basic Usage
===========
The objects in this module provide the basic structure for how images
are constructed using the pjinoise module. In general, the following
are true:
* Source objects (pjinoise.sources) create the initial raw image
data.
* Op... |
# Imports :
# for the Wiktionary scrape
from bs4 import BeautifulSoup
import requests
# argument parser
import argparse
# to clear the terminal
from os import system
# to print with colors
class Colors:
"""
Class Colors - colors the text to be printed with ANSI
--------------------------------------... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
import random
class PPOCuriosity(object):
def __init__(self,
actor_critic,
clip_param,
ppo_epoch,
num_mini_batch,
value_los... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=C0103
"""
Process shallow discourse relations from CoNLL16st corpus (from `relations.json` or `relations-no-senses.json`).
"""
__author__ = "GW [http://gw.tnode.com/] <<EMAIL>>"
__license__ = "GPLv3+"
from files import load_parses, load_raws, load_relatio... |
from detectron2.engine.train_loop import HookBase
# from detectron2.reg_dataset1 import get_custom_dicts
from detectron2.utils import comm
from torch.nn.parallel import DistributedDataParallel
from detectron2.checkpoint import DetectionCheckpointer
import argparse
import logging
import os
from collections import Ordere... |
# Copyright: 2005-2011 <NAME> <<EMAIL>>
# License: GPL2/BSD
"""DepSet parsing.
Turns a DepSet (depend, rdepend, SRC_URI, license, etc) into
appropriate conditionals.
"""
__all__ = ("DepSet", "stringify_boolean")
from snakeoil.compatibility import IGNORED_EXCEPTIONS
from snakeoil.iterables import expandable_chain
fr... |
import rsk
import time
from math import sqrt, radians, pi
class Predict:
def __init__(self, client, team):
self.client = client
self.team = team
self.couleur = ['green', 'blue']
self.numero = [1, 2]
def delta(self):
'''Calcule inertie de la balle'''
if str(sel... |
"""
T2T-ViT
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from timm.models.helpers import load_pretrained
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_
import numpy as np
from token_transformer import Token_transformer... |
"""
THIS CLASS IS NOT A LOGGER, but it plays one on TV.
The purpose of this class is to make it easy for other code to get a scoped-logger with just an import statement.
And while I was at it, I added a TRACE log level (below DEBUG).
USAGE:
If you want to do some logging...
put this at the top of y... |
from typing import List,Iterator,Callable
import random
#全自動モード
AUTO_MODE=False
#プレイヤー人数
PLAYER_NUMBER=4
#パス回数
PASS_NUMBER=3
#トランプカードクラス
class TrumpCard:
suitStrs=["▲","▼","◆","■","Jo","JO"]
powerStrs=["A","2","3","4","5","6","7","8","9","10","J","Q","K","KR"]
suits=4
powers=13
def __init__(sel... |
"""
X-Ray Tests
"""
import os
import unittest
from pathlib import Path
from typing import Tuple
from unittest import TestCase
import fitz
from fitz import Rect
import xray
from xray.pdf_utils import (
get_bad_redactions,
get_good_rectangles,
get_intersecting_chars,
intersects,
)
root_path = Path(__fi... |
import torch
import torch.nn as nn
from transformers import PreTrainedModel, AutoModel
import torch.nn.functional as F
def dot_attention(q, k, v, v_mask=None, dropout=None):
attention_weights = torch.matmul(q, k.transpose(-1, -2))
if v_mask is not None:
extended_v_mask = (1.0 - v_mask.unsqueeze(1)) * ... |
# downloads ALL GRAPHS from PVL into the specific directory
import argparse
import os
import time
from datetime import datetime
from requests import get
from requests_html import HTMLSession
from urllib.parse import urljoin
def fetch_vodagov_charts(dst_dir, agency, base_url, subpages, datatype_prefix):
"""
... |
# coding=utf-8
# Copyright 2021 The RecSim Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
#!/usr/bin/env python3
# (C) Phonism, LLC. 2018
# All rights reserved
# Licensed under BSD 3-Clause "New" or "Revised" License (see LICENSE)
import sys
import subprocess
import json
import requests
import argparse
import configparser
from pprint import pprint
from collections import defaultdict
class VAction(argpars... |
"""
[CSCI-GA 3033-090] Special Topics: Deep Reinforcement Learning
Homework - 1, DAgger
Deadline: Sep 17, 2021 11:59 PM.
This is my code for Question 3 - Bonus points
"""
import tqdm
import hydra
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvi... |
# -*- coding: utf-8 -*-
"""
cymod.tabproc
~~~~~~~~~~~~
This module contains classes involved in loading Cypher queries from a tabular
data source.
"""
import re
import json
import collections
import warnings
import six
import pandas as pd
from cymod.params import validate_cypher_params
from cymod.cybase import Cyphe... |
import gmpy2
import argparse
import pickle
import signature
from transaction import Transactor
# import pytest
from cocks.utils import InvalidIdentityString
from cocks.cocks import CocksPKG, Cocks
from charm.toolbox.pairinggroup import PairingGroup, GT
from charm.toolbox.ecgroup import ECGroup
from charm.toolbox.eccu... |
# utility functions for other test classes
import gzip
import numpy as np
import pytest
def _make_info_dict(info):
d = {}
for pair in info.split(';'):
k, v = pair.split('=')
vals = np.array(v.split(','))
try:
vals = vals.astype(float)
except ValueError: # not a nu... |
__all__ = ("GHApiObj", "json")
import typing
from urllib.parse import urlencode
from os import environ
#gh api is not working this way
#import certifi
#from urllib3 import PoolManager
#import urllib3.contrib.pyopenssl
#urllib3.contrib.pyopenssl.inject_into_urllib3()
#certsStore = certifi.where()
#http = PoolManager(... |
from random import randint
import random
import math
import utils
import pyglet
import resources as res
import constants as CONSTS
def enter(self):
while(True):
if self.x < self.min_x:
self.x += 5
elif self.x >= self.max_x:
self.x -= 5
if self.y < self.min_y:
... |
from abc import ABC
import numpy as np
import torch
from Globals import *
class model_utils(ABC) :
def __init__(self) :
super().__init__()
def cut_and_paste_down( batch, dim=1) :
return batch.transpose(0,1).reshape(-1)
def cut_and_paste_up( batch, dim=1, beam_size=1) :
'''
... |
import re
from operator import itemgetter
from typing import Iterable
import git
from django.conf import settings
from django.core.cache import caches
from django.shortcuts import get_object_or_404, render
from django.utils.translation import get_language_info
from i18n import DEFAULT_LANGUAGE_CODE
from i18n.utils im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.