content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from csv import reader, writer
from datetime import date
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import db, create_app
from app.constants import FILE_HANDLES
from app.models import Users, RepExercisesTaxonomy, RepExercisesHistory, TimeExe... | nilq/baby-python | python |
#!/usr/bin/env python
from setuptools import setup
from setuptools.extension import Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.egg_info import egg_info
from setuptools.command.sdist import sdist
from distutils import errors
import os
import sys
# ========================== c... | nilq/baby-python | python |
import datetime
import email
# import time
from datetime import datetime
from email.utils import parsedate
def convert_to_http_date_format(date_time):
# def httpdate(dt)
# https://stackoverflow.com/questions/225086/rfc-1123-date-representation-in-python
# A manual way to format it which is identical with... | nilq/baby-python | python |
from collections import OrderedDict
from types import MethodType
from django.db.models import Field
from django.db.models import sql
from django.db.models.sql.compiler import *
class SQLCompiler:
def get_return_fields(self):
cols, params = [], []
col_idx = 1
for _, (s_sql, s_params), alia... | nilq/baby-python | python |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.utils import six
from django.conf import settings
import json
class OpenIDConnectConfigurationTestCase(TestCase):
"""
Test OpenIDConnectConfiguration URI
"""
def setUp(self)... | nilq/baby-python | python |
from asciisciit import lut
import pytest
@pytest.mark.parametrize("lut_name", ("simple", "binary", "\u3105\u3106\u3107"))
def test_bars(lut_name):
lut.bars(lut_name)
def test_linear_lut():
l = lut.linear_lut("123456789")
assert(len(l._chars) == 9)
assert(len(l._bins) == 8)
def test_get_lut():
... | nilq/baby-python | python |
import asyncio
@asyncio.coroutine
def test_async():
print((yield from func()))
@asyncio.coroutine
def func():
return "Hello, async world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(test_async()) | nilq/baby-python | python |
from math import copysign
import pxng
from pxng.colors import *
from pxng.keys import *
def update(window: pxng.Window):
handle_input(window)
window.draw_grid(tint=DARK_GREY)
window.draw_text(10, 10, 'Text Rendering', tint=LIGHT_BLUE)
# Use the bitmap font as something interesting to scroll through... | nilq/baby-python | python |
import logging
from ..extended_properties import ExtendedProperty
from ..fields import BooleanField, ExtendedPropertyField, BodyField, MailboxField, MailboxListField, EWSElementField, \
CharField, IdElementField, AttachmentField
from ..properties import InvalidField, IdChangeKeyMixIn, EWSElement, ReferenceItemId, ... | nilq/baby-python | python |
# ---------------------------------------------------------------------
# Iskratel.MSAN.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pyth... | nilq/baby-python | python |
"""Write a model protocol buffer to mat file."""
from deepnet import util
import numpy as np
import sys
import scipy.io
import scipy.io as sio
import gzip
import os
def Convert(mat_file, out_file):
""" Create the necesarry things"""
matfile = sio.loadmat(mat_file)
# get the weight matrix
weight = np.... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
| nilq/baby-python | python |
import copy
import json
from pytests.basetestcase import BaseTestCase
from pytests.security.x509_multiple_CA_util import x509main, Validation
class MultipleCANegative(BaseTestCase):
def setUp(self):
super(MultipleCANegative, self).setUp()
self.x509 = x509main(host=self.master)
for server... | nilq/baby-python | python |
# -*- coding=utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... | nilq/baby-python | python |
# Test file for each of the component of CRUD operation of API routers | nilq/baby-python | python |
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# ALLOWED_HOSTS must be correct in production!
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
# Databases
DATABASES['default']['NAME'] = 'hobo'
DATABASES['default']['USER'] = 'hobo'
DATABASES[... | nilq/baby-python | python |
import argparse
import sys
from datetime import datetime
import badget
def parse_args():
parser = argparse.ArgumentParser(
description='Simple transactional budget app',
epilog=f'Example: python3 {sys.argv[0]} "./budgets/2019" -w "2019-12-01 12:30:00" -sc -sa -v')
parser.add_argument('budget_... | nilq/baby-python | python |
# coding: utf-8
"""
DFC
DFC is a scalable object-storage based caching system with Amazon and Google Cloud backends. # noqa: E501
OpenAPI spec version: 1.1.0
Contact: dfcdev@exchange.nvidia.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
... | nilq/baby-python | python |
from segtypes.n64.segment import N64Segment
from segtypes.linker_entry import LinkerEntry
from util import options, log
class CommonSegLib(N64Segment):
def __init__(self, rom_start, rom_end, type, name, vram_start, extract, given_subalign, given_is_overlay, given_dir, args, yaml):
super().__init__(rom_st... | nilq/baby-python | python |
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
if __name__ == '__main__':
number_of_trials = [0, 2, 10, 20, 50, 500]
data = stats.bernoulli.rvs(0.5, size=number_of_trials[-1])
x = np.linspace(0, 1, 100)
for i, N in enumerate(number_of_trials):
heads = data[:N].sum... | nilq/baby-python | python |
import enum
class appErrorCodes(enum.Enum):
OK = 0
METER_NOT_FOUND = 431
MISSING_INPUT = 432
INVALID_INPUT = 433
BAD_DB_INSERT = 434
| nilq/baby-python | python |
from pytorch_lightning import LightningModule
import torch
from torch.utils.data import Dataset
class RandomDataset(Dataset):
def __init__(self, size, num_samples):
self.len = num_samples
self.data = torch.randn(num_samples, size)
def __getitem__(self, index):
return self.data[index]
... | nilq/baby-python | python |
# Generated by Django 3.0.13 on 2021-04-08 09:59
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
import pretix.base.models.base
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0184_customer'),
]
operations = [
mi... | nilq/baby-python | python |
# Contains dictionaries that map English letters to braille.
letters = {
"a": chr(10241),
"b": chr(10243),
"c": chr(10249),
"d": chr(10265),
"e": chr(10257),
"f": chr(10251),
"g": chr(10267),
"h": chr(10259),
"i": chr(10250),
"j": chr(10266),
"k": chr(10245),
"l": chr(10... | nilq/baby-python | python |
import os
import pandas as pd
import numpy as np
import warnings
import math
from sklearn.ensemble import ExtraTreesRegressor, AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import KFold, LeaveOneGroupOut, GroupKFold
from sklearn.model_selection import cross_val_score,... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import numpy as np
def main():
lst = [1,2,3,4,5]
lst_01 = get_average_by_sum(lst)
print('by sum(): ')
print(lst_01)
lst_02 = get_average_by_numpy(lst)
print('by numpy: ')
print(lst_02)
# Using sum()
def get_average_by_sum(lst):
average = sum(lst)/len... | nilq/baby-python | python |
import configparser
import os
con=configparser.ConfigParser()
def readconf(n):
con.read('step.ini')
step=con.get("config",n)
step=int(step)
return step
def writestep(num,n):
con.read('step.ini')
con.set("config",n,str(num))
con.write(open('step.ini','w'))
| nilq/baby-python | python |
import pygame
import sys
import serial
ser = serial.Serial('/dev/cu.usbmodem14202', 115200, timeout = 1000)
serial_buffer = ''
pygame.init()
pygame.display.set_mode((320,200))
pygame.display.set_caption('Serial communication')
clock = pygame.time.Clock()
while True:
clock.tick(60)
serial_data = ser.read()
... | nilq/baby-python | python |
from recorder import Recorder
from twitch import TwitchClient, constants as tc_const
# Checker class
# It's check streams and
import logging
class Checker:
# Twitch client from main.py
client: TwitchClient = None
# Twitch user id for check
id = None
# Twitch user name for check
username = ""... | nilq/baby-python | python |
#!/usr/bin/env python3
import argparse
import os
import requests
import sys
import sqlite3
import time
__author__ = "pacmanator"
__email__ = "mrpacmanator at gmail dot com"
__version__ = "v1.0"
def get_file():
"""
Downloads a list of OUIs.
"""
url = "https://linuxnet.ca/ieee/oui/nmap-mac-prefixe... | nilq/baby-python | python |
# GENERATED FILE - DO NOT EDIT
VERSION = '201909061227'
BUILDS = {}
| nilq/baby-python | python |
"""Choice type.
A union type similar to the `Result` type. But also allows for higher
number of choices. Usually you would most likekly want to use the
`Result` type instead, but choice can be preferered in non-error cases.
"""
from abc import ABC
from typing import Any, Generic, Iterable, TypeVar, get_origin, overloa... | nilq/baby-python | python |
from . import utils
class ContinuousScale(object):
def __init__(self, data_lim, svg_lim):
self.data_0 = data_lim[0]
self.data_len = utils.lims2len(data_lim)
self.svg_0 = svg_lim[0]
self.svg_len = utils.lims2len(svg_lim)
def __call__(self, value):
return self.svg_0 + s... | nilq/baby-python | python |
#!/usr/bin/python3
# Copyright 2020 Uraniborg authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
with tf.Session() as sess:
with tf.gfile.GFile('./artifacts/model2.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def)
input_node = sess.graph.get_tensor_by_name('import/inpu... | nilq/baby-python | python |
from PIL import Image
from PIL import ImageFilter
def resizeImgInsta(imgOrig,useBGBlurInsteadOfWhiteBG=False,fotoSeries=False):
#from PIL import Image
#from PIL import ImageFilter
MAX_INSTA_IMG_PortSide_HEIGHT = 1350;
MAX_INSTA_IMG_LandSide_SIZE=1080;
MIN_INSTA_ING_LANDSIZE_HEIGHT=608;
BG_COL... | nilq/baby-python | python |
#
# PySNMP MIB module TIARA-NETWORKS-CONFIG-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIARA-NETWORKS-CONFIG-MGMT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:16:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | nilq/baby-python | python |
"""
Demonstration handle dump for CMIP/ESGF files ..
USAGE
=====
-h: print this message;
-v: print version;
-t: run a test
-f <file name>: examine file, print path to replacement if this file is obsolete, print path to sibling files (or replacements).
-id <tracking id>: examine handle record of tracking id.
-V:... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | nilq/baby-python | python |
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$ 1.250,00, calcule um aumento de 10%. Para salários inferiores ou iguais o aumento é de 15%.
nome = str(input('Informe o seu nome: '))
salario = float(input('Informe o seu salário: '))
salariom... | nilq/baby-python | python |
from test.apps.openapi._fastapi.app import app
import pytest
import schemathesis
from schemathesis import Case
from schemathesis.constants import SCHEMATHESIS_TEST_CASE_HEADER, USER_AGENT
schema = schemathesis.from_dict(app.openapi())
@pytest.mark.parametrize("headers", (None, {"X-Key": "42"}))
@schema.parametrize... | nilq/baby-python | python |
import torch, os
def mask_(matrices, maskval=0.0, mask_diagonal=True):
"""
Masks out all values in the given batch of matrices where i <= j holds,
i < j if mask_diagonal is false
In place operation
:param tns:
:return:
"""
b, h, w = matrices.size()
indices = torch.triu_indices(h, ... | nilq/baby-python | python |
# coding: utf-8
"""
Encoding DER to PEM and decoding PEM to DER. Exports the following items:
- armor()
- detect()
- unarmor()
"""
from __future__ import unicode_literals, division, absolute_import, print_function
import base64
import re
import sys
from ._errors import unwrap
from ._types import type_name, str... | nilq/baby-python | python |
# Copyright (c) 2021, erpcloud.systems and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
import frappe, erpnext, json
from frappe import _, scrub, ValidationError, throw
from frappe.utils import flt, comma_or, nowdate, getdate, cint
from erpne... | nilq/baby-python | python |
from django.contrib import admin
from .models.board_model import Board
# Register your models here.
from .models.todo_model import TblTodo
admin.site.register(TblTodo)
admin.site.register(Board)
| nilq/baby-python | python |
from flask import Flask, jsonify, request
import docker
from flask_cors import CORS
DEBUG = True
CONTAINERS = []
app = Flask(__name__)
app.config.from_object(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
def remove_container(container_id):
container = client.containers.get(container_id)
container... | nilq/baby-python | python |
def read_file_and_convert_to_list(file_path, ignore_comment=True):
"""
This method read in file and convert it to list, separated by line-breaker
:param file_path: path to the file
:param ignore_comment: if True, will ignore the line start with '#'; if False, read all.
:return: list of strings
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# coding: utf8
"""
/***************************************************************************
coller
A QGIS plugin
Paste selected vetors to vector layer
-------------------
begin : 2017-12-01
git sh... | nilq/baby-python | python |
import numpy as np
from colors import bcolors
from os import listdir
from sklearn.externals import joblib
from os.path import isfile, join
from neural_net_trainer import Collision_NN_Trainer
import os
class Config_Engine:
def __init__(self, collision_graph, vars, config_fn='', override=False):
self.collis... | nilq/baby-python | python |
# License: MIT
import time
import os
import numpy as np
import pickle as pkl
from openbox.utils.logging_utils import get_logger, setup_logger
from openbox.core.message_queue.master_messager import MasterMessager
PLOT = False
try:
import matplotlib.pyplot as plt
plt.switch_backend('agg')
PLOT = True
except... | nilq/baby-python | python |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include".split(';') if "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include" != "" else []
PROJECT_CATKIN_DEPEN... | nilq/baby-python | python |
CID=0
CFROM=1
CTO=2
CSPEED=3
CPLANTIME=4
RID=0
RLENGTH=1
RSPEED=2
RCHANNEL=3
RFROM=4
RTO=5
RISDUPLEX=6
XID=0
XXY=0
XUP=1
XRIGHT=2
XDOWN=3
XLEFT=4
X=0
Y=1
global cars
global roads
global crosses
global crossxy
global crossid
cars={}
roads={}
crosses={}
crossxy={}
crossid={}
with open('car.txt','r') as f:
for i in f.... | nilq/baby-python | python |
"""PyTorch implementation of the LARNN, by Guillaume Chevalier."""
import math
import copy
from collections import deque
import torch
from torch import nn
import torch.nn.functional as F
from multi_head_attention import MultiHeadedAttention, PositionalEncoding
__author__ = "Guillaume Chevalier"
__license__ = "MIT... | nilq/baby-python | python |
#!/usr/bin/python2.5
#
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | nilq/baby-python | python |
"""Example package for generating stardoc from rules_nodejs at source"""
load("@build_bazel_rules_nodejs//packages/typescript:index.bzl", "ts_library")
def custom_ts_library(name, deps = [], **kwargs):
"""
Helper wrapper around ts_library adding default attributes and dependencies
Args:
name: The... | nilq/baby-python | python |
from app import db
class Player(db.Model):
__tablename__ = "players"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(128))
# TODO maybe make uid and provider TOGETHER be unique
# UniqueConstraint('col2', 'col3', name='uix_1')
uid = db.Column(d... | nilq/baby-python | python |
from tempConversions import *
def test_temp_conversions_fToC_32_0():
assert fToC(32.0) == 0.0
def test_temp_conversions_fToC_212_100():
assert fToC(212.0) == 100.0
def test_temp_conversions_cToF_0_32():
assert cToF(0.0) == 32.0
def test_temp_conversions_cToF_100_212():
assert cToF(100.0) == 212.0
| nilq/baby-python | python |
range(5, 10) # 5, 6, 7, 8, 9
range(0, 10, 3) # 0, 3, 6, 9
range(-10, -100, -30) # -10, -40, -70
range(-10, -101, -30) # -10, -40, -70 -100
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# Poio Tools for Linguists
#
# Copyright (C) 2009-2014 Poio Project
# Author: Peter Bouda <pbouda@cidles.eu>
# URL: <http://media.cidles.eu/poio/>
# For license information, see LICENSE.TXT
from __future__ import unicode_literals
import os
import poioapi.io.mandinka
import poioapi.data
impo... | nilq/baby-python | python |
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
# @Author skillnull
# @Function 获取网易云音乐评论
import os
import random
import sys
import json
import time
import base64
import codecs
import requests
import multiprocessing # 多进程
from Crypto.Cipher import AES
import re # 正则表达式库
import numpy as np # numpy数据处理库
import co... | nilq/baby-python | python |
import os
import sys
import base64, json, re
import time
import requests
import api
from time import sleep as timeout
from requests import get
R='\033[1;31m'; B='\033[1;34m'; C='\033[1;37m'; Y='\033[1;33m'; G='\033[1;32m'; RT='\033[;0m'
os.system('git pull && clear')
a='aHR0cDovL3d3dy5qdXZlbnR1ZGV3ZWIubXRlL... | nilq/baby-python | python |
"""
Copyright (c) 2018-2021 Intel Corporation
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 w... | nilq/baby-python | python |
input_data = list(map(int, input().split()))
row = input_data[0]
column = input_data[1]
graph = []
result = 0
for i in range(row):
graph.append(list(map(int, input())))
def dfs(x, y):
if x < 0 or x > row - 1 or y < 0 or y > column - 1:
return False
if graph[x][y] == 1:
return False
graph[x][... | nilq/baby-python | python |
# Generated by Django 2.2 on 2019-05-19 12:29
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... | nilq/baby-python | python |
from justgood import imjustgood
media = imjustgood("YOUR_APIKEY_HERE")
tgl = "17-08-1945" # example birth date
data = media.lahir(tgl)
# Get attributes
result = "Lahir : {}".format(data["result"]["lahir"])
result = "\nHari : {}".format(data["result"]["hari"])
result = "\nZodiac : {}".format(data["result"]["zodiak"])
... | nilq/baby-python | python |
from keras.models import Sequential
from keras.layers import Embedding
import numpy as np
model = Sequential()
model.add(Embedding(1000, 1, input_length=10))
# the model will take as input an integer matrix of size (batch, input_length).
# the largest integer (i.e. word index) in the input should be no larger than 999... | nilq/baby-python | python |
"""Redis: Delete emote hashes
Revision ID: 5f746af0a82d
Revises: 186928676dbc
Create Date: 2019-06-04 19:07:25.109751
"""
from pajbot.managers.redis import RedisManager
from pajbot.streamhelper import StreamHelper
# revision identifiers, used by Alembic.
revision = '5f746af0a82d'
down_revision = '186928676dbc'
br... | nilq/baby-python | python |
from django.conf.urls import url
from wagtailnetlify.views import success_hook, redirects
urlpatterns = [
url(r"^success$", success_hook, name="success_hook"),
url(r"^redirects$", redirects, name="redirect_builder"),
]
| nilq/baby-python | python |
from reversion.revisions import create_revision, set_user, set_comment, deactivate
class RevisionMiddleware:
"""Wraps the entire request in a revision."""
manage_manually = False
using = None
atomic = True
def __init__(self, get_response):
self.get_response = get_response
def __c... | nilq/baby-python | python |
#!/usr/bin/env python -*- coding: utf-8 -*-
from config import *
from flask import Flask, render_template, Response, jsonify, request, redirect, url_for
from jinja2 import Template
import json
import pigpio
from i2c import I2c
from motor import Motor
import time
from threading import Thread
import sys
import sqlite3
im... | nilq/baby-python | python |
from PyDictionary import PyDictionary
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter("ignore")
dictionary=PyDictionary()
s = ""
old_s = ""
while(s != "0"):
s = input("Word / option: ")
print("")
if s == "1":
if old_s == "":
print("No previous records")
else:
print(dict... | nilq/baby-python | python |
import os
import numpy
import tensorflow as tf
import scipy as scp
import scipy.misc
KITTI_TRAIN_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/image_2/'
KITTI_GT_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/gt_image_2/'
UM_TRAIN_TEMPLATE = "um_0000%02... | nilq/baby-python | python |
from urllib.parse import urlparse, unquote
from records_mover.url.gcs.gcs_directory_url import GCSDirectoryUrl
from typing import IO
from records_mover.url import BaseFileUrl
from smart_open.gcs import open as gs_open
import google.cloud.storage
from google.cloud.storage.blob import Blob
import google.api_core.exceptio... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from openerp import SUPERUSER_ID
from openerp.osv import orm, fields
class PaymentTransaction(orm.Model):
_inherit = 'payment.transaction'
_columns = {
# link with the sale order
'sale_order_id': fields.many2one('sale.order', 'Sale Order'),
}
def form_feedbac... | nilq/baby-python | python |
#!/usr/bin/env python
from multi_circle_2 import Multi_circle_2
if __name__ == '__main__':
multi_circle_2 = Multi_circle_2(
[
#x , y, z, yaw, sleep
[0.0 , 0.0, 1.0, 0, 8],
[0.0 , 0.0 ,1.0, 0, 3],
[-0.3 , -1.4, 0.0, 0, 0],
]
)
multi_circle_2.run(... | nilq/baby-python | python |
# Given a column title as appear in an Excel sheet, return its corresponding column number.
# For example:
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
# AB -> 28
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
d = {'... | nilq/baby-python | python |
"""
Clustered/Convolutional/Variational autoencoder, including demonstration of
training such a network on MNIST, CelebNet and the film, "Sita Sings The Blues"
using an image pipeline.
Copyright Yida Wang, May 2017
"""
import matplotlib
import tensorflow as tf
import numpy as np
from scipy.misc import imsave
import o... | nilq/baby-python | python |
"""
This provides wrappers for FMUs so they are easy to assemble in a short
script, as well as support writing data in HDF5 format using pytable, as
well as a library of FMUs ready to be assembled.
The structure of the file starts with the FMU utilities, goes on to define
modules and simulations, and ends with a list... | nilq/baby-python | python |
import numpy as np
from jitcdde import input as system_input
from symengine import exp
from ..builder.base.constants import EXC, INH, LAMBDA_SPEED
from ..builder.base.network import SingleCouplingExcitatoryInhibitoryNode
from ..builder.base.neural_mass import NeuralMass
from .model_input import OrnsteinUhlenbeckProces... | nilq/baby-python | python |
import os
import shutil
os_license = '{{ cookiecutter.license }}'
notebooks = '{{ cookiecutter['jupyter notebooks'] }}'
containers = '{{ cookiecutter.containers }}'
if os_license == "No license file":
os.remove("LICENSE")
if notebooks == "No":
shutil.rmtree("src/notebooks")
if containers == "one":
shuti... | nilq/baby-python | python |
"""Basic functionality sanity tests"""
from urllib.parse import urljoin
import pytest
# Various sub-urls for the main page
PAGE_URL_LIST = ["", "about/", "docs/", "scls/"]
# Various sub-urls for a collection
SCL_URL_LIST = ["", "edit/", "coprs/", "repos/", "acl/", "review_req/"]
@pytest.mark.django_db
def test_scl_... | nilq/baby-python | python |
from collections import OrderedDict
import jsonschema
from django.db.models import Q
from jsonschema import Draft4Validator
from rest_framework import serializers
from architecture_tool_django.modeling.models import Edgetype, Nodetype
from ..models import Edge, Node
class EdgeSerializer(serializers.ModelSerializer... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from patsy import dmatrix
from patsy import DesignMatrix, DesignInfo
from patsy import LookupFactor,ModelDesc,Term
X = [[1, 10], [1, 20], [1, -2]]
print(dmatrix(X))
design_info = DesignInfo(["Intercept!", "Not intercept!"])
X_dm = DesignMatrix(X, design_info)
print(dmatri... | nilq/baby-python | python |
table_file_template = """
import argparse
from deriva.core import ErmrestCatalog, AttrDict, get_credential
import deriva.core.ermrest_model as em
from deriva.core import tag as chaise_tags
from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args
{groups}
table_name = '{table_name}'
schema_na... | nilq/baby-python | python |
from opentelemetry import trace
from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor
trace.set_tracer_provider(TracerProvider())
cloud_trace_exporter = CloudTraceSpanExporter()
trac... | nilq/baby-python | python |
# Duas formas para se fazer a leitura de um número inteiro...#
def leiaint(msg):
valor = 0
while True:
n = str(input(msg))
if n.isnumeric():
valor = int(n)
break
else:
print('\033[31mERRO ! Digite um número inteiro válido.\033[m')
retur... | nilq/baby-python | python |
from torch.nn import CrossEntropyLoss
class GPT2Loss(CrossEntropyLoss):
def __init__(self, pad_token_id):
super(GPT2Loss, self).__init__(ignore_index=pad_token_id)
def forward(self, output, labels):
"""
Loss function for gpt2
:param output:
:param labels:
:retu... | nilq/baby-python | python |
from mccq.cli import cli
| nilq/baby-python | python |
import sys
from bidi.algorithm import get_display
# variable length print, the string constants are adjusted for bidi.
# an unrelated editor is that vs code doesn't support bidi.
# the workaround is to put bidi text into separate string variables.
#not entirely sure, if we need to swap each element seperately...
def... | nilq/baby-python | python |
import os
from pathlib import Path
from string import Template
template = Template("""
Package: zram-swap
Version: $version
Depends: python3, libpython3-stdlib
Section: custom
Priority: optional
Architecture: all
Essential: no
Installed-Size: $size
Maintainer: Dmitry Orlov <me@mosquito.su>
Description: Easy way to co... | nilq/baby-python | python |
"""Test label"""
from napari.components.text_overlay import TextOverlay
def test_label():
"""Test creating label object"""
label = TextOverlay()
assert label is not None
| nilq/baby-python | python |
import sys, clr
import ConfigParser
from os.path import expanduser
# Set system path
home = expanduser("~")
cfgfile = open(home + "\\STVTools.ini", 'r')
config = ConfigParser.ConfigParser()
config.read(home + "\\STVTools.ini")
# Master Path
syspath1 = config.get('SysDir','MasterPackage')
sys.path.append(syspath1)
# Bui... | nilq/baby-python | python |
import json
from urllib.parse import urlencode
from flask import Response, request
def _create_link(path, limit, offset, order_by, order_how, args_dict):
# copy of the dict passed in so we don't modify the original
params = dict(args_dict)
params["limit"] = limit
params["offset"] = offset
params... | nilq/baby-python | python |
from distutils.core import setup
setup(
name='http_request',
version='1.1',
packages=['http_request'],
url='https://github.com/dennisfischer/http_request',
license='MIT',
author='Dennis Fischer',
author_email='dennis.fischer@live.com',
description='A small python library to parse and bu... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2018. Authors: see NOTICE file.
# *
# * 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... | nilq/baby-python | python |
import pandas as pd
from age.data.load.countries import base
from age.data.load import transformations
from age.data.load import utils
from age.data.load import ined
import logging
import datetime
from urllib.request import urlopen
_CASES_PATH = 'https://data.rivm.nl/covid-19/COVID-19_casus_landelijk.csv'
_INED_URL = ... | nilq/baby-python | python |
"""
MIT License
Copyright (c) 2018 Elias Doehne
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, modify, merge, publish, ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
import xml.dom.minidom
import argparse
class Config():
def __add_server(self, parent_node, settings, server_name):
try:
os.environ["TRAVIS_SECURE_ENV_VARS"]
except KeyError:
print "no secur... | nilq/baby-python | python |
#!/usr/bin/python
import gzip
import socket
#UDP_IP = "127.0.0.1"
UDP_IP = "0.0.0.0"
UDP_PORT = 6550
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
f = gzip.open('flight.dat.gz', 'wb')
print "Aura Logger"
print "listening for", UDP_IP,... | nilq/baby-python | python |
"""REST API endpoints"""
from fastapi import APIRouter
from app.api.api_v1.endpoints import items, users
api_router = APIRouter()
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(items.router, prefix="/items", tags=["items"])
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.