text stringlengths 3.07k 22.1k |
|---|
"""ShutIt module. See http://shutit.tk
"""
from shutit_module import ShutItModule
class docker_1_10(ShutItModule):
def build(self, shutit):
# Some useful API calls for reference. See shutit's docs for more info and options:
#
# ISSUING BASH COMMANDS
# shutit.send(send,expect=<default>) - Send a command, w... |
#########################
## ##
## <NAME> ##
## May 10, 2021 ##
## ##
#########################
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
from statsmodels.tools.tools import add_constant
from ... |
# Copyright 2006 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""defines controller classes which help to define the function transformation
The idea behind implementation of "Function Transformation" f... |
#!/usr/lib/supl-proxy/venv/bin/python3
# -*- coding: utf-8 -*-
import argparse
import asyncio
from binascii import a2b_hex
from copy import deepcopy
from datetime import datetime
from functools import partial
import glob
import json
import logging
from logging.handlers import RotatingFileHandler
import os
from python_... |
# Copyright (c) 2018 The Regents of the University of Michigan
# and the University of Pennsylvania
#
# 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 li... |
import os, logging, shutil, time, json, configparser
import tempfile, uuid
import io, base64
from PIL import Image
from flask import Flask
from flask import request
from collections import OrderedDict
from flask_cors import CORS
print("...importing Ludwig")
from ludwig import LudwigModel
ROUND_FLOATS_TO = 10
# imag... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Twitter analysis helpers. Command line interface is a work in progress.
Usage:
twitter.py init <app_key> <app_secret>
twitter.py [options] user <username> words [minimum] [maximum] [limit] [words | count]
twitter.py [options] user <username> dates [minimum] [max... |
# -*- coding: utf-8 -*-
"""
Tests for the ElementPath implementation.
"""
from __future__ import absolute_import
import unittest
from copy import deepcopy
from .common_imports import etree, HelperTestCase
def summarize(elem):
return elem.tag
def summarize_list(seq):
return list(map(summarize, seq))
def n... |
#!/usr/bin/env python
import numpy as np # For efficient utilization of array
import cv2 # Computer vision library
import os # Here this package is used writing CLI commands
import vlc_ctrl
import time
import pandas as pd
import os # package used for controlling vlc media player
import subproc... |
#!/usr/bin/python
# Copyright (c) 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 detail... |
# -*- coding: utf-8 -*-
"""
@author: AngelFGC
"""
# https://github.com/joshuaskelly/twitch-observer
from twitchobserver import Observer, ChatEventType
import sys
import time
import queue
import re
import random
import operator
import math
########################
# GLOBALS
########################
# Manages how ofte... |
'''
U-Net implementation in PyTorch (Ronneberger et al., 2015).
Adapted from 2019 <NAME> (source: https://raw.githubusercontent.com/jvanvugt/pytorch-unet/master/unet.py).
2020 <NAME>
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class UNet(nn.Module):
def __init__(self, lab... |
#!/usr/bin/env python3
#
# Copyright (c) 2021 Seagate Technology LLC and/or its Affiliates
#
# 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
#
... |
import datetime
from collections import defaultdict
from functools import cmp_to_key
import json
import os
import re
from dotenv import load_dotenv
import requests
from tabulate import tabulate
load_dotenv()
holiday_calendar_url = os.environ['HOLIDAY_CALENDAR_URL']
token = os.environ['GITHUB_TOKEN']
org_name = os.en... |
"""
ARCHES - a program developed to inventory and manage immovable cultural heritage.
Copyright (C) 2013 <NAME> and World Monuments Fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either ... |
"""
@package mi.instrument.ooici.mi.test_driver.test.test_driver
@file marine-integrations/mi/instrument/ooici/mi/test_driver/driver.py
@author <NAME>
@brief Test cases for test_driver driver
USAGE:
Make tests verbose and provide stdout
* From the IDK
$ bin/test_driver
$ bin/test_driver -u [-t testna... |
# Created By: <NAME>
# Created On: 2009-10-22
# Copyright 2013 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_... |
from copy import deepcopy
def form_Matrix(l,row ,col):#l: list of inputs row wise
M = []
c = 0
for i in range(row):
m = []
for j in range(c,col+c):
m += [l[j]]
c += 1
M += [m]
return M
def filtermatrix(M):
N = []
row = len(M)
col = len(M[0])
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pickle
import sys
import numpy as np
import inception_input
from tensorflow.contrib.learn.python.learn.datasets import base
from tensorflow.python.framework import dtypes
class DataSet(object):
... |
"""transforms_s.py
SUPER-transforms to apply to lists of plots before fitting
These are transforms that operate on a list of multiple plots as a whole.
For example, combine_like will combine multiple plots that share a common set
of properties into a single plot.
Definitions:
plot:
4-tuple (xarray, yarray... |
from __future__ import annotations
import copy
import json
import dataclasses
import pathlib
from hashlib import sha256
from io import TextIOWrapper
from typing import Optional, List, Dict, cast, Union, Any
import atomicwrites
import toml
from toml.decoder import TomlDecodeError
from ..semver import VersionConstraint... |
import torch
import torch.nn as nn
from .generalization import RandomBatchGeneralization, BatchGeneralization
from .generalization import GeneralizationDoNothing
from torchvision import models
from .function import onehot, do_nothing
from .attention import VisionTransformer, EmbeddingBnReLU2222, EmbeddingFactory
from .... |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import argparse
parser = argparse.ArgumentParser(description='PyTorch CIFAR10... |
import kivy
kivy.require('1.10.0')
from kivy.lang import Builder
Builder.load_file('ui/layout.kv')
import _global_
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.image import Image
from kivy.graphics.texture import Texture
from kivy.cl... |
"""ESMValTool CMORizer for ESRL data.
Tier
Tier 2: other freely-available dataset.
Source
https://www.esrl.noaa.gov/gmd/dv/data/
ftp://aftp.cmdl.noaa.gov/data/trace_gases/co2/
Last access
20201126
Download and processing instructions
Download the txt files from the ftp server/data interface
""... |
#!/usr/bin/env python3
import os
import cv2
import numpy as np
import pandas as pd
import tensorflow as tf
from tqdm import tqdm
from glob2 import glob
from skimage import transform
from skimage.io import imread, imsave
from sklearn.preprocessing import normalize
from sklearn.metrics import roc_curve, auc
from tensorf... |
import warnings
from functools import partial
import numpy as np
import pandas as pd
from estimagic.benchmarking.cartis_roberts import CARTIS_ROBERTS_PROBLEMS
from estimagic.benchmarking.more_wild import MORE_WILD_PROBLEMS
from estimagic.benchmarking.noise_distributions import NOISE_DISTRIBUTIONS
def get_benchmark_p... |
# -*- coding: UTF-8 -*-
from logging import warning
import os
import numpy as np
from sympde.topology import Cube, Mapping
from psydac.api.postprocessing import OutputManager, PostProcessManager
from psydac.fem.basic import FemField
from psydac.utilities.utils import refine_array_1d
NUM_DIMS_LOGICAL = 3
NUM_DIMS_... |
#!/usr/bin/env python
""" methods for reading the findNeighbour config file
A component of the findNeighbour4 system for bacterial relatedness monitoring
Copyright (C) 2021 <NAME> <EMAIL>
repo: https://github.com/davidhwyllie/findNeighbour4
This program is free software: you can redistribute it and/or modify
it unde... |
from __future__ import absolute_import
import logging
import sys
import threading
import uuid
from pykka.exceptions import ActorDeadError
from pykka.proxy import ActorProxy
from pykka.registry import ActorRegistry
__all__ = [
'Actor',
'ActorRef',
]
logger = logging.getLogger('pykka')
class Actor(object):... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class SobelConv2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,
padding=0, dilation=1, groups=1, bias=True, requires_grad=True):
assert kernel_size % 2 == 1, 'SobelConv2d\'s kernel_siz... |
import itertools
from collections import defaultdict
import numpy as np
import pandas as pd
from fancyimpute import KNN
from sklearn.preprocessing import StandardScaler
class DataProcessor:
"""
processes data, is well adapted for processing training DataFrame,
- deals with missing data,
- converts co... |
#!/usr/bin/env python3
supported_extensions = ['jpeg', 'jpg', 'gif', 'png']
import os
import cv2
import numpy as np
# Load and preprocess image
def load_image(image_path, # Full path to processing image
target_size, # Desired size of resulting image
intermediate_siz... |
"""
This file contains the primary server code for the SFTP server.
See COPYING for license information.
"""
from zope import interface
from collections import defaultdict
from twisted.conch.interfaces import ISFTPServer, ISession
from twisted.python import components, log
from twisted.internet import defer
from twis... |
from scipy.ndimage.filters import gaussian_filter
from scipy.interpolate import RectBivariateSpline
from scipy.ndimage.interpolation import zoom
import numpy
def upsampleL(fieldmap, activation_data, reduction=1, shape=None,
scaleshape=None, out=None):
'''
Applies a bilinear upsampling.
'''
... |
"""
CLI defined here
When adding new function:
1. add a func_register_subparser function to register the subparser
2. add a condition in main func about this new func name, import the real func as func in main
"""
import argparse
import inspect
import subprocess
import sys
import logging
log = logging.getLogger()
D... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.optimizer import Optimizer
def policy_kl(p0_mu, p0_sigma, p1_mu, p1_sigma):
c1 = torch.log(p1_sigma/p0_sigma + 1e-5)
c2 = (p0_sigma**2 + (p1_mu - p0_mu)**2)/(2.0 * (p1_sigma**2 + 1... |
from mayavi import mlab
from torch.utils.data import Dataset
from utils.draw_utils import draw_lidar, draw_gt_boxes3d
from utils.data_classes import PointCloud, Box
from pyquaternion import Quaternion
import numpy as np
import pandas as pd
import os
import torch
from tqdm import tqdm
import utils.kitty_util... |
#!/usr/bin/env python
"""Deal with stuck bits in HiRISE pixels via unflipping.
This program will attempt to unflip the bit-flipped pixels.
Only the image area is affected. This is also an older approach
and is less supported than bitflips.py.
Please see bitflips.py for a more detailed explanation of
the HiRISE bit-fl... |
from typing import Sequence
import pandas as pd
import numpy as np
import logging
import sys
import click
import joblib
from pathlib import Path
from collections import OrderedDict
from sklearn.metrics import roc_auc_score, accuracy_score, average_precision_score, f1_score, \
confusion_matrix, classification_repo... |
import contextlib
import functools
import math
import skia
from .document import RecordingDocument
from .errors import DrawbotError
from .gstate import GraphicsState
class Drawing:
def __init__(self, document=None, flipCanvas=True):
self._stack = []
self._gstate = GraphicsState()
if docum... |
import jsonlines
import rltk
import time
import re
def compare_cpu(g2a_min_cpu_1, techpowerup_cpu, g2a_min_cpu_2=None, max_score_1=-1, max_score_2=-1):
# techpowerup_cpu_reader = jsonlines.open(techpowerup_cpu, 'r')
similar_id_1 = ''
similar_id_2 = ''
most_similar_cpu_1 = ''
most_similar_cpu_2 = '... |
#!/usr/bin/env python3
import argparse
import os
from os import path
import pandas as pd
from cobra.io import read_sbml_model, write_sbml_model
from cobra.util import solvers
from corda import CORDA
from corda.util import reaction_confidence
from fastcore import Fastcore
from csm4cobra.io import read_json
from csm4co... |
# -*- coding: utf-8 -*-
import json
import re
import shlex
from django.db.models import Lookup
class FilterTree:
"""This class should properly assemble the pieces necessary to write the WHERE clause of
a postgres query
The jsonb_filter_field property of your view should designate the
name of the colu... |
import os
import imageio
import pandas as pd
import time
from scipy.stats import pearsonr
from scipy.ndimage import zoom
from ct_slice_detection.inout.dataloader import image_slide_generator
from ct_slice_detection.inout.preprocessing import *
from .generic_utils import printProgressBar
def get_best_loc(loc, heigh... |
import numpy as np
import h5py as h5
import os
from optparse import OptionParser
import matplotlib.pyplot as plt
from matplotlib import gridspec
import tensorflow as tf
from tensorflow.keras import backend as K
import tensorflow.keras.layers as layers
from tensorflow.keras import Sequential
from tensorflow.keras.layers... |
import os, shutil, pytest, random, time
import pyslabs
here = os.path.dirname(__file__)
prjdir = os.path.join(here, "workdir")
workdir = os.path.join(prjdir, "slabs")
slabfile = os.path.join(prjdir, "test.slab")
npslabsdir = os.path.join(here, "numpy_slabs")
NPROCS = 3
NSIZE = 10
NITER = 5
#<EMAIL>.fixture(autouse=T... |
#!/usr/bin/env python
"""
########################################################################
# Author: <NAME>
# Email: <EMAIL>
# Github: https://github.com/cruizperez
# Institution: Georgia Institute of Technology
# Version: 1.0.0
# Date: Nov 13, 2020
# Description: This script... |
#! /usr/bin/env python
"""
Module with utilities to estimate the spectral type and gravity of an object
based on spectral indices.
.. [GOR03]
| Gorlova et al. 2003
| **Gravity Indicators in the Near-Infrared Spectra of Brown Dwarfs**
| *The Astrophysical Journal, Volume 593, Issue 1, pp. 1074-1092*
| `ht... |
__author__ = ("<NAME> <mrost AT inet.tu-berlin.de>, "
"<NAME> <aelvers AT inet.tu-berlin.de>")
__all__ = [
"get_active_plan_dict",
"get_rooms_by_day",
"check_plan",
"get_schedule_per_tutor",
"get_tutorials_by_time",
"get_tutorials_for_tickets",
"get_extended_tutorials_for_tick... |
# ======================================================================
# Copyright CERFACS (February 2018)
# Contributor: <NAME> (<EMAIL>)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/or redistribute ... |
from __future__ import unicode_literals
from django.contrib import admin, messages
from django.db import transaction
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils.decorators import method_decorator
from dja... |
import sys
import argparse
import itertools
import collections
import push.hosts
import push.utils
__all__ = ["parse_args", "ArgumentError"]
class MutatingAction(argparse.Action):
def __init__(self, *args, **kwargs):
self.type_to_mutate = kwargs.pop("type_to_mutate")
argparse.Action.__init__(se... |
# Copyright (c) 2016, <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the foll... |
import copy
import os
import time
from os.path import join as pjoin
from splinter import Browser
from splinter.exceptions import ElementDoesNotExist
from BilayerBrowserProcess import BilayerBrowserProcess
from InputBrowserProcess import InputBrowserProcess
def init_module(test_cases, args):
"""Preprocesses test ca... |
import re
from csv import DictReader
from functools import partial
from io import BytesIO
from operator import attrgetter
from pathlib import Path
from typing import Callable, Iterator, Sequence, Optional
from cytoolz import first, keyfilter
from dustgoggles.pivot import split_on
import googleapiclient.discovery as di... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from cnn import element_wise_op
from activators import SigmoidActivator, TanhActivator, IdentityActivator
class LstmLayer(object):
def __init__(self, input_width, state_width,
learning_rate):
... |
import json
import os
import shutil
import traceback
import uuid
import zipfile
import requests
from flask import current_app as app
from flask import request
from flask_jwt_extended import current_user
from werkzeug import secure_filename
from app.api.helpers.db import save_to_db
from app.api.helpers.errors import S... |
"""
libyate - engine command definitions
"""
from abc import abstractmethod
from datetime import datetime
import libyate.type
_id = id
KW_CLS_MAP = {}
class CommandMeta(libyate.type.DescriptorMeta):
"""Meta class for Yate command objects"""
def __new__(mcs, name, bases, attrs):
cls = super(Comma... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from .. import _logging as logging
from .core import *
__all__ = [
'Quant_DenseLayer',
'Quant_Conv2d',
'Quant_Layer',
]
def _quantize_median(x, k):
G = tf.get_default_graph()
n = float(2**k)
with G.gradient_override_map({"Round": "Identity"}):... |
# Copyright 2006 <NAME>
# 2013-2014 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation
from gi.repository import Gtk
from quodlibet.qltk.msg import confirm_action
from quod... |
import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import seaborn as sns
def heatmap(matrix=None, out_path=None, boundary=[], diag=False, matrixPath=None, boundaryPath=None):
if matrixPath:
matrix = np.loadtxt(matrixPath)
if boundaryPath:
b... |
from __future__ import print_function
import argparse
import logging
import pprint
import os
import mxnet as mx
import numpy as np
from rcnn.config import config, default, generate_config
from rcnn.symbol import *
from rcnn.core import callback, metric
from rcnn.core.loader import AnchorLoader
from rcnn.core.module im... |
#!/usr/bin/env python
from kafka import SimpleClient
from kafka.protocol.offset import OffsetRequest, OffsetResetStrategy
from kafka.common import OffsetRequestPayload
from kafka import KafkaClient
from kafka import KafkaConsumer
from kafka import TopicPartition
from kafka import KafkaProducer
import json
from pymongo ... |
#!/usr/bin/env python
"""This script pulls completed subjects from the Scribe mongodb for Workflow 1, writes
these annotations and coordinates to the workflow database, adds business groupings to the
Data_Source table, then pulls relevant metadata from the workflow database and outputs CSV files
of business grouping... |
"""
Copyright 2021 by <NAME> and <NAME>
This file is part of the Thermostat Enhancer presented for MakeUofT
Written by <NAME> <<EMAIL>>, February 2021
"""
import time
import board
import busio
import dht11
import mysql.connector
import pigpio
import os.path
import logging
import adafruit_ads1x15.ads1115 as ADS
from ... |
"""
Different ways to analyze data to search for rhythms in behavior
"""
import numpy as np
from scipy import stats
import statsmodels.api as sm
from statsmodels.stats.multitest import multipletests
from skimage import measure
from .utils import dft
def ar_surr(x, fs, k_perm, freq_cutoff=15, correction='cluster'):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from datetime import date, timedelta
import calendar
from slack_sdk import WebClient
import argparse
import subprocess
import re
from collections import defaultdict
import gzip
# Example:
# python loginbonus.py
#
post_to_slack = True
slacktoken_file = 'slack_to... |
import ast
import csv
import os
import pygame
import pygame.freetype
from pygame.transform import scale
class PreviewBox(pygame.sprite.Sprite):
main_dir = None
effectimage = None
def __init__(self, pos):
import main
SCREENRECT = main.SCREENRECT
self.widthadjust = SCREENRECT.width... |
from typing import List, Optional, Tuple
import dask
import numpy
from arbol import aprint, asection
from dask.array import Array
from joblib import Parallel, delayed
from dexp.processing.registration.model.sequence_registration_model import (
SequenceRegistrationModel,
)
from dexp.processing.registration.model.t... |
from copy import copy
import numpy as np
import torch
import torch.nn as nn
import pdb
class GRUEncoder(nn.Module):
def __init__(self, input_dim, hidden_dim, z_dim, num_embeddings, device):
super(GRUEncoder, self).__init__()
self.z_dim = z_dim
self.hidden_dim = hidden_dim
self.d... |
'''
## Bezier discretization
For efficient discretization by arc-length we need the arclength along a 4-point cubic bezier curve.
The 4 point bezier curve is given by
$$ (1-t)^3 p_0 + 3 t (1-t)^2 p_1 + 3 t^2 (1-t) p_2 + t^3 p_3 $$
The analytic closed form of arclength $s$ of a *quadratic* bezier curve is [1]
$$ s = (t+... |
"""
Config loader
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Any, Dict, List, Optional, Type, TypeVar
import yaml
CommandType = TypeVar("CommandType", bound="Command")
ProjectType = TypeVar("ProjectType", bound="Project")
var_pattern = re.compile(r"\{\{\s*project\.... |
import json
from numbers import Number
from pathlib import Path
from typing import Mapping, Iterable, Optional, List
import torch
import tqdm
from torchvision.utils import save_image as _save_image
from homura import liblog
from homura.utils import is_master, get_args
from homura.utils._vocabulary import *
from .base... |
from __future__ import print_function
from itertools import product
from copy import deepcopy, copy
from collections import namedtuple
from pddlstream.algorithms.instantiation import Instantiator
from pddlstream.algorithms.scheduling.recover_streams import evaluations_from_stream_plan, get_achieving_streams
from pddls... |
# -*- coding: utf-8 -*-
"""A parser for Microsoft Train Simulator/Open Rails (SIMISA@@@) text files."""
import re
import typing as typ
from dataclasses import dataclass
from enum import Enum
from itertools import chain
class ParserException(RuntimeError):
def __init__(self, subject, message):
self.subjec... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Lightweight and configurable .ini config parser with dot notation property access.
Features:
- dot notation (value = cfg.section.property);
- customizable parsing options;
- no dependencies inside, only plain Python;
- can handle text files, multiline ... |
from datetime import timedelta
import pytest
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.core.validators import URLValidator
from apps.core.models import Board, Article, Comment
from tests.conftest import RequestSetting, TestCase
@pytest.fixture(scope='class')
de... |
__author__ = "mlovati"
import random as rnd
deltalimit = 0
raw = open("dipinto.ppm","r")
raw2 = raw.read()
lines = raw2.split("\n")
width = int(lines[1].split(" ")[0])
height = int(lines[1].split(" ")[1])
matrix_toedit = [[[]for m in range (0,width)]for n in range(0,height)]
for c in range(0,height):
for ... |
"""
sableye_data_collect.py - Collect data from sableye's sensors.
Public:
* detect()
* set_up_([Device])
* record_from_([Device])
* sableye__record(Device, [options])
* sableye__stream(Device, [options])
* sableye__pause(Device, [options])
* sableye__close(Device, [options])
modified: 5/1/2... |
import numpy as np
"""
Coordinate helpers:
Images in are treated as numpy arrays as they are in cv2.
numpy uses the convention of a .shape which is in (vertical, horizontal) order.
To prevent getting confused by this, the following helpers all aliasing
of .x, .y and .w, .h properties
Naming conven... |
import datetime
import pprint
import numpy
from spacy.gold import GoldParse, minibatch
from spacy.language import _pipe
from spacy.pipeline.pipes import Language
from spacy.scorer import Scorer
from spacy.util import compounding, minibatch_by_words, env_opt, load_model_from_path
from tqdm.auto import tqdm
from models... |
# -*- coding: utf-8 -*-
'''
###############################
Acme::MetaSyntactic::doctor_who
###############################
****
NAME
****
Acme::MetaSyntactic::doctor_who - The Doctor Who theme
***********
DESCRIPTION
***********
This theme uses names of various people, places and things from the original
run (... |
# Copyright (c) 2019, 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 required by applic... |
import csv
import json
import operator
import os
import sqlite3
import urllib.request
from raven import Client
from flask import Flask, request, session, g, redirect, make_response, url_for, abort, escape, render_template, flash, send_from_directory
from passwords import SENTRY_DSN
client = Client(SENTRY_DSN) #add de... |
import os
import sys
import time
import torch
import numpy as np
_, term_width = os.popen('stty size', 'r').read().split()
term_width = int(term_width)
TOTAL_BAR_LENGTH = 35.
last_time = time.time()
begin_time = last_time
def progress_bar(current, total, msg=None):
global last_time, begin_time
if current == ... |
"""
Goal:
* Get monero seed nodes from /src/p2p/net_node.inl.
How to:
* for default values and how to use the tool
- python get_monero_seed_nodes.py --help
* current master:
- python get_monero_seed_nodes.py
- python get_monero_seed_nodes.py --branch master
* It is also possible to set the branch n... |
import os
from contextlib import contextmanager
import pytest
import tempfile
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from peewee import IntegrityError
from cryp_to_go import interface, co... |
import argparse
import os
import torch
from settings import Settings as stng
import utils.evaluator as eu
from quicknat import QuickNat
from solver import Solver
#utility imports
import utils.data_utils as du
from utils.data_loader import ToTensor, NiftiData
from utils.log_utils import LogWriter
import shutil
impor... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class Complex(object):
''' Simple Complex Number Class for pytorch '''
def __init__(self, real, imag=None):
''' if imag is none we divide real --> [re, im]'''
if imag is no... |
import math
from uuid import uuid4
from django.db import models
from django.db.models import Sum
class Voting(models.Model):
voting_name = models.CharField(max_length=50)
voting_description = models.CharField(max_length=200, blank=True)
max_votes = models.IntegerField(default=1)
is_open = models.Bool... |
import os
import sys
from colorama import init, Fore, Style
import number_quiz
import pronounciation_review
import gender_review
import plurals_review
import edit_voca
init()
normal_vocas_path = './vocas/normal_voca'
grammatical_vocas_path = './vocas/grammatical_voca'
normal_vocabulary_book = {}
grammer_vocabulary_boo... |
#FIXME: UNDO, click time at end to undo
from PyQt4 import QtCore, QtGui
import sys, os
import volume_editor_layout, settings_layout, cPickle
import numpy as np
from utils import Utils
class SettingsEditWidget(QtGui.QDialog, settings_layout.Ui_Dialog):
#################################################### Init
... |
from sklearn.metrics import classification_report, f1_score, cohen_kappa_score, accuracy_score, mean_absolute_error
from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split
from models.auto_encoder_model import RecurrentAutoencoder
from torch.uti... |
#!/usr/bin/env python
from __future__ import print_function
from keras.losses import binary_crossentropy, sparse_categorical_crossentropy
from keras.losses import categorical_crossentropy, mean_squared_error
from keras.optimizers import SGD, Adam, Adadelta, Adagrad
from keras.optimizers import Adamax, RMSprop, Nadam
... |
"""This is an actual recursive-descent parser.
I'm sorry I didn't find something funnier to do here."""
from abc import ABC, abstractmethod
from collections import namedtuple
import typing as T
def is_number_char(c: str) -> bool:
"""Check if char c is part of a number."""
return c.isdigit() or c == "."
def... |
from PIL import Image, ImageDraw
from tqdm import tqdm
import numpy as np
import pdb
import cv2
DEFAULT_HEIGHT = 640
DEFAULT_GAUSSIAN_KERNEL_SIZE = (11, 11)
DEFAULT_GAUSSIAN_KERNEL_VARIANCE = 1.5
def preprocess(image):
'''Takes in a pillow image and resizes it to a fixed height preserving aspect ratio
Args:
... |
# -*- coding: utf-8 -*-
__author__ = '<NAME>'
import copy
import warnings
from warnings import warn
from colorama import init
from colorama import Fore, Back, Style
init(autoreset=True)
warnings.simplefilter('ignore')
class Field(object):
SHAPE = [
['#', '#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#', '#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module for fetching/storing encrypted credentials from/to a local file."""
import argparse
import base64
import dotenv
import os
import pickle
from getpass import getpass
from pbkdf2 import PBKDF2
from Crypto.Cipher import AES
from Crypto import Random
class KeyStor... |
import math
import svgwrite
import bpy
import logging
import io
import mathutils
import operator
logger = logging.getLogger("svg_exporter")
class SvgExporter(bpy.types.Operator):
bl_idname = "svg.exporter"
bl_label = "Export SVG"
location_matrix = mathutils.Matrix((
[1.0, 0.0, 0.0],
[0.0, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.