content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_utils import (
Builder,
PipelineStage,
TrainingPipeline,
Line... | nilq/baby-python | python |
import py.path
import pytest
from .conftest import TEST_PLAYBOOKS
MODULES_PATH = py.path.local(__file__).realpath() / '..' / '..' / 'plugins' / 'modules'
def find_all_modules():
for module in MODULES_PATH.listdir(sort=True):
module = module.basename
if module.endswith('.py') and not module.start... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... | nilq/baby-python | python |
import os
import sys
import time
import glob
import numpy as np
import pandas as pd
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torch.nn.functional as F
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from copy import deepcopy
from nu... | nilq/baby-python | python |
"""
hhpy
~~~~~~
The hhpy package - a Python package developed by Henrik Hanssen centered around the idea of providing
unified and convenient tools for Data Science
"""
from hhpy.main import *
from hhpy.ds import *
from hhpy.ipython import *
from hhpy.modelling import *
from hhpy.plotting import *
from hhpy.regression... | nilq/baby-python | python |
"""
Copyright 2017 Nikolay Stanchev
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 |
import importlib
from pathlib import Path
from airflow.hooks.base import BaseHook
from astro.databases.base import BaseDatabase
from astro.utils.path import get_class_name, get_dict_with_module_names_to_dot_notations
DEFAULT_CONN_TYPE_TO_MODULE_PATH = get_dict_with_module_names_to_dot_notations(
Path(__file__)
)... | nilq/baby-python | python |
from PySide2 import QtWidgets
import maya.cmds as cmds
class MyWindow(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
lay = QtWidgets.QHBoxLayout(self)
self._line = QtWidgets.QLineEdit('', self)
self._line.setPlaceholde... | nilq/baby-python | python |
# Copyright 2021 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 |
"""AVMATH
Avmath is a Python module for mathematical purposes.
It contains functionalities for simple mathematical
usage as sine or logarithm functions and submodules
for more advanced applied math in the topics of ana-
lysis and linear algebra.
The module uses a mathematical syntax. The classes
and functions are nam... | nilq/baby-python | python |
"""
This script deploys all the AWS instances required for a single distributed experiment and runs the docker container
on the instances.
The experiment is one of inner_product / quadratic / kld / dnn.
The user could choose whether to run the coordinator on a strong EC2 instance, or on an ECS Fargate instance.
"""
imp... | nilq/baby-python | python |
from .models import Answer, Landscape
def landscape_boundary(landscape_name):
"""
Return landscape boundary as GeoJSON
:param landscape_name:
:return:
"""
landscape_boundaries = Landscape.objects.raw("""SELECT
id,
... | nilq/baby-python | python |
import random, string
from datetime import datetime
import pytz
import json
import types
from unittest import TestCase
from unittest.mock import patch
from plaw.wrapper import Plaw, InvalidGrant, InvalidToken
class TestPlaw(TestCase):
# helper
def generate_random_token(self, length=16):
return ''.jo... | nilq/baby-python | python |
# encoding: utf-8
# Duke the dog
# Este código va destinado al reconocimiento de un perro por su color de pelaje,
# eliminando todo ruido causado por el ambiente.
# Todo mediante la librería open cv en Python..subl
# Programador Sergio Luis Beleño Díaz
# Enero.2019
'''
Para empezar se importan las librerías de Open... | nilq/baby-python | python |
from chemlib.chemistry import Combustion, Compound, Reaction
from chemlib.utils import reduce_list
# TODO: TEMP IMPLEMENTATIONS, NEED TO CONSIDER ADDITIONAL METHODS/CALCULATIONS
# INTERFACE?
def combustion_analysis(CO2, H2O) -> str:
molesC = Compound("CO2").get_amounts(grams = CO2)["moles"]
molesH = (Compou... | nilq/baby-python | python |
__all__ = [ 'assign','smart_assign','LCA','linkable',
'Assign','SmartAssign','Linkable',
'join_name',
'Component',
'Input','Output','UInt','SInt','IOGroup','Parameter','Wire','Reg',
'And','Or','Greater','Less','GreaterEqual','LessEqual','NotEqual','Equal',
... | nilq/baby-python | python |
import numpy as np
import torch
import torch.nn as nn
from .anchor_head_template import AnchorHeadTemplate
class GradReverse(torch.autograd.Function):
def __init__(self, lambd):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
return (... | nilq/baby-python | python |
# coding= utf-8
# author= Administrator
# date= 2021/3/15 17:38
from bs4 import BeautifulSoup
# 创建html字符串
html_doc = """
<!DOCTYPE html><!--STATUS OK-->
<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always... | nilq/baby-python | python |
# Generated by Django 3.0.7 on 2020-06-30 17:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0005_auto_20200630_1658'),
]
operations = [
migrations.AddField(
model_name='collection',
name='spotlig... | nilq/baby-python | python |
from tool.runners.python import SubmissionPy
class DivSubmission(SubmissionPy):
def match(self, x):
s = str(x)
n = len(s)
if n != 6:
return False
# always increasing (or equal)
for i in range(n-1):
if s[i] > s[i+1]:
return False
... | nilq/baby-python | python |
#take file called numbers.txt to start
fileName = "numbers.txt"
def main():
global fileName
fileInput = open(fileName, 'r')
numAry = []
for line in fileInput.readlines():
numAry.append(eval(line))
maxInt = findMax(numAry, 0, len(numAry)-1)
print("The Max Value Is " + str... | nilq/baby-python | python |
#!/usr/bin/python2.7
# coding:utf-8
import logging
from time import sleep
from RPi import GPIO
from cmdtree import INT
from cmdtree import command
from cmdtree import entry
from cmdtree import group
from cmdtree import option
GPIO_CONTROL_PORT = 12
FAN_ON_TEMPERATURE = 55
def get_cpu_temp():
... | nilq/baby-python | python |
from copy import deepcopy
from torch import nn
import numpy as np
import math
import torch
from torch.utils.data import dataset
from torch.utils.data.dataset import Subset
from torch.utils.data import DataLoader
# def compare_models(model: nn.Module, clients: 'list[Client]', num: int):
# def print_params(model... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at
# http://www.apache.org/licenses/LICENS... | nilq/baby-python | python |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render... | nilq/baby-python | python |
nome = str(input('Digite seu nome completo: ')).strip()
print('Silva' in nome.title())
| nilq/baby-python | python |
from __future__ import print_function
from optparse import make_option
from datetime import datetime, timedelta
import sys
from textwrap import dedent
from django.core.mail import mail_admins
from django.contrib.auth.models import User
from reversion.models import Revision
from cobl.utilities import LexDBManagementComm... | nilq/baby-python | python |
def load_STNTable(fobj, kwArgCheck = None, debug = False, errors = "strict", indent = 0):
# NOTE: see https://github.com/lw/BluRay/wiki/STNTable
# Import standard modules ...
import struct
# Import sub-functions ...
from .load_StreamAttributes import load_StreamAttributes
from .load_StreamEntr... | nilq/baby-python | python |
import unicodedata
def parse(dict_file):
with open(dict_file, 'r', encoding='utf-8') as r:
for line in r:
for word in line.split("#")[1].split(","):
word = unicodedata.normalize('NFKC', word.strip())
yield word
def parse_lexemes(dict_file):
with open(dict_... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2014, Stanford University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list ... | nilq/baby-python | python |
import pyperclip
class User:
'''
class for passing all instances of the user
'''
user_list = []
def __init__(self,user_name,account_name,email,password):
'''
initiates properties of my objects
Args:
user_name:New username of the account
'''... | nilq/baby-python | python |
from ecco.attribution import gradient_x_inputs_attribution
import torch
import pytest
@pytest.fixture
def simpleNNModel():
class simpleNNModel(torch.nn.Module):
def __init__(self):
super(simpleNNModel, self).__init__()
self.w = torch.tensor([[10., 10.]])
def forward(self, ... | nilq/baby-python | python |
from sklearn import ensemble
from model_man import get_models
def create():
models = get_models()
v_models = [(key, models[key].create()) for key in models.keys()]
return ensemble.VotingClassifier(
estimators=v_models,
voting="hard"
)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
A nested dict with both attribute and item access.
NA stands for Nested and Attribute.
"""
import collections
import copy
class NADict:
"""A nested dict with both attribute and item access.
It is intended to be used with keys that are valid Python
identifiers. However, excep... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# FreeCAD macro for woodworking
# Author: Darek L (aka dprojects)
# Version: 5.0
# Latest version: https://github.com/dprojects/getDimensions
import FreeCAD
# #######################################################
# SETTINGS ( SET HERE )
# ####################################################... | nilq/baby-python | python |
def get_length_of_missing_array(arr):
if len(arr) == 0:
return 0
else:
lens = []
for i in arr:
if i == None or len(i) == 0:
return 0
lens.append(len(i))
lens.sort()
prevInt = 0
for i in lens:
... | nilq/baby-python | python |
"""
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous
subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no
such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Ou... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2021 Jacob M. Graving <jgraving@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless requi... | nilq/baby-python | python |
from typing import Sequence, Hashable
def find_field(d, candidates):
"""
Given a dict and a list of possible keys, find the first key
which is included into this dict. Throws ValueError if not found.
"""
for c in candidates:
if c in d:
return c
raise ValueError(f"Can't find any of: {candidates}")
def find... | nilq/baby-python | python |
from zmodulo.plot.properties.color.color import Color
class LineColor:
""" A Z-Tree plot line color """
def __init__(self, color=None):
"""
Initializes the LineColor object
:param color: line color
:type color: Color
"""
if color is None:
self.color... | nilq/baby-python | python |
from lin import db
from lin.core import File
from lin.exception import NotFound
from pydash import uniq_by
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import aliased
from app.models.base import Base
class Category(Base):
id = Column(Integer, primary_key=True)
name = Column(String(50), ... | nilq/baby-python | python |
swaps=[]
def heapify(data,n,vert):
min=vert
l=2*vert+1
r=2*vert+2
if l<n and data[l]<data[min]:
min=l
if r<n and data[r]<data[min]:
min=r
if min!=vert:
data[vert],data[min]=data[min],data[vert]
swaps.append([vert,min])
heapify(data,n,min)
def main():
... | nilq/baby-python | python |
from django.contrib import admin
from .models import Report, ReportFiles, ReportIndex
admin.site.register(Report)
admin.site.register(ReportFiles)
admin.site.register(ReportIndex)
| nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: anly_jun
@file: github_trending
@time: 16/10/17 下午2:23
"""
import requests
from bs4 import BeautifulSoup
GITHUB = 'https://github.com'
TRENDING_URL = GITHUB + "/trending"
TRENDING_DEV_URL = TRENDING_URL + "/developers"
USER_AGENT_BY_MOBILE = 'Mozilla/5.0 (Linux; A... | nilq/baby-python | python |
import requests
from bs4 import BeautifulSoup as bs
import time
import random
import os
import pandas as pd
from pathlib import Path
pwd = os.getcwd()
# Creating /details_page folder
Path(pwd + '/details_pages').mkdir(parents=True, exist_ok=True)
df = pd.read_csv(pwd + '\\dataframes\\Data - IT_Companies_Algiers.csv')... | nilq/baby-python | python |
def make_local_image( embedded_cid , filename, payload):
"""helper func that creates an image object. others may replace this with a specific solution.
the important point is that it returns a link
"""
import models #my models module. you will probably replace this entire function with your own code
... | nilq/baby-python | python |
import json
from mock import patch
import jenkins
from tests.base import JenkinsTestBase
class JenkinsCancelQueueTest(JenkinsTestBase):
@patch.object(jenkins.Jenkins, 'jenkins_open')
def test_simple(self, jenkins_mock):
job_name_to_return = {u'name': 'TestJob'}
jenkins_mock.return_value = js... | nilq/baby-python | python |
from itertools import permutations
l=list(map(int,input().split()))
r=list(permutations(l))
print(r)
| nilq/baby-python | python |
import typing
import datetime
import pandas as pd
from .make_df import ComicDataFrame
from lib.aws_util.s3.upload import upload_to_s3
from lib.aws_util.s3.download import download_from_s3
def store(df: ComicDataFrame) -> typing.NoReturn:
dt = datetime.datetime.now()
bucket = 'av-adam-store'
save_dir = '/tmp/'
... | nilq/baby-python | python |
from .charge import Charge | nilq/baby-python | python |
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ChatAction
#Google
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import pandas as pd
INPUT_... | nilq/baby-python | python |
"""
Manages creation of POVMs and geneartion of outcomes from measuring these POVM given a state
Author: Akshay Seshadri
"""
import numpy as np
import scipy as sp
from scipy import stats
import project_root # noqa
from src.utilities.qi_utilities import generate_random_state, generate_POVM, generate_Pauli_ope... | nilq/baby-python | python |
#!/usr/bin/env python3
import logging
import resource
import sys
logging.basicConfig(level=logging.INFO)
import teether.project
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: %s [flags] <code>' % sys.argv[0])
exit(-1)
mem_limit = 4 * 1024 * 1024 * 1024 # 4GB
resource.set... | nilq/baby-python | python |
#!/usr/bin/python3
from PyQt5.QtWidgets import *
class ModulPU(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout()
self.setLayout(self.layout)
#################################################################################################################
############################... | nilq/baby-python | python |
# encoding: utf-8
# Copyright 2011 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
'''Service Binding: implementation'''
from Acquisition import aq_inner, aq_parent
from ipdasite.services import ProjectMessageFactory as _
from ipdasite.services.config import PROJEC... | nilq/baby-python | python |
from pathlib import Path
from conanRunner import conanRunner
def conanInstall(conanfile, installFolder):
print("\n")
conanfile = str(conanfile)
installFolder = str(installFolder)
args = ["install", conanfile, "--install-folder", installFolder]
for s in conanRunner(args):
print(s)
| nilq/baby-python | python |
# coding: utf-8
"""
Telstra Event Detection API
# Introduction Telstra's Event Detection API provides the ability to subscribe to and receive mobile network events for registered mobile numbers associated with Telstra's mobile network, such as; SIM swap, port-in, port-out, new MSIDN, new mobile service and c... | nilq/baby-python | python |
import unittest
import mock
from factor_graph import FactorGraph, FactorGraphService, Node, Edge
class TestFactorGraph(unittest.TestCase):
pass
class TestFactorGraphService(unittest.TestCase):
## mock FG for failure tests
def test_create_success(self):
factor_graph_service = FactorGraphService()
... | nilq/baby-python | python |
import configparser
import inspect
import logging
import os
import typing
import numpy as np
from ConfigSpace.configuration_space import Configuration
from smac.runhistory.runhistory import RunHistory, RunKey
from cave.utils.exceptions import NotApplicable
def get_timeout(rh, conf, cutoff):
"""Check for timeout... | nilq/baby-python | python |
# encoding: utf-8
from .default import Config
class DevelopmentConfig(Config):
# App config
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite:///../db/dictionary.sqlite3"
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 KuraLabs S.R.L
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | nilq/baby-python | python |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... | nilq/baby-python | python |
import sysconfig
import sys
CFLAGS = "{} -I{} -I{} -fno-omit-frame-pointer".format(
sysconfig.get_config_var("CFLAGS"),
sysconfig.get_path("include"),
sysconfig.get_path("platinclude"),
)
if __name__ == "__main__":
print(f'export CFLAGS="{CFLAGS}"')
| nilq/baby-python | python |
#!/usr/bin/env python3
# This example demonstrates the interaction between different execution modes
import mavlinkinterface # Needed to use the library
from time import sleep # For waiting between commands
# Create interface object, All calls will be made through this
# execMode="queue" means that the "que... | nilq/baby-python | python |
from uuid import uuid4
import pytest
from protean import BaseCommand, BaseEventSourcedAggregate
from protean.exceptions import IncorrectUsageError
from protean.fields import String
from protean.fields.basic import Identifier
class User(BaseEventSourcedAggregate):
id = Identifier(identifier=True)
email = Str... | nilq/baby-python | python |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to ... | nilq/baby-python | python |
import dataclasses
import logging
from dataclasses import dataclass
import tempfile
import os
from typing import Optional
import loaders
import synth
from synth import ( # noqa: F401
grid_dataset,
grid_dataset_path,
dataset_fixtures_dir,
)
import fv3fit
from fv3net.diagnostics.offline import compute
from ... | nilq/baby-python | python |
import gym
from agents.random_agent import RandomAgent
def main(episode_count):
env = gym.make('CartPole-v0')
agent = RandomAgent(env.action_space.n)
for i in range(episode_count):
observation = env.reset() # initialize the environment
done = False
step = 0
while not done:... | 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 |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX XX XXX XXXXXX XXXX XXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXXXXX XXXX
XXXXXXX XX X XXXXXXXXXXX XXXX XXXXXX XXX XXXXX XXXXXXXXXX XX XXXXXXX XX XXX
XXXXXX XXXXXXXX XX XXXX XX XXX XXXXXXXXX XXXXXX XXX XXXXX
XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX XXXXXX
XXXXXXXXX... | nilq/baby-python | python |
"""
zoom.mail
email services
"""
import os
import json
import logging
from smtplib import SMTP
from mimetypes import guess_type
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
fro... | nilq/baby-python | python |
# SPDX-License-Identifier: MIT
# Copyright (c) 2022 MBition GmbH
from ..globals import logger
from .compumethodbase import CompuMethod
class TabIntpCompuMethod(CompuMethod):
def __init__(self,
internal_type,
physical_type):
super().__init__(internal_type, physical_type... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from hashlib import md5
from flask import Flask, request, redirect, current_app
from time import gmtime
from xmltodict import parse
import requests
import urllib
app = Flask(__name__)
app.config.from_pyfile('config.py', silent=True)
app.config.from_pyf... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from catboost import Pool
from sklearn.model_selection import StratifiedKFold
from tqdm import tqdm
class CatBoostCustomModel:
def __init__(self, model, model_params={}):
self.result = {}
try:
self.model = model
self.model.set_params(**m... | nilq/baby-python | python |
from __future__ import unicode_literals
import logging
from inspect import ismethod
from django.core.urlresolvers import (reverse, resolve, NoReverseMatch,
Resolver404)
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.encoding i... | nilq/baby-python | python |
from sklearn.model_selection import GridSearchCV
from luciferml.supervised import classification as cls
def hyperTune(classifier, parameters, X_train, y_train, cv_folds, tune_mode, isReg):
"""
Takes classifier, tune-parameters, Training Data and no. of folds as input and Performs GridSearch Crossvalidation.
... | nilq/baby-python | python |
import os.path
import logging
from utils import make_id, get_resource
from os.path import join
logger = logging.getLogger(__name__)
def apps_dir():
return os.path.dirname(os.path.abspath(__file__))
def load_app(app_def_file, app_id=None, parent_group="/"):
"""Loads an app definition from a json file and s... | nilq/baby-python | python |
from abc import ABCMeta
import numpy as np
from torch.utils.data import ConcatDataset, Dataset, WeightedRandomSampler
from mmpose.datasets.builder import DATASETS
from .mesh_base_dataset import MeshBaseDataset
@DATASETS.register_module()
class MeshMixDataset(Dataset, metaclass=ABCMeta):
"""Mix Dataset for 3D hu... | nilq/baby-python | python |
# coding: utf-8
# pylint: disable=missing-docstring
# pylint: disable=invalid-name
import os
import glob
import subprocess
from setuptools import setup, find_packages
about = {}
HERE = os.path.abspath(os.path.dirname(__file__))
with open(file=os.path.join(HERE, 'src','dima', '__version__.py'), mode='r', encoding='u... | nilq/baby-python | python |
import logging
from os.path import expanduser
from git import InvalidGitRepositoryError
from pythoncommons.file_utils import FileUtils
from pythoncommons.git_wrapper import GitWrapper
LOG = logging.getLogger(__name__)
class FormatPatchSaver:
"""
A class used to export git-format-patch files from a git repo... | nilq/baby-python | python |
"""Test the Cloudflare config flow."""
from pycfdns.exceptions import (
CloudflareAuthenticationException,
CloudflareConnectionException,
CloudflareZoneException,
)
from homeassistant.components.cloudflare.const import CONF_RECORDS, DOMAIN
from homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER... | nilq/baby-python | python |
#!/usr/bin/env python
# Requires metasploit, snmpwalk, snmpstat and John the Ripper
# _____ _ ____ _______ ____ __
# / ___// | / / |/ / __ \ / __ )_______ __/ /____
# \__ \/ |/ / /|_/ / /_/ / / __ / ___/ / / / __/ _ \
# ___/ / /| / / / / ____/ / /_/ / / / /_/ / /_/ __/
#/____/_/ |_/_... | nilq/baby-python | python |
nasc = int(input('Ano de nascimento: '))
idade = 2018 - nasc
if idade <= 9:
print('Categoria: Mirim')
elif idade <= 14:
print('Categoria: Infantil')
elif idade <= 19:
print('Categoria: Júnior')
elif idade <= 20:
print('Categoria: Sênior')
elif idade >= 21:
print('Categoria: Master') | nilq/baby-python | python |
#!/usr/bin/env python
# coding:utf-8
"""
Test functionality of Service elements.
"""
# -- standard library ---------------------------------------------------------
from cgi import parse_header, FieldStorage
from threading import Thread
import unittest
import tempfile
import zipfile
import socket
import json
import s... | nilq/baby-python | python |
import unittest
from PySide2.QtWidgets import *
from qtimgren.main_window import MainWindow
from unittest.mock import Mock, patch
import qtimgren.main_window
import qtimgren.about
import qtimgren.profile
import qtimgren.profiles
class TestMainWindow(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None... | nilq/baby-python | python |
from airflow.plugins_manager import AirflowPlugin
from freshdesk_plugin.operators.freshdesk_to_s3_operator import FreshdeskToS3Operator
class freshdesk_plugin(AirflowPlugin):
name = "freskdesk_plugin"
operators = [FreshdeskToS3Operator]
hooks = []
# Leave in for explicitness
executors = []
mac... | nilq/baby-python | python |
import numpy as np
import random
import matplotlib.pyplot as plt
from collections import deque
class UniformNoise(object):
def __init__(self, action_space, initial_exploration = 0.99, final_exploration = 0.05, decay_rate = 0.999):
self.action_dim = action_space.shape[0] # Requires Space with... | nilq/baby-python | python |
# These dictionaries are applied to the generated attributes dictionary at build time
# Any changes to the API should be made here. attributes.py is code generated
# We are not code genning attributes that have been marked as obsolete prior to the initial
# Python API bindings release
attributes_codegen_method = {
... | nilq/baby-python | python |
from Components.Sources.Source import Source
from Components.Network import iNetwork
from Tools.Directories import fileExists
from twisted import version
from socket import has_ipv6, AF_INET6, inet_ntop, inet_pton
def normalize_ipv6(orig):
net = []
if '/' in orig:
net = orig.split('/')
if net[1] == "128":
d... | nilq/baby-python | python |
from services.lib.config import Config
from services.lib.db import DB
from localization.base import BaseLocalization
from localization.eng import EnglishLocalization
from localization.rus import RussianLocalization
from services.lib.utils import Singleton
class LocalizationManager(metaclass=Singleton):
def __init... | nilq/baby-python | python |
import cv2
import numpy as np
img = cv2.imread("Resources/lena.png")
kernel = np.ones((5,5),np.uint8)
imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray,(7,7),0)
imgCanny = cv2.Canny(img,150,200)
imgDialation = cv2.dilate(imgCanny,kernel,iterations=1)
imgEroded = cv2.erode(img... | nilq/baby-python | python |
from __future__ import annotations
from collections import defaultdict
from typing import Any, Dict, Optional, Tuple
from .fields import Field, ModelField
from .validation import Validation
class ModelBase:
__slots__ = ()
def __init__(self):
pass
@classmethod
def get_xmltag(cls) -> str:
... | nilq/baby-python | python |
"""Extension for using climatecontrol with dataclasses."""
from dataclasses import is_dataclass
from typing import Generic, Mapping, Type, TypeVar
import dacite
from climatecontrol.core import Climate as BaseClimate
from climatecontrol.core import SettingsItem as BaseSettingsItem
from climatecontrol.fragment import ... | nilq/baby-python | python |
from flask import Blueprint, request, Response, json
from main.models import database
import csv
mypage_page = Blueprint('mypage', __name__)
def read_csv(user_id):
file = csv.reader(open('../main/recommendation/recommend_list/{}.csv'.format(user_id), 'r',encoding='utf-8'))
lists = []
for row in file:
... | nilq/baby-python | python |
# Imports
import numpy as np
import matplotlib.pyplot as plt
import os
# Results directory
directory = os.path.join("results", "cbis", "history")
figs_directory = os.path.join("results", "cbis", "figures")
# Models
MODELS = ["densenet121", "resnet50", "vgg16"]
# Training Formats
TRAINING_MODE = ["baseline", "basel... | nilq/baby-python | python |
import scapy.all as scapy
import time
import termcolor
class ConnectToTarget:
def spoof(self,router_ip,target_ip,router_mac,target_mac ):
packet1=scapy.ARP(op=2, hwdst=router_mac,pdst=router_ip, psrc=target_ip)
packet2=scapy.ARP(op=2, hwdst=target_mac,pdst=target_ip, psrc=router_ip)
scapy.send(packet1)
scap... | nilq/baby-python | python |
"""Test stack
"""
import ARgorithmToolkit
algo = ARgorithmToolkit.StateSet()
stack = ARgorithmToolkit.Stack("st",algo)
def test_declare():
"""Test stack creation
"""
last_state = algo.states[-1]
assert last_state.content["state_type"] == "stack_declare"
def test_operations():
"""Test stack operat... | nilq/baby-python | python |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2017, Johannes Köster"
__email__ = "johannes.koester@tu-dortmund.de"
__license__ = "MIT"
import os
import re
import shutil
import subprocess as sp
from datetime import datetime
import time
from snakemake.remote import AbstractRemoteObject, AbstractRemoteProvid... | nilq/baby-python | python |
import os
import os.path
import json
import numpy as np
import sys
import itertools
import random
import argparse
import csv
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UTILS_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'utils'))
sys.path.append(UTILS_DIR)
sys.path.append(BASE_DIR)
# sys.path.insert(1... | nilq/baby-python | python |
import unittest
from Calculator import Calculator
from CsvReader.CSVReader import CsvReader
class MyTestCase(unittest.TestCase):
def test_instantiate_calculator(self):
calculator = Calculator()
self.assertIsInstance(calculator, Calculator)
def test_addition_method(self):
calculator =... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.