content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python3 """ See freq_response.md for details """ from dataclasses import dataclass import fractions import math from typing import Iterable, Optional, Tuple, Union import numpy as np from analysis import linearity, time_domain_response from utils import utils from unit_test import unit_test from pro...
nilq/baby-python
python
""" 2019/12/23 23:42 162.【正则表达式】开始结束和或语法 """ import re # TODO: 1. ^托字号: 表示以...开始 """ 如果是在中括号中,那么代表取反操作. """ text1 = 'hello' ret_text1 = re.match('^h', text1) print('^托字号: 表示以...开始...') print(ret_text1.group()) # TODO: 2.$ 表示以...结束 email = 'hynever@163.com' ret_email = re.match('\w+@163\.com$', email) print('$ 表示以.....
nilq/baby-python
python
import paddle import paddle.nn.functional as F import random import numpy as np import math from PIL import Image from ..registry import PIPELINES from collections.abc import Sequence import cv2 import random @PIPELINES.register() class Toskeleton(object): """ transpose (M,T,V,2) to (2,T,V,...
nilq/baby-python
python
class RoundEdge: def __init__(self, r, obj): self.r = r self.obj = obj self.material = obj.material self.color = obj.color def signedDistance(self, point): return self.obj.signedDistance(point) - self.r def evalColorAtPoint(self, point): return self.obj.ev...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ unistorage.adapters.amazon ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module an adapter for Amazon Simple Storage Service (S3). :copyright: (c) 2012 by Janne Vanhala. :license: BSD, see LICENSE for more details. """ from datetime import datetime, timedelta from email.utils import...
nilq/baby-python
python
import numpy as np import time #Note, all modes should have a return to forward, to prevent stucks def forward_mode(Rover): # Calm the roll and pitch if (Rover.roll >= 1.5 and Rover.roll <= 358.5) or (Rover.pitch >= 1.5 and Rover.pitch <= 359): Rover.max_vel = 0.5 else: Rover.max_vel = 5 ...
nilq/baby-python
python
# License: MIT License import typing import numpy as np class Trajectory(object): """ Abstracts the infos about a complete set of trajectories, represented as a numpy array of doubles (the time deltas) and a numpy matrix of ints (the changes of states). :param list_of_columns: the list containing the...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright 2016 Battelle Energy Alliance, LLC # # 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
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Conversions between formats.""" import numpy as np import pytest from .. import linear as _l from ..io import LinearTransformArray as LTA @pytest.mark.parametrize( "filename", [ "f...
nilq/baby-python
python
import sys import os class Configuration: ###################################### ###### Configuration parameters ###### ###################################### # Change them if required # path to the root of ExaHyPe from this file pathToExaHyPERoot = os.path.abspath(os.path.join(os.pa...
nilq/baby-python
python
from socket import socket, AF_INET, SOCK_STREAM from message_handler import MessageHandler from string_match import match from rsa_ops import init_rsa class Client: def __init__(self, server_adr, bsize=1024): self.server_adr = server_adr # a tuple self.bsize = bsize self.pubkey, self.priv...
nilq/baby-python
python
from django.db import models from datetime import date class CompletionDate(models.Model): """Store a task completion on a certain date""" completion_date = models.DateField(auto_now_add=True, primary_key=True) class Task(models.Model): """Daily task model and related functions""" task_id = models.A...
nilq/baby-python
python
#!/usr/bin/env python import keras import numpy as np from imgaug import augmenters as iaa from keras.applications.mobilenet import preprocess_input from keras.preprocessing.image import image class CustomDataGenerator(keras.utils.Sequence): """ Takes input of image paths and corresponding labels and generat...
nilq/baby-python
python
# Generated by Django 3.2.7 on 2021-10-06 22:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0008_alter_review_reviewer'), ] operations = [ migrations.AlterField( model_name='watchl...
nilq/baby-python
python
# # PySNMP MIB module APPACCELERATION-STATUS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-STATUS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import os import sys if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess from . import common as cmn task_registry = {} def task(task_func): ""...
nilq/baby-python
python
#!/usr/bin/env python """Test for near equality """ import unittest class AlmostEqualTest(unittest.TestCase): def testNotAlmostEqual(self): self.failIfAlmostEqual(1.1, 3.3 - 2.0, places=1) def testAlmostEqual(self): self.failUnlessAlmostEqual(1.1, 3.3 - 2.0, places=0) if __name__ == '__m...
nilq/baby-python
python
import pytest from generalizer import generalize_label test_data = [ ('enter the email associated with your account', 'email'), ('zip code', 'ZIPcode'), ('postal code', 'ZIPcode'), ('first name', 'firstname'), ('last name', 'surname'), ('city', 'city'), ('reference name', 'name'), ('pas...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import sys from json import loads as json_loads from wolframclient.utils import six from wolframclient.utils.encoding import force_text # Python 3.4 and 3.5 json loads only accept str. if sys.version_info[0] == 3 and sy...
nilq/baby-python
python
from csc148_queue import Queue class Tree: """ A bare-bones Tree ADT that identifies the root with the entire tree. """ def __init__(self, value=None, children=None): """ Create Tree self with content value and 0 or more children @param Tree self: this tree @param obj...
nilq/baby-python
python
pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24] def mean(dataset): return sum(dataset) / len(dataset) print(mean(pythonic_machine_ages)) print(sum(pythonic_machine_ages))
nilq/baby-python
python
""" business days module """ from datetime import timedelta, date from collections.abc import Generator import holidays def business_days_list(sdate: date, edate: date) -> list[date]: """ get business days for start and end date inclusive """ days = [] us_holidays = holidays.UnitedStates() for num ...
nilq/baby-python
python
from random import randint from math import hypot, fabs, ceil class AudioSource: def __init__(self, pos, tile): self.pos = pos self.tile = tile def ValidatedMove(self, velocity, map): new_location = {'tile' : [self.tile.pos[0], self.tile.pos[1]], 'position' : [0, 0]} if...
nilq/baby-python
python
* * * * * * * * * * * * * * * * * * PRINT TRIANGLE LOOK LIKE THIS =========================================== for row in range(7): for col in range(7): if(row-col==row)or(row==6)or(row==col): print("*",end=" ") else: ...
nilq/baby-python
python
DEPARTMENTS_MAP = { "che": "Chemical", "che-idd": "Chemical IDD", "cer": "Ceramic", "cer-idd": "Ceramic IDD", "civ": "Civil", "civ-idd": "Civil IDD", "cse": "Computer Science", "cse-idd": "Computer Science IDD", "eee": "Electrical", "eee-idd": "Electrical IDD", "ece": "Electr...
nilq/baby-python
python
# -*- coding: utf-8 -*- __author__ = 'study_sun' from spider_base.downloader import * import sys reload(sys) sys.setdefaultencoding('utf-8') class IndexDownloader(SBDownloader): pass
nilq/baby-python
python
INPUT_IMAGE_WIDTH = 1024
nilq/baby-python
python
##### Imports ##### from datetime import date, datetime import json import dateutil.parser import babel from flask import ( Flask, render_template, request, Response, flash, redirect, url_for) from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_migrate ...
nilq/baby-python
python
#!/usr/bin/env python """ a collection of functions for reading EEG signals and applying basic filtering operations """ import os import scipy.io import numpy as np from scipy.signal import butter, lfilter def butter_lowpass(cutoff, fs, order=5): """ wrapper for calculating parameters of a lowpass filter ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.db import models, migrations import orchestra.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_...
nilq/baby-python
python
raise ValueError("test failed! wrapper did not ignore polluted PWD. either the wrapper is faulty, or ooni is still unpatched (Tor bug #13581)")
nilq/baby-python
python
"""empty message Revision ID: 879fe8a73df4 Revises: 8c3766231a8f Create Date: 2018-06-07 19:56:40.800424 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '879fe8a73df4' down_revision = '8c3766231a8f' branch_labels = None depends_on = None def upgrade(): # ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('peacecorps', '0035_auto_20141202_2354'), ] operations = [ migrations.AddField( model_name='campaign', ...
nilq/baby-python
python
import time from flask import request, jsonify, make_response from app import app from controllers.mock_data import request_method_list, get_mock_data @app.route('/mock/<path:path>', methods=request_method_list) def mock_call(path): try: if not path.startswith('/'): path = "/" + path ...
nilq/baby-python
python
# Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See L...
nilq/baby-python
python
"""Routines for performing spectral unmixing on earth engine images.""" import ee as _ee from tqdm import tqdm as _tqdm from .utils import selectSpectra as _selectSpectra # this function must be run before any of the specific unmixing routines are set def Initialize(sensor, n=30, bands=None): """Initializes sen...
nilq/baby-python
python
from builtins import * import numpy as np import scipy.linalg from scipy.special import gammaln, digamma from bnpy.suffstats import ParamBag, SuffStatBag from bnpy.util import LOGTWO, LOGPI, LOGTWOPI, EPS from bnpy.util import dotATA, dotATB, dotABT from bnpy.util import as1D, as2D, as3D, toCArray from bnpy.util impor...
nilq/baby-python
python
import networkx as nx import operator import matplotlib.pyplot as plt g = nx.read_weighted_edgelist('data/edgelist24.csv') degree = nx.degree(g) numNodes = nx.number_of_nodes(g) numEdges = nx.number_of_edges(g) minDegree = min([item[1] for item in degree]) maxDegree = max([item[1] for item in degree]) print(degree) ...
nilq/baby-python
python
# Copyright 2019 Google LLC # # 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, ...
nilq/baby-python
python
import vcr from .common import * from keepassxc_pwned.cli import main_wrapper from keepassxc_pwned.parser import Database db_file_loc = os.path.join(db_files, "duplicate_entry.kdbx") db_pw = "duplicate_entry" @pytest.fixture() def database(): db: Database = Database(pathlib.Path(db_file_loc)) db._password ...
nilq/baby-python
python
import sys import logging import random import numpy as np import os # from nltk.corpus import wordnet as wn import argparse import torch import pickle from transformers import GPT2Tokenizer, TransfoXLTokenizer from shutil import copyfile import collections from multiprocessing.pool import Pool import multiprocessing ...
nilq/baby-python
python
from keras.models import load_model import cv2 import numpy as np from mtcnn.mtcnn import MTCNN cap = cv2.VideoCapture(0) model = load_model('../model/face-detector-model.h5') size = (200, 200) detector = MTCNN() while True: ret, frame = cap.read() faces = detector.detect_faces(frame) for face in fac...
nilq/baby-python
python
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
nilq/baby-python
python
from mayan.apps.testing.tests.base import BaseTestCase from ..events import event_otp_disabled, event_otp_enabled from .mixins import AuthenticationOTPTestMixin class UserOTPDataTestCase(AuthenticationOTPTestMixin, BaseTestCase): create_test_case_superuser = True def test_method_get_absolute_url(self): ...
nilq/baby-python
python
import xlwings as xw import requests from aruba import Config, switch def vlans(data): """Enumera las VLANs del switch""" # Obtengo el workbook, las coordenadas y la dirección IP del servidor API wb, row, col, api_host = splitExcel(data) # Y ahora, obtengo los datos del switch with switch.sessio...
nilq/baby-python
python
""" module(requirement) - Python依赖. Main members: # check_requirement - 检查依赖. """ from qytPython import logger # 模块与pypi对应关系 module_pypi_config = { 'docx': 'python-docx', 'yaml': 'PyYAML' } def check_requirement(module_obj, module_name): """ 检查依赖. @params: ...
nilq/baby-python
python
import numpy as np # See discussion around this question: https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve/2022348#2022348 def index_of_elbow(points): """Returns the index of the "elbow" in ``points``. Decently fast and pretty approximate. Performs worse with disproporti...
nilq/baby-python
python
from .abstract import * from .. import schema class Lead( ListableAPIResource, MutableAPIResource ): """ Attributes: assessment_run_id (str): ID of the associated assessment run confidence (mage.schema.Confidence): Confidence level of the lead created_at (str): When the lead was created...
nilq/baby-python
python
# Generated by Django 3.1.4 on 2021-01-02 07:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', ...
nilq/baby-python
python
import unittest import numpy as np from svreg.summation import Rho, FFG from tests._testStructs import _all_test_structs, r0 class Test_Summation(unittest.TestCase): def setUp(self): self.ffg = FFG( name='ffg', allElements=['H', 'He'], neighborElements=['H', 'He'], ...
nilq/baby-python
python
from .testing import Tester from .training import Trainer from .dataloader import multiview_dataloader def get_trainer(cfg, net, optimizer, device=None): return Trainer(cfg=cfg, net=net, optimizer=optimizer, device=device) def get_tester(cfg, net, device=None): return Tester(cfg=cfg, net=net, device=device) ...
nilq/baby-python
python
from datetime import timedelta, datetime from django.conf import settings from django.utils.timezone import make_aware import pytz from rest_framework import exceptions from rest_framework.authentication import TokenAuthentication import logging logger = logging.getLogger(__name__) class BearerAuthentication(TokenA...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ hdf5events.py Description: """ # Package Header # from ..__header__ import * # Header # __author__ = __author__ __credits__ = __credits__ __maintainer__ = __maintainer__ __email__ = __email__ # Imports # # Standard Libraries # import datetime import time import uuid ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Module Level Imports # ----------------------------------------------------------------------------- from .typings import ( missing, snowflake, nullable, string, optional, snowflakearray, ...
nilq/baby-python
python
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt class Logger: def __init__(self, cnf): self.dat, self.acc, self.cnf = [], 0, cnf self.path_out = cnf.path_out self.path_out += '/{0}/'.format(self.cnf.log_name) self.pa...
nilq/baby-python
python
import speech_recognition as sr import subprocess from subprocess import call import os import gnk import time os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "//add_credentials" def prepare_date(self): self.response = self.response + self.result[2:18] def prepare_time(self): self.response = self.response + se...
nilq/baby-python
python
'''Checkout how many servers I'm used in!''' import discord from discord.ext import commands from packages.utils import Embed, ImproperType import textwrap import lorem import math from mongoclient import DBClient client = discord.Client class Command(commands.Cog): def __init__(self, client): self.clien...
nilq/baby-python
python
# Copyright 2020 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 script generates header/source files with C++ language bindings # for the X11 protocol and its extensions. The protocol information # is obtained fro...
nilq/baby-python
python
from math import sin, radians #for i in range(100): # r = radians(i) # # print(f" sinus z {i} = {sin(i)}") # print(f" sinus z {r} = {sin(r)}") x = 0 i = 0 while x < 1: i = i + 1 r = radians(i) x = sin(r) print(i,r,x) x = 0 i = 0 while True: i = i + 1 r = radians(i) x = sin(r) i...
nilq/baby-python
python
# Generated by Django 2.2.13 on 2020-06-18 21:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('oidc_provider', '0027_token_refresh_token_expire_at'), ] operations = [ migrations.AddField( model_name='client', n...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayBossRelatedCompanyConsultModel(object): def __init__(self): self._biz_time_in_mills = None self._is_whole_month_valid = None self._type = None self._value = ...
nilq/baby-python
python
from .cprint import aprint, printInfo from .utils import Utils
nilq/baby-python
python
#!/usr/bin/env python # Copyright 2018 Criteo # # 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 agree...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
nilq/baby-python
python
''' Script to check the correctness of the clustering. ''' import unittest import os import numpy as np from pixel_clusterizer.clusterizer import HitClusterizer, default_hits_dtype, default_clusters_dtype, default_clusters_descr, default_cluster_hits_dtype def create_hits(n_hits, max_column, max_row, max_frame, ma...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright CERN since 2022 # # 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 ...
nilq/baby-python
python
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from tests.test_files import html_doc def mocked_requests_get(*args, **kwargs): """this method will be used by the mock to replace requests.get""" class MockResponse: def __init__(self, html, status_code): sel...
nilq/baby-python
python
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories class GoogleComputeIPForward(BaseResourceCheck): def __init__(self): name = "Ensure that IP forwarding is not enabled on Instances" id = "CKV_GCP...
nilq/baby-python
python
import pytest from leapp.exceptions import InvalidTagDefinitionError from leapp.tags import Tag, get_tags, ExperimentalTag, DisabledTag class TestTag(Tag): name = "test-tag" def test_tag_members_correctly_set(): assert hasattr(TestTag, 'Common') and TestTag.Common.name == 'common-test-tag' assert hasat...
nilq/baby-python
python
from django.contrib import admin from .models import name_cat,items_cat from django.db import models from mdeditor.widgets import MDEditorWidget # Register your models here. @admin.register(name_cat) class Name_admin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',)} @admin.register(items_cat) class Ite...
nilq/baby-python
python
import json import os from solc import compile_standard from web3.contract import ConciseContract from web3 import Web3, HTTPProvider OUTPUT_DIR = os.environ['HOME'] + '/plasma-dex/plasma/root_chain/build/contracts' class Deployer(object): def __init__(self, eth_node_endpoint): provider = HTTPProvider(et...
nilq/baby-python
python
# Unit test for bayesnet_inf_autodiff import numpy as onp # original numpy import jax.numpy as np from jax import grad import bayesnet_inf_autodiff as bn # Example from fig 3 of Darwiche'03 paper # Note that we assume 0=False, 1=True so we order the entries differently thetaA = np.array([0.5, 0.5]) # thetaA[a] = P(A...
nilq/baby-python
python
#! /usr/bin/env python #IDN #This node subscribes to the topics which include motor RPM speeds published by arduino analog outputs def wheels2twist(w1,w2,w3,w4): l_x = 0.33 r = 0.0762*2 l_y = 0.33 d=1/(l_x+l_y) I_J = np.array([[ 1, 1, 1, 1 ], [ 1, -1, -1, ...
nilq/baby-python
python
import serial import config from time import sleep config.x = 0 config.y = 0 config.PORT = '/dev/ttyACM0' ser = None def setup(): global ser ser = serial.Serial(config.PORT, 9600, timeout=1) st = serial_read() print(st) def serial_write(s): t = s global ser if ser is None: return "Er...
nilq/baby-python
python
from django.db import models from django.contrib.auth.models import AbstractUser from PIL import Image class User(AbstractUser): is_teacher = models.BooleanField(default=False) is_student = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(ma...
nilq/baby-python
python
from django.urls import reverse from rest_framework.test import APIClient from django.test import TestCase from people.models import Person from owf_groups.models import OwfGroup, OwfGroupPeople requests = APIClient() class GroupsApiTests(TestCase): fixtures = ['resources/fixtures/default_data.json', ]...
nilq/baby-python
python
from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, UserTypeForm, UserDeleteForm from django.contrib.auth.decorators import login_required from functions import find_special_chars # Form for registration page def register(request): ...
nilq/baby-python
python
import os import csv import json import glob import gzip import random import tarfile import zipfile import pandas as pd from .downloader_utils import get_corpora_dict from .downloader_utils import get_resource_dir def _extract_tarfile(filename, target_dir): with tarfile.open(filename, 'r:*') as tar: ta...
nilq/baby-python
python
import argparse try: from . import treedata_pb2 as proto from . import utils except (ValueError, ImportError): import treedata_pb2 as proto import utils import represent_ast as ra class Node: def __init__(self, id, label, position): self.id = id self.label = labe...
nilq/baby-python
python
from setuptools import setup def get_install_requires(): install_requires = [ 'Django>=3,<4', 'django-jsoneditor>0.1,<0.2', ] try: import importlib except ImportError: install_requires.append('importlib') try: from collections import OrderedDict except...
nilq/baby-python
python
""" :py:class:`Model` is an abstract class representing an AllenNLP model. """ import logging import os from typing import Dict, Union, List import numpy import torch from allennlp.common.checks import ConfigurationError from allennlp.common.params import Params from allennlp.common.registrable import Registrable fr...
nilq/baby-python
python
# Importing Specific Items # Fill in the blanks so that the program below prints 90.0. # Do you find this version easier to read than preceding ones? # Why wouldn’t programmers always use this form of import? ____ math import ____, ____ angle = degrees(pi / 2) print(angle)
nilq/baby-python
python
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. 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 required by applicable...
nilq/baby-python
python
from .base import Widget class PasswordInput(Widget): """ This widgets behaves like a TextInput but does not reveal what text is entered. Args: id (str): An identifier for this widget. style (:obj:`Style`): An optional style object. If no style is provided then a new one will be c...
nilq/baby-python
python
import os import alignfaces as af expression = ["an", "ca", "di", "fe", "ha", "ne", "sa", "sp"] mouth = ["o", "c"] databases = [] for ex in expression: for mo in mouth: databases.append("NIM-" + ex + "-" + mo) num_dirs = len(expression) * len(mouth) file_postfixes = ["bmp"] * num_dirs my_project_path = os....
nilq/baby-python
python
import unittest import json from lambda_function import get_user, get_users class TestTwitterUpdates(unittest.TestCase): def test_get_users(self): users_resp = get_users() self.assertEqual(200, users_resp['statusCode']) users = users_resp['body'] self.assertEqual(10, len(users)) self.assertEqua...
nilq/baby-python
python
# Copyright 2015 Google # 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...
nilq/baby-python
python
import cv2 import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from python_util.image_processing.image_stats import get_scaling_factor def load_image_paths(image_list): with open(image_list) as f: image_paths = f.readlines() return [image_path.rstrip() for image_path in image_pa...
nilq/baby-python
python
# Copyright (C) 2019 Intel Corporation. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # import os import subprocess BIOS_INFO_KEY = ['BIOS Information', 'Vendor:', 'Version:', 'Release Date:', 'BIOS Revision:'] BASE_BOARD_KEY = ['Base Board Information', 'Manufacturer:', 'Product Name:', 'Version:']...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # 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, softwa...
nilq/baby-python
python
from arekit.common.experiment.api.enums import BaseDocumentTag from arekit.common.experiment.api.ops_doc import DocumentOperations class CustomDocOperations(DocumentOperations): def iter_tagget_doc_ids(self, tag): assert(isinstance(tag, BaseDocumentTag)) assert(tag == BaseDocumentTag.Annotate) ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from distutils.core import setup """ @author: Kirill Python @contact: https://vk.com/python273 @license Apache License, Version 2.0, see LICENSE file Copyright (C) 2017 """ setup( name='vk_api', version='8.3.1', author='python273', author_email='whoami@p...
nilq/baby-python
python
import pytest import torch from src.defs import layers def test_flatten(): x = torch.arange(12).view(2, 1, 3, 2) print('Before flattening: ', x) print('After flattening: ', layers.flatten(x))
nilq/baby-python
python
#!/usr/bin/env python3 import unittest from typing import Tuple, Union import numpy as np import torch from torch import Tensor from reagent.ope.estimators.types import TypeWrapper, Values class TestTypes(unittest.TestCase): TestType = Union[int, Tuple[int], float, Tuple[float], np.ndarray, Tensor] TestCla...
nilq/baby-python
python
#!/usr/bin/python #TODO Update the line below #Date last updated: 27 Mar 2018 #NO7 Web logs #Software: Microsoft Internet Information Services 7.0 #Version: 1.0 #Date: 2011-12-11 00:00:00 #Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-s...
nilq/baby-python
python
import os import sys import time import argparse import re from tqdm import tqdm from colorama import Fore, Back, Style from google.cloud import translate ''' * @desc load input file function * @param string file_path - input file path and name * @param string split_on - split each line with. Default: "\n" *...
nilq/baby-python
python
# Generated by Django 3.2.3 on 2021-06-01 05:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('reviews', '0003_vote'), ] operations = [ migrations.RemoveField( model_name='project', name='voters', ), ]
nilq/baby-python
python
from flask import render_template, request, jsonify, make_response, url_for, redirect, Blueprint from blueprints.hotdog.static.forms.hotdog_form import FileUploadForm from blueprints.hotdog.model.pretrained_resnet import Hotdog_Model_Resnet from PIL import Image from torch.nn.functional import softmax from torch import...
nilq/baby-python
python
""" Keeps track of configured datastore indexes. """ import json import logging import time from kazoo.client import NoNodeError from kazoo.protocol.states import KazooState from tornado import gen from tornado.ioloop import IOLoop from tornado.locks import Event as AsyncEvent from appscale.common.async_retrying impo...
nilq/baby-python
python