content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
from setuptools import setup, find_packages
from Cython.Build import cythonize
import pysam
setup(
name='svtk',
version='0.1',
description='Structural variation toolkit',
author='Matthew Stone',
author_email='mstone5@mgh.harvard.edu',
p... | nilq/baby-python | python |
from colour import Color
from utils.animation_maker import *
import numpy as np
from time import time
song = 1
in_file = f'./Songs/Song0{song}.wav'
c1, c2 = Color('#fceaa8'), Color('#00e5ff')
#c1, c2 = Color('#000000'), Color('#00fffb')
c3, c4 = Color('#000000'), Color('#000000')
gradient_mode = 'hsl'
n_points = 100
a... | nilq/baby-python | python |
import argparse
import asyncio
import rlp
from typing import Any, cast, Dict
from quarkchain.p2p import auth
from quarkchain.p2p import ecies
from quarkchain.p2p.exceptions import (
HandshakeFailure,
HandshakeDisconnectedFailure,
UnreachablePeer,
MalformedMessage,
)
from quarkchain.p2p.kademlia import ... | nilq/baby-python | python |
"""redux_field_creator URL Configuration"""
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^fields/', include('fields.urls')),
]
| nilq/baby-python | python |
# echo_04_io_multiplexing.py
import socket
import selectors
sel = selectors.DefaultSelector()
def setup_listening_socket(host='127.0.0.1', port=55555):
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen()
sel.register(sock, sele... | nilq/baby-python | python |
import json
import sys
import getopt
from os import system
sys.path.insert(0, '/requests')
import requests
def getBridgeIP():
r = requests.get('http://www.meethue.com/api/nupnp')
bridges = r.json()
if not bridges:
bridge_ip = 0
else:
bridge_ip = bridges[0]['internalipaddress']
r... | nilq/baby-python | python |
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_skylib//lib:structs.bzl", "structs")
load("//ocaml/_functions:utils.bzl", "capitalize_initial_char")
load("//ocaml/_functions:module_naming.bzl",
"normalize_module_label",
"normalize_module_name")
load("//ocaml/_rules:impl_common.bzl", "module_sep")... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
#
# Copyright (c) [2020] Huawei Technologies Co.,Ltd.All rights reserved.
#
# OpenArkCompiler is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://licens... | nilq/baby-python | python |
from os import listdir
from os.path import isfile, join
import pandas as pd
import pickle
def get_latest_file(filename_str_contains, datapath='../data/', filetype='parquet'):
"""
Method to get the latest file to given a certain string value.
Parameters
----------
filename_str_contains :... | nilq/baby-python | python |
class SymbolTableError(Exception):
"""Exception raised for errors with the symbol table.
Attributes:
message -- explanation of the error
"""
def __init__(self, message):
self.message = message | nilq/baby-python | python |
# Created by woochanghwang at 12/07/2021
import toolbox.drugbank_handler_postgres as drug_pg
import pandas as pd
def get_DDI_of_a_drug(drug):
# drug_a = row['DrugA_ID']
# drug_b = row['DrugB_ID']
sql = "SELECT * from structured_drug_interactions where subject_drug_drugbank_id = \'{}\' " \
"or ... | nilq/baby-python | python |
import unittest
from machinetranslation import translator
from translator import englishToFrench
from translator import frenchToEnglish
class TestTranslator(unittest.TestCase):
# test function
def test_englishToFrench(self):
self.assertIsNotNone(englishToFrench('Hello'),'Bonjour')
self.assertE... | nilq/baby-python | python |
import tkinter as tk
import tkinter.ttk as ttk
from ..elements import TreeList
from ...head.database import Database as db
from ...globals import SURVEY_TYPES
from .templates import ListFrameTemplate
class SurveysListFrame(ListFrameTemplate):
def __init__(self, top):
super().__init__(top)
self.dat... | nilq/baby-python | python |
import unittest
import os
import plexcleaner.database as database
from plexcleaner.media import Library, Movie
__author__ = 'Jean-Bernard Ratte - jean.bernard.ratte@unary.ca'
# flake8: noqa
class TestMediaLibrary(unittest.TestCase):
_nb_movie = 98
_effective_size = 100275991932
def test_init(self):
... | nilq/baby-python | python |
#coding=utf-8
import os
import jieba
import shutil
dirs = []
for d in os.listdir(os.getcwd()):
if os.path.isfile(d):
continue
dirs.append(d)
imgs = []
with open("data.txt",'w') as fw , open("imgs.txt","w") as fi:
for d in dirs:
for f in os.listdir(os.path.join(d)):
... | nilq/baby-python | python |
from urllib.parse import parse_qsl
from establishment.socialaccount.providers.base import Provider
class OAuth2Provider(Provider):
def get_auth_params(self, request, action):
settings = self.get_settings()
ret = settings.get("AUTH_PARAMS", {})
dynamic_auth_params = request.GET.get("auth_p... | nilq/baby-python | python |
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
from acapy_wrapper.models.credential_offer import Credentia... | nilq/baby-python | python |
from pyilluminate import Illuminate
import numpy as np
import pytest
pytestmark = pytest.mark.device
@pytest.fixture(scope='module')
def light():
with Illuminate() as light:
yield light
def test_single_led_command(light):
light.color = 1
# setting led with an integer
light.led = 30
def te... | nilq/baby-python | python |
"""Tests for deletion of assemblies."""
import os
import unittest
from hicognition.test_helpers import LoginTestCase, TempDirTestCase
# add path to import app
# import sys
# sys.path.append("./")
from app import db
from app.models import (
Dataset,
Assembly,
)
class TestDeleteAssembly(LoginTestCase, TempDirT... | nilq/baby-python | python |
import ccxt
def build_exchange(name):
exchange = getattr(ccxt, name)
return exchange({
'enableRateLimit': True
})
def timestamps_to_seconds(data):
for datum in data:
datum[0] = datum[0] // 1000
def secs_to_millis(datum):
return datum * 1000
| nilq/baby-python | python |
# TODO: add more filetypes
paste_file_types = [
["All supprted files", ""],
("All files", "*"),
("Plain text", "*.txt"),
("Bash script", "*.sh"),
("Batch script", "*.bat"),
("C file", "*.c"),
("C++ file", "*.cpp"),
("Python file", "*.py"),
("R script file", "*.R")
]
for _, extension ... | nilq/baby-python | python |
'Faça um script de menu que mostra na tela, com o título de "Menu Principal" e mais três opções:'
# 1. FIM
# 2. CADASTRO
# 3. CONSULTA
"O programa recebe um input do teclado a opção desejada e mostra uma mensagem confirmando a opção escolhida."
# Caso a opção escolhida seja inválida, mostrar uma mensagem de erro "Opç... | nilq/baby-python | python |
from django.http import HttpResponse, JsonResponse, Http404
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from tasks.models import Task
from tasks.... | nilq/baby-python | python |
from math import sqrt
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils import data as data
from torchvision import transforms as transforms
from data.datasets import MNIST_truncated, FEMNIST, FashionMNIST_truncated, SVHN_custom, CIFAR10_truncated, Generated
... | nilq/baby-python | python |
class Solution(object):
def maxDistance(self, nums):
"""
:type arrays: List[List[int]]
:rtype: int
"""
low = float('inf')
high = float('-inf')
res = 0
for num in nums:
# We can use num[0] && num[-1] only because these lists are sorted
... | nilq/baby-python | python |
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
app_name = 'mailviews'
urlpatterns = [
url(regex=r'', view=site.urls)
]
| nilq/baby-python | python |
# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml.
from flask import jsonify, request
from ..models import FarmerRegistration, FarmerNotFoundError
def GetFarmerHandler(iyo_organization):
try:
farmer = FarmerRegistration.get(iyo_organization)
except FarmerNotFoundError:
... | nilq/baby-python | python |
import web
from web import form
import socket
import sensor
from threading import Thread
localhost = "http://" + socket.gethostbyname(socket.gethostname()) + ":8080"
print(localhost)
urls = (
'/','Login',
'/control','Page_one',
'/left', 'Left',
'/right', 'Right',
'/... | nilq/baby-python | python |
import os
import sys
command = " ".join(sys.argv[1:])
os.system(command)
| nilq/baby-python | python |
from __future__ import unicode_literals, print_function
from pprint import pprint
import xmltodict
with open("show_security_zones.xml") as infile:
show_security_zones = xmltodict.parse(infile.read())
print("\n\n")
print("Print the new variable and its type")
print("-" * 20)
pprint(show_security_zones)
print(typ... | nilq/baby-python | python |
# https://www.urionlinejudge.com.br/judge/en/problems/view/1012
entrada = input().split()
a = float(entrada[0])
b = float(entrada[1])
c = float(entrada[2])
print(f"TRIANGULO: {a*c/2:.3f}")
print(f"CIRCULO: {3.14159*c**2:.3f}")
print(f"TRAPEZIO: {(a+b)*c/2:.3f}")
print(f"QUADRADO: {b**2:.3f}")
print(f"RETANGU... | nilq/baby-python | python |
import torch
tau = 6.28318530718
class FractalPerlin2D(object):
def __init__(self, shape, resolutions, factors, generator=torch.random.default_generator):
shape = shape if len(shape)==3 else (None,)+shape
self.shape = shape
self.factors = factors
self.generator = generator
s... | nilq/baby-python | python |
import json
from unittest.mock import Mock
import graphene
from django.conf import settings
from django.shortcuts import reverse
from django_countries import countries
from django_prices_vatlayer.models import VAT
from tests.utils import get_graphql_content
from saleor.core.permissions import MODELS_PERMISSIONS
from ... | nilq/baby-python | python |
# Copyright 2019 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 agreed to... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
# scripts/manifest/lib/verify_input.py
# (c) 2020 Sam Caldwell. See LICENSE.txt.
#
# input verification functions.
#
"""
from .hasher import SUPPORTED_HASH_ALGORITHMS
def url_string(s: str) -> bool:
"""
Verify the given string (s) is a URL.
:param s: string
:r... | nilq/baby-python | python |
from flask import Flask, request, jsonify
import customs.orchestrator as orch
import customs.validator as valid
app = Flask(__name__)
@app.route('/customs', methods=['POST'])
def customs():
content = request.get_json(silent=True) # exception?
check = valid.is_json_correct(content)
if check is True:
... | nilq/baby-python | python |
a = float(input("Zadej velikost polomeru kruhu v cm: "))
obsah = a*a*3.14
obvod = 2*3.14*a
print("Obsah je", "", obsah, "cm")
print("Obvod je", "", obvod, "cm") | nilq/baby-python | python |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.0
# kernelspec:
# display_name: Python [conda env:PROJ_irox_oer] *
# language: python
# name: conda-env-PROJ... | nilq/baby-python | python |
#import random package
import random
#get random number between 1 and 10
#print(random.randint(0, 1))
choice = random.randint(0,3)
if choice == 0:
print("Tails")
elif choice == 1:
print("Heads")
else:
print("Your quarter fell in the gutter.")
#get random number between 1 and 100
# print(random.randint(0,... | nilq/baby-python | python |
# Copyright (c) 2018, Neil Booth
#
# All rights reserved.
#
# The MIT License (MIT)
#
# 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
# without limitation the r... | nilq/baby-python | python |
from mopidy import backend
class KitchenPlaybackProvider(backend.PlaybackProvider):
def translate_uri(self, uri):
return self.backend.library.get_playback_uri(uri)
| nilq/baby-python | python |
url = "https://lenta.ru/parts/news/"
user_agent = "text"
| nilq/baby-python | python |
#Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
#For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
#Bonus: Can you do this in one pass?
def k_sum_in_list(k, list):
needed = {}
for n in list:
if needed.get(n, False):
... | nilq/baby-python | python |
"""Test suits for Anytown Mapper."""
import math
import os
import unittest
import sqlite3
import tempfile
from main import app
from main import get_db
from main import init_db
from anytownlib.kavrayskiy import coords_to_kavrayskiy
from anytownlib.kavrayskiy import make_global_level_image
from anytownlib.map_cache im... | nilq/baby-python | python |
# flake8: noqa
# Import all APIs into this package.
# If you have many APIs here with many many models used in each API this may
# raise a `RecursionError`.
# In order to avoid this, import only the API that you directly need like:
#
# from .api.chamber_schedule_api import ChamberScheduleApi
#
# or import this pack... | nilq/baby-python | python |
from flask import Flask,render_template,request,redirect,url_for
import os, git
def styleSheet():
stylesheet = "/static/styles/light_theme.css"
if request.cookies.get('darktheme') == 'True':
stylesheet = "/static/styles/dark_theme.css"
return stylesheet
def create_app(test_config=None):
# cre... | nilq/baby-python | python |
#!/usr/bin/env python
try:
from scapy.all import *
#from scapy.layers.dot11 import Dot11, Dot11Elt, Dot11Auth, Dot11Beacon, Dot11ProbeReq, Dot11ProbeResp, RadioTap
from gui.tabulate_scan_results import Gui
from multiprocessing import Process
import time, threading, random, Queue
import signal, os
import scapy_e... | nilq/baby-python | python |
from pyibex import Interval, tan, bwd_imod, atan
import math
def Cmod(x,y):
xx = Interval(x)
yy = Interval(y)
bwd_imod(xx,yy,2*math.pi)
return yy
def Catan2(x,y,th):
iZeroPi2 = Interval(0)| Interval.PI/2.
iPi2Pi = Interval.PI/2. | Interval.PI
if x.is_empty() or y.is_empty() or th.is_empty():
return... | nilq/baby-python | python |
#!/usr/bin/env python
import maccleanmessages
import sys
from setuptools import setup
requires=[]
if sys.version_info[:2] == (2, 6):
requires.append('argparse>=1.1')
setup(
name='maccleanmessages',
version=maccleanmessages.__version__,
description='Remove macOS Messages app history (chats / texts ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from pyparsing import lineno, col
"""
Base classes for implementing decoder parsers.
A decoder parser receives a data structure and returns an instance of a class
from the domain model.
For example, it may receive a JSON and return a CWRFile instance.
... | nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2020 Adam Dodd
#
# 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 without limitation the rights
# to use, copy, modify, merge, pu... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import logging
def categorical_accuracy(preds, y):
"""Return accuracy given a batch of label distributions and true labels"""
max_preds = preds.argmax(dim=1, keepdim=True)
correct = max_preds.squeeze(1).eq(y)
return correct.sum().floa... | nilq/baby-python | python |
from pathlib import Path
import pandas as pd
DATA_DIR = Path('data')
DIR = DATA_DIR / 'raw' / 'jigsaw-unintended-bias-in-toxicity-classification'
def load_original_dataset():
df = pd.read_csv(DIR / 'train.csv', index_col=0)
df['label'] = (df.target >= 0.5)
df = df[['comment_text', 'label']]
df.column... | nilq/baby-python | python |
import yunionclient
from yunionclient.common import utils
import json
@utils.arg('--limit', metavar='<NUMBER>', default=20, help='Page limit')
@utils.arg('--offset', metavar='<OFFSET>', help='Page offset')
@utils.arg('--order-by', metavar='<ORDER_BY>', help='Name of fields order by')
@utils.arg('--order', metavar='... | nilq/baby-python | python |
inter = dict.fromkeys([x for x in a if x in b])
| nilq/baby-python | python |
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
s= n1 + n2
m = n1 * n2
d = n1 / n2
di = n1 // n2
e = n1 ** n2
print(f'A soma é: {s}, o produto é: {m}, a divisão é: {d:.3f},', end=' ')
print(f'a divisão inteira é: {di} e a potência é: {e}') | nilq/baby-python | python |
"""
Utility functions
=======================
"""
import time
from . import RUNNING_ON_PI
if RUNNING_ON_PI: # pragma: no cover
import RPi.GPIO as GPIO
def digital_write(pin, value): # pragma: no cover
GPIO.output(pin, value)
def digital_read(pin): # pragma: no cover
return GPIO.input(pin)
def del... | nilq/baby-python | python |
from unittest.mock import patch
from django.test import TestCase
from vimage.core.base import VimageKey, VimageValue, VimageEntry
from .const import dotted_path
class VimageEntryTestCase(TestCase):
def test_entry(self):
ve = VimageEntry('app', {})
self.assertIsInstance(ve.key, VimageKey)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Utilities related to reading and generating indexable search content."""
from __future__ import absolute_import
import os
import fnmatch
import re
import codecs
import logging
import json
from builtins import next, range
from pyquery import PyQuery
log = logging.getLogger(__name__)
def... | nilq/baby-python | python |
from django.test import TestCase
from wagtailimportexport import functions
class TestNullPKs(TestCase):
"""
Test cases for null_pks method in functions.py
"""
def test_null(self):
pass
class TestNullFKs(TestCase):
"""
Test cases for null_fks method in functions.py
"""
def tes... | nilq/baby-python | python |
from django import forms
from django.contrib.contenttypes.forms import generic_inlineformset_factory
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.test import TestCase
from django.test.utils import isolate_apps
from .models import (
Animal, ForProxyMode... | nilq/baby-python | python |
from django.db import models
class Core(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(max_length=100)
back_story = models.TextField()
height = models.CharField(max_length=50)
weight = models.FloatField()
strength = models.IntegerField()
wisdom = model... | nilq/baby-python | python |
# high-level interface for interacting with Brick graphs using rdflib
# setup our query environment
from rdflib import RDFS, RDF, Namespace, Graph, URIRef
class BrickGraph(object):
def __init__(self, filename='metadata/sample_building.ttl'):
self.bldg = Graph()
self.bldg = Graph()
self.bldg... | nilq/baby-python | python |
#!/usr/local/bin/python3
from random import randint
def sortea_numero():
return randint(1, 6)
def eh_impar(numero: float):
return numero % 2 != 0
def acertou(numero_sorteado: float, numero: float):
return numero_sorteado == numero
if __name__ == '__main__':
numero_sorteado = sortea_numero()
... | nilq/baby-python | python |
import pytest
from datetime import datetime, timedelta
import xarray as xr
import cftime
import numpy as np
import vcm
from vcm.cubedsphere.constants import TIME_FMT
from vcm.convenience import (
cast_to_datetime,
parse_current_date_from_str,
parse_timestep_str_from_path,
round_time,
parse_datetime... | nilq/baby-python | python |
# This code is based off the DUET algorithm presented in:
# O. Yilmaz and S. Rickard, "Blind separation of speech mixtures via time-frequency masking."
# S. Rickard, "The DUET Blind Source Separation Algorithm"
#
# At this time, the algorithm is not working when returning to the time domain
# and, to be honest, I haven... | nilq/baby-python | python |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2016 the HERA Collaboration
# Licensed under the BSD License.
"""The way that Flask is designed, we have to read our configuration and
initialize many things on module import, which is a bit lame. There are
probably ways to work around that but things work well enough ... | nilq/baby-python | python |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from datetime import datetime
import pandas as pd
class Funcion_salida:
def Retirar_desplegar_teclado(self):
MOV = -100
# movimiento botones
self.salida_nombre.setGeometry(self.width/3.6, (self.height/2.7)+... | nilq/baby-python | python |
class Command:
def __init__(self, name, obj, method, help_text):
assert hasattr(method, '__call__')
self._name = str(name)
self._obj = obj
self._method = method
self._help = str(help_text)
@property
def name(self):
return self._name
@property
def hel... | nilq/baby-python | python |
from __future__ import print_function
from hawc_hal import HAL
import matplotlib.pyplot as plt
from threeML import *
import pytest
from conftest import point_source_model
@pytest.fixture(scope='module')
def test_fit(roi, maptree, response, point_source_model):
pts_model = point_source_model
hawc = HAL("HAWC... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import sys
sys.path.insert(0,os.environ['HOME']+'/P3D-PLASMA-PIC/p3dpy/')
import numpy as np
from mpi4py import MPI
from subs import create_object
import AnalysisFunctions as af
#
# MPI INITIALIZATION
#
comm = MPI.COMM_WORLD
size = comm.Get_size()
rank = comm.Get_rank()
status = MPI.St... | nilq/baby-python | python |
import unittest
from sharepp import SharePP, Coin
class SharePPTest(unittest.TestCase):
def test_valid_input(self):
price = SharePP.get_etf_price("LU1781541179")
self.assertTrue(float, type(price))
def test_invalid_input(self):
try:
SharePP.get_etf_price("invalid_isin")
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<i@binux.me>
# http://binux.me
# Created on 2014-10-19 16:23:55
from __future__ import unicode_literals
from flask import render_template, request, json
from flask import Response
from .app import a... | nilq/baby-python | python |
import os
import shutil
import subprocess
def create_videos(video_metadata, relevant_directories, frame_name_format, delete_source_imagery):
stylized_frames_path = relevant_directories['stylized_frames_path']
dump_path_bkg_masked = relevant_directories['dump_path_bkg_masked']
dump_path_person_masked = rel... | nilq/baby-python | python |
from django.urls import path, include
from mighty.functions import setting
from mighty.applications.user import views
urlpatterns = [
path('user/', include([
path('create/', views.CreateUserView.as_view(), name="use-create"),
])),
]
api_urlpatterns = [
path('user/', include([
path('form/',... | nilq/baby-python | python |
from django.core.management.base import BaseCommand, CommandError
from openfood.models import Product, Category, Position
from django.db import models
from datetime import datetime
import sys
import requests
class Collector:
"""
Get products from Open Food Facts database.
Register fields for 'Products' &... | nilq/baby-python | python |
import altair as alt
from model import data_wrangle
def return_fatality_bar_chart(value=None):
"""
creates an altair chart object for the plot of the fatality barchart.
Parameters
----------
value: the value passed in from the radio buttons.
"0", "1", and "2" for "first-world", "non-first-wo... | nilq/baby-python | python |
import sys
from collections import OrderedDict
import calplot
import pandas as pd
def loadData(filename: str):
df = pd.read_csv(filename, usecols=['DateTime', 'Open', 'High', 'Low', 'Close', 'Volume'], na_values=['nan'])
df['DateTime'] = pd.to_datetime(df['DateTime'], utc=True).dt.tz_convert('US/Eastern')
... | nilq/baby-python | python |
from aiohttp import web, test_utils
import typing
import asyncio
import functools
from .const import InputQuery
import attr
@attr.s
class AppContainer:
host: typing.Optional[str] = attr.ib(default=None)
port: typing.Optional[int] = attr.ib(default=None)
_app: web.Application = attr.ib(factory=web.Applica... | nilq/baby-python | python |
'''OpenGL extension SGIS.texture_color_mask
Overview (from the spec)
This extension implements the same functionality for texture
updates that glColorMask implements for color buffer updates.
Masks for updating textures with indexed internal formats
(the analog for glIndexMask) should be supported by a separate ... | nilq/baby-python | python |
from .api import AppSyncAPI
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import time
from typing import List, Dict, Any
from chaosaws import aws_client
from chaoslib.exceptions import FailedActivity
from chaosaws.types import AWSResponse
from chaoslib.types import Configuration, Secrets
from logzero import logger
from .constants import OS_LINUX, OS_WINDOWS, GREP_PR... | nilq/baby-python | python |
import torch as T
import dataclasses as dc
from typing import Optional, Callable
def vanilla_gradient(
output, input,
filter_outliers_quantiles:tuple[float,float]=[.005, .995]):
map = T.autograd.grad(output, input)
assert isinstance(map, tuple) and len(map) == 1, 'sanity check'
map = map[0... | nilq/baby-python | python |
import argparse
import torch
import wandb
wandb.login()
from dataloader import get_dataloaders
from utils import get_model
from train import Trainer
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True, choices=['c10', 'c100', 'svhn'])
parser.add_argument('--model', required=True, choice... | nilq/baby-python | python |
def divide(num):
try:
return 42 / num
except ZeroDivisionError:
print('Error: Invalid argument')
print(divide(2))
print(divide(12))
print(divide(0))
print(divide(1))
| nilq/baby-python | python |
# coding=utf-8
#
# created by kpe on 28.Mar.2019 at 15:56
#
from __future__ import absolute_import, division, print_function
| nilq/baby-python | python |
import graphviz
dot = graphviz.Digraph(comment='GIADog system overview')
dot.render('output/system.gv', view=True) | nilq/baby-python | python |
# The MIT License (MIT)
# Copyright (c) 2020 Mike Teachman
# https://opensource.org/licenses/MIT
# Platform-independent MicroPython code for the rotary encoder module
# Documentation:
# https://github.com/MikeTeachman/micropython-rotary
import micropython
_DIR_CW = const(0x10) # Clockwise step
_DIR_CCW = const(0... | nilq/baby-python | python |
from flask import Flask
app = Flask(__name__)
import sqreen
sqreen.start()
from app import routes
if __name__ == '__main__':
app.run(debug=True)
| nilq/baby-python | python |
"""Module to generate datasets for FROCC
"""
import os
import numpy as np
import sklearn.datasets as skds
import scipy.sparse as sp
def himoon(n_samples=1000, n_dims=1000, sparsity=0.01, dist=5):
# n_samples = 1000
# n_dims = 1000
# dist = 5
# sparsity = 0.01
x, y = skds.make_moons(n_samples=n_sa... | nilq/baby-python | python |
import pytest
from mixer.main import mixer
from smpa.models.address import Address, SiteAddress
@pytest.fixture
def address():
obj = Address()
obj.number = "42"
obj.property_name = "property name"
obj.address_line_1 = "address line 1"
obj.address_line_2 = "address line 2"
obj.address_line_3 =... | nilq/baby-python | python |
# Russell RIchardson
# Homework 2, problem 1
"""This reads from a text file and returns a string of the text"""
def read_from_a_file(the_file):
file=open(the_file,'r')
the_string=file.read()
file.close()
return the_string
"""This takes in a string and writes that string to a text file"""
def write... | nilq/baby-python | python |
"""
Perform inference on inputted text.
"""
import utils
import torch
from termcolor import cprint, colored as c
import model
import data
import re
import sys
source = sys.argv[1]
# get an edgt object
def get_edgt():
input_chars = list(" \nabcdefghijklmnopqrstuvwxyz01234567890")
output_chars = ["<nop>", "<cap... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''checkplot.py - Waqas Bhatti (wbhatti@astro.princeton.edu) - Jan 2017
License: MIT.
Contains functions to make checkplots: quick views for determining periodic
variability for light curves and sanity-checking results from period-finding
functions (e.g., from periodbase)... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: lazy_read.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol... | nilq/baby-python | python |
import os
import sys
import socket
import time
from multiprocessing import Process
from pathlib import Path
from typing import Tuple, Union
import torch
from torch.utils.tensorboard import SummaryWriter
from super_gradients.training.exceptions.dataset_exceptions import UnsupportedBatchItemsFormat
# TODO: These utils... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2016-2017 Stella/AboodXD
# Supported formats:
# -RGBA8
# -RGB10A2
# -RGB565
# -RGB5A1
# -RGBA4
# -L8/R8
# -L8A8/RG8
# -BC1
# -BC2
# -BC3
# -BC4U
# -BC4S
# -BC5U
# -BC5S
# Feel free to include this in your own program if you want, just give cr... | nilq/baby-python | python |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | nilq/baby-python | python |
# Marcelo Campos de Medeiros
# ADS UNIFIP
# REVISÃO DE PYTHON
# AULA 10 CONDIÇÕES GUSTAVO GUANABARA
'''
Faça um Programa que pergunte o salário do funcionário e calcule o valor do seu aumento.
* Para salários superiores a R$ 1.250.00, Calcule um aumento de 10%.
* Para os inferiores ou iguais o aumento é de 15%... | nilq/baby-python | python |
# global imports
from dash.dependencies import Input, Output, State, ALL # ClientsideFunction
from dash import html
# local imports
from ..dash_app import app
import pemfc_gui.input as gui_input
from .. import dash_layout as dl
tab_layout = html.Div(dl.frame(gui_input.main_frame_dicts[1]))
@app.callback(
Outpu... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.