content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 10:11:05 2019 @author: alheritier """ from pykds import KDSForest import numpy as np from sklearn.datasets import load_breast_cancer data = load_breast_cancer() dim = data.data.shape[1] alpha_label= len(np.unique(data.target)) m = KDSForest(ntrees=1,se...
nilq/baby-python
python
import luigi import json import time import re import datetime import subprocess import base64 from urllib import urlopen import uuid from uuid import uuid4 from uuid import uuid5 from elasticsearch import Elasticsearch #for hack to get around non self signed certificates import ssl import sys # TODO # * I think we wa...
nilq/baby-python
python
# Lint as: python3 # Copyright 2019, The TensorFlow Federated Authors. # # 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 ...
nilq/baby-python
python
import weakref import numpy as np import qmhub.helpmelib as pme from .dobject import cache_update class DependPME(pme.PMEInstanceD): def __init__(self, cell_basis, alpha, order, nfft): super().__init__() self._name = "PME" self._kwargs = {"alpha": alpha, "order": order, "nfft": nfft} ...
nilq/baby-python
python
import torch import torch.nn as nn class NeuralColumn(nn.Module): def __init__(self, channels: int, output_dim: int) -> None: """ channels is the number of output convolution channels for each convolution layer of the network, except the last one. """ super(NeuralColumn, self)....
nilq/baby-python
python
"""D-Bus interface objects.""" from .systemd import Systemd from .hostname import Hostname from .rauc import Rauc from ..coresys import CoreSysAttributes class DBusManager(CoreSysAttributes): """A DBus Interface handler.""" def __init__(self, coresys): """Initialize D-Bus interface.""" self....
nilq/baby-python
python
from enforce_typing import enforce_types from engine import AgentBase from agents.PublisherAgent import PublisherAgent from agents.SpeculatorAgent import StakerspeculatorAgent from agents.DataconsumerAgent import DataconsumerAgent @enforce_types class DataecosystemAgent(AgentBase.AgentBaseNoEvm): """Will operate...
nilq/baby-python
python
from django.core.management.commands.test import Command as TestCommand from jsdir.core import JSDir class Command(TestCommand): def __init__(self): JSDir.set_use_finders(True) # sets the value only for this thread super(Command, self).__init__()
nilq/baby-python
python
import matplotlib as mil import tensorflow as tf from matplotlib import pyplot fig = pyplot.gcf() fig.set_size_inches(4, 4) sess = tf.InteractiveSession() image_filename = "/home/ubuntu/Downloads/n02107142_16917.jpg" filename_queue = tf.train.string_input_producer([image_filename]) # list of files to read reader...
nilq/baby-python
python
# # Copyright (C) 2014-2015 UAVCAN Development Team <uavcan.org> # # This software is distributed under the terms of the MIT License. # # Author: Ben Dyer <ben_dyer@mac.com> # Pavel Kirienko <pavel.kirienko@zubax.com> # from __future__ import division, absolute_import, print_function, unicode_literals import...
nilq/baby-python
python
from .binarytree import BinaryTree class LinkedBinaryTree(BinaryTree): """ Linked reperesentation of a binary tree structure. """ class _Node: # Ligtweight non-public class for storing a node __slots__ = '_element', '_parent', '_left', '_right' def __init__(self, element, parent=None, lef...
nilq/baby-python
python
import logging from helper import is_welsh logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class CoursesBySubject: def __init__(self, mapper, language): self.mapper = mapper self.language = language def group(self, courses, limit, of...
nilq/baby-python
python
import copy import numpy def convert_to_binary(list_of_digits): list_of_str_digits = [str(digit) for digit in list_of_digits] return int("".join(list_of_str_digits), 2) with open("data/day3.txt") as f: # The entire input forms a matrix of integers, parse it as such. matrix = [[int(num) for num in l...
nilq/baby-python
python
# Copyright 2018 The ops Developers # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ KJ-65X9500G の輝度制限と階調特性の関係調査 ========================================= Description. """ # import standard libraries import os # import third-party libraries import numpy as np from colour import write_image from PIL import Image from PIL import ImageFont from PIL import ImageDraw # impor...
nilq/baby-python
python
import pytest from openpecha.utils import download_pecha @pytest.mark.skip("Downloading github repo") def test_download_pecha(): pecha_path = download_pecha("collections")
nilq/baby-python
python
# Generated by Django 2.2 on 2020-08-11 11:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Iniciativa', fields=[ ('id', models.AutoField...
nilq/baby-python
python
from dsame.trees.BinaryTreeNode import BinaryTreeNode def inOrder(root: BinaryTreeNode): if root: inOrder(root.left) print(root.data) inOrder(root.right) a = BinaryTreeNode(2) b = BinaryTreeNode(3) c = BinaryTreeNode(1, a, b) print(inOrder(c))
nilq/baby-python
python
import os from ast import literal_eval from pathlib import Path import numpy as np def read_info(filename: os.PathLike) -> dict: """Read volume metadata. Parameters ---------- filename : PathLike Path to the file. Returns ------- dct : dict Dictionary with the metadata. ...
nilq/baby-python
python
import time from options.train_options import TrainOptions opt = TrainOptions().parse() # set CUDA_VISIBLE_DEVICES before import torch import pickle from data.custom_transforms import ToLabelTensor # with open("opt.obj",'wb') as f: # pickle.dump(opt,f) from data.segmentation import SegmentationDataset from models...
nilq/baby-python
python
from ...attribute import models as attribute_models from ...discount import models as discount_models from ...product import models as product_models from ...shipping import models as shipping_models def resolve_translation(instance, _info, language_code): """Get translation object from instance based on language...
nilq/baby-python
python
# Generated by Django 3.0.13 on 2021-04-01 08:17 from django.db import migrations, models import ensembl.production.djcore.models class Migration(migrations.Migration): dependencies = [ ('ensembl_dbcopy', '0005_targethostgroup'), ] operations = [ migrations.AlterField( model...
nilq/baby-python
python
from __future__ import absolute_import import logging # App must be initialized before models or ADDONS_AVAILABLE are available from website.app import init_app init_app() from osf.models import OSFUser, AbstractNode from framework.database import paginated from scripts.analytics.base import SnapshotAnalytics from w...
nilq/baby-python
python
#!/usr/bin/env python3 #class dedicated to archival functions for dnmt data import re import sys import subprocess,platform,os,time,datetime,zipfile import difflib import pickle import collections # import pysvn # import git #3rd party imports #local subroutine import from DNMT.procedure.subroutines import SubRou...
nilq/baby-python
python
# Django from django.db import models class UserAbstractModel(models.Model): """ Modelo basico abstracto. UserAbstractModel es una clase abstracta de la que heredan todos los modelos de User de la API. Esta clase provee los siguientes atributos: + created (DateTime): Almacena la fecha de creacio...
nilq/baby-python
python
from time import perf_counter def timer(func): def wrapper(*args, **kwargs): start_t = perf_counter() r_val = func(*args, **kwargs) end_t = perf_counter() elapsed = end_t - start_t print(f"{func.__name__} took time: {elapsed} seconds, {elapsed/60} minutes") return r...
nilq/baby-python
python
from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .models import MetodPage def metod(request): metods = MetodPage.objects.all().order_by('title') paginator = Paginator(metods, 10) page = request.GET.get('page') try: ...
nilq/baby-python
python
import itertools def subpaths_for_path_range(path_range, hardening_chars="'pH"): """ Return an iterator of paths # examples: # 0/1H/0-4 => ['0/1H/0', '0/1H/1', '0/1H/2', '0/1H/3', '0/1H/4'] # 0/2,5,9-11 => ['0/2', '0/5', '0/9', '0/10', '0/11'] # 3H/2/5/15-20p => ['3H/2/5...
nilq/baby-python
python
#!/usr/bin/env python3 """ Play Nerdle (https://nerdlegame.com) """ import json import logging from itertools import product from os import mkdir from os.path import dirname, join, realpath from typing import Any, Iterator, List, Optional, Tuple from .exceptions import CorrectAnswer, OutOfEquations, OutOfGuesses cla...
nilq/baby-python
python
from dbt.contracts.graph.manifest import Manifest import os from test.integration.base import DBTIntegrationTest, use_profile def get_manifest(): path = './target/partial_parse.msgpack' if os.path.exists(path): with open(path, 'rb') as fp: manifest_mp = fp.read() manifest: Manifest...
nilq/baby-python
python
import time from base.common.skeleton_base import SkeletonBase from base.constants import DEFAULT_BEFORE_EXPIRES from base.exceptions import ChannelTemplateNotFound from base.helpers import validate_channel from base.utils import format_response from typing import Dict from .router import * from .webhook import * fro...
nilq/baby-python
python
from django.forms.widgets import CheckboxSelectMultiple, RadioSelect class RadioSelectBootstrap(RadioSelect): template_name = "leprikon/widgets/multiple_input.html" option_template_name = "leprikon/widgets/input_option.html" class CheckboxSelectMultipleBootstrap(CheckboxSelectMultiple): template_name = ...
nilq/baby-python
python
import pandas as pd class LeakageInspector: def __init__(self, df1, df2, patient_col): """ Args: df1 (dataframe): dataframe describing first dataset df2 (dataframe): dataframe describing second dataset patient_col (str): string name of column with patient IDs """ self.df1 = df1 self.df2 = df...
nilq/baby-python
python
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup(name="Pairtree", version="0.7.5", description="Pairtree FS implementation.", long_description="""\ From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html : Pairtree, a filesystem hierarc...
nilq/baby-python
python
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from pages.createprojectpage.questionnaire_creation_options_page import QuestionnaireCreationOptionsPage from pages.dashboardpage.dashboard_locator import * from pages.page import Page class DashboardPage(Page): def __init__(self, driver): Page.__init__(self, dr...
nilq/baby-python
python
'''Use this for development''' from .base import * ALLOWED_HOSTS += ['127.0.0.1'] DEBUG = True WSGI_APPLICATION = 'home.wsgi.dev.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'sarytask', 'USER': 'postgres', 'PASSWORD': 'S3d6622...
nilq/baby-python
python
import re from jinja2.filters import contextfilter @contextfilter def to_dockbarx_items(context, pin_to_launcher_favorites): ''' returns the DockbarX launcher items ''' pin_to_launcher_favorites = list(pin_to_launcher_favorites) omit = context.resolve('omit') launcher_items = [] for f...
nilq/baby-python
python
import collections import itertools import typing from checkmerge import analysis, report class AnalysisResultMaxSeverityMetric(report.Metric): """ Metric for the maximum analysis result severity within a type. """ name = 'Max. severity' low = .5 high = 1.5 def __init__(self, items: typi...
nilq/baby-python
python
""" parser.py products.json의 반찬 상세 페이지 url에 요청을 보내 크롤링하는 메소드 정의 메소들을 crawl.py 파일에서 사용함 """ import requests from bs4 import BeautifulSoup import re def get_soup(url): webpage = requests.get(url).text soup = BeautifulSoup(webpage, 'lxml') return soup def parse_name(name): # content에 중량이 포함되어 있는지 체크 ...
nilq/baby-python
python
import pandas as pd import os import sys import subprocess import numpy as np import streamlit as st import time import random from random import randint from streamlit_player import st_player from streamlit_autorefresh import st_autorefresh import altair as alt import back as fl import usessss as fh ...
nilq/baby-python
python
GREY = (0.78, 0.78, 0.78) # uninfected RED = (0.96, 0.15, 0.15) # infected GREEN = (0, 0.86, 0.03) # recovered BLACK = (0, 0, 0) # dead COVID19_PARAMS = { "r0": 2.28, "incubation": 5, "percent_mild": 0.8, "mild_recovery": (7, 14), "percent_severe": 0.2, "severe_recovery": (21, 42...
nilq/baby-python
python
from troposphere import FindInMap, GetAtt, Join, Output, Parameter, Ref, Template from troposphere.awslambda import MINIMUM_MEMORY, MAXIMUM_MEMORY, Code, Function from troposphere.cloudformation import CustomResource from troposphere.constants import NUMBER from troposphere.ec2 import Instance, SecurityGroup from tropo...
nilq/baby-python
python
from flask import Flask, render_template, redirect app = Flask(__name__) #--- routes start --- from user import routes @app.route("/") def home(): return render_template('home.html') @app.route("/login/") def login_page(): return render_template('login.html') @app.route("/about/") def about(): return ...
nilq/baby-python
python
# qmpy/materials/element """ Django models representing elements and species. """ from django.db import models from qmpy.db.custom import DictField from qmpy.utils import * class Element(models.Model): """ Core model for an element. Relationships: | :mod:`~qmpy.Atom` via atom_set | :mod:`~...
nilq/baby-python
python
# # coding=utf-8 import unittest import uuid from google.appengine.ext import testbed from application import create_app from application.routes import create_routes class FlaskClient(unittest.TestCase): def setUp(self): self.tb = testbed.Testbed() self.tb.activate() self.tb.init_memcache_...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.db import models from django.template.defaultfilters import date from django.core.validators import MinValueValidator from django.urls import reverse_lazy from decimal import Decimal from djangosige.apps.vendas.models import TIPOS_DESCONTO_ESCOLHAS, MOD_FRETE_ESCOLHAS, ST...
nilq/baby-python
python
class Stack(object): """This class implements all the need functions for a stack""" def __init__(self): self.items = [] def is_empty(self): """Returns true if stack is empty, returns false if stack has an item""" return self.items == [] def push(self, item): ""...
nilq/baby-python
python
# Implementacion generica de Arboles de Decisiones. from math import log, inf class Node: def __init__(self, parent, X, Y, atr_types, default): self.parent = parent # Ejemplos del entrenamiento que pertenecen a este nodo. self.X = X # Etiquetas de los ejemplos. self.Y = Y # Tipos de atribut...
nilq/baby-python
python
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class ISCSIDataIn(Base): __slots__ = () _SDM_NAME = 'iSCSI_Data_In' _SDM_ATT_MAP = { 'HeaderOpcode': 'iSCSI_Data_In.header.Opcode-1', 'HeaderFlags': 'iSCSI_Data_In.header.Flags-2', 'HeaderTotalAHSLength...
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. # This is more akin to a .pyl/JSON file, so it's expected to be long. # pylint: disable=too-many-lines from gpu_tests import common_browser_args as cba from...
nilq/baby-python
python
import plotly.plotly as py import plotly.graph_objs as go import pandas as pd import numpy as np import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #transform to [[x,y,z]...] [[x...],[y...],[z...]] #plot def plot_sample_list(sample_list,lim_val=10): sample_mat = np.array(sample_list...
nilq/baby-python
python
### --------------------------------------------------------------------------- from .core.startup import initialize from .sublime import commands, events __version_tuple = (1, 0, 0) __version__ = ".".join([str(num) for num in __version_tuple]) ### ------------------------------------------------------------------...
nilq/baby-python
python
# coding:utf-8 import redis SCRIPT_PUSH = ''' local q = KEYS[1] local q_set = KEYS[1] .. "_set" local v = redis.call("SADD", q_set, ARGV[1]) if v == 1 then return redis.call("RPUSH", q, ARGV[1]) and 1 else return 0 end ''' SCRIPT_POP = ''' local q = KEYS[1] local q_set = KEYS[1] .. "_set" local v = redis.call("LP...
nilq/baby-python
python
import os import datetime os.system("powercfg /batteryreport") d = datetime.datetime.now() try: os.rename('battery-report.html', f'battery-health/reports/battery-report-{d.month}-{d.day}-{d.year}.html') os.startfile(f'battery-health\\reports\\battery-report-{d.month}-{d.day}-{d.year}.html') except WindowsError...
nilq/baby-python
python
import aspose.words as aw from docs_examples_base import DocsExamplesBase, MY_DIR, ARTIFACTS_DIR class WorkingWithPclSaveOptions(DocsExamplesBase): def test_rasterize_transformed_elements(self): #ExStart:RasterizeTransformedElements doc = aw.Document(MY_DIR + "Rendering.docx") ...
nilq/baby-python
python
# MINLP written by GAMS Convert at 04/21/18 13:54:00 # # Equation counts # Total E G L N X C B # 750 619 34 97 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
nilq/baby-python
python
import sqlite3 import os from pomodoro import Pomodoro os.chdir("..") # Go up one directory from working directory # Create database if it does not exist database_path = "data\pomodoros.db" if not os.path.exists(database_path): print("Creating database ...") os.system("database.py") conn = sqlite3.connect(...
nilq/baby-python
python
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ w,h,k=map(int,input().split());r=0 for _ in [0]*k: r+=(w+h<<1)-4;w-=4;h-=4 print(r)
nilq/baby-python
python
# -*- coding: utf-8 -*- # À partir de l’export csv de https://opendata.paris.fr/explore/dataset/les-titres-les-plus-pretes/ # vous compterez le nombre d’ouvrages par ‘type de document’ et vous afficherez les types par ordre décroissant from collections import Counter sep = ';' cnt = Counter() with open('les-titres...
nilq/baby-python
python
#!/usr/bin/env python #pythonlib import os import sys import math import re import time import glob import numpy #appion from pyami import imagefun from appionlib import appionLoop2 from appionlib import apImage from appionlib import apDisplay from appionlib import apDatabase from appionlib.apCtf import ctfdb from app...
nilq/baby-python
python
import torch import torch.nn as nn from models.pytorch_revgrad import RevGrad from efficientnet_pytorch import EfficientNet as effnet class EfficientNet(effnet): def __init__(self, blocks_args=None, global_params=None): super(EfficientNet, self).__init__(blocks_args=blocks_args, global_params=global_par...
nilq/baby-python
python
from idm.objects import dp, MySignalEvent, SignalEvent, __version__ from idm.utils import ment_user from datetime import datetime import time @dp.signal_event_register('инфо', 'инфа', 'info') def sinfo(event: SignalEvent) -> str: if event.msg['from_id'] not in event.db.trusted_users: message_id = event.sen...
nilq/baby-python
python
""" Title: Video Vision Transformer Author: [Aritra Roy Gosthipaty](https://twitter.com/ariG23498), [Ayush Thakur](https://twitter.com/ayushthakur0) (equal contribution) Date created: 2022/01/12 Last modified: 2022/01/12 Description: A Transformer-based architecture for video classification. """ """ ## Introduction V...
nilq/baby-python
python
import logging.config import unittest #import testing.mysqld import sqlalchemy from src.utils.Settings import Settings # Modules to Test from src.utils.Connector import Connector class TestConnector(unittest.TestCase): @classmethod def tag(cls, *tags): ''' Decorator to add tags to a test class...
nilq/baby-python
python
from rsTools.ui.menus import menu from ... import shelf, shelfButton from rsTools.glob import * import os import rsTools.utils.osUtils.enviroments as env import maya.cmds as cmds from rsTools.core.skeleton import skeletonAsset class skeletonShelfButton(shelfButton.ShelfButton): _color = (255, 157, 0) _title =...
nilq/baby-python
python
# must be first, as it does event loop patching and other "first" things from common.page_tokens import PageTokenManager from oozer.entities.collect_entities_iterators import ( iter_collect_entities_per_page, iter_collect_entities_per_page_graph, ) from tests.base.testcase import TestCase, mock from common.enu...
nilq/baby-python
python
""" Model """ from . import attention from . import evaluator from . import GAN_model from . import GAN_trainer from . import generator from . import trainer
nilq/baby-python
python
import json from typing import Dict, Optional from azure.durable_functions.models.FunctionContext import FunctionContext class DurableOrchestrationBindings: """Binding information. Provides information relevant to the creation and management of durable functions. """ # parameter names are as de...
nilq/baby-python
python
# Copyright 2014-2020 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program i...
nilq/baby-python
python
""" Unit Testing """ def unittest(tests=None): """ A Unit Test wrapper that will return the return code and an error message ( if any ) - Return Syntax: { 0 : [return_code_1, error_message_1], 1 : [return-code_2, error_message_2], } Type: Dictionary :: Syntax tests Description: The function ...
nilq/baby-python
python
n = int(input()) m = n line = input().split() t = 0 for i in range(0, n): if int(line[i]) >= 0: t += int(line[i]) else: m -= 1 a = t / m print(a)
nilq/baby-python
python
import pandas as pd from pathlib import Path import sys import re from collections import OrderedDict import pyqtgraph as pg from pyqtgraph.parametertree import Parameter, ParameterTree from ephys.ephysanalysis import acq4read from ephys.mapanalysistools import analyzeMapData as AMD import pylibrary.tools.fileselector...
nilq/baby-python
python
first="Akash" last="Singh" fname=first+" "+last print(fname)
nilq/baby-python
python
# Generated by Django 3.1.5 on 2021-01-13 18:09 import django.db.models.deletion import django.utils.timezone from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUT...
nilq/baby-python
python
#!/usr/bin/env python3 # # MIT License # # Copyright (c) 2020-2021 EntySec # # 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...
nilq/baby-python
python
#!/usr/bin/env python ############################################################# # ubi_reader/ubi_io # (c) 2013 Jason Pruitt (jrspruitt@gmail.com) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Founda...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from codegen.spec import * from codegen.mir_emitter import * from codegen.isel import * from codegen.x64_def import * from codegen.matcher import * class X64OperandFlag(IntFlag): NO_FLAG = auto() # GOT_ABSOLUTE_ADDRESS - On a symbol operand = auto() this represe...
nilq/baby-python
python
import pathlib from setuptools import setup, find_packages HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setup( name='pylateral', version='1.0.0', description='Intuitive multi-threaded task processing in python.', long_description=README, long_description_content_t...
nilq/baby-python
python
import numpy as np class BaseAgent: def __init__(self, name, environment=None): self.name = name self.environment = environment def choose_action(self): action = np.random.choice(self.environment.valid_actions) pawn_actions = [a for a in self.environment.valid_actions if a < 1...
nilq/baby-python
python
# Copyright 2014 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. """Updates ExtensionPermission2 enum in histograms.xml file with values read from permission_message.h. If the file was pretty-printed, the updated version ...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict import pkg_resources import pytest import torch from flsim.common.pytest_helper i...
nilq/baby-python
python
import click import json from pathlib import Path from PIL import Image import pycountry import re import shlex import subprocess import time import traceback import youtube_dl SUB_LANGUAGES = ['en', 'en-US', 'en-UK', 'en-us', 'en-uk', 'de', 'de-DE', 'de-de', 'un'] ytops = { 'outtmpl': '{}.%(ext)s', 'hls_pref...
nilq/baby-python
python
from dataclasses import dataclass @dataclass class SpotifyConfig: client_id: str client_secret: str refresh_token: str
nilq/baby-python
python
""" Application load balancer stack for running ConsoleMe on ECS """ from aws_cdk import aws_ec2 as ec2 from aws_cdk import aws_elasticloadbalancingv2 as lb from aws_cdk import core as cdk class ALBStack(cdk.NestedStack): """ Application load balancer stack for running ConsoleMe on ECS """ def __ini...
nilq/baby-python
python
# -------------------------------------------------- # Gene class # Authors: Thomas Schwarzl, schwarzl@embl.de # -------------------------------------------------- import gzip import logging from collections import OrderedDict, defaultdict from HTSeq import GenomicArray, GenomicArrayOfSets, GenomicPosition, GenomicF...
nilq/baby-python
python
from __future__ import print_function import os import subprocess import shlex from getpass import getuser from distutils.command.build import build # type: ignore from setuptools import ( find_packages, setup, Command ) import numpy as np CUSTOM_COMMANDS = [ shlex.split(command_line) for command...
nilq/baby-python
python
# Copyright 2004-present, Facebook. All Rights Reserved. from django.contrib.auth.decorators import login_required from django.urls import path from . import views urlpatterns = [ # products path( "store/<int:storeId>/products/create", login_required(views.createProduct), name="createP...
nilq/baby-python
python
from detective import functions import math MOCK_ATTRIBUTE = { "battery_level": 61, "unit_of_measurement": "°C", "friendly_name": "Living room sensor temperature", "device_class": "temperature", } def test_device_class(): """Test get_device_class""" assert functions.get_device_class(MOCK_ATTR...
nilq/baby-python
python
from argparse import ArgumentParser import examples.example02.tasks from cline.cli import ArgumentParserCli, RegisteredTasks class ExampleCli(ArgumentParserCli): def make_parser(self) -> ArgumentParser: parser = ArgumentParser() parser.add_argument("a", help="first number", nargs="?") par...
nilq/baby-python
python
import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker from pandas.compat import StringIO import sys import re import os import ntpath def file_to_df(filename): with open(filename, 'r') as file: contents = file.read() # Read run configurations sta...
nilq/baby-python
python
import os import socket import struct import sys import select os.system("") UDP_PORT = 13117 MESSAGE_LEN = 1024 GAME_TIME = 10 sockUDP = None sockTCP = None # Colors for prints class Colors: GREEN = '\033[32m' BLUE = '\033[34m' PINK = '\033[35m' def printMessageOrRead(): # wait for read or write ...
nilq/baby-python
python
from tests.testcases import TestCaseUsingRealAPI from vortexasdk import Products, Geographies, Corporations, Vessels endpoints_and_searchterms = [ (Products(), "Gasoil"), (Geographies(), "China"), (Corporations(), "Oil"), (Vessels(), "Ocean"), ] class TestSearchReal(TestCaseUsingRealAPI): def tes...
nilq/baby-python
python
from app import app from flask import request, session from helpers.database import * from helpers.hashpass import * from helpers.mailer import * from bson import json_util, ObjectId import json def checkloginusername(): username = request.form["username"] check = db.users.find_one({"username": username}) ...
nilq/baby-python
python
"""Hyperparameters from paper """ import numpy as np import torch.optim as optim from .model import DQN, DuelingDQN class AtariHyperparams: ALGO = "DQN" SEED = 2 LOG_DISPLAY_FREQ = 10 # Image sizing WIDTH = 84 HEIGHT = 84 # Number of most recent frames given as input to Q-network A...
nilq/baby-python
python
""" Queue backend abstraction manager. """ import json import logging import sched import socket import time import uuid from typing import Any, Callable, Dict, List, Optional, Union from pydantic import BaseModel, validator import qcengine as qcng from qcfractal.extras import get_information from ..interface.data ...
nilq/baby-python
python
import logging from importlib import import_module from .groups import Groups log = logging.getLogger(__name__) class ConfigHelper: @classmethod def cog_name(cls, key): return ''.join(map(str.capitalize, key.split('_'))) CONFIG_GROUP_MAPPINGS = [ ('sudo', 'user', 'sudo'), ('sysb...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import from django.apps import apps, AppConfig class PanopticonConfig(AppConfig): name = "panopticon.django" label = "panopticon" verbose_name = "Panopticon" def ready(self): package_names = (a.module.__name__ for a in ...
nilq/baby-python
python
import numpy as np from numba import jit from scipy.sparse.construct import random from ..tools import compute_dist from ._utils import _CheckInputs from .base import IndependenceTest, IndependenceTestOutput from scipy.stats import rankdata class HHG(IndependenceTest): r""" Heller Heller Gorfine (HHG) test s...
nilq/baby-python
python
from django.contrib import admin from spaweb.models import Customer, ProductCategory, City from spaweb.models import Product, Order, OrderItem from spaweb.models import BusinessDirection, Topic admin.site.register(ProductCategory) admin.site.register(City) admin.site.register(BusinessDirection) admin.site.register(To...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Pype custom errors.""" class PypeError(Exception): """Custom error.""" pass
nilq/baby-python
python