content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from ..grammar import Grammar
from typing import Deque
from ..tokenizer import Token
class FinalToken:
def __init__(self):
self.name = '$'
self.lexeme = '$'
class Parser:
def __init__(self, grammar: Grammar, action, go_to):
self.grammar = grammar
self.action = action
... | nilq/baby-python | python |
def processChange(job):
service = job.service
args = job.model.args
if args.pop('changeCategory') != 'dataschema':
return
if 'url' in args:
service.model.data.url = args['url']
if 'eventtypes' in args:
service.model.data.eventtypes = args['eventtypes']
service.saveAll... | nilq/baby-python | python |
"""Fire animation, by Uck!"""
import dcfurs
import random
# Colors, from top to bottom of the fire.
colors = [0, 0x1f0f0f, 0x3f0000, 0xff0000, 0xff7f00, 0xffff00, 0x1f007f,
0x0000ff, 0xffffff]
# Bitmask values copied from emote.boop().
boop_mask = [
0x0e48e,
0x12b52,
0x12b52,
0x0eb4e,
0... | nilq/baby-python | python |
from agents.common import PLAYER1, PLAYER2, initialize_game_state, apply_player_action, \
evaluate_rows, is_player_blocking_opponent, is_player_winning
def test_evaluate_rows_True_Player1_is_player_blocking_opponent():
game = initialize_game_state()
num_rows = game.shape[0]
num_cols = game.shape[1]
... | nilq/baby-python | python |
# project/server/tests/base.py
from flask_testing import TestCase
from price_picker import db, create_app
from price_picker.common.create_sample_data import create_sample_data
app = create_app()
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object("config.TestingConfig")
... | nilq/baby-python | python |
from resotolib.baseresources import BaseResource
import resotolib.logger
import socket
import multiprocessing
import resotolib.proc
from concurrent import futures
from resotolib.baseplugin import BaseCollectorPlugin
from argparse import Namespace
from resotolib.args import ArgumentParser
from resotolib.config import Co... | nilq/baby-python | python |
from enum import Enum
__NAMESPACE__ = "http://www.opengis.net/gml"
class KnotTypesType(Enum):
"""
This enumeration type specifies values for the knots’ type (see ISO
19107:2003, 6.4.25).
"""
UNIFORM = "uniform"
QUASI_UNIFORM = "quasiUniform"
PIECEWISE_BEZIER = "piecewiseBezier"
| nilq/baby-python | python |
#!/usr/bin/env python3
"""Bumps the detect-secrets version,
in both `detect_secrets/__init__.py` and `README.md`.
Then commits.
"""
import argparse
import pathlib
import subprocess
import sys
PROJECT_ROOT = pathlib.Path(__file__).absolute().parent.parent
INIT_FILE_PATH = PROJECT_ROOT.joinpath('detect_secrets/__init_... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
from models.archs.dcn.deform_conv import ModulatedDeformConvPack as DCN_sep
class PCD_Align(nn.Module):
''' Alignment module using Pyramid, Cascading and Deformable convolution
with 3 pyramid levels.
'''
def... | nilq/baby-python | python |
import os
os.chdir("../..")
print(os.getcwd())
import sys
sys.path.append('')
from envs.aslaug_v1_cont import AslaugEnv
env = None
def setup():
global env, obs
env = AslaugEnv(gui=True)
os.chdir("baselines/mpc-acado")
obs = env.reset()
def get_obs():
global obs
return obs.tolist()
def step(inp)... | nilq/baby-python | python |
import re
import sqlite3
import util
import db
def main():
con = db.connect_db()
tbl = "art_of_worldly_wisdom"
db.purge_table(con, tbl)
db.init_table(con, tbl)
cur = con.cursor()
sql = f"INSERT INTO {tbl} (_id, _body) VALUES (?, ?)"
body_lines = []
is_last_line_page_break = False
... | nilq/baby-python | python |
# 5_pennyBoard.py
# A program that assigns each square on a checkerboard to a set number of pennies getting exponentially bigger
# Date: 9/22/2020
# Name: Ben Goldstone
square = 1
numberOfPennies = 0.01
#Constants
ONEPENNYTOGRAMS = 2.5
ONEPOUNDTOGRAMS = 453.6
ONEPOUNDOFCOPPERTODOLLARS = 3.15
#counters
totalAmountOfMon... | nilq/baby-python | python |
"""attendanceManagement URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='ho... | nilq/baby-python | python |
"""Tests for the to_cnf transformation."""
import unittest
from tt.errors import InvalidArgumentTypeError
from tt.expressions import BooleanExpression
from tt.transformations import to_cnf
class TestExpressionToCnf(unittest.TestCase):
def assert_to_cnf_transformation(self, original, expected):
"""Helpe... | nilq/baby-python | python |
initialized = True
class TestFrozenUtf8_1:
"""\u00b6"""
class TestFrozenUtf8_2:
"""\u03c0"""
class TestFrozenUtf8_4:
"""\U0001f600"""
def main():
print("Hello world!")
if __name__ == '__main__':
main()
| nilq/baby-python | python |
from __future__ import print_function, division, absolute_import
from datetime import timedelta
import errno
import logging
import socket
import struct
import sys
from tornado import gen
from tornado.iostream import IOStream, StreamClosedError
from tornado.tcpclient import TCPClient
from tornado.tcpserver import TCPS... | nilq/baby-python | python |
from output.models.nist_data.atomic.integer.schema_instance.nistschema_sv_iv_atomic_integer_max_inclusive_3_xsd.nistschema_sv_iv_atomic_integer_max_inclusive_3 import NistschemaSvIvAtomicIntegerMaxInclusive3
__all__ = [
"NistschemaSvIvAtomicIntegerMaxInclusive3",
]
| nilq/baby-python | python |
import pygame
import copy
from vector import Vec2, Vec4
from pixel import Pixel
from colors import *
from mymath import clamp, get_line_pixels
class Canvas:
def __init__(self, x, y, width, height, zoom=1.00):
self.pos = Vec2(x, y)
self.size = Vec2(width, height)
self.zoom = zoom
se... | nilq/baby-python | python |
from __future__ import annotations
from threading import Thread
from typing import Callable, Optional
from .interfaces import ITimeoutSendService
from ..clock import IClock
from ..service import IService, IServiceManager
from ..send import ISendService
from ..util.Atomic import Atomic
from ..util.InterruptableSleep imp... | nilq/baby-python | python |
"""
IOEcho device, receive GPIO, send them thought TCP to target
"""
__all__ = ['IOEcho']
__version__ = '0.1'
from .deviceBase import DeviceBase
from time import sleep
from lib.common import PrintColor
import requests
import json
from socket import *
try:
import RPi.GPIO as GPIO
is_running_on_pi = True
except Run... | nilq/baby-python | python |
import os
import sys
import numpy as np
import csv
import matplotlib.pyplot as plt
from src import readFiles as rf
from os import listdir
import re
def getDirectoriesAtPath(path):
return [name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))]
# Function to read the execution time an applic... | nilq/baby-python | python |
class NoSuchOmekaClassicItemException(Exception):
pass
| nilq/baby-python | python |
'''
1) Add an item to your cart
2) Proceed to checkout
3) Quit
$ 1
Enter item description: Red Bull
Enter item quantity: 48
Price per unit: $2.00
$ 2
48 - Red Bull @ $2.00 ea
Subtotal: $96.00
Tax (4.712%): $4.52
Total: $100.52
age = raw_input("How old is you? ")
height ... | nilq/baby-python | python |
from django.template.defaulttags import register
@register.filter
def index(sequence, position):
return sequence[position] | nilq/baby-python | python |
# Noysim -- Noise simulation tools for Aimsun.
# Copyright (c) 2010-2011 by Bert De Coensel, Ghent University & Griffith University.
#
# Run the viewer as a windows program
import noysim.viewer
app = noysim.viewer.wx.PySimpleApp()
app.frame = noysim.viewer.ViewerFrame()
app.frame.Show()
app.MainLoop()
| nilq/baby-python | python |
__all__ = ('reduce',)
from asyncio import create_task
from ._create_channel import create_channel
async def _reduce(out, fn, ch, init):
"""Reduce items from channel."""
acc = init
async for x in ch:
acc = fn(acc, x)
await out.put(acc)
out.close()
def reduce(fn, ch, init=None, *,
... | nilq/baby-python | python |
class WizardPlayer:
def __init__(self, player_id, np_random):
''' Initilize a player.
Args:
player_id (int): The id of the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.stack = [] # might need to be changed... | nilq/baby-python | python |
"""
На региональном этапе Всероссийской олимпиады школьников по информатике в 2009 году предлагалась следующая задача.
Всем известно, что со временем клавиатура изнашивается, и клавиши на ней начинают залипать. Конечно, некоторое время
такую клавиатуру еще можно использовать, но для нажатий клавиш приходиться использо... | nilq/baby-python | python |
import logging
import docker
from docker.models.containers import Container
from factioncli.processing.cli import log
from factioncli.processing.cli.printing import error_out
client = docker.from_env()
class container_status:
name = ""
status = ""
ip_address = ""
message = ""
created = ""
def ... | nilq/baby-python | python |
"""
The ``zen.nx`` module provides functions for converting graph objects to and from the `NetworkX <http://networkx.lanl.gov/>`_ library.
.. autofunction:: to_networkx(G)
.. autofunction:: from_networkx(G)
"""
from graph import Graph
from digraph import DiGraph
import networkx
__all__ = ['to_networkx','from_netwo... | nilq/baby-python | python |
# encoding: utf-8
#
from flask.sessions import SessionInterface as FlaskSessionInterface
from mo_dots import Data, wrap, exists, is_data
from mo_future import first
from mo_json import json2value, value2json
from mo_kwargs import override
from mo_logs import Log
from mo_math import bytes2base64URL, crypto
from mo_thr... | nilq/baby-python | python |
#!/usr/bin/env pypy
from random import *
from sys import *
n, q = map(int, argv[1:])
print n
L = range(0, n)
shuffle(L)
print ' '.join(map(str, L))
print ' '.join(map(str, (randint(1, i - 1) for i in xrange(2, n + 1))))
print q * 2
for i in xrange(q):
print 1, randint(1, n), randint(1, n)
print 2
| nilq/baby-python | python |
job = 'source $HOME/.bashrc ; source activate threshold-devel ; python experiment.py --method {} --thresh {} --max-iters {} --num-burn {} --num-samples {} --num-steps-hyper {} --partial-momentum {} --check-prob 0.01 {} {} 2>/dev/null'
with open('joblist.txt', 'w') as f:
for nb in [10000]:
for ns in [100000... | nilq/baby-python | python |
import base64
import cattle
import os
import pytest
import random
import time
import inspect
from datetime import datetime, timedelta
import requests
import fcntl
import logging
@pytest.fixture(scope='session', autouse=os.environ.get('DEBUG'))
def log():
logging.basicConfig(level=logging.DEBUG)
@pytest.fixture(... | nilq/baby-python | python |
import sys
def is_triangle(a,b,c):
if a + b > c:
if a + c > b:
if b + c > a:
print("True")
else:
print("False")
else:
print("False")
else:
print("False")
def read_nonnegative(word):
num = float(input(word))
if n... | nilq/baby-python | python |
import os
import easypost
from dotenv import load_dotenv
load_dotenv()
easypost.api_key = os.getenv('EASYPOST_TEST_API_KEY')
try:
shipment = easypost.Shipment.retrieve('shp_123...')
smartrates = shipment.get_smartrates()
print(smartrates)
except Exception as error:
print(error)
| nilq/baby-python | python |
from django.template import Library, Node, TemplateSyntaxError
from django.utils.encoding import force_unicode
from convert.base import MediaFile, EmptyMediaFile, convert_solo
from convert.conf import settings
register = Library()
class ConvertBaseNode(Node):
def error(self, context):
if sett... | nilq/baby-python | python |
import examples.PEs.alu_basic as alu_basic
import examples.PEs.PE_lut as PE_lut
from hwtypes import BitVector as BV
from peak import family
from metamapper import CoreIRContext
def test_alu():
CoreIRContext(reset=True)
width = 8
ALU_fc = alu_basic.gen_ALU(width)
isa_fc = alu_basic.gen_isa(width)
is... | nilq/baby-python | python |
"""
This module contains the WPS inputs and outputs that are reused across multiple WPS processes.
"""
from dataclasses import fields
from pywps import (
FORMATS,
ComplexInput,
ComplexOutput,
Format,
LiteralInput,
LiteralOutput,
)
from pywps.app.Common import Metadata
from ravenpy.config.rvs... | nilq/baby-python | python |
import os
from deepartransit.utils import data_generator
from deepartransit.utils.config import process_config
config_path = os.path.join('tests', 'deepar_config_test.yml')
def test_data():
config = process_config(config_path)
data = data_generator.DataGenerator(config)
batch_Z, batch_X = next(data.nex... | nilq/baby-python | python |
''' Helper functions to select and combine data '''
from __future__ import division
import logging
import re
import os
from collections import Iterable
import numpy as np
import tables as tb
import numexpr as ne
from tqdm import tqdm
from beam_telescope_analysis.telescope.telescope import Telescope
from beam_telesc... | nilq/baby-python | python |
# coding: utf-8
"""
Gate API v4
Welcome to Gate.io API APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf. # noqa: E501
Contact: support@mail.gate.io
Gen... | nilq/baby-python | python |
import pathlib
import numpy as np
import matplotlib.pyplot as plt
from os import listdir
from tqdm import tqdm
from visionutils import flow2mag
# workaround for bug https://github.com/tqdm/tqdm/issues/481
tqdm.monitor_interval = 0
font = {'family' : 'DejaVu Sans',
'weight' : 'bold',
'size' : 50}
pl... | nilq/baby-python | python |
#Declare and initialize the variables
monthlyPayment = 0
loanAmount = 0
interestRate = 0
numberOfPayments = 0
loanDurationInYears = 0
#Ask the user for the values needed to calculate the monthly payments
strLoanAmount = input("How much money will you borrow? ")
strInterestRate = input("What is the interest rate on th... | nilq/baby-python | python |
from difflib import SequenceMatcher
from six import iteritems
from datadog_checks.base.stubs.common import MetricStub, ServiceCheckStub
'''
Build similar message for better test assertion failure message.
'''
MAX_SIMILAR_TO_DISPLAY = 15
def build_similar_elements_msg(expected, submitted_elements):
"""
Ret... | nilq/baby-python | python |
from database.mysql import MySQLDatabase
from settings import db_config
"""
Retrieve the settings from the
'db_config' dictionary to connect to
our database so we can instantiate our
MySQLDatabase object
"""
db = MySQLDatabase(db_config.get('db_name'),
db_config.get('user'),
db_c... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ======================================================================================================================
# Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie,
# Caen, France. =
# CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See ... | nilq/baby-python | python |
t1 = [[1], [1], [1], [1], [1]]
t2 = [[1], [1, [1, 1]], [1]]
t3 = [[1], [1, [1, [1], 1]], [1]]
| nilq/baby-python | python |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code end... | nilq/baby-python | python |
# -----------------------------------------------------------------------------
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens & Font Bureau
# www.pagebot.io
#
# P A G E B O T
#
# Free to use. Licensed under MIT conditions
# Made for usage in DrawBot, www.drawbot.com
# -----------------... | nilq/baby-python | python |
#entrada
while True:
n = int(input())
if n == 0:
break
tempos = str(input()).split()
#processamento
tempoTotal = 10
for i in range(1, len(tempos)):
if (int(tempos[i]) - int(tempos[i - 1])) < 10:
tempoTotal += int(tempos[i]) - int(tempos[i - 1])
else:
... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2011 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.
"""A class to help start/stop a local apache http server."""
from __future__ import print_function
import logging
import optparse... | nilq/baby-python | python |
import sys
a = sys.stdin.readline().split()
def main():
a.sort(reverse=True)
a.insert(2, '+')
return eval(''.join(a))
if __name__ == '__main__':
ans = main()
print(ans)
| nilq/baby-python | python |
from config.config import success, header, proxy_ip_type
from proxyip import proxy_ip
def get_rest_list(sort: int):
'''
:param sort: 0最新,1最低价格
:return:
'''
api = "https://api-app.ibox.art/nft-mall-web/v1.2/nft/product/getResellList?origin=0&page=1&pageSize=20&sort=%s&type=0" % sort
while True:... | nilq/baby-python | python |
"""
This file contains the necessary to reconstruct the intermediary featuress from
a save of the models an inputs
Author Hugues
"""
import torch
from pathlib import Path
if __name__ == '__main__':
import sys
sys.path.append("..")
from param import data_path
file_location = Path(data_path) / Path('models')
... | nilq/baby-python | python |
from discord import DMChannel, User
from discord import Message
import stummtaube.data.rounds as rounds_management
from stummtaube import main
from stummtaube.commands import START, JOIN, END
from stummtaube.data.game import players
from stummtaube.data.round import Round
async def handle_message(message: Message) -... | nilq/baby-python | python |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.range import Range
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.graph.graph import Node
class RangeFrontExtractor(FrontExtractorOp):
op = 'Range'
enabled = Tru... | nilq/baby-python | python |
from .bslcp import bslcp
from .phoenix14 import phoenix14
__all__ = (
"bslcp",
"phoenix14",
)
| nilq/baby-python | python |
from __future__ import division, print_function
import numpy as np
from mlfromscratch.unsupervised_learning import Apriori
def main():
# Demo transaction set
# Example 2: https://en.wikipedia.org/wiki/Apriori_algorithm
transactions = np.array([[1, 2, 3, 4], [1, 2, 4], [1, 2], [2, 3, 4], [2, 3], [3, 4], [... | nilq/baby-python | python |
from aiogram import types
from ..bot import bot, dispatcher
@dispatcher.message_handler(commands=["start"])
async def start_handler(message: types.Message):
await message.answer(bot.phrases.start_message)
| nilq/baby-python | python |
from itertools import chain
from euclidean.R2.cartesian import P2, V2, cross2
from euclidean.R2.line import LineSegment
from .hull import convex_hull
from .line_sweep import shamos_hoey
class Polygon:
"""
"""
@classmethod
def ConvexHull(cls, points):
return cls(convex_hull(points), is_conv... | nilq/baby-python | python |
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("auth", "0006_require_contenttypes_0002"),
]
operations = [
migrations.CreateModel(
... | nilq/baby-python | python |
import requests
import time
class PickCourse(object):
def __init__(self):
"""
复制粘贴请求头
将下面值不一样的换掉即可
"""
self.headers = {
'accept': '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9',
'content-typ... | nilq/baby-python | python |
import contextlib
from Qt import QtCore
def _iter_model_rows(
model, column, include_root=False
):
"""Iterate over all row indices in a model"""
indices = [QtCore.QModelIndex()] # start iteration at root
for index in indices:
# Add children to the iterations
child_rows = model.rowCou... | nilq/baby-python | python |
#!/usr/bin/env python
# Programa 5.1 - Estrutura de repetição while
x = 1
while x <= 3:
print(x)
x = x + 1
print (' FIM ') | nilq/baby-python | python |
# 2019-11-24 20:59:47(JST)
import sys
def main():
n = int(sys.stdin.readline().rstrip())
m = map(int, sys.stdin.read().split())
ab = list(zip(m, m))
graph = [[] for _ in range(n + 1)]
for a, b in ab:
graph[a].append(b)
graph[b].append(a)
root = 1
parent = [... | nilq/baby-python | python |
# Copyright (c) 2017 The Johns Hopkins University/Applied Physics Laboratory
# 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/LICEN... | nilq/baby-python | python |
import asyncio
import nertivia
import nertivia.bot
from nertivia import http
URL = "https://nertivia.net/api/messages/channels/"
URL_MSG = "https://nertivia.net/api/messages/"
URL_STA = "https://nertivia.net/api/settings/status"
class Message:
# __slots__ = ('id', 'content', 'author')
def __init__(self, me... | nilq/baby-python | python |
from TestHelperSuperClass import testHelperSuperClass
from unittest.mock import patch
import passwordmanpro_cli
import datetime
from python_Testing_Utilities import assertMultiLineStringsEqual
from samplePayloadsAndEnvs import envNoKey, envUrlWithSlash, envAPIKEYFILE, env, resourseResponse, resourseResponseRAW, resour... | nilq/baby-python | python |
#!/usr/bin/env python3
import utils, os, random, time, open_color, arcade
utils.check_version((3,7))
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Sprites Example"
class MyGame(arcade.Window):
def __init__(self):
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
file_path = ... | nilq/baby-python | python |
#!/usr/bin/python3
import sys
import os
from tqdm import tqdm
from binascii import b2a_hex
import pandas as pd
import pickle
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument, PDFNoOutlines
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPa... | nilq/baby-python | python |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... | nilq/baby-python | python |
import telegram
from telegram import *
from telegram.ext import *
import os
import responses
from dotenv import load_dotenv
load_dotenv()
TELEBOT_API_KEY = os.environ.get('TELE_BOT_API')
bot = telegram.Bot(token=TELEBOT_API_KEY)
updater = Updater(token=TELEBOT_API_KEY, use_context=True)
# Dispatcher
ud = updater.dis... | nilq/baby-python | python |
#!/usr/bin/python
# coding=utf-8
class BadRequest(Exception):
def __init__(self):
self.message = "Bad request"
class DuplicationError(BadRequest):
def __init__(self, field):
self.message = "Field {wrong} already exist".format(wrong=field)
class MissingFieldError(BadRequest):
def __init... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) 2002-2019 "Neo4j,"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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 L... | nilq/baby-python | python |
import logging
from device.base.power_source import PowerSource
from device.simulated.battery import Battery
from power_source_item import PowerSourceItem
from simulation_logger import message_formatter
class PowerSourceManager(object):
def __init__(self):
self.power_sources = []
self.logger = logg... | nilq/baby-python | python |
import tools
import torch
a = torch.randn(1,6).cuda()
b = tools.stereographic_project(a)
c = tools.stereographic_unproject(b)
print (tools.normalize_vector(a))
print (tools.normalize_vector(b))
print (tools.normalize_vector(c)) | nilq/baby-python | python |
from .move import MoveAction # noqa
from .inspect import InspectAction # noqa
from .menus import ( # noqa
ShowMenuAction,
ShowInventoryAction, SelectInventoryItemAction,
BackToGameAction, BackToInventoryMenuAction,
ShowCharacterScreenAction)
from .action import NoopAction, WaitAction # noqa
from .t... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import (nested_scopes, generators, division, absolute_import,
with_statement, print_function, unicode_literals)
from grass.pygrass.modules.interface.docstring import docstring_property
from grass.pygrass.modules.interface import read
class Flag(object):
... | nilq/baby-python | python |
#!/usr/bin/python3
"""
Script to delete all of the CloudFormation stacks in an account.
This will loop until all of them are deleted, with an exponental
backoff.
"""
import boto3
from time import sleep
from colorama import Fore, Style
client = boto3.client("cloudformation")
cloudformation = boto3.resource("cloudforma... | nilq/baby-python | python |
from database.database import Database
from flask import request
from flask_restful import Resource
import re
class Sources(Resource):
def post(self):
body = request.get_json()
db = Database()
results = []
if "domain" in body:
results += db.find_by_domain(body["domain"]... | nilq/baby-python | python |
from res_manager import ResultManager
import os
def test_all():
if os.path.exists('./data.db'):
os.remove('./data.db')
rm = ResultManager('.')
rm.save([1, 2, 3], topic='test saving', name='data1', comment='Test saving a list')
rm.save(65535, topic='test saving', comment='Test saving a number w... | nilq/baby-python | python |
import socket, re, subprocess, os, time, threading, sys, re, requests
server = "192.186.157.43"
channel = "#channel_to_connect" #write here the channel you want to connect
botnick = "youtubeBot"
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((server, 6667))
ircsock.send("USER "+ bo... | nilq/baby-python | python |
import os
import json
import time
from copy import deepcopy
from datetime import date, datetime
from decimal import Decimal
from random import random, randint, choice
import stdnet
from stdnet.utils import test, zip, to_string, unichr, ispy3k, range
from stdnet.utils import date2timestamp
from stdnet.utils.populate im... | nilq/baby-python | python |
with open('2016/day_03/list.txt', encoding="utf-8") as f:
lines = f.readlines()
t = []
c = 0
for i in lines:
w = ''
for a in i:
if a != ' ': w += str(a)
if a == ' ' and w != '':
t.append(int(w))
w = ''
if a == '\n': t.append(int(w.split('\n')[0]))
t.sort(... | nilq/baby-python | python |
# -*- coding = utf-8 -*-
# @Time:2021/3/1917:36
# @Author:Linyu
# @Software:PyCharm
from datetime import datetime
from web import db
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import DataRequired,Length
class Message(db.Model):
id = db.Colum... | nilq/baby-python | python |
import numpy as np
import pytest
from ..simulator import adjacent, Simulator
from ..problem import Problem
def simple_problem():
return Problem(10, 10, np.ones((3, 3)) * 5)
def test_adjacent():
assert adjacent((1, 1), (1, 2))
assert adjacent((1, 1), (2, 1))
assert adjacent((1, 1), (1, 0))
asser... | nilq/baby-python | python |
from pptx import Presentation
from paragraphs_extractor.file_iterator_interface import FileIteratorInterface
class PPTXIterator(FileIteratorInterface):
def __init__(self, filename):
super().__init__()
self.filename = filename
prs = Presentation(filename)
for slide in prs.sl... | nilq/baby-python | python |
import turtle
def draw_square(some_turtle, shape, color, side_length, speed):
some_turtle.shape(shape)
some_turtle.color(color)
some_turtle.speed(speed)
for i in range(1,5):
some_turtle.forward(side_length)
some_turtle.right(90)
def draw_circle(some_turtle, shape, color, radi... | nilq/baby-python | python |
from django.apps import AppConfig
class GgConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'GG'
| nilq/baby-python | python |
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from website.models import Exam, Problem, Task, Competitor, Score
from django.http import HttpResponse
@login_required
def view_problem(request, exam_id, ... | nilq/baby-python | python |
"""Apply high level effects to images such as shadows and convert to black and white."""
from __future__ import annotations
from pathlib import Path
from blendmodes.blend import BlendType, blendLayers
from colourswatch.io import openColourSwatch
from layeredimage.layeredimage import LayeredImage
from PIL import Image... | nilq/baby-python | python |
'''
Python module for creating synthetic data sets.
'''
import os
import csv
import math
import random
from typing import List, Dict
param_funcs = [
lambda x: math.factorial(abs(x) ** 0.1 // 1),
lambda x: math.frexp(x)[0],
lambda x: math.log(abs(x) + 0.1),
lambda x: math.log(abs(x) + 0.1, 5),
lamb... | nilq/baby-python | python |
#!/usr/bin/env python
from logging import StreamHandler
from typing import Optional
from datetime import datetime
class CLIHandler(StreamHandler):
def formatException(self, _) -> Optional[str]:
return None
def format(self, record) -> str:
exc_info = record.exc_info
if record.exc_info... | nilq/baby-python | python |
from __future__ import division
from ...problem_classes.heat_exchange import *
from pyomo.environ import *
from pyomo.opt import SolverFactory
# Helper for precision issues
epsilon = 0.0000001
def solve_fractional_relaxation(inst,lamda):
# Local copy of the instance
n = inst.n
m = inst.m
k = inst.k
QH = list... | nilq/baby-python | python |
from __future__ import absolute_import, unicode_literals
import itertools
import django
from django import template
from wagtail.wagtailcore import hooks
register = template.Library()
@register.inclusion_tag('wagtailusers/groups/includes/formatted_permissions.html')
def format_permissions(permission_bound_field):
... | nilq/baby-python | python |
import math
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import roc_auc_score
from torchvision import datasets, transforms
from tqdm import tqdm, trange
DEVICE = torch.device("cuda" if torch.cuda.... | nilq/baby-python | python |
import Tkinter as tk
import random
import time
import pygame as p
import random
import math
mutation_rate=10
increase_rate=0.1
complex=True
pop_size=200
black=((0,0,0))
fps=60
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
grid=[]
size=20
w=32
flag=0
mousepos=[]
space="udlr"
sp... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from glob import glob
#################################
#
# MAIN
#
#################################
if __name__ == "__main__":
import argparse
from pysedm import io, rainbowcam
parser = argparse.ArgumentParser(
description="""Build the ... | nilq/baby-python | python |
# oci-utils
#
# Copyright (c) 2018, 2019 Oracle and/or its affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown
# at http://oss.oracle.com/licenses/upl.
import logging
import os
import os.path
import subprocess
import cache
import oci_utils
from oci_utils import _configura... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.