content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import torch import torch.nn as nn class Ensemble(nn.Module): """ Ensemble decoding. Decodes using multiple models simultaneously, Note: Do not use this class directly, use one of the sub classes. """ def __init__(self, models): super(Ensemble, self).__init__() self.mo...
nilq/baby-python
python
# -*- coding: utf-8 -*- from gui.shared.tooltips.module import ModuleTooltipBlockConstructor ModuleTooltipBlockConstructor.MAX_INSTALLED_LIST_LEN = 1000 print '[LOAD_MOD]: [mod_tooltipsCountItemsLimitExtend 1.00 (11-05-2018), by spoter, gox]'
nilq/baby-python
python
from .utils import validator @validator def ipv4(value): """ Return whether or not given value is a valid IP version 4 address. This validator is based on `WTForms IPAddress validator`_ .. _WTForms IPAddress validator: https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py ...
nilq/baby-python
python
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """TC77: Serially accessible digital temperature sensor particularly suited for low cost and small form-factor applications.""" __author__ = "ChISL" __copyright__ = "TBD" __credits__ = ["Microchip"] __license__ = "TBD" __version__ = "0.1" __maintainer__ = "h...
nilq/baby-python
python
file = open('Day 10 input.txt','r') #file = open('Advent-of-Code-2021\\Day 10 testin.txt','r') illegal = [0,0,0,0] completescores = [] for line in file: line = line.strip() illegalflag = False stack = [] for char in line: if ((ord(char) == 40) or (ord(char) == 91) or (ord(char) == 123) or (o...
nilq/baby-python
python
import numpy as np import pyautogui def screenshot(bounds=None): image = pyautogui.screenshot() open_cv_image = np.array(image) open_cv_image = open_cv_image[:, :, ::-1] if bounds is not None: x = bounds[0] y = bounds[1] open_cv_image = open_cv_image[x[0]:x[1], y[0]:y[1]] r...
nilq/baby-python
python
from pathlib import PurePath from typing import Dict, List from lab import util from lab.logger import internal from .indicators import Indicator, Scalar from .writers import Writer class Store: indicators: Dict[str, Indicator] def __init__(self, logger: 'internal.LoggerInternal'): self.values = {} ...
nilq/baby-python
python
#Verilen listenin içindeki elemanları tersine döndüren bir fonksiyon yazın. # Eğer listenin içindeki elemanlar da liste içeriyorsa onların elemanlarını da tersine döndürün. # Örnek olarak: # input: [[1, 2], [3, 4], [5, 6, 7]] # output: [[[7, 6, 5], [4, 3], [2, 1]] liste = [[1, 2], [3, 4], [5, 6, 7]] liste.reverse() ...
nilq/baby-python
python
import discord from discord.ext import commands from typing import Union from CatLampPY import isGuild, hasPermissions, CommandErrorMsg # pylint: disable=import-error class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot self.bot.cmds.append(self.purge) self.bot.cmds.app...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """Low-level feature detection including: Canny, corner Harris, Hough line, Hough circle, good feature to track, etc. """ from __future__ import annotations
nilq/baby-python
python
from dataclasses import dataclass from typing import Optional from pyhcl.core._repr import CType from pyhcl.ir import low_ir @dataclass(eq=False, init=False) class INT(CType): v: int def __init__(self, v: int): self.v = int(v) @property def orR(self): return Bool(not not self.v) c...
nilq/baby-python
python
""" Main Methods are declared here """ from picocv._settings import Settings from picocv.utils.train import Trainer from picocv.utils.augment import DatasetAugmenter def autoCorrect(model_func, dataset_func, settings : Settings): """ Performs Auto Correct Algorithm (Main Method) :param model_func: Function...
nilq/baby-python
python
from .run import wait, load __all__ = ['wait', 'load']
nilq/baby-python
python
# Админка раздел редактор курсов # Энпоинты меню редактора курсов ДШ в тек. уг path_admin_schedules_grade_1 = '/schedules?grade=1&school=true&' path_admin_schedules_grade_2 = '/schedules?grade=2&school=true&' path_admin_schedules_grade_3 = '/schedules?grade=3&school=true&' path_admin_schedules_grade_4 = '/schedules?gra...
nilq/baby-python
python
import os import re import sys sys.path.append(os.path.dirname(__file__)) import nb_file_util as fu class SymbolLister(fu.CellProcessorBase): def calls_sympy_symbol(self): """ if symbol definition line included, return the line numbers and the contents in a list :return: list of dict(...
nilq/baby-python
python
class ParserListener: def update(self, phase, row): """ Called when the parser has parsed a new record. """ pass def handle(self, event, message, groups): """ Called when the parser has parsed a registered event. """ pass def registerKey(self, phase, key)...
nilq/baby-python
python
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (f...
nilq/baby-python
python
def f(x): y = x return f(y) f(0)
nilq/baby-python
python
import os import sys root_path = os.path.abspath("../../../") if root_path not in sys.path: sys.path.append(root_path) import numpy as np import tensorflow as tf from _Dist.NeuralNetworks.DistBase import Base, AutoBase, AutoMeta, DistMixin, DistMeta class LinearSVM(Base): def __init__(self, *args, **kwargs...
nilq/baby-python
python
#!/usr/bin/python # # Copyright 2019 Fortinet Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
nilq/baby-python
python
import sys print("Congratulations on installing Python!", '\n') print("This system is running {}".format(sys.version), '\n') if "conda" in sys.version: print("Hello from Anaconda!") else: print("Hello from system-installed Python!")
nilq/baby-python
python
from collections import defaultdict import re from collections import Counter print("Reactor Reboot") with open("day22/day22_1_input.txt", "r") as f: commands = [entry for entry in f.read().strip().split("\n")] # print(commands) cubeDict = defaultdict(bool) for command in commands: action, cubePositions = ...
nilq/baby-python
python
from .fp16_optimizer import FP16_Optimizer from .fused_adam import FusedAdam
nilq/baby-python
python
""" An audio URL. """ def audio_url(): return 'https://vecsearch-bucket.s3.us-east-2.amazonaws.com/voices/common_voice_en_2.wav'
nilq/baby-python
python
############################################################### # Autogenerated module. Please don't modify. # # Edit according file in protocol_generator/templates instead # ############################################################### from typing import Dict from ...structs.api.offset_fetch_reque...
nilq/baby-python
python
import gym import pybullet as p import pybullet_data import os import numpy as np from gym import spaces # Initial joint angles RESET_VALUES = [ 0.015339807878856412, -1.2931458041875956, 1.0109710760673565, -1.3537670644267164, -0.07158577010132992, .027] # End-effector boundaries BOUNDS_XMI...
nilq/baby-python
python
from discord import Embed async def compose_embed(bot, msg, message): names = { "user_name": msg.author.display_name, "user_icon": msg.author.avatar_url, "channel_name": msg.channel.name, "guild_name": msg.guild.name, "guild_icon": msg.guild.icon_url } if msg.guild ...
nilq/baby-python
python
import time import datetime from haste_storage_client.core import HasteStorageClient, OS_SWIFT_STORAGE, TRASH from haste_storage_client.interestingness_model import RestInterestingnessModel haste_storage_client_config = { 'haste_metadata_server': { # See: https://docs.mongodb.com/manual/reference/connecti...
nilq/baby-python
python
"""Checkmarx CxSAST source up-to-dateness collector.""" from dateutil.parser import parse from collector_utilities.functions import days_ago from collector_utilities.type import Value from source_model import SourceResponses from .base import CxSASTBase class CxSASTSourceUpToDateness(CxSASTBase): """Collector ...
nilq/baby-python
python
#!/usr/bin/env python import argparse import re import sys # Prevent creation of compiled bytecode files sys.dont_write_bytecode = True from core.framework import cli from core.utils.printer import Colors # =================================================================================================...
nilq/baby-python
python
from copy import copy def _rec(arr, n, m): if n < 1: return yield from _rec(arr, n-1, m) for i in range(1,m): arr_loop = copy(arr) arr_loop[n-1] = i yield arr_loop yield from _rec(arr_loop, n-1, m) def main(n, m): arr = [0]*n yield arr yield from _r...
nilq/baby-python
python
___assertEqual(0**17, 0) ___assertEqual(17**0, 1) ___assertEqual(0**0, 1) ___assertEqual(17**1, 17) ___assertEqual(2**10, 1024) ___assertEqual(2**-2, 0.25)
nilq/baby-python
python
from libqtile.backend.x11 import core def test_keys(display): assert "a" in core.get_keys() assert "shift" in core.get_modifiers() def test_no_two_qtiles(manager): try: core.Core(manager.display).finalize() except core.ExistingWMException: pass else: raise Exception("expe...
nilq/baby-python
python
# Copyright (C) 2017-2019 New York University, # University at Buffalo, # Illinois Institute of Technology. # # 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 th...
nilq/baby-python
python
#!/usr/bin/env python3 # author: https://blog.furas.pl # date: 2020.07.08 # import requests import pandas as pd url = "https://www.pokemondb.net/pokedex/all" html = requests.get(url) dfs = pd.read_html(html.text) print( dfs )
nilq/baby-python
python
# # Autogenerated by Thrift Compiler (0.9.3) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TException, TApplicationException import logging from ttypes import * from thrift.Thrift import TProcessor from thrift.transport imp...
nilq/baby-python
python
import random from cocos.actions import Move, CallFunc, Delay from cocos.layer import Layer, director from cocos.sprite import Sprite import cocos.collision_model as CollisionModel from app import gVariables from app.audioManager import SFX class Enemy(Layer): def __init__(self): super(Enemy, self).__init...
nilq/baby-python
python
# SPDX-License-Identifier: Apache-2.0 """ Tests pipeline within pipelines. """ from textwrap import dedent import unittest from io import StringIO import numpy as np import pandas try: from sklearn.compose import ColumnTransformer except ImportError: # not available in 0.19 ColumnTransformer = None try: ...
nilq/baby-python
python
''' Created on 09.10.2017 @author: Henrik Pilz ''' from xml.sax import make_parser from datamodel import Feature, FeatureSet, Mime, OrderDetails, Price, PriceDetails, Product, ProductDetails, Reference, TreatmentClass from exporter.xml.bmecatExporter import BMEcatExporter from importer.xml.bmecatImportHandle...
nilq/baby-python
python
#!/usr/bin/env python3 # Written by Daniel Oaks <daniel@danieloaks.net> # Released under the ISC license import unittest from girc import formatting class FormattingTestCase(unittest.TestCase): """Tests our formatting.""" def setUp(self): errmsg = 'formatting.{} does not exist!' self.assertT...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding: utf-8 -*- # 2017 vby ############################ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 #--------------------------------------------------------------------------------------------------- import sys import os, errno import math import collections import subprocess i...
nilq/baby-python
python
import pandas as pd import numpy as np from trav_lib.data_prep import reduce_memory def test_reduce_memory(): df = pd.DataFrame({'ints':[1,2,3,4],'floats':[.1,.2,.3,.4],'strings':['a','b','c','d']}) df2 = reduce_memory(df) assert df2['ints'].dtype == np.dtype('int8') assert df2['floats'].dtype ...
nilq/baby-python
python
from plotly.graph_objs import Ohlc
nilq/baby-python
python
''' Created on May 28, 2015 @author: local ''' import sys import argparse import logging import subprocess import os import json logging.getLogger("spectrumbrowser").disabled = True def getProjectHome(): command = ['git', 'rev-parse', '--show-toplevel'] p = subprocess.Popen(command, ...
nilq/baby-python
python
import numpy as np import pytest from inspect import currentframe, getframeinfo from pathlib import Path from ..flarelc import FlareLightCurve from ..lcio import from_K2SC_file #example paths: target1 = 'examples/hlsp_k2sc_k2_llc_210951703-c04_kepler_v2_lc.fits' target2 = 'examples/hlsp_k2sc_k2_llc_211119999-c04_ke...
nilq/baby-python
python
# Copyright (c) Niall Asher 2022 from socialserver.util.test import ( test_db, server_address, create_post_with_request, create_user_with_request, create_user_session_with_request ) from socialserver.constants import ErrorCodes import requests def test_get_unliked_post(test_db, server_address): ...
nilq/baby-python
python
import sys import struct """ Takes data from the Android IMU app and turns it into binary data. Data comes in as csv, data points will be turned into the format: Time Stamp Accelerometer Gyroscope x y z x y z ========================================= 0 1 2 3 4 5 ...
nilq/baby-python
python
from Compiler.types import * from Compiler.instructions import * from Compiler.util import tuplify,untuplify from Compiler import instructions,instructions_base,comparison,program import inspect,math import random import collections from Compiler.library import * from Compiler.types_gc import * from operator import i...
nilq/baby-python
python
from flask_app.factory import create_app app = create_app('meeting-scheduler')
nilq/baby-python
python
#!/usr/bin/env python3 import numpy as np class BPTTBatches(object): """Wraps a list of sequences as a contiguous batch iterator. This will iterate over batches of contiguous subsequences of size ``seq_length``. TODO: elaborate Example: .. code-block:: python # Dictionary # Se...
nilq/baby-python
python
# A module to make your error messages less scary import sys from characters import AsciiCharacter def output_ascii(err_message="You certainly messed something up."): one_line = False err_line_1 = err_message.split('--')[0] try: err_line_2 = err_message.split('--')[1] except: on...
nilq/baby-python
python
from keras.preprocessing.image import load_img, img_to_array target_image_path = 'img/a.jpg' style_image_path = 'img/a.png' width, height = load_img(target_image_path).size img_height = 400 img_width = int(width * img_height / height) import numpy as np from keras.applications import vgg19 def preproces...
nilq/baby-python
python
#!/usr/bin/python # -*- coding: utf-8 -*-  class Demo(object): __x = 0 def __init__(self, i): self.__i = i Demo.__x += 1 def __str__(self): return str(self.__i) def hello(self): print("hello " + self.__str__()) @classmethod def getX(cls): return cls.__...
nilq/baby-python
python
import abc from typing import Callable from typing import Iterator from typing import List from typing import Optional from xsdata.codegen.models import Class from xsdata.models.config import GeneratorConfig from xsdata.utils.constants import return_true class ContainerInterface(metaclass=abc.ABCMeta): """Wrap a...
nilq/baby-python
python
#testing the concept import re #file_name = raw_input("Enter textfile name (ex. hamlet.txt): ") def app(f_name): fd = open(f_name, 'r') fd = fd.read() lines = fd.split('\n') c1 = 0 while(c1 < len(lines)): #lines[c1] = re.sub('[^0-9a-zA-Z]+', '', lines[c1]) if len(lines[c1]) == 0: ...
nilq/baby-python
python
import pytest import os, time import sys from datetime import date, datetime from pytest_html_reporter.template import html_template from pytest_html_reporter.time_converter import time_converter from os.path import isfile, join import json import glob from collections import Counter from PIL import Image from io impor...
nilq/baby-python
python
import datetime import logging import time import googleapiclient class TaskList: def __init__(self, id): self.id = id self.tasks = [] def update(self, service): try: results = service.tasks().list(tasklist = self.id, showCompleted = False, dueMax = rfc3339_today_midnight()).execute() except...
nilq/baby-python
python
from datetime import * from dateutil.relativedelta import * now = datetime.now() print(now) now = now + relativedelta(months=1, weeks=1, hour=10) print(now)
nilq/baby-python
python
FLASK_HOST = '0.0.0.0' FLASK_PORT = 5000 FLASK_DEBUG = False FLASK_THREADED = True import os ENV_SETUP = os.getenv('MONGO_DATABASE', None) is not None MONGO_DATABASE = os.getenv('MONGO_DATABASE', 'avoid_kuvid') MONGO_ROOT_USERNAME = os.getenv('MONGO_ROOT_USERNAME', 'admin') MONGO_ROOT_PASSWORD = os.getenv('MONGO_ROOT_...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @Author: Marc-Antoine # @Date: 2019-03-17 17:18:42 # @Last Modified by: Marc-Antoine Belanger # @Last Modified time: 2019-03-17 17:20:31 from gym.envs.registration import register register( id='cribbage-v0', entry_point='gym_cribbage.envs:CribbageEnv', )
nilq/baby-python
python
# coding:utf-8 # 2019/9/3 """ 给定一个整数的数组,找出其中的pair(a, b),使得a+b=0,并返回这样的pair数目。(a, b)和(b, a)是同一组。 输入 整数数组 输出 找到的pair数目 样例输入 -1, 2, 4, 5, -2 样例输出 1 """ def solver(nums): maps = {} ret = 0 retList = [] for n in nums: if n in maps: if maps[n] == 1: if n no...
nilq/baby-python
python
class UserErrorMessage(object): OPERATION_NOT_SUPPORTED = "Operation is not supported." NO_MODEL_PUBLISHED = "No model published for the current API." NO_ENDPOINT_PUBLISHED = "No service endpoint published in the current API." NO_OPERATION_PUBLISHED = "No operation published in the current API." CAN...
nilq/baby-python
python
# -*- encoding: utf-8 -*- from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import Http404, HttpResponse from django.shortcuts import render, get_object_or_404, redirect from accounts....
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 from xumm.resource import XummResource from typing import List class UserTokenValidity(XummResource): """ Attributes: model_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is a...
nilq/baby-python
python
#!/usr/bin/python import unittest import GT3 from tests.ShotBase import * from matplotlib.axes._axes import Axes from matplotlib.pyplot import Figure class CommonFunctions(object): """Tests to see if a shot has the expected attributes typical for a fully run shot.""" def test_gt3_has_core(cls): cls....
nilq/baby-python
python
import datetime def current_year(): """current_year This method used to get the current year """ return datetime.date.today().year
nilq/baby-python
python
import streamlit as st import pandas as pd st.title("File uploader example") st.write( """ This is an example of how to use a file uploader. Here, we are simply going to upload a CSV file and display it. It should serve as a minimal example for you to jump off and do more complex things. """ ) st.header("Upload...
nilq/baby-python
python
""" ASGI config for scheduler project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ from os import environ from django.core.asgi import get_asgi_application # type: ignore envi...
nilq/baby-python
python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import json import datetime import time import os import boto3 from datetime import timedelta import random # Tries to find an existing or free game session and return the IP and Port to the client def lambda_handle...
nilq/baby-python
python
import anachronos from test.runner import http class PingTest(anachronos.TestCase): def test_ping(self): res = http.get("/ping") self.assertEqual(200, res.status_code) self.assertEqual("Pong!", res.text)
nilq/baby-python
python
from setuptools import setup setup( name="minigit", version="1.0", packages=["minigit"], entry_points={"console_scripts": ["minigit = minigit.cli:main"]}, )
nilq/baby-python
python
__author__ = 'cvl' class Domain_model(): def __init__(self, json_dict): self.free_domains = json_dict['free_domains'] self.paid_domains = json_dict['paid_domains']
nilq/baby-python
python
import pandas as pd class CurrentPositionStatusSettler: def __init__(self, calculation_source): self.__calculation_source = calculation_source def settle_current_position_status(self) -> pd.DataFrame: self.__calculation_source = self.__calculation_source[ ~self.__calculat...
nilq/baby-python
python
''' Stanle Bak Python F-16 Thrust function ''' import numpy as np import tensorflow as tf from util import fix, fix_tf def thrust(power, alt, rmach): 'thrust lookup-table version' a = np.array([[1060, 670, 880, 1140, 1500, 1860], \ [635, 425, 690, 1010, 1330, 1700], \ [60, 25, 345, 755, 1130...
nilq/baby-python
python
from datetime import date nascimento = int(input('qual o ano do seu nascimento: ')) anoatual = date.today().year idade = anoatual - nascimento if idade <= 9: print('VocÊ tem {} anos, sua categoria é Mirim'.format(idade)) elif idade <= 14 and idade > 9: print('Você tem {} anos, sua categoria é Infantil'.format(i...
nilq/baby-python
python
# coding=utf-8 class Human(object): def __init__(self, input_gender): self.gender = input_gender def printGender(self): print self.gender li_lei = Human('male') # 这里,'male'作为参数传递给__init__()方法的input_gender变量。 print li_lei.gender #这一行结果与下一行对比 li_lei.printGender() #这一行结果与上一行对比
nilq/baby-python
python
from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, FullGrad from pytorch_grad_cam.utils.model_targets import ClassifierOutputTarget from pytorch_grad_cam.utils.image import show_cam_on_image from torchvision.models import resnet50 import torch model = resnet50(pretrained=...
nilq/baby-python
python
#!/usr/bin/env python3 from email.message import EmailMessage import smtplib, ssl import getpass message = EmailMessage() sender = "me@example.com" recipient = "youw@example.com" message['From'] = sender message['To'] = recipient message['Subject'] = 'Greetings from {} to {}!'.format(sender, recipient) body = """H...
nilq/baby-python
python
# Copyright 2020 The TensorFlow Probability 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 applicable law o...
nilq/baby-python
python
import os import sys import math import json import numpy as np from pycocotools.coco import COCO import pickle sys.path.insert(0,'..' ) from config import cfg COCO_TO_OURS = [0, 15, 14, 17, 16, 5, 2, 6, 3, 7, 4, 11, 8, 12, 9, 13, 10] def processing(ann_path, filelist_path, masklist_path, json_path, mask_dir): ...
nilq/baby-python
python
# Copyright 2017 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. SPEC = { 'settings': { 'build_gs_bucket': 'chromium-v8', # WARNING: src-side runtest.py is only tested with chromium CQ builders. # Usage not c...
nilq/baby-python
python
# Copyright (c) 2015 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import sys import rosunit from mock import patch from parameterized import parameterized, param from fiware_ros_bridge.logging import getLogger class TestGetLogger(unittest.TestCase): @parameterized.expand([ param(logm='debugf', rosm='logd...
nilq/baby-python
python
from sims4.tuning.tunable import HasTunableSingletonFactory, AutoFactoryInit, OptionalTunable, TunableVariant from ui.ui_dialog import UiDialogOk, UiDialogOkCancel import enum import services class SituationTravelRequestType(enum.Int): ALLOW = ... CAREER_EVENT = ... DISALLOW = ... class _SituationTravelRe...
nilq/baby-python
python
""" Intersecting Linked Lists Given two singly linked lists that intersect at some point, find the intersecting node. The lists are non-cyclical. In this example, assume nodes with the same value are the exact same node objects. Input: 3 -> 7 -> 8 -> 10, 99 -> 1 -> 8 -> 10 Output: 8 =================================...
nilq/baby-python
python
from setuptools import setup from torch.utils.cpp_extension import CUDAExtension, BuildExtension setup(name='syncbn_gpu', ext_modules=[CUDAExtension('syncbn_gpu', ['syncbn_cuda.cpp', 'syncbn_cuda_kernel.cu'])], cmdclass={'build_ext': BuildExtension})
nilq/baby-python
python
# -*- coding: utf-8 -*- class MetadataError(Exception): pass class CopyError(RuntimeError): pass def err_contains_group(path): raise ValueError('path %r contains a group' % path) def err_contains_array(path): raise ValueError('path %r contains an array' % path) def err_array_not_found(path): ...
nilq/baby-python
python
#Write a function to swap a number in place( that is, without temporary variables) #Hint 491: Try picturing the two numbers, a and b, on a number #Hint 715: Lef diff be the difference betweeen a and b. Can you use diff some way? Then can you get rid of this temporary variable. #Hint 736: You could also try to using XO...
nilq/baby-python
python
msg = ['We see immediately that one needs little information to begin to break down the process.','An enciphering-deciphering machine (in general outline) of my invention has been sent to your organization.','The significance of this general conjecture, assuming its truth, is easy to see. It means that it may be feasib...
nilq/baby-python
python
""" Sazonov, S. Yu., Ostriker, J. P., & Sunyaev, R. A. 2004, MNRAS, 347, 144 """ import numpy as np # Parameters for the Sazonov & Ostriker AGN template _Alpha = 0.24 _Beta = 1.60 _Gamma = 1.06 _E_1 = 83e3 _K = 0.0041 _E_0 = (_Beta - _Alpha) * _E_1 _A = np.exp(2e3 / _E_1) * 2e3**_Alpha _B = ((_E_0**(_Beta - _Alpha)) ...
nilq/baby-python
python
import sympy as sp import numpy as np import pickle class SymbolicRateMatrixArrhenius(sp.Matrix): """ Symbolic representation of Arrhenius process rate matrix. """ class Symbols: @classmethod def _barrier_element_symbol(cls, i, j): if i == j: return 0 ...
nilq/baby-python
python
"""Author: Brandon Trabucco. Very the installation of GloVe is function. """ import glove config = glove.configuration.Configuration( embedding=50, filedir="./embeddings/", length=127, start_word="</StArT/>", end_word="</StoP/>", unk_word="</UnKnOwN/>") vocab, embeddings = glove.load(confi...
nilq/baby-python
python
# -*- coding: utf-8 -*- ''' 程序思想: 有两个本地语音库,美音库Speech_US,英音库Speech_US 调用有道api,获取语音MP3,存入对应的语音库中 主要接口: word_pronounce() 单词发音 multi_thread_download() 单词发音的批量多线程下载 ''' import urllib.request from concurrent.futures import ThreadPoolExecutor import os from playsound import playsound class pronounciation(): def __init...
nilq/baby-python
python
# ********************************************************************** # Copyright (C) 2020 Johns Hopkins University Applied Physics Laboratory # # All Rights Reserved. # For any other permission, please contact the Legal Office at JHU/APL. # **********************************************************************...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Jun 29 23:33:28 2020 @author: abhi0 """ class Solution: def plusOne(self, digits: List[int]) -> List[int]: tempTilda='' for i in digits: tempTilda=tempTilda+str(i) temp=re.split('',tempTilda) ...
nilq/baby-python
python
from unyt import unyt_array, unyt_quantity from astropy.units import Quantity import logging from more_itertools import always_iterable import numpy as np pyxsimLogger = logging.getLogger("pyxsim") ufstring = "%(name)-3s : [%(levelname)-9s] %(asctime)s %(message)s" cfstring = "%(name)-3s : [%(levelname)-18s] %(asctim...
nilq/baby-python
python
import PIL from PIL import Image, ImageOps, ImageEnhance import numpy as np import sys import os, cv2 import csv import pandas as pd myDir = "..\GujOCR\Output" #Useful function def createFileList(myDir, format='.png'): fileList = [] print(myDir) for root, dirs, files in os.walk(myDir, topdown=Fa...
nilq/baby-python
python
from __future__ import unicode_literals import frappe import re def execute(): for srl in frappe.get_all('Salary Slip',['name']): if srl.get("name"): substring = re.search("\/(.*?)\/",srl.get("name")).group(1) emp = frappe.db.get_value('Employee',{'name':substring},'user_id') ...
nilq/baby-python
python
# coding: utf-8 r"""timeout decorators for Windows and Linux Beware that the Windows and the Linux decorator versions do not raise the same exception if the timeout is exceeded """ import platform # import errno # import os import signal import multiprocessing import multiprocessing.pool from functools import wrap...
nilq/baby-python
python
import argparse import calendar import dotenv import json import libraries.api import libraries.handle_file import libraries.record import logging import logging.config import os import pandas as pd import requests import time from csv import writer from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredErro...
nilq/baby-python
python