text stringlengths 3.07k 22.1k |
|---|
import hashlib
USER_AGENT = ['Dalvik/2.1.0 (Linux; U; Android 5.0.1; GT-I9508V Build/LRX22C)',
'Dalvik/2.1.0 (Linux; U; Android 5.0.1; MX4 Build/LRX22C)',
'Dalvik/2.1.0 (Linux; U; Android 5.0.2; D5322 Build/19.3.A.0.472)',
'Dalvik/2.1.0 (Linux; U; Android 5.0.2; D816w Build/LR... |
import argparse
from ast import Str
import os
from os import access, makedirs
import shutil
import torch
import numpy as np
import torchvision.transforms as transforms
import matplotlib as mpl
from skimage import io
from ..experiments import utils
from ..experiments._dataset import ToTensor
def get_device... |
from future import standard_library
standard_library.install_aliases()
from os.path import join, exists
import threading
from collections import namedtuple
import time
import datetime
import numpy as np
import queue
import pickle
from spodernet.utils.util import get_data_path, load_data, Timer
from spodernet.utils.g... |
"""Utiliites for mapping the gene identifiers in an edge file.
Contains module functions::
map_list(namefile, args=None)
main_parse_args()
main(tablefile, args=None)
Attributes:
DEFAULT_HINT (str): the default mapping hint for converting identifiers
DEFAULT_TAXON (int): the default taxon id to us... |
import os
import sys
from datetime import date, datetime
import stat
from shutil import rmtree
import yaml
import logging
import logging.config
from bagit import BagValidationError
import time
from bulk_mover.mover_classes.Item import PItem
from bulk_mover.mover_classes.SANCBagger import SANCBagger
from bulk_mover.mo... |
import time
import Trekker
import numpy as np
import os
import vtk
import pickle
import threading
import math
"""
Thread to update the coordinates with the fiducial points
co-registration method while the Navigation Button is pressed.
Sleep function in run method is used to avoid blocking GUI and
for better real-ti... |
#MenuTitle: Find Shapeshifting Glyphs
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Finds glyphs that change the number of paths while interpolating. Opens a new tab and reports to Macro Window.
"""
import vanilla
tempMarker = "###DELETEME###"
def glyphInterpol... |
import re
import random
import dateparser
from lxml import etree
from PIL import ImageDraw
from bs4 import BeautifulSoup
from datetime import datetime
from urllib.parse import unquote
from typing import List, Optional, Tuple
from pydantic import ValidationError
from nonebot.adapters.mirai2 import MessageChain, MessageS... |
from abc import abstractmethod
from typing import Optional
import torch
import torch.nn as nn
IMPOSSIBLE_SCORE = -100
def log_sum_exp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_sc... |
# This Python module is part of the PyRate software package.
#
# Copyright 2021 Geoscience Australia
#
# 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/... |
# -*- coding: utf-8 -*-
from itertools import chain
from django.forms import TextInput, Textarea, FileInput, CheckboxSelectMultiple
import os
from django import forms
from django.core.validators import EMPTY_VALUES
from django.utils.encoding import StrAndUnicode, force_unicode
from django.forms.util import flatatt
fro... |
#
# snimpy -- Interactive SNMP tool
#
# Copyright (C) <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "A... |
from copy import deepcopy
from collections import defaultdict
from datetime import datetime
import multiprocessing
import time
import traceback
import pickle
from . import utils, exceptions
from .core import Processor
from .configuration import combine_configs
import psutil
import rabbitpy
try:
import queue
exce... |
#!/usr/bin/env python
"""Generic script for processing large data sets in small batches.
Reads events from one datasource and commits them into another one,
either one by one or in batches.
Config template::
[data_maintainer3]
job_name = dm_remove_expired_services
# if source is database, you ne... |
import enum
import abilities
from simpleeval import simple_eval
import sys
class Unit:
def __init__(self, **kwargs):
self.name = kwargs.get("name", self.__class__.__name__)
self.health = kwargs.get("health", 100)
self.movement = kwargs.get("movement")
self.attack = kwargs.get("attac... |
#!/usr/bin/env python
"""
Evaluate rhyme schemes against gold standard.
"""
from __future__ import division, print_function, unicode_literals
import argparse
import json
import os
import sys
from collections import defaultdict
from functools import reduce
class SuccessMeasure:
def __init__(self):
self... |
import tabulate
import os.path
from clint.textui import puts, colored, indent, progress
import string, shutil
from s3skiddie.buildtree import buildtree
def writeIndexReadResults(path, results):
filepath = os.path.join(path, "index-read-results.txt")
file = open(filepath, "w")
toWrite = []
for result ... |
import os
import pytest
import signal
import subprocess
import time
import copy
from warnings import warn
import Pyro4
import pocs.base
from pocs.utils.logger import get_root_logger
from pocs.utils.database import PanDB
from pocs.utils.messaging import PanMessaging
from huntsman.pocs.utils import load_config, get_own... |
"""
These "scans" bundle a Message generator with an instance of the RunEngine,
combining two separate concepts -- instructions and execution -- into one
object. This makes the interface less flexible and somewhat less "Pythonic"
but more condensed.
This module is meant to be run in a namespace where several global
va... |
import importlib.util
import os
import requests
import sys
from argparse import ArgumentParser
from datetime import datetime
from tqdm import tqdm
class BaseConfig:
# Required - must be set in config file
api_token = ''
qcat_attributes = []
# Optional - can be overwritten in config file
qcat_b... |
"""
This script performs a single training run for a specific parameter setting.
"""
import os
import pickle
import numpy as np
from copy import deepcopy
from pprint import pprint
from timeit import default_timer as timer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_r... |
#!/usr/bin/env python
# coding:utf8
"""
@Time : 2019/11/26
@Author : fls
@Contact : <EMAIL>
@Desc : darkripples总平台相关-用户及权限相关:用户登录
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2019/11/26 08:52 fls 1.0 create
2020/08... |
#-*- encoding=utf-8 -*-
# Copyright (c) 2017 <NAME> <<EMAIL>>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/COPYING.LESSER
import unittest
import contextlib
try:
import numpy # pylint: disable=unused-import
HAS... |
#-*- coding: utensorflow-8 -*-
#Run in server
#three-layer perceptron Neural Network
'''
input >
weights 1 > convolution 1 > activation 1 > pooling 1 >
weights 2 > convolution 2 > activation 2 > pooling 2 >
weights 3 > fully_connected_perceptron 3 > activation 3 >
output
compare output to intended output > cost fu... |
import random
from PIL import Image, ImageOps
import torchvision.transforms.functional as F
from torchvision.transforms.transforms import Lambda
import numbers
import torch
import torch
import numpy as np
try:
import accimage
except ImportError:
accimage = None
class MultiScaleRandomCrop(object):
def __i... |
# Databricks notebook source
"""Orchestrator notebook for diabetes training."""
# Initialization of dbutils to avoid linting errors during developing in vscode
from pyspark.sql import SparkSession
def get_dbutils(spark):
"""Return dbutils for databricks."""
if spark.conf.get("spark.databricks.service.client.e... |
# Copyright (C) 2021 UAVCAN Consortium <uavcan.org>
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
from __future__ import annotations
import sys
import abc
from fnmatch import fnmatchcase
from typing import Optional, Iterator, Union, Callable, Tuple, Sequence, Dict
impo... |
"""
Read/write ticDat objects from json files. Requires the json module
PEP8
"""
import os
from collections import defaultdict
from ticdat.utils import freezable_factory, TicDatError, verify, stringish, dictish, containerish
from ticdat.utils import find_duplicates_from_dict_ticdat
import datetime
import itertools
try... |
# Copyright 2015 ClusterHQ Inc. See LICENSE file for details.
"""
Request load scenario for the control service benchmarks.
"""
from itertools import repeat
from zope.interface import implementer
from eliot import start_action, write_failure, Message
from eliot.twisted import DeferredContext
from twisted.internet.de... |
# ------------ Helper Functions -------------------------------------------------------------------------
#
# This file provides all necessary helper functions.
#
# ----- (0) Imports --------------------------------------------------------------------------------------
import random
import numpy as np
import keras
f... |
import unittest
import numpy
import pandas
from helpers.general import add_temporal_noise
from ..features import TimeRange, get_event_series, add_roll, roll
from .. import general
class TimeShiftTests(unittest.TestCase):
@staticmethod
def _get_data(n=100):
X = numpy.asarray(range(n))
return ... |
import math
import numpy as np
from manim import *
config.background_color = WHITE
FG = BLACK
class ColourAxesRGB(Scene):
def construct(self):
r = Arrow( [-6,0,0], [6,0,0], stroke_width=3, buff=0, color=RED )
g = Arrow( [0,-3,0], [0,3,0], stroke_width=3, buff=0, color=GREEN )
b = Arrow(... |
from flask import Flask
from flask import render_template, request, redirect, url_for, session, escape
from flask_cors import CORS
import json
import pymysql
import os
import smtplib
from email.mime.text import MIMEText
PWD = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, template_folder="static/tem... |
import math
import base64
import numpy as np
import tensorflow as tf
from .tflite_schema import Model as tflite_schema_model
from .tflite_schema import BuiltinOperator as tflite_schema_builtin_operator
from .tflite_schema import TensorType as tflite_schema_tensor_type
builtin_operator_code_lookup = {
code: name
... |
import ast
import json
import math
import os
import sys
import time
from dataclasses import dataclass
from pprint import pprint
from typing import Dict, List
from loguru import logger
import h5py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
im... |
#! /usr/bin/env python
# coding=utf-8
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import cv2
import numpy as np
import core.utils as utils
import tensorflow as tf
import re
from PIL import Image
import xml.etree.ElementTree as ET
from xml.etree import ElementTree # 导入ElementTree模块
return_elements = ["input/inpu... |
import io, struct, json, os, datetime
def readStruct(fb, structFormat, seek=False, cleanStrings=True):
if not isinstance(fb, io.BufferedReader):
raise ValueError("require an ABF file open in 'fb' mode")
if seek:
fb.seek(seek)
varSize = struct.calcsize(structFormat)
byteString = fb.rea... |
# rasta_server.py
#
# before running, make sure your locale is set to some UTF8 locale
# e.g. with export LANG=C.UTF-8
#
import http.server
import socketserver
import sys
import subprocess
import json
from urllib.error import URLError
from urllib.request import urlopen
from urllib.parse import unquote, quote, urlparse... |
'''
Zowie: a program to write Zotero select links into attachment files
Authors
-------
<NAME> <<EMAIL>> -- Caltech Library
Copyright
---------
Copyright (c) 2020 by <NAME> and the California Institute of Technology.
This code is open-source software released under a 3-clause BSD license.
Please see the file "LICEN... |
from __future__ import absolute_import
import os
import sys
from dateutil import parser
from threading import Thread
from anyjson import dumps, loads
from amqp.protocol import queue_declare_ok_t
from kombu.exceptions import ChannelError
from kombu.five import Empty, Queue
from kombu.log import get_logger
from kombu.... |
# PyGEP: Gene Expression Programming for Python
# Copyright (C) 2007 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later ve... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 13 20:01:17 2018
@author: alnoah
"""
import os
import shutil
import subprocess as sp
from itertools import product
import numpy as np
from tqdm import tqdm
from astropy.table import Table, hstack, vstack
import colorcovering as cc
def make_training(cat_train, label, t... |
__doc__ = """Use isolation forest in attempt to detect minority class examples.
Idea is to forget about the two-class classification problem and attempt to use
an siolation forest to give predictions as to whether a point is in the inlier
group (majority class) or in the outlier group (minority class).
Inspired by `t... |
###################################################
# FNC-1 Neural Network Implementation
# <NAME>
# 2017/11/06
#
# 2017/11/22 <NAME> simplify / rewrite again
###################################################
import numpy as np
import tensorflow as tf
from tensorflow.python import debug as tf_debug
import tim... |
#! /usr/bin/python3
"""
InstabotAI - Instagram Bot With Face Detection
Intro:
This bot autoscrape users from variable output -l
if a face is detected it will repost, repost to
stories, send DM to users, like and comment that
photo. If no face is detected in image it will
scrape the next prof... |
#
# Copyright (c) 2019-2020, NVIDIA CORPORATION.
# Copyright (c) 2019-2020, BlazingSQL, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... |
"""
Python library for parsing FastQC results.
Provides methods and classes for parsing a FastQC run results.
Tested with FastQC 0.9.5 output, should work with other versions as well.
Requirements:
* Python == 2.7.x
Copyright (c) 2013 <NAME> <<EMAIL>>
Copyright (c) 2013 LUMC Sequencing Analysis Support Core <<... |
"""Tests for the general many-body problem.
Some general tensor operations requiring range and dummies in the drudge are
also tested here.
"""
import pytest
from sympy import IndexedBase, conjugate, Symbol, symbols, I, exp, pi, sqrt
from drudge import GenMBDrudge, CR, AN, Range
@pytest.fixture(scope='module')
def ... |
#!/usr/bin/python3
# Script which simulates the random placement of enemies in rooms.
#
# Made this to investigate a bug in the US/EU versions of Ages/Seasons where
# enemies don't clear their ID/SubID values properly if they fail to spawn in
# due to not finding valid positions. This applies only to "random-position
... |
from datetime import date
from dynts import timeseries, hasextensions
from dynts.utils import test, cross, asarray
class TestTS(test.TestCase):
def _rollingTest(self, func):
# A rolling function calculation
ts = self.getts(cols=2)
rollfun = 'roll%s' % func
# Calculate... |
# Text On Image
# importing necessary library
from tkinter import * # from tkinter we import everything
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog # from tkinter importing file dialog box
import tkinter.messagebox as mbox # for displaying the dialog box
from PIL import Image, ImageTk,... |
"""
mpir.py - MPIR attach implementation
MIT License
(C) Copyright [2020] Hewlett Packard Enterprise Development LP
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... |
from flask import jsonify
import json
from datetime import datetime, timedelta
from app.models.office import User, Location
from app.models.chores import Event, Announcement, EventParticipant
def process_and_fullfill_chat_request(input_payload):
# print(input_payload)
if validate_input_payload(input_payload):... |
from rich.console import Console
from rich.text import Text
from rich.table import Table
from rich.highlighter import ReprHighlighter
from rich.filesize import decimal as format_size
import pkgutil
import importlib
from pathlib import Path
import ast
import requests
import os
import inspect
from inspect import (
g... |
import os.path
import SCons.Util
def _quote_spaces( arg ):
arg = str(arg)
if (' ' in arg) or ('\t' in arg):
return '"%s"' % arg
else:
return arg
#//---------------------------------------------------------------------------//
def _convert_defines( defines ):
args_defines ... |
#%% [markdown]
# # A group-based test
#%%
from pkg.utils import set_warnings
set_warnings()
import datetime
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from myst_nb import glue as default_glue
from pkg.data import load_matched, load_network_palette, load... |
import datetime
import asyncio
import random
from urllib.parse import urljoin
from typing import *
import requests
import tweepy
from aioify import aioify
from parse import parse
from bs4 import BeautifulSoup
from twitterscraper.models.domain import TwitterProfile, TwitterTweet, TweetScanStatus
from twitterscraper.ut... |
# Code generated by lark_sdk_gen. DO NOT EDIT.
from pylark.lark_request import RawRequestReq, _new_method_option
from pylark import lark_type, lark_type_sheet, lark_type_approval
import attr
import typing
import io
@attr.s
class GetAttendanceGroupReq(object):
employee_type: lark_type.EmployeeType = attr.ib(
... |
import FreeCAD
import math
import json
from pivy import coin
import arch_texture_utils.faceset_utils as faceset_utils
import arch_texture_utils.py2_utils as py2_utils
class TextureConfigEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, FreeCAD.Vector):
return [obj.x, obj.y,... |
import datetime
import os
import time
import torch
import sys
sys.path.insert(0, 'ImageScience')
from mask_rcnn import maskrcnn_resnet50_fpn
from coco_utils import get_cellsegm
from engine import train_one_epoch, evaluate
import utils
import transforms as T
def get_dataset(data_name, process_phase, transform_func, ro... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2020, Exa Analytics Development Team
# Distributed under the terms of the Apache License 2.0
"""
The Atomic Universe
#########################
The :class:`~exatomic.container.Universe` object is a subclass of
:class:`~exa.container.Container` that stores data coming from com... |
import numpy as np
import matplotlib.pyplot as plt
def getStartingPhases():
with open('Results.txt') as f:
first_line = f.readline()
return first_line
def phaseGroupInRing(SP, ring_phases, phasesInRing):
i = SP
for i in ring_phases:
if i > SP:
phasesInRing.append(i)
... |
# In this file we input the tickers given with potential shady
# activity and look at grant history to check if the stock is worth investing in
# We also look at past grants and see if typically a company's stock goes up after
# grants. This corresponds to a rating system that can be seen below.
# Import libraries
... |
import typing as t
from gettext import gettext as _
import click
import click_logging
from click_option_group import optgroup, MutuallyExclusiveOptionGroup
from functools import wraps
import urllib3
import logging
from .logging import logger
from .version import __version__
FC = t.TypeVar("FC", t.Callable[..., t.Any... |
from description import *
from stmt import *
from layout import *
class TileLoopBuilder:
def build(self, loopdesc, body_stmt):
assert(isinstance(loopdesc, FusedTileLoopDesc))
assert(isinstance(body_stmt, StmtInterface))
boundstmt = BinaryExpr(IdExpr(loopdesc.looprange), IdExpr(loopdesc.star... |
"""
:mod:`disco.worker.task_io` -- I/O Utility functions for Disco tasks
=====================================================================
"""
from disco import util
from disco.error import DataError
from disco.compat import bytes_to_str, str_to_bytes, UnpicklingError
def gzip_reader(fd, size, url, params):
... |
import json
import weakref
try:
from inspect import getfullargspec as getargspec
except:
from inspect import getargspec
from Qt import QtCore
from Qt import QtGui
from Qt.QtWidgets import QAbstractItemView
from Qt.QtWidgets import QFrame
from Qt.QtWidgets import QLineEdit
from Qt.QtWidgets import QTreeWidget, ... |
import discord
from discord.ext import commands
import random
import asyncio
import re
client = commands.Bot(command_prefix='your prefix')
def convert(seconds):
seconds = seconds % (24 * 3600)
seconds %= 3600
minutes = seconds // 60
seconds %= 60
return f'{minutes} minutes {seconds} seconds... |
"""
.. module:: networks
:synopsis: Flow neural networks for single speed and fast-slow hierarchies
.. moduleauthor:: <NAME> <<EMAIL>>
Coupling layer from https://github.com/ikostrikov/pytorch-flows modified
to use variable number of layers
"""
import math
import torch
import torch.nn as nn
class BatchNormFlow(... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
import argparse
import random
import warnings
from loguru import logger
import torch
import torch.backends.cudnn as cudnn
from yolox.core import Trainer, launch
from yolox.exp import get_exp
from yolox.utils import configu... |
import cv2
import os
import numpy as np
import pretty_midi
import subprocess
from midi2audio import FluidSynth
from collections import Counter
from config.load_yaml import configs
def frame_to_music(label):
pass
def pic_list_to_music(label_list):
init = True
cluster_idx = []
for i, label in enumerat... |
from typing import Dict, List, Optional, Union
import conan_app_launcher.app as app # using global module pattern
from conan_app_launcher.app.logger import Logger
from conan_app_launcher.core import ConanApi
from conan_app_launcher.core.conan import ConanPkg
from conan_app_launcher.ui.common import (TreeModel, ... |
from __future__ import print_function,division
from builtins import range
from six import iteritems
import math
import random
from . import differences
from . import sampling
from ..klampt import vectorops
import numpy as np
class Set:
"""Abstract base class for a set in a d-dimensional vector space.
A... |
# Copyright 2015 StackHut Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... |
#!/usr/bin/env python
""" """
# Standard library modules.
# Third party modules.
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import cleanup
from matplotlib.font_manager import FontProperties
import numpy as np
import pytest
# Local modules.
from matpl... |
import html.entities
import re
import unicodedata
from gzip import GzipFile
from io import BytesIO
from .functional import keep_lazy, keep_lazy_text, lazy
from .safestring import SafeText, mark_safe
@keep_lazy_text
def capfirst(x):
"""Capitalize the first letter of a string."""
return x and str(x)[0].upper()... |
import math
import cv2
import numpy as np
"""Pipeline to process images and draw road lanes"""
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
(assuming your grayscaled image is called 'gray'... |
"""Pairwise genome alignment
src: {ensemblgenomes.prefix}/fasta/{species}/*.fa.gz
dst: ./pairwise/{target}/{query}/{chromosome}/sing.maf
https://lastz.github.io/lastz/
"""
import concurrent.futures as confu
import gzip
import logging
import os
import shutil
from pathlib import Path
from ..db import ensemblgenomes, p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTW-PV3 - Export weather data for POLYSUN
Export weatherdata for POLYSUN
SPDX-License-Identifier: AGPL-3.0-or-later
"""
__copyright__ = "© <NAME>"
__license__ = "GNU Affero General Public License Version 3 (AGPL-3.0)"
__url__ = "https://www.gnu.org/licenses/agpl-3.0... |
"""
Classes for acqoptimizers implemented with scipy.optimize.
"""
from argparse import Namespace
import numpy as np
from scipy.optimize import minimize
from .acqopt import AcqOptimizer
from ..util.misc_util import dict_to_namespace
class SpoAcqOptimizer(AcqOptimizer):
"""AcqOptimizer using algorithms from scip... |
# -*- coding: utf-8 -*-
'''
By <NAME>(<EMAIL>) and <NAME>(https://github.com/ozmig77)
https://www.github.com/kyubyong/g2p
'''
import nltk
import numpy as np
import codecs
import os
import re
from builtins import str as unicode
import hazm
from PersianG2p.expand import normalize_numbers
from PersianG2p.hparams import ... |
# Copyright 2017 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
# coding: utf-8
# ### Compute results for task 1 on the humour dataset.
#
# Please see the readme for instructions on how to produce the GPPL predictions that are required for running this script.
#
# Then, set the variable resfile to point to the ouput folder of the previous step.
#
import string
import pandas as p... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.utils.safestring import mark_safe
from .models import Profile
from django.forms import ModelForm
from django.utils.translation import ugettext_lazy as _
import re
import datetime
cl... |
import numpy as np
import imageio
from skimage.feature import canny
import cv2
DEG = np.pi / 180.0
def rgb2gray(rgb):
return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]).astype(np.uint8)
def fast_hough_line(img, angle_step=1, lines_are_white=True, value_threshold=5):
"""
hough line using vectorized numpy ... |
import pytest
import os.path as op
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Alphabet import IUPAC
from BCBio import GFF
from ssbio.databases.kegg import KEGGProp
@pytest.fixture(scope='class')
def seq_record_loaded_from_file_example(fasta_path):
"""Original SeqReco... |
#!/usr/bin/env python3
import os
import glob
import cv2
import json
import argparse
from functools import reduce
from importlib import import_module
from itertools import islice
from datetime import datetime
from src.cameras.camera_pi import Camera, Predictor
import logging
from flask import Flask, Response, send_from... |
"""Contains the base class for the Snux driver overlay.
This class overlays an existing WPC-compatible platform interface to work with
<NAME>'s System 11 interface board.
"""
import asyncio
import logging
from typing import Any, Optional, Set, Tuple
from mpf.core.machine import MachineController
from mpf.core.platfo... |
'''
## Train T-REX ##
# Train the T-REX network on the demonstration samples
@author: <NAME> (<EMAIL>)
'''
import os
import sys
import tensorflow as tf
import numpy as np
import argparse
from utils.data_loader import DataGenerator
from utils.network import RewardNet
from utils.preprocess_trajs_offline ... |
# django imports
from django.contrib.auth.decorators import permission_required
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.http import HttpResponseRedirect
... |
from cogs.utils import checks, paginator
import discord
from discord.ext import commands
class ShowDonations(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.DONATION_PING_CHANNEL_ID = 462205081945899008
async def cog_command_error(self, ctx, error):
if isinstance(error, c... |
import argparse
import sys
import random
import pandas as pd
from itertools import zip_longest
from save_table import save_tables, save_list
from print_tables import print_tables, print_person_table_list, print_allergies
from person import Person, Empty
def getArgs(argvals=None):
"""Parse the arguments from the c... |
import abc
from scipy.stats import norm
from numpy.random import normal
import streamlit as st
class OptionClass(metaclass=abc.ABCMeta):
'''Template Class for credit spread options trading'''
def __init__(self, principal, stockprice, sigma, numTrades=1000):
# Amount in the account
self.principa... |
from seamless.core.transformation import SeamlessTransformationError
header = """
/*
The following C header has been auto-generated from the transformer schema
It will be used to generate bindings, but it will not be automatically
added to the compiled transformer code.
If your transformer code is written in C/C++,... |
import os
import traceback
import subprocess
import numpy as np
import elfi
from elfie.serializable import Serializable
import matplotlib
from matplotlib import pyplot as pl
import logging
logger = logging.getLogger(__name__)
""" DFT choice model
Busemeyer & Townsend 1993
"""
class ChoiceParams():
def __in... |
# Copyright (c) 2020, <NAME>
import argparse
import os
import numpy as np
import torch.nn.functional as F
import json
from data_simulation import get_dataset_splits, TCGA_Data, get_iter
from utils.evaluation_torch import compute_eval_metrics
import torch
from torch.autograd import Variable
from TransTEE import TransT... |
import numpy as np
import torch
from torch.utils.data import Dataset
def sigmoid(x):
return 1. / (1 + np.exp(-x))
def gen_synth_causal_dat(nObs=100, causalFunc='nueralnet_l1', noise_dist='laplace'):
"""
generate causal data where one variable causes another
Inputs:
- nObs: number of observat... |
'''
Copyright (C) 2021 CG Cookie
http://cgcookie.com
<EMAIL>
Created by <NAME>, <NAME>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your op... |
""" Version 2.2 dated April 15th 2021 by <NAME>
This script reads sample names from a list, presents the user with
a couple of options to modify the names and arranges them on a
sheet of A4 paper so that it can be printed on Avery-Zweckform
L7871 labels
"""
from pathlib import Path # we use this for f... |
#!/usr/bin/env python
"""
Encryption - Hill Cipher
This script ingests ASCII text, then encrypts it and decrypts it.
Simple, right? Encryption and decryption is handled partially via
PyCUDA ReductionKernel OR direct CUDA matrix multiplication on the GPU.
Usage:
~$ python hillcipher.py <textfile> <dotprod>
"""
impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.