text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python
"""
@author: <NAME>, Jan 2017
Purpose: Implement Convolutional Variational Autoencoder for Semi-Supervision with partially-labeled MNIST dataset.
Use mnist_process.py to generate training, validation and test files.
"""
from tensorbase.base import Data, Model, Layers
from scipy.misc import ims... |
import argparse
import os
import shutil
import sys
import time
from pathlib import Path
import numpy as np
import tensorflow as tf
import pandas as pd
from lingofunk_generate.constants import (
BATCH_SIZE_DEFAULT,
DATA_FILE_PATH_DEFAULT,
DROPOUT_DEFAULT,
MAX_GEN_LENGTH_DEFAULT_CHAR_LEVEL,
MAX_GEN_... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from ast import literal_eval
import Rhino
import Rhino.UI
import Eto.Drawing
import Eto.Forms
class MeshDataForm(Eto.Forms.Dialog[bool]):
"""Form for working with mesh data.
Parameters
---------... |
# This module is derived from https://github.com/LingDong-/linedraw, by
# <NAME>.
import json
import math
import time
from PIL import Image, ImageOps
# file settings
export_path = "images/out.svg"
svg_folder = "images/"
json_folder = "images/"
# CV
no_cv = False
try:
import numpy as np
import cv2
except:
... |
#!/usr/bin/env python
# -*- coding: utf-8 vi:noet
# PYTHON_ARGCOMPLETE_OK
# ExMakhina reStructuredText timesheets stuff
import sys, argparse, re, datetime, decimal, logging
import datetimeparse
logger = logging.getLogger()
def printf(x):
sys.stdout.write(x)
sys.stdout.flush()
def ts_range(x):
if x is None:
t_... |
from optparse import OptionParser
class NoDefault(object):
def __nonzero__(self):
return False
class DefaultObject(object):
pass
class HookboxOptionParser(object):
def __init__(self, defaults):
parser = OptionParser()
self._add_logging_options(parser, defaults)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:
# <NAME>
#
# Contact
# <EMAIL>
#
# <NAME>,
# Biomolecular Sciences Building,
# University of St Andrews,
# North Haugh Campus,
# St Andrews,
# KY16 9ST
# Scotland,
# UK
#
# The MIT License
"""Retrieves datasets for evaluating the CAZyme prediction tools: dbCAN, CU... |
import multiprocessing
import numpy as np
from functools import partial
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import submodels_module as mb
import time
# import ray.util.multiprocessing.pool
from ray.util import ActorPool
import ray
import tensorflow as tf
def build_new_model():
'transfers weight from o... |
# data: 1-d numpy array
# model: same as self-developed 2017 model: https://drive.google.com/drive/u/1/folders/0B48QxlXgxW-GdGJ0M1ZNZDlrbW8
"""AlexNet Intention Predictor for pitch2d, built with tf.layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
... |
from datetime import datetime
import pytest
from pyinter import interval as i
from pyinter import IntervalSet
def test_interval_copy():
assert i.open(1, 4).copy() == i.open(1, 4)
assert i.openclosed(1, 4).copy() == i.openclosed(1, 4)
assert i.closedopen(1, 4).copy() == i.closedopen(1, 4)
assert i.clos... |
# Funktion til Fama-MacBeth 2-pass regression der skal bruges i Fama-French Framework
import numpy as np
from numpy import mat, mean, sqrt, diag
import statsmodels.api as sm
import pandas as pd
# Første forsøg kører med det downloadede Kenneth French data
returns = pd.read_csv(r'Data/5x5 FF.csv')
riskFactors = pd.read... |
import unittest
from dt.model import ShardKey, ForeignKey, GenericRelationship, \
Column, Table, Database, DatamodelConstants, DatabaseValidator
# -------------------------------------------------------------------------------------------------------------------
class TestColumn(unittest.TestCase):
"""Tests ... |
# -*- coding: UTF-8 -*-
import multiprocessing
import time
import signal
import argparse
import threading
import os
import queue
import sys
import datetime
import hashlib
import json
import logging
import psutil
import re
from daemon import daemonize
from urllib.request import urlopen
import socket
from configparser... |
import numpy as np
import pickle
import cvxopt
from cvxopt import matrix, solvers
import sklearn
from sklearn.metrics import classification_report, confusion_matrix , accuracy_score, mean_squared_error
from sklearn.model_selection import train_test_split
from python.svmutil import *
import time
import sys
import war... |
"""
This script is the server-side of the XML-RPC defined for gef for
BinaryNinja.
It will spawn a threaded XMLRPC server from your current BN session
making it possible for gef to interact with Binary Ninja.
To install this script as a plugin:
$ ln -sf /path/to/gef/binja_gef.py ~/.binaryninja/plugins/binaryninja_gef.... |
import itertools
import numpy as np
import tensorflow as tf
import contrib.baselines
from contrib.baselines import logger
from contrib.baselines import deepq
from contrib.baselines.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer
from contrib.baselines.deepq.utils import BatchInput
from contrib.baselin... |
import os
import pwd
import random
import tempfile
from osgtest.library import core
from osgtest.library import files
from osgtest.library.osgunittest import OSGTestCase
from osgtest.library import service
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
NAMESPACE = "st... |
import math
import re, sys, json
_param = {'B':'Number of bits reserved for parameters n',
'E':'Amplification type for parameter n',
'N':'Short name for parameter n',
'R':'Range for parameter number n',
'CALIBRATION':'Conversion of parameter values to any well defined units, e.g... |
from collections import namedtuple
from functools import lru_cache
import json
import logging
import os
import asana
import boto3
import requests
logger = logging.getLogger('asanabot')
logger.setLevel(logging.DEBUG)
s3 = boto3.resource('s3')
def process_payload(event, context):
"""Take the in-bound message and ... |
def calcular_precio_producto(coste_producto):
"""
num -> num
se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste
:param coste_producto: valor numerico del coste
:return: precio del producto
>>> calcular_precio_producto(1000)
1500.0
>>> calcular_precio_... |
"""Check the configuration for cspell.
See `cSpell
<https://github.com/streetsidesoftware/cspell/tree/master/packages/cspell>`_.
"""
import itertools
import json
import os
import textwrap
from configparser import ConfigParser
from pathlib import Path
from typing import Any, Iterable, List, Sequence, Union
import yam... |
'''
Installs the application to a server
Installs the application to a server, using the current location of the extracted files as their final location (so
extract the files from any install archive to where they should be installed first).
- Guides user through configuration file changes
- Sets up and configures the... |
# -*- coding: UTF-8 -*-
"""
strided_funcs
=============
Script : strided_funcs.py
Author : <EMAIL>
Modified : 2018-07-28
Purpose: tools for working with numpy arrays using srided functions
Useage :
Generate sequence
def seq(N=100, diff_val=1):
'''generate a sequence in the range 0, N
... |
import os
import numpy as np
import tensorflow as tf
class BasicDeepQNetwork(object):
def __init__(
self,
inputs_shape,
n_actions,
gamma=0.99,
optimizer=tf.train.AdamOptimizer(0.0001),
batch_size=32,
memory_size=10000,
summary_path=None,
):
... |
import numpy as np
from numba import jit
from ControlledSystem import ControlledSystem
def select_slice_by_dimension(shape, dim, slice_num):
idx = [slice(None)] * dim + [slice_num] + [slice(None)] * (len(shape) - dim - 1)
return tuple(idx)
def control_mask(shape, i1, i2):
mask = np.ones(shape)
mask... |
########################
# MODULE CONFIG
########################
from rapidsms.conf import settings
# annoyingly, settings.x throws a valueerror when x is not set
if hasattr(settings, 'MESSAGELOG_APP'):
# rl: not sure why i have to specifically list submodules...
messagelog = __import__(settings.MESSAGELOG_APP... |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance... |
import tensorflow.compat.v1 as tf
from detector.constants import SHUFFLE_BUFFER_SIZE, NUM_PARALLEL_CALLS, DOWNSAMPLE
from detector.input_pipeline.heatmap_creation import get_heatmaps
# height and width
CROP_SIZE = [56, 36]
class PoseResidualNetworkPipeline:
"""
"""
def __init__(self, filenames, is_train... |
#!/usr/bin/env python
# coding=utf-8
'''
* @File : file_helper.py
* @Time : 2020/07/14 16:35:39
* @Author : Hanielxx
* @Version : 1.0
* @Desc : 用于文件处理
'''
import os
import re
import sys
def get_files_prefix(path, chr_num=2):
'''
Desc:
获取path下所有文件的前缀集合
Args:
path: str --... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... |
#!/usr/bin/evn python3
import numpy as np
import torch
import torch.nn.functional as F
def detect_R_peak(data, sada_wd_size=7, fs_wd_size=12, threshold=35):
"""
Take a Batch of ECG data and find the location of the R peak
The algorithm is based on the paper:
Online and Offline Determination of QT an... |
"""Genomic interval calculations"""
import collections
from numba import njit, typeof
from numba.typed import List
from typing import Optional, Type, Union, Tuple
from typing_extensions import Literal
import numpy as np
import xarray as xr
from xarray import Dataset, DataArray
from ...dispatch import NumbaBackend, disp... |
# coding: utf-8
"""
OpenGLES.Util.Shader.py
Create and manipulate ShaderPrograms with ShaderSources.
"""
from io import IOBase
import ctypes
from OpenGLES.GLES import gles2
from OpenGLES.GLES.gles2 import *
# reload(gles2)
class ShaderSource(object):
def __init__(self, source, shader_type):
"""
Create a ... |
import six
import os
import time
import logging
import tensorflow as tf
from eight_mile.confusion import ConfusionMatrix
from eight_mile.utils import listify
from eight_mile.tf.layers import reload_checkpoint
from eight_mile.tf.optz import optimizer
from baseline.progress import create_progress_bar
from baseline.util... |
# coding=utf-8
# Copyright 2018 Google LLC & <NAME>.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView as DefaultLoginView... |
#!/usr/bin/env python3
"""
Language modeling adapted from Huggingface transformers.
The file is an adaptation of https://github.com/huggingface/transformers/blob/v3.1.0/examples/language-modeling/run_language_modeling.py
"""
import json
import logging
import math
import os
import warnings
from dataclasses import dat... |
"""
.. module: plotting
:platform: Unix
:synopsis: Functions to plot various outputs of the `Pyranha` methods.
.. moduleauthor: <NAME> <<EMAIL>>
"""
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
from pylab import cm
import numpy as np
def plot_fisher_corner(fisher_mats, labels, xcen=0,... |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
import django.core.validators
from django import forms
from django.core.exceptions import ValidationError
from django.co... |
import speech_recognition as sr
import pyttsx3
import random
import datetime
import time as t
import webbrowser
import wikipedia
import csv
import os
import cv2
import pyaudio
import playsound
from PIL import ImageTk,Image
import tkinter as ttk
import json
from chatterbot import ChatBot
from chatterbot.... |
# generated by datamodel-codegen:
# filename: openapi.yaml
# timestamp: 2021-12-31T02:54:04+00:00
from __future__ import annotations
from datetime import datetime
from enum import Enum
from typing import Annotated, Any, List, Optional
from pydantic import BaseModel, Field, SecretStr
class DeleteLexiconOutput(... |
"""
Conway's Game of Life Simulation
-----------------------------------
Language: Python
GUI Package: Pygame
GUI Menu Package: Pygame_menu
------------------------------------
Type of game: zero-player
Rules:
1) Any live cell with two or three live neighbours survives.
2) Any dead cell with three live neighbours becom... |
import logging
import os
import warnings
import joblib
import bentoml
import catboost as cb
import lightgbm as lgb
import mlflow
import dagshub
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Dropout
from preprocess impo... |
import tkinter as tk
import tkinter.ttk as ttk
import math
class LargeSep( tk.Frame ) :
def __init__( self, parent, width = 0, height = 0, bg = "", highlightthickness = 0, orient = 'horizontal', bd = 0 ) :
tk.Frame.__init__( self, parent, width = width, height = height, bg = bg, highlightthickness = highl... |
import torch.utils.data
from torch.utils.data.dataloader import default_collate
from torch_geometric.data import Data
from torch._six import container_abcs, string_classes, int_classes
import torch
from torch import Tensor
from torch_sparse import SparseTensor, cat
import torch_geometric
from torch_geometric.data imp... |
# https://deeplearningcourses.com/c/cutting-edge-artificial-intelligence
import numpy as np
import tensorflow as tf
import gym
import matplotlib.pyplot as plt
from datetime import datetime
### avoid crashing on Mac
# doesn't seem to work
from sys import platform as sys_pf
if sys_pf == 'darwin':
import matplotlib
... |
from rich.color import Color
from rich.style import Style
from rich.progress import (
BarColumn,
DownloadColumn,
TextColumn,
TransferSpeedColumn,
TimeRemainingColumn,
Progress,
ProgressColumn,
TaskID,
)
from rich.text import Text
from rich.progress_bar import ProgressBar
from rich.style... |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
from action.models import Action
from django.contrib.contenttypes import generic
from django.db import models
from entity_items.models import Advocate, ContentItem, MediaItem, TimelineItem
from etc import cache
from etc.templatetags.tags import _create_static_url
from lib.image_upload import ImageSize, ImageType, S3Ena... |
# -*- coding: utf-8 -*-
__author__ = 'ffuentes'
from abc import ABC, abstractmethod
from apps.noclook.models import User, NodeType, NodeHandle, Role
from apps.noclook.helpers import set_member_of, set_works_for
from apps.nerds.lib.consumer_util import get_user
from django.core.management import call_command
from niwe... |
#!/usr/bin/env python
from pamfax import PamFax
import logging
import socket
import sys
import unittest
import time
sys.path = ['..:'] + sys.path
IP_ADDR = socket.gethostbyname('www.dynaptico.com')
HOST = 'sandbox-api.pamfax.biz'
USERNAME = 'username'
PASSWORD = 'password'
APIKEY = 'apikey'
APISECRET = 'apisecret'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: <NAME>
# License: BSD (https://opensource.org/licenses/BSD-3-Clause)
# Date: 24/10/2021
# Import all submodules typically used in launch modules:
from .group import *
from .parameter import *
from .machine import *
from .package import *
from .logger import... |
import os
import time
import torch
from options.train_options import TrainOptions
from models.models import ModelBuilder
from models.audioVisual_model import AudioVisualModel
from data_loader.custom_dataset_data_loader import CustomDatasetDataLoader
from util.util import TextWrite, compute_errors
import numpy as np
fro... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
import django.contrib.auth as auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from apps import EftConfig
from . import models as etf_models
import json
from parser import parse... |
# https://github.com/pytorch/ignite/blob/master/examples/notebooks/FashionMNIST.ipynb
# https://www.kaggle.com/stuarthallows/using-xgboost-with-scikit-learn
import time
import sys, os
from sklearn.metrics import f1_score
idx = os.getcwd().index("trade")
PROJECT_HOME = os.getcwd()[:idx] + "trade"
sys.path.append(PROJE... |
#python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 3 15:24:02 2020
@author: lovro
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4417569/
"""
result = open("tests\\107a.txt", "r").readline()
class Node:
def __init__ (self, label, id, low, up, chain_len):
self.label = label
self.id = id
... |
import codecs
import copy
import json
import os
import uuid
import nose.tools as nt
from webtest import TestApp
import checkit.server.api as api
from checkit.backend import setup_stores, users, todo_lists
########################
# Tests initialization #
########################
# Create and initialize the test da... |
from datetime import datetime, timedelta
from enum import Enum
from pathlib import Path
from pyproj import CRS
import pytest
from shapely.geometry import LineString, MultiPoint, Point, Polygon
from tablecrow.utilities import convert_value
DATA_DIRECTORY = Path(__file__).parent / 'data'
INPUT_DIRECTORY = DATA_DIRECTO... |
import copy
import random
from functools import wraps
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms as T
from einops import rearrange
# augmentations
class RandomApply(nn.Module):
def __init__(self, fn, p):
super().__init__()
self.fn = fn
... |
#!/usr/bin/env python3
# File: cbrscraper.py
# Author: Syeerus
# License: MIT
import argparse
import json
import os
import time
import shutil
import logging
import sqlite3
import json
import scrapers.leanstream
from urllib.request import URLError
from helpers import str_to_log_level
from exceptions import UnknownScra... |
import numpy as np
import pandas as pd
import torch
import sklearn
from sklearn.neighbors import NearestNeighbors
def get_metrics(config, list_metrics, n_neighbors=2):
"""
Generates an adversarial examples x' from an original sample x. Expected to contain
Dataset, MaxIters, Alpha, Lambda, TrainDat... |
from .Manager import Manager
import uuid
import os
import sys
import yaml
import json
class LcConfigException( Exception ):
pass
class Sync( object ):
def __init__( self, oid, apiKey ):
self._confVersion = 2
self._oid = oid
self._apiKey = apiKey
self._man = Manager( self._oid,... |
import difflib
import itertools
from abc import ABC, abstractmethod
from typing import List, Optional, Union, Tuple
import attrs
from databutler.datana.generic.autodoc import few_shot
from databutler.utils import langmodels
@attrs.define(eq=False)
class NatLangToCodeChangeTask:
few_shot_examples: List[few_shot.... |
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
import six
from f3utils.service_meta import abstractmethod, _ServiceMeta
from .helpers import textescape, Integer
from .dom_meta import DOM_Meta
from six.moves.html_parser import HTMLParser
from six.moves import html_entities
from selenium.webdriver.remot... |
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker, ParseTreeListener, ErrorNode, TerminalNode
from .tptp_v7_0_0_0Lexer import tptp_v7_0_0_0Lexer
from .tptp_v7_0_0_0Parser import tptp_v7_0_0_0Parser
from .Tptp import Tptp
from collections import Counter, deque
import pandas as pd
import numpy as np
i... |
import numpy as np
import pandas as pd
from os.path import join as joinPaths
from os.path import isdir
from os.path import isfile
from os import listdir as ls
from IPython.display import display, Markdown, Latex
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
from matplotlib.pyplot import cm
# Defini... |
# Copyright (C) 2021 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
bioBakery Workflows: general tasks module
A collection of common tasks for workflows with shotgun sequences
Copyright (c) 2017 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
... |
# Copyright (c) 2011-2019, <NAME>
# License: MIT License
from typing import TYPE_CHECKING, Iterable, Union, Sequence, List, cast
import logging
from ezdxf.lldxf.const import DXFStructureError, DXFAttributeError, DXFBlockInUseError, DXFTableEntryError, DXFKeyError
from ezdxf.lldxf import const
from ezdxf.entities.dxfgf... |
# coding=utf-8
# Copyright 2017 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
#!/usr/bin/env python
#coding=utf-8
'''
Definition of OneHotEncoding class (for named entity sparse representation),
PretrainedEmbs (for pretrained embeddings) and
RndInitLearnedEmbs (for random initialized ones). # just indices starting from 1?
Embs puts everything together, using the same random seed.
@author: <N... |
#!/usr/bin/python
# Copyright (c) 2017, 2018, Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for ... |
# coding:utf-8
# Copyright (c) 2019 PaddlePaddle 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 req... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 18 15:51:45 2019
@author: Paul
"""
# Solution to Advent of Code 2019 Day 17: Set and Forget
import random
import numpy as np
import matplotlib.pyplot as plt
import time
def read_data(filename):
"""
Reads csv file into a list, and converts stri... |
from einops import rearrange
from einops.layers.torch import Rearrange
from torch import nn
from ..helpers import calc_same_padding
from .switchnorm import SwitchNorm3d
def create_conv(in_channels,
out_channels,
kernel_size,
order,
num_groups,
... |
import enum
import copy
from .vtl import vtl_compile
global_counter = 0
def not_none(thing1, thing2):
if thing1 == None:
return thing2
else:
return thing1
class SourceType(enum.Enum):
VERILOG = 1
SYSTEM_VERILOG = 2
BLUESPEC_SYSTEM_VERILOG = 3
BLUESPEC_CLASSIC = 4
SOFTWARE ... |
import tensorflow as tf
if hasattr(tf, 'enable_eager_execution'):
tf.enable_eager_execution()
from waymo_open_dataset import dataset_pb2 as open_dataset
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def show_camera_image(frame, camera_image, camera_labels, layout, cmap=None):
"""Show... |
from tkinter import filedialog, messagebox
from tkinter import ttk
import tkinter as tk
from PIL import ImageTk, Image
import os
import sys
from itertools import cycle
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('App')
logger.setLevel(logging.INFO)
IMA... |
### Main RBM code taken from: https://github.com/odie2630463/Restricted-Boltzmann-Machines-in-pytorch ###
import numpy as np
import torch
import torch.utils.data
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
from torchvision import datasets, transf... |
import pytest
import numpy as np
import torch
import time
from htvlearn.delaunay import Delaunay
from htvlearn.plots.plot_cpwl import Plot
from htvlearn.data import (
BoxSpline,
SimplicialSpline,
CutPyramid,
SimpleJunction,
DistortedGrid,
Data
)
@pytest.fixture(autouse=True)
def set_seed(requ... |
#!/usr/bin/python3
'''
--- Day 13: Shuttle Search ---
Your ferry can make it safely to a nearby port, but it won't get much further. When you call to book another ship, you discover that no ships embark from that port to your vacation island. You'll need to get from the port to the nearest airport.
Fortunately, a sh... |
from manimlib.imports import *
import numpy as np
import input_gui
import output_gui
import data
import math
T_final_matrix = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]], dtype="float64")
class Shapes(Scene):
# A few simple shapes
def construct(self):
... |
import tempfile
import subprocess
import os
import sys
import re
sys.path.append(os.path.dirname(__file__) + '../.')
from semantic_parsing.data_utils.definitions import Derivation
# YOU SHOULD NOT NEED TO LOOK AT THIS FILE.
# This file consists of evaluation code adapted from Jia + Liang, wrapping predictions and sen... |
import copy
import numpy as np
from PIL import Image, ImageChops
from matplotlib import pyplot as plt
import a_star
import tile
class board(object):
# TODO: Probabilties changes
# 0.7/3 for each terrain, 0.3 for block
def __init__(self, size=50, terrainP=[0.24, 0.23, 0.23, 0.3], failP=[0.2,... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... |
import os, shutil, time, itertools
def read_item(file_name=None, promp=False, extension=None, cf=os.getcwd()):
"""Reads an .xyz, .gjf, .com or .log item and returns a list of its contents ready for class instantiation"""
if promp != False:
if extension is None: extension = [".xyz"]
print(promp)
files ... |
#
# Cypclass transforms
#
from __future__ import absolute_import
import cython
cython.declare(Naming=object, PyrexTypes=object, EncodedString=object, error=object)
from collections import defaultdict
from . import Naming
from . import Nodes
from . import PyrexTypes
from . import ExprNodes
from . import Visitor
f... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''\
Module to facilitate the use of state design pattern.
'''
import inspect
from functools import partial
__all__ = ['State', 'stateful', 'Stateful']
class behavior():
def __init__(self, func):
self.func = func
def __get__(self, instance, owner=None):
if inst... |
#!/usr/bin/env python3
# Written by <NAME> <<EMAIL>>
# Released under the ISC license
from functools import partial
import collections
import encodings.idna
import string
class IMap:
"""Base object for supporting IRC casemapping."""
def __init__(self):
self._std = None
self._lower_chars = No... |
import os
import re
import sys
import allstat
import settings
trans = str.maketrans({"\"": "\\\"", "\\": "\\\\"})
def process_kern_return(config, context, file):
incfile = os.path.basename(file)
with open(file) as fp:
lines = fp.readlines()
line_index = -1
rexp = r'#define\s*(KERN... |
#!/usr/bin/env python3
import argparse
import os
import re
import sys
import traceback
from pyarrow import csv
def convert_to_batch(my_cccc, in_file_list, seq_num, file_ext, out_dir, out_list_file, out_seq_num_file, limit_num, limit_size, debug):
warno = 189
out_batch_file_counter = 0
batch_00_head_1 = byt... |
import json
import alfred
from functools import reduce
from collections import defaultdict
from node import Node, Interface
from link import Link, LinkConnector
class NodeDB:
def __init__(self, time=0):
self.al = alfred.alfred()
self.time = time
self._nodes = []
self._links = []
# fetch list of li... |
# -*- coding: utf-8 -*-
# Copyright 2018 <NAME>. All Rights Reserved.
# Licensed under MIT license.
#cython: language_level=3, boundscheck=False
"""Network logging support."""
#c cdef gc
import time
import struct
import socket
import gc
from collections import deque
from threading import Thread, Event, L... |
from torch.autograd import Function
import torch.nn.functional as F
import torch
import random
MAX_POSITIONS_LEN = 16000 * 50
def save_model(model, optimizer, args, current_step):
if args.method == 'PTN':
torch.save(model, f'{args.ckptdir}/{args.model}.pth')
else:
path = f'{args.ckptdir}/SE_{a... |
import math,os
from svg import Circle,Rectangle,Scene,Line,Rectangle,Text
def colorstr(rgb): return "#%x%x%x" % (int(rgb[0]/16),int(rgb[1]/16),int(rgb[2]/16))
'''def test(s):
a=s[0]
b=s[1]
scene = Scene('test')
scene.add(Rectangle((100,100),200,200,(255,255,255)))
# scene.add(Line((200,200),(200,300... |
from collections import ChainMap
import argparse
import os
import random
import sys
from torch.autograd import Variable
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data as data
import copy
import matplotlib.pyplot as plt
from .spec_aug import freq_mask, time_mask, time_warp
from . import mo... |
# SPDX-FileCopyrightText: Copyright 2021, <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileType: SOURCE
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the license found in the LICENSE.txt file in the root directory
# of this source tree.
# =======
#... |
# -*- coding: utf-8 -*-
import tensorflow
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow.keras as keras
#import uuid for uniquely naming solutions
from uuid import uuid4
#from keras.models import model_from_json
#supress warnings because they serve no purpos... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Dependencies
import os
import numpy as np
import pandas as pd
from bom1 import *
import argparse
import difflib
import re
import shutil
import time
import threading
import queue
#Counter to show which files are done - previous progress counter will yield result... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.