text stringlengths 3.07k 12.6k |
|---|
# Copyright 2017 The Forseti Security 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 ap... |
"""
A Lake Winnipeg Basin Information Network (BIN) harvester for the SHARE project
Example API request: http://130.179.67.140/api/3/action/package_search?q= (problematic)
http://130.179.67.140/api/3/action/current_package_list_with_resources (currently using)
It oddly returns 5 more datasets than all searchable ones ... |
#!/usr/bin/env python
import boto3
import cv2
import numpy
import os
import base64
import gspread
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from httplib2 import Http
from time import localtime, strftim... |
from __future__ import division
import itertools
import json
import math
import os
import random
import shutil
import subprocess
import sys
durationA = str(5)
durationB = str(4)
durationC = str(1)
def main():
if len(sys.argv) > 1:
nbDepth = int(sys.argv[1])
if nbDepth < 2 :
nbDept... |
# Copyright (c) 2018 Cloudify Platform Ltd. 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 ap... |
import numpy as np
from stable_baselines import PPO2
from stable_baselines.common.policies import CnnPolicy
from stable_baselines.a2c.utils import conv, linear, conv_to_fc
from src.envs import CMDP, FrozenLakeEnvCustomMap
from src.envs.frozen_lake.frozen_maps import MAPS
from src.students import LagrangianStudent, i... |
import fcntl
import os
import socket
import struct
import warnings
import subprocess
import logging
import base64
logger = logging.getLogger(__name__)
# Dummy socket used for fcntl functions
_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
class AddrMeta(type):
@property
def maxvalue(cls):
... |
import time
import sys
import dask
from dask.distributed import (
wait,
futures_of,
Client,
)
from tpch import loaddata, queries
#from benchmarks import utils
# Paths or URLs to the TPC-H tables.
#table_paths = {
# 'CUSTOMER': 'hdfs://bu-23-115:9000/tpch/customer.tbl',
# 'LINEITEM': 'hdfs://bu-... |
# Copyright 2019 The Keras Tuner 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# !/usr/bin/env python
# coding=UTF-8
"""
@Author: <NAME>
@LastEditors: <NAME>
@Description:
@Date: 2021-09-24
@LastEditTime: 2022-04-17
源自OpenAttack的DCESSubstitute
"""
import random
from typing import NoReturn, List, Any, Optional
import numpy as np
from utils.transformations.base import CharSubstitute
from utils... |
# OS-Level Imports
import os
import sys
import multiprocessing
from multiprocessing import cpu_count
# Library Imports
import tensorflow as tf
from tensorflow.keras import mixed_precision
from tensorflow.python.distribute.distribute_lib import Strategy
# Internal Imports
from Utils.enums import Environme... |
"""
Cartesian genetic programming
"""
import operator as op
import random
import copy
import math
from settings import VERBOSE, N_COLS, LEVEL_BACK
class Function:
"""
A general function
"""
def __init__(self, f, arity, name=None):
self.f = f
self.arity = arity
self.name = f.... |
#/*
# * Copyright (C) 2017 - This file is part of libecc project
# *
# * Authors:
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# *
# * Contributors:
# * <NAME> <<EMAIL>>
# * <NAME> <<EMAIL>>
# *
# * This software is licensed under a dual BSD and GPL v2 license.
# * See LI... |
from .request import Request
from .response import Response
class HttpRequestCookieTrait:
'Designed for the Request Object; Adds methods to store COOKIE data'
def get_cookies(self, *args):
'Returns COOKIE given name or all COOKIE'
return self.get('cookie', *args)
def remove_cookies(self,... |
import os
import multiprocessing
if os.name != "nt":
# https://bugs.python.org/issue41567
import multiprocessing.popen_spawn_posix # type: ignore
from pathlib import Path
from typing import Optional
# PROFILES_DIR must be set before the other flags
# It also gets set in main.py and in set_from_args because t... |
#!/usr/bin/env python3
import collections
import logging
import os
import typing
import unicodedata
from janome.tokenizer import Tokenizer
from transformers.file_utils import cached_path
from transformers.models.bert.tokenization_bert import BertTokenizer, WordpieceTokenizer, load_vocab
import bunkai.constant
"""
T... |
# -*- coding: utf-8 -*-
import os
import urllib.parse
from datetime import date, datetime
from functools import partial
from urllib.parse import quote_plus
import pandas as pd
import plotly.express as px
import pytz
from csci_utils.luigi.requires import Requirement, Requires
from csci_utils.luigi.target import Target... |
#!/usr/bin/python
import math
import random
from utils.log import log
from bots.simpleBots import BasicBot
def get_Chosen(num_cards, desired_score):
chosen = list(range(1,num_cards+1))
last_removed = 0
while sum(chosen) > desired_score:
#remove a random element
last_removed = random.randint(0,len(chosen)-1)
... |
"""Perform normalization on inputs or rewards.
"""
import numpy as np
import torch
from gym.spaces import Box
def normalize_angle(x):
"""Wraps input angle to [-pi, pi].
"""
return ((x + np.pi) % (2 * np.pi)) - np.pi
class RunningMeanStd():
"""Calulates the running mean and std of a data stream.
... |
import requests, json, bs4, urllib.parse, math
from . import Course, Platform
class Edx(Platform):
name = 'edX'
def _urls(self):
res = requests.get(make_url())
count = json.loads(res.text)['objects']['count']
num_pages = math.ceil(count / 20)
urls = [make_url(pag... |
import unittest
import os
import json
from functions.db.connector import *
from functions.db.models import *
from functions.authentication import *
sample_search = {
"search_groups": [
{
"search_terms": ["blockchain", "distributed ledger"],
"match": "OR"
},
{
... |
from transformer import Encoder
from torch import nn,optim
from torch.nn.functional import cross_entropy,softmax, relu
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
import torch
import utils
import os
import pickle
class GPT(nn.Module):
def __init__(self, model_d... |
# -*- coding: utf-8 -*-
##############################################################################
# Copyright (c) 2017 Science and Technology Facilities Council
#
# All rights reserved.
#
# Modifications made as part of the fparser project are distributed
# under the following license:
#
# Redistribution and use i... |
# Author : <NAME> "blackdaemon"
# Email : <EMAIL>
#
# Copyright (c) 2010, <NAME> <<EMAIL>>
# All rights reserved.
#
# 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... |
import unittest
class PerlinTestCase(unittest.TestCase):
def test_perlin_1d_range(self):
from noise import pnoise1
for i in range(-10000, 10000):
x = i * 0.49
n = pnoise1(x)
self.assertTrue(-1.0 <= n <= 1.0, (x, n))
def test_perlin_1d_octaves_range(self):
... |
import sys
from pprint import pprint
import os
#--------------------------------------------------------------------------#
class CsPP():
def __init__(self, domains):
self.domains = domains
self.maindict = {}
self.keyitems = []
pass
def check_if(self):
emptylist = []
... |
from __future__ import division
from __future__ import print_function
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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.a... |
#!/usr/bin/env python
#
# Copyright (c) 2017 Ericsson AB and others. All rights reserved
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
imp... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
Author : Virink <<EMAIL>>
Date : 2019/04/18, 14:49
"""
import string
import re
L = string.ascii_lowercase
U = string.ascii_uppercase
A = string.ascii_letters
def func_atbash(*args):
"""埃特巴什码解码"""
arg = args[0]
arg = arg.lower().replace(' ', 'vv... |
import subprocess
import os.path
import json
import time
import urllib.parse
from typing import Any, Tuple
import config
from requests_html import HTMLSession
from markdownify import markdownify
class Data:
def __init__(
self,
data_file_path: str = config.DATA_FILE_PATH,
preload: bool = Fa... |
from budgetportal.models import (
FinancialYear,
Sphere,
Government,
Department,
Programme,
)
from django.core.management import call_command
from django.test import TestCase
from tempfile import NamedTemporaryFile
from StringIO import StringIO
import yaml
class BasicPagesTestCase(TestCase):
de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import argparse
import json
import os
from pinliner import __version__
import sys
TEMPLATE_FILE = 'importer.template'
TEMPLATE_PATTERN = '${CONTENTS}'
def output(cfg, what, newline=True):
# We need indentation for PEP8
cfg... |
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import numpy as np
import math
from functools import wraps
def clip(img, dtype, maxval):
return np.clip(img, 0, maxval).astype(dtype)
def clipped(func):
"""
wrapper to clip results of transform to image dtype value range
"""
... |
"""Ingest USGS Bird Banding Laboratory data."""
from pathlib import Path
import pandas as pd
from . import db, util
DATASET_ID = 'bbl'
RAW_DIR = Path('data') / 'raw' / DATASET_ID
BANDING = RAW_DIR / 'Banding'
ENCOUNTERS = RAW_DIR / 'Encounters'
RECAPTURES = RAW_DIR / 'Recaptures'
SPECIES = RAW_DIR / 'species.html'
... |
"""
Various utilities functions used by django_community and
other apps to perform authentication related tasks.
"""
import hashlib, re
import django.forms as forms
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ValidationError
import django.http as http
from django.conf import setting... |
import logging
from django.utils import timezone
from typing import Union
from .exceptions import InvalidTrustchain, TrustchainMissingMetadata
from .models import FetchedEntityStatement, TrustChain
from .statements import EntityConfiguration, get_entity_configurations
from .settings import HTTPC_PARAMS
from .trust_ch... |
from django.shortcuts import render, HttpResponse
from django.views.generic.list import ListView
from django.views.generic.edit import UpdateView, DeleteView, CreateView
from . models import OuverTimeRecord
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.views import View
im... |
# -*- coding: utf-8 -*-
"""
Core client, used for all API requests.
"""
import os
import platform
from collections import namedtuple
from plivo.base import ResponseObject
from plivo.exceptions import (AuthenticationError, InvalidRequestError,
PlivoRestError, PlivoServerError,
... |
import base64
import datetime
import io
import json
import os
import requests
from collections import namedtuple
from urllib.parse import urlparse
import faust
import numpy as np
import keras_preprocessing.image as keras_img
from avro import schema
from confluent_kafka import avro
from confluent_kafka.avro import Avr... |
from app import App
import requests
import json
import polling2
from behave import step
from openshift import Openshift
from util import substitute_scenario_id
from string import Template
class GenericTestApp(App):
deployment_name_pattern = "{name}"
def __init__(self, name, namespace, app_image="ghcr.io/mul... |
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from orchestra.models.fields import PrivateFileField
from orchestra.models.queryset import group_by... |
import asyncio
import os
import signal
import tomodachi
from typing import Any, Dict, Tuple, Callable, Union # noqa
from aiohttp import web
from tomodachi.transport.http import http, http_error, http_static, websocket, Response, RequestHandler
from tomodachi.discovery.dummy_registry import DummyRegistry
async def mi... |
# -*- Mode: python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from publications import list_import_formats, get_publications_importer
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = '<NAME> <<EMAIL>>'
__docformat__ = 'epytext'
from django.contrib import a... |
import logging
from tests.common.helpers.assertions import pytest_assert
from tests.common.utilities import get_host_visible_vars
from tests.common.utilities import wait_until
CONTAINER_CHECK_INTERVAL_SECS = 1
CONTAINER_RESTART_THRESHOLD_SECS = 180
logger = logging.getLogger(__name__)
def is_supervisor_node(inv_file... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright (c) 2018 - huwei <<EMAIL>>
"""
This is a python script for the ezalor tools which is used to io monitor.
You can use the script to open or off the switch, or point the package name which you want to monitor it only.
The core function is to export data what ezalor... |
import discord
from discord.ext import commands
from discord import Embed, Permissions
from Util import logger
import os
import database
# Import the config
try:
import config
except ImportError:
print("Couldn't import config.py! Exiting!")
exit()
# Import a monkey patch, if that exists
try:
import mo... |
# -*- coding:utf-8 -*-
# Bot2Human
#
# Replaces messages from bots to humans
# typically used in channels that are connected with other IMs using bots
#
# For example, if a bot send messages from XMPP is like `[nick] content`,
# weechat would show `bot | [nick] content` which looks bad; this script
# make weecaht displ... |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import string
import unittest
from uuid import uuid4
from unittest import mock
from random import random, randint
from datetime import datetime, timedelta
pkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) # noqa
sys.path.insert(0, pkg... |
# -*- coding: utf-8 -*-
import pandas as pd
import pytest
from bio_hansel.qc import QC
from bio_hansel.subtype import Subtype
from bio_hansel.subtype_stats import SubtypeCounts
from bio_hansel.subtyper import absent_downstream_subtypes, sorted_subtype_ints, empty_results, \
get_missing_internal_subtypes
from bio_... |
import pygame;
import numpy as np;
from math import sin, cos;
pygame.init();
width, height, depth = 640, 480, 800;
camera = [width // 2, height // 2, depth];
units_x, units_y, units_z = 8, 8, 8;
scale_x, scale_y, scale_z = width / units_x, height / units_y, depth / units_z;
screen = pygame.display.set_mode((width, he... |
import json
import sqlite3
import typing
from typing import Optional, Dict
from copy import deepcopy
from contextlib import suppress
from bson.objectid import ObjectId
from pymongo import MongoClient
from pymongo.errors import ConfigurationError
class MongoStorageException(Exception):
pass
class Mongo:
def... |
import zeep
import asyncio, sys
from onvif import ONVIFCamera
import cv2
import numpy as np
import urllib
from urllib.request import urlopen
IP="192.168.2.22" # Camera IP address
PORT=80 # Port
USER="admin" # Username
PASS="<PASSWORD>" # Password
XMAX = 1
XMIN = -1
YMAX = 1
YMIN = -1
movere... |
from assets.lambdas.transform_findings.index import TransformFindings
import boto3
from moto import mock_s3
def __make_bucket(bucket_name: str):
bucket = boto3.resource('s3').Bucket(bucket_name)
bucket.create()
return bucket
@mock_s3
def test_fix_dictionary():
bucket = __make_bucket('tester')
tr... |
import copy
import logging
import os
from typing import Dict, List, Tuple
import checksumdir
import imageio
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm
from ..adapter import download_object
logger = logging.getLogger("fastface.dataset")
class _IdentitiyTra... |
import os
import re
import sys
import json
#upper import
sys.path.append("../../")
from utils import levenshtein
from utils.io import load_json, write_to
def strQ2B(ustring):
"""全角转半角"""
rstring = ""
for uchar in ustring:
inside_code=ord(uchar)
if inside_code == 12288: ... |
# -*- coding: UTF-8 -*-
"""
collector.xhn - 新华网数据采集
官网:http://www.xinhuanet.com/
接口分析:
1. 获取文章列表
http://qc.wa.news.cn/nodeart/list?nid=115093&pgnum=1&cnt=10000
新华全媒体头条
http://www.xinhuanet.com/politics/qmtt/index.htm
====================================================================
"""
import requests
import re... |
import os
from PIL import Image
import seaborn as sn
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
from sidechainnet.utils.sequence import ProteinVocabulary
from einops import rearrange
# general functions
def exists(val):
return val is not None
def default(val, d):
return va... |
import pytest
from array import array
from game_map import GameMap
from tests.conftest import get_relative_path
sample_map_data = tuple(
reversed(
(
array("I", (0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0)),
array("I", (0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0... |
#!/usr/bin/env python3
from __future__ import print_function
import gzip
import json
import re
import sys
# import time
from argparse import ArgumentParser
# from datetime import datetime
class Options:
def __init__(self):
self.usage = 'characterise_inauthentic_tweets.py -i <file of tweets> [-v|--verbos... |
from enum import Enum
from typing import Generator, Tuple, Iterable, Dict, List
import cv2
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.ndimage import label, generate_binary_structure
from scipy.ndimage.morphology import distance_transform_edt as dist_trans
import trainer.lib as... |
import sys
import copy
import pprint
pp = pprint.PrettyPrinter(width=120)
import inspect
import numpy as np
from .. import __version__
from .. import qcvars
from ..driver.driver_helpers import print_variables
from ..exceptions import *
from ..molecule import Molecule
from ..pdict import PreservingDict
from .worker im... |
import hlt
import logging
from collections import OrderedDict
# GAME START
game = hlt.Game("Spoof_v7")
logging.info('Starting my %s bot!', game._name)
TURN = 0
def navigate(ship, entity, multiplier = 1):
navigate_command = ship.navigate(
ship.closest_point_to(entity),
game_map,
speed=int(h... |
#!python
import string
# Hint: Use these string constants to encode/decode hexadecimal digits and more
# string.digits is '0123456789'
# string.hexdigits is '0123456789abcdefABCDEF'
# string.ascii_lowercase is 'abcdefghijklmnopqrstuvwxyz'
# string.ascii_uppercase is 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.ascii_letters ... |
import math
import numpy as np
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from tqdm import tqdm
from model import CharRNN
from data import TextDataset, TextConverter
class Trainer(object):
def __init__(self, args):
self.args = args
... |
#!/usr/bin/env python
import math
import os
import numpy as np
import time
import sys
import copy
import rospy
import moveit_msgs.msg
import geometry_msgs.msg
import random
import csv
from sensor_msgs.msg import JointState
from gazebo_msgs.msg import LinkStates
from gazebo_msgs.msg import LinkState
from std_msgs.msg i... |
"""Coverage based QC calculations.
"""
import glob
import os
import subprocess
from bcbio.bam import ref, readstats, utils
from bcbio.distributed import transaction
from bcbio.heterogeneity import chromhacks
import bcbio.pipeline.datadict as dd
from bcbio.provenance import do
from bcbio.variation import coverage as co... |
import logging
import random
import os
import json
from typing import Tuple, List
import requests
def predict(player_name: str) -> str:
next_move = _predict_next_move(*_get_player_games(player_name))
return _convert_game_to_json(next_move)
R_rock, P_paper, S_scissors, V_spock, L_lizard = ('R', ... |
import unittest
from nose.tools import eq_, ok_, raises
from sqlalchemy import create_engine, MetaData, Column, Integer, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from geoalchemy2 import Geometry
from sqlalchemy.exc import DataError, IntegrityError, InternalE... |
import sys
import difflib
import errno
import json
import logging
import functools
import os
import pytest
from shell import shell
from diag_paranoia import diag_paranoia, filtered_overview, sanitize_errors
VALIDATOR_IMAGE = "datawire/ambassador-envoy-alpine:v1.5.0-116-g7ccb25882"
DIR = os.path.dirname(__file__)
E... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import mechkit
import mechmean
class KanataniFactory(object):
def __init__(self, N):
self.con = mechkit.notation.Converter()
self._I2 = mechkit.tensors.Basic().I2
self.N = N = self.con.to_tensor(N)
self.degree = le... |
from ymmsl import Identifier, Reference
import pytest
import yatiml
def test_create_identifier() -> None:
part = Identifier('testing')
assert str(part) == 'testing'
part = Identifier('CapiTaLs')
assert str(part) == 'CapiTaLs'
part = Identifier('under_score')
assert str(part) == 'under_score... |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import os
import math
from utils import logger
use_cuda = torch.cuda.is_available()
# utility
def to_var(x, dtype=None):
if type(x) is np.ndarray:
x = torch.from_numpy(x)
elif type(x) is list:
... |
from http import HTTPStatus
from unittest import TestCase, mock
import jwt
from fastapi.testclient import TestClient
from src.api.review_resource import REVIEWS
from src.config import config
from src.main import app
from src.models.article import Article
from src.models.review import Review
def _bearer(**payload):
... |
"""
Tests for the h5py.Datatype class.
"""
from __future__ import absolute_import
from itertools import count
import numpy as np
import h5py
from ..common import ut, TestCase
class TestVlen(TestCase):
"""
Check that storage of vlen strings is carried out correctly.
"""
def assertVlenArrayEq... |
import csv
from core.exceptions import InvalidFileException
def load_so_item_from_file(path, db_service):
with open(path) as csv_file:
csv_reader = csv.reader(csv_file)
error_msg = 'Missing required header: {}'
for i, row in enumerate(csv_reader, 1):
data = {
... |
#! -*- coding:utf-8 -*-
# 语义相似度任务-无监督:训练集为网上pretrain数据, dev集为sts-b
from bert4torch.tokenizers import Tokenizer
from bert4torch.models import build_transformer_model, BaseModel
from bert4torch.snippets import sequence_padding, Callback, ListDataset
import torch.nn as nn
import torch
import torch.optim as optim
from to... |
import os
import urllib
from google.appengine.api import users
from google.appengine.ext import ndb
import jinja2
import webapp2
from sys import argv
import datetime
import pickle
import sys
sys.path.insert(0, 'libs')
import BeautifulSoup
from bs4 import BeautifulSoup
import requests
import json
JINJA_ENVIRONM... |
# Copyright 2019 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
# Copyright 2017 The Bazel 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 la... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from masked_cross_entropy import *
from preprocess import *
from parameter import *
import time
# # Training
def train(input_batches,... |
import bitmath
class V2RegistryException(Exception):
def __init__(
self,
error_code_str,
message,
detail,
http_status_code=400,
repository=None,
scopes=None,
is_read_only=False,
):
super(V2RegistryException, self).__init__(message)
... |
from flask import Flask, render_template, url_for, redirect, request
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from dateutil.relativedelta import relativedelta
from demail import demail
__author__ = '<NAME>'
__doc__ = 'Never Forget online remainder'
app = Flask(__name__)
app.config['SQLALC... |
import os, sys
from distutils.util import strtobool
import numpy as np
import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.python.util import nest, tf_inspect
from tensorflow.python.eager import tape
# from tensorflow.python.ops.custom_gradient import graph_mode_decorator
# 是否使用重计... |
import pickle
import os
import tensorflow as tf
from glob import glob
import utils.DataLoaderUtils as dlu
from utils.AnnotationUtils import write_dad_masks
# Static Dataset Config Options
TAG_NAMES = {'highlights',
'urls_to_supplementary',
'abbreviation',
'abstract',
... |
import __init__
import os
#os.environ['LD_LIBRARY_PATH'] += ':/usr/local/cuda-11.1/bin64:/usr/local/cuda-11.2/bin64'
import numpy as np
import torch
import torch.multiprocessing as mp
import torch_geometric.datasets as GeoData
from torch_geometric.loader import DenseDataLoader
import torch_geometric.transforms as T... |
import abc
import argparse
import logging
import pathlib
from collections import namedtuple
from operator import itemgetter
import toml
class NotConfiguredError(Exception):
pass
class ParseError(Exception):
pass
class Model(abc.ABC):
"""Interface for model that can save/load parameters.
Each mod... |
#!/usr/bin/python
import requests
import boto3
import time
import geopy.distance
import xml.etree.ElementTree as ET
import itertools
import sys
import pickle
S3_BUCKET = "panku-gdzie-jestes-latest-storage"
class LatestPositionStorage(object):
def __init__(self, service):
self.objectName = "%s.latest" % service... |
# 2020 <NAME> and <NAME>
import os
import json
import numpy as np
from typing import Set, List
from geopy.distance import great_circle
from scipy.spatial.ckdtree import cKDTree
from shapely.geometry import Polygon, shape, Point
from icarus_simulator.sat_core.coordinate_util import geo2cart
from icarus_simulator.stra... |
# Machine Learning Online Class - Exercise 2: Logistic Regression
#
# Instructions
# ------------
#
# This file contains code that helps you get started on the logistic
# regression exercise. You will need to complete the following functions
# in this exericse:
#
# sigmoid.py
# costFunction.py
# predic... |
#poly_gauss_coil model
#conversion of Poly_GaussCoil.py
#converted by <NAME>, Mar 2016
r"""
This empirical model describes the scattering from *polydisperse* polymer
chains in theta solvents or polymer melts, assuming a Schulz-Zimm type
molecular weight distribution.
To describe the scattering from *monodisperse* poly... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import torch
from torch.utils.data.dataloader import DataLoader as torchDataLoader
from torch.utils.data.dataloader import default_collate
import os
import random
from .samplers import YoloBatchSampler
def ... |
#!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
---
module: ec2_vpc_vpn_info
version_added: 1.0.0
short_description:... |
# Copyright 2014 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 the "license" file accompa... |
import bpy
import bmesh
import numpy
from random import randint
import time
# pointsToVoxels() has been modified from the function generate_blocks() in https://github.com/cagcoach/BlenderPlot/blob/master/blendplot.py
# Some changes to accomodate Blender 2.8's API changes were made,
# and the function has been made m... |
from django.core.exceptions import FieldError
from staff.models import Staff
import re
def get_choices():
# choices in a seperated funtion to change it easier
STATUS_CHOICES = (
('', ''),
('Test', 'Test'),
('Fertig', 'Fertig'),
('Löschen', 'Löschen'),
('Vertrieb', 'Vert... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from collections import OrderedDict
from decimal import Decimal
from parser_data import InlineList, DuplicationList
from state import State, StateMachine
from type_check import is_int, is_float, is_sci_notation
from format import format
from error import DMPException
cl... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
from collections import namedtuple, OrderedDict
from subprocess import call
import scipy.io.wavfile as wavfile
import argparse
import codecs
import timeit
import struct
import toml
import re
import sys
import os
def _int64_feature(value)... |
import torch
from torch import nn
from torch.autograd import Variable
import config
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_normal_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0)
def conv(in_chann... |
# -*- encoding: utf-8 -*-
try:
import unittest2 as unittest
except ImportError:
import unittest
from multiprocessing import Manager
from random import randint
import logging
import sys
import os
import copy
import shutil
# add kamma path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.