content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# utils
from .rfb_utils import object_utils
from .rfb_utils import transform_utils
from .rfb_utils import texture_utils
from .rfb_utils import scene_utils
from .rfb_utils import shadergraph_utils
from .rfb_logger import rfb_log
from .rman_sg_nodes.rman_sg_lightfilter import RmanSgLightFilter
from . import rman_consta... | nilq/baby-python | python |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
#TODO1: Create the turtle and move it with keypress
player = Player()
screen.listen()
screen.onkey(player.go_up... | nilq/baby-python | python |
s = list(input('Escriba el string: '))
s[0] = s[0].upper()
print(''.join(s))
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Charge logging script
This script will download the get_vehicle_status every 5 minutes
and log them locally. Based on the Charge Off-Peak script.
This script is independent from visualization script in order to run it on different computers
"""
import jlrpy
import threading
import datetim... | nilq/baby-python | python |
from time import sleep
from jumpscale import j
from .VirtualboxClient import VirtualboxClient
JSBASE = j.application.jsbase_get_class()
class VirtualboxFactory(JSBASE):
def __init__(self):
self.__jslocation__ = "j.clients.virtualbox"
JSBASE.__init__(self)
self.logger_enable()
s... | nilq/baby-python | python |
from PIL import ImageFont
class Letter:
""" letter class- each letter is one of these objects, and is rendered in order. """
def __init__(self,char,size,font,color = (255,255,255,255),b=False,i=False,u=False):
"""
char: character.
size: size of letter.
font: PIL truetype font obj... | nilq/baby-python | python |
#TODO: Add datadump | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from . import helpers
import os
import shutil
import json
import logging
import sys
import face_recognition
from ringFace.ringUtils import commons
def processUnencoded(imageDir):
"""
Processes any unencoded image in the new-images subdir of a person, and moves it into encoded-ima... | nilq/baby-python | python |
from os import path
import click
from glob import glob
from pathlib import Path
from app.newAnimeEpisodes import *
@click.command()
@click.option('--source', required=True, type=str, help='Enter absolute path of directory to move from')
@click.option('--destination', required=True, type=str, help='Enter absolute path ... | nilq/baby-python | python |
""" A test action set. """
# Enthought library imports.
from envisage.ui.action.api import Action, Group, Menu, ToolBar
from envisage.ui.workbench.api import WorkbenchActionSet
class TestActionSet(WorkbenchActionSet):
""" An action test useful for testing. """
#### 'ActionSet' interface ###################... | nilq/baby-python | python |
"""This module provide the builder for the zlib library."""
import logging
from nvp.components.build import BuildManager
from nvp.nvp_builder import NVPBuilder
logger = logging.getLogger(__name__)
def register_builder(bman: BuildManager):
"""Register the build function"""
bman.register_builder('zlib', Bui... | nilq/baby-python | python |
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def animale_array(xm,fname,lbls=None,cmap='gray',figsize=(7,7),fps=25,vmin=None,vmax=None):
'''
This function helps to make an animation from a (2+1+1)d array (xy+t+c)
'''
# from IPy... | nilq/baby-python | python |
import asyncio
import json
import logging
import random
import time
import uuid
import websockets
from common import Client, ClientReport, OffsetTransform, Position, Rotation
logging.basicConfig(level=logging.INFO)
TIME_BETWEEN_UPDATES = 0.0166
LOW_POSITION = -3.0
HIGH_POSITION = 3.0
LOW_ROTATION = 0.0
HIGH_ROTATION... | nilq/baby-python | python |
import logging
import os
from pathlib import Path
from flatpaksync.commands.command import command
from flatpaksync.configs.write import write as writeconfig
from flatpaksync.structs.app import app
from flatpaksync.structs.settings import settings
from flatpaksync.actions.app import app as appaction
from flatpaksync.... | nilq/baby-python | python |
"""generatedata
Function that collects the transmutation data and
prepares the transmutation matrix required for depletion or decay
calculations.
The following reactions are considered:
- Radiative capture
- Capture to ground state
- Capture to metastable
- n, 2n
- n, 3n
- Fission
- n, alp... | nilq/baby-python | python |
import pandas as pd
from sklearn.metrics import r2_score
from sklearn.svm import SVR
MAX_AGE = 71
MAX_PCLASS = 3
def process_df(df):
df = df[['pclass', 'survived', 'age', 'sex']]
df = df.dropna()
df['pclass'] = df['pclass'].map(lambda x: float(x[:-2]) / MAX_PCLASS) # drop sufix
df['age'] = df['age... | nilq/baby-python | python |
import datetime
import calendar
from posixpath import dirname
import os
import pytz
import lockfile
import pycountry
import geoip2.errors
from flask.ext.babel import lazy_gettext
from flask import url_for
from flask.helpers import find_package
import rfk
def now():
return pytz.utc.localize(datetime.datetime.... | nilq/baby-python | python |
from typing import List, Iterator, Dict
from pyot.conf.model import models
from pyot.core.functional import cache_indexes, lazy_property
from pyot.core.exceptions import NotFound
from pyot.utils.tft.cdragon import abs_url, join_set_data
from pyot.utils.lol.cdragon import sanitize
from .base import PyotCore, PyotStatic... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Authors: Olexa Bilaniuk
# Imports.
import sys; sys.path += [".", ".."]
import argparse as Ap
import logging as L
import numpy as np
import os, pdb, sys
import time
import tensorflow.c... | nilq/baby-python | python |
from django.db import models
from django_handleref.models import HandleRefModel
class Org(HandleRefModel):
name = models.CharField(max_length=255, unique=True)
website = models.URLField(blank=True)
notes = models.TextField(blank=True)
class HandleRef:
tag = 'org'
delete_cascade = ["s... | nilq/baby-python | python |
import os
import pickle
import yaml
import numpy as np
import pandas as pd
import pyprind
from stats.plot_utils import get_dn_rn_info, load_best_rl
from stats.thresholds import th
rng = np.random.RandomState(123)
ROOT_DIR = os.path.abspath(".")
RAW = False # True == num patients ; False == percentage
# Make plots d... | nilq/baby-python | python |
from setuptools import setup, find_packages
with open("requirements.txt") as f:
install_requires = f.read().strip().split("\n")
# get version from __version__ variable in erptn/__init__.py
from erptn import __version__ as version
setup(
name="erptn",
version=version,
description="adaption of erpnext in the tunis... | nilq/baby-python | python |
# Generated by Django 3.2.3 on 2021-08-12 05:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0004_auto_20210811_1941'),
]
operations = [
migrations.RenameField(
model_name='vehicle',
old_name='size',
... | nilq/baby-python | python |
num = int(input('Insira um número: '))
if num % 3 == 0:
print(f'O número {num} é divisível por 3.')
else:
print(f'O número {num} não é divisível por 3.')
if num % 7 == 0:
print(f'O número {num} é divisível por 7.')
else:
print(f'O número {num} não é divisível por 7.')
| nilq/baby-python | python |
from flask import Flask, render_template, url_for
from forms import RegistrationForm, LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = '23630345ae74e203656e76a7cab735a7'
posts = [
{
'author': 'Name',
'title': 'Blog post 1',
'content': 'First blog post',
'date_posted': 'A... | nilq/baby-python | python |
import time
import fitlog
def random_tmp_name():
#random is useless for seed has been fixed
a = (time.time() * 1000) % 19260817
return "tmp_%d.txt" % a
| nilq/baby-python | python |
import numpy as np
import myrand
import scipy.stats
import sys
import random
import pytest
class TestRandoms( ):
@classmethod
@pytest.fixture(scope="class")
def setUpClass(cls):
print("Doing setUpClass")
cls.numVals = 10000
#print(vars(self))
#print(self)
@pytest.fixtu... | nilq/baby-python | python |
"""Proxy objects for sending commands to transports"""
import logging
# We need to offset the pin numbers to CR and LF which are control characters to us
# NOTE: this *must* be same as in ardubus.h
# TODO: Use hex encoded values everywhere to avoid this
IDX_OFFSET = 32
LOGGER = logging.getLogger(__name__)
def idx2by... | nilq/baby-python | python |
import numpy as np
import itertools as itr
import os as os
import sys as sys
import matplotlib.pyplot as plt
class GridTopology:
r"""
Control the layout/connectivity of the lattice the models are based on.
This can be used as a parent class for other topologies.
Here sites are assigned unique indice... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
from mcfly.models import DeepConvLSTM
from test_modelgen import get_default
class DeepConvLSTMSuite(unittest.TestCase):
"""
Tests cases for DeepconvLSTM models.
"""
def test_deepconvlstm_batchnorm_dim(self):
"""The output shape of the batchnorm should be... | nilq/baby-python | python |
from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cosine
import scipy.optimize as opt
__all__ = ['CPTC... | nilq/baby-python | python |
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from imephu.annotation.general import CircleAnnotation, RectangleAnnotation
from imephu.finder_chart import FinderChart
def test_rectangle_annotation(fits_file, check_finder):
"""Test rectangle annotations."""
finder_chart ... | nilq/baby-python | python |
#!/usr/bin/env python
# This file should be available from
# http://www.pobox.com/~asl2/software/Pinefs
# and is licensed under the X Consortium license:
# Copyright (c) 2003, Aaron S. Lav, asl2@pobox.com
# All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this ... | nilq/baby-python | python |
#!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from std_msgs.msg import Float64MultiArray, UInt8
from std_srvs.srv import Trigger, TriggerResponse
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from scipy import optimize
import time
class linear_controller(object):
... | nilq/baby-python | python |
#!/bin/python
import datetime
YAHOO_ENDPOINT = 'https://fantasysports.yahooapis.com/fantasy/v2'
class YHandler:
"""Class that constructs the APIs to send to Yahoo"""
def __init__(self, sc):
self.sc = sc
def __getattribute__(self, attr):
cred = super(YHandler, self).__getattribute__(att... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import time
import math
import atexit
import numpy as np
import threading
import random
import cereal.messaging as messaging
import argparse
from common.params import Params
from common.realtime import Ratekeeper
import queue
import requests
import cereal.messaging.messaging_pyx as mess... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('... | nilq/baby-python | python |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Licensed to Anthony Shaw (anthonyshaw@apache.org) 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 "Li... | nilq/baby-python | python |
from datetime import datetime
from caselawclient.Client import api_client
from requests_toolbelt.multipart import decoder
from .models import SearchResults
def format_date(date):
if date == "" or date is None:
return None
time = datetime.strptime(date, "%Y-%m-%d")
return time.strftime("%d-%m-%Y... | nilq/baby-python | python |
""" https://adventofcode.com/2018/day/6 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
lines = [line[:-1].split(", ") for line in f.readlines()]
return [Point(int(line[0]), int(line[1])) for line in lines]
class Point:
n = 0
def __init__(self, x, y):
... | nilq/baby-python | python |
import os
from helpers import dist_init, getData, getLossFun, getModel
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.optim as optim
import fairscale
from fairscale.nn.model_parallel import initialize_model_parallel
DEVICE = "cuda" if torch.cuda.is_available() else "cpu... | nilq/baby-python | python |
###############################################################################
# Copyright (c) 2021, Milan Neubert (milan.neuber@gmail.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. ... | nilq/baby-python | python |
from typing import Optional
from datetime import datetime
BETFAIR_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
# will attempt to use C/Rust libraries if installed
try:
import orjson as json
except ImportError:
import json
try:
imp... | nilq/baby-python | python |
from random import random
from matplotlib import pyplot as plt
import numpy as np
def discrete(a):
t = sum(a)*random()
subtotal = 0.0
for j in range(len(a)):
subtotal += a[j]
if subtotal > t:
return j
def tabler():
n, *m = map(int, input().split(' '))
... | nilq/baby-python | python |
import pygame as pg
import sys
import time
from pygame.locals import *
# Setting up few properties
XO = 'x'
winner = None
draw = None
width = 500
height = 450
white = (255, 255, 255)
line_color = (130, 0, 0)
board = [[None]*3, [None]*3, [None]*3]
pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.s... | nilq/baby-python | python |
import os
from datetime import timedelta
DEBUG = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
PROPAGATE_EXCEPTIONS = True
JWT_BLACK_LIST_ENABLED = True
UPLOADED_IMAGES_DEST = os.path.join("static", "images")
JWT_BLACK_LIST_TOKEN_CHECKS = ["access", "refresh"]
JWT_SECRET_KEY = os.environ["JWT_SECRET_KEY"]
JWT_ACCESS_TOK... | nilq/baby-python | python |
import os
from tqdm import tqdm
import subprocess
def alphafold(path):
# run alphafold
print("Running for path {}...".format(path))
subprocess.run(['bash', '/opt/alphafold/run.sh', '-d /lambda_stor/data/hsyoo/AlphaFoldData',
'-o ~/mutate_msa/folding_results/',
'-f {... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
import random
from pygorithm.data_structures import (
stack,
queue,
linked_list,
tree,
graph,
heap,
trie,
quadtree,
)
from pygorithm.geometry import vector2, rect2
class TestStack(unittest.TestCase):
def test_stack(self):
myStack = ... | nilq/baby-python | python |
# coding: utf-8
# # Projects markdown generator for academicpages
#
# Takes a TSV of projects with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook, with the core python code in projects.py. Run either from the `markdown_generator` fo... | nilq/baby-python | python |
from six.moves.urllib.parse import urljoin
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.ex... | nilq/baby-python | python |
import click
from django.conf import settings
from django.contrib.sites.models import Site
def setup_current_site(site_name=None, domain=None):
'''
Sets up the user with the current site.
'''
site_id = settings.SITE_ID
click.secho('\nA site has not been configured for this CMS. Please answer the q... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/12 17:00
# @Author : Iydon
# @File : matlab.py
# `matlab -nodesktop' -> `from matlab import *'
# tic, toc, disp
import time
def tic(): globals()['TIC+TIME'] = time.time()
toc = lambda :time.time()-globals()['TIC+TIME']
disp = print
tic()
# numpy
i... | nilq/baby-python | python |
import base64
import numpy as np
import os
import pathlib
import re
import shutil
from urllib.request import urlopen
raw = urlopen("https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Algorithm.QCAlgorithm").read().decode("utf-8") \
.replace("true", "True") \
.replace("false", "False") \
.r... | nilq/baby-python | python |
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
import pandas as pd
import numpy as np
import math
import os
from scipy.cluster.hierarchy import dendrogram
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap
from matp... | nilq/baby-python | python |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#data_file='file.csv' # path for the file
data=np.genfromtxt(path, delimiter=",", skip_header=1)
#print("\nData: \n\n", data)
#print("\nType of data: \n\n", type(data))
#New record
new... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pandas as pd
import requests
from zvdata.api import df_to_db
from zvdata.recorder import Recorder
from zvt.api.common import china_stock_code_to_id
from zvt.api.quote import get_entities
from zvt.domain import StockIndex, StockCategory
from zvt.domain.stock_meta import Index
from zvdata.... | nilq/baby-python | python |
import json
import re
import string
try: # ST3
from .elm_plugin import *
from .elm_project import ElmProject
except: # ST2
from elm_plugin import *
from elm_project import ElmProject
default_exec = import_module('Default.exec')
@replace_base_class('Highlight Build Errors.HighlightBuildErrors.Exec... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
def get_steps_colors(values):
values = 1 / values
_range = np.max(values) - np.min(values)
_values = (values - np.min(values)) / _range
colors_data = plt.cm.Wistia(_values)
return colors_data
def paint_table(df, title_cols, title_text, result_pa... | nilq/baby-python | python |
import binascii
import logging
from lbrynet.core.cryptoutils import get_lbry_hash_obj, verify_signature
from twisted.internet import defer, threads
from lbrynet.core.Error import DuplicateStreamHashError, InvalidStreamDescriptorError
from lbrynet.lbrylive.LiveBlob import LiveBlobInfo
from lbrynet.interfaces import IStr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JdZhilianItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
companyname = scrapy.Field()
jobl... | nilq/baby-python | python |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from django_plotly_dash import DjangoDash
import dash_table
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import plotly.express as px
import random
import json
... | nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Lien(pulumi.CustomResource):
def __init__(__self__, __n... | nilq/baby-python | python |
from glob import glob
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def main():
file = "./cpp/tests/bin/Distribution_bucket_0_15_08_2021.dat"
df = pd.read_csv(
file, delim_whitespace=True, header=None, names=["id", "x", "px", "y", "py", "t", "delta"]
)
df["turn"]... | nilq/baby-python | python |
dividendo=int(input("Dividendo es: "))
divisor=int(input("Divisor es: "))
if dividendo>0 and divisor>0:
coc=0
residuo=dividendo
while (residuo>=divisor):
residuo-=divisor
coc+=1
print(residuo)
print(coc) | nilq/baby-python | python |
from __future__ import unicode_literals
from sideboard.lib import mainloop
if __name__ == '__main__':
mainloop()
| nilq/baby-python | python |
import json
from helper import OuraModel, from_json
class UserInfo(OuraModel):
_KEYS = ['age', 'weight', 'gender', 'email']
if __name__ == '__main__':
test = """
{
"age": 27,
"weight": 80,
"email": "john.doe@the.domain",
"surprise" : "wow this is new"
}"""
u = from_json(test, UserInfo)
... | nilq/baby-python | python |
# Date: 05/10/2018
# Author: Pure-L0G1C
# Description: Wrapper for gimme object
from .gimme import Gimme
class Wrapper(object):
def __init__(self, kwargs):
self.gimme = Gimme(kwargs)
@property
def start(self):
self.gimme.start()
@property
def stop(self):
self.gimme.stop()
@property
def get(self):
... | nilq/baby-python | python |
def implode(lst):
s = ""
for e in lst:
s = s+e
return s
print(implode(['h', 'e', 'l', 'l', 'o']))
| nilq/baby-python | python |
# Generated by Django 3.2.3 on 2021-05-21 21:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cities', '0002_phone'),
]
operations = [
migrations.RenameField(
model_name='phone',
old_name='phone_model',
new... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
import warnings
import shutil
import json
import tests.test_helpers as th
import submission_validator
class TestSubmissionValidatorValidateDetections(th.ExtendedTestCase):
def test_errors_for_missing_label_probs(s... | nilq/baby-python | python |
import requests
use_paragraphs = True
def main():
url = "http://0.0.0.0:8100/model"
if use_paragraphs:
request_data = [
{
"human_sentences": ["Who played Sheldon Cooper in The Big Bang Theory?"],
"dialog_history": ["Who played Sheldon Cooper in The Big Bang... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import platform
from subprocess import run
def is_macos():
"""
:return: True if system is MacOS, False otherwise
"""
return platform.system() == 'Darwin'
def is_windows():
"""
:return: True if system is Windows, False otherwise
... | nilq/baby-python | python |
from django.db import models
# Create your models here.
class SigninModel(models.Model):
username = models.CharField(max_length=10)
password = models.CharField(max_length=50)
class BookTicketModel(models.Model):
post = models.CharField(max_length=10)
class AdjustTicketModel(models.Model):
post = mode... | nilq/baby-python | python |
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, GMapOptions
from bokeh.plotting import gmap
output_file("gmap.html")
map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11)
# For GMaps to function, Google requires you obtain and enable an API key:
#
# h... | nilq/baby-python | python |
"""
Common utility functions for NPP/SNPP
"""
import os
import numpy as np
from pathlib import Path
# Country enumerations
EN = "en"
WA = "wa"
SC = "sc"
NI = "ni"
# Aggregations
EW = [EN, WA]
GB = [EN, WA, SC]
UK = [EN, WA, SC, NI]
# ONS country codes
CODES = {
EN: "E92000001",
WA: "W92000004",
SC: "S92... | nilq/baby-python | python |
from __future__ import print_function
from utensor_cgen.ir import uTensorGraph
from utensor_cgen.ir.utils import graph_check
from utensor_cgen.transformer import CMSIS_NN_Transformer
def test_cmsisnn_trnasformer(fusion_graph_tuple):
(ugraph, ugraph1) = fusion_graph_tuple
transformer = CMSIS_NN_Transformer()
... | nilq/baby-python | python |
import requests
import json
import execjs # 必须,需要先用pip 安装,用来执行js脚本
from urllib.parse import quote
# 用来判断是否需要打印日志
debug = True
class Py4Js:
def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 ... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pylab as plt
import random
from celluloid import Camera
class Energy(nn.Module):
def __init__(self):
super(Energy, self).__init__()
self.sigma = nn.Parameter(torch.tensor([0.5]))
self.mu = nn.Parameter(torch.tens... | nilq/baby-python | python |
import scrapy
from celery import Celery
from scrapy.settings import Settings
from scrapy.spiders import Spider
from scrapyscript import Job, Processor, ScrapyScriptException
from spiders import ItemSpider, TitleSpider
app = Celery("hello", broker="amqp://guest@localhost//")
@app.task
def celery_job(url):
job = ... | nilq/baby-python | python |
from copy import copy
from Cat.utils.collections_ import ChainedList
from model.commands.argumentTypes import *
from model.commands.command import CommandSchema, KeywordSchema, ArgumentSchema, TERMINAL, COMMANDS_ROOT, SwitchSchema
from model.data.mcVersions import MCVersion
def fillCommandsFor1_17(version: MCVersion... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Port of the official ttgo library for the LilyGo TTGO T-Watch 2020.
# Author: Nikita Selin (Anodev)[https://github.com/OPHoperHPO]
import gc
import _thread
import axp202
import lvgl as lv
import st7789_lvgl
import ft6x36
from bma42x import BMA42X
from pcf8563 import PCF8563
from machine import... | nilq/baby-python | python |
# https://leetcode.com/problems/longest-common-prefix/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ''
# since list of string will be sorted and retrieved min max by alphebetic order
s1, s2 = min(strs), max(strs)
for i, c in... | nilq/baby-python | python |
from django.apps import AppConfig
class S3FileConfig(AppConfig):
name = 'apps.s3file'
| nilq/baby-python | python |
"""
test_django-oci api
-------------------
Tests for `django-oci` api.
"""
from django.urls import reverse
from django.contrib.auth.models import User
from django_oci import settings
from rest_framework import status
from rest_framework.test import APITestCase
from django.test.utils import override_settings
from tim... | nilq/baby-python | python |
from _todefrost import package_md5sum
md5 = None
try:
with open('/flash/package.md5') as f:
md5 = f.read().strip()
except Exception as e:
pass
if md5 != package_md5sum.md5sum:
print("package md5 changed....defrosting...")
from _todefrost import microwave
microwave.defrost()
import mach... | nilq/baby-python | python |
#!/usr/bin/env python
import pytest
from clichain import cli, pipeline
import click
from click.testing import CliRunner
import sys
import ast
import logging
from difflib import SequenceMatcher
def test_main_help():
tasks = cli.Tasks()
args = ['--help']
result = cli.test(tasks, args)
print('>> test_ma... | nilq/baby-python | python |
compiler = 'C:\\Users\\Public\\Documents\\Mikroelektronika\\mikroC PRO for PIC\\mikroCPIC1618.exe'
settings = {
'cmdln0': '"{compiler}" -MSF -DBG -p{device} -GC -DL -O11111110 -fo{clock} -N"{project}" "{filename}"',
'cmdlnSP': '-SP"{path}"',
'cmdlnIP': '-IP"{path}"',
'cmdlnLIBS': '"__Lib_Math.mcl" "__L... | nilq/baby-python | python |
from rest_framework import serializers
from .models import Post, Category
class BlogCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = [
'name',
'created_at',
'updated_at',
]
class BlogPostSerializer(serializers.Mode... | nilq/baby-python | python |
from dictpy.dict_search import DictSearch
from dictpy.serializer import Serializer
__all__ = ["DictSearch", "Serializer"]
| nilq/baby-python | python |
import pandas as pd
class TrainDataSampler:
def name(self):
raise NotImplementedError
def sample(self, df):
raise NotImplementedError
class CompleteData(TrainDataSampler):
def name(self):
return 'complete_data'
def sample(self, df):
return df
class BalancedExampl... | nilq/baby-python | python |
from unbillit_project import app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, debug=True)
############## set envirnment variable for secret key #############
# Add password strength validators later to user/form.py
# work on putting everything together
# implement password reset functiona... | nilq/baby-python | python |
import psycopg2
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
from numpy import random
from sklearn.preprocessing import StandardScaler
import os
os.chdir('/home/rafalb/work/molecules/chemicalSmilesSpace/src')
from keras.layers import LSTM, TimeDistributed, concatenate, Input, ... | nilq/baby-python | python |
from django.db import models
class Contact(models.Model):
first_name = models.CharField(null=False, blank=False, max_length=50)
last_name = models.CharField(null=False, blank=False, max_length=50)
email = models.CharField(null=False, blank=False, max_length=50)
ip = models.CharField(null=False, blank=... | nilq/baby-python | python |
"""
Provides animated GIF images of weather-radar imagery derived the Australian
Bureau of Meteorology (http://www.bom.gov.au/australia/radar/).
"""
import datetime as dt
import io
import logging
import os
import re
import time
import PIL.Image
import requests
# Legend:
#
# NSW: http://www.bom.gov.au/australia/radar... | nilq/baby-python | python |
from AttachmentFetcherGUI import runGUI
runGUI()
| nilq/baby-python | python |
from typing import Tuple
import numpy as np
import tensorflow as tf
from absl import logging
from xain.datasets import prep
from xain.types import KerasHistory, KerasWeights, Metrics, VolumeByClass
from . import ModelProvider
class Participant:
# pylint: disable-msg=too-many-arguments
# pylint: disable=too... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import heapq
# Generates gawk code. Run this manually and update hinter.awk if you don't like current alphabet or want to increase number of hints.
#
# This script builds prefix code for given number of hints using n-aray Huffman Coding.
# We precompute hints for hinter.awk to make it... | nilq/baby-python | python |
#!/usr/bin/python2.7
# -*- coding=utf-8 -*-
##################################################################
# WaterLevelTree Test
# Goal: Test script for WaterLevelTree algorithm
# Author: wenchieh
#
# Project: eaglemine
# waterleveltree.py
# Version:
# Date: November 29 2017
# Main Contact... | nilq/baby-python | python |
from restaurant import Restaurant
rest1 = Restaurant('Alitas y Costillas', 'BBQ')
print(rest1.describe_restaurant())
print(rest1.open_restaurant())
from user import Admin
admin1 = Admin('Antonio', 'Perez', '25', 'Monterrey, Nuevo Leon')
admin1.privileges = ['Edit', 'Delete', 'Ban']
print(admin1.describe_User())
admin... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.