content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import sys import os import re import shutil import tempfile import subprocess from distutils import dir_util from typing import Any, List, Mapping, Set import pathspec REPLACE_PATTERN = re.compile(r"#\[(\w+)\]#") HELP = """ Usage: netbeansify <input directory> [options] Available Options: --help ...
nilq/baby-python
python
from __future__ import annotations import pathlib from contextlib import contextmanager from typing import Any, Iterable, Iterator, Union from alembic import command from alembic.config import Config from dcp import Storage from dcp.storage.base import DatabaseStorageClass from sqlalchemy.engine import Result from sq...
nilq/baby-python
python
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython """ from random import randint # pip install prototools from prototools import int_input, text_align, textbox from prototools.colorize import * LIMITE, MIN, MAX, intentos = 5, 1, 10, 0 NUMERO_ALEATORIO = randint(MIN, MAX) textbox( cyan("ADIVINA EL NUME...
nilq/baby-python
python
# -*- coding:utf-8 -*- from xml.dom import minidom from xlrd import open_workbook import json import re jdict = {} axls = open_workbook('student.xls') sheet1 = axls.sheet_by_name('student') for i in range(3): sign = str(sheet1.cell(i,0).value) jdict[sign] = [] for j in range(1,5): if j...
nilq/baby-python
python
import os import pytest from analyzer.ResultsCollector.PytestResults import PytestResult pytest_version = 'pytest-6.2.5' @pytest.fixture(scope='module') def data(data_dir): return os.path.join(data_dir, 'PytestResults') @pytest.fixture(scope='module') def happy_day(data): with open(os.path.join(data, 'hap...
nilq/baby-python
python
# -*- coding: utf-8 -*- import plotly.graph_objs as go def draw(x1, y1, x2, y2, x3, y3, safety_factor, flag=None, x4=None, y4=None, x5=None, y5=None, x6=None, y6=None, x7=None, y7=None, x8=None, y8=None, x9=None, y...
nilq/baby-python
python
''' Created on 24 Nov 2015 @author: wnm24546 ''' from scipy.constants import c, h, k, pi from scipy.optimize import curve_fit from collections import OrderedDict import numpy as np from Lucky.LuckyExceptions import BadModelStateException #k is kb class CalculationService(object): def __init__(self, pp): ...
nilq/baby-python
python
from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User from .models import Employee, CostCenter, Unity class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSe...
nilq/baby-python
python
import numpy as np import astropy.constants as cst import astropy.units as u def blackbody(wave, T): ''' Blacbody function Parameters ---------- wave : float Wavelength(s) in micron T : float Temperature in Kelvin Results ------- bb_spectrum : float Black...
nilq/baby-python
python
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. import json import sys import re import traceback from os.path import expanduser import os import urllib from uforge.objects.uforge import * im...
nilq/baby-python
python
import argparse import yaml from train_eval.evaluator import Evaluator import os # Parse arguments parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", help="Config file with dataset parameters", required=True) parser.add_argument("-r", "--data_root", help="Root directory with data", required=True)...
nilq/baby-python
python
from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView from users.models import super_table, teacher_table, student_table from users.serializers import SuperSerializer, TeacherSerializer, Stude...
nilq/baby-python
python
"""Represents a tether from one actor to another""" from nari.types.event.base import Event from nari.types.actor import Actor from nari.types.event import Type class NetworkTether(Event): """Network tether event""" __id__ = Type.networktether.value def handle_params(self): self.source_actor = Act...
nilq/baby-python
python
from flask import Flask, Blueprint, request from flask_bcrypt import Bcrypt from flask_cors import CORS from api.models import db from api.email import mail import os app = Flask(__name__) CORS(app) app.config.from_object(os.environ["APP_SETTINGS"]) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db.init_app(...
nilq/baby-python
python
from tkinter import * from tkinter.filedialog import askopenfilename from tkinter.filedialog import asksaveasfilename from os.path import basename from tkinter.messagebox import askokcancel, askyesno from tkinter import PhotoImage # functions = Functions() class Frontend(): activefile = 'unactive' def __ini...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Create COMSOL compatible color encodings for the CET perceptually uniform colour maps available at: http://peterkovesi.com/projects/colourmaps/ To install to COMSOL, copy the unzipped tsv files to the comsol\data\colormap directory Works at least for COMSOL 4.2a. Cre...
nilq/baby-python
python
import ipaddress import os.path from unittest import TestCase from unittest.mock import MagicMock, patch from parameterized import parameterized from salt.exceptions import CommandExecutionError import yaml import metalk8s_network from tests.unit import mixins from tests.unit import utils YAML_TESTS_FILE = os.path...
nilq/baby-python
python
import torch.nn as nn from .losses import get_loss from ..architectures import get_backbone from .wrapper import Wrapper class SimpleClassifierWrapper(Wrapper): def __init__(self, wrapper_config): super().__init__() self.backbone = None self.classifier = None self._init_modules(wra...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # Project: silx (originally pyFAI) # https://github.com/silx-kit/silx # # Copyright (C) 2012-2017 European Synchrotron Radiation Facility, Grenoble, France # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docume...
nilq/baby-python
python
#!/usr/bin/env python3 import random def emit_test_one(max_len_list,len_cmd_min,len_cmd_max,no_exception): header = ''' #define CATCH_CONFIG_MAIN #include "catch.hpp" #include "DoublyLinkedList.h" #include <list> #include <stdexcept> using namespace std; ''' ''' Test cases ...
nilq/baby-python
python
import numpy as np from tqdm import tqdm LOOP_SIZE = 10000000 SEED = [0, 1, 0] def monty_hall(typed): doors = SEED np.random.shuffle(doors) opted_3 = np.random.randint(0, 3) if not typed: result = doors[opted_3] return result else: for i in range(3): if i != o...
nilq/baby-python
python
CARDINALITA = 10 lista_numeri = [] somma = 0.0 contatore = 0 while contatore < CARDINALITA: numero = input('inserisci un numero ') print "iterazione ", contatore lista_numeri += [numero] somma += float(numero) contatore += 1 media = somma / CARDINALITA varianza2 = 0.0 contatore = 0 while contato...
nilq/baby-python
python
from utils import test_execution COUNT = 8000 @test_execution('with context manager') def with_context_manager(): def runner(): for _ in range(COUNT): with open('test.txt', 'r') as file: content = file.read() return runner @test_execution('without context manager') def ...
nilq/baby-python
python
import tensorflow as tf import cv2 import numpy as np IMG_SIZE=(224,224) Model=tf.keras.models.load_model ('Ensamble_Model(Ori).h5') path='C:/Users/mariotiara/Desktop/GUI/Sampel/ffc04fed30e6_(0)_Normal.jpeg' img=tf.keras.preprocessing.image.load_img(path,target_size=IMG_SIZE) x = tf.keras.preprocessing.i...
nilq/baby-python
python
#!/usr/bin/env python __all__=['configstruc', 'loadpdb', 'loadstruc', 'molecule', 'protein', 'ligand', 'lipid'] from loadstruc import (FetchPDB, Loadstruc)
nilq/baby-python
python
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange 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 by applic...
nilq/baby-python
python
import argparse as ag import ast import csv import datetime from ebooklib import epub import feedparser import json import logging from termcolor import colored logging.basicConfig(filename='logs.log', level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - ' '%(me...
nilq/baby-python
python
# ---------------------------------------------------------------------------- # meh # Copyright (c) 2021 TreeCaptcha # # 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, in...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2011 Fanficdownloader team # # 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 require...
nilq/baby-python
python
from collections import namedtuple import csv import gzip from os.path import abspath, join import subprocess from growser.app import db, log from growser.db import from_sqlalchemy_table from growser.models import Recommendation from growser.cmdr import DomainEvent, Handles from growser.commands.recommendations impor...
nilq/baby-python
python
# 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 in writing, software # distributed under t...
nilq/baby-python
python
from json import decoder, loads from os import getenv from re import findall, search from nfu.expand_bus.network import http_get from nfu.expand_bus.ticket import get_alipay_url from nfu.nfu_error import NFUError def get_bus_schedule(route_id: int, date: list) -> dict: """ 若日期在车票预售期内,获取班车时刻表。 - 字段说明 ...
nilq/baby-python
python
import os import sys import argparse import requests import flask import json import re import yaml import shutil import mmh3 from munch import Munch, munchify from flask import render_template, redirect, url_for, send_from_directory from markupsafe import escape def log(*args, **kwargs): print(*args, **kwargs, ...
nilq/baby-python
python
from .models import Electricity from django.http import HttpResponse from django.utils import timezone from django.views.generic import View import datetime import json class get_json(View): """ Returns list of timestamp-consumption pairs. """ def get(self, request, *args, **kwargs): time_start = tim...
nilq/baby-python
python
# utility packages import os from tqdm import tqdm import csv # math and support packages from scipy import ndimage import numpy as np import pandas as pd # image processing packages import cv2 import matplotlib.pyplot as plt import sklearn from sklearn.model_selection import train_test_split from random import shuff...
nilq/baby-python
python
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Modifications made by Cloudera are: # Copyright (c) 2016 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A cop...
nilq/baby-python
python
import CollectionsManager from UserController.UserCommand import UserCommandClass # ==================================== UserCommandAddNewDuck Class =================================# class UserCommandAddNewDuck(UserCommandClass): component = None component_index = 0 component_selected = None ...
nilq/baby-python
python
import numpy as np import ctypes as C import cv2 libmog = C.cdll.LoadLibrary('libmog2.so') def getfg(img): (rows, cols) = (img.shape[0], img.shape[1]) res = np.zeros(dtype=np.uint8, shape=(rows, cols)) libmog.getfg(img.shape[0], img.shape[1], img.ctypes.data_as(C.POINTER(C.c_ubyte))...
nilq/baby-python
python
# coding: utf-8 """ Camunda BPM REST API OpenApi Spec for Camunda BPM REST API. # noqa: E501 The version of the OpenAPI document: 7.13.0 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from openapi_client.configuration import Configuration clas...
nilq/baby-python
python
import multiprocessing import time from functools import wraps def logging_decorator(f): @wraps(f) def wrapper(*args, **kwds): print('Entering decorator') result=f(*args, **kwds) print('Exiting decorator') return result return wrapper @logging_decorator def compute_squares(number):...
nilq/baby-python
python
from setuptools import setup setup( name='nlzss', author='magical', license='MIT', packages=['nlzss'] )
nilq/baby-python
python
# coding: utf-8 #!/usr/bin/python import sys, getopt, time import operator import pickle import numpy as np #for euclidean distance import pandas as pd # to read the actual dataset from numpy import zeros, sum as np_sum, add as np_add, concatenate, repeat as np_repeat, array, float32 as REAL, empty, ones, memmap ...
nilq/baby-python
python
# # PySNMP MIB module ELTEX-MES-eltMacNotification-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-eltMacNotification-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:47:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pyt...
nilq/baby-python
python
from abc import ABC class AbstractDiscriminantStrategy(ABC): def calculate_discriminant(self, a, b, c): pass
nilq/baby-python
python
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com> # # 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 applicabl...
nilq/baby-python
python
import pandas as pd import numpy as np UTIL_SCORING = {'player': { 'assists': 2, 'kills': 3, 'deaths': -1, 'total cs': 0.02, # 'games_not_played': 20 }, ...
nilq/baby-python
python
""" Business logic for the orchestration operations. """ from http import HTTPStatus import bson import requests from shipyard_cli.errors import StatusError class CraneService(): """Service for orchestration operations.""" def __init__(self, url: str, port: str): self.base_url = url + ':' + port ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Aug 21 16:20:46 2018 @author: Arvinder Shinh """ import tensorflow as tf from tensorflow import saved_model as sm import DevnagriLipiDataGenerator import DevnagriLipiDataVerifier SerializedImgContainer, Labels = DevnagriLipiDataGenerator.DevnagriData() Classfy_Inputs=tf.p...
nilq/baby-python
python
from . import settings from django.conf import settings from django.core.exceptions import ObjectDoesNotExist if hasattr(settings, 'SALES_MODEL_FROM') and hasattr(settings, 'SALES_MODEL_IMPORT'): User = getattr(__import__(settings.SALES_MODEL_FROM, fromlist=[settings.SALES_MODEL_IMPORT]), settings.SALES_MODEL_IMPO...
nilq/baby-python
python
from datetime import datetime from unittest import TestCase import jsons from jsons import DeserializationError class TestPrimitive(TestCase): def test_dump_str(self): self.assertEqual('some string', jsons.dump('some string')) def test_dump_int(self): self.assertEqual(123, jsons.dump(123)) ...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2021 Tong LI <tongli.bioinfo@protonmail.com> # # Distributed under terms of the BSD-3 license. """ """ import fire from zarr import consolidate_metadata from pathlib import Path import zarr def main(file_in): stem = Path(file_in).st...
nilq/baby-python
python
# coding=utf-8 # Copyright 2018 The TensorFlow Datasets 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 by appl...
nilq/baby-python
python
# coding: utf-8 ########################################################################## # NSAp - Copyright (C) CEA, 2019 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for det...
nilq/baby-python
python
import codecs import numpy as np import copy import time import random import json import multiprocessing import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import os import joblib entities2id = {} relations2id = {} relation_tph = {} relation_hpt = {} ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # encoding: utf-8 # /run.py """ Tic-Toc-Tpe API ------------------------------------------------------------------------ App for production ------------------------------------------------------------------------ """ import os ...
nilq/baby-python
python
from Tkinter import * root = Tk() root.title("kaki") root.resizable(0,0) points = [] tag = "line" c = Canvas(root, bg="white", width=1280, height= 720) def make_dot(x, y, xmax, ymax): dot = c.create_oval(x, y, xmax, ymax, fill="black") def point(event): x = event.x - 2 y = event.y - 2 o = 4 do...
nilq/baby-python
python
# # Catalog creation history: # # catalog creation requires one to set the RESULTS_VERS environment variable to the correct reduction # # DR11 catalog created using 'python make_rcsample.py -o /work/bovy/data/bovy/apogee/apogee-rc-DR11.fits --addl-logg-cut --rmdups' # rmdups was added after the fact because this option...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-09-15 09:15 from django.db import migrations, models import django.db.models.deletion import wagtail.core.models class Migration(migrations.Migration): dependencies = [ ("wagtailcore", "0028_merge"), ("torchbox", "0067_auto_20160906_16...
nilq/baby-python
python
n=int(input('no of primes to be generated : ')) counter=0 n1=2 while True: is_prime=True for i in range(2,n1//2+1): if n1%i==0: is_prime=False break if is_prime==True: print(n1) counter=counter+1 if counter==n: break n1=n1+1
nilq/baby-python
python
# -*- encoding: utf-8 -*- """Main application window Contains : - menubar with File, Edit - statusbar displaying cursor position on the scene - NodeEditorWidget instance containing a graphics view and the scene """ import os import json from PyQt5.QtWidgets import QMainWindow, QAction, QFileDialog, QLabel,...
nilq/baby-python
python
import dgl import networkx as nx # create a graph g_nx = nx.petersen_graph() g_dgl = dgl.DGLGraph(g_nx) import matplotlib.pyplot as plt plt.subplot(121) nx.draw(g_nx, with_labels=True) plt.subplot(122) nx.draw(g_dgl.to_networkx(), with_labels=True) plt.show() # add edges and nodes into graph import dgl import torc...
nilq/baby-python
python
#!/usr/bin/env python3 import base64 import sys from pprint import pformat from nullroute.irc import Frame class SaslMechanism(object): def __init__(self): self.step = 0 self.inbuf = b"" def do_step(self, inbuf): return None def feed_input(self, inbuf): self.inbuf += inbuf...
nilq/baby-python
python
"""Config flow for nVent RAYCHEM SENZ.""" import logging from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN class OAuth2FlowHandler( config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN ): """Config flow to handle SENZ OAuth2 authentication.""" DOMAIN = DO...
nilq/baby-python
python
# -*- encoding: utf-8 -*- # # Copyright 2012 Martin Zimmermann <info@posativ.org>. All rights reserved. # License: BSD Style, 2 clauses -- see LICENSE. # # Provide a homogenous interface to Templating Engines like Jinja2 import abc class AbstractEnvironment(object): """Generic interface for python templating eng...
nilq/baby-python
python
import pandas as pd import torch def get_covariates(cov_name, split): """ get a list of strutured covariates as a pytorch tensor split by train/val/test input: - cov_name = 'Male' - split = 'train', 'val' or 'test' Here we're mostly interested in gender so our covaraite is male...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Defines the unit tests for the :mod:`colour.plotting.section` module. """ import unittest from matplotlib.pyplot import Axes, Figure from colour.geometry import primitive_cube from colour.models import RGB_COLOURSPACE_sRGB, RGB_to_XYZ from colour.plotting import (plot_visible_spectrum_sect...
nilq/baby-python
python
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name="index"), url(r'^dashboard$', views.dashboard, name="dashboard"), url(r'^properties$', views.properties, name="properties"), url(r'^add_property$', views.add_property, name="add_property"), ...
nilq/baby-python
python
import sys import os import cv2 images_path = sys.argv[1] thumbnail_size = 300 thumbnails_path = os.path.join(images_path, "thumbnails") event_name = os.path.basename(images_path) if not os.path.isdir(thumbnails_path): os.mkdir(thumbnails_path) images = os.listdir(images_path) yml_line = "gallery:\n" for ind,...
nilq/baby-python
python
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder)==0: return None tn=TreeNode(preorder[0]) l=[] r=[] for i in preorder: if i<preorder[0]: l.append(i) elif i>preorder[0]: ...
nilq/baby-python
python
from onboarding_project.celery import app from squad_pantry_app.models import PerformanceMetrics @app.task def calc_performance_metrics(): PerformanceMetrics.create_avg_performance_metrics()
nilq/baby-python
python
""" Creates components from JSON files. This provides an easy way for adding custom components without mucking around with blenders API. Of course, for more advanced tools it is necessary to create more complex UI's, but if you just want a component with a couple twiddleable numbers, bools and vecs, a JSON component ca...
nilq/baby-python
python
#!/usr/bin/env python3 import os import re import sys import errno import subprocess import json import glob IMPORTPREFIX="github.com/kentik/" REPOROOT=os.path.basename(os.getcwd()) SRCDIR="staging" TGTDIR="proto_go" PACKAGE="^(package .*);" # # Attributes pertinent to building the go code to serve proto types # f...
nilq/baby-python
python
#!/usr/bin/env python3 import sys import time import automationhat time.sleep(0.1) # Short pause after ads1015 class creation recommended try: from PIL import Image, ImageFont, ImageDraw except ImportError: print("""This example requires PIL. Install with: sudo apt install python{v}-pil """.format(v="" if sy...
nilq/baby-python
python
"""Application credentials platform for the Honeywell Lyric integration.""" from homeassistant.components.application_credentials import ( AuthorizationServer, ClientCredential, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from .api import LyricLoca...
nilq/baby-python
python
import tensorflow as tf from tensorflow import keras from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession from tensorflow.keras.layers import Input, Lambda, Dense, Flatten from tensorflow.keras.models import Model from tensorflow.keras.applications.inception_resnet_v2 import ...
nilq/baby-python
python
from django.test import TestCase from ..models import Tag, Medium from ..management.commands.add_tag_to_media import AssignTag class RenameTagTest(TestCase): fixtures = ['test_basic_data.yaml'] def setUp(self): pass def tearDown(self): pass def test_assign_tag_to_one_file(self): ...
nilq/baby-python
python
r""" ``$ mwtext preprocess_text -h`` :: Converts MediaWiki XML dumps to plaintext. One line per text chunk with wiki markup and punctuation cleaned up. This utility is designed with word embeddings in mind. Generally, you can expect one line per paragraph. Usage: preprocess_text (-h|--help)...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Transformers installation import numpy as np from transformers import GPT2LMHeadModel, GPT2TokenizerFast from qtorch.quant import posit_quantize, float_quantize, configurable_table_quantize device = 'cuda' model_id = 'gpt2-large' tokenizer = GPT2TokenizerFast.from_pretrained(model_id) fro...
nilq/baby-python
python
# coding=utf-8 import tensorflow as tf from tensorflow.python.ops import variable_scope import numpy as np import sys import os sys.path.append('..') from tensor2tensor.models import transformer from tensor2tensor.layers import common_layers from tensor2tensor.utils import trainer_lib from tensor2tensor.utils import r...
nilq/baby-python
python
#!/bin/python import listify_circuits listify_circuits.optimize_circuits(48, 'forward')
nilq/baby-python
python
""" Register Me Silly Repeatedly checks Drexel's Term Master Schedule for availability of class sections Author: Anshul Kharbanda Created: 9 - 21 - 2018 """ from . import LabeledInput from tkinter import * class LabeledSpinbox(LabeledInput): """ Docstring for LabeledSpinbox """ def __init__(self, ma...
nilq/baby-python
python
#Detector Functions # ------------------ Importing Libraries ------------------ # import cv2 import os import time # ------------------ Importing Functions ------------------ # from utils import open_thresholds, get_audio_list, reshape_image, input_output_details, make_prediction, get_dist_values, play_audio_record...
nilq/baby-python
python
""" Xero Accounts API """ from .api_base import ApiBase class Accounts(ApiBase): """ Class for Accounts API """ GET_ACCOUNTS = '/api.xro/2.0/accounts' def get_all(self): """ Get all accounts Returns: List of all accounts """ return self._get...
nilq/baby-python
python
"""Defines a Tornado Server that consumes Kafka Event data for display""" import logging import logging.config from pathlib import Path import tornado.ioloop import tornado.template import tornado.web # Import logging before models to ensure configuration is picked up logging.config.fileConfig(f"{Path(__file__).paren...
nilq/baby-python
python
link_template="""\ <ul> <li><a href="{langfam_code:}/overview/introduction.html">Introduction</a></li> <li><a href="{langfam_code:}/overview/tokenization.html">Tokenization</a></li> <li>Morphology <ul> <li><a href="{langfam_code:}/overview/morphology.html">General principles</a></...
nilq/baby-python
python
import tensorflow as tf hello =tf.constant('hello') sess=tf.Session() print(sess.run(hello))
nilq/baby-python
python
import os, numpy, sys from numpy.linalg import norm import isambard_dev def get_SHparams(protein): sequence = protein[0].sequence residue_ids = [protein[0][i].id for i in range(len(protein[0].sequence))] reference_axis = isambard_dev.analyse_protein.reference_axis_from_chains(protein) residue_code = [sequence[n...
nilq/baby-python
python
# coding=utf-8 import toml class Config(object): def __init__(self, config_file_name): dictionary = toml.load(config_file_name) mqtt = Config.get_value_or_default(dictionary, "mqtt") self.broker_address = Config.get_value_or_default(mqtt, "broker_address") csv = Config.get_value_...
nilq/baby-python
python
#! /usr/bin/env python import argparse import itertools import cv2 import numpy as np if __name__=='__main__': parser = argparse.ArgumentParser( description='Arrange a number of images as a matrix.') parser.add_argument('f', help='Output filename.') parser.add_argument('w', type=int, ...
nilq/baby-python
python
#!/usr/bin/env python import rospy import numpy as np from sensor_msgs.msg import Image, CompressedImage import cv2 from cv_bridge import CvBridge, CvBridgeError bridge = CvBridge() image_pub = rospy.Publisher("output",Image,queue_size=1) def callback(original_image): np_arr = np.fromstring(original_image.data, ...
nilq/baby-python
python
import sys filename=sys.argv[1] def tableHTMLtoMatrix(filename): file=open(filename,"r") for i in range (2): file.readline() all_lines=file.readline().split("</td></tr></tbody></table></td></tr></thead>") entries=all_lines[1].split('<tr align="center">') dict,Enodes={},[] for entry in entries[1:]: entry=entry...
nilq/baby-python
python
import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as col import math from mpl_toolkits.mplot3d import Axes3D import numpy as np #import string INTP_METHODS = ["bilinear", "bicubic"] COLOR_SPECTRUMS = ["rainbow", "gray", "BuGn"] FILE_NAMES = [ "aug_6_temp","Aug-2016...
nilq/baby-python
python
from brownie import accounts, web3, Wei, reverts, chain from brownie.network.transaction import TransactionReceipt from brownie.convert import to_address import pytest from brownie import Contract from settings import * # reset the chain after every test case @pytest.fixture(autouse=True) def isolation(fn_isolation): ...
nilq/baby-python
python
from __future__ import annotations import re from librespot.common import Utils from librespot.metadata import SpotifyId from librespot.metadata.PlayableId import PlayableId class TrackId(PlayableId, SpotifyId): _PATTERN = re.compile("spotify:track:(.{22})") _hexId: str def __init__(self, hex_id: str):...
nilq/baby-python
python
import torch import numpy as np from models_repo.massive_resnets import * from models_repo.tiny_resnets import * from models_repo.Middle_Logit_Generator import * import argparse from train_funcs import train_regular_ce,\ train_regular_middle_logits,\ train_kd_or_fitnets_2,\ stage_1_fitnet_train,\ dml_tr...
nilq/baby-python
python
from nlgen.cfg import read_cfg EXAMPLE_NO_FEATURE = """ # example.nlcfg SENTENCE -> PRONOUN VI NOUN; VI -> VERB; PRONOUN -> "I"; VERB -> "play"; NOUN -> "blackjack" | "poker"; """.strip() def test_no_feature_example(): cfg = read_cfg(EXAMPLE_NO_FEATURE) # permutations returns a generator. # we use sets f...
nilq/baby-python
python
from typing import Optional from pydantic import BaseModel, Field class UserModel(BaseModel): name: str = Field(...) user_id: str = Field(...) password: str = Field(...) email: str = Field(...) is_admin: bool = Field(...) en_date: str = Field(...) de_date: str = Field(...) birth_date:...
nilq/baby-python
python
""" Misc lr helper """ from torch.optim import Adam, Adamax from .adamw import AdamW def build_optimizer(model, opts): param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimi...
nilq/baby-python
python
# Generated by Django 3.0.5 on 2020-04-07 16:08 import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('django_products', '0001_initial'), ] operations = [ migra...
nilq/baby-python
python
import aiodocker async def get_docker_images(): docker = aiodocker.Docker() print("== Images ==") for image in await docker.images.list(): tags = image["RepoTags"][0] if image["RepoTags"] else "" print(image["Id"], tags) async def pull(name: str): docker = aiodocker.Docker() awai...
nilq/baby-python
python