text stringlengths 3.07k 22.1k |
|---|
import os
import codecs
import numpy as np
import torch
import torch.utils.data
import torch.nn.functional
import matplotlib.pyplot as plt
import argparse
from data_provider import cv_dataset, cv_dataset_inference
from network import Spatial_RNN
from utils import tprint, get_batch_PSNR
from conf import config_general
... |
import pandas as pd
import numpy as np
import multiprocessing
import os
import pywt
import json
import quaternion
from pandas.io.json import json_normalize
# File manipulation
def generatePath(pointer, timeSeriesName):
"""
Outputs the path to find the specified JSON file.
Input:
- pointer: float
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import json
from datetime import datetime
import numpy as np
from scipy.interpolate import interp1d
from dateutil import parser
def totimestamp(datetime_object):
"""Because in python2 datetime doesn't have timestamp() method,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import decimal
import datetime
from scipy.optimize import fsolve
from django.db import models
from django.urls import reverse
from django.utils.html import format_html
class Currency(models.Model):
class Meta:
... |
"""
Script that trains a NOGO coarse classifier.
To use tensorboard during or after model training, open a terminal and say:
conda activate vesper-dev-tf2
tensorboard --logdir "/Users/harold/Desktop/NFC/Data/Vesper ML/NOGO Coarse Classifier 0.0/Logs"
and then visit:
127.0.0.1:6006
in Chrome... |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
#
# Copyright (c) 2015 <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, including without limitation th... |
#
# dens.py
# Handles the main use-cases for our program.
#
from flask import ( Blueprint, flash, g, redirect, render_template, request, url_for )
from werkzeug.exceptions import abort
from bobchat.auth import login_required
from bobchat.db import get_db
bp = Blueprint('dens', __name__, url_prefix='/dens')
... |
import tensorflow as tf
import tensorflow.keras.layers as Layers
import tensorflow.keras.activations as Actications
import tensorflow.keras.models as Models
import tensorflow.keras.optimizers as Optimizer
import tensorflow.keras.metrics as Metrics
import tensorflow.keras.utils as Utils
from keras.utils.vis_utils import... |
import os
import pickle
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
from .randaugment import RandomAugment
from sklearn.preprocessing import OneHotEncoder
from .utils_algo import generate_uniform_cv_candidate_labels
import copy
def load_cub200(input_size, partial_r... |
import sys
import argparse
import datetime
import json
import numpy as np
import os
import tensorflow as tf
#os.environ["CUDA_VISIBLE_DEVICES"]='2'
from config import load_arguments
args=load_arguments(1)
from TextCNN import TextCNN
import logging
logger = None
def setup_custom_logger(name, log_level):
formatter... |
# -*- coding: utf-8 -*-
from operator import getitem
from africanus.averaging.time_and_channel_mapping import (
row_mapper as np_row_mapper,
channel_mapper as np_channel_mapper)
from africanus.averaging.time_and_channel_avg import (
row_average as np_row_average,
... |
#! -*- coding: utf-8 -*-
# 用seq2seq的方式做阅读理解任务
# 数据集和评测同 https://github.com/bojone/dgcnn_for_reading_comprehension
# 8个epoch后在valid上能达到约0.77的分数
# (Accuracy=0.7259005836184343 F1=0.813860036706151 Final=0.7698803101622926)
import json, os, re
import numpy as np
from bert4keras.backend import keras, K
from bert4keras.ber... |
import discord
import requests
import os
client = discord.Client()
#If you wish to hardcode the variables (for testing, it's a security risk if you do it for production), you can do that here
DISCORD_BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN')
GOOGLE_API_KEY = os.getenv('GOOGLE_API')
GOOGLE_SPREADSHEET_ID = os.getenv('... |
from manimlib.imports import *
class Plot1(GraphScene):
CONFIG = {
"y_max" : 100,
"y_min" : 0,
"x_max" : 10,
"x_min" : 0,
# x,y 轴分别的刻度
"y_tick_frequency" : 10,
"x_tick_frequency" : 1,
"axes_color" : BLUE,
"y_label_direction": RIGHT,
... |
from dash_website.app import APP
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash
import pandas as pd
import numpy as np
from dash_website.utils.controls import get_item_radio_items
from dash_website ... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from PyQt4 import QtGui, QtCore # , uic
import pineboolib
#from pineboolib.qsaglobals import ustr
from pineboolib.utils import DefFun
from pineboolib import decorators
Qt = QtCore.Qt
# TODO: separar en otro fichero... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
selfsupervised3d.dataset.blendowski
datasets to support blendowski-style self-supervised learning methods
References:
[1] M. Blendowski et al. "How to Learn from Unlabeled Volume Data:
Self-supervised 3D Context Feature Learning." MICCAI. 2019.
[2] htt... |
import sys
sys.path.append('../')
import click
import os
import torch
import logging
from filelock import FileLock
import random
import numpy as np
import logging
import ray
from ray import tune
from ray.tune import track
from ray.tune.suggest.ax import AxSearch
from ax.plot.contour import plot_contour
from ax.plot.tra... |
import numpy as np
import time
from perception import to_polar_coords
def slice_polar_coords(dist, angles, dist_range, angle_range):
"""
Returns a subset of pixel radial distances and angles, such that any pixel's radial distance and angle fall within specified range
:param dist: list of pixel radial dista... |
import numpy as np
from numpy import ndarray
def plane(img: ndarray) -> ndarray:
assert img.ndim == 2
h, w = img.shape
ret = np.ones((3 * h, 3 * w), dtype=np.uint8)
for i in range(8):
r, c = (7 - i) // 3, (7 - i) % 3
ret[r * h: (r + 1) * h, c * w:(c + 1) * w] = \
np.bitwise... |
import ctypes
from yololayer import *
from Utils.common import GiB
USE_FP16=False
USE_INT8=False
TRT_LOGGER = trt.Logger(trt.Logger.WARNNING)
# Force init TensorRT plugins
trt.init_libnvinfer_plugins(TRT_LOGGER, "")
input_name = 'data'
out_name = 'prob'
# Calculate the width and depth of CSP
# For yolov5s, gw,gd=0.50... |
'''
block_followers
===============
Block followers of a certain accounts, by screen-name.
Block followers **does** not block an account if the account is
whitelisted. See [whitelist.py](whitelist.py) for more information.
# Warnings
The rate-limiting factor is the number of API calls, w... |
import os
import argparse
import time
import load_data
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
from models.LSTM import LSTMClassifier
from models.LSTM_Attn import AttentionModel
from models.selfAttention import SelfAttention
from to... |
"""
This module contains some wrappers for using ASE to perform
various operations on BigDFT molecules.
https://wiki.fysik.dtu.dk/ase/
"""
from ase.calculators.calculator import Calculator
def bigdft_to_ase(sys):
"""
Given a BigDFT system, this transforms that system into an ASE
collection of atoms.
... |
import glob
import json
import os
import shutil
import gzip
import yaml
def get_new_d3m_path():
"""
Gets the name of the newest version path for d3m/byudml
:return:
"""
new_directory = max(glob.glob('submission/primitives/primitives'))
byu_path = "byu-dml"
byu_dir = os.path.join(new_direc... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Evaluate the ensemble of 4 CTC models (Librispeech corpus)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join, abspath
import sys
import yaml
import argparse
import re
from tqdm im... |
from functools import wraps
import os.path as path
import jinja2
from generators import ecs_helpers
# jinja2 setup
TEMPLATE_DIR = path.join(path.dirname(path.abspath(__file__)), '../templates')
template_loader = jinja2.FileSystemLoader(searchpath=TEMPLATE_DIR)
template_env = jinja2.Environment(loader=template_loader... |
#!/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.
'''Edit from OpenQA'''
import os
import json
import subprocess
import torch
import logging
import regex as re... |
import networkx as nx
import geopandas as gpd
import pandas as pd
from tqdm import tqdm
from shapely.geometry import Point
import numpy as np
import ast
import osmnx as ox
from shapely.ops import cascaded_union
import os
import time
def calculate_min_travel_time(gdf):
other_road_type = []
for idx, row in gdf.... |
"""
Credits:
Copyright (c) 2018-2020 <NAME>
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
Copyright (c) 2017-2022 <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (Sinergise)
This source code is licensed under the MIT license found in the LICENSE
file in the root directory of this source tree.
"""
i... |
#!/usr/bin/env python3.6
from random import random
from pathlib import Path
from multiprocessing.pool import Pool
from typing import Any, Callable, Iterable, List, Set, Tuple, TypeVar, Union
import torch
import numpy as np
import scipy as sp
import scipy.ndimage
from tqdm import tqdm
from torch import einsum
from to... |
from .soc_algo import _SamplingAndOcclusionAlgo
from .lm import BiGRULanguageModel
from .train_lm import do_train_lm
import os, logging, torch, pickle
import json
import itertools
logger = logging.getLogger(__name__)
class SamplingAndOcclusionExplain:
def __init__(self, model, configs, tokenizer, output_path, dev... |
import json
from abc import ABC, abstractmethod
import xmltodict
from harvestmouseapp.mvc_model.model import Mouse, MouseList, Record, AdvancedRecord
class MouseModelAdapter(ABC):
"""
This is the Mouse Model Adapter Class.
Subclass must implement the transform the any expected
raw_data into either Mou... |
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
from skimage import io
from skimage.morphology import convex_hull_image, watershed, skeletonize_3d
from skimage import img_as_float
from skimage.color import rgb2gray
from skimage.filters import gaussian
from skimage.segmentation import active_c... |
import numpy as np
from pylops.utils.backend import get_array_module
try:
import pyfftw
except:
pyfftw = None
def _chirp_radon_3d(data, dt, dy, dx, pmax, mode='f'):
r"""3D Chirp Radon transform
Applies 3D Radon transform using Fast Fourier Transform and Chirp
functions. (mode='f': forward, 'a':... |
# Generated by rpcgen.py from /home/nickolai/proj/go-rpcgen/rfc1057/prot.x on Fri Dec 6 10:47:00 2019
import const
class opaque_auth:
# XDR definition:
# struct opaque_auth {
# auth_flavor flavor;
# opaque body<400>;
# };
def __init__(self, flavor=None, body=None):
self.flavor =... |
import pandas as pd
from pandas import DataFrame
df_tennis = DataFrame.from_csv('tennis.csv')
print("\n Given Play Tennis Data Set:\n\n",df_tennis)
#df_tennis.columns[0]
df_tennis.keys()[0]
#Function to calculate the entropy of probaility of observations
# -p*log2*p
def entropy(probs):
import math
return su... |
import curses
import pprint
import gc
import re
import os
import sys
import subprocess
from io import StringIO,BytesIO
import pytest
import pyodbc
import os
import shutil
import random
from datetime import datetime,timedelta
import keyring
from elasticsearch import Elasticsearch
import shutil
def screen_size( rows, co... |
# coding: utf-8
#details of awesome oscillator can be found here
# https://www.tradingview.com/wiki/Awesome_Oscillator_(AO)
#basically i use awesome oscillator to compare with macd oscillator
#lets see which one makes more money
#there is not much difference between two of em
#this time i use exponential smoothing on ... |
from numba import jit, njit
import numba
from PIL import Image
import numpy as np
from .heatmap_to_points import *
try:
import cv2
except ModuleNotFoundError:
printing("UNALBE TO IMPORT OpenCV", print_types.WARNING)
__all__ = ["gray_norm_stats","rgb_norm_stats","square_image","load_image","load_heatmap","bat... |
# -*- coding: utf-8 -*-
import asyncio
import datetime
import logging
import os
import platform
import requests
import subprocess # nosec
import sys
import textwrap
import time
import webbrowser
from bz2 import BZ2Decompressor
from collections import OrderedDict
BUFFER_SIZE = 128 * 1024
BROWSER = os.getenv('BROWS... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 6 20:33:56 2019
@author: abhigyan
"""
import numpy as np
"""Class state to initialize various states in a Gridworld (the various positions
at which a users might find themselves). It has attributes like position, state
type (transient/recu... |
"""Standard library imports"""
# Django imports
from django.contrib.auth import get_user_model, authenticate, login
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic import TemplateView, View
from django.template.response import TemplateResponse
from django.http import HttpResp... |
# importing requisite libraries
from stockstats import StockDataFrame as sdf
import requests
from dotenv import load_dotenv
import os
import pandas as pd
import numpy as np
import alpaca_trade_api as tradeapi
from pathlib import Path
def fetch_ohlcv(ticker, start_date= "2020-01-01", end_date = "2021-01-01"):
""... |
import random
from main.mongo_handler import Mongo
import discord
from discord.ext import commands
import os
import time
import cv2
MAX_MESSAGE_LENGTH = 256
class Card:
def __init__(self, suit=None, rank=None, value=None):
"""
Card object holds suit, rank, and value properties
:param suit... |
from unittest import mock
import pytest
import cbpro
class TestClientMessaging:
def test_send_message(self):
client = cbpro.PublicClient()
with mock.patch.object(client.session, 'request'):
client._send_message(
'post',
'/endpoint',
pa... |
# Copyright (c) 2017-2022 Reveal Energy Services, 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 appli... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import neurogym as ngym
from neurogym import spaces
class PerceptualDecisionMaking(ngym.TrialEnv):
"""Two-alternative forced choice task in which the subject has to
integrate two stimuli to decide which one is higher on average.
A noisy ... |
"""Implementation of the service."""
import asyncio
import queue as sync_queue
from contextlib import suppress
from copy import deepcopy
import logging
import sys
import traceback
from .config import Config
from .exceptions import Abort
__all__ = ('Application',)
class Application:
"""A service application.
... |
# -*- coding: utf-8 -*-
"""
Psychoinfomatics and Neuroinformatics
Final Project
Find discriminative words in all articles on Dcard.
NTUEE3 B03901014 <NAME>
NTUEE3 B03901015 <NAME>
"""
from dcard import Dcard
#import pickle
import re
#from dataIO import TypeResultWrapper, WordResultWrapper
import dataIO
import os, sy... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""TEST api.py
"""
from errno import EINVAL
from sys import maxsize as sys_maxsize
from random import seed as rnd_seed
from random import randint as rnd_randint
from fastapi import status
from fastapi.testclient import TestClient
import pytest
from app.kapibara.api imp... |
"""Unit tests for openjpeg."""
from io import BytesIO
import os
try:
import pydicom
from pydicom.encaps import generate_pixel_data_frame
from pydicom.pixel_data_handlers.util import (
reshape_pixel_array, get_expected_length, pixel_dtype
)
HAS_PYDICOM = True
except ImportError:
HAS_PYD... |
import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from nn_model.replay_memory import ReplayBuffer
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, max_action=1):
super(Ac... |
import argparse, random, os, glob
import numpy as np
import torch
import torch.nn as nn
from dgl_model.gin_all import GIN
from dgl_model.gcn_all import GCN, GCN_dp
from torch.utils.data import DataLoader
from ogb.graphproppred.dataset_dgl import DglGraphPropPredDataset, collate_dgl
from ogb.graphproppred ... |
import os
from pathlib import Path
from subprocess import check_call
from charms import layer
from charms.reactive import hook
from charms.reactive import set_state, remove_state
from charms.reactive import when
from charms.reactive import set_flag, clear_flag
from charms.reactive import endpoint_from_flag
from charm... |
from __future__ import print_function
import pandas as pd
import numpy as np
import os
import sys
import gzip
import argparse
try:
import configparser
except ImportError:
import ConfigParser as configparser
from keras import backend as K
from keras.layers import Input, Dense, Dropout, Activation, Conv1D, Max... |
# -*- coding: utf-8 -*-
"""
Módulo: Resultados
Diseño: Eliana
Código: M.Alejandra y Eliana
---
Este módulo contiene la clase Resultados, cuya escena muestra el resultado final obtenido, para lo cual necesita los parámetros 'puntos' y 'vidas'.
También la clase Ranking, que es la escena final, que... |
"""The GainTables used for easy access to the gain of a node. The
gain of a node is here the decrease in cut when switching the part
of this node.
"""
__author__ = "<NAME>"
__version__ = "1.0"
import bisect
from collections import defaultdict
import copy as cp
import random as rd
from crack.models.models_fcts i... |
# ====================================================================================== #
# Enumerate module for writing equations for Potts models. There are many different kinds
# of ways of parameterizing Potts models especially in the face of limited data. Here are
# a few particular examples that may be useful.
#... |
"""Common transforms refactored as CALLABLES."""
import numpy as np
import scipy.signal as signal
from .spectemp import pncc, modspec, invspec
from .spectral import logpow
from .window import hamming
from .transform import stft, istft
from .fbanks import Gammatone, ConstantQ, MelFreq
class STFT(object):
"""Short... |
import subprocess
import global_var
from util import *
from render import *
from loss import *
from torch.optim import Adam
import shutil
from applications import interpolate_single_texture
sys.path.insert(1, 'materialGAN/higan/models/')
from stylegan2_generator import StyleGAN2Generator
np.set_printoptions(precision=... |
import os
import logging
from chibi.atlas import Chibi_atlas
from chibi.file import Chibi_path
from chibi_command.lxc import lxc
from chibi_command.lxc import delegate as lxc_delegate
from chibi_command.rsync import Rsync
from chibi_hybrid import Class_property
from chibi_lxc.file.config import Chibi_lxc_config
from ch... |
from __future__ import print_function, unicode_literals
from datetime import date, datetime, timedelta
from dateutil import rrule
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import (GenericForeignKey,
... |
"""A simplified API to the Paris SAT solver.
SATProblem allows you to add certain kinds of expressions to the SAT
problem. The expressions are represented as nested Conjunctions and Disjunctions
with True/False used directly as booleans and any other object treated as a
variable name.
"""
import collections
import lo... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .misc import *
OUT_DIM = {2: 39, 4: 35, 6: 31}
LOG_FREQ = 1000
class Flatten(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return x.view(x.size(0), -1)
class Share... |
#!/usr/bin/env python
#
# ** The MIT License **
#
# Copyright (c) 2013 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
# imports
from opentrons import protocol_api
from opentrons.commands.commands import blow_out
# metadata
metadata = {
'protocolName': 'Prep BioER Deepwell Plate for E32 Extraction.',
'author': '<NAME> <<EMAIL>>',
'description': 'Making a BioER plate with beads, lysis buffer, wash1-3 and NFW.',
'apiLeve... |
#!/usr/bin/env python
# file: vid2webm.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2018 <NAME> <<EMAIL>>.
# SPDX-License-Identifier: MIT
# Created: 2018-12-16T22:45:15+0100
# Last modified: 2019-07-27T21:17:04+0200
"""
Convert videos to webm files, using 2-pass constrained rate VP9
encoding for vid... |
from bs4 import BeautifulSoup
def section(name: str, level: int, id=None, unnumbered=False):
"""Creates a new tag with the correct structure for a section.
Parameters:
- name: str, is the name of the header.
- level: int, 1 is section, 2 is subsection and so on.
- id: str, optional, the id for referencing this se... |
import click
import dedupe
import untrash
import subset
import frequencies
# used to tell Click that -h is shorthand for help
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group()
def cli():
click.echo('Utils launched.')
# START CLI COMMANDS
@cli.command('dedupe', context_settings=CONTEXT_SE... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
---------------------------------------------... |
__author__= """<NAME> (<EMAIL>)"""
__revision__="0.5"
#! /usr/bin/python;
import os
import subprocess
import re
import csv
import sys
def expr_cor_parallel_script(bsize, cnt=292146, log=False, qtype="short"): # c
dnjobs = "jobs/lsf_scripts"
if log:
dncor = "ndar_intermediate/cor_mat_log"
dat... |
#!/usr/bin/python
from __future__ import print_function
#Python Libraries
import os.path, sys
from glob import glob
from decimal import Decimal
from optparse import OptionParser
#Read molecule data from an input file
class getoutData:
def __init__(self, file):
if not os.path.exists(file):
prin... |
# -*- coding: utf-8 -*-
from abc import ABC
from PyQt5.QtCore import Qt, QRect, QRectF
from PyQt5.QtGui import QBrush, QColor
from PyQt5.QtWidgets import QStyle, QStyleOptionButton, QTreeWidgetItem, QListWidgetItem
_author_ = 'luwt'
_date_ = '2022/1/21 13:57'
# 默认空的rect
none_rect = QRect(0, 0, 0, 0)
class ItemPai... |
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from collections import OrderedDict
from networks.custom_layers import EqualizedLinear, EqualizedConv2d, \
NormalizationLayer, _upscale2d
from networks.building_blocks import EarlySynthesisBlock, LaterSynthesisBlock, \
Ea... |
#!/usr/bin/python3
# Copyright 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publi... |
from __future__ import with_statement
import random, threading, time
from nose.tools import assert_equal # @UnresolvedImport
from whoosh import analysis, fields, formats, reading
from whoosh.compat import u, xrange
from whoosh.filedb.filereading import SegmentReader
from whoosh.filedb.filestore import RamStorage
fro... |
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""Functional tests for :module:`flocker.node.gear`."""
import os
import json
import subprocess
from unittest import skipIf
from twisted.trial.unittest import TestCase
from twisted.python.filepath import FilePath
from twisted.internet.defer import succeed
... |
from disnake.ext import commands
import disnake
import asyncio
import time
import numpy as np
from PIL import Image
from utils.discord_utils import (
AuthorView,
autocomplete_log_canvases,
autocomplete_canvases,
format_number,
image_to_file,
)
from utils.setup import db_canvas, db_users, stats
from... |
import os,time,re,sys
import speech_recognition as sr
from webcam import Webcam
import docker,time,json,bcrypt
from getpass import getpass
EMOTIONS = ['enervé', 'dégoûté', 'apeuré','joyeux', 'triste', 'surpris', 'neutre']
def abspath(file):
return os.path.abspath(os.path.dirname(file))+"/"
path_volume= abspath(_... |
import os
import re
import json
import subprocess
def write_html_begin(version):
if not os.path.exists('./trackLinkmapObjSize/'):
os.mkdir('./trackLinkmapObjSize/')
html_file_path = './trackLinkmapObjSize/trackLinkmapObjSize%s.html' % version
file = open(html_file_path, 'w+')
file.write('<html... |
import torch
import torch.nn as nn
import torch.utils.data as data
import numpy as np
import pytorch_lightning as pl
from pytorch_lightning.loggers import TensorBoardLogger
import time
import os
from src.maths.dennet import DENNet
from src.mechanics.hamiltonian import HNN1DWaveSeparable
from src.time_integrator_1DWa... |
"""
This file takes the ~2950 samples from the preliminary data set and checks that the number of content paragraphs is
also appropriate. Since our histogram indicates that there are quite a few articles that don't have too many
content lines in themselves.
Further, we remove special characters, and create mappings for... |
from datetime import datetime
from easedate.easedate import *
# TODO:
# Human-intelligible date
# https://strftime.org/ apply theses rules
def test_parse_from_dd_mm_yyyy_to_yyyy_mm_dd():
result = str_to_date("22/03/2020", input_format="%d/%m/%Y")
assert result == parse("2020-03-22")
def test_parse_f... |
#!/usr/bin/env python3
# coding=utf-8
"""
SQLite persistence layer for FleetScraper.
Created: <NAME>, 17.03.2021
Modified:
"""
import logging
import sqlite3 as sql
from pyutilities.pylog import setup_logging
# setup logging for the whole script
setup_logging(default_path="logging.yml")
log = logging.g... |
# -*- coding: utf-8 -*-
# @Time : 2021/01/02 16:55
# @Author : lishijie
import os
import sys
import pathlib
import torch
import numpy as np
from torch import cat, nn
from torch.nn import functional as F
import math
from torch.nn.modules import linear
import torchvision.models as torch_models
__dir__ = pathlib.Pa... |
import argparse
import pandas as pd
import os
import random
from random import choices, sample
import numpy as np
from collections import defaultdict, Counter
from itertools import combinations
from helpful_functions import safe_open_w
def readArgs ():
parser = argparse.ArgumentParser (description="swapping code ")
... |
import ezdxf
AAMA_CUT = "1"
AAMA_DRAW = "8"
AAMA_INTCUT = "11"
def filterlayerelements(d, layernames):
return [ e for e in d.entities if (e.dxf.layer in layernames) and (e.dxftype() not in ["MTEXT", "INSERT"]) ]
def linearizeelement(e):
if e.dxftype() == "LINE":
return [e.dxf.start, e.dxf.end]
... |
# Copyright 2020-present, Netherlands Institute for Sound and Vision (<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 requ... |
import os
import tensorflow as tf
import numpy as np
from tensorflow.contrib import layers
from tensorflow.python import debug as tf_debug
from tensorflow.python.debug.lib.debug_data import InconvertibleTensorProto
from rl.common.pre_processing import get_input_channels
from rl.common.util import compute_entropy, safe... |
import itertools
from mite_vspkg.src.util import util_const
from mite_vspkg.lib import vsdownload
def get_possible_MSI_combos(MSIs_lists):
return list({frozenset(c) for c in itertools.product(*MSIs_lists)})
def get_light_req_MSIs(mite_payloads_info, payload_name):
def prioritize_MSI_combo(MSI_combo):
... |
#!/usr/bin/env python
"""Harness for running benchmarks.
This module handles all aspects of running a series of benchmarks with
pre-built executables and emitting the results into a central location for
further processing.
It's currently very focused on HHVM and php-octane, but it could be generalized
because it uses... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/7 14:51
# @Author : 一叶知秋
# @File : sign_api_sec.py
# @Software: PyCharm
from django.http import JsonResponse
from sign.models import Event
from sign.models import Guest
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from djan... |
from utils import *
from pprint import pprint
import operator
from random import sample
import copy
import re
import csv
import ast
# only to make prediction possible
import pandas as pd
import time
from sklearn.preprocessing import OneHotEncoder
import numpy as np
from sklearn.model_selection import train_test_split
c... |
""" mfdn_v14_b06.py -- MFDn version 14 beta06 wrappers for mcscript
Environment variables
MFDN_NDIAG (int) : number of diagonal processes (optional)
Created by <NAME>, University of Notre Dame.
8/2/14 (mac): Originated, based on old wrappers in ncsm.py.
5/13/15 (mac): Insert "future" statemen... |
import fire
import os
import os.path as osp
import numpy as np
import pandas as pd
from cytokit import config as cytokit_config
from cytokit.ops import cytometry
from cytokit.ops import tile_generator
from cytokit.ops import tile_crop
from cytokit.utils import ij_utils
from cytokit import io as cytokit_io
from cytokit ... |
"""
This module defines a Fastai `Learner` subclass used to train Self-Organizing Maps.
"""
import pathlib
from functools import partial
from typing import Callable, Collection, List, Optional, Tuple, Type, Union
import numpy as np
import pandas as pd
import torch
from fastai.callback.core import Callback
from fastai.... |
# MODULE: ppc64-simple-components
# CLASS: ppc970-simple
from sim_core import *
from components import *
# Generic Simple System for PPC64 Processors
class ppc64_simple_base_component(component_object):
basename = 'system'
connectors = {
'uart0' : {'type' : 'serial', 'direction' : 'down',
... |
import os.path
import unittest, textwrap
import urllib.request, urllib.error, urllib.parse, urllib.request, urllib.parse, urllib.error
from PIL import ImageFont, Image, ImageDraw
'''
Base image downloader & processing class
This will download image, put caption & description if passed
and export to given path
This ... |
'''Commands:
Setting the color mask:
s: (save) save hsv threshold values and line length, starts main loop.
Bucle principal:
c: (clear) Resets all values so you can start another set.
p: (plot)
q: (quit)
'''
'''for it to work you have to draw a line on the 'frame' screen, so it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.