text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Python example script showing SecureX Cloud Analytics Alerts.
Copyright (c) 2020 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
... |
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, List, Optional
import numpy as np
import numpy.typing as npt
from nuplan.common.actor_state.agent import Agent
from nuplan.common.actor_state.ego_state import EgoState
from nuplan.common.actor_state.vehicle_parameters impor... |
# -*- coding: utf-8 -*-
from django.db import models
from datetime import date
from django.utils import timezone
from user.models import Person,Customer
from .price_category import PriceCategory
from core.models import Address
from core.mixins import TimeStampedMixin,PartComposMixin,ThumbnailMixin
from core.utils impor... |
from collections import Counter
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.views.generic import ListView
from apps.corecode.models import AcademicSession, AcademicTerm,StudentClass
from a... |
"""
Res2Net for ImageNet-1K, implemented in Gluon.
Original paper: 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
"""
__all__ = ['Res2Net', 'res2net50_w14_s8', 'res2net50_w26_s8']
import os
from mxnet import cpu
from mxnet.gluon import nn, HybridBlock
from mxnet.gluon.co... |
from betdaq.utils import make_tz_naive, floatify
from betdaq.enums import OrderActionType, OrderStatus, OrderKillType, Polarity, MarketStatus
def parse_suspended_order(suspend):
return {
'order_id': suspend.get('OrderId'),
'size_suspended': floatify(suspend.get('SuspendedForSideStake')),
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class Project(models.Model):
_inherit = 'project.project'
sale_line_id = fields.Many2one(
... |
import tkinter as tk
import random
class Controller(object):
"""
A class to control the movement of the snake in the game
"""
def __init__(self, screen):
"""
Binds the arrow keys to the game canvas.
Parameters:
screen (Canvas): The canvas for the Snake game.
... |
# coding: utf-8
from __future__ import with_statement, print_function, absolute_import
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_pl... |
import torch
from torch import nn
from torch.nn import functional as F
from lib.utils import bounding_box_batch, get_member
from models.pose_discriminator import MIDisc, MIDiscConv1
from lib.utils import toggle_grad
from torch.optim import Adam
from collections import namedtuple
VGGOutput = namedtuple(
"VGGOutput... |
import collections
import datetime
import json
import logging
import time
# Python 2 compatibility
try:
from logging.handlers import QueueHandler
except ImportError:
from logutils.queue import QueueHandler
# Python 2/3 hack for stringify, below
try:
unicode
except NameError:
unicode = str
nocolor =... |
import copy
import logging
from datetime import datetime, timedelta
from collections import namedtuple
from blinker import Signal
__all__ = [
'Event',
'TrainingMachineObserver',
'TrainingMachine',
]
logger = logging.getLogger(__name__)
class Event(dict):
""" Events that are expected by the process... |
"""
Authors: <NAME>, <NAME>.
Copyright:
Copyright (c) 2021 Microsoft Research
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, ... |
#!/usr/bin/env python3
from WellKnownHandler import WellKnownHandler
from WellKnownHandler import TYPE_UMA_V2, KEY_UMA_V2_RESOURCE_REGISTRATION_ENDPOINT, KEY_UMA_V2_PERMISSION_ENDPOINT, KEY_UMA_V2_INTROSPECTION_ENDPOINT
from flask import Flask, request, Response
from flask_swagger_ui import get_swaggerui_blueprint
fr... |
#!/usr/bin/env python
'''
run social sim trials
'''
import actionlib
import rospy
from rospy_message_converter import message_converter
import tf
from geometry_msgs.msg import PoseArray, Pose
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionGoal
from social_sim_ros.msg import TrialStart, Tria... |
'''
This version uses a Q function for PPO, the same that is
later used for BCQ
'''
import torch
import torch.nn as nn
import torch.autograd as autograd
import torch.nn.functional as F
from torch.distributions.categorical import Categorical
import random
import numpy as np
# Function from https://github.com/ikostrik... |
from distriopt import VirtualNetwork
from distriopt.embedding.physical import PhysicalNetwork
from distriopt.embedding.algorithms import (
EmbedBalanced,
# EmbedILP,
EmbedPartition,
EmbedGreedy,
)
from distriopt.packing.algorithms import ( BestFitDopProduct,
Fir... |
import hashlib
import math
import time
import typing
import jwt
import pydantic
from fastapi.exceptions import HTTPException
from fastapi.requests import Request
from fastapi.security import OAuth2PasswordBearer
from starlette.status import HTTP_401_UNAUTHORIZED, HTTP_403_FORBIDDEN
from fastapi_token.encrypt import g... |
##### Student name: <NAME>
##### Student ID: 200 684 094
### This program has a series of functions/procedures that produce anagrams.
### The final procedure/function of the program reads from a text file, extracts
### all student names and then produces a one word and two word anagrams.
# This function takes two s... |
import json
import torch
import torch.nn as nn
import numpy as np
import torchvision
from torchvision import models, transforms
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
from efficientnet_pytorch import EfficientNet
from PIL import Image
from trivialaugment import aug_lib
np.random.seed(42)
to... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
'''
Created on Aug 10, 2018
@author: <NAME>
@contact: <EMAIL>
This module uses tensorflow on a dataset to implement a multivarian linear regression.
The following input arguments are needed and for practical purposes, in CSV format
and only float values
1. File name. Must be specified with -i
2. Colum... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
"""
About: Basic chain topology for test DPDK L2 forwarding application.
"""
import argparse
import multiprocessing
import subprocess
import sys
import time
from shlex import split
from subprocess import check_output
from comnetsemu.cli import CLI
from... |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... |
from __future__ import print_function
import numpy as np
from scipy import sparse
from scipy.interpolate import griddata
def fast_histogram2d(x, y, bins=10, weights=None, reduce_w=None, NULL=None,
reinterp=None):
"""
Compute the sparse bi-dimensional histogram of two data samples where *x... |
import logging
from collections import Counter, namedtuple
from datetime import date
from typing import Optional, Tuple, Set
from core.logic.debug import log_memory
from logs.logic.validation import clean_and_validate_issn, ValidationError, normalize_isbn
from logs.models import ImportBatch
from nigiri.counter5 import... |
from spikeextractors import RecordingExtractor
import numpy as np
import h5py
import ctypes
class BiocamRecordingExtractor(RecordingExtractor):
def __init__(self, recording_file):
RecordingExtractor.__init__(self)
self._recording_file = recording_file
self._rf, self._nFrames, self._sampli... |
# coding: utf8
import json
import os
import time
import random
import socket
import hashlib
try:
lib = __import__('pandas')
globals()['pd'] = lib
except ImportError:
pandas_import_error_msg = \
'''
Este script utiliza la libreria de Python Pandas.
Por favor ejecuta:
$ sudo -H pip install pand... |
# Copyright INRIM (https://www.inrim.eu)
# See LICENSE file for full licensing details.
import copy
from copy import deepcopy
from formiodata.builder import Builder
from formiodata.form import Form
import collections
from . import custom_components
import logging
import uuid
logger = logging.getLogger(__name__)
cla... |
from sqlalchemy import *
import os
import testbase
ECHO = testbase.echo
db = testbase.db
metadata = BoundMetaData(db)
users = Table('users', metadata,
Column('user_id', Integer, Sequence('user_id_seq', optional=True), primary_key = True),
Column('user_name', String(40)),
mysql_engine='innodb'
)
address... |
#-*- encoding: utf-8 -*-
"""
About : Code to run as a linux daemon service, interface with it via REST POST
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__company__ = ""
__copyright__ = "Copyright (C) 2020 {a}".format(a=__author__)
__credits__ = ""
__license__ = "MIT"
__version__ = 0.03
__lastdate__ = "2020-04-13"... |
import copy
import pprint
import inspect
from collections import OrderedDict
import six
from neupy.exceptions import LayerConnectionError
__all__ = ('LayerGraph',)
def filter_list(iterable, include_values):
"""
Create new list that contains only values
specified in the ``include_values`` attribute.
... |
import argparse
import sys
import torch
from inferno.trainers.basic import Trainer
from inferno.trainers.callbacks.logging.tensorboard import TensorboardLogger
from torch import nn
from torch.autograd import Variable
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from t... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["GP"]
try:
from itertools import izip
except ImportError:
izip = zip
import numpy as np
import scipy.optimize as op
from scipy.linalg import cho_factor, cho_solve, LinAlgError
from .utils import multivariate_gaussian_samples... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Integrate two files known as 'packages.xml'.
Usage:
python combine_packages_xml.py FPATH_1 FPATH_2 >result.xml
Description:
The script reads FPATH_1 and updates the data with FPATH_2.
Entries are sorted by 'version+language'. The file timestamp
is set... |
# coding:utf8
'''
利用synset的embedding,基于SPWE进行义原推荐
输入:所有synset(名词)的embedding,训练集synset及其义原,测试集synset
输出:测试集义原,正确率
'''
import sys
import os
import numpy as np
from numpy import linalg
import time
import random
outputMode = eval(sys.argv[1])
def ReadSysnetSememe(fileName):
'''
读取已经标注好义原的sysnet... |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..','..'))
import numpy as np
import pickle
import random
import json
from collections import OrderedDict
import itertools as it
from src.neuralNetwork.policyValueResNet import GenerateModel, Train, saveVariables, sampleData, Approximat... |
import os
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir="./logs")
from tqdm import tqdm
import numpy as np
import torch
import torchvision.datasets as dset
import torch.nn as nn
import torchvision.transforms as transforms
import pyro
import pyro.distr... |
# Copyright 2014: Mirantis 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 b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Importa as bibliotecas básicas para o funcionamento da tradução
import json
import xml
import xmltodict
import jsonschema
# Classe Model é responsável por validar o Input/Output, i.e., a estrutura do autômato
class Model(object):
def __init__(self):
self.m... |
# !usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2018-10-11 17:51:43
# @Last modified by: <NAME>
# @Last Modified time: 2018-11-29 17:23:15
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import... |
from snovault import (
AuditFailure,
audit_checker,
)
@audit_checker('ReferenceEpigenome', frame=['related_datasets',
'related_datasets.replicates',
'related_datasets.replicates.library',
... |
from sklearn import svm
from ..data_wrappers import reject
import numpy as np
from scipy.stats import multivariate_normal
from sklearn.mixture import GMM
from sklearn.neighbors import KernelDensity
class DensityEstimators(object):
def __init__(self):
self.models = {}
self.unknown = {}
self... |
"""
fakedata.py
====================================
Generate artificial pupil-data.
"""
import numpy as np
import scipy.stats as stats
from .baseline import *
from .pupil import *
def generate_pupil_data(event_onsets, fs=1000, pad=5000, baseline_lowpass=0.2,
evoked_response_perc=0.02, respon... |
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/model... |
import os
from argparse import SUPPRESS
import numpy as np
from pysam import Samfile, Fastafile
from scipy.stats import scoreatpercentile
# Internal
from rgt.Util import GenomeData, HmmData, ErrorHandler
from rgt.GenomicRegionSet import GenomicRegionSet
from rgt.HINT.biasTable import BiasTable
from rgt.HINT.signalProc... |
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Sequence, Type, TypeVar
from eth._utils.datatypes import Configurable
from eth.constants import ZERO_HASH32
from eth_typing import BLSSignature, Hash32
from eth_utils import humanize_hash
from ssz.hashable_container import HashableContainer, SignedH... |
def corpus_file_transform(src_file,dst_file):
import os
assert os.path.isfile(src_file),'Src File Not Exists.'
with open(src_file,'r',encoding = 'utf-8') as text_corpus_src:
with open(dst_file,'w',encoding = 'utf-8') as text_corpus_dst:
from tqdm.notebook import tqdm
text_co... |
import sys
import datetime
import pytest
import pandas as pd
try:
import unittest.mock as mock
except ImportError:
import mock
from dagster_pandas import DataFrame
from dagster import (
DependencyDefinition,
InputDefinition,
List,
ModeDefinition,
Nothing,
OutputDefinition,
Path,
... |
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Any
from typing import List
from typing import Optional
from typing import Union
from pyspark.sql import DataFrame
from pyspark.sql import functions as F
from cishouseholds.edit import assign_from_map
from cishouseholds.edit i... |
from __future__ import annotations
import os
import signal
import subprocess
import sys
import time
from multiprocessing import cpu_count
from typing import List, Union
import click
from .__version__ import __version__
from .routing.commands import display_urls
from .utils import F, import_from_string, import_module... |
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse, JsonResponse
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
f... |
import json
from datetime import timedelta
import dateutil.parser
from flask import Blueprint, request
from app.models.main import Channel, Performer, Song, Play
# Response codes
CODE_KO = 1
CODE_OK = 0
music_ws = Blueprint('music_ws', __name__)
@music_ws.route('/', methods=['GET'])
def index():
return 'Hello... |
import os
import traceback
from ToolBox import utils
class SelectInterface():
def __init__(self, options=None):
if options is None:
options = {}
self.options = options
# options should be a dict
def add_option(self, option, alias=None):
if type(alias) ... |
"""
define model for gp
"""
# from threading import Thread
# from queue import Queue
from multiprocessing import Pool
from random import random, randint
from math import floor
import operator
from autoprover.gp.gene import Gene
from autoprover.gp.rule import GeneRule
from autoprover.gp.action import GeneAction
from aut... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
## # Python Cheet Sheet
# Python version Python3.8
# 简单地列出一些有关基础知识的例子,详细说明请看个人笔记
# `##` 开头表示是 markdown 的标题
import math
## ## Basic
def funcForDebug():
print('### funcForDebug')
i = 100
print(type(i))
print(type(int))
print(dir())
print(id(i... |
"""
Project resources
Many configuration and scripting resources are extracted here.
"""
from shared.tools.snapshot.utils import encode, hashmapToDict
def extract_project_props(client_context):
global_props = client_context.getGlobalProps()
configuration = {
'permissions': hashmapToDict(global_props.getPe... |
#!/usr/bin/env python
########################################################################
# RSA2ELK, by <NAME>
# Converts Netwitness log parser configuration to Logstash configuration
# see https://github.com/blookot/rsa2elk
########################################################################
import config
i... |
import random
import pandas as pd
import pronouncing
from collections import defaultdict
import re
import pkg_resources
def load_data():
stream = pkg_resources.resource_stream(__name__, 'data.pkl.compress')
return pd.read_pickle(stream, compression="gzip")
def define_structure():
length = random.randint(4... |
#!/usr/bin/env python3
from joblib import Parallel, delayed
import os
import sys
from pathlib import Path
from typing import Dict, List
import fire
from logless import get_logger, logged, logged_block
import runnow
from tqdm import tqdm
import uio
code_file = os.path.realpath(__file__)
repo_dir = os.path.dirname(os.p... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#! /usr/bin/env python3
#
"""
Plot time series data in an interactive plot viewer.
Usage
=====
$ python3 plot_time_series.py --loglevel=20 --stderr
Plots add new data every second, and update on screen every 5 sec.
24 hours of data is kept. Each plot starts out in "autoaxis X PAN"
and "autoaxis Y VIS".
Things you c... |
import collections
import logging
import asyncio
import importlib
import pip
import toastbot.toast as toast
try:
import discord
import discord.ext.commands as commands
except ImportError:
print('Installing discord package...')
pip.main(['install', 'discord'])
import discord
import discord.ext... |
from flask import Flask, render_template, request
from keras.preprocessing.image import img_to_array, load_img
from keras.models import load_model
import cv2
import os
import numpy as np
from flask_cors import CORS, cross_origin
import tensorflow.keras
from PIL import Image, ImageOps
import base64
import json
import dl... |
"""
Tests of ModelAdmin validation logic.
"""
from django.db import models
class Album(models.Model):
title = models.CharField(max_length=150)
class Song(models.Model):
title = models.CharField(max_length=150)
album = models.ForeignKey(Album)
original_release = models.DateField(editable=False)
... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2017 the Critic contributors, Opera Software ASA
#
# 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... |
import operator
def pozicijaSprite(broj, x_velicina):
#vraca pixel na kojem se sprite nalazi
pixel = broj * (x_velicina + 1) #1 je prazan red izmedu spritova
return(pixel)
#spriteSlova = ["A", "B", "C", "D", "E", "F", "G", "H", "i", "s", "e"]
spriteSlova = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "s", ",",... |
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import numpy as np
import argparse
global pred_map,sat_map,inst_map
pred_map = { 1 : '1 (constant) ',
2 : '1000-300hPa thickness',
3 : '200-50hPa thickness... |
"""
Copy the contents of a local directory into the correct S3 location,
using the correct metadata as supplied by the metadata file (or
internal defaults).
"""
####
#### Copy the contents of a local directory into the correct S3
#### location, using the correct metadata as supplied by the metadata
#### file (or intern... |
# Copyright 2017 National Research Foundation (Square Kilometre Array)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditi... |
#!/usr/bin/python3
import os
import subprocess
import sys
import json
import requests
import time
# --- Function to execute command with interactive printout sent to web-terminal in real-time
def interactive_command(cmd,session_name):
# --- Execute command
try:
cmd2 = 'printf "' + cmd + '" > /VVebUQ_ru... |
#!/usr/bin/env python
#
# genbank_get_genomes_by_taxon.py
#
# A script that takes an NCBI taxonomy identifier (or string, though this is
# not reliable for taxonomy tree subgraphs...) and downloads all genomes it
# can find from NCBI in the corresponding taxon subgraph with the passed
# argument as root.
#
# (c) TheJa... |
from django.shortcuts import render, redirect
from django.db import connection
from .forms import ProfileForm, LocationForm, SearchLocationForm
import populartimes
import datetime
import math
from mycrawl import popCrawl
def index(request):
# Render the HTML template index.html with the data in the context varia... |
"""This module contains various decorators.
There are two kinds of decorators defined in this module which consists of either two or
three nested functions. The former are decorators without and the latter with arguments.
For more information on decorators, see this `guide`_ on https://realpython.com which
provides a... |
import argparse
import compile_sandbox
import default_nemesis_proto
import logging
import nemesis_pb2
import os
import runner
import shutil
import tempfile
class Judger(object):
def __init__(self, conf, logger):
self.conf = conf
self.logger = logger
self.checker_path = None
self.w... |
# import key libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud, STOPWORDS
import nltk
import re
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize,... |
"""Jednostavni SQL parser, samo za nizove CREATE i SELECT naredbi.
Ovaj fragment SQLa je zapravo regularan -- nigdje nema ugnježđivanja!
Semantički analizator u obliku name resolvera:
provjerava jesu li svi selektirani stupci prisutni, te broji pristupe.
Na dnu je lista ideja za dalji razvoj.
"""
from pj import ... |
import re
import six
import datetime
from urllib import urlencode
from django.conf import settings
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from django.utils.encoding import force_text
import debug # pyflakes:... |
#!/usr/bin/env python3
"""
#------------------------------------------------------------------------------
#
# SCRIPT: forecast_task_05.py
#
# PURPOSE: Computes the bias correction for the NMME dataset. Based on
# FORECAST_TASK_03.sh.
#
# REVISION HISTORY:
# 24 Oct 2021: <NAME>, first version
#
#-----------------------... |
"""A module for anything color/animation related."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from math import ceil, cos, pi
from time import time
from typing import *
Numeric = Union[int, float]
def linear_interpolation(a: Numeric, b: Numeric, x: Nume... |
# Copyright (c) 2015 Xilinx Inc.
#
# 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, distrib... |
import copy
import torch
import torch.nn as nn
from pytorch_metric_learning.losses import NTXentLoss
from transformers import BertForMaskedLM, BertForPreTraining, BertTokenizer
def mask_tokens(inputs, tokenizer, not_mask_pos=None):
""" Prepare masked tokens of inputs and labels for masked language modeling (80% MA... |
# coding: utf-8
# In[1]:
from path import Path
from matplotlib import pyplot as plt
import numpy as np
import skimage.io as io
import os
from PIL import Image
import cv2
import random
import shutil
def crop_by_sequence(image_path,img_class_path,crop_size_w,crop_size_h,prefix,save_dir ,same_scale = False):
... |
from helpers import *
from discord.ext import commands
from discord.ext.commands import Cog, Bot, command, Context
import database as db
import discord
import asyncio
def setup(bot):
bot.add_cog(Commands(bot))
class Commands(Cog):
def __init__(self, bot: Bot):
self.bot = bot
# List spread acros... |
import tkinter as tk
from tkinter import ttk, messagebox, font, StringVar
from tkcalendar import DateEntry
from tkcrud.controller.client_controller import ClientController,\
saving_updating, get_clients, window_popup
class FormClientRegister(tk.Toplevel, ClientController):
def __init__(self, master, tree):
... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import os, sys
from tensorboardX import SummaryWriter
import time
import numpy as np
import pprint
import socket
import pickle
from resnet import *
from kwng import *
from gaussi... |
import numpy as np
import asyncio
import time
import ntplib
import json
import os
import yaml
import websockets
import threading
import uuid
import logging
MODULE_DIR = os.path.dirname(__file__)
with open(os.path.join(MODULE_DIR, "hardwareconstants.yaml"), "r") as f:
constants = yaml.load(f, Loader=yaml.FullLoader... |
# 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.
#
# Description: generate inputs and targets for the DLRM benchmark
#
# Utility function(s) to download and pre-process public data sets
# - Cr... |
#!/usr/bin/env python3
import sys
import numpy as np
import cv2
import time
def get_time(start_time):
return int((time.time() - start_time) * 1000)
def is_inside(inside, outside, limit_val=-1):
point_limit = limit_val * len(inside)
if limit_val < 0:
point_limit = 1
in_point = 0;
for i in ... |
import numpy as np
import re
from nltk import Tree
from nltk import induce_pcfg
from nltk import Nonterminal
from nltk.parse.generate import generate
epsilon = 1e-20
class corpus:
# stores all sentence forms in data
def __init__(self):
self.sentence_forms = {}
for i in range(6): # init si... |
"""
.. module:: Augmentation
:platform: Unix, Windows
:synopsis: A useful module indeed.
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import numpy as np
import random
from nltk.corpus import wordnet
import collections
import math
#import nltk
#nltk.download('wordnet')
class Augmentation:
r"""
This is the clas... |
# from flask import Flask, render_template, flash, redirect, url_for, session, request, logging
# from wtforms import Form, StringField, TextAreaField, PasswordField, validators
# from functools import wraps
import requests
import json
import pandas as pd
import platform
import shutil
import datetime
from module import... |
from argparse import ArgumentParser
from itertools import starmap
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from fyne import blackscholes, heston
from matplotlib.patches import Patch
from scipy.stats import gaussian_kde
import settings
from align_settings import STARTTIME, ENDTIME
from ut... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/env python
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is
# located at
# http://aws.amazon.com/apache2.0/
#
# or in t... |
import os
import cv2
import gc
import random
import time
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
import argparse
from glob import glob
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from PIL import Image, ImageFilter
from models.OEFT import OEFT
parse... |
# Copyright 2018 DeepMind Technologies Limited.
#
# 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 ag... |
#!/usr/bin/env python3
#
# aimap.py
#
# This code is part of the aimap package, and is governed by its licence.
# Please see the LICENSE file that should have been included as part of
# this package.
import json
import logging
import logging.handlers
import os
import subprocess
import pandas as pd
import gffutils
imp... |
import time, subprocess, os.path, re, multiprocessing, threading
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class Kink:
driver = None
dispatcher_thread ... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
#===============================================================================
# Filename : check_ssh_file_existence
# Author : <NAME> <<EMAIL>>
# Description : Check on remote server if some files are present using SSH.
#---------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.