text stringlengths 3.07k 12.6k |
|---|
from django.urls import reverse
from django.views import View
from django.http import HttpResponse
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase, RequestFactory
from django.core.exceptions import PermissionDenied
from datetime import timedelta
from tables.models impo... |
import logging
import sys
import json
import base64
import random
import string
import psycopg2
from apikeys import settings
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
TABLE_NAME = 'apikeys'
APPLICATION_TABLE = 'available_apis'
if not settings.PG_DBNAME or not settings.PG_USER:
log... |
from pygears.typing.visitor import TypingVisitorBase
from pygears.typing import bitw, is_type
class SVGenTypeVisitor(TypingVisitorBase):
struct_str = "typedef struct packed {"
union_str = "typedef union packed {"
def __init__(self, name, basic_type='logic', depth=4):
self.struct_array = []
... |
""" Copy of https://github.com/pytorch/vision/blob/master/torchvision/transforms/transforms.py
But for dict entries of the following format
{
'image': PIL.Image object,
'bbox' (optional): (x1, y1, x2, y2) coords,
'annotations' (optional): np.ndarray in shape (N, 5),
'mask' (optional): PIL.Image object,... |
import pandas as pd
from pathlib import Path
import pdb
from typing import List, Tuple
from mseg.utils.dir_utils import check_mkdir
from mseg.utils.csv_utils import write_csv
from mseg.label_preparation.dataset_update_records import (
cocop_update_records,
ade20k_update_records,
bdd_update_records,
idd_update... |
import argparse
from builtins import input
from collections import defaultdict
import datetime
import logging
import os
import pprint
import re
import sys
import ee
import utils
# from . import utils
def main(ini_path=None):
"""Remove earlier versions of daily tcorr images
Parameters
----------
ini... |
#!/usr/bin/env python
import os
from datetime import datetime, timezone, timedelta
import threading
import logging
import re
from botocore.vendored import requests
import boto3
# semaphore limit of 5, picked this number arbitrarily
maxthreads = 5
sema = threading.Semaphore(value=maxthreads)
logging.getLogger('boto3... |
from argparse import Namespace
from datetime import datetime, timedelta
from typing import List, Optional
from enum import Enum
import pytz
import os
import time
import json
from telethon import TelegramClient
from telethon.errors import FloodWaitError
from telethon.sessions import StringSession
from telethon.tl.funct... |
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
"""
Our gruop submit this individual assignment as group assignment
Firstly, we manually found all the versions in the level of 3.x,4.x,5.x, then we use git tag
to grab all the sorted subversions for every 3.x,4.x,5.x. After looking at the commit time,
our group use... |
# -*- coding: utf-8 -*-
import sublime
import sublime_plugin
import os
import re
from .util import log
from .util.env import *
from .util.tpl import PATCH_TEMPLATE
PKG = 'zz File Icons'
SETTINGS = 'File Icons.sublime-settings'
SETTINGS_CHANGED = False
THEME_EXTENSION = '.sublime-theme'
UUID = '9ebcce78-4cac-4089-8bd... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
import torch.nn as nn
from torch.distributions import constraints
from pyro.distributions.torch_transform import TransformModule
from pyro.distributions.transforms.householder import Householder
from pyro.distribution... |
'''
Deep Residual Learning for Image Recognition
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import os
import sys
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__)))))
sys.path.append(BASE_DIR)
import torch
import torc... |
import os
import time
import json
import threading
import requests
# ========================================
GOOGLE_API_KEY = None
if "GOOGLE_API_KEY" in os.environ:
GOOGLE_API_KEY = os.environ["GOOGLE_API_KEY"]
if GOOGLE_API_KEY is None:
raise ValueError("Please set the GOOGLE_API_KEY environment variable"... |
import os
import json
import re
from src.config import *
from src import preprocessing, utils
import time
import numpy as np
from tqdm import tqdm
CITATION_COUNTS = dict()
def get_paper_from_json(json_string):
p = json.loads(json_string) # load the paper as a json object
paper = dict()
... |
import logging
import re
import time
from os import getenv
import sentry_sdk
from deeppavlov import build_model
from flask import Flask, request, jsonify
sentry_sdk.init(getenv("SENTRY_DSN"))
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logger = logging.getL... |
import cv2
from matplotlib.animation import ArtistAnimation
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from os.path import join
import pandas as pd
import time
class Timer:
def __init__(self, msg='Time elapsed'):
self.msg = msg
def __enter__(self):
... |
"""
Visualize output of fitted models on FDEM covid-19 data
"""
from os.path import join
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource, HoverTool, Legend
from bokeh.layouts import column
from bokeh.layouts import row
from bokeh.io import curdoc
from bokeh.palettes import Purples
from ... |
class FiniteAutomata:
def __init__(self, trans=None, initial="0", accepting=None, states=None, alphabet=None):
self.trans = {}
self.initial = initial
self.accepting = set()
self.states = set()
self.alphabet = set()
def return_constructor_recipe(self):
return {
... |
import cv2
from sklearn.linear_model import LinearRegression
import numpy as np
def prediction(c):
data=[]
for i in range(len(c)-1):
data.append([c[i],c[i+1]])
X = np.array(data)[:, 0].reshape(-1, 1)
y = np.array(data)[:, 1].reshape(-1, 1)
to_predict_x = [c[len(c)-1]]
to_predict_x = np... |
from __future__ import annotations
from ctc import evm
from ctc import spec
from .. import analytics_spec
async def async_compute_dex_volume(
blocks: list[int], verbose: bool = False
) -> analytics_spec.MetricGroup:
import asyncio
volume_tasks = []
for pool_name, pool_info in analytics_spec.dex_pool... |
"""
Helper to create static Python code from Nasse objects
"""
import json
from nasse.models import Endpoint, Error, Login, Return, UserSent
def return_to_python(element: Return, indent: str = " " * 4, end_indent: str = ""):
result = "Return(\n"
result += indent + "name = " + \
json.dumps(element.name... |
# -*- coding: utf-8 -*-
"""A module providing input and output formatters."""
import re
from collections.abc import Callable
from decimal import Decimal
from re import Pattern
from typing import Final
from typing import final
from src.cashier.purchase.container import PurchasedItem
@final
class OutFormatter:
"""... |
import os
from segmentation_refinement.main import Refiner
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import cv2
import glob
import segmentation_refinement as refine
from tqdm ... |
import io
import os
import time
import atexit
import datetime
import threading
from queue import Queue, Empty
import Utils
import Model
from GetResults import ResetVersionRAM
from WebServer import WsRefresh
q = None
streamer = None
terminateMessage = '<<<terminate>>>'
def formatTimeHHMMSS( secs ):
return Utils.for... |
#!/usr/bin/env python
# Functions:
# annotate_linked_variants
#
# filter_min_total_reads
#
# filter_min_callers
# filter_linked_perc
# exonic_only
def filter_min_total_reads(MATRIX, args):
if args is None:
return MATRIX
raise NotImplementedError
def filter_min_callers(MATRIX, args, germline):
... |
import pygame
import pygame._view
from pygame.locals import *
import sys
import random
pygame.init()
class Cell(pygame.sprite.Sprite):
def __init__(self, game, pos, num):
pygame.sprite.Sprite.__init__(self)
self.game = game
self.num = num
self.color = self.getColor()
... |
import threading
import time
# Define a query cache.
# ==========================
class Entry:
"""An entry in a QueryCache.
"""
timestamp = None # The timestamp of the last query run [datetime.datetime]
lock = None # Access control for this record [threading.Lock]
exc = None ... |
import json
import pandas as pd
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from tensorflow import keras
import numpy as np
import nltk
import pickle
import multiprocess as mp
import gzip
from polyglot.detect import Detector
from polyglot.detect.base import l... |
"""Support for HERE travel time sensors."""
from __future__ import annotations
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const ... |
#! /usr/bin/env python3
#-*- coding: utf-8 -*-
"""
Script to parse PDF resumes, create a csv file containing info
#hackyourstart - Python hacketon(19.-20.11.2016)
"""
import re
import string
import os
import logging
import argparse
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfi... |
from __future__ import annotations
import hashlib
import typing
from itertools import combinations, product
from typing import TYPE_CHECKING
import pytest
from pyflocker.ciphers import Hash, exc
from pyflocker.ciphers.backends import Backends
if TYPE_CHECKING:
from pyflocker.ciphers.base import BaseHash
ALL_HA... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: plotSpiralSpotUsingArrayTrace.py
# Purpose: Demonstrate array tracing function by plotting spiral spot diagram
# It also shows two ways of using the arraytrace module functions --
# 1. s... |
#!/usr/bin/env python2
# Copyright (C) 2019 The Android Open Source Project
#
# 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 requ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import json
import os
import time
from common import file, console
from manage import whiptail, upgrade, get
dialog = whiptail.Whiptail()
dialog.height = 15
dialog.backtitle = "SilverBlog management tool"
if os.path.exists("./config/system.json"):
system_config = json.l... |
from collections import Counter
from typing import Optional, Union, Set, List, Any
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
from milkviz.utils import doc
def find_intersec(*arr_list):
count = 0
counter = [Counter(arr) for arr in arr_list]
max_ix = np.argmax([le... |
# Copyright 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import flask
from flask.views import MethodView
from flask import Blueprint
from importlib import import_module
config = {
'container': {
'aliases': {
'flask_caching.cacheDriver':'pyrindow.stdlib.lrucache.LruCache',
},
'components': {
'flask.Flask': {
... |
"""Add a new repository for the Arcyd instance to manage."""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# abdcmd_addrepo
#
# Public Functions:
# getFromfilePrefixChars
# setupParser
# pr... |
#!/usr/bin/env python
#
# ESP32 x509 certificate bundle generation utility
#
# Converts PEM and DER certificates to a custom bundle format which stores just the
# subject name and public key to reduce space
#
# The bundle will have the format: number of certificates; crt 1 subject name length; crt 1 public key length;
... |
# Copyright 2018/2019 The Rlgraph Authors, All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
"""Implementation Bigquery builder base."""
import os
import time
import tempfile
from google.cloud import bigquery
from rudra import logger
from rudra.data_store.aws import AmazonS3
_POLLING_DELAY = 1 # sec
class BigqueryBuilder:
"""BigqueryBuilder class Implementation."""
def __init__(self, query_job_c... |
import numpy as np
#%% jasmine noise model in ppm as a function of Hw=0.7J+0.3H for 5min
def noise_model(hw, hwlim=[7.756708395177219, 12.756708395177219], coeff=[2.73659218e+00, -9.95974284e+01, 1.37688923e+03, -8.47717270e+03,1.95861269e+04]):
m = np.poly1d(coeff)
if np.sum((hw<hwlim[0])|(hwlim[1]<hw)):
... |
##################################################
## ## ## ## ### ## ## ### ##
#### #### ### ## ## ## ## ## ### ## ### ## ### ##
#### #### ### ## ### # # ## ### ## ### ## ### ##
#### #### ### ## ## ## ## ## ## ### ## ### ##
#### #### ## ## ## ### ## ### ## ### ##
########... |
#!/usr/bin/env python
# coding: utf-8
# Dernier TP (mini projet) : exemples de calcul numérique
# - Prof : <NAME>
# - Site du cours : [https://perso.crans.org/besson/teach/intro_num_DEM_2020/](https://perso.crans.org/besson/teach/intro_num_DEM_2020/)
# - Date : mercredi 14/10/2020 et vendredi 16/10/2020.
# ----
# ## ... |
"""Handlers for specific details of events."""
from collections import OrderedDict
from datetime import datetime
from itertools import chain
from typing import List
from dateutil.parser import isoparse, parse
from gcalcli.exceptions import ReadonlyError, ReadonlyCheckError
from gcalcli.utils import is_all_day
FMT_D... |
#!/usr/bin/env python
"""Export data from helpscout to files (and S3)"""
import base64
import json
import os.path
import sqlite3
import sys
import time
import requests
import boto3
HELPSCOUT_API_KEY = os.environ['HELPSCOUT_API_KEY']
MAILBOX_LIST = [8430] # GeekOUT # List of mailboxes to process
DB_FILE = 'data.db'
S... |
import pandas as pd
from constants import *
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.ticker as ticker
import numpy as np
import torch
import torch.nn as nn
import random
import time
from utils import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def... |
import cv2
import numpy as np
from os.path import join, isdir
from os import mkdir, makedirs
from concurrent import futures
import sys
import time
import json
import glob
# Print iterations progress (thanks StackOverflow)
def printProgress(iteration, total, prefix='', suffix='', decimals=1, barLength=100):
"""
... |
# import modules
from tkinter import *
import tkinter.messagebox
# Create main window
tk = Tk()
# Set window title and icon
tk.title("Tic Tac Toe")
tk.iconbitmap("logo-ico.ico")
# Player variables
pa = StringVar()
pb = StringVar()
p1 = StringVar()
p2 = StringVar()
player1_name = Entry(tk, textvariable=p1, bd=5)
pla... |
# -*- coding: utf-8 -*-
"""
viz
~~~
Functions for visiualization of data.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import utils
import process
def plot_surface(agg_tdata, surface_result, num_levels=10):
"""plot the 3D surface and the level set"""
... |
# https://www.codewars.com/kata/574be65a974b95eaf40008da/train/python
# My solution
from itertools import product, permutations
DICT_OPS = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"/": lambda a, b: a / b,
"*": lambda a, b: a * b,
}
def math_expr(keys_ops, values, direction):
... |
import hashlib
from typing import Tuple
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
import hmac
import secrets
"""
There are some ways this module can encrypt/hash the data.
WARNING: all the functions here operate on BYTES, not STRINGS.
Be sure to encode the strings into byte arrays be... |
import asyncio
import logging
from abc import ABC, abstractmethod
from http import HTTPStatus
from typing import Any, Optional, Mapping, List
import aiohttp
from aiohttp import ClientSession, hdrs
from thriftpy2.utils import serialize # noqa
from async_jaeger import thrift
from async_jaeger.constants import DEFAULT_... |
# -*- coding: utf-8 -*-
import sqlite3
def dict_factory(cursor: object, row: object) -> object:
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class Db:
def __init__(self, filename):
self.filename = filename
if filename:
self.... |
import os
import base64
import time
import logging
import uuid
import boto3
from boto3.dynamodb.conditions import Key
from common import utilities
## Config
CONFIG_OPTIONS = utilities.load_config()
## Logging
logger = utilities.initialize_logging(logging.getLogger(__name__))
class CommandItem:
def __init__(self... |
import numpy as np
import cv2
import os
import argparse
import json
from raspberryturk import setup_console_logging
from raspberryturk.core.vision.square import Square
from raspberryturk.core.data import class_encoding
from raspberryturk.core.data.dataset import Dataset
from random import shuffle
from sklearn.model_sel... |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to ... |
import pandas as pd
import json
from gerar_evidencias import discretizacao_BDCompleta
#from dataframe import base
import dataframe
import sys
import argparse
import datetime
import os.path
# MANDAR A BASE, O N_BINS, A VARIAVEL ALVO, QUATIDADE DE ANOS, TIPO DE DISCRETIZAÇÃO
def get_evd_tendencias(base, n_bins,type_dis... |
# Based on code from https://github.com/wilson1yan/cs294-158-ssl
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from deepul_helper.resnet import resnet_v1
from deepul_helper.batch_norm import BatchNorm1d
class CPC(nn.Module):
latent_dim = 204... |
# Author: <NAME>
from typing import Union
from utils import *
S_BOX = [
['63', '7C', '77', '7B', 'F2', '6B', '6F', 'C5', '30', '01', '67', '2B', 'FE', 'D7', 'AB', '76'],
['CA', '82', 'C9', '7D', 'FA', '59', '47', 'F0', 'AD', 'D4', 'A2', 'AF', '9C', 'A4', '72', 'C0'],
['B7', 'FD', '93', '26', '36', '3F', '... |
#!/usr/bin/env python3
import os, sys
from collections import defaultdict, OrderedDict
from datetime import datetime
import yaml, yamlloader
from urllib.parse import quote as url_quote
from illuminatus import illuminatus_version
"""This script provides information about a sequencing run that appears at the top
of... |
import re
import unittest
from xcube.webapi.service import url_pattern, parse_tile_cache_config, new_default_config
class TileCacheConfigTest(unittest.TestCase):
def test_parse_tile_cache_config(self):
self.assertEqual({'no_cache': True}, parse_tile_cache_config(""))
self.assertEqual({'no_cache':... |
import os
from typing import Dict, Any, List, Optional, Set
import yaml
from nftgen.model.Attribute import Attribute
from nftgen.settings import config
from nftgen.settings.AttributeSettings import Slot, AttributeSettings
from nftgen.settings.ColorTheme import ColorTheme, ColorSettings
from nftgen.utils.none import g... |
# main.py
# 4/11 6:55pm SH & JD - Work realated with camera link ajax loding
# 4/11 7:36pm JD - work related to the prediction indicator
# 4/13 8:51pm JL - fixed a small bug in the querry of getCameraListWithPredictedMotion()
# 4/15 5:05pm LH - added method to load activity from database and added route to sent it back... |
#---------------------------------------------------------------------------------
# (c) 2013-2014 <NAME>
#---------------------------------------------------------------------------------
#--------------------------------------------------------------------------
# Useful small utility functions and classes that are ... |
# # NEON AI (TM) SOFTWARE, Software Development Kit & Application Development System
# # All trademark and other rights reserved by their respective owners
# # Copyright 2008-2021 Neongecko.com Inc.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the foll... |
#!/usr/bin/env python
'''
To run this, set the environment variables $SRC and $SRC2 to full paths to two mp4 files.
This has three pipelines:
- Pipeline 1 plays the file $SRC
- Pipeline 2 plays the file $SRC2
- Pipeline 3 displays them mixed
Pipeline-1 --\
---> Output-pipe
Pipeline 2 --/
This demo sho... |
import json
import os
import random
import shutil
import socket
import tempfile
import time
import unittest
import urllib
import urllib.request
from subprocess import Popen
from urllib.error import HTTPError
def get_samples_dir():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), '../samples')
cla... |
######################################################################
##
## Copyright 2013 <NAME> <<EMAIL>>
##
## Permission is hereby granted, free of charge, to any person
## obtaining a copy of this software and associated documentation
## files (the "Software"), to deal in the Software without
## restriction, incl... |
from core import forms
from core.exceptions import FormNotValidError
from core.models import GitlabUser
from django import forms as django_forms
from groups import models
from groups import tasks
from groups.parser import csv_members_parse, csv_subgroup_and_members_parse
class TaskGroupForm(forms.BaseTaskGroupForm):
... |
# Copyright 2015 FUJITSU 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 agreed to in writin... |
import os
from datetime import datetime, timedelta
import pytest
from paddle import PaddleException
from .test_paddle import paddle_client # NOQA: F401
@pytest.fixture()
def create_coupon(paddle_client): # NOQA: F811
product_id = int(os.environ['PADDLE_TEST_DEFAULT_PRODUCT_ID'])
currency = 'GBP'
now ... |
import os
import numpy as np
from .training import load_old_model
from .utils import pickle_load, get_image
from .utils.patches import reconstruct_from_patches, get_patch_from_3d_data, compute_patch_indices
from .augment import permute_data, generate_permutation_keys, reverse_permute_data
from .data import load_data_n... |
##############################################################################
#
# Copyright (c) 2006-2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THI... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from collections import OrderedDict
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import torch.nn.functional as F
import htk_io
import numpy as np
import subprocess
class SequenceWise(nn.Module):
def __init__(self, mo... |
import logging
import numpy as np
import pickle
from implicit.als import AlternatingLeastSquares
from implicit.utils import augment_inner_product_matrix
from scipy import sparse
log = logging.getLogger("rb.recommendation")
class RecommenderException(Exception):
pass
class ImplicitRecommender:
def __init_... |
import contextlib
import logging
import random
import typing
from urllib.parse import quote
import aiohttp
import discord
from discord.ext import commands
logger = logging.getLogger(__name__)
class IdiotError(Exception):
pass
api_endpoints = {
"api_endpoints": {
"Generators": ("achievement", "bats... |
import numpy as np
import torch
def cross_op(r):
"""
Return the cross operator as a matrix
i.e. for input vector r \in \R^3
output rX s.t. rX.dot(v) = np.cross(r, v)
where rX \in \R^{3 X 3}
"""
rX = np.zeros((3, 3))
rX[0, 1] = -r[2]
rX[0, 2] = r[1]
rX[1, 2] = -r[0]
rX = rX - rX.T
return rX
def... |
# Copyright 2021, Google LLC. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import sys
import os
from PyQt5 import QtWidgets
from PyQt5.QtGui import QIcon, QPixmap, QImage
import design
import numpy as np
from PIL import Image
import sample as lib
import cv2
from argparse import ArgumentParser, SUPPRESS
from openvino.inference_engine import IECore
def build_argparser():
parser = Argument... |
import unyt as u
from gmso.utils.io import import_, has_openmm, has_simtk_unit
if has_openmm & has_simtk_unit:
simtk_unit = import_('simtk.unit')
from simtk.openmm.app import *
from simtk.openmm import *
def to_openmm(topology, openmm_object='topology'):
"""
Convert an untyped topology object to... |
"""Readout Layer for GNN implementation."""
import tensorflow as _tf
from abc import ABC as _ABC, abstractmethod as _abstractmethod
from .input import ReadoutInput
from .mlp import MLP
class ReadoutLocalLayer(_tf.keras.layers.Layer, _ABC):
"""Base Readout Local Layer abstract class to be inherited by Readout Lay... |
# Copyright 2021 Sony Corporation.
# Copyright 2021 Sony Group 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 requi... |
#! /usr/bin/python
# Script for parsing the E-value parameters and calculation of the E-value
# for nucleotide alignment scores.
#
#
# Written by <NAME>, March 2015.
#
# The MIT License (MIT)
# Copyright (c) 2015 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software... |
import torch
import torch.nn as nn
class ParamGaussian(torch.distributions.Distribution):
def __init__(self, mu, log_sigma):
self.mu = mu
self.sigma = log_sigma.exp()
def get_eps(self):
return torch.rand_like(self.sigma)
def rsample(self):
eps = self.get_eps()
... |
#! /usr/bin/env python
import pygame, random
random.seed()
class CellularAutomaton() :
"""
The CellularAutomaton object structures how cells behave
Attributes:
columns (int): number of cells in column
rows (int) : number of cells in row
list (list) : list of how cells are displaye... |
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers
from wagtail.admin import messages
from wagtail.admin.forms.search import Sear... |
import random
from Houdini.Handlers import Handlers, XT
from Houdini.Handlers.Games.Table import TableHandler
class TreasureHunt(object):
def __init__(self):
self.mapWidth = 10
self.mapHeight = 10
self.coinNumHidden = 0
self.gemNumHidden = 0
self.turns = 12
self.ge... |
""" Implementation of stats sources for cluster stats. """
import asyncio
import inspect
import logging
import time
import random
import aiohttp
from appscale.common import appscale_info
from appscale.hermes import constants, converter
from appscale.hermes.producers import (
proxy_stats, node_stats, process_stats, ... |
import heapq
import random
from itertools import product, starmap
import const
from resource import Node
'''
A tie breaker that sorts none Moves before place Moves and place Moves before
flip Moves. Thus the AI will slightly prefer doing nothing to flipping. Place
Moves are randomly sorted.
'''
def tieChoice_priorit... |
from numpy import ndindex
from Primer import product
def row_naive(n):
ans = 0
for r1 in ndindex(*([3] * 1)):
if n == 1:
ans += 1
continue
for r2 in ndindex(*([3] * 3)):
if any(a == b for a, b in zip(r1[0::2], r2[1::2])) or any(a == b for a, b in zip(r2, r2... |
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""DrQA reader utilities."""
import json
import time
import logging
import random
from collections import Coun... |
from utils import *
import pandas as pd
import datetime
import time
from math import exp
import multiprocessing as mp
#Function for splitting the dataframe processing across multiple workers
def divide_and_conquer(df):
n_workers=16
N_ROWS = round(len(df)/n_workers+1)
with mp.Pool(n_workers) as pool:
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:owefsad
# software: PyCharm
# project: lingzhi-webapi
import json
import re
import time
from dongtai.models.agent import IastAgent
from dongtai.models.project import IastProject
from dongtai.models.server import IastServer
from dongtai.models.vulnerablity import I... |
from __future__ import division
from bound import Bound
from name import XYZNamingScheme
from math import ceil, floor, log
import math, os
# Be sure to add a key point to your class to this hash after writing
# it.
# TODO: consider getting rid of this in favor of an abstract base
# class that is used to look up inhe... |
# Copyright (C) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# This work is made available under the Nvidia Source Code License-NC.
# To view a copy of this license, check out LICENSE.md
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from imaginaire.utils.distributed im... |
import numpy as np
import os
import random
from typing import List, Tuple
import paddle as torch
import paddle
from paddle import Tensor, nn
def compute_mhsa(q, k, v, scale_factor=1, mask=None):
# resulted shape will be: [batch, heads, tokens, tokens]
k=paddle.transpose(k,perm=[0,1,3,2])
scaled_dot_prod ... |
import sys
import json
import os
from ImportScoreDraft import *
def set_note_vol_pan(item, info):
if 'vol' in info:
item.shell.volume=info['vol']
if 'pan' in info:
item.shell.pan=info['pan']
# instrument initializers
def KarplusStrong(info):
inst = sd.KarplusStrongInstrument()
set_note_vol_pan(inst, info)
i... |
from mau.lexers.base_lexer import Token, TokenTypes
from mau.lexers.text_lexer import TextLexer
from mau.parsers.base_parser import BaseParser, analyse, Literal
from mau.parsers.arguments_parser import ArgumentsParser, merge_args
from mau.parsers.nodes import (
WordNode,
SentenceNode,
TextNode,
StyleNod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.