content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... | nilq/baby-python | python |
from django.db import models
from django.utils import timezone
from django.db.models import Q
from django_filters.rest_framework import *
from django_filters import filters
from django_filters.constants import EMPTY_VALUES
class Filter(FilterSet):
def __init__(self,form,request=None,queryset=None):
quer... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
flask_micron.method
===================
This module provides the functionality for wrapping functions to
make them work for Flask-Micron request handling.
:copyright: (c) 2016 by Maurice Makaay
:license: BSD, see LICENSE for more details.
"""
import re
import sys
import traceback
from f... | nilq/baby-python | python |
import os
import testinfra.utils.ansible_runner
runner = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE'])
ALL_HOSTS = runner.get_hosts('all')
MANAGER_HOSTS = runner.get_hosts('docker_swarm_manager')
WORKER_HOSTS = runner.get_hosts('docker_swarm_worker')
testinfra_hosts = ALL_HOSTS
... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import os
import subprocess
import tempfile
import re
import itertools
import hashlib
import shutil
import argparse
def parse_stats(stats):
m = re.search('([0-9]+) work registers', stats)
registers = int(m.group(1)) if m else 0
m = re.search('([0-9]+) uniform registers',... | nilq/baby-python | python |
#
# PySNMP MIB module HPN-ICF-FR-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FR-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:26:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | nilq/baby-python | python |
#!/usr/bin/env python3
from uuid import UUID, uuid4
def generate_client_token():
return uuid4().hex
def is_valid_uuid(uuid_string):
try:
UUID(uuid_string)
except ValueError:
return False
return True
| nilq/baby-python | python |
from .gui import *
from .ui import *
| nilq/baby-python | python |
import numpy as np
from typing import Type
from nn.activations import Activation, Sigmoid
class Layer:
m, n = None, None
class Input(Layer):
def __init__(self, n_features, batch_size):
self.m = n_features
self.n = batch_size
self.cache = dict()
def forward_step(self, x):
... | nilq/baby-python | python |
import numpy as np
from matplotlib import pyplot as plt
import time
from numba import jit
def load_delta_U(fname):
# Assumes npz
npz_arr = np.load(fname)
delta_U = npz_arr['arr_0']
print("Successfully Loaded covariate distances from {}".format(fname))
return delta_U
def create_delta_U(dmr, U, dU... | nilq/baby-python | python |
import time
from datetime import datetime
# our libs
from src import lcd
def renderDisplay():
# Initialise display
lcd.lcd_init()
now = datetime.now()
# dd/mm/YY H:M:S
date_time = now.strftime("%d/%m/%Y %H:%M:%S")
# Send some more text
lcd.lcd_string("Akaal last fed:", lcd.LCD_LINE_1)... | nilq/baby-python | python |
from typing import List, Dict, Callable, Optional
from utils.types import Box
from .utils import RELATIONS, optimize_latex_string
class SymbolTreeNode:
# these will be placed when a bracket should not be optimized
# for example `\frac{w}{a}` should not be converted to `\fracwa`, but `\frac{w}a` is fine
#... | nilq/baby-python | python |
import os
import tempfile
import unittest
from epregressions.builds.base import BaseBuildDirectoryStructure, autodetect_build_dir_type, KnownBuildTypes
class TestAutoDetectBuildType(unittest.TestCase):
def setUp(self):
self.build_dir = tempfile.mkdtemp()
def add_cache_file(self, content):
c... | nilq/baby-python | python |
from comprehemd.blocks import HeadingBlock
def test_repr() -> None:
block = HeadingBlock("foo", level=1, source="foo\n")
assert repr(block) == 'HeadingBlock("foo", level="1", source="foo\\n")'
def test_str() -> None:
block = HeadingBlock("foo", level=1, source="foo\n")
assert str(block) == "HeadingB... | nilq/baby-python | python |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="cae",
version="0.1",
author="Arsenii Astashkin",
author_email="ars.astashkin@gmail.com",
description="Hybrid Singular Value Decomposition (SVD) implementation",
long_description=long_d... | nilq/baby-python | python |
__________________________________________________________________________________________________
sample 16 ms submission
class Solution:
def combinationSum3(self, k: int, n: int, d:int = 9) -> List[List[int]]:
if k * (2 * d - k + 1) <= 2 * n:
return [list(range(d - k + 1, d + 1))] if k * (2 * ... | nilq/baby-python | python |
import pd_base_tests
import pdb
import time
import sys
from collections import OrderedDict
from ptf import config
from ptf.testutils import *
from ptf.thriftutils import *
import os
from pal_rpc.ttypes import *
from netlock.p4_pd_rpc.ttypes import *
from mirror_pd_rpc.ttypes import *
from res_pd_rpc.ttypes import *... | nilq/baby-python | python |
from fipie import NoCluster, EqualWeight
from fipie.data import load_example_data
from fipie.tree import Tree, create_tree
def test_create_tree():
price = load_example_data()
ret = price.asfreq('w', method='pad').pct_change()
tree = create_tree(ret, NoCluster())
assert len(tree.nodes) == ret.shape[1... | nilq/baby-python | python |
from __future__ import absolute_import
import os
import itertools
from numpy.testing import assert_equal
import pytest
from brian2 import *
from brian2.devices.device import reinit_and_delete
from brian2.tests.utils import assert_allclose
@pytest.mark.codegen_independent
def test_custom_events():
# Set (could b... | nilq/baby-python | python |
from django.db import models
from django.contrib.auth.models import AbstractUser
class BaseModel(models.Model):
"""
A base abstract model from which all other models will inherit.
"""
created = models.DateTimeField(
auto_now_add=True,
blank=True, null=True,
help_text='Record fi... | nilq/baby-python | python |
from __future__ import absolute_import
import pkg_resources
import setuptools
import setuptools.command.build_ext
import setuptools.command.test
__author__ = 'Shashank Shekhar'
__version__ = '0.14'
__email__ = 'shashank.f1@gmail.com'
__download_url__ = 'https://github.com/shkr/routesimilarity/archive/0.1.tar.gz'
try... | nilq/baby-python | python |
import json
import os
from itertools import groupby
from pathlib import Path
from typing import List, Union
from google.cloud import storage
def load_config(train_or_apply: str) -> dict:
"""Load config"""
config_file_path = Path(__file__).parent.resolve() / "config.json"
with open(config_file_path, "r") ... | nilq/baby-python | python |
# Adapted from repo botwizer by DevGltich
# https://github.com/DevGlitch/botwizer
# Resources used:
# https://github.com/AlexeyAB/darknet
# https://www.youtube.com/watch?v=Z_uPIUbGCkA
import cv2
import numpy as np
from time import sleep
def stream_object_detection_text(rtsp_url, config_path, weights_path, labels_pa... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from time import sleep
from visitor import *
from visitor import VisitInstrumentation, VISIT_MESHTYPE_POINT
counter = 0
def dp(*args, **kwargs):
x = np.linspace(-5.,4.,100)
y = np.linspace(0.,10.,100)
retu... | nilq/baby-python | python |
from os import environ
environ["MKL_THREADING_LAYER"] = "GNU"
import pymc3
import pymc as pymc2
import cPickle as pickle
import theano
import theano.tensor as tt
import numpy as np
from collections import OrderedDict
from time import sleep
from numpy import mean, std, square, percentile, median, sum as np_sum, array, o... | nilq/baby-python | python |
import launchpad_py as launchpad
MK2_NAME = "Launchpad MK2"
# MK3MINI_NAME = "LPMiniMK3"
MK3MINI_NAME = "minimk3"
PRO_NAME = "Launchpad Pro"
LPX_NAME = "lpx"
CTRL_XL_NAME = "control xl"
LAUNCHKEY_NAME = "launchkey"
DICER_NAME = "dicer"
PAD_MODES = {
launchpad.Launchpad: "Mk1",
launchpad.LaunchpadMk2: "Mk2",
... | nilq/baby-python | python |
import os
import shutil
import tempfile
from unittest import TestCase, skip
from IPython import embed
from qlknn.pipeline.pipeline import *
from tests.base import *
class TrainNNTestCase(TestCase):
def setUp(self):
self.settings = default_train_settings.copy()
self.settings.pop('train_dims')
... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from jawa.constants import *
from jawa.util.descriptor import method_descriptor
import six.moves
def class_from_invokedynamic(ins, cf):
"""
Gets the class type for an invokedynamic instruction that
calls a constructor.
"""
const = ins.operands[0]
bootstrap ... | nilq/baby-python | python |
"""
Content Provider: Metropolitan Museum of Art
ETL Process: Use the API to identify all CC0 artworks.
Output: TSV file containing the image, their respective meta-data.
Notes: https://metmuseum.github.io/
No rate limit specified.
"""
from m... | nilq/baby-python | python |
import numpy as np
from pymoo.experimental.deriv import DerivationBasedAlgorithm
from pymoo.algorithms.base.line import LineSearchProblem
from pymoo.algorithms.soo.univariate.exp import ExponentialSearch
from pymoo.algorithms.soo.univariate.golden import GoldenSectionSearch
from pymoo.core.population import Population... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-10 17:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... | nilq/baby-python | python |
from django.core.management.base import BaseCommand
import django.db.models.base
import core.models
class Command(BaseCommand):
help = 'Custom manage.py command to start celery.'
def add_arguments(self, parser):
parser.add_argument(
"needle", type=str, help="The uuid/field that you are l... | nilq/baby-python | python |
from pybricks.tools import wait
print("Started!")
try:
# Run your script here as you normally would. In this
# example we just wait forever and do nothing.
while True:
wait(1000)
except SystemExit:
# This code will run when you press the stop button.
# This can be useful to "clean up", s... | nilq/baby-python | python |
"""
This module contains a set of functions related to strings
>
> strcat : String concatenation for a 1xN list
> strcat_array : String concatenation for a MxN array
> strrep : String replacement for array
> repmat : Repeat char NxM times
> find : Find the location of a input character in... | nilq/baby-python | python |
from checkov.terraform.context_parsers.base_parser import BaseContextParser
class ResourceContextParser(BaseContextParser):
def __init__(self):
definition_type = 'resource'
super().__init__(definition_type=definition_type)
def get_block_type(self):
return self.definition_type
parser... | nilq/baby-python | python |
'''
Por algum motivo desconhecido, Rangel só tem um par de meias de cada cor.
Hoje ele está atrasado para ir a faculdade e ainda precisa pegar um par de meias, mas as meias estão todas bagunçadas.
Dado o número de pares de meias na gaveta de Rangel, ele quer saber quantas meias ele precisa pegar, no mínimo, para ter ... | nilq/baby-python | python |
"""
KGE Web User Interface Application Code package.
"""
from os import getenv, path
import logging
from kgea.server.web_services.kgea_session import KgeaSession
import jinja2
import aiohttp_jinja2
from aiohttp import web
import aiohttp_cors
from .kgea_ui_handlers import (
kge_landing_page,
kge_login,
kg... | nilq/baby-python | python |
"""
05-strange-attractors.py - Non-linear ordinary differential equations.
Oscilloscope part of the tutorial
---------------------------------
A strange attractor is a system of three non-linear ordinary
differential equations. These differential equations define a
continuous-time dynamical system that exhibits chaot... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import struct
from io import BytesIO
class Buffer(BytesIO):
"""
A buffer-like object with shortcut methods to read C objects
"""
def __read(self, size: int, unpack=None):
res = self.read(size)
if unpack:
res = struct.unpack(unpack, res)[0]
... | nilq/baby-python | python |
"""Saturation classes."""
from __future__ import annotations
from abc import ABC, abstractmethod
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted, check_array
class Saturation(BaseEstimator, TransformerMixin, ABC):
"""Base class fo... | nilq/baby-python | python |
from dsbox.template.template import DSBoxTemplate
from d3m.metadata.problem import TaskKeyword
from dsbox.template.template_steps import TemplateSteps
from dsbox.schema import SpecializedProblem
import typing
import numpy as np # type: ignore
class UMASSClassificationTemplate(DSBoxTemplate):
def __init__(sel... | nilq/baby-python | python |
''' This script handles local interactive inference '''
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import numpy as np
import spacy
from seq2seq.Models import Seq2Seq
from seq2seq.Translator import Translator
from seq2seq.Beam import Beam
from seq2seq import Constants
class Int... | nilq/baby-python | python |
"""Tests for encodings submodule."""
from nxviz import encodings as aes
import pytest
import pandas as pd
from random import choice
import numpy as np
def categorical_series():
"""Generator for categorical series."""
categories = "abc"
return pd.Series([choice(categories) for _ in range(30)])
def conti... | nilq/baby-python | python |
'''
Created by auto_sdk on 2015.04.03
'''
from aliyun.api.base import RestApi
class Mkvstore20150301DescribeInstancesRequest(RestApi):
def __init__(self,domain='m-kvstore.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.InstanceIds = None
self.InstanceStatus = None
self.NetworkType = N... | nilq/baby-python | python |
"About API endpoints."
import http.client
import flask
from webapp import utils
blueprint = flask.Blueprint("api", __name__)
@blueprint.route("")
def root():
"API root."
items = {
"schema": {
"root": {"href": utils.url_for("api_schema.root")},
"logs": {"href": utils.url_for... | nilq/baby-python | python |
data_all = pandas.read_csv('../data/gapminder_all.csv', index_col='country')
data_all.plot(kind='scatter', x='gdpPercap_2007', y='lifeExp_2007',
s=data_all['pop_2007']/1e6)
# A good place to look is the documentation for the plot function -
# help(data_all.plot).
# kind - As seen a... | nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Responses/GetMapObjectsResponse.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
fr... | nilq/baby-python | python |
import os
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#TEST_DATA = os.path.join(PROJECT_ROOT, "data/train_2008011514_data.json")
#TEST_JSON = os.path.join(PROJECT_ROOT, "test/test.json")
BERT_MODEL = "bert-base-chinese"
PAD = 0
UNK = 1
CLS = 2
SEP = 3
COMMA = 117
LESS_THAN = 133
LARGER... | nilq/baby-python | python |
from samtranslator.model import PropertyType, Resource
from samtranslator.model.types import is_type, is_str
class SNSSubscription(Resource):
resource_type = 'AWS::SNS::Subscription'
property_types = {
'Endpoint': PropertyType(True, is_str()),
'Protocol': PropertyType(True, is_str()),
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.addons.stock_account.tests.test_stockvaluationlayer impo... | nilq/baby-python | python |
# django==1.6.1
# django_facebook==5.3.1
from django.test import TestCase
from django_facebook.models import FacebookCustomUser
class MyTest(TestCase):
def setUp(self):
user = FacebookCustomUser()
user.facebook_id = '123456789'
user.save()
def do_login(self):
self.client.logi... | nilq/baby-python | python |
f = open("tags_from_tiktok.txt", 'r')
data = f.read()
lst = data.split('\n')
tmp = []
for line in lst:
if line == '':
continue
line = line.strip()
if not (line in tmp):
tmp.append(line)
f.close()
f = open("tags_from_tiktok.txt", 'w')
for line in tmp:
f.write(line + '\n')
f.close() | nilq/baby-python | python |
import komand
from .schema import AnalyzeInput, AnalyzeOutput
# Custom imports below
import requests
class Analyze(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="analyze",
description="Initialize an SSL assessment",
input=AnalyzeInput()... | nilq/baby-python | python |
# demo
import numpy as np
from skimage import io
import glob
from core.DUT_eval.measures import compute_ave_MAE_of_methods
def dut_eval(gt_dir, rs_dirs):
## 0. =======set the data path=======
print("------0. set the data path------")
# # >>>>>>> Follows have to be manually configured <<<<<<< #... | nilq/baby-python | python |
a = ["a3","a2","a1"]
# print(f"{a[0]}")
a = range(1,9)
for i in range(1,9):
print(f"{a[i-1]}") | nilq/baby-python | python |
"""Python Enumerations"""
import sys as _sys
__all__ = ['Enum', 'IntEnum', 'unique']
version = 1, 1, 3
pyver = float('%s.%s' % _sys.version_info[:2])
try:
any
except NameError:
def any(iterable):
for element in iterable:
if element:
return True
return False
try:... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np
import healpy as hp
import astropy.table as Table
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import rc
from matplotlib import rcParams
from matplotlib.colors import LogNorm
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
impor... | nilq/baby-python | python |
import torch
from torch import nn
import torch.nn.functional as F
class SelfAttention2d(nn.Module):
def __init__(self, in_channels, spectral_norm=True):
super(SelfAttention2d, self).__init__()
# Channel multiplier
self.in_channels = in_channels
self.theta = nn.Conv2d(self.in_chann... | nilq/baby-python | python |
#coding:utf-8
#Author:Dustin
#Algorithm:单层感知机(二分类)
'''
数据集:Mnist
训练集数量:60000
测试集数量:10000
------------------------------
运行结果:
正确率:80.29%(二分类)
运行时长:78.55s
'''
from keras.datasets import mnist
import numpy as np
import time
class Perceptron:
#定义初始化方法,记录迭代次数和学习率。
def __init__(self, iteration = 30, learning_rate... | nilq/baby-python | python |
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Optional, Set, List
class OutOfStock(Exception):
pass
def allocate(line: OrderLine, batches: List[Batch]) -> str:
try:
batch = next(
b for b in sorted(batches) if b.can_allo... | nilq/baby-python | python |
from django.shortcuts import render
from .models import Product_origin
from django.http import JsonResponse
# Create your views here.
def product(request):
if request.method == "POST":
product = request.GET['p']
product_details = Product_origin.objects.get(Product_code=product)
print(produ... | nilq/baby-python | python |
"""
construct 2d array of pase state
distance array
"""
import sys
import os
import re
# sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from pathlib import Path
sys.path.append(Path(__file__).resolve().parents[1])
if __name__ == '__main__' and __package__ is None:
__package__ = 'kuro... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import urllib
from datetime import datetime
import time
import json
from alex.applications.PublicTransportInfoEN.site_preprocessing import expand_stop
from alex.tools.apirequest import APIRequest
from alex.utils.cache import lru_c... | nilq/baby-python | python |
from multiprocessing import Queue
from urlobj import URLObj
import logging
class WorkQueue():
def __init__(self):
# Specify maxsize when multithreading.
self.queue = Queue()
self.loaded = False
# Semantics:
# Puts 'urlo' into the queue. If there's no free space, it will block
... | nilq/baby-python | python |
"""
Example logger file.
I've found this doesn't work on bluehost, unless you set up the handler thus:
http_handler = logging.handlers.HTTPHandler(
'example.com',
'http://example.com/path_to_logger/api_upload?key=test&other_keys...',
method='GET',
)
"""
import logging
import logging.handlers
logger = log... | nilq/baby-python | python |
#!/usr/bin/env python3
def main():
"""Checks if there's enough free memory in the computer."""
main() | nilq/baby-python | python |
from django.contrib import admin
from .models import *
admin.site.register(Usuario)
admin.site.register(Media)
admin.site.register(Ramo)
admin.site.register(Cliente)
admin.site.register(Colaborador)
admin.site.register(Pedido)
admin.site.register(Solicitacao)
admin.site.register(Post)
| nilq/baby-python | python |
from setuptools import setup, find_packages
entry_points = """
[console_scripts]
autowheel = autowheel.autowheel:main
"""
setup(name='autowheel',
version='0.1.dev0',
description='Automatically build wheels from PyPI releases',
long_description=open('README.rst').read(),
install_requires=['clic... | nilq/baby-python | python |
import os
import sys
import urllib
import multiprocessing
import ConfigParser
import tempfile
import yaml
import re
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_execut... | nilq/baby-python | python |
bot0_wieght_layer_one = [[0.4935829386124425, 0.2486496493340803, 0.45287661299189763, 0.6228461025230169, 0.0027775129778663254, 0.1708073345725104, 0.519667083534109, 0.23366912853189226, 0.6139798605829813, 0.5293127738090753, 0.6567206010553531, 0.7435351945616345, 0.7015167444631532, 0.14995488489543307, 0.4975771... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from loop_index import LoopIndex
from os import system
def backward_iter_console_test(num_list, jump, start=None):
test_announcement = "Backward iteration by " + str(jump)
if start == None:
start = len(num_list)-1
else:
test_announcement += " from " + str(star... | nilq/baby-python | python |
"""Implementation of a contact graph object."""
from collections import OrderedDict, namedtuple
import math
import networkx as nx
from .contact_plan import ContactIdentifier, ContactPlan
# ContactIdentifier object for better readability and access to identifer
# tuple object.
NeighborLists = namedtuple('NeighborLists... | nilq/baby-python | python |
#!/usr/bin/python
import serial, time
ser = serial.Serial('/dev/ttyUSB0') # open serial port
def comm(msg):
print("msg: %s" % msg)
ser.write("XA/%s\r\n" % msg )
resp = ser.readline()
print resp
print(ser.name) # check which port was really used
msgs = ['kamu', 'N?', 'B?', 'T?']
# test he... | nilq/baby-python | python |
from .comparable import Comparable
class String(Comparable):
@classmethod
def validate(cls, yaml_node):
super().validate(yaml_node)
if not isinstance(yaml_node.value, str):
cls.abort("Expected string input", yaml_node.loc)
| nilq/baby-python | python |
from .reader import Reader
from .exception import ParseException
class Node(object):
"""
ノードを示す基底クラス
"""
def __init__(self) -> None:
#: ノードの開始位置
self.startpos:int = 0
#: ノードの終了位置
self.endpos:int = 0
#: ノード番号
self.nodenum:int = 0
... | nilq/baby-python | python |
# Copyright (c) Jeremías Casteglione <jrmsdev@gmail.com>
# See LICENSE file.
import os
import os.path
import sqlite3
from datetime import datetime
from _sadm import log
from _sadm.utils import sh, path
__all__ = ['SessionDB']
_detectTypes = sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
_sessTable = """
CREATE ... | nilq/baby-python | python |
from app.models.DAO import DAOUsuario
import pymysql
from app import app
from config import mysql
from flask import jsonify
from flask import flash, request
from werkzeug.security import generate_password_hash, check_password_hash
from app.models.classes_basicas.User import User
def add_user(user):
try:... | nilq/baby-python | python |
import sys
import time
import logging
import h5pyd
if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
print("usage: python get_station_ids <ghcn_file>")
sys.exit(0)
filename = sys.argv[1]
logging.basicConfig(level=logging.ERROR)
start_time = time.time()
logging.info(f"start_time: {start_time:.2f}")
f ... | nilq/baby-python | python |
"""
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from byceps.services.global_setting import service as settings_service
from byceps.services.global_setting.transfer.models import GlobalSetting
def test_create(admin_app):
name = 'name1'
v... | nilq/baby-python | python |
def delt(a,b,c):
dell = (b**2) - (4*a*c)
return dell | nilq/baby-python | python |
from typing import *
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
def calc_orbit(p0: Tuple[int, int], v0: Tuple[int, int], aa: List[Tuple[int, int]], d: int):
p = p0
v = v0
orbit = [p0]
for i in range(d-1):
ax, ay = 0, 0
if abs(p[0]) >= abs(p[1])... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import sys
sys.path.append("../")
from unittest import TestCase, main
from chat.graph import Database
from chat.mytools import Walk, time_me
class WalkUserData(Walk):
def handle_file(self, filepath, pattern=None):
self.db.handle_excel(filepath)
class TestMe(TestCase)... | nilq/baby-python | python |
# Generated by Django 2.2.24 on 2021-12-27 08:20
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),
('hom... | nilq/baby-python | python |
#importing some useful packages
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math
import os
from moviepy.editor import VideoFileClip
from IPython.display import HTML
# List of images from test_images folder
test_path = "test_images/"
test_output_path="test_image... | nilq/baby-python | python |
#!/usr/bin/python3
def print_last_digit(number):
n = abs(number) % 10
print(n, end='')
return n
| nilq/baby-python | python |
from ScanResult import *
from TokenFileWorker import *
from AlgorithmScan import *
from PIL import Image
import profile
# Имя файла с изображением бланка.
#---------------------------------------------------
SOURCE_IMAGE = "001_2.jpg"
#---------------------------------------------------
tokenFileWorker = TokenFileWor... | nilq/baby-python | python |
"""This module aims to load and process the data."""
# pylint: disable=import-error, no-name-in-module
import argparse
import os
import torch
import yaml
from torch.utils.data import DataLoader
from data.preprocessing import apply_preprocessing
from data.dataset_utils import basic_random_split, RegressionDataset, load... | nilq/baby-python | python |
"""Waypoint planning."""
from typing import List, Optional, Sequence, Tuple
from typing_extensions import Final
from opentrons.types import Point
from opentrons.hardware_control.types import CriticalPoint
from .types import Waypoint, MoveType
from .errors import DestinationOutOfBoundsError, ArcOutOfBoundsError
DEFAU... | nilq/baby-python | python |
"""Tests for parsing."""
import unittest
from typing import Iterable
import citation_url
from citation_url import IRRECONCILABLE, PREFIXES, PROTOCOLS, Result, Status
class TestParse(unittest.TestCase):
"""Tests for parsing."""
def test_protocols(self):
"""Test all protocols are formed properly."""
... | nilq/baby-python | python |
import click
from graviteeio_cli.http_client.apim.api import ApiClient
from ....exeptions import GraviteeioError
@click.command()
@click.option('--api', 'api_id',
help='API id',
required=True)
@click.pass_obj
def stop(obj, api_id):
"""Stops an API."""
api_client: ApiClient = obj[... | nilq/baby-python | python |
from __future__ import absolute_import, print_function
import argparse
import math
try:
import cPickle as pickle
except ImportError:
import pickle
import scipy.sparse
from xgboost.sklearn import XGBClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
fr... | nilq/baby-python | python |
# 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 applicable law or agreed to in... | nilq/baby-python | python |
#
# =================================================================
# =================================================================
from oslo.config import cfg
from powervc_nova.network.powerkvm.agent import commandlet
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = c... | nilq/baby-python | python |
import pickle
import tempfile
import numpy as np
import pytest
from scipy import stats
import hypney
import hypney.utils.eagerpy as ep_util
def test_naming():
m = hypney.models.uniform(name="bla")
assert m.name == "bla"
# Names are preserved in WrappedModel
assert m.fix_except("rate").name == "bla"
... | nilq/baby-python | python |
# import gi
# gi.require_version("Gtk", "3.24")
from gi.repository import Gtk as g,cairo
try:
from gi_composites import GtkTemplate
except:
from sysmontask.gi_composites import GtkTemplate
if __name__=='sysmontask.sidepane':
from sysmontask.sysmontask import files_dir
else:
from sysmontask import fil... | nilq/baby-python | python |
"""
URLConf for Caching app
"""
from __future__ import unicode_literals
from django.urls import path
from . import views
urlpatterns = [
path('', views.stats_page, {}, 'keyedcache_stats'),
path('view/', views.view_page, {}, 'keyedcache_view'),
path('delete/', views.delete_page, {}, 'keyedcache_delete'),
]... | nilq/baby-python | python |
import numpy as np
"""
Utility functions to initialize a lattice .
image, random, random positive, random within range with a single 'maximum' ping site in center, center ping binary 0s except maximum 1 in center, binary 1 and 0 with density parameter
magic square and scaled primes are amusing seeds
"""
from PIL impo... | nilq/baby-python | python |
"""
Overview
========
PySB implementations of the extrinsic apoptosis reaction model version 1.0
(EARM 1.0) originally published in [Albeck2008]_.
This file contains functions that implement the extrinsic pathway in three
modules:
- Receptor ligation to Bid cleavage (:py:func:`rec_to_bid`)
- Mitochondrial Outer Memb... | nilq/baby-python | python |
# SVR
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Splitting the dataset into the Training set and Test set
"""from sklearn.cross_... | nilq/baby-python | python |
from BeautifulSoup import BeautifulSoup
import re
import os
import sys
import string
openclosetags = re.compile('''<.*?>|</.*?>''',re.DOTALL)
spaces = re.compile('''\s+''',re.DOTALL)
files = []
#files.append('./docs/apple/osx/developer.apple.com.library/mac/documentation/Cocoa/Reference/NSCondition_class/... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.