content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import time import pytest import examples import progressbar import original_examples def test_examples(monkeypatch): for example in examples.examples: try: example() except ValueError: pass @pytest.mark.filterwarnings('ignore:.*maxval.*:DeprecationWarning') @pytest.mark...
nilq/baby-python
python
from .default import Config class DevelopmentConfig(Config): """ Configurations for Development. """ DEBUG = True TESTING = True SECRET = "DevelopSecret123!!" # pragma: allowlist secret
nilq/baby-python
python
import numpy as np NUM_EXP = 1 def evaluate(job_id, params): np.random.seed(NUM_EXP) x = params['X'] y = params['Y'] z = params['Z'] a = params['A'] #print 'Evaluating at (%f, %f, %f, %f)' % (x, y, z, a) obj1 = float(1.10471 * np.power(x,2.0) * z + 0.04811 * a * y * (14.0+z)) + np.rand...
nilq/baby-python
python
class Config: HOST_URL = "https://www.mirrativ.com" USER_AGENT = "MR_APP/8.67.0/Android/GA00747-UK/5.1.1" USER_ME = "/api/user/me" PROFILE_EDIT = "/api/user/profile_edit" FOLLOW = "/api/graph/follow" COMMENT = "/api/live/live_comment" LIVE = "/api/live/live" EDIT_LIVE = "/api/li...
nilq/baby-python
python
import os import torch import numpy as np import pickle from utils import * def hook_fn(m, i, o): try: visualisation[m] = o.cpu().numpy() except AttributeError: visualisation[m] = o[0].cpu().numpy() if __name__=='__main__': with open('./results/cka/act_std.pkl', 'rb') as file: ...
nilq/baby-python
python
# https://leetcode.com/problems/subsets-ii/description/ # # algorithms # Medium (40.24%) # Total Accepted: 173.2K # Total Submissions: 430.4K # beats 100.0% of python submissions class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] ...
nilq/baby-python
python
""" retrieve environment variables and resolve references to AWS Parameter Store Parameters. """ from typing import Dict import os import boto3 def get(name: str, session: boto3.session.Session) -> str: """ gets the environment variable value specified by `name`. if the `value` starts with ssm://, it will...
nilq/baby-python
python
""" A repository of typed entities, retrievable by their external reference Entity object API: entity.entity_type --> string used for groupung entity.external_ref --> lookup name entity.origin --> one-time settable parameter, set by the entity store entity.validate() --> must return True [for valid enti...
nilq/baby-python
python
import bpy from bpy.props import * from ..node_socket import RenderNodeSocket, SocketBase, RenderNodeSocketmixin, RenderNodeSocketInterface from ..node_socket import update_node class RenderNodeSocketInterfaceRenderList(RenderNodeSocketmixin, RenderNodeSocketInterface, bpy.ty...
nilq/baby-python
python
import ocaml assert(ocaml.Result.get_ok(ocaml.Result.Ok(True)) == True)
nilq/baby-python
python
from opera.parser.yaml.node import Node from ..entity import Entity from ..path import Path from ..string import String class ImportDefinition(Entity): ATTRS = dict( file=Path, repository=String, namespace_prefix=String, namespace_uri=String, ) DEPRECATED = { "name...
nilq/baby-python
python
#online = mongodb_online() #print('mongodb-online: ', online) #TODO: cron docker para mongo
nilq/baby-python
python
# -*- coding: utf-8 -*- import json from django.db.models import Q from rest_framework.exceptions import PermissionDenied from rest_framework.generics import ( CreateAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from rest_framework.permissions import ( AllowAny, I...
nilq/baby-python
python
from django.contrib import admin # Register your models here. from reg.models import UserProfile from .models import * class BookAuthorAdmin(admin.ModelAdmin): list_display = ('author_last_name', 'author_first_name', 'author_middle_name') search_fields = ('author_last_name', 'author_first_name', 'author_middle_name...
nilq/baby-python
python
import numpy as np class ArgMaxPolicy(object): def __init__(self, critic): self.critic = critic def get_action(self, obs): if len(obs.shape) > 3: observation = obs else: observation = obs[None] ## TODO return the action that maxinmizes the Q-v...
nilq/baby-python
python
# coding: utf-8 """ DocuSign REST API The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. OpenAPI spec version: v2 Contact: devcenter@docusign.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from ppr...
nilq/baby-python
python
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys import json import argparse from modules.FIC_Core import FICCore from modules.config import DEFAULT_DAYS, REP...
nilq/baby-python
python
from django import forms from django.contrib.admin import widgets import os CHOICE = { ('0','キュート'), ('1','クール'), ('2','パッション'), } form SampleForm(forms.Form): select = forms.ChoiceField(label='属性', widget=forms.RadioSelect, choices= CHOICE, initial=0)
nilq/baby-python
python
L=[[[*map(int,v.split(','))]for v in l.split('->')]for l in open("inputday5")] r,m=lambda n,x,y:x<=n<=y or y<=n<=x,max(max(max(p)for p in l)for l in L)+1 c=lambda a,b,f,s,w:(r(a,f[0],s[0])and r(b,f[1],s[1])and(f[0]==s[0]or f[1]==s[1]or(w and abs(f[0]-a)==abs(f[1]-b)))) print(*(sum(a)for a in((sum(c(i,j,f,s,b)for f,s in...
nilq/baby-python
python
# Filename: HCm_UV_v5.0.py ##################### ###### IMPORTS ###### ##################### import string import numpy as np import sys #sys.stderr = open('errorlog.txt', 'w') import warnings warnings.filterwarnings("ignore") ####################### ###### FUNCTIONS ###### ####################### #Function for int...
nilq/baby-python
python
__all__ = [ 'apply', 'applyCSS', 'change', 'changeCSS', 'delete', 'forwarddelete', 'insert', 'queryEnabled', 'queryIndeterm', 'queryState', 'querySupported', 'queryValue', 'selection', 'unapply', 'unapplyCSS' ]
nilq/baby-python
python
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
nilq/baby-python
python
from Application import Application if __name__ == '__main__': app = Application()
nilq/baby-python
python
# determines whether a matrix is orthogonal. A square matrix is orthogonal, # if its columns and rows are orthogonal unit vectors, # which is equivalent to: MT M = I import numpy as np def check_orthogonal(M): # make sure the input is a matrix if len(np.shape(M)) !=2: print("error: input is not a mat...
nilq/baby-python
python
""" 抽象工厂 代码实例 Abstract Factory Code Demo 家具工厂 """ from __future__ import annotations from abc import ABC, abstractmethod class Chair(ABC): """ product interface 1: Chair """ @abstractmethod def sit_on(self) -> str: pass class Sofa(ABC): """ product interface 2: Sofa """ ...
nilq/baby-python
python
import requests import time import datetime import json import csv # def get(t): # res_text=requests.get('http://nufm.dfcfw.com/EM_Finance2014NumericApplication/JS.aspx?type=CT&cmd=0000011,3990012&sty=CTBFTA&st=z&sr=&p=&ps=&cb=&token=70f12f2f4f091e459a279469fe49eca5').text # data=eval(res_text) # dh=data[0...
nilq/baby-python
python
import socket from socket import * from win32clipboard import * from win32con import * print "ClipCross Alpha" host = "" #Accept connection from any machine. port = 6000 #We will communicate over port 6000 of this machine. Ports 0-1024 are restricted, ports 1025-65535 are n...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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, Dict, List, Mapping, Optional, Tuple, Union from .. import ...
nilq/baby-python
python
import logging from pkg_resources import DistributionNotFound, get_distribution from feast.infra.offline_stores.bigquery_source import BigQuerySource from feast.infra.offline_stores.contrib.spark_offline_store.spark_source import ( SparkSource, ) from feast.infra.offline_stores.file_source import FileSource from ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Sun Apr 8 10:41:43 2018 @author: Haosong """ import sys sys.path.append("C:\\CSCI1001_Project\\PrepareData.py") # Replace the thing in the braces above with the current path PrepareData.py is in import PrepareData PrepareData.prepareData()
nilq/baby-python
python
from django.shortcuts import render, get_object_or_404, redirect from rest_framework.views import APIView from rest_framework.response import Response import json from .functions import classify_passenger, load_model class get_classification(APIView): def post(self, request): model = load_model('./api/titanic_...
nilq/baby-python
python
# -*-coding:utf-8-*- from mobpush.model.BasePush import BasePush class IosNotify(BasePush): serialVersionUID = 6316980682876425791 BADGE_TYPE_SET = 1 BADGE_TYPE_ADD = 2 SLIENT = 1 def __init__(self, title=None, subtitle=None, attachment=None, attachmentType=None, mutableContent=N...
nilq/baby-python
python
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from itsdangerous import URLSafeSerializer as URLSafeSerializer def generate_auth_token(secret_key, username, password): serializer = Serializer(secret_key, expires_in=15000) token = serializer.dumps({'username': username, "password": pass...
nilq/baby-python
python
import mlflow from threading import Thread import os import time from sapsan.core.models import ExperimentBackend class MLflowBackend(ExperimentBackend): def __init__(self, name: str = 'experiment', host: str = 'localhost', port: int = 9000): super().__init_...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright 2019 HTCondor Team, Computer Sciences Department, # University of Wisconsin-Madison, WI. # # 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....
nilq/baby-python
python
from core.buckets import BucketExtend from core.sampler import Sampler class LowDiscrepancySampler(Sampler): def __init__(self, bucket_extend: BucketExtend, samples_count: int, shutterOpen: float, shutterClose: float): super().__init__(bucket_extend, samples_count, shutterOpen, shutterClose) ...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 # In[2]: from pathlib import Path import numpy as np import pandas as pd train = pd.read_csv("corpus/imdb/labeledTrainData.tsv", header=0, delimiter="\t", quoting=3) test = pd.read_csv("corpus/imdb/testData.tsv", header=0, delimiter="\t",...
nilq/baby-python
python
# Available debug categories. DEBUG_CATEGORIES = { 'architects': False, 'callbacks': False, 'controllers': False, 'drivers': False, 'emitters': False, 'imap': False, 'managers': False, 'workers': False, 'all': False, } # Default categories for the 'all' keyword. DEBUG_ALL_CATE...
nilq/baby-python
python
class Solution: def sortColors(self, nums): return nums.sort() if __name__ == '__main__': nums = [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] print("Before Sort: ") print(nums) # [0, 1, 2, 2, 1, 1, 2, 2, 0, 0, 0, 0, 2, 1] Solution().sortColors(nums) print("After Sort: ") print(n...
nilq/baby-python
python
#!/usr/bin/env python3 """ Check Lisp examples in a Markdown file. To run (assuming this repo is a submodule in a dir called .cl-make): $ pip3 install -r .cl-make/requirements.txt $ .cl-make/readme.py README.md The return code is zero iff all Lisp examples in the file run without errors in an SBCL REPL and ...
nilq/baby-python
python
#!/usr/bin/python import serial import time import sys if len(sys.argv) != 2: print "Usage: %s <serial port>" % sys.argv[0] sys.exit() def getResponse(): time.sleep(0.25) s = ser.readline() print "RECV: " print s if "NMI:" in s: print "NMI signal received" #sys.exit() ...
nilq/baby-python
python
import cfscrape from flask import request from flask_restplus import Resource, Namespace, fields, abort from Servers.AnimeFLV.scraper import getList, scrapeEpisodeList, scrapeEpisode, scrapeGenre, scrapeGenreList, scrapeFeed, scrapeLastAnimeAdded cfscraper = cfscrape.create_scraper(delay=10) animeflv_api = Namespace(...
nilq/baby-python
python
from threading import Lock from twisted.internet import protocol, reactor class ClientProtocol(protocol.Protocol): def dataReceived(self, data): self.server_protocol.transport.write(data) def connectionLost(self, reason): self.server_protocol.transport.loseConnection() class ClientFactory(...
nilq/baby-python
python
from pathlib import Path from collections import defaultdict import sys TEST_MODE = bool(len(sys.argv) > 1 and sys.argv[1] == "test") CARD = ['E', 'S', 'W', 'N'] DIRECTIONS = [(1,0),(0,1),(-1,0),(0,-1)] ROTATIONS = [(1,0,0,1),(0,-1,1,0),(-1,0,0,-1),(0,1,-1,0)] def phase1(data): pos = [0,0] facing = 0 for...
nilq/baby-python
python
import pytest from rotkehlchen.tests.utils.ethereum import ETHEREUM_TEST_PARAMETERS @pytest.mark.parametrize(*ETHEREUM_TEST_PARAMETERS) def test_get_block_by_number(ethereum_manager): block = ethereum_manager.get_block_by_number(10304885) assert block['timestamp'] == 1592686213 assert block['number'] == ...
nilq/baby-python
python
# Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved. import os import random import numpy as np import torch def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) os.environ['PYT...
nilq/baby-python
python
# Copyright 2006-2012 Mark Diekhans import re from pycbio.hgdata.autoSql import intArraySplit, intArrayJoin, strArraySplit, strArrayJoin from pycbio.tsv.tabFile import TabFileReader from pycbio.hgdata import dnaOps from pycbio.hgdata.cigar import ExonerateCigar from collections import defaultdict from deprecation impor...
nilq/baby-python
python
from pydantic import BaseSettings class Settings(BaseSettings): MONGO_URI: str = "mongodb://localhost:27017/" APP_DB: str = "ultraapp" JWT_SECRET: str = "S3CR3T" # jwt secret JWT_LIFETIME: int = 3600 * 24 settings = Settings()
nilq/baby-python
python
import time from typing import List class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if not stack: stack.append(token) if token in {'+', '-', '*', '/'}: y = stack.pop() x = stack.pop...
nilq/baby-python
python
""" Create an OpenVINO model package to upload to Azure Blob Storage and use IoT Hub module update twin to update the Azure Percept AzureEyeModule. """ import argparse import os import json import zipfile import datetime from azure.storage.blob import ( BlockBlobService, BlobPermissions, ) from azure.iot.hub im...
nilq/baby-python
python
EPSILON = 0 UNICODE_LATIN_START = 32 UNICODE_LATIN_END = 127 SEEK_RULE = 1 SEEK_RULE_NAME = 2 SEEK_ST_COLON = 3 SEEK_ND_COLON = 4 SEEK_EQUALS = 5 SEEK_ST_PROD = 6 SEEK_ST_TERM = 7 SEEK_ST_NTERM = 8 SEEK_ST_ESC = 9 SEEK_PROD = 10 SEEK_TERM = 11 SEEK_NTERM = 12 SEEK_ESC = 13 SEEK_SPECIAL_TERM = 14 SEEK_SPECIAL_NTERM = ...
nilq/baby-python
python
''' Script to do analysis ''' import argparse import logging import time import torch import transformers import itertools from collections import defaultdict from models import MTModel # Use with care: logging error only while printing analysis for reading sanity transformers.utils.logging.set_verbosity_error() de...
nilq/baby-python
python
from __future__ import annotations import numpy as np from PySide2.QtCore import QPoint, QRect from PySide2.QtWidgets import QMdiSubWindow class DataViewerSubWindow(QMdiSubWindow): def __init__(self, viewer: DataViewer): super().__init__() self.viewer = viewer self.layout_anchors = None...
nilq/baby-python
python
class AMQPError(Exception): message = 'An unspecified AMQP error has occurred: %s' def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self.message % self.args) # Backward compatibility AMQPException = AMQPError class AMQPConnectionError(AMQPError): message = 'Connection can not ...
nilq/baby-python
python
import sys import time from collections import deque from datetime import timedelta from rich import get_console from rich.progress import BarColumn, Progress, ProgressColumn, SpinnerColumn, TextColumn class TimeRemainingColumn(ProgressColumn): """Renders estimated time remaining.""" # Only refresh twice a ...
nilq/baby-python
python
import arcpy arcpy.env.overwriteOutput = True # Note: Script assumes data from Pro SDK community samples are installed under C:\Data, as follows: inFC = r"E:\GISTech\2021\ProProjects\PythonUsage\PythonUsage.gdb\FCL_Lijn" outFC = r"E:\GISTech\2021\ProProjects\PythonUsage\PythonUsage.gdb\ViaScript" # Buffer the input f...
nilq/baby-python
python
# -*- coding: utf-8 -*- from bitshares import BitShares from bitshares.instance import set_shared_bitshares_instance from bitshares.amount import Amount from bitshares.price import Price from bitshares.asset import Asset import unittest class Testcases(unittest.TestCase): def __init__(self, *args, **kwargs): ...
nilq/baby-python
python
from ._version import VERSION from ._chat_client import ChatClient from ._chat_thread_client import ChatThreadClient from ._generated.models import ( SendChatMessageResult, ChatThreadInfo, ChatMessageType ) from ._shared.user_credential import CommunicationTokenCredential from ._shared.user_token_refresh_op...
nilq/baby-python
python
from django.test import TestCase from wagtailmenus.conf import constants from wagtailmenus.models import MainMenu from wagtailmenus.tests import base, utils Page = utils.get_page_model() class MainMenuTestCase(TestCase): """A base TestCase class for testing MainMenu model class methods""" fixtures = ['test...
nilq/baby-python
python
""" Receba a altura do degrau de uma escada e a altura que o usuário deseja alcançar subindo a escada. Calcule e mostre quantos degraus o usuário deverá subir para atingir o seu objetivo. """ a = float(input('Qual é a altura do degrau da escada (cm)? ')) ab = float(input('Qual é a altura que você deseja alcançar subin...
nilq/baby-python
python
import numpy as np from netCDF4 import Dataset from .utils import popEntries,setDimensions from .OBSstruct import OBSstruct import pandas as pd def remove_duplicates(S, coordinate = 'fractional'): ''' This function identifies duplicated observations and makes sure all observation on output are unique. ...
nilq/baby-python
python
import matplotlib.pyplot as plt import csv import random import numpy as np import math import matplotlib.patches as patches data = {} with open('datasets/data_boston.csv', 'r') as csvfile: csvfile.readline() file = csv.reader(csvfile, delimiter=',') for row in file: if data.has_key(row[5]): data[row[5]].appe...
nilq/baby-python
python
#!/usr/bin/python #coding:utf-8 import os import re import string import linecache import shutil #Get file name from given directory directoryPath = os.getcwd() #directoryPath2 = os.getcwd() + '\\New' file_extension = ".md" if __name__ == '__main__': for fileName in os.listdir(directoryPath): if(fileName...
nilq/baby-python
python
from .point_cloud import PointCloud, PointCloudMeta, PointCloudSpatial # noqa
nilq/baby-python
python
def empty_graph(n): res = [] for i in range(n): res.append([0]*n) return res def convert(graph): matrix = [] for i in range(len(graph)): matrix.append([0]*len(graph)) for j in graph[i]: matrix[i][j] = 1 return matrix def prims_algo(graph): graph1 = conver...
nilq/baby-python
python
# # customization fragment to run L1 GT emulator starting from a RAW file # # V.M. Ghete 2010-06-09 import FWCore.ParameterSet.Config as cms def customise(process): # # (re-)run the L1 GT emulator starting from a RAW file # from L1Trigger.Configuration.L1Trigger_custom import customiseL1GtEmulat...
nilq/baby-python
python
""" Overview: Useful functions for build representation format of object. """ from typing import List, Tuple __all__ = [ 'get_repr_info', ] def get_repr_info(cls: type, args: List[Tuple]) -> str: """ Overview: Get representation information for object. Can be used in ``__repr__`` meth...
nilq/baby-python
python
# -*- Mode: Python; tab-width: 4 -*- # Copyright (c) 2005-2010 Slide, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyrig...
nilq/baby-python
python
from bnop_source.b_code.bnop_facades import BnopFacades from bnop_source.b_code.core.object_model.bnop_repositories import BnopRepositories from bnop_source.b_code.core.object_model.objects.bnop_objects import BnopObjects from boro_common_source.ckids.boro_object_ckids import BoroObjectCkIds from nf_common_source.code....
nilq/baby-python
python
""" Unit tests for flat_file.py See: https://code.visualstudio.com/docs/python/testing """ import unittest from cred_manage.flat_file import FlatFileCredContainer import os FLAT_FILE_THAT_EXISTS='/tmp/file_that_exist.txt' FLAT_FILE_THAT_DOES_NOT_EXIST='/tmp/file_that_not_exists.txt' def setUpModule(): """ ...
nilq/baby-python
python
from marshmallow import fields, validate from app import ma from nfmanagementapi.models import FilterRule class FilterRuleSchema(ma.SQLAlchemyAutoSchema): class Meta: model = FilterRule ordered = True uuid = fields.UUID(required=True, description="Unique Identifier", dump_only=True) n...
nilq/baby-python
python
import sys import Adafruit_DHT import Adafruit_BMP.BMP085 as BMP085 import requests def getReadings(): humidity, dht_temp = Adafruit_DHT.read_retry(22, 4) if humidity is not None and dht_temp is not None: bmp_sensor = BMP085.BMP085() pressure = bmp_sensor.read_pressure() bmp_temp = bmp_...
nilq/baby-python
python
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 ...
nilq/baby-python
python
import bug_killer_client.network.project as project_client from bug_killer_api_interface.schemas.request.project import CreateProjectPayload, UpdateProjectPayload from bug_killer_api_interface.schemas.response import UserProjectsResponse, ProjectResponse async def get_user_projects(auth: str) -> UserProjectsResponse:...
nilq/baby-python
python
import imageio import pandas as pd import matplotlib.pyplot as plt import trackviz.static tracks = pd.read_csv('sample_data/ant_tracking_res.csv').rename(columns={'frame': 't'}) fig, ax = trackviz.static.trajectory_3d(tracks, color='t', line_kws=dict(linewidths=0.5)) fig.savefig('output/static_3d_color_frame.png') # ...
nilq/baby-python
python
from typing import Any from typing import Optional import aiohttp from ...box import box from ...command import argument from ...command import option from ...event import Message from ...utils import json box.assert_config_required('NAVER_CLIENT_ID', str) box.assert_config_required('NAVER_CLIENT_SECRET', str) LANG...
nilq/baby-python
python
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: image_ops.cc """ import collections as _collections from tensorflow.python.eager import execute as _execute from tensorflow.python.eager import context as _context from tensorflow.python.eager import core...
nilq/baby-python
python
""" Copyright 2018 Ederson Bilhante Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to ...
nilq/baby-python
python
import math import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from einops import rearrange from torch import Tensor device = "cuda" if torch.cuda.is_available() else "cpu" DEVICE = device class PositionalEncoding(nn.Module): def __init__(self, d_model: int, dro...
nilq/baby-python
python
# teste = list() # teste.append('Henrique') # teste.append(15) # # galera = list() # galera.append(teste[:]) # # teste[0] = 'Maria' # teste[1] = 22 # # galera.append(teste[:]) # print(galera) galera = [['João', 19], ['Alana', 16], ['Maria', 33], ['Pedro', 25]] for p in galera: print(f'Nome: {p[0]} \nIdade: {p[1]}...
nilq/baby-python
python
from django.db import IntegrityError from django.db.models import Q from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from cajas.boxes.services.box_daily_square_manager import BoxDailySquareManager from cajas.users.models.employee import Employee ...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (C) 2018 Adrian Herrera # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modi...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.12.8) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\xb4\xdf\ \xff\ \xd8\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x00\x00\x01\x00\ \x01\x00\x00\x...
nilq/baby-python
python
class RunnerTemplate: def exec(self, data): pass
nilq/baby-python
python
import asyncio import logging import re from io import BytesIO import discord from redbot.core import checks, commands from redbot.core.bot import Red from redbot.core.utils.chat_formatting import box, inline from tsutils.emoji import char_to_emoji, fix_emojis_for_server, replace_emoji_names_with_code logger = loggin...
nilq/baby-python
python
# Lint as: python3 # Copyright 2019 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 ...
nilq/baby-python
python
# LIBRARIES from django.db import models from django.db.utils import IntegrityError from django.contrib.contenttypes.models import ContentType # DJANGAE from djangae.db import transaction from djangae.fields import ( ComputedCharField, GenericRelationField, ListField, RelatedSetField, RelatedListFi...
nilq/baby-python
python
class DocumentOCRViewTestMixin(object): def _request_document_content_view(self): return self.get( viewname='ocr:document_ocr_content', kwargs={ 'document_id': self.test_document.pk } ) def _request_document_content_delete_view(self): return self...
nilq/baby-python
python
import attr import aiohttp import asyncio from typing import Any, Optional # Not frozen, since that doesn't work in PyPy @attr.s(slots=True, auto_exc=True, auto_attribs=True) class FacebookError(Exception): """Base class for all custom exceptions raised by ``fbchat``. All exceptions in the module inherit thi...
nilq/baby-python
python
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
nilq/baby-python
python
"""Lambda pocket-to-kindle create_epub.""" from datetime import datetime from os import environ as env from os import stat from shlex import join from subprocess import (run, CalledProcessError, TimeoutExpired) from tempfile import NamedTemporaryFile from uuid import uuid4 import utils import utils.aws as aws import u...
nilq/baby-python
python
# default_settings.py # # Author(s): # Exequiel Ceasar Navarrete <esnavarrete1@up.edu.ph> # # Licensed under MIT # Version 1.0.0 import os #======================================================== # [Flask-specific configuration] ::start #======================================================== DEBUG = False CACH...
nilq/baby-python
python
from __future__ import annotations import typing if typing.TYPE_CHECKING: from src.typehints import AnyCallableT __all__: tuple[str, ...] = ("is_classvar",) def is_classvar(fn: AnyCallableT) -> bool: return hasattr(fn, "__classvar__")
nilq/baby-python
python
#!/usr/bin/python from urllib2 import urlopen import json, re from json import loads def print_json(j): j = json.dumps(j, sort_keys=True, indent=2) # j = re.sub(j, r'\n', '\\n') print j def my_urlopen(url): print "\nurlopen:", url return urlopen(url) print "\nget all projects" req = urlopen('ht...
nilq/baby-python
python
"""Tests for the Update integration init.""" from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable from typing import Any from unittest.mock import Mock, patch from aiohttp import ClientWebSocketResponse import pytest from homeassistant.components.update import ( DOMAI...
nilq/baby-python
python
class Events: def __getattr__(self, name): if hasattr(self.__class__, '__events__'): assert name in self.__class__.__events__, \ "Event '%s' is not declared" % name self.__dict__[name] = ev = _EventSlot(name) return ev def __repr__(self): retu...
nilq/baby-python
python
""" Code modified from PyTorch DCGAN examples: https://github.com/pytorch/examples/tree/master/dcgan """ import argparse import os import random import torch import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.utils.data def get_parsers(): parser = argparse.ArgumentParser() parser.add_...
nilq/baby-python
python
import math import torch import torch.nn as nn import torch.nn.functional as F class FunctionRepresentation(nn.Module): """Function to represent a single datapoint. For example this could be a function that takes pixel coordinates as input and returns RGB values, i.e. f(x, y) = (r, g, b). Args: ...
nilq/baby-python
python
import random import os import matplotlib.image as mpimg import matplotlib.pyplot as plt plt.ion() PROJECT_FOLDER = os.path.dirname(__file__) DATASET_FOLDER = PROJECT_FOLDER + '/data/columbia-prcg-datasets' PHOTO_FOLDER = DATASET_FOLDER + '/google_images/' CG_FOLDER = DATASET_FOLDER + '/prcg_images/' NUM_IMA...
nilq/baby-python
python
import os import tempfile from ..spectrify import load_data, spectrify_audios import numpy as np def test_spectrify(): out_bins = 80 samplerate = 44100 frame_len = 0.1 input_fnames = [os.path.dirname(__file__)+"/test.mp3"] spec_datas = [load_data(filename,samplerate) for filename in input_fnames] ...
nilq/baby-python
python