content stringlengths 5 1.05M |
|---|
// AUTHOR: Devendra Patel
//Python3 Concept: Palindrome
// GITHUB: https://github.com/github-dev21
print("Enter the Number ")
num = int(input())
temp = num
reverse = 0
while(num>0):
dig = num%10
reverse = reverse*10+dig
num = num//10
print(reverse)
if temp==reverse:
print("Number is in Palindrome")
e... |
#!/usr/bin/python3
"""
In a given 2D binary array A, there are two islands. (An island is a
4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change 0s to 1s so as to connect the two islands together to form 1
island.
Return the smallest number of 0s that must be flipped. (It is guar... |
from random import choice
import matplotlib.pyplot as plt
class Randomwalk:
"""A class to generate random walks"""
def __init__(self, num_points=5000):
"""initialize attributes of a walk"""
self.num_points = num_points
#All walks start at (0, 0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(se... |
"""
This script starts up our game
"""
from game_window import main
if __name__ == "__main__":
main()
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import math
from .neural_blocks import ( SkipConnMLP, NNEncoder, FourierEncoder )
from .utils import ( autograd, eikonal_loss, dir_to_elev_azim, fat_sigmoid )
from .refl import ( LightAndRefl )
def load(args, shape, light_and_refl: Light... |
#!/usr/bin/env python3
import os
import bspump
import bspump.ipc
import bspump.common
class EchoSink(bspump.Sink):
def process(self, context, event):
'''
Send the event back to the client socket.
'''
print(event)
sock = context['stream']
sock.send(event.encode('utf-8'))
sock.send(b'\n')
class EchoP... |
import os
import shutil
import tensorflow as tf
import matplotlib.pyplot as plt
import logging
import copy
from collections import OrderedDict
import signal
from skopt import gp_minimize
from skopt import dump as dump_result
from skopt import load as load_result
from skopt.space import Real, Categorical, Integer
from ... |
import math
a = int(input())
print(round(3 * a**2 * math.sqrt(5 * (5 + 2 * math.sqrt(5))), 2))
print(round(a**3 / 4 * (15 + 7 * math.sqrt(5)), 2)) |
"""
Tests for BlockCountsTransformer.
"""
# pylint: disable=protected-access
from openedx.core.djangoapps.content.block_structure.factory import BlockStructureFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import SampleCourseFactory
from ..blo... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loadingDialog.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QMovie
from PyQt... |
from itertools import islice
from random import random
import time
import csv
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
from matplotlib import interactive
import datetime as dt
import matplotlib.animation as animation
from pylive import live_plotter
interactive(True)
... |
#brew install wxpython
#sudo apt install linuxbrew-wrapper
#sudo apt install python-pip
#pip install SpeechRecognition
#sudo apt-get install python-pyaudio python3-pyaudio
#pip install --allow-unverified=pyaudio pyaudio
#sudo apt-get install python-wxtools
#sudo pip install pyttsx
#sudo pip install wikipedia
#IF MEMOR... |
import hashlib
from six.moves.urllib.request import urlopen # noqa
from six.moves.urllib.parse import urlencode # noqa
class Message:
'''
@init
'''
def __init__(self, message_configs):
self.sign_type = 'normal'
self.message_configs = message_configs
self.signature = ''
... |
from __future__ import unicode_literals
from . import ValidationTestCase
from .models import ModelToValidate
class TestModelsWithValidators(ValidationTestCase):
def test_custom_validator_passes_for_correct_value(self):
mtv = ModelToValidate(number=10, name='Some Name', f_with_custom_validator=42,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPen
from src.Figure import Figure
from utils import midpoint
class LineSegment(Figure):
def __init__(self, start_point=None, end_point=None, border_color=None):
location = midpoint(start_point, end_point)... |
'''
introduction to multi-threading with python
'''
import threading, time
def take_a_nap():
time.sleep(5)
print('wake up!')
print('start of program')
thread_obj = threading.Thread(target=take_a_nap)
thread_obj.start()
print('end of program') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from typing import List, Optional
from io import BufferedIOBase
from pathlib import Path
from .exceptions import MissingEnv, CreateDirectoryException
from redis import Redis
from redis.exceptions import ConnectionError
from datetime import datetime, timedelta
imp... |
# Copyright 2017 Conchylicultor. 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 applicable law ... |
import os
import requests
import unittest
from riptide.engine import loader as riptide_engine_loader
from riptide.tests.integration.project_loader import load
from riptide.tests.integration.testcase_engine import EngineTest
class EngineStartStopTest(EngineTest):
def test_engine_loading(self):
for proje... |
#!/usr/bin/python
import random
import sys
import time
def overlap(start1, end1, start2, end2):
# using this routine to check if two lines overlap. Essential if they
# intersect and are on the same row (horizontal) or column (vertical)
# then they overlap
return (end1 >= start2) and (end2 >= start1)
d... |
from bs4 import BeautifulSoup as bs
import pandas as pd
from splinter import Browser
from splinter.exceptions import ElementDoesNotExist
import time
import re
import ast
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import datetime
matplotlib.use('Agg')
def init_browser():
"""start chrome... |
"""
codeeval.py
A utility for setting up codeeval challenges.
Usage: codeeval.py <challenge index>
"""
import sys
import requests
import os
from bs4 import BeautifulSoup
URL = "https://www.codeeval.com/browse/{}/".format
index = sys.argv[1]
FILE_CONTENTS = """\"\"\"
{url}
{title}
Challenge Description:
{challeng... |
from setuptools import find_packages, setup
with open("./README.md") as readme_file:
readme = readme_file.read()
with open("./requirements.txt") as req_file:
requirements = req_file.read()
setup(
name='qubot',
version='0.0.13',
python_requires=">=3.7",
packages=find_packages(exclude=["tests",... |
# coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... |
class BaseRetryStorage(object):
"""Plugable interface for retry queue storage"""
fields = ['operation', 'target_host', 'source_host', 'filename']
def count(self):
"""Returs total retry count"""
raise NotImplementedError
def all(self):
"""Returns all retries in queue"""
... |
from __future__ import unicode_literals
# Django
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
# 3rd Party
from grapevine.admin.base import BaseModelAdmin, SendableInline
from grapevine.emails.admin import EmailableAd... |
import discum
bot = discum.Client(token="ur token")
@bot.gateway.command
def example(resp):
if resp.raw[
"t"] == "MESSAGE_CREATE": # if you want to play with the raw response
print("Detected a message")
bot.gateway.removeCommand(
example
) # this works because bo... |
import unittest
import numpy as np
import galsim
from desc.imsim.atmPSF import AtmosphericPSF
class AtmPSF(unittest.TestCase):
def test_r0_500(self):
"""Test that inversion of the Tokovinin fitting formula for r0_500 works."""
np.random.seed(57721)
for _ in range(100):
airmass... |
# DESAFIO - 005 - ANTECESSOR E SUCESSOR:
# Escreva um código em que peça um número ao usuário e retorne esse número
# mais o seu antecessor e seu sucessor:
numero = int(input("Digite um número: "))
antecessor = numero - 1
sucessor = numero + 1
print(f"Você digitou {numero} , seu antecessor é {antecessor} e seu sucesso... |
input = """
p(X) | -p(Y) :- a(X,Y).
a(1,2).
a(2,1).
"""
output = """
p(X) | -p(Y) :- a(X,Y).
a(1,2).
a(2,1).
"""
|
# -*- coding: utf-8 -*-
"""IPv6 Destination Options and Hop-by-Hop Options"""
import collections
import csv
import re
from pcapkit.vendor.default import Vendor
__all__ = ['Option']
#: IPv6 option registry.
DATA = {
# [RFC 8200] 0
0x00: ('pad', 'Pad1'),
0x01: ('padn', 'PadN'), ... |
import time
from datetime import timedelta
from multiprocessing import Value, Manager
# Each column is 20 chars wide, plus the separator
COL_WIDTH = 12
COLUMNS = ["CURRENT", "TOTAL", "PERCENTAGE", "RUNTIME", "RATE", "EXPECTED"]
COL_SEPARATOR = "|"
ROW_SEPARATOR = "-"
TIME_FORMAT = "%H:%M:%S"
class SyncedCrawlingProg... |
class StorageException(Exception):
"""Base class for all storage exceptions"""
class PathExistsException(StorageException):
"""The given path already exists"""
class StorageNotSupported(StorageException):
"""Storage type not supported"""
class InvalidStoragePath(StorageException):
"""Invalid storage... |
# "Lorenz-95" (or 96) model.
#
# A summary for the purpose of DA is provided in
# section 3.5 of thesis found at
# ora.ox.ac.uk/objects/uuid:9f9961f0-6906-4147-a8a9-ca9f2d0e4a12
#
# A more detailed summary is given in Chapter 11 of
# Majda, Harlim: Filtering Complex Turbulent Systems"
#
# Note: implementation is ndim... |
from jinja2 import Environment, FileSystemLoader
import json
import pytest
import os
import copy
from em_stitch.montage.montage_solver import (
MontageSolver, get_transform)
from tempfile import TemporaryDirectory
import glob
import shutil
from marshmallow import ValidationError
test_files_dir = os.path.join(o... |
"""
Copyright (c) 2014, Austin R. Benson, David F. Gleich,
Purdue University, and Stanford University.
All rights reserved.
This file is part of MRNMF and is under the BSD 2-Clause License,
which can be found at http://opensource.org/licenses/BSD-2-Clause
Copyright (c) 2015, Mariano Tepper,
Duke ... |
"""An example of sending and receiving cookies."""
import logging
from typing import Dict
from urllib.parse import parse_qsl
from bareasgi import (
Application,
Scope,
Info,
RouteMatches,
Content,
HttpResponse,
text_reader,
text_writer
)
import bareutils.header as header
logging.basic... |
from datetime import datetime
import pytest
import pytest_mock
import book2
def test_book_b4_begin_time(mocker):
fake_time = begin_date_time = datetime(2021, 6, 14, 7, 59)
mocker.patch('book2._get_now', return_value=fake_time)
result = book2.book_vaccine()
assert result == "2021-06-14 08:00 才能預約"
de... |
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?
# This is a naive approach that only works for small numbers.
def is_prime(current, primes):
# Search if current value already exists in primes or is a multiple of known primes
for prime in pri... |
# -*- coding: utf-8 -*-
# Copyright 2013-2021 CERN
#
# 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 a... |
from os import environ
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from logger import Logger
class Mailer:
def __init__(self):
self.email = environ.get('email_address')
self.password = environ.get('email_password')
self.server = environ... |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
from waflib import Utils,Task,Options,Errors
from waflib.TaskGen import before_method,after_method,feature
from waflib.Tools import ccroot
from waflib.Configure import conf
ccroot.USELIB_VARS['cs']=s... |
from autofunc.get_match_factor import match
from autofunc.get_top_results import get_top_results
from autofunc.find_associations import find_associations
from autofunc.get_data import get_data
import os.path
import numpy as np
def test_1():
"""
Tests that the match factor for a known learning set and test ca... |
from factory.declarations import LazyAttribute, Sequence, SubFactory
from factory.django import DjangoModelFactory
from roster.factories import StudentFactory
from exams.models import ExamAttempt, PracticeExam
class ExamFactory(DjangoModelFactory):
class Meta:
model = PracticeExam
family = 'Waltz'
number = Seq... |
import asyncio
from aiofsk.transport import AFSKTransport
async def text_console(modem):
def _text_console():
while True:
text = input(">> ")
if 'quit' in text:
return
modem.write(text.encode())
try:
return await asyncio.get_event_loop().run_... |
from sklearn.model_selection import train_test_split
from sklearn import datasets
from keras.optimizers import SGD
from keras.utils import np_utils
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import cv2
import os
from glob import glob
import random
import shutil
class... |
import numpy as np
import astropy.units as u
__all__ = [
"energy_dispersion",
]
def _normalize_hist(hist):
# (N_E, N_MIGRA, N_FOV)
# (N_E, N_FOV)
norm = hist.sum(axis=1)
h = np.swapaxes(hist, 0, 1)
with np.errstate(invalid="ignore"):
h /= norm
h = np.swapaxes(h, 0, 1)
retu... |
import os
from webdriverwrapper import unittest, Chrome, ChromeOptions
from webdriverwrapper.decorators import *
from webdriverwrapper.exceptions import ErrorMessagesException
class TestCaseTest(unittest.WebdriverTestCase):
instances_of_driver = unittest.ONE_INSTANCE_PER_TESTCASE
def init(self):
sel... |
from Jumpscale import j
# as used in gec farms as standard rack
def bom_calc(environment):
from hardware.components.components_hpe import bom_populate
environment.bom = bom_populate(environment.bom)
# # see the bill of material sheet to define the devices
# compute = environment.bom.device_get("hpe... |
import re
from . import basiciv
from .helper import check_date
from . import worksiv
class Batch(basiciv.Queue):
def __init__(self, **kwargs):
super().__init__()
self.que_tar = [
{
'illust_attrs': zip_[0],
'rank': zip_[1],
'yes_rank': zi... |
from .base import * # noqa: F403
from .base import env
MIDDLEWARE.append("api.middleware.RangesMiddleware") # noqa: F405
DJANGO_DRF_FILEPOND_STORAGES_BACKEND = "storages.backends.s3boto3.S3Boto3Storage"
AWS_ACCESS_KEY_ID = env("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = env("AWS_SECRET_ACCESS_KEY")
AWS_S3_REGION_N... |
# Author: Payam Ghassemi, payamgha@buffalo.edu
# Sep 8, 2018
# Copyright 2018 Payam Ghassemi
import numpy as np
from matplotlib import pyplot as plt
import scipy.io
import pickle
# Built-in python libraries
import sys
import os
from urllib.request import urlretrieve
# 3rd-party libraries I'll be ... |
#! /usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import argparse
from itertools import cycle
class Calibrator(object):
def __init__(self, start):
self.start = start
self.updates = []
self.current_frequency = start
def load_input_file(self, file_name)... |
#!/usr/bin/env python3
"""
A tool for sorting text with human-readable byte sizes like "2.5 KiB" or "6TB"
Example uses include sorting the output of "du -h" or "docker image ls".
"""
import argparse
import re
import sys
# byte size multiples are hard. https://en.wikipedia.org/wiki/Kibibyte
# fmt: off
IEC_MULTIPLES = ... |
import prefect
from prefect import task, Flow
from prefect.storage import Docker
@task
def hello_task():
logger = prefect.context.get("logger")
logger.info("Hello, Kubernetes!")
with Flow("encoding-task",
storage=Docker(registry_url="prefectdevacr.azurecr.io",
python_dependenc... |
import filecmp
import os
def dirs_same_enough(dir1,dir2,report=False):
''' use os.walk and filecmp.cmpfiles to
determine if two dirs are 'same enough'.
Args:
dir1, dir2: two directory paths
report: if True, print the filecmp.dircmp(dir1,dir2).report_full_closure()
befor... |
from operator import itemgetter
from django.http import Http404
from django.shortcuts import redirect, render
from django.urls import reverse_lazy
from django.views.generic import TemplateView
from exporter.applications.forms.countries import (
countries_form,
choose_contract_type_form,
contract_type_per_... |
#!/usr/bin/env python3
from __future__ import unicode_literals, print_function, division
import sys
sys.path.append('..')
from io import open
import os
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import argparse
import json
from model.settings import hparams
import glob
if __name__ == '__ma... |
#!/usr/bin/python3 -m unittest
#
# basic inspection
#
import unittest
import pymm
import numpy as np
import math
import torch
def colored(r, g, b, text):
return "\033[38;2;{};{};{}m{} \033[38;2;255;255;255m".format(r, g, b, text)
def log(*args):
print(colored(0,255,255,*args))
shelf = pymm.shelf('myTransacti... |
#!/usr/bin/env python3
# encoding: utf-8
import importlib
import tensorflow as tf
assert tf.__version__[0] == '2'
# algorithms based on TF 2.x
from typing import (Tuple,
Callable,
Dict)
from rls.common.yaml_ops import load_yaml
from rls.utils.display import colo... |
from format.util import *
def visualize(file_before, file_after, file_diffs, file_output_name = None):
"""visualize the jpg diff, open with Tk window or save as file
args:
file_before (str)
file_after (str)
file_diffs (list)
file_output_name (str)
"""
if file_output_nam... |
class Electric_calculation:
def __init__(self, datacase, resistance):
try:
self.datacase = datacase
self.resistance = resistance
self.datacaseinit = datacase
except:
self.datacase = int(input("테스트 케이스의 갯수를 입력하세요> "))
self.resistance = int(i... |
def condition(row):
'''
Args:
row (int): Individual entry for specified column
Returns:
val (int): If number equals 0 returns
Else return 1
'''
if row == 0:
val = 0
else:
val = 1
return val
def roundup(row):
'''
Args:
ro... |
import pandas as pd
import os
import argparse
import re
from Bio import SeqIO
pd.set_option("display.max_columns",40)
parser=argparse.ArgumentParser()
parser.add_argument("-f1","--File1")
parser.add_argument("-f2","--File2")
args=parser.parse_args()
f1=args.File1
f2=args.File2
f_1=pd.read_table(f1,header=0)
f_1[... |
from aiohttp_admin.contrib import models
from aiohttp_admin.backends.sa import PGResource
from .main import schema
from ..db import comment
@schema.register
class Comments(models.ModelAdmin):
fields = ('id', 'post_id', 'created_at', 'body', )
class Meta:
resource_type = PGResource
table = co... |
"""
Probabilistic multiple cracking model
"""
from typing import List, Any, Union
import bmcs_utils.api as bu
import traits.api as tr
import numpy as np
import warnings
from bmcs_utils.trait_types import Float
from scipy.optimize import newton
warnings.filterwarnings("error", category=RuntimeWarning)
class CrackBr... |
"""cv_detect_train.pu
Multiplatform OpenCV (cv2) face detection and capture tool.
The MIT License (MIT)
Copyright (c) 2020 Román Ramírez Giménez (MIT License)
Run this script to detect faces, save images and then be able to train models
for different tools (for example, Magic Mirror 2 facial recognition ones).
U... |
import contextlib
import logging
import signal
import sys
LOGGER = logging.getLogger(__name__)
class ApplicationState(object):
LOAD = 0
MAIN_LOOP = 1
def __init__(self):
self.state = self.LOAD
self.running = True
signal.signal(signal.SIGINT, self.signal_handler)
def set_ap... |
# Problem statement: Print all possible strings of length k that can be formed from a set of n charactersFor a length k ,set of size n n^k
# strings can be formed
''' Approach is to start with a string which is empty/blank ,add all characters one by one to that empty string ,
for every character added print all possib... |
"""
Example implementation of a UBXMessage file reader
using the UBXReader iterator functions
Created on 25 Oct 2020
@author: semuadmin
"""
from pyubx2.ubxreader import UBXReader
import pyubx2.exceptions as ube
class UBXStreamer:
"""
UBXStreamer class.
"""
def __init__(self, file... |
import os
import bpy
from .. import base
from ... import particles_io
def get_cache(socket):
node = socket.node
pos = node.outputs['Position']
vel = node.outputs['Velocity']
col = node.outputs['Hex Color']
mat = node.outputs['Material']
emt = node.outputs['Emitter']
size = node.outputs['... |
import datetime
from direct.directnotify import DirectNotifyGlobal
from toontown.uberdog.ClientServicesManagerUD import executeHttpRequest
from direct.fsm.FSM import FSM
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.MsgTypes import *
from otp.ai.MagicWordGlobal import *
from direct.showba... |
# Generated by Django 3.0.2 on 2020-01-20 14:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('babybuddy', '0007_auto_20190607_1422'),
]
operations = [
migrations.AlterField(
model_name='settings',
name='languag... |
"""Responsys REST API Client."""
# used to issue CRUD requests, the meat and 'taters of this thing
import requests
# used with the login with certificate functions
# import base64 as base64
# Interact API returns a lot of json-like text objects
# we use this to bind them to python objects
import json
# used with the ... |
""" usuario table
Revision ID: 375f0af244b6
Revises: 2f9a3ba45b00
Create Date: 2018-09-08 03:19:22.000647
"""
# revision identifiers, used by Alembic.
revision = '375f0af244b6'
down_revision = '2f9a3ba45b00'
from alembic import op
import sqlalchemy as sa
def upgrade():
""" Executa as seguintes tarefas no banc... |
import os
class Config(object):
DEVELOPMENT = True
TEMPLATES_AUTO_RELOAD = True
SECRET_KEY = os.environ.get('SECRET_KEY')
|
def interversion(s):
return " ".join(list(reversed(s.split(" "))))
print(interversion("Marc Barthet"))
|
import copy
import contextlib
import StringIO
import unittest
from view import viewfile
def _make_simple_entry(name, branch='master', revision='HEAD'):
return viewfile.ViewFileEntry(name, 'git://{0}/{0}'.format(name), 'GIT',
branch, revision)
class TestViewFileEntryMethods(unitt... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
import subprocess
import time
"""Takes a textfile with ip-adresses and their frequency as input, performs
whois-request using the Linux-Bash and produces a csv-output showing the
ip-address and the correspondign frequency, the countrycode and the owner
of the ip-ad... |
# ----------------------------------------------------------------------
# Author: yury.matveev@desy.de
# ----------------------------------------------------------------------
import os, subprocess
aliases_path = os.path.expanduser('~/.bash_aliases')
my_alias = "alias camera='" + os.getcwd() + "/start_camera.sh'\... |
import pytest
from src.root.search.binary import binary_search
def test_binary():
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 6
index = 6
assert binary_search(array, target) == index
def test_binary_not_found():
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
target = 100
index = -1
... |
from __future__ import print_function
from tensorflow.python.keras.models import Model, load_model
from tensorflow.python.keras.layers import Input, LSTM, Dense, Embedding
import numpy as np
from src.utils import one_hot_encode, add_n
class Seq2Seq:
def __init__(self, num_encoder_tokens, num_decoder_tokens, st... |
import inspect
from django.contrib.auth.models import User
from rest_framework import permissions
class PermissionFix(object):
"""
This class addresses a shortcoming in permissions.BasePermission.
Use as a mixin, to ensure that a Permission class defaults to
the has_permission m... |
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge, FallingEdge, ClockCycles
from frequency_counter.test.test_seven_segment import read_segments
@cocotb.test()
async def test_wrapper(dut):
clock = Clock(dut.wb_clk_i, 10, units="ns")
cocotb.fork(clock.start())
# reset but ... |
#!/usr/bin/python3
'''
decode a CID (Content IDentifier) as used in IPFS
see https://github.com/multiformats/cid
To decode a CID, follow the following algorithm:
1. * If it's a string (ASCII/UTF-8):
* If it is 46 characters long and starts with Qm..., it's a CIDv0. Decode
it as base58btc and continue to ... |
import sys
import cv2
import numpy
# ------------------------------
# stdin = sys.stdin.buffer.read()
# array = numpy.frombuffer(stdin, dtype='uint8')
# img = cv2.imdecode(array, 1)
# cv2.imshow("window", img)
# cv2.waitKey() |
"""empty message
Revision ID: 7349ce2f6db4
Revises:
Create Date: 2020-07-10 18:57:58.357627
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7349ce2f6db4'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
from src.tabular.policies import *
from src.tabular.TD import QLearning |
from cougar.graphs.backbone import vgg
import torch
def test_vgg():
size = 300
input = torch.randn(1, 3, size, size)
model = vgg(size)
output = model(input)
assert len(output) == 6
assert output[0].shape[2] == 38
assert output[5].shape[2] == 1
|
import torch
import argparse
import glob
import logging
import os
import time
from data import load_dataset
from models import StyleTransformer, Discriminator, BartSystem
from train import train
from transformer_base import add_generic_args, add_generic_args, generic_train
class Config():
data_path = './data/ch... |
"""
Maps each :mod:`Reading <snsary.models.reading>` to a new one with the name altered as specified. This can be useful to distinguish the same :mod:`Readings <snsary.models.reading>` being aggregated in different ways.
Supported alterations include:
- ``to`` - replaces the name of the reading with the one speci... |
import functools
from flask import session, url_for, redirect
def needs_auth(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
if "api_key" not in session:
return redirect(url_for("root.root"))
return f(*args, **kwargs)
return wrapper
def allowed_file(filename, extensio... |
import SimpleITK as sitk
import matplotlib.pyplot as plt
import numpy as np
import cv2
from scipy.signal import convolve
import skimage
from skimage import util
def random_noise(image,noise_num):
img_noise = image
rows, cols = img_noise.shape
for i in range(noise_num):
x = np.random.randint(0, ro... |
from .gos import *
__all__ = ["World", "Globe", "Agent"]
__title__ = 'globalopensimulator'
__version__ = '0.0.0a'
|
# Generated by Django 2.2.7 on 2021-10-31 14:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ugc', '0004_berries_customers_decors_forms_levels_orders_orderstatuses_topping'),
]
operations = [
migrations.AlterField(
model_... |
'''
================================================
## VOICEBOOK REPOSITORY ##
================================================
repository name: voicebook
repository version: 1.0
repository link: https://github.com/jim-schwoebel/voicebook
author: Jim Schwoebel
author contact: js@neur... |
import logging
from collections import OrderedDict
from operator import itemgetter
import networkx as nx
import torch
from torch import nn
from torch.utils.data import DataLoader
from src.models.samplers.arch_sampler import ArchSampler
from src.models.samplers.conditional_softmax_sampler import \
CondiSoftmaxArch... |
import numpy as np
import os
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import sklearn
from sklearn.datasets import make_blobs
from sklearn.cluster import AgglomerativeClustering
##################################################
### Agglomerative clustering on random... |
#!/usr/bin/env python
import sys
import os
# put this module at the front of the path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], "../../")))
from hcp_prep.interfaces import *
out_file = os.path.join(os.path.split(__file__)[0], "interface_docs.txt")
ints = [HCDcm2nii, DicomInfo, Nii... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.