text stringlengths 3.07k 12.6k |
|---|
#
# Copyright © 2022 <NAME>, <NAME>, <NAME>,
# <NAME>, <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 t... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
import logging
import re
from django import forms
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from core.utilities import time_jump
from core.utilities import discover_type
from .models import CertificateMonitor, DomainMonitor, IpMonitor
from .tasks import GEOLOCATIO... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: layers.py
# Author: <NAME> <<EMAIL>>
import numpy as np
import tensorflow as tf
from tensorflow.contrib.framework import add_arg_scope
import lib.utils.utils as utils
# import tensorcv.models.layers as layers
INIT_W_STD = 0.02
@add_arg_scope
def conv_bn_leaky(
... |
# -*- coding: utf-8 -*-
"""
# @file name : camvid_dataset.py
# @author : JLChen
# @date : 2019-08-21 10:08:00
# @brief : CamVid数据集的Dataset定义
"""
import os
import torch
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms.functional as ff
import torchvision.transforms... |
from dragonfly import get_engine, get_current_engine, FuncContext, Function, MappingRule, Grammar, Choice, Dictation
from castervoice.lib import printer
engine = get_current_engine().name
if engine == 'natlink':
import natlink
class EngineModesManager(object):
"""
Manages engine modes and microphone stat... |
import collections
import inspect
import json
import jsonschema
import os
import sys
from pprint import pprint
from datacatalog import settings
from datacatalog.extensible import ExtensibleAttrDict
from ...dicthelpers import data_merge
from ...jsonschemas import DateTimeEncoder, formatChecker, DateTimeConverter
from .... |
import os
import time
import uuid
import json
import datetime
import io
import shutil
import base64
import hashlib
from pydub import AudioSegment
import wave
from PIL import Image, ImageDraw, ImageFont
from flask import Blueprint
from flask.views import MethodView
from flask import (request, jsonify,
... |
import jq
import json
import re
import sys
import glom
import runAM
class GlomDict(dict):
def assign(self, glom_path, value):
glom.assign(self, glom_path, value, missing=dict)
class PortConfigGenerator(runAM.db.JSONStore):
def generatePortConfigData(self):
"""Generate low level data to par... |
#!/usr/bin/env python
"""
plot_permeate.py
Purpose: Plot PMF or diffusivity profiles. Check that units in script are
consistent with units in input files.
Examples:
- python plot_permeate.py -i pmf_symmetrized_with_errbars.dat --pmf -w 'talk'
- python plot_permeate.py -i diffusivity_symmetrized.dat ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
通常情况下,GEO MINiML formatted family文件,包含三个部分:
1. 以GSM*.txt模式的样本表达文件,一个文件代表一个样本,通常有多行、两列,
一行代表一个探针,第一列是探针ID、第二列是该探针在该样本的表达值
2. 以GPL-*.txt为模式的平台文件,该文件每一行代表一个探针,第一列是探针ID,
还有一个其他的列有该探针对应的gene symbol
3. 以GSE*-family.xml为模式的样本表型信息XML文件
以下子命令的作用:
1... |
import random
# State at which the game is still processing 'drawing cards'.
# This helps preserve the streamlining, as some data may end up
# being sent first.
drawing = 0
# This is for collecting callbacks, where all will be fired as soon
# as the 'drawing' state is back to 0.
drawing_queue = []
info = {
"stun": [
... |
"""Pen recording operations that can be accessed or replayed."""
from fontTools.misc.py23 import *
from fontTools.pens.basePen import AbstractPen, DecomposingPen
from fontTools.pens.pointPen import AbstractPointPen
__all__ = [
"replayRecording",
"RecordingPen",
"DecomposingRecordingPen",
"RecordingPoi... |
#! /usr/bin/env python3
"""Generate LL(1) parse table and token info from Grammar definition"""
from string import Template
from operator import itemgetter
from itertools import chain
from pathlib import Path
from simplecompiler.generate import generate_grammar
from simplecompiler.util import format_code, double_qout... |
from __future__ import absolute_import, print_function
import json
import os
import re
import flask_assetrev
from flask import g, render_template, request, send_from_directory
#from raven.contrib.flask import Sentry
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
from sqlalchemy.sql.expre... |
import random
from itertools import chain
import warnings
import torch
import torch.nn.functional as F
from transformers import GPT2LMHeadModel, GPT2Tokenizer
SPECIAL_TOKENS = ["<bos>", "<eos>", "<speaker1>", "<speaker2>", "<pad>"]
ATTR_TO_SPECIAL_TOKEN = {
"bos_token": "<bos>",
"eos_token": "<eos>",
"p... |
"""
Create Contiguity-based Spatial Weights Files.
Author(s): <NAME>, <NAME>, <NAME>, <NAME>
"""
import arcpy as ARCPY
import pysal as PYSAL
import pysal.lib.io as FileIO
import pysal.lib.weights as WEIGHTS
import SSUtilities as UTILS
import SSDataObject as SSDO
import pysal2ArcUtils as AUTILS
import WeightsUtilities... |
import os
import requests
import shutil
import gzip
import pprint
import json
pp = pprint.PrettyPrinter(indent=4)
__base_url__ = 'https://www.encodeproject.org/'
__root_dir__ = '/media/dna/ENCODE_idr_20Jan_2017/'
ALLOWED_FILETYPES = ['bed narrowPeak', 'bed broadPeak']
def safe_makedir(dname):
"""Make a directory ... |
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
# Create your models here.
@python_2_unicode_compati... |
"""Contains :class:`InputStream` to allow for input sources other than devices."""
__author__ = '<NAME>'
__version__ = '1.0'
__all__ = ['generate_input_stream',
'input_stream_parameters',
'register_input_stream',
'input_stream',
'InputStream']
import abc
import enum
import ... |
"""
Original code by <NAME> here: https://github.com/aspamers/siamese/blob/master/mnist_siamese_example.py commit: 7b48475
Modified by <NAME> so it would work with the "theta" data from here: https://github.com/flag0010/pop_gen_cnn/tree/master/theta.
A siamese neural network is used to pre-train an embedding for the... |
from typing import Type
from pyntcloud import PyntCloud
import numpy as np
from pyntcloud.io import obj
from . import binvox_rw
import os
import shutil
PLY = "PLY"
NPY = "NPY"
BINVOX = "BINVOX"
FILE = "FILE"
FILELIST = "FILELIST"
OBJ = "OBJ"
def _get_filename(file):
return os.path.splitext(os.path.basename(file)... |
#!/usr/bin/env python3
'''---------------------------------------------------------------------------------------'''
# Thomas (Desnord)
# entrada: A entrada do programa será de 9x9 dígitos de 0 a 9,
# onde 0 representa as posições com valores indefinidos que devem ser resolvidas.
# saida: A saída do program... |
from django.shortcuts import Http404, render,HttpResponse,get_object_or_404,HttpResponseRedirect,redirect
from .models import elan
from .forms import elanform
# from .forms import postform
from django.contrib import messages
from django.db.models import Q
from datetime import datetime, time, date, timedelta
import date... |
from phylo._core.genotypematrix import *
import pytest as pt
import pandas as pd
import numpy as np
def stub_matrix():
return GenotypeMatrix([[0, 0, 0], [0, 0, 0], [1, 0, 0]], ['a', 'b', 'c'], ('sabbia', 'pollo', 'facocero'))
class Test_Accessors:
def test_cells(self):
a = stub_matrix()
asser... |
# The MIT License (MIT)
# Copyright (c) 2018 Massachusetts Institute of Technology
#
# Author: <NAME>
# This software has been created in projects supported by the US National
# Science Foundation and NASA (PI: Pankratius)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softwa... |
import numpy as np
import torch
from torch import nn
EPSILON = 1e-8
def count_leaves(depth):
return int(2 ** depth)
def reshape_mask(mask):
return mask.unsqueeze(1).reshape((int(mask.size(0) / 2), 2))
class Layer(nn.Module):
def __init__(self, in_features, depth, tying_ratio):
super().__init_... |
# -*- coding: latin-1 -*-
# Copyright (c) 2008 Pycircuit Development Team
# See LICENSE for details.
import unittest
from nose.tools import *
from numpy.testing import assert_array_almost_equal, assert_array_equal
from pycircuit.utilities.param import *
def test_parameter():
p = Parameter('name', desc='Descripti... |
'''
Gaussian Mixture Model code.
============================
This code is meant to be imported by another Python script to be run.
Here is an example of usage. This will test all neurons in 'en-es-1.desc'
for f1 selectivity for words that end in 's'. It can also be found in gmm_example.py
```
import gmm
import json... |
import PIL.Image
from PIL.ExifTags import TAGS, GPSTAGS
import sys
import json
import os
#36867 DateTimeOriginal = 2014:07:31 18:57:42
#274 Orientation = 1
#270 ImageDescription = {"MAPDeviceMake":"Samsung","MAPCameraMode":1,"MAPCaptureTime":"2014_07_31_18_57_43_182","MAPSettingsEmail":"<EMAIL>","MAPLocalTimeZone":"+0... |
from multiprocessing.pool import Pool
import numpy as np
from scipy import sparse
from sklearn.base import TransformerMixin
from sklearn.pipeline import FeatureUnion, _fit_one_transformer, _fit_transform_one, _transform_one, _name_estimators
from sklearn.utils.metaestimators import _BaseComposition
class FeatureUnio... |
import re
import sys
import cv2
import numpy as np
from skimage import io
import warnings
warnings.filterwarnings("ignore")
block = 8
# standard quantization matrix
Quantization = np.array(
[
[16, 11, 10, 16, 24, 40, 51, 61],
[12, 12, 14, 19, 26, 58, 60, 55],
[14, 13, 16, 24, 40, 57, 69, 5... |
import csv
import logging
import sys
if sys.version_info >= (3, 0):
import configparser as ConfigParser
else:
import ConfigParser
import requests
from os.path import dirname, join
from datetime import datetime
from lxml import etree
from zipfile import ZipFile
from io import BytesIO
from carto.auth import APIK... |
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import tkinter.messagebox
import sidebar_treeview
import status_box
from styling import tkinter_styles_
from data_pages import data_page_frontend
from data_pages import data_page_backend
from data_pages import d... |
#!/usr/bin/env python
'''
This software was created by United States Government employees at
The Center for the Information Systems Studies and Research (CISR)
at the Naval Postgraduate School NPS. Please note that within the
United States, copyright protection is not available for any works
created by United Sta... |
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
import sys
import datetime
from dateutil.parser import parse
import logging
from urlparse import urlparse
from pyquery import PyQuery as pq
fr... |
from ..tools.dynamical_model_utils import unspliced, mRNA, vectorize, tau_inv, get_vars
from .utils import make_dense
import numpy as np
import matplotlib.pyplot as pl
from matplotlib import rcParams
def get_dynamics(adata, key='fit', extrapolate=False, sorted=False, t=None):
alpha, beta, gamma, scaling, t_ = ge... |
import builtins
import os
import pytest
from dp_builder.const import ROOT_PATH
from dp_builder.pythons_file_worker import PythonFileWorker
settings_path = os.path.join(ROOT_PATH, 'tests', 'unit', 'data', 'settings.py')
settings_content = """#Test sections to check get sections
from pathlib import Path
# Build paths... |
import argparse
import csv
import itertools
import os
import mir_eval
import numpy as np
import matplotlib.pyplot as plt
from chord_recognition.cache import HDF5Cache
from chord_recognition.dataset import prepare_datasource, ChromaDataset, collect_files
from chord_recognition.predict import ChordRecognition
def plo... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
By <NAME>
Find any QTLs near SNPs found to be significant in the Sorghum QTL Atlas
"""
import sys
import argparse
from sqlalchemy import create_engine
def parse_arguments():
"""Parse arguments passed to script"""
parser = argparse.ArgumentParser(description... |
import logging
import sys
import unittest
import json
import zlib
from types import ModuleType
import numpy as np
from numpy.testing import assert_equal
from ..base import open
_log = logging.getLogger(__name__)
# hijack cothread
assert 'cothread' not in sys.modules
CM = ModuleType('cothread')
sys.modules['cothre... |
import copy
import random
import networkx as nx
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from cogdl import options
from cogdl.datasets import build_dataset
from cogdl.models import build_model
from . import BaseTask, registe... |
import yaml
import os
from hybridbosse.hybrids_shared_infrastructure.run_BOSSEs import run_BOSSEs
from hybridbosse.hybrids_shared_infrastructure.PostSimulationProcessing import PostSimulationProcessing
import pandas as pd
# Main API method to run a Hybrid BOS model:
def run(hybrids_input_dict):
"""
Returns a ... |
import os
import pkg_resources
import argparse
try:
from pip import main as pip_install
except:
from pip._internal import main as pip_install
"""
Python script to build python project environment.
Responsibilities:
- check if a virtual environment exists on global python, if not it will install it -
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 19:32:58 2020
@author: Danish
"""
import json
import os
import numpy as np
def key_id_generator(id_type, allowed_counts=50):
if id_type=='LifeTime':
if allowed_counts<int(10e8):
raise ValueError('Invalid value given to argument `allowed_count... |
import base64
import logging
import binascii
import string
import xml.sax.saxutils
from sdb import SDB_TAGS
from sdb import SDB_TAG_TYPES
g_logger = logging.getLogger("sdb_dump_common")
g_logger.setLevel(logging.DEBUG)
def getTagName(header):
tagname = SDB_TAGS.vsReverseMapping(header.tag)
if tagname is Non... |
import paddle.fluid as fluid
import numpy as np
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.dygraph.nn import Pool2D, BatchNorm, Linear ,Conv3D #Conv2D,
from paddle.fluid.dygraph.base import to_variable
class ConvBNLayer(fluid.dygraph.Layer):
def __init__(self,
name_sco... |
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from django.views.generic import DetailView, UpdateView, ListView, CreateView
from .models import Profile, Message, Client
from .forms import ReviewForm, UserProfileForm, MessageForm,... |
#
# 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 appl... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... |
import torch
from torch import nn
import numpy as np
import torch.nn.functional as F
def num_pixels(tensor):
assert tensor.dim() == 4
return tensor.size(2) * tensor.size(3)
class _BaseInvertibleConv2d(nn.Module):
def _get_w(self):
raise NotImplementedError
def _get_w_inv(self):
rais... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped, TwistStamped
from tf.transformations import euler_from_quaternion, quaternion_from_euler
from std_msgs.msg import Float64, Int64
import tf
def pos_reference_cb(msg):
global pos_reference_msg
pos_reference_msg = msg
def stage_idx_cb(msg):... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2018-2022 Amano Team
from pyrogram import Client, filters
from pyrogram.enums import ParseMode
from pyrogram.errors import BadRequest
from pyrogram.types import InlineKeyboardMarkup, Message
from eduu.config import PREFIXES
from eduu.database.welcome import get_welcome, ... |
import warnings
import datetime
import elasticsearch
from elasticsearch import Elasticsearch, RequestsHttpConnection
from core.helpers.hevlog import Hevlog
from core.helpers.sleeper import Sleeper
from core.helpers.networking import Networking
hevlog = Hevlog('elasticsearch', level='info')
# TODO: These are expect... |
""" <NAME>, University of Warwick, March 2018
Extraction and handling of routing info
"""
from urlparse import urlparse
import re
from copy import deepcopy
import match_heuristics as mh
class simple_node:
""" Tree node for a given route
Contains the endpoint name, full route, and details such as decorators
Also ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 13:56:01 2020
@author: <NAME>
"""
import numpy as np
import numpy.linalg as LA
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
xs = np.array([[0,0,0],
[0,1,0],
[0,2,0],
[0,3,0... |
import enum
import time
import random
import threading
class StatesPhilosopher(enum.Enum):
'''
Representa los posibles estados de los filosofos.
'''
thinking = 1
hungry = 2
eating = 3
left_fork = 4
right_fork = 5
finished_eat = 6
class Philosopher:
def __init... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = [
'colorizeansi',
'ttyautocolorizeansi',
'combineansi',
'colorize',
'ttyautocolorize',
'combine',
'escapeset',
'escapereset',
'escapefgcolor',
'escapebgcolor',
'ColoredSetting',
]
import sys, enum, abc, collections
fr... |
# -*- coding: utf-8 -*-
"""Tests for the subplots module.
BSD 3-Clause License
Copyright (c) 2020-2021, <NAME>
All rights reserved.
"""
import numpy as np
import pytest
from matplotlib import collections
from matplotlib import patches
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
... |
import logging
import torch.nn as nn
from ..runner import load_checkpoint
from .utils import constant_init, kaiming_init, normal_init
def conv3x3(in_planes, out_planes, dilation=1):
'3x3 convolution with padding.'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, padding=dilation, dilation=dilation)
d... |
import gzip
import pickle
import matplotlib
matplotlib.use('Agg')
import sys
from argparse import ArgumentParser
from tqdm import tqdm
import imageio
import numpy as np
from skimage.transform import resize
import torch
from imageio import mimread
from skimage import io, img_as_float32
from skimage.color import gray2r... |
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
import os
import pandas as pd
from app import app
from . import db
dt = db.live_data_history()
dropdown... |
import argparse
import os
import time
from multiprocessing.pool import Pool
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from raw import Possession
p = argparse.ArgumentParser()
p.add_argument('--input-dir', required=True)
p.add_argument('--output-dir', required=True)
args = ... |
from icecream import ic
import argparse
import numpy as np
import pandas as pd
from collections import defaultdict
# loss_s columns are here:
# c6d1, c6d2, c6d3, c6d4, aa_CCE, acc1, acc2, acc3, str_loss (x10), lddt_loss, ca_lddt (x10), dih_loss, blen_loss, bang_loss
cols = ['c6d1', 'c6d2', 'c6d3', 'c6d4', 'aa_CCE... |
from attr import dataclass
from omegaconf import MISSING
from typing import List, Optional
@dataclass
class DatasetsConfig:
# path to train dataset
train_path: str = MISSING
# path to validation dataset
valid_path: str = MISSING
# path to test dataset
test_path: Optional[str] = None
# path... |
#!/usr/bin/env python3
# Disabling some unhappy pylint things
# pylint: disable=no-name-in-module,import-error,redefined-argument-from-local,no-self-use
# === IMPORTS ===
import redpipe
from inovonics.cloud.datastore import InoModelBase, InoObjectBase
from inovonics.cloud.datastore import DuplicateException, ExistsE... |
import random
import array
from reconchess import *
import os
import math
# from attacker_bot.py, used to flip move sequence if player color
# starts as black
def flipped_move(move):
def flipped(square):
return chess.square(chess.square_file(square), 7 - chess.square_rank(square))
return c... |
from typing import Dict, Any, Optional, List, Tuple, Set
import networkx
from .edge import Edge
class Direction:
TOP = 0
BOTTOM = 1
BOTH = 2
class TreeGraphEdgeRouter:
def __init__(self,
layers: List[List[Any]],
layer_widths: List[float],
graph: n... |
#!/usr/bin/env python
import argparse
import os
import socket
import concurrent.futures
import time
import ipaddress
from typing import List
from typing import Any
from signal import SIG_DFL, SIGPIPE, signal
import nmap
from tqdm import tqdm
from tabulate import tabulate
signal(SIGPIPE, SIG_DFL)
# Return the Local ... |
# Copyright (c) 2018-2021 Trim21 <<EMAIL>>
# Copyright (c) 2008-2014 <NAME> <<EMAIL>>
# Licensed under the MIT license.
import base64
import pathlib
import datetime
import warnings
from typing import Any, Dict, List, Tuple, Union, TypeVar, BinaryIO, Callable, Optional
from urllib.parse import urlparse
from transmissio... |
"""
Gender-based normalizers
~~~~~~~~~~~~~~~~~~~~~~~~
Normalizers which adjust calculations based
on the speaker's identified/identifying gender.
Note, that as defined in the literature
:citep:`e.g., {% bladon_etal_1984, nordstrom_1977 %}`
the normalizers use a binary gender classification.
.. normalizers-list::
... |
from enum import Enum
import torch.nn as nn
import torch.nn.init as init
from torch.optim.lr_scheduler import LambdaLR
def set_seed(seed_val: int, os_, random_, numpy_, torch_):
"""Set random seed for build-in and external modules.
set global random seed for reproducibility for os, random, numpy and torch.
... |
from copy import copy
from dataclasses import dataclass
from os import path
from pathlib import Path
from typing import List
import h5py
import matplotlib.pyplot as plt
import numpy as np
from joblib import Parallel, delayed
from tqdm import tqdm
from .beamline import Beamline
from .distributions import (
CeNTREX... |
#!/usr/bin/env python3
#
# -*- coding: utf-8 -*-
"""
Implementation of mkdfa.pl for python 3
"""
import sys
import os
import shutil
import re
import codecs
import subprocess
import argparse
JULIUS_BIN = os.path.dirname(os.path.abspath(__file__))
if sys.platform == 'win32':
CMD_MKFA = JULIUS_BIN + '/mkfa.exe'
... |
"""
This module deals with the definition of all the database models needed for the application
"""
from app import db, app
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
from math import cos, sin,... |
import numpy
import scipy.stats
def one_hot(array, N):
"""
Convert an array of numbers to an array of one-hot vectors.
:param array: classes to convert
:type array: numpy.ndarray
:param N: number of classes
:type N: int
:return: one-hot vectors
:rtype: numpy.ndarray
"""
array... |
from __future__ import print_function
try:
import cPickle as pickle
except:
import pickle
import os
import cv2
import numpy as np
import theano
# constant
# output size for training images, input size will be crop_size // 2
crop_size = 232
# global variable
crop_height = crop_size
crop_width = crop_size
ima... |
#! /usr/bin/env python
#=========================================================================
# graph.py
#=========================================================================
# Takes a ninja DOT graph and outputs a new graph with per-tag subgraphs
#
# -h --help Display this message
# -v --verbose Verbos... |
# -*- coding: utf-8 -*-
"""URL normalize main module."""
import re
from .tools import deconstruct_url, force_unicode, quote, reconstruct_url, unquote
DEFAULT_PORT = {
"ftp": "21",
"gopher": "70",
"http": "80",
"https": "443",
"news": "119",
"nntp": "119",
"snews": "563",
"snntp": "563"... |
import os
import time
import yaml
import pickle
import shutil
import datetime
import argparse
import matplotlib.pyplot as plt
import torch
import torch.utils.data
import torch.nn as nn
import torch.optim
import src.utils
import src.loss
import src.dataset
import models.stgae
def graph_loss(V_pred ,V_target):
re... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.addons.project.tests.test_access_rights import TestPortalProjectBase
from odoo.exceptions import AccessError
from odoo.tools import mute_logger
class TestPortalProjectBase(TestPortalProjectBase):
def set... |
"""Reddit to Excel
This script scrape a list of keywords from Reddit into a neatly formatted .xlsx file.
This file contains the following functions:
* convert_time - Converts seconds at the end to show how long the scrapeing and formatting process took
* load_keywords - Loads a text file as a list
* get_da... |
""" Klei rowid communication
Methods:
* getRegionalLobbies(ip_list) : list
* getServerInfoStea(ip, steam_port) : dictionary
By: github.com/iamflea
Licence: who cares July 2019
"""
import http.client
import json
from config import *
import zlib
import re
import os.path as op # For checking when th... |
from flask import Flask, render_template, request, flash, redirect, url_for
import os
from werkzeug.utils import secure_filename
# for YOLOv3 Detection and Speed Estimation
from speed_estimation import estimate_speed
from yolo import yolo_detection
# for assignment of calibration coordinates
from yolo_utils import as... |
# coding=utf-8
import numpy as np
import zipfile
import random
import scipy.sparse as sp
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import ConstantKernel, RBF
from sklearn.decomposition import SparsePCA,PCA
from sklearn.externals import joblib
from collections ... |
import threading
from test.cl_node.client_parser import parse_show_blocks
from test.cl_node.docker_node import DockerNode
from test.cl_node.errors import NonZeroExitCodeError
from typing import List
import pytest
import logging
from . import conftest
from .cl_node.casperlabs_network import ThreeNodeNetwork, \
Cust... |
# -*- coding: utf-8 -*-
"""
Code for PF-Net (Pulmonary Fibrosis Segmentation Network) according to the following paper:
Guotai Wang et al., Semi-Supervised Segmentation of Radiation-Induced Pulmonary Fibrosis from
Lung CT Scans with Multi-Scale Guided Dense Attention, IEEE Transactions on Medical Imaging, 2021... |
import numpy as np
from pymoo.algorithms.genetic_algorithm import GeneticAlgorithm
from pymoo.docs import parse_doc_string
from pymoo.model.survival import Survival
from pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover
from pymoo.operators.default_operators import set_if_none
from p... |
import types
from inspect import getargs, getfullargspec
from ..Magic.Classic import discrete_cache, singleton
from ..Tools.TypeInterface import BuiltinMethod
from .traits import Discrete
from ..Opt.utils import new_func_maker
import warnings
__all__ = ['data', 'P', 'PatternList', 'match', 'RDT']
def data(cls_def: t... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os
import sys
from blessings import Terminal
from werckercli.git import get_priority
from werckercli import prompt
terminal_file_handle = sys.stdout
INFO = "INFO"
DEBUG = "DEBUG"
def get_term():
return Terminal(stream=term... |
__all__ = ('playsound', 'voice_via_baidu', 'voice_via_google', 'music')
import execjs
import hashlib
import json
import music_dl
import os
import requests
music_dl.config.init()
from music_dl.addons.netease import netease_search
from pydub import AudioSegment, playback
from you_get.extractors.netease import neteas... |
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Union, List
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler as SkMinMaxScaler
from sklearn.preprocessing import Normalizer as SkNormalizer
from sklearn.preprocessing import RobustScaler as SkRobu... |
import pickle
import random
import pyro
import torch
from pyro.contrib.examples.util import print_and_log
from pyro.infer import SVI, JitTrace_ELBO, JitTraceEnum_ELBO, Trace_ELBO, TraceEnum_ELBO, config_enumerate
from pyro.optim import ClippedAdam
from tqdm import tqdm
from torch.utils.data import DataLoader, Dataset
... |
r"""
The file creates a pickle file where the values needed for loading of dataset is stored and the model can load it
when needed.
Parameters from hparam.py will be used
"""
import argparse
import os
import sys
import time
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from src.hparams i... |
from twitter_cred import access_token, access_token_secret, consumer_key, consumer_secret
import json
import sqlite3 as sql
from datetime import datetime, timedelta
from tweepy import OAuthHandler, API
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk import word_tokenize, sent_tokenize
from nltk.... |
from typing import (
List,
Tuple,
Dict,
Optional,
Iterator,
Any,
)
import os
import sys
import argparse
import torch
import numpy as np
import allennlp
from allennlp.data import Vocabulary
import pickle
from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder
from allennlp.mo... |
# Copyright (c) 2016 <NAME>.
# Cura is released under the terms of the LGPLv3 or higher.
from UM.Logger import Logger
from UM.PluginRegistry import PluginRegistry # So MachineAction can be added as plugin type
from UM.Settings.ContainerRegistry import ContainerRegistry
from UM.Settings.DefinitionContainer import Defi... |
import os
import re
import csv
from io import StringIO
from PIL import Image
from django.db import migrations
from django.conf import settings
from cvat.apps.engine.media_extractors import get_mime
def parse_attribute(value):
match = re.match(r'^([~@])(\w+)=(\w+):(.+)?$', value)
if match:
prefix = matc... |
import torch
from torch import nn
import torch.nn.functional as F
def normalize(x, axis=-1):
"""Normalizing to unit length along the specified dimension.
Args:
x: pytorch Variable
Returns:
x: pytorch Variable, same shape as input
"""
x = 1. * x / (torch.norm(x, 2, axis, kee... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021 EPAM Systems
"""This module processes build configuration files"""
import logging
import re
from collections import namedtuple
from functools import partial
from pprint import pformat
log = logging.getLogger(__name__)
def process_config(tree, args):
"""This... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.