content stringlengths 5 1.05M |
|---|
import unittest
from p1 import *
from p2 import *
from p3 import *
# Test cases
class TestCodeEdX(unittest.TestCase):
def test_count(self):
self.assertEqual(remainingBalance(42, 0.2, 0.04), 31.38)
self.assertEqual(remainingBalance(484, 0.2, 0.04), 361.61)
self.assertEqual(estimateLowestPaym... |
import logging
import os
import win32com.client
import pandas as pd
logging.basicConfig(level=logging.INFO)
templateName = "Template.msg"
recipientsFile = "Recipients.xlsx"
logging.info('Violet App Start')
path = os.getcwd()
logging.info('Current Directory {}'.format(path))
outlook = win32com.client.D... |
from .gossip_net import GossipNode
|
import numpy as np
from scipy.stats import f
from statsmodels.stats.stattools import durbin_watson
class AR_model(object):
def __init__(self, X, Y, Q_L=1.6, Q_U=2.3, upper=True, basis_type='residual'):
self.Y = Y
self.X = X
self.n = X.shape[0]
self.p = X.shape[1]
self.Q_L =... |
import requests
import os
from dotenv import load_dotenv
from get_file_extension_and_dowland_images import get_file_extension, download_image
def fetch_spacex_last_launch(directory):
response = requests.get("https://api.spacexdata.com/v3/launches")
response.raise_for_status()
launches = response.json()
... |
# Generated by Django 3.1.2 on 2020-11-03 12:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('portfolio_admin', '0002_project'),
]
operations = [
migrations.AlterField(
model_name='project'... |
from django.contrib import admin
from .models import Services, Reference, Article, Category, Tag, Customer, Feature, Skill
class ArticleAdmin(admin.ModelAdmin):
list_display = ['caption', 'author', 'visible']
class Meta:
model = Article
admin.site.register(Article, ArticleAdmin)
class CategoryAd... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
%prog -i query.fa -d database.fa [options]
run LASTZ similar to the BLAST interface, and generates -m8 tabular format
"""
import os
import sys
import math
import logging
logging.basicConfig(level=logging.DEBUG)
from subprocess import Popen, PIPE
from multiprocessing... |
import logging
import time
from aprsd import plugin, trace
LOG = logging.getLogger("APRSD")
class PingPlugin(plugin.APRSDRegexCommandPluginBase):
"""Ping."""
command_regex = "^[pP]"
command_name = "ping"
short_description = "reply with a Pong!"
@trace.trace
def process(self, packet):
... |
# Copyright 2019-2021 Huawei Technologies Co., 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 agre... |
from sklearn import metrics
from sklearn.model_selection import cross_validate
import pandas as pd
def evaluation_report(y_test, pred, labels=None):
"""Generate report for demand metrics
Args:
y_test ([pd.series]): [ground truth label]
pred ([[pd.series]]): [model prediction]
labels (... |
"""
Module that makes use of the Spotify Web API to retrieve songs below a selected
'threshold' of popularity.
Genres list scrapped from: http://everynoise.com/everynoise1d.cgi?scope=all&vector=popularity
Spotify Ref: https://developer.spotify.com/documentation/web-api/reference-beta/#category-search
"""
from json imp... |
import argparse
import os.path as osp
import os
import mmcv
from functools import partial
import SimpleITK as sitk
from PIL import Image
import numpy as np
def convert_mhd(mhd_file, in_dir, out_dir):
data = sitk.ReadImage(osp.join(in_dir, mhd_file))
np_data=sitk.GetArrayFromImage(data)
np_data=np.moveaxis... |
# this is python/flask server
# flask is a python based framwork, similar to django or express
# importing necessary modules
import requests
import flask
from flask import Flask, request, render_template, jsonify, redirect, url_for, make_response
from flask.ext.sqlalchemy import SQLAlchemy
import jwt
from logging impo... |
from setuptools import setup
setup(
name='InstagramAPI',
version='1.0.3',
description='Unofficial instagram API, give you access to ALL instagram features (like, follow, upload photo and video and etc)! Write on python.',
url='https://github.com/ganeshkrishnan1/Instagram-API-python/',
author='Pasha... |
# *-* coding: UTF-8 *-*
import functools
import mock
import unittest2
import urlparse
import rdflib
from django.core.urlresolvers import set_urlconf
from django_hosts.reverse import get_host
from humfrey.linkeddata import mappingconf, resource
from humfrey.linkeddata.uri import doc_forward, doc_backward
from humfrey... |
import os
from time_lapse import make_movie
NAME = os.path.basename(__file__).replace('.py', '')
PATTERNS = [
'/Volumes/Falcon/tl_temp/181014/1/*.tiff', # ADL_244715 - ADL_244857
'/Volumes/Falcon/tl_temp/181014/2/*.tiff', # ADL_244862 - ADL_245077
]
if __name__ == '__main__':
make_movie(NAME, PATTERNS... |
#!/usr/bin/env python
import warnings
from collections import namedtuple
import numpy as np
import matplotlib.pyplot as plt
import lsst.afw.geom as afw_geom
import lsst.afw.table as afw_table
import lsst.daf.persistence as dp
import GCRCatalogs
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
f... |
""" Namespace to keep all application storage keys
Unique keys to identify stored data
Naming convention accounts for the storage scope: application, request, response, configuration and/or resources
All keys are constants with a unique name convention:
$(SCOPE)_$(NAME)_KEY
See https://aiohttp.readthedocs.io/en... |
##
# File: ChemCompIndexWorkflow.py
# Date: 2-Jun-2020 jdw
#
# Workflow wrapper -- generate chemical component and BIRD search indices --
#
# Updates:
# 10-Jun-2020 jdw Hookup to ChemCompSearchWrapper()
##
__docformat__ = "google en"
__author__ = "John Westbrook"
__email__ = "jwest@rcsb.rutgers.edu"
__license__ ... |
# Generated by Django 3.1.7 on 2021-03-11 07:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0058_auto_20210309_0816'),
]
operations = [
migrations.AlterField(
model_name='automaticperitonealdialysis',
... |
print("Hola christian")
a=45
b=30
print("suma:",a+b)
print("resta",a-b)
print("division",a/b)
print("multiplicacion",a*b)
print("suma:",b+a)
print("resta",b-a)
print("division",b/a)
print("multiplicacion",b*a)
print("¿ella me ama?")
print("no")
|
#first program in python!
print("Hello,World")
#using upper and lower cases
message = "Hello World"
print(message.upper())
print(message.lower())
#combining variables
first_word = "Hello"
last_word = "World"
full_words = f"{first_word} {last_word}"
print(full_words)
#adding longer strings
message = ... |
import sys
input = sys.stdin.readline
a, b = map(int, input().split())
v = 0
for j in range(len(bin(b))):
c = 0
for i in range(len(bin(b))-len(bin(a))):
if(j-1 > len(bin(a+i))):
t = bin(a+i)[-len(bin(a+i))]
else:
t = bin(a+i)[-j-1]
if(t == "b"):
c += ... |
#!/usr/bin/env python
# coding=utf-8
from os.path import abspath, dirname
from sanic import Sanic
from sanic.response import json, html
from jinja2 import Environment, PackageLoader, select_autoescape
from ProxyIP.database import RedisClient
app = Sanic()
redis_conn = RedisClient()
env = Environment(
loader=Pack... |
import splineJointsScript
reload(splineJointsScript)
from splineJointsScript import splineJoints
# Este script permite crear 3 c cadenas de huesos(rotacion, posicion y bindeo) a partir de una curva, un control
# para cada uno de los huesos y uno general con conexion directa a todos ellos
# ejemplo de uso con una cu... |
import os
import argparse
from easydict import EasyDict
from tensorboardX import SummaryWriter
import pprint
import time, datetime
from prototype.model import Momentum
import torch
import torchvision
import json
import spring.linklink as link
import torch.nn.functional as F
import random
from .base_solver import BaseSo... |
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2019/1/28 7:44 PM
import logging
LOG_FORMAT = "[%(asctime)s] [%(processName)s:%(threadName)s] [%(levelname)s:%(filename)s:%(funcName)s:%(lineno)d] %(message)s"
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
Logger = logging.getL... |
#!/usr/bin/env python3
# -*- config: utf-8 -*-
# Вариант 5
# Одноклеточная амеба каждые три часа делится на 2 клетки. Определить, сколько будет
# клеток через 6 часов.
if __name__ == '__main__':
amoeba = 1
for i in range(amoeba, 6, 3):
amoeba *= 2
print(f"{amoeba}")
|
from bg_tts import talk
import random
import temp
from RPLCD import CharLCD
import RPi.GPIO as GPIO
from LCD import writeOnLCD
import time
lcd = CharLCD(cols=16, rows=2, pin_rs=37, pin_e=35, pins_data=[40, 38, 36, 32, 33, 31, 29, 23], numbering_mode=GPIO.BOARD, auto_linebreaks=True)
def hello_rep():
hello = ["Здр... |
import cog
from pathlib import Path
import torch
import pixray
import yaml
import pathlib
import os
import yaml
# https://stackoverflow.com/a/6587648/1010653
import tempfile, shutil
def create_temporary_copy(src_path):
_, tf_suffix = os.path.splitext(src_path)
temp_dir = tempfile.gettempdir()
temp_path = o... |
class RdopkgException(Exception):
msg_fmt = "An unknown error occurred"
exit_code = 1
def __init__(self, msg=None, exit_code=None, **kwargs):
self.kwargs = kwargs
if not msg:
try:
msg = self.msg_fmt % kwargs
except Exception:
# kwargs ... |
# magicblast_alignment.py
#
# Author: Jan Piotr Buchmann <jan.buchmann@sydney.edu.au>
# Description:
#
# Version: 0.0
class MappingAlignment:
class Read:
def __init__(self, name, start, stop, strand, qlen):
self.name = name
self.length = int(qlen)
self.sra_rowid = name.split('.')[1]
... |
"""Test the CHGCAR parser."""
# pylint: disable=unused-import,redefined-outer-name,unused-argument,unused-wildcard-import,wildcard-import
import pytest
import numpy as np
from aiida_vasp.utils.fixtures import *
from aiida_vasp.utils.fixtures.testdata import data_path
from aiida_vasp.parsers.content_parsers.chgcar imp... |
from cvc5_pythonic_api import *
if __name__ == '__main__':
# Let's introduce some variables
x, y = Reals('x y')
a, b = Ints('a b')
# We will confirm that
# * 0 < x
# * 0 < y
# * x + y < 1
# * x <= y
# are satisfiable
solve(0 < x, 0 < y, x + y < 1, x <= y)
# If we get ... |
#!/usr/bin/python
import inspect
import re
class Fail(Exception): pass
class Shardable(object):
def __init__(self):
super(Shardable,self).__init__()
print "Initialising Shardable"
self.IShards = {}
def addMethod(self, name, method):
self.__dict__[name] = lambda *args: method(... |
from common.DataFilterHandler import DataFilterHandler
if __name__ == '__main__':
# first filter the data
filter = DataFilterHandler(database_name='TechHub', collection_name='CSDN', use_localhost=False)
filter.start() |
from unittest import TestCase
from jsonconf import CommandLineParser
class ConfigTests(TestCase):
def setUp(self):
pass
def test_constructor(self):
parser = CommandLineParser()
self.assertTrue(parser is not None)
self.assertEqual(parser.getKeywordArguments(), {})
self... |
#!/usr/bin/env python3
import json
import sys
import subprocess
import time
import argparse
import requests
from jwcrypto import jwk, jwt, jws
from jwcrypto.common import json_encode
from jwcrypto.jws import InvalidJWSSignature
def command_line_validate():
parser = argparse.ArgumentParser(formatter_class=argpars... |
def idstring(s):
return s
def printstring(s):
print("%s\n" % idstring(s), end='')
def print_toto(t):
print("%s = %d\n" % (t["s"], t["v"]), end='')
tab = [None] * 2
for i in range(0, 2):
tab[i] = idstring("chaine de test")
for j in range(0, 2):
printstring(idstring(tab[j]))
print_toto({"s":"one", "v... |
# Benchmarking Suite
# Copyright 2014-2017 Engineering Ingegneria Informatica S.p.A.
#
# 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 ... |
import requests
from openpyxl import load_workbook
from openpyxl import Workbook
import json
import gc
gc.collect()
url = "http://openapi.uml-tech.com/farm/getLocation"
header = {'Content-Type': 'application/json'}
#------------获取50辆农机的did号----------------
excel_did = load_workbook('50_did.xlsx')
table_did = excel_did... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 15 22:15:40 2017
@author: psamtik071
"""
#functions for feature-engineering
import pandas as pd
# make sure tot_docks > 0 (especially when calculating bikes available)
def bulk_query(year):
# query all bikes after or before a certain time
... |
from discord.ext import commands
import discord
import rethinkdb as r
import aiohttp
import logging
log = logging.getLogger()
class Donator(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def __has_donated(self, user:int):
data = await self.bot.redis.get("donate:{}".format(user)... |
import re
import json
import scrapy
from gymshark.items import GymsharkItem
p = r"(?P<conf_start>var gtmPushData =\s)(?P<config>{[^;]+ee-productView[^;]+})(?P<conf_end>;)"
PAGE_CONFIG_PATTERN = re.compile(p)
class ProductSpider(scrapy.Spider):
"""Gymshark product spider"""
name = 'gymshark_products'
... |
#Shape of small m:
def for_m():
"""printing small 'm' using for loop"""
for row in range(5):
for col in range(8):
if col%3==1 and row!=0 or row==0 and col in(2,3,5,6) or row==col==0:
print("*",end=" ")
else:
print(" ",end=" ")
prin... |
# -- MAIN FILE ---------------------------------------------
# ----------------------------------------------------------
# # -- IMPORTS ---------------------------------------------
# # --------------------------------------------------------
import os, sys, json
from parse_database import make_new_database
from g... |
'''
Documentation dependencies:
- sphinx
- sphinx_rtd_theme
- sphinx-autobuild
- jsx-lexer
'''
#-- Path setup -----------------------------------------------------------------
import sys
sys.path.append('python')
#-- Project information --------------------------------------------------------
project = 'artisan'
la... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import argparse, sys
stdin_fname = '$stdin$'
def get_args():
description = "plot points into graph. x and y seperated with white space in one line, or just y's"
parser = argparse.ArgumentParser(d... |
from .util import synthetic |
import argparse
import csv
import pickle
from symbolic_pursuit.models import SymbolicRegressor
from datasets.data_loader_UCI import data_loader, mixup
from experiments.train_model import train_model
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from time import strftime, gmtime
d... |
from functools import wraps
from .responses import RevenueCatError
def require_secret():
def decorator(f):
@wraps(f)
def decorated(self, *args, **kwargs):
if not self.secret_key:
raise RevenueCatError(message="Secret key required")
return f(self, *args, **k... |
import branca.colormap as cm
import folium
import geopandas as gpd
import numpy as np
import pandas as pd
import datetime
# Create dataframe of preds
date, fips, pred = [], [], []
with open('submission.csv') as f:
submission = f.read().strip().split('\n')[1:]
for line in submission:
line = line[:10] + ',' + ... |
import unittest
import network_utils
import re
class LanInterfacesTest(unittest.TestCase):
def testGetExternalIpAddress(self):
external_ip_address = network_utils.get_external_ip_address()
pattern = re.compile('^[0-9]+.[0-9]+.[0-9]+.[0-9]+')
self.assertTrue(pattern.match(external_ip_address))
def tes... |
# Desenvolva um programa que leia seis numeros inteiros e mostre
# a soma apenas daq ueles que forem pares. se o valor digitado for impar
# Desconsidere-o
soma = 0
for num in range(1, 7):
numero = int(input(f'Digite o {num}° numero: '))
if numero % 2 == 0:
soma += numero
print(soma)
|
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"ColabBase": "00_core.ipynb",
"ColabStreamlit": "00_core.ipynb",
"ColabFlask": "00_core.ipynb",
"ColabFastapi": "00_core.ipynb",
"ColabCustom": "00_core.ipynb"}
modules = ... |
df.index = pd.to_datetime(combined, dayfirst=True) |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 02:16:33 2020
@author: yashm
"""
from flask import Flask, jsonify, request
import functools
import requests
from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
fr... |
import discord
import asyncio
import random
import urllib.request
import json
client = discord.Client()
token = os.environ['DISCORD_BOT_TOKEN']
@client.event
async def on_message(message):
# 「おはよう」で始まるか調べる
d = 0
a = 0
if message.content.startswith('K!pc'):
if client.user != mes... |
import sys
import json
from requests import post
from uuid import uuid4
bot_authorization = 'Key '
commands_url = 'https://msging.net/commands'
def setResourceValue(name, value):
print(f'Setting {name} as {value}')
res = post(
commands_url,
headers={
'Authorization': bot_authoriza... |
from flask import Flask, request
from flask_restplus import Namespace, Resource, Api, fields
import pymongo
from bson import ObjectId
from database import get_db
api = Namespace('clientes', description='clientes related operations')
clientesParser = api.parser()
clientesParser.add_argument(
'page', type=int, hel... |
from client_session import ClientSession
from commands.command_base import CommandBase
class GetManyTasks(CommandBase):
def __init__(self):
super().__init__("Queries Tasks using given filter parameters and prints them.")
self._parser.add_argument("-r", "--robot",
... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#======================================================================
#
# kanaquiz.py - play hiragana / katakana quiz
#
# Created by skywind on 2019/09/11
# Last Modified: 2019/09/11 16:35:48
#
#======================================================================
from... |
import json
import yaml
# do tags
tagsYaml = yaml.load_all(open('tags.yaml'))
tagsJSON = []
for doc in tagsYaml:
tagsJSON.append(doc)
json.dump(tagsJSON, open('tags.json', 'w'), indent=4, separators=(',', ': '))
|
import os
import json
import numpy as np
import pandas as pd
import pickle
import re
from pandas.io.json import json_normalize
from tqdm import tqdm
pretty_names = {
'model_init_strategy': {
"SimpleCombinedStrategy(RuleOfThumbScott(), FixedCStrategy(1))": 'RoT_C1',
"SimpleCombinedStrategy(RuleOfThu... |
from abc import ABCMeta, abstractmethod
from typing import List, Optional, Sequence
import gym
import numpy as np
from ..containers import FIFOQueue
from ..dataset import (
Episode,
MDPDataset,
Transition,
TransitionMiniBatch,
trace_back_and_clear,
)
from .utility import get_action_size_from_env
... |
from django import template
from django.urls import resolve
register = template.Library()
@register.simple_tag(takes_context=True)
def is_active(context, value):
url_name = resolve(context.request.path)
if url_name.url_name.split("_")[0] == "accounts":
if url_name.kwargs.get("account_type") == value... |
exclude_patterns = ['_build']
linkcheck_anchors = True
|
import torch
import utility
import data
import model
import loss
from option import args
from trainer import Trainer
def print_network(net):
num_params = 0
for param in net.parameters():
num_params += param.numel()
print(net)
print('Total number of parameters: %d' % num_params)
def print_set... |
"""The tests for the Template light platform."""
import pytest
import homeassistant.components.light as light
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP,
ATTR_EFFECT,
ATTR_HS_COLOR,
ATTR_TRANSITION,
ATTR_WHITE_VALUE,
SUPPORT_BRIGHTNESS,
SUPPORT_COLOR... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
__author__ = "Bannings"
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def convertBST(self, r... |
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import datasets # Load dataset
iris=datasets.load_iris()
print("Iris Data set loaded...") # Split the data into train and test samples
x_train, x_test, y_train, y_test = train_test_split(ir... |
#!/router/bin/python
import sys
import os
_ext_libs = [ {'name': 'simple_enum'},
{'name': 'pyyaml-3.11', 'py-dep': True},
{'name': 'pyzmq-ctypes'},
{'name': 'jsonrpclib-pelix-0.2.5'},
{'name': 'termstyle'},
{'name': 'netstat'}
]
def _i... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from reversion.admin import VersionAdmin
from .models import Company, Brand
class CompanyAdmin(VersionAdmin):
list_display = (
u'id',
'nip',
'name',
'address',
'plCapital',
'plCapital_notes',
)
search... |
import logging
import numpy as np
import os
import yamlargparse
from SVS.model.layers.global_mvn import GlobalMVN
from SVS.model.network import RNN_Discriminator
from SVS.model.utils.loss import MaskedLoss
from SVS.model.utils.SVSDataset import SVSCollator
from SVS.model.utils.SVSDataset import SVSDataset_filter
from... |
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from ..chatbot import chat
from ..models import Conversation
@csrf_exempt
@login_required
def web_hook(request):
sender_id = request.user.username
last_message_id... |
import scrapy
import pandas as pd
from environs import Env
env = Env()
env.read_env()
cookies = env("COOKIES")
def _s(s):
return ''.join(s) if s else ''
class DoubanSpider(scrapy.Spider):
name = 'douban_spider'
start_url = 'https://book.douban.com/mine?status=collect'
headers = {
'cookie':... |
from .telegramabstract import TelegramApi
class TELEGRAMAPIDefaultAPI(TelegramApi):
def __init__(self, api_key, api_server, **kwargs):
super(TELEGRAMAPIDefaultAPI, self).__init__(**kwargs)
self.api_key = api_key
self.api_server = api_server
def bulk_send(self, usernames: [str], messa... |
from datetime import datetime
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from forms.forms import GameForm
from game.models import Player, Sport, Game
def about(request):
return render(request, 'abou... |
# Generated by Django 2.0.1 on 2018-02-13 19:24
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('team', '0007_auto_20180125_1827'),
]
operations = [
migrations.CreateModel(
name='D... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
# The Hello request verifies login.
#
# A successful Hello request means that login was successful. Unsuccessful
# logins raise GWIS_Error.
from lxml import etree
import os
import sys
import conf
import g
... |
#-*-coding:utf-8-*-
# date:2020-05-21
# Author: x.l.eric
# function:
import os
import json
import cv2
import sys
sys.path.append('./')
from utils.common_utils import *
import glob
import math
import os
import random
import shutil
from pathlib import Path
from PIL import Image
# import matplotlib.pyplot as plt
from t... |
# prof. edmund weitz
# weihnachtsvorlesung 2021
# https://www.youtube.com/watch?v=YIkqZsz4faA
def LFSR(n,taps):
state = 1<<(n-1)
while True:
out = state&1
yield out
state = (state>>1)^(out*taps)
def check(n,taps):
m = 2**n-1
L = [out for out,_ in zip(LFSR(n,taps),range(m+n))]
M = {sum(L[k+1... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from flask import flash, request
from sqlalchemy.orm import joine... |
import asyncio
import discord
import ffmpeg
from ffprobe import FFProbe
import media_cache
import os
import traceback
boost_info = [
{ 'mb': 7.9, 'bits': 750000 },
{ 'mb': 49.9, 'bits': 45000000 },
{ 'mb': 99.9, 'bits': 95000000 }
]
loading_emotes = [
'\U0001F1EC',
'\U0001F1F2',
... |
import io
import os
from contextlib import contextmanager
import pytest
import six
from mock import patch
from dbnd._core.task_run.log_preview import merge_read_log_files, read_head_and_tail
TARGET_OPEN = "io.open"
DBND_LOG_FILE = """[2020-01-01 00:00:01,000] first log line
[2020-01-01 00:00:11,000] second log l... |
# -*- coding: utf-8 -*-
def main():
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
if m == 0:
print(1)
exit()
if n == m:
print(0)
exit()
a = list(map(int, input().split()))
max_a = max(a)
min_a = min(a)
if max_a != n:
... |
import logging
from django.db import models
from django.dispatch import receiver
from seahub.signals import repo_deleted
logger = logging.getLogger(__name__)
@receiver(repo_deleted)
def remove_repo_auto_del(sender, **kwargs):
repo_id = kwargs['repo_id']
try:
RepoAutoDelete.objects.filter(repo_id=repo... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.api_request_handler),
path('contribute/',views.api_contribute_request_handler)
] |
"""
Given an integer array nums, find the contiguous subarray (containing at least one number)
which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another so... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------------------------------------------------------------
# includes
# 2+3 compat
from __future__ import absolute_import, division, print_function, unicode_literals
# standards
from collections imp... |
from enum import Enum
class FileExt(Enum):
lm = '.ljson'
template = '.yml'
old_template = '.txt'
collection = '.txt'
class CacheFile(Enum):
texture = 'texture.jpg'
image = 'image.json'
thumbnail = 'thumbnail.jpg'
mesh_tmp = 'mesh.raw.tmp'
mesh = 'mesh.raw.gz'
class Server(Enum)... |
from genz_tokenize.models.bert.model_utils import Config
class DistilBertConfig(Config):
def __init__(
self,
vocab_size: int = 33333,
hidden_dim: int = 256,
num_hidden_layers: int = 8,
num_attention_heads: int = 8,
max_position_embeddings: int = 1024,
num_la... |
"""
Routines to find heliocentric correction using slalib
Originally from Alba Orion West project
"""
import numpy as np
from astropy.io import fits # type: ignore
from astropy import coordinates as coord # type: ignore
from astropy import units as u # type: ignore
from astropy import constants as const # type: ... |
"""Node API: simple tools for complex reservoir computing architectures.
The Node API features a simple implementation of computational graphs, similar
to what can be found in other popular deep learning and differenciable calculus
libraries. It is however simplified and made the most flexible possible by
discarding t... |
# Generated by Django 2.2.10 on 2020-07-30 11:20
from django.db import migrations, models
import wazimap_ng.points.models
class Migration(migrations.Migration):
dependencies = [
('points', '0031_auto_20200717_1053'),
]
operations = [
migrations.AddField(
model_name='location... |
"""Following tutorial from:
https://machinelearningmastery.com/learn-add-numbers-seq2seq-recurrent-neural-networks/"""
#%%
"""Addition as a mapping problem (the beginners mistake)
the problem solved has multiple inputs but was techinacally not a sequence prediction problem, and can be solved by a MLP"""
from random im... |
#!/usr/bin/env python
#
# Copyright 2017 Hewlett-Packard Development Company, L.P.
#
# 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... |
# coding=utf-8
from __future__ import print_function
import os
from six.moves import xrange as range
import math
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.utils
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn i... |
from typing import NoReturn
from ...base import BaseEstimator
import numpy as np
from numpy.linalg import det, inv
class LDA(BaseEstimator):
"""
Linear Discriminant Analysis (LDA) classifier
Attributes
----------
self.classes_ : np.ndarray of shape (n_classes,)
The different labels classe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.