content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Generated by Django 2.0.1 on 2018-01-23 11:13
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0013_auto_20170829_0515'),
]
operations = [
migrations.AlterField(
model_name='page',
... | nilq/baby-python | python |
from metaflow import resources
from metaflow.api import FlowSpec, step
class ResourcesFlow(FlowSpec):
@resources(memory=1_000)
@step
def one(self):
self.a = 111
@resources(memory=2_000)
@step
def two(self):
self.b = self.a * 2
class ResourcesFlow2(ResourcesFlow):
pass
| nilq/baby-python | python |
import struct
from slmkiii.template.input.button import Button
class PadHit(Button):
def __init__(self, data=None):
super(PadHit, self).__init__(data)
self.max_velocity = self.data(28)
self.min_velocity = self.data(29)
self.range_method = self.data(30)
def from_dict(self, data... | nilq/baby-python | python |
"""Implementation of the MCTS algorithm for Tic Tac Toe Game."""
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import numpy.typing as npt
from mctspy.games.common import TwoPlayersAbstractGameState
from mctspy.tree.nodes import TwoPlayersGameMonteCarloTreeSearchNode
fr... | nilq/baby-python | python |
from gettext import Catalog
from xml.etree.ElementInclude import include
from django.contrib import admin
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^catalog/', include(Catalog.urls)),
]
| nilq/baby-python | python |
from phq.kafka.consumer import _latest_distinct_messages
from phq.kafka import Message
def test_latest_distinct_messages():
messages = [
Message(id='abc', payload={}),
Message(id='def', payload={}),
Message(id='xyz', payload={}),
Message(id='xyz', payload={}),
Message(id='a... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Checks that gyp fails on static_library targets which have several files with
the same basename.
"""
import TestGyp
test = TestGyp.Tes... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
pySnarlNetLib
author: Łukasz Bołdys
licence: MIT
Copyright (c) 2009 Łukasz Bołdys
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 w... | nilq/baby-python | python |
from setuptools import setup
# read the contents of your README file
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="rubrix",
# other arguments omitted
descript... | nilq/baby-python | python |
# Generated by Django 3.0.7 on 2021-01-19 13:36
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('payment_system', '0027_a... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Author : kyclark
Date : 2018-11-02
Purpose: Rock the Casbah
"""
import argparse
import pandas as pd
import matplotlib.pyplot as plt
import sys
# --------------------------------------------------
def get_args():
"""get args"""
parser = argparse.ArgumentParser(
description... | nilq/baby-python | python |
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
s = ''
for i in zip(*strs):
if len(set(i)) != 1:
return s
else:
s += i[0]
return s
if __name__ == '__main__... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: uber/cadence/api/v1/tasklist.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _messa... | nilq/baby-python | python |
import string
def print_rangoli(n):
alpha = string.ascii_lowercase
L = []
for i in range(n):
s = "-".join(alpha[i:n])
L.append((s[::-1]+s[1:]).center(4*n-3, "-"))
print('\n'.join(L[:0:-1]+L))
if __name__ == '__main__':
n = int(input())
print_rangoli(n)
# def print_rangoli(size... | nilq/baby-python | python |
from pydantic import BaseModel
class PartOfSpeech(BaseModel):
tag: str
| nilq/baby-python | python |
# coding:utf-8
import os
import json
import numpy as np
import torch.utils.data as data
from detectron2.structures import (
Boxes,
PolygonMasks,
BoxMode
)
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_train2017.jso... | nilq/baby-python | python |
#Need to prebuild in maya first
#RenderScript.py
#MayaPythonScript : RenderScript
#A script that can use python to automativly render the scene
import maya.cmds as cmds
import maya.cmds as mc
import maya.app.general.createImageFormats as createImageFormats
from mtoa.cmds.arnoldRender import arnoldRender
#Function : g... | nilq/baby-python | python |
import torch
from torch import nn
from torch.nn import functional as F
def normalization(feautures):
B, _, H, W = feautures.size()
outs = feautures.squeeze(1)
outs = outs.view(B, -1)
outs_min = outs.min(dim=1, keepdim=True)[0]
outs_max = outs.max(dim=1, keepdim=True)[0]
norm = outs_max - outs_m... | nilq/baby-python | python |
from .nucleus_sampling import top_k_top_p_filtering
from .transformer_decoder import TransformerDecoder | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from odoo import http
# class ControleEquipement(http.Controller):
# @http.route('/controle_equipement/controle_equipement/', auth='public')
# def index(self, **kw):
# return "Hello, world"
# @http.route('/controle_equipement/controle_equipement/objects/', auth='public')
# ... | nilq/baby-python | python |
import consts
quotes = []
fp = open(consts.quotes_file, "r")
for line in fp:
if line[0] == '*':
quotes.append(line[2:-1])
fp.close()
| nilq/baby-python | python |
# Jogo da Forca versão 2
import tkinter as tk
import applic
window = tk.Tk()
applic.Application(window)
window.mainloop() | nilq/baby-python | python |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nilq/baby-python | python |
import pydocspec
from pydocspec import visitors
def dump(root:pydocspec.TreeRoot) -> None:
for mod in root.root_modules:
mod.walk(visitors.PrintVisitor())
# pydocspec_processes = {
# 90: dump
# }
| nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import mock
from click.testing import CliRunner
from elasticsearch_loader import cli
def invoke(content, *args, **kwargs):
if sys.version_info[0] == 2:
content = content.encode('utf-8')
runner = CliRunner()
with runner.isolated_filesystem... | nilq/baby-python | python |
from dataclasses import dataclass
import os
from typing import Optional
@dataclass(frozen=True)
class ENV:
workspace_name: Optional[str] = os.environ.get('WORKSPACE_NAME')
subscription_id: Optional[str] = os.environ.get('SUBSCRIPTION_ID')
resource_group: Optional[str] = os.environ.get('RESOURCE_GROUP')
... | nilq/baby-python | python |
# Learn more: https://github.com/Ensembl/ols-client
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
readme = f.read()
with open(os.path.join(os.path.dirname(__file__), 'LICENSE')) as f:
license_ct = f.read()
with open(os.path.join(... | nilq/baby-python | python |
from vidispine.base import EntityBase
from vidispine.errors import InvalidInput
from vidispine.typing import BaseJson
class Search(EntityBase):
"""Search
Search Vidispine objects.
:vidispine_docs:`Vidispine doc reference <collection>`
"""
entity = 'search'
def __call__(self, *args, **kwarg... | nilq/baby-python | python |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import copy
from datetime import datetime
from functools import partial
import os
from code import Code
import json_parse
# The template fo... | nilq/baby-python | python |
from flask_jsondash import settings
def test_settings_have_url_keys_specified():
for family, config in settings.CHARTS_CONFIG.items():
assert 'js_url' in config
assert 'css_url' in config
def test_settings_have_urls_list_or_none():
for family, config in settings.CHARTS_CONFIG.items():
... | nilq/baby-python | python |
number ="+919769352682 " | nilq/baby-python | python |
import asyncio
import statistics
import time
from typing import Optional
import pytest
import pytest_asyncio
from janus import Queue as JanusQueue
from utils import create_kafka_event_from_dict, create_kafka_message_from_dict
from eventbus.config import (
ConsumerConfig,
HttpSinkConfig,
HttpSinkMethod,
... | nilq/baby-python | python |
import numpy as np
import pandas as pd
import numba
import multiprocessing as mp
import itertools as it
import analyzer as ana
import concurrent.futures as fut
def calculate_pvalues(df, blabel, tlabel, mlabel, n, f=np.mean, **kwargs):
"""
Calculates the p value of the sample.
Parmas:
df --- (panda... | nilq/baby-python | python |
"""Create openapi schema from the given API."""
import typing as t
import inspect
import re
from http import HTTPStatus
from functools import partial
from apispec import APISpec, utils
from apispec.ext.marshmallow import MarshmallowPlugin
from http_router.routes import DynamicRoute, Route
from asgi_tools.response impo... | nilq/baby-python | python |
#!/usr/bin/env python
from setuptools import setup, find_packages
import versioneer
setup(name='hiwenet',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Histogram-weighted Networks for Feature Extraction and Advance Analysis in Neuroscience',
long_descriptio... | nilq/baby-python | python |
import os
import time
def main():
try:
os.remove("/etc/pmon.d/neutron-avs-agent.conf")
except:
pass
while True:
time.sleep(100)
if __name__ == "__main__":
main()
| nilq/baby-python | python |
from rest_framework import serializers
from paste import constants
from paste.models import Snippet
class SnippetSerializer(serializers.ModelSerializer):
"""Snippet model serializer."""
class Meta:
model = Snippet
fields = '__all__'
read_only_fields = ['owner']
def create(self, ... | nilq/baby-python | python |
""" Seeking Alpha View """
__docformat__ = "numpy"
import argparse
from typing import List
import pandas as pd
from datetime import datetime
from gamestonk_terminal.helper_funcs import (
check_positive,
parse_known_args_and_warn,
valid_date,
)
from gamestonk_terminal.discovery import seeking_alpha_model
... | nilq/baby-python | python |
import os
import ntpath
from preprocessing.segmentation import segment
from preprocessing.augment import augment
from CNN.recognize_character import recognize
from Unicode.seqgen import sequenceGen
from Unicode.printdoc import unicode_to_kn
def segmentation_call(image):
rootdir = 'web_app/hwrkannada/hwrapp/stat... | nilq/baby-python | python |
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from authors.apps.authentication.models import User
class ReadStats(models.Model):
"""
Users read statistics
"""
user = models.OneToOneField(User, on_delete=models.CASCADE, db_index=Tr... | nilq/baby-python | python |
import matplotlib.pyplot as plt
from flask import Flask
from flask_cors import CORS
from api.v1 import api_v1
app = Flask(__name__, static_url_path='', static_folder='frontend')
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.register_blueprint(api_v1, url_prefix='/api/v1')
app.config.SWAGGER_UI_DOC_EXP... | nilq/baby-python | python |
from datetime import datetime
from django.utils import timezone
import factory
from .. import models
from faker.generator import random
random.seed(0xDEADBEEF)
class BundleFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Bundle
easydita_id = factory.Faker('first_name')
ea... | nilq/baby-python | python |
from argparse import ArgumentParser
from irun.compiler import compile_node, construct
from irun.parser import parse
def compile_irun(source):
tree = parse(source)
rql_context = compile_node(tree)
return construct(rql_context)
def main(argv=None):
parser = ArgumentParser()
parser.add_argument("-... | nilq/baby-python | python |
import torch
from torch.autograd import Variable
import render_pytorch
import image
import camera
import material
import light
import shape
import numpy as np
resolution = [256, 256]
position = Variable(torch.from_numpy(np.array([0, 0, -5], dtype=np.float32)))
look_at = Variable(torch.from_numpy(np.array([0, 0, 0], dt... | nilq/baby-python | python |
f=open("./CoA/2020/data/02a.txt","r")
valid=0
for line in f:
first=int(line[:line.index("-")])
print(first)
second=int(line[line.index("-")+1:line.index(" ")])
print(second)
rule = line[line.index(" ")+1:line.index(":")]
print(rule)
code = line[line.index(":")+2:]
print(code)
if code... | nilq/baby-python | python |
## An implementation of the credential scheme based on an algebraic
## MAC proposed by Chase, Meiklejohn and Zaverucha in Algebraic MACs and Keyed-Verification
## Anonymous Credentials", at ACM CCS 2014. The credentials scheme
## is based on the GGM based aMAC. (see section 4.2, pages 8-9)
from amacs import *
from ge... | nilq/baby-python | python |
import pygame
import math
from Tower import *
pygame.init()
class T_SuperTower(Tower):
def __init__(Self , sc , Images):
Self.L1 = Images
Self.image = Self.L1[0]
Self.level = 5
Self.range = 100
Self.damage = 100
Self.x = 0
Self.y = 0
Self.bulletx ... | nilq/baby-python | python |
import os
import tempfile
class Config:
IS_TRAIN = True # Set whether you want to Train (True) or Predict (False)
TICKER = 'EURUSD'
num_of_rows_read = 1000 # If set 0 then all the rows will be read
# Set MySQL inputs if True
IS_MYSQL = False
MYSQL_USER = 'Write your user name'
MYSQL_PASSWORD = 'Write your... | nilq/baby-python | python |
from typing import Any
class TonException(Exception):
def __init__(self, error: Any):
if type(error) is dict:
error = f"[{error.get('code')}] {error.get('message')} " \
f"(Core: {error.get('data', {}).get('core_version')})"
super(TonException, self).__init__(error)
| nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import Flask
'''
Created on Nov 22, 2016
@author: jmartan
'''
import os,signal
import requests
import argparse
import uni_func
import atexit
import unicornhat
def update_widget(codec_ip, username, password, widget_id, value, unset=False):
# "unset" is needed in a si... | nilq/baby-python | python |
from slackbot.bot import Bot
from slackbot.bot import respond_to
import re
import foobot_grapher
def main():
bot = Bot()
bot.run()
@respond_to('air quality', re.IGNORECASE)
def air_quality(message):
attachments = [
{
'fallback': 'Air quality graph',
'image_url': foobot_grapher.getSensorReadings(Fal... | nilq/baby-python | python |
"""
Дан список, заполненный произвольными целыми числами. Найдите в этом списке два числа, произведение которых
максимально. Выведите эти числа в порядке неубывания. Решение должно иметь сложность O(n), где n - размер списка. То
есть сортировку использовать нельзя.
"""
a = list(map(int, input().split()))
negative_max =... | nilq/baby-python | python |
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.http import HttpResponse, HttpRequest
from zilencer.models import RemotePushDeviceToken, RemoteZulipServer
from zerver.lib.exceptions import JsonableError
from zerver.lib.push_notifications import send_android_push_notif... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
class InjaConan(ConanFile):
name = "inja"
version = "2.1.0"
url = "https://github.com/yasamoka/conan-inja"
description = "Template engine for modern C++, loosely inspired by jinja for Python"
licens... | nilq/baby-python | python |
class Learner(object):
def log_update(self, o, a, r, op, logpb, dist, done):
self.log(o, a, r, op, logpb, dist, done)
info0 = {'learned': False}
if self.learn_time(done):
info = self.learn()
self.post_learn()
info0.update(info)
info0['learned'... | nilq/baby-python | python |
import os
import shutil
import json
print("[+] Cleaning...")
with open("tree.json", "r") as f:
json_str = f.read()
json_data = json.loads(json_str)
f.close()
for (path, dirs, files) in os.walk(os.curdir):
if path not in json_data["dirs"]:
shutil.rmtree(path)
else:
for f in files:
f = f"{path}{os.sep}{f}"... | nilq/baby-python | python |
# BT5071 pop quiz 2
# Roll Number: BE17B037
# Name: Krushan Bauva
def bubble(A):
n = len(A)
if n%2 == 1:
A1 = A[0:n//2+1]
A2 = A[n//2+1:n]
else:
A1 = A[0:n//2]
A2 = A[n//2:n]
n1 = len(A1)
for i in range(n1-1, 0, -1):
for j in range(i):
if A1[j]>A1... | nilq/baby-python | python |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth.models import Permission, User
from django.db import models
from localflavor.us.models import USStateField
from phonenumber_field.modelfields import PhoneNumberField
from multiselectfield import MultiSelectField
from endor... | nilq/baby-python | python |
# -*- coding: utf-8 -*-createacsr_handler
from __future__ import unicode_literals
import json
import logging
import os
import uuid
import time
import secrets
import cryptography
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.p... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.management.base import BaseCommand
from credocommon.models import Detection
from credocommon.helpers import validate_image, rate_brightness
class Command(BaseCommand):
help = "Validate detections"
def handle(self, *args, **opt... | nilq/baby-python | python |
"""Implement an error to indicate that a scaaml.io.Dataset already exists.
Creating scaaml.io.Dataset should not overwrite existing files. When it could
the constructor needs to raise an error, which should also contain the dataset
directory.
"""
from pathlib import Path
class DatasetExistsError(FileExistsError):
... | nilq/baby-python | python |
from datetime import datetime
from django.views.generic.edit import BaseCreateView
from braces.views import LoginRequiredMixin
from .base import BaseEditView
from forum.forms import ReplyForm
from forum.models import Topic, Reply
class ReplyCreateView(LoginRequiredMixin, BaseCreateView):
model = Topic
form_... | nilq/baby-python | python |
"""
See the problem description at: https://leetcode.com/problems/minimum-add-to-make-parentheses-valid/
"""
class Solution:
def minAddToMakeValid(self, S: str) -> int:
"""
Time complexity : O(n)
Space complexity: O(1)
"""
score1 = score2 = 0
for char in S... | nilq/baby-python | python |
from tests.seatsioClientTest import SeatsioClientTest
from tests.util.asserts import assert_that
class ListAllTagsTest(SeatsioClientTest):
def test(self):
chart1 = self.client.charts.create()
self.client.charts.add_tag(chart1.key, "tag1")
self.client.charts.add_tag(chart1.key, "tag2")
... | nilq/baby-python | python |
"""empty message
Revision ID: 20210315_193805
Revises: 20210315_151433
Create Date: 2021-03-15 19:38:05.486503
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "20210315_193805"
down_revision = "20210315_151433"
branch_labels = None
depends_on = None
def upgra... | nilq/baby-python | python |
def parse_full_text(status):
"""Param status (tweepy.models.Status)"""
return clean_text(status.full_text)
def clean_text(my_str):
"""Removes line-breaks for cleaner CSV storage. Handles string or null value.
Returns string or null value
Param my_str (str)
"""
try:
my_str... | nilq/baby-python | python |
#!/usr/bin/env python
"""Command line utility to serve a Mapchete process."""
import click
import logging
import logging.config
import os
import pkgutil
from rasterio.io import MemoryFile
import mapchete
from mapchete.cli import options
from mapchete.tile import BufferedTilePyramid
logger = logging.getLogger(__name_... | nilq/baby-python | python |
from .dualconv_mesh_net import DualConvMeshNet
from .singleconv_mesh_net import SingleConvMeshNet
| nilq/baby-python | python |
from __future__ import print_function
import json
import urllib
import boto3
print('*Loading lambda: s3FileListRead')
s3 = boto3.client('s3')
def lambda_handler(event, context):
print('==== file list in bucket ====')
AWS_S3_BUCKET_NAME = 'yujitokiwa-jp-test'
s3_resource = boto3.resource('s3')
bucke... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 21:05:47 2020
@author: Richard
"""
from newsapi import NewsApiClient
newsapi = NewsApiClient(api_key='0566dfe86d9c44c6a3bf8ae60eafb8c6')
all_articles = newsapi.get_everything(q='apple',
from_param='2020-04-01',
... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pandas_datareader import data as web
from datetime import datetime, timedelta
from yahoo_finance import Share
from math import ceil, floor
from collections import deque
class Stock():
""" Historical data of a Stock
Attribute... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
size = 1000
x = np.random.randn(size)
y = 1.051 * x + np.random.random(size)
plt.plot(x,y,'*',color='black',label="Dado original")
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Regressão Linear')
slope, intercept, r_value, p_value, std_err = s... | nilq/baby-python | python |
"""
Contains functions to assist with stuff across the application.
ABSOLUTELY NO IMPORTS FROM OTHER PLACES IN THE REPOSITORY.
Created: 23 June 2020
"""
| nilq/baby-python | python |
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (C) 2015 by Brian Horn, trycatchhorn@gmail.com.
#
# 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 w... | nilq/baby-python | python |
from cto_ai import sdk, ux
cto_terminal = """
[94m██████[39m[33m╗[39m [94m████████[39m[33m╗[39m [94m██████[39m[33m╗ [39m [94m█████[39m[33m╗[39m [94m██[39m[33m╗[39m
[94m██[39m[33m╔════╝[39m [33m╚══[39m[94m██[39m[33m╔══╝[39m [94m██[39m[33m╔═══[39m[94m██[39m[33m╗[39m... | nilq/baby-python | python |
# http://book.pythontips.com/en/latest/for_-_else.html
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, "equals", x, "*", n // x)
break
else:
# loop fell through without finding a factor
print(n, "is a prime number")
# 2 is a prime number
# ... | nilq/baby-python | python |
""" pygame module for loading and playing sounds """
import math
from pygame._sdl import sdl, ffi
from pygame._error import SDLError
from pygame.base import register_quit
import pygame.mixer_music as music
from pygame.mixer_music import check_mixer
from pygame.rwobject import (rwops_encode_file_path, rwops_f... | nilq/baby-python | python |
# pylint: disable=missing-docstring
from openshift_checks import OpenShiftCheck, get_var
class DockerImageAvailability(OpenShiftCheck):
"""Check that required Docker images are available.
This check attempts to ensure that required docker images are
either present locally, or able to be pulled down from ... | nilq/baby-python | python |
import torch
from torch.multiprocessing import Pool
class Simulator(torch.nn.Module):
r"""Base simulator class.
A simulator defines the forward model.
Example usage of a potential simulator implementation::
simulator = MySimulator()
inputs = prior.sample(torch.Size([10])) # Draw 10 sa... | nilq/baby-python | python |
import re
from localstack.constants import TEST_AWS_ACCOUNT_ID
from localstack.utils.common import to_str
from localstack.services.generic_proxy import ProxyListener
class ProxyListenerIAM(ProxyListener):
def return_response(self, method, path, data, headers, response):
# fix hardcoded account ID in ARNs... | nilq/baby-python | python |
from __future__ import absolute_import, print_function
from django.conf.urls import patterns, url
from .action_endpoint import SlackActionEndpoint
from .event_endpoint import SlackEventEndpoint
from .link_identity import SlackLinkIdentitiyView
urlpatterns = patterns(
"",
url(r"^action/$", SlackActionEndpoin... | nilq/baby-python | python |
import cv2
import numpy as np
path = "./underexposed.jpg"
def _mask(img):
img = cv2.bitwise_not(img)
mask = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blured_img = cv2.GaussianBlur(mask, (15, 15), cv2.BORDER_DEFAULT)
return blured_img
def _local_contrast_correction(img, mask):
exponent = np.repeat((... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Launch a distributed job
"""
import argparse
import os, sys
import signal
import logging
curr_path = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(curr_path, "./tracker"))
#print sys.path
def dmlc_opts(opts):
"""convert from mxnet's opts to dmlc's opts
"""
... | nilq/baby-python | python |
import logging
import copy
import numpy as np
from scipy.linalg import expm
from .population import Population
from spike_swarm_sim.utils import eigendecomposition, normalize
from spike_swarm_sim.algorithms.evolutionary.species import Species
from ..operators.crossover import *
from ..operators.mutation import ... | nilq/baby-python | python |
# Generated by Django 2.2.7 on 2019-11-30 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('neighbourhood', '0005_neighbourhood_image'),
]
operations = [
migrations.AddField(
model_name='business',
name='imag... | nilq/baby-python | python |
#!/usr/bin/env python
import exifread
import logging
class Exif2Dict:
def __init__(self, filename):
self.__logger = logging.getLogger("exif2dict.Exif2Dict")
self.__tags = {}
try:
with open(filename, 'rb') as fh:
self.__tags = exifread.process_file... | nilq/baby-python | python |
#GUI Stuff
from tkinter import *
#GPIO setup for non-expander ports
import RPi.GPIO as GPIO
import time
#port Expander stuff
import board
import busio
from digitalio import Direction
from adafruit_mcp230xx.mcp23008 import MCP23008
#Port expander setup
i2c = busio.I2C(board.SCL, board.SDA)
mcp = MCP230... | nilq/baby-python | python |
r""" This module implements Peak Signal-to-Noise Ratio (PSNR) in PyTorch.
"""
import torch
from typing import Union
from typing import Tuple, List, Optional, Union, Dict, Any
def _validate_input(
tensors: List[torch.Tensor],
dim_range: Tuple[int, int] = (0, -1),
data_range: Tuple[float, float] ... | nilq/baby-python | python |
import numpy, random
import os
import uuid
import cloudpickle
import json
from flor.constants import *
from .. import stateful as flags
from torch import cuda
class Writer:
serializing = False
lsn = 0
pinned_state = []
seeds = []
store_load = []
partitioned_store_load = []
max_buffer = 500... | nilq/baby-python | python |
from leapp.actors import Actor
from leapp.models import Report, OpenSshConfig
from leapp.tags import ChecksPhaseTag, IPUWorkflowTag
from leapp.libraries.common.reporting import report_generic
class OpenSshUsePrivilegeSeparationCheck(Actor):
"""
UsePrivilegeSeparation configuration option was removed.
Che... | nilq/baby-python | python |
import tensorflow as tf
import tensorflow.keras as tk
import nthmc
conf = nthmc.Conf(nbatch=1, nepoch=1, nstepEpoch=1024, nstepMixing=64, stepPerTraj = 10,
initDt=0.4, refreshOpt=False, checkReverse=False, nthr=4)
nthmc.setup(conf)
beta=3.5
action = nthmc.OneD(beta=beta, transform=nthmc.Ident())
loss = nthmc.LossFu... | nilq/baby-python | python |
from __future__ import annotations
from injector import Injector
from labster.domain2.model.structure import Structure, StructureRepository
from labster.domain2.model.type_structure import CO, DU, FA, LA, UN
def test_single():
universite = Structure(nom="Sorbonne Université", type_name=UN.name, sigle="SU")
... | nilq/baby-python | python |
from django.contrib import admin
from .models import Confirguracoes
# Register your models here.
admin.site.register(Confirguracoes)
| nilq/baby-python | python |
from __future__ import division
import matplotlib
#matplotlib.use('agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection
import numpy as np
class RobotArm(object):
def __init__(self):
self.dh_a= [ 0,... | nilq/baby-python | python |
""" Exceptions for the library. """
class CatnipException(Exception):
""" Base exception class. """
class NoFrame(CatnipException):
""" Failed to receive a new frame. """
| nilq/baby-python | python |
# test of printing multiple fonts to the ILI9341 on a esp32-wrover dev kit using H/W SP
# MIT License; Copyright (c) 2017 Jeffrey N. Magee
from ili934xnew import ILI9341, color565
from machine import Pin, SPI
import tt14
import glcdfont
import tt14
import tt24
import tt32
fonts = [glcdfont,tt14,tt24,tt32]
text = 'No... | nilq/baby-python | python |
"""
Simple time checker by David. Run with `python time_checker.py` in
the same folder as `bat_trips.json`
"""
import json
from datetime import datetime as dt
with open('bat_trips.json') as f:
start_times = []
end_times = []
for i in range(24):
start_times.append(0)
end_times.append(0)
... | nilq/baby-python | python |
import cv2, numpy as np
import time
import math as mth
from PIL import Image, ImageDraw, ImageFont
import scipy.io
from keras.models import Sequential
from keras import initializations
from keras.initializations import normal, identity
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimiz... | nilq/baby-python | python |
import pytest
from typing import Any, Callable, Tuple
from aio_odoorpc_base.sync.common import login
from aio_odoorpc_base.protocols import T_HttpClient
import httpx
@pytest.fixture(scope='session')
def runbot_url_db_user_pwd(runbot_url_db_user_pwd) -> Tuple[str, str, str, str]:
base_url, url_jsonrpc, db, usernam... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import math
import glob
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing
from common import DataPreset, load_preset_from_file, save_plot
def plot_step(params):
name = params['name']
#preset = params['preset']
ste... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.