text stringlengths 3.07k 12.6k |
|---|
import io
import math
import random
from time import sleep
import numpy as np
import picamera
import RPi.GPIO as GPIO
from matplotlib import pyplot as plt
from matplotlib import style
from picamera import Color, PiCamera
from picamera.array import PiRGBArray
from PIL import Image
import cv2
global img_rgb
global cur... |
# This python script builds Privly applications so they
# can share a common user interface and (eventually)
# support localization. If you are building
# a new application, you will probably want to copy
# an existing application folder, e.g. PlainPost,
# to a new directory and work there. When you are
# wanting to sh... |
"""Calculate readability measures."""
from math import log
from typing import List
from sparv import Annotation, Output, annotator
@annotator("Annotate text chunks with LIX values")
def lix(text: Annotation = Annotation("<text>"),
sentence: Annotation = Annotation("<sentence>"),
word: Annotation = A... |
#!/usr/bin/env python3
import torch
from tqdm import trange
from combinators import adam, effective_sample_size, log_Z_hat
from experiments.annealing.models import mk_model
from experiments.annealing.objectives import nvo_rkl, nvo_rkl_mod, nvo_avo
from experiments.annealing.plotting import plot
from experiments.anneal... |
# encoding='utf-8'
import os
'''
统计车牌样本中各个字符的次数
'''
def compare(txt, writePath):
'''
判断文本文件中图片路径是否有重复
:return:
'''
outfile = open(writePath, 'a+', encoding='utf-8')
f = open(txt, 'r', encoding='utf-8')
lines_seen = set()
i = 0
for line in f.readlines():
i += 1
... |
# Python 2 / 3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import logging
from . import config
Metric = collections.namedtuple(
"Metric",
("reference", "timestamp", "inte... |
#!/usr/bin/env python3
import os
import sys
import logging
import json
import requests
import datetime
import pyteamcity
import http.server
import validators
from urllib.parse import urlparse
config = {}
tc = None
logger = None
def initializeLogger():
logger = logging.getLogger('teamcity_connector')
logger.setL... |
"""
A GUI for creating a node to compute information about one transform node with
respect to another.
\b Requirements:
AM_ExposeTransform.py
To use this tool, select a transform node to expose and enter the desired data
into the option fields before pressing either the Create or Apply button.
\par Expose Transform ... |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
from waflib import Task
from waflib.Configure import conf
from waflib.TaskGen import feature, before_method, after_method
LIB_CODE = '''
#ifdef _MSC_VER
#define testEXPORT __declspec(dllexport)
#els... |
from django.contrib import admin
from index.models import CalculateResult
from django.core.exceptions import ObjectDoesNotExist
from index.models import CityIndex
from city.models import City
from city.enums import CityArea
from calculate.models import DataFile
import openpyxl
def getDataInfo(year: int, month: int, c... |
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import time
import pandas as pd
from geopy.geocoders import Nominatim
def get_all_timestamp_lags(data, unit_of_time = 'Second'):
""" Computes the difference between timestamps for every dataframe in the provided data dictionary and
returns a dictionary that has the ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals, print_function
import json
import os
from astropy.extern import six
from astropy.utils.compat.odict import OrderedDict
from jsonschema import validators
from js... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main driver for Windows 10. Initializes instruments and communication, then activates scheduled jobs for the main loop.
This relies on https://schedule.readthedocs.io/en/stable/index.html.
@author: <EMAIL>
"""
import colorama
import os
import logging
import time
impor... |
from common import *
def align_image_tiles(tiles, top_left_corner, border_counter):
def wanted_tile(current_tile, border):
for i, tile in enumerate(tiles):
if border in tile.get_possible_borders():
if current_tile.id == tile.id: continue
return tiles.pop(i)... |
import sklearn
import sklearn.svm
import numpy as np
import metrics
def create_trainset_for_user(xfeatures, y, yforg, user):
positive_samples = xfeatures[(y == user) & (yforg == 0)]
negative_samples = xfeatures[(y != user) & (yforg == 0)]
X = np.concatenate((positive_samples, negative_samples))
y = n... |
from random import random
from math import sqrt
from sys import argv
import json
def init_matrix(L, p):
return [1 if random() < p else 0 for _ in range(L * L)]
def print_matrix(matrix):
L = int(sqrt(len(matrix)))
for i in range(0, len(matrix), L):
print(matrix[i : i + L])
def up(i, L):
ret... |
"""
util functions for profiles
"""
from contextlib import contextmanager
from io import BytesIO
from os import path
from tempfile import NamedTemporaryFile
from PIL import Image
from micromasters.utils import now_in_utc
# This is the Django ImageField max path size
IMAGE_PATH_MAX_LENGTH = 100
# Max dimension of ei... |
import os
import time
import requests
from flask import Flask, abort, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
if app.debug:
url = "postgresql+psycopg2://postgres:password@db:5432/postgres"
time.sleep(10)
from pathlib import Path
api_key = Path("keys.txt").read_text()
el... |
#!/usr/bin/env python
import sys, traceback
import cv2
import os
import re
import numpy as np
import argparse
import string
import plantcv as pcv
def options():
parser = argparse.ArgumentParser(description="Imaging processing with opencv")
parser.add_argument("-i", "--image", help="Input image file.", requir... |
# -*- coding: utf-8 -*-
import re
import datetime
import logging
log = logging.getLogger(__name__)
_RX_WHITECHARS_DUPLICATE = re.compile(r'\s{2,}')
_RX_HITS_MAINPAGE = \
re.compile(r'''
(\d+,?\d*)
\s*?
HITs
</\w+?>
\s*?
available
''', re.M | re.X)
_RX_HITS_T... |
import contextlib
import logging
import threading
import time
import types
from enum import Enum
from typing import Dict, Optional, Union
logger = logging.getLogger(__name__)
class Status(Enum):
NOT_START = 'connection not start'
AVAILABLE = 'connection available'
QUERY_IN_PROGRESS = 'query in progress'
... |
# services/tasks/project/api/tasks.py
from flask import Blueprint, jsonify, request, render_template, current_app
from project import db
from sqlalchemy import exc
from project.api.models import Task
from python_http_client import Client
from .priority import Priority
import os
import sys
import json
import time
tas... |
# Copyright (c) 2011-2013 <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:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
bvg-cli is a command line tool for the public transport of Berlin.
It provides a simple way to get the latest departure times for the stations of
subway, bus, tram and urban rail system.
https://github.com/behrtam/bvg-cli
Copyright (c) 2015 <NAME>
License: MIT (see L... |
"""
LSH Based Text Retrieval System
Retrieving Documents based on the given Genome transcript, using a sample dataset of 4380
strings of human genome transcripts. LSH has been used to identify the most similar documents
"""
import numpy as np
import json
#import matplotlib.pyplot as plt
import timeit
i... |
# -*- coding:utf-8 -*-
import codecs
import datetime
import pytz
import screen
import xlwt
from django.conf import settings
from django.utils import timezone
from .compat import basestring, str
def get_cell_styles(self):
al = xlwt.Alignment()
al.horz = self.horz
al.vert = self.vert
datetime_style ... |
import networkx as nx
import random
import numpy.random as rand
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import statistics
import csv
def make_nodes(G, n_nodes):
G.add_nodes_from(range(n_nodes))
for node in list(G.nodes):
G.nodes[node]["tie"] = 1
def normal_rand_edge... |
# -*- coding: utf-8 -*-
"""
The seismic data class
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from ..core import core, core3d, io
# from ..core.pair import Pair
from ..core.window import Window
# from . import eigval, rotcorr, transmin, sintens
im... |
#!/usr/bin/python3 -tt
### FYI - example input file 'data/input/Website2021.csv'
### FYI - header line of this example file:
### "Code";"Type";"Wijn";"Land";"Regio";" Prijs/fles ";"Beschrijving";"Description";"Website";"Pakketactie"
##
## Run like so: python3 test-diff-csv.py --left data/test-data-in.csv --right... |
from __future__ import print_function
import struct
import wave
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import pygame,time
from math import pi
import numpy as np
import csv
import json
import requests
import random
CONST_W = int(1280)
CONST_H = int(720)
BLACK = (... |
'''
Miscellaneous user interface utilities for
- getting the screen size
- selecting files or directories.
If nothing or a non-existing file/direcoty is selected, the return is "0".
Otherwise the file/directory is returned.
- Selection from a list.
- waitbar
- listbox
'''
'''
author:... |
import math
from collections import namedtuple
import sdxf
import svgwrite
# Basic shapes and objects, output formats should not be known outside this file.
STROKE_WIDTH = 1
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Point(se... |
#
# Copyright (c) 2016 Nordic Semiconductor ASA
# 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 con... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 5 15:08:36 2021
@author: danie
"""
# %% Imports
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import ExponentialLR
from torchvision import transforms
import matplotlib.pyplot as plt
import numpy as np
from barbar import Bar
f... |
from os import environ, listdir
from database import Files
from tempfile import mkstemp, mkdtemp
from pathlib import Path
from typing import Optional, List, TypedDict
from download import download
from zip import unzip
from aws import S3Manager
import pandas as pd
PGFN_DEFAULT_URL = 'http://dadosabertos.pgfn.gov.br/... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import defaultdict
import os.path
import configparser
import argparse
import json
import sys
from googleapiclient import discovery
def list_instances(project='project-12345', zone='europe-west1-b', use_gcloud_config=True, use_cache=False,
... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import errno
import logging
import os
from argparse import ArgumentParser
from pex.common import safe_delete, safe_rmtree
from pex.enum import Enum... |
# -*- coding: utf-8 -*-
"""
tests.ext
~~~~~~~~~~~~~~~~~~~
Tests the extension import thing.
:copyright: (c) 2015 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
import sys
import pytest
try:
from imp import reload as reload_module
except ImportError:
reload_module = reload
f... |
from abc import ABC, abstractmethod
import torch.nn as nn
from aitoolbox.torchtrain.data.batch_model_feed_defs import AbstractModelFeedDefinition
class TTModel(nn.Module, ABC):
"""
TTModel is an extension of core PyTorch nn.Module
TT in TTModel --> TorchTrain Model
In addition to the common ``forwa... |
'''
Test Port Forwarding with TCP connection and SG rule coexist
@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.net_operations as net_ops
import zstackwoodpecker.operatio... |
from scipy import signal, interpolate
import numpy as np
from .detect_peaks import detect_peaks
import pandas as pd
from .numeric_transformation import vector_magnitude
def active_perc(X, threshold):
"""
The percentage of active samples, active samples are samples whose value is beyond certain threshold
""... |
import argparse
import traceback
import sys
import csv
'''
Input: FASTA
Expect defline starts with '>'
The rest of the defline is ignored.
Expect entire sequence on one line.
Output: CSV
Header line explains the columns.
Col 1 = sequence number (starts at 1 by default)
Col 2 = sequence length
... |
import docker
import dockerfile
import getpass
import hyperdrive
import os
import os.path
import re
import uuid
class Docker:
def __init__(self, base_url, name=None):
self.base_url = base_url
self.client = docker.DockerClient(base_url=base_url)
self.image = self.client.image.get(name) if ... |
import os , shutil , json
from copy import deepcopy
from numpy.random import choice, randint,uniform
from trainers import TI_Trainer
from detectron2.config import get_cfg
from detectron2 import model_zoo
from detectron2.data import DatasetMapper, build_detection_train_loader
import detectron2.data.transforms as T
from ... |
#!/usr/bin/env python
"""
Get cookies from Firefox.
"""
import sys
import os
FTSTR = ["FALSE", "TRUE"]
def get_cookie_jar(profile_folder):
"""
Original Author: <NAME> <EMAIL>
Original URL:
http://blog.mithis.net/archives/python/90-firefox3-cookies-in-python
License: MIT
... |
# python3
from sys import stdin
# Splay tree implementation
# Vertex of a splay tree
class Vertex:
def __init__(self, key, sum, left, right, parent):
(self.key, self.sum, self.left, self.right, self.parent) = (key, sum, left, right, parent)
def update(v):
if v == None:
return
v.sum = v.k... |
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
'''
This version of DistributedDataParallel is designed to be used in conjunction with the multiproc.py
launcher included with ... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 8 21:15:04 2014
@author: <NAME>
"""
import datetime
import os
import pickle
import sys
PKLFILES = ['ANTE.pkl','POST.pkl']
def dump(ind):
"""
Retrieve the environmental variables
and serialize them into a pickle object
@input :: ind \in [0,2[
@r... |
import seqm
import torch
from seqm.seqm_functions.fock import fock
from seqm.seqm_functions.hcore import hcore
from seqm.seqm_functions.diag import sym_eig_trunc1
from seqm.basics import Hamiltonian, Energy
class Hamiltonian_One(Hamiltonian):
def __init__(self,seqm_parameters):
super().__init__(seqm_para... |
#!/usr/bin/env python3
import os
import requests
from collections import namedtuple
local_ip = os.getenv("IP", default="")
host = "localhost"
env_file_path = ".env"
Config = namedtuple("Config", [
"keycloak_endpoint",
"keycloak_admin",
"keycloak_password",
"client_id",
"client_secr... |
import copy
import gettext
import re
import django
from django.conf import settings
from django.utils.functional import lazy
from django.utils.importlib import import_module
from django.utils.translation import (trans_real as django_trans,
ugettext as django_ugettext,
... |
import difflib
import json
import textwrap
from urllib.parse import unquote
import requests
from pygments import highlight as syntax_highlight
from pygments.formatters.img import ImageFormatter
from pygments.lexers import *
from telegram.ext import CommandHandler
from src.constants import font
def toJson(obj):
... |
from Aligner import Aligner
from utils import *
import pandas as pd
class annotation2MRPC_Aligner(Aligner):
"""
gets gold crowdsourced alignments in a csv format
and convert them to a .tsv file that fits the huggingface 'transformers' MRPC format (a classification paraphrasing model)
"""
de... |
# -*- coding: utf-8 -*-
from os import name
import frappe
from toolz.curried import compose, merge, keyfilter
from firebase_admin import auth
from cm_custom.api.firebase import get_decoded_token, app
from cm_custom.api.utils import handle_error, transform_route
CUSTOMER_FIELDS = ["customer_name", "mobile_no", "email_... |
from django.views import View
from django.db.models import Q
from django.shortcuts import render
from django.shortcuts import redirect
from django.shortcuts import get_object_or_404
from django.utils.encoding import force_bytes
from django.utils.encoding import force_text
from django.utils.http import urlsafe_base64_en... |
#
# (c) 2019 Kaminario Technologies, Ltd.
#
# This software is licensed solely under the terms of the Apache 2.0 license,
# the text of which is available at http://www.apache.org/licenses/LICENSE-2.0.
# All disclaimers and limitations of liability set forth in the Apache 2.0 license apply.
#
import click
from kmexpe... |
"""This module manages the integraton with mitmproxy."""
import logging
import random
import socket
import subprocess
import time
from contextlib import closing
try:
import mitmproxy
except ImportError as e:
raise ImportError("To use the mitmproxy backend you must first "
"install mitmpr... |
import ocnn
import torch
import numpy as np
import scipy.interpolate
import scipy.ndimage
import random
from plyfile import PlyData
from solver import Dataset
def read_file(filename):
def _read_ply(filename):
plydata = PlyData.read(filename)
vtx = plydata['vertex']
xyz = np.stack([vtx['x'], vtx['y'], v... |
import sys
from videocore6.assembler import assemble, qpu
from common import ilog2
@qpu
def qpu_somatcopy_n(asm, *, num_qpus, unroll, code_offset,
align_cond=lambda pos: True):
assert unroll in [1, 2, 4, 8]
g = globals()
for i, v in enumerate(['rows', 'cols', 'alpha', 'a', 'lda', ... |
"""Tests for classes from cve_report_helper module."""
import pytest
import json
from unittest import mock
from f8a_report.cve_helper import CVE
from datetime import datetime as dt
from requests.exceptions import Timeout
cve = CVE()
cve_stats = {"github_stats": {"open_count": {}}}
with open('tests/data/github_data.j... |
#!/usr/bin/env python
import cv2
import numpy as np
import time
from threading import Thread
from queue import Queue
from datetime import datetime
from motion import Detector
def putIterationsPerSec(frame, iterations_per_sec):
"""
Add iterations per second text to lower-left corner of a frame.
"""
cv2... |
#!/usr/bin/env python3
#
# Copyright (c) 2019 <NAME>
# Author(s): <NAME> (<EMAIL>), <NAME> (<EMAIL>)
#
# 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/LICE... |
"""
Advent of Code 2021: day 14
This looks potentially hard. Part A is ok,
but part B could become a nightmare if they ask for 1000 iteration or similar.
Part B only asks for 40 iterations, but the length of string over over 2 trillion
So we need a new design
"""
import pytest
from helper import *
def load_polymer(... |
import screen
class BlockObj():
def __init__(self, x, y):
name = 'block_%d_%d' % (x, y)
posx = x * 64 + 32
posy = y * 64 + 32
images = [
'./pics/0.png', './pics/1.png', './pics/2.png',
'./pics/3.png', './pics/4.png', './pics/5.png',
'./pics/6.pn... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from datetime import date, datetime
from decimal import Decimal
from pandas import tslib, DataFrame
from mining.utils import slugfy
from mining.utils._pandas import fix_type, fix_render, df_generate
class df_slugfy_test(unittest.TestCase):
def test_g... |
def doOverlap(boxA, boxB):
if (boxA[0] > boxB[2] or boxB[0] > boxA[2]):
return False
if (boxA[1] > boxB[3] or boxB[1] > boxA[3]):
return False
return True
def intersection_over_union(boxA, boxB):
# Determine the coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
... |
"""
This script contains functions which will build networks based on entities appearing together in the same documents. It calculates measures of i) degree, 2) betweenness, and 3) eigenvectors to give an output of network visualisations.
As the script is written to be executable from the commande line, it can perfor... |
'''
Basic numpy style statistics operations on arrays.
These include --
*
'''
import sys
import __builtin__
import numpy as np
import scipy.sparse as sp
import scipy.stats
from .mathematics import sqrt, sum
from .operator.map import map, map2
from .operator.map_with_location import map_with_location
from .operator.r... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, cint, getdate
from frappe import msgprint, _
from calendar import monthrange
import re
from datetime import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : redis.py
# @Author: <NAME>
# @Date : 2019/9/4
# @Role : 获取Aliyun Redis实例信息
import json
from aliyunsdkcore.client import AcsClient
from aliyunsdkr_kvstore.request.v20150101.DescribeInstancesRequest import DescribeInstancesRequest
from libs.db_context import DB... |
"""Tests of error handling."""
# std
# external
from fakeredis import FakeStrictRedis as Redis
import pytest
# funsies
import funsies
from funsies import _graph, Fun, options
from funsies._context import get_connection
from funsies._run import run_op
from funsies._storage import RedisStorage
from funsies.config impor... |
# This file is taken unchanged from the server repo at dropbox/python_linters/analysis.py
from __future__ import absolute_import
import ast
import re
class AnalysisVisitor(object):
def __init__(self, linters, path):
self.items = []
self.path = path
self.ancestors = []
def path_f... |
## load dependency - third party
import numpy as np
## load dependency - internal
from smogn.box_plot_stats import box_plot_stats
## calculate parameters for phi relevance function
def phi_ctrl_pts(
## arguments / inputs
y, ## response variable y
method = "auto", ## relevance ... |
import json
from flask import Flask, render_template, redirect, url_for, jsonify, request
from flask_mongoengine import MongoEngine
from flask_security import (
MongoEngineUserDatastore, Security, login_required, logout_user,
current_user
)
from flask_wtf import FlaskForm
from wtforms import validators
from wt... |
import os
import numpy
import numpy as np
# import open3d as o3d
import torch
import torch.utils.data
import transforms3d
from torch.utils.data import DataLoader
from tqdm import tqdm
from pcrnet.data_utils import ModelNet40Data, RegistrationData
from pcrnet.losses import ChamferDistanceLoss
from pcrnet.models import... |
import copy
from dataclasses import dataclass
from enum import Enum
from typing import Dict, Union, Tuple, List
import ujson, traceback
# noinspection PyUnresolvedReferences
from drepr import drepr_engine
from drepr.version import __engine_version__
from drepr.models import DRepr, DEFAULT_RESOURCE_ID, SemanticModel, ... |
import os
import subprocess
import sys
from datetime import datetime
from os.path import relpath
from pathlib import Path
from typing import Dict, Mapping, Optional
from zipfile import ZipFile
from rlbot.parsing.bot_config_bundle import get_bot_config_bundle, BotConfigBundle
from rlbot.parsing.directory_scanner import... |
import os
import random
from collections import OrderedDict
from PIL import Image
from mapparse.reader import Reader
from mapparse.writer import Writer
STATION_MAPS = {
'box': '~/ExternalRepos/third_party/Paradise/_maps/map_files/cyberiad/cyberiad.dmm',
'delta': '~/ExternalRepos/third_party/Paradise/_maps/ma... |
from crawler import parsers
class TestFirstGradeProcess:
def test_parser_movements_return_correct_list(self, movements):
expected = [
{'data': '25/11/2018',
'movimento': ('Informação do Sistema\nPJMS - Certidão de '
'realização de consulta de repetiçaõ d... |
import argparse
import json
import gdown
import os
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
from pathlib import Path
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import tensorflow as tf
from tensorflow.keras.models import load_model
@st.cache(s... |
import random
import torch
import torch.nn as nn
import torch.optim as opt
import torch.nn.functional as F
from src.dataloader import load_mnist, load_fmnist
from src.model import Encoder, Decoder
from src.utils import train, vae_loss
from src.config import args
import matplotlib.pyplot as plt
import argparse
# p... |
from pathlib import Path
import json
import re
import os
# ______ General Configuration ______
# Set what you want to download: mp3, webm, mp4, custom
# if custom, you need to set your custom parameters further down
download_type = "mp3"
# Relative output path where your downloaded files will go
output_path = "downl... |
#! /usr/bin/env python3
import tensorflow as tf
from tensorflow.python.ops.rnn import dynamic_rnn
import numpy as np
import string
char_dict = {x:k for k,x in enumerate(string.printable)}
def get_shakespeare_training_set(n_steps=200):
# Get file from https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8... |
import torch
import nibabel
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
from nilearn.image import resample_img
all_areas = {
"Accumbens": (23, 30),
"Amygdala": (31, 32),
"Brain Stem": (35, 35),
"Caudate": (36, 37),
"Cerebellum": (38, 41),
"Hippocampus": (47, 48),
... |
import json
import struct
import itk
import numpy as np
JS_TO_NPY_TYPEMAP = {
'Int8Array': {
'struct': (1, 'b'),
'dtype': 'int8',
},
'Int16Array': {
'struct': (2, 'h'),
'dtype': 'int16',
},
'Int32Array': {
'struct': (4, 'i'),
'dtype': 'int32',
},
... |
import copy
from typing import Tuple, List, Dict, Optional
from drkns.util import sh
from drkns.configunit import ConfigUnit
from drkns.stepexecutionstatus.StepExecutionStatus import StepExecutionStatus
from drkns.step.get_step_type import get_step_type
import drkns.step.step_type
from drkns.context.get_past_executi... |
from spira.log import SPIRA_LOG as LOG
from spira.yevon.filters.filter import Filter
from spira.yevon.gdsii.elem_list import ElementList
from spira.yevon.geometry.ports.port_list import PortList
from spira.yevon.process import get_rule_deck
RDD = get_rule_deck()
__all__ = [
'ProcessBooleanFilter',
'Simplify... |
######################################CONSTANTS######################################
DEFAULT_PLOT_KWARGS = {
'color': 'blue',
'linewidth': 1
}
DEFAULT_RC = {
'font.size': 8,
'font.family': 'serif',
'font.serif': ['Times'],
# 'text.usetex': True,
'axes.titlesize': 8,
'axes.labelsize': 8,... |
# Copyright 2020 The FedLearner Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# Copyright 2020 EMBL - European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... |
#!/usr/bin/env python
"""
A prototype of a custom bitcoin client with pluggables for callbacks.
PARAMETERS:
- network (MAINNET)
- callback for blockchain change
- callback for Tx received
- callback to validate Tx
"""
import asyncio
import os
import logging
from pycoin.blockchain.BlockChain import B... |
from typing import (
NoReturn,
Optional,
Callable,
Union,
Tuple,
List,
Type,
Dict,
Any
)
from inspect import (
Parameter,
signature,
iscoroutinefunction,
isfunction,
isclass,
_empty as inspect_empty
)
from hius.requests import Request
from hius.routing.excepti... |
import random
import matplotlib.pyplot as plt
from collections import namedtuple, deque
from itertools import count
from pyvirtualdisplay import Display
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from utils import Transition
class Replay... |
"""
Module for class factory generation.
"""
import datetime
class Model:
...
class GenModel:
default_values = {
"str": '""',
"int": "0",
"float": "0.0",
"datetime": "datetime.datetime.now()",
}
ATTRIBUTE_TMPL = " {name}: {type} = {value}"
CLASS_TMPL = (
... |
"""Utility functions for computing feature association statistics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numpy as np
import sys; sys.path.append('../..')
import src.msc.utils as utils
np.warnings.filterwarnings('ignore')
d... |
from functools import wraps
import os
import time
import pickle
import traceback
import inspect
import threading
import types
from astropy.io import fits
from arte.utils.logger import LoggerException
from numpy import ndarray
class ReturnTypeMismatchError(Exception):
pass
def _raiseReturnTypeMismatchError(expct... |
import copy
from drs import drs
import numpy as np
import random
# Calculate the longest path of a given DAG task
def longest_path_dag_gen(adjacency) -> float:
cost = np.zeros(adjacency.shape)
num_nodes = adjacency.shape[0]
for k in range(num_nodes):
for i in range(num_nodes):
if k ==... |
from dragonfly import Function, Repeat, Dictation, Choice, ContextAction, MappingRule
from castervoice.lib.context import AppContext
from castervoice.lib import navigation, context, textformat, text_utils
from castervoice.rules.core.navigation_rules import navigation_support
from dragonfly.actions.action_mimic import ... |
from __future__ import print_function
#该模块提供了一种使用与操作系统相关的功能的便携方式
import os
import argparse #解析命令行参数
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import Dataset
from torchvision import transforms
# from torch.utils.data.distributed import Distribute... |
"""Python utilities required by Keras."""
import inspect
import sys
from tensorflow.keras.utils import CustomObjectScope
from tensorflow.keras.utils import custom_object_scope
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.utils import serialize_keras_object
from tensorflow.keras.utils im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.