content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""OAuth 2.0 WSGI server middleware implements support for basic bearer
tokens and also X.509 certificates as access tokens
OAuth 2.0 Authorisation Server
"""
__author__ = "R B Wilkinson"
__date__ = "12/12/11"
__copyright__ = "(C) 2011 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file i... | nilq/baby-python | python |
"""A milestone is a set of parameters used to add a label on a time period.
A milestone can then be used as a time's and timezone's filter."""
from .utils._internal import instance_builder
from .model import SourceModel
class Milestone(SourceModel):
"""This object stores all information about a milestone. Data s... | nilq/baby-python | python |
import RPi.GPIO as GPIO
import time
# Class to manage the LEDs on the breakout board
class LedArray:
def __init__(_self):
# Set board numbering scheme and warnings
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
# Set the pins to be outputs
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setu... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"IMPORTED"
def foo():
"""imported module"""
return "FOO"
print __name__
| nilq/baby-python | python |
# Este es un ejemplo de un for
for n in range(10)
print(n)
| nilq/baby-python | python |
import asyncio
import asyncws
clients = []
clients_lock = asyncio.Lock()
def chat(websocket):
client_copy = None
with (yield from clients_lock):
client_copy = list(clients)
clients.append(websocket)
peer = str(websocket.writer.get_extra_info('peername'))
for client in client_copy:
... | nilq/baby-python | python |
from deepflash2.learner import EnsembleLearner, get_files, Path
from app import crud
import pathlib
import numpy as np
from app.api import classes, utils_transformations
import app.fileserver_requests as fsr
from app.api import utils_paths
import zarr
def predict_image_list(classifier_id, image_id_list, use_tta, chan... | nilq/baby-python | python |
import os
class OccupEyeConstants():
"""
A function-less class that defines cache and URL constants
for the OccupEye API.
These are used to try and avoid typos and repeated typing
of long strings.
Each {} is a format string container that is replaced by
an appropriate string from... | nilq/baby-python | python |
#! /usr/bin/env python
from socket import *
host = 'localhost'
port = 10000
sock = socket(AF_INET,SOCK_DGRAM)
sock.bind((host,port))
while 1:
data = sock.recvfrom(1024)
print data
sock.close()
| nilq/baby-python | python |
import os
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
class OUActionNoise(object):
def __init__(self, mu, sigma=0.15, theta=.2, dt=1e-2, x0=None):
self.theta = theta
self.mu = mu
self.sigma = sigma
self.dt = ... | nilq/baby-python | python |
import wandb
import torch
import numpy as np
import sklearn.gaussian_process as skgp
import sklearn.utils.validation as skval
import scipy.stats as stat
import utils
import constants
kernels = {
"rbf": skgp.kernels.RBF,
"matern": skgp.kernels.Matern,
"rat_quad": skgp.kernels.RationalQuadratic,
"period... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.db import models
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, UserManager as BaseUserManager
from recipi.core.tasks.mail import send_mai... | nilq/baby-python | python |
# A logarithmic solution to the Knight's Dialer problem mentioned here:
# https://medium.com/@alexgolec/google-interview-questions-deconstructed-the-knights-dialer-f780d516f029
import numpy as np
import sys
from timeit import default_timer as timer
# Uses a fibonacci sequence approach to compute matrices that "add" u... | nilq/baby-python | python |
"""I don't like how the error messages are shown in attrs"""
import attr
import numpy as np
from attr._make import attrib, attrs
@attrs(repr=False, slots=True, hash=True)
class _InstanceOfValidator(object):
type = attrib()
def __call__(self, inst, attr, value):
"""
We use a callable class to... | nilq/baby-python | python |
def fibo(n):
flist = [1,1]
if n <= 0 :
return 0
if n == 1 or n == 2:
return n
else :
while n >= 3:
temp = flist[1]
flist[1] += flist[0]
flist[0] = temp
n -= 1
return flist[1]
print(fibo(45))
| nilq/baby-python | python |
import json
import datetime
from uuid import UUID
from django.test import TestCase
from django.utils import six
from model_mommy import mommy
from rest_framework.fields import empty
from rest_framework.test import APIClient
from django.contrib.auth import get_user_model
from .compat import resolve
from dynamic_rest.me... | nilq/baby-python | python |
##############################################################################
# Copyright 2018 Rigetti Computing
#
# 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://ww... | nilq/baby-python | python |
from django.test import TestCase
from ..models import Meal
from authentication.models import CustomUser
class TestMeal(TestCase):
def setUp(self):
self.user = CustomUser.objects.create_user(
email="zoran@zoran.com", password="123456")
Meal.objects.create(
text="breakfast", ... | nilq/baby-python | python |
import unittest
import operator
import pytest
from loris import transforms
from loris.loris_exception import ConfigError
from loris.webapp import get_debug_config
from tests import loris_t
class ColorConversionMixin:
"""
Adds a helper method for testing that a transformer can edit the
embedded color pro... | nilq/baby-python | python |
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import calinski_harabasz_score
from sklearn.metrics import adjusted_mutual_info_score, adjusted_rand_score
from gama import GamaCluster
if __name__ == "__main__":
X, y = load_breast_cancer(return_X_y=True)
automl = GamaCluster(max_total_tim... | nilq/baby-python | python |
import math
import itertools
flatten_iter = itertools.chain.from_iterable
# https://stackoverflow.com/a/6909532/5538273
def factors(n):
return set(flatten_iter((i, n//i) for i in range(1, int(math.sqrt(n)+1)) if n % i == 0))
def prime_factors(n):
dividend = n
prime_nums = primes(n)
prime_factors =... | nilq/baby-python | python |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2016 Eotvos Lorand University, Budapest, Hungary
from utils.codegen import format_expr, make_const
import utils.codegen
from compiler_log_warnings_errors import addError, addWarning
from compiler_common import generate_var_name, prepend_statement
#[ #include "dataplan... | nilq/baby-python | python |
"""
The tests exercise the casting machinery in a more low-level manner.
The reason is mostly to test a new implementation of the casting machinery.
Unlike most tests in NumPy, these are closer to unit-tests rather
than integration tests.
"""
import pytest
import textwrap
import enum
import itertools
import random
i... | nilq/baby-python | python |
import numpy as np
from core.region.region import Region
from random import randint
import warnings
from intervals import IntInterval
import numbers
class Chunk(object):
"""
Each tracklet has 2 track id sets.
P - ids are surely present
N - ids are surely not present
A - set of all animal ids.
... | nilq/baby-python | python |
import configparser
import typing
class BaseConfig:
default = {
"copy_ignores": [
"venv",
"logs",
".git",
".idea",
".vscode",
"__pycache__",
],
"clean_py": True,
"build_dir": "build",
}
@property
d... | nilq/baby-python | python |
from django.db import models
# Create your models here.
class Order(models.Model):
is_payed = models.BooleanField(default=False, blank=True, null=True)
amount = models.DecimalField(max_digits=50, decimal_places=2, blank=True, null=True)
amount_for_payme = models.DecimalField(max_digits=50, decimal_places... | nilq/baby-python | python |
from .core import * # noqa
__version__ = '1.0.0'
| nilq/baby-python | python |
from celestial_bodies.celestial_body import Celestial_Body
from celestial_bodies.trajectories.stationary import Stationary
from celestial_bodies.trajectories.ellipse_approx import Ellipse_Mock
from celestial_bodies.trajectories.rotation import Rotation
from vector3 import Vector3
# the kepler model is practically the... | nilq/baby-python | python |
#! /usr/bin/env python
#
#
# Brute-force dump of single row from WKT Raster table as GeoTIFF.
# This utility is handy for debugging purposes.
#
# WARNING: Tha main purpose of this program is to test and
# debug WKT Raster implementation. It is NOT supposed to be an
# efficient performance killer, by no means.
#
#######... | nilq/baby-python | python |
text = input()
upper_cases_count, lower_cases_count = 0, 0
for character in text:
if character.isupper():
upper_cases_count += 1
elif character.islower():
lower_cases_count += 1
if upper_cases_count > lower_cases_count:
print(text.upper())
else:
print(text.lower()) | nilq/baby-python | python |
import unittest
from unittest import mock
from tinydb import TinyDB, Query
from motey.repositories import capability_repository
class TestCapabilityRepository(unittest.TestCase):
@classmethod
def setUp(self):
self.test_capability = 'test capability'
self.test_capability_type = 'test capabili... | nilq/baby-python | python |
tasks = [
{
'name': 'A simple command',
'function': 'scrapli_command.scrapli_command',
'kwargs': { 'command' : 'show version | i uptime'}
},
]
tasks = [tasks[0]]
taskbook = {}
taskbook['name'] = "Testing with Scrapli Async!"
taskbook['run_mode'... | nilq/baby-python | python |
import pytest
from mlflow.exceptions import MlflowException
from mlflow.store.dbmodels.db_types import DATABASE_ENGINES
from mlflow.utils import get_unique_resource_id, extract_db_type_from_uri, get_uri_scheme
def test_get_unique_resource_id_respects_max_length():
for max_length in range(5, 30, 5):
for _... | nilq/baby-python | python |
__author__ = 'fran'
| nilq/baby-python | python |
import argparse
from nuts.testhandling.evaluator import Evaluator
from nuts.testhandling.network_test_builder import TestBuilder
from nuts.testhandling.network_test_runner import TestRunner
from nuts.testhandling.reporter import Reporter
from nuts.utilities.ui_handler import UIHandler
class TestController:
"""
... | nilq/baby-python | python |
import tkinter as tk
SQUARE_DIM = 120
BOARD_DIM = SQUARE_DIM*8
TEXT_SIZE = 28
HAVE_DRAWN = False
global images
images = {}
def ranges(val):
return range(val - SQUARE_DIM//2, val + SQUARE_DIM//2)
def move_piece(piece_x, piece_y, piece_name, x, y):
if x <= 0:
x = 1
if x>= BOARD_DIM + 4*SQUARE_DI... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import click
import json
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from numpy import linalg as LA
from scipy.optimize imp... | nilq/baby-python | python |
from __future__ import print_function
from PIL import Image
import torchvision.datasets as datasets
import torch.utils.data as data
class CIFAR10Instance(datasets.CIFAR10):
"""CIFAR10Instance Dataset.
"""
def __init__(self, root='./data/cifar10', train=True, download=True, transform=None, two_imgs=False, ... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Grabs brain volumes for Freesurfer and SIENAX segmentations with follow up
scans and plots them
"""
import os
from glob import glob
import re
import itertools
import numpy as np
import matplotlib.pyplot as plt
import nibabel as nib
from scipy import stats
sienax_mas... | nilq/baby-python | python |
from src.utilities.geometry import dist_between_points
def cost_to_go(a: tuple, b: tuple) -> float:
"""
:param a: current location
:param b: next location
:return: estimated segment_cost-to-go from a to b
"""
return dist_between_points(a, b)
def path_cost(E, a, b):
"""
Cost of the un... | nilq/baby-python | python |
"""Extensions module - Set up for additional libraries can go in here."""
import logging
# logging
logger = logging.getLogger("flask.general")
| nilq/baby-python | python |
from config import config
from packettest.packets import make_packet
# from packettest.test_context import make_context
from packettest.test_context import TestContext
from packettest.predicates import received_packet
from packettest.predicates import saw_packet_equals_sent
from simple_switch.simple_switch_runner imp... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/Condition
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
import io
import json
import os
import unittest
import pytest
from .. import condition
from ..fhirdate import FHIRDate
from .fixtures ... | nilq/baby-python | python |
class Parser:
site_url = ""
required_path_elements = []
@staticmethod
def parse_thread(soup_obj, url):
pass
@staticmethod
def parse_title(soup_obj):
pass
| nilq/baby-python | python |
#!/usr/bin/env python
"""
Horn Concerto - Evaluation for inference.
Author: Tommaso Soru <tsoru@informatik.uni-leipzig.de>
Version: 0.1.0
Usage:
Use test endpoint (DBpedia)
> python evaluation.py <TEST_SET> <INFERRED_TRIPLES>
"""
import sys
from joblib import Parallel, delayed
import numpy as np
import multipro... | nilq/baby-python | python |
"""Tokenization utilities."""
import pyonmttok
_ALLOWED_TOKENIZER_ARGS = set(
[
"bpe_dropout",
"bpe_model_path",
"case_feature",
"case_markup",
"joiner",
"joiner_annotate",
"joiner_new",
"lang",
"mode",
"no_substitution",
"pre... | nilq/baby-python | python |
""" nvo
This module contains a collection of YANG definitions
for Cisco VxLAN feature configuration.
Copyright (c) 2013\-2014 by Cisco Systems, Inc.
All rights reserved.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, B... | 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 |
import json
from collections import namedtuple, defaultdict, deque
try:
from collections import Mapping
except ImportError:
from collections.abc import Mapping
from glypy.io import glycoct
from glypy.structure.glycan_composition import HashableGlycanComposition
EnzymeEdge = namedtuple("EnzymeEdge", ("parent"... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages
from setuptools import setup
setup(
name='blueprint-webapp-flask-graphql',
version='1.0.0',
packages=find_packages(exclude=["*_tests"]),
license='MIT',
long_description=open('README.md').read(),
install_requires=... | nilq/baby-python | python |
#!/usr/bin/env python
import setuptools
setuptools.setup(
name='loops',
description='Convenience classes and functions for looping threads',
author='Fenhl',
author_email='fenhl@fenhl.net',
packages=['loops'],
use_scm_version={
'write_to': 'loops/_version.py'
},
setup_requires=[... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @copyright © 2010 - 2021, Fraunhofer-Gesellschaft zur Foerderung der
# angewandten Forschung e.V. All rights reserved.
#
# BSD 3-Clause License
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fol... | nilq/baby-python | python |
import argparse
def get_options(args):
parser = argparse.ArgumentParser(description="Parses command.")
parser.add_argument("-i", "--input", help="Your input file.", required=True)
parser.add_argument("-o", "--output", help="Your destination output file.", default='/data/adversarial_image.png')
parser.... | nilq/baby-python | python |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free S... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
SPDX-License-Identifier: BSD-3-Clause
Copyright (c) 2020 Deutsches Elektronen-Synchrotron DESY.
See LICENSE.txt for license details.
"""
import setuptools
from pathlib import Path as path
from frugy import __version__
readme_contents = path('./README.md').read_text()
requirements = path('./... | nilq/baby-python | python |
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "YaraGuardian.settings")
from django.core.wsgi import get_wsgi_application
from whitenoise import WhiteNoise
from django.conf import settings
application = get_wsgi_application()
if settings.SERVE_STATIC:
application = WhiteNoise(application)
| nilq/baby-python | python |
'''
Objectives :
1. Input a JSON file from user. (here, Employees.json)
2. Read the JSON file and print the data on console
3. Create methods (units) for each field of an employee and check the fields values using regular expression.
4. Perform unit testing for each unit using Python module unittest.
'''
import json
i... | nilq/baby-python | python |
#!/usr/bin/env python
"""This script compiles multiple instances of a program trying out different
heuristics, and storing in the database the best one that is found"""
import sys
import os
import shutil
import sqlite3
import random
import xml.dom.minidom
import re
import pbutil
import tunerwarnings
import maximaparser... | nilq/baby-python | python |
#!/home/joan/Documents/Myproject/mynewenv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| nilq/baby-python | python |
from Lexer import *
# Keywords can execute outside main function
kw_exe_outside_main = {KW_main, KW_def, KW_import1}
variables = []
functions = []
current_line = 0
class Token:
def __init__(self, tokens):
self.t_values = []
self.last_kw = ''
for tok in tokens:
... | nilq/baby-python | python |
from __future__ import division
import os
from flask import Flask, url_for, request, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
import math
import sqlite3
app = Flask(__name__)
app.config['SERVER_NAME'] = 'the-gpa-calculator-noay.herokuapp.com'
app.secret_key = 'Secre... | nilq/baby-python | python |
from src.DataReader.CNN_Data.ReadData_CNN import *
import time
from src.Params import branchName
##############################################################################################
## Rule of thumb: don't call any other function to reduce lines of code with the img data in np.
## Otherwise, it could c... | nilq/baby-python | python |
import os
import re
import sys
try:
from Cython.Distutils import build_ext
except ImportError:
from setuptools.command.build_ext import build_ext
from distutils.extension import Extension
from distutils.sysconfig import get_config_vars, get_python_lib, get_python_version
from pkg_resources import Distribution... | nilq/baby-python | python |
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declared_attr, declarative_base
from backend import Backend
Base = declarative_base()
class DjangoLikeModelMixin(object):
id = Column(Integer, primary_key=True)
@declared_attr
def __tablename__(cls):
return cls.__name... | nilq/baby-python | python |
import datetime, send_data
cefmapping = {"ip-src": "src", "ip-dst": "dst", "hostname": "dhost", "domain": "dhost",
"md5": "fileHash", "sha1": "fileHash", "sha256": "fileHash",
"url": "request"}
mispattributes = {'input': list(cefmapping.keys())}
outputFileExtension = "cef"
responseType = "... | nilq/baby-python | python |
#! /usr/local/bin/stackless2.6
# by pts@fazekas.hu at Thu Apr 29 19:20:58 CEST 2010
"""Demo for hosting a Concurrence application within a Syncless process."""
__author__ = 'pts@fazekas.hu (Peter Szabo)'
# It would work even with and without these imports, regardless of the import
# order.
#from syncless.best_stackl... | nilq/baby-python | python |
# Multiple Linear Regression
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
# Importing the dataset
path = Path(__file__).parent / '50_Startups.csv'
dataset = pd.read_csv(path)
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# ... | nilq/baby-python | python |
#encoding:utf-8
import xml.etree.ElementTree as ET
import requests
KEY = '7931e48c2618c58d14fc11634f2867db'
TRANSFER_URL = u'http://openapi.aibang.com/bus/transfer?app_key=%s&city=武汉&start_addr=%s&end_addr=%s'
LINES_URL = u'http://openapi.aibang.com/bus/lines?app_key=%s&city=武汉&q=%s'
STATUS_URL = u'http://openapi.aib... | nilq/baby-python | python |
from app import app, db
from app.models import User, Listing
@app.shell_context_processor
def make_shell_context():
with app.app_context():
return {'db': db, 'User': User, 'Listing': Listing} | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.netapp_cluster_info
import cohesity_management_sdk.models.netapp_volume_info
import cohesity_management_sdk.models.netapp_vserver_info
class NetappProtectionSource(object):
"""Implementation of the 'NetappProtectionSourc... | nilq/baby-python | python |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#Importações e tratamento de exceções
#try:
import kivy
from kivy.app import App as app
from kivy.uix.boxlayout import BoxLayout as bl
from kivy.uix.button import Button as btn
from kivy.uix.label import Label as lb
# except:
# import kivy
# kivy.require('1.0.1')
# fr... | nilq/baby-python | python |
"""
AudioFile class
Load audio files (wav or mp3) into ndarray subclass
Last updated: 15 December 2012
"""
import os
from subprocess import Popen, PIPE
import numpy
from numpy import *
import scipy.io.wavfile
from pymir import Frame
import pyaudio
class AudioFile(Frame.Frame):
def __new__(subtype, shape, dtyp... | nilq/baby-python | python |
from keras.layers import Flatten, Dense, Dropout, Input
from keras.models import Sequential, Model
import tensorflow as tf
import pickle
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('dataset', 'cifar10', "Make bottleneck features this for dataset, one of 'cifar10', or 'traffic'")
flags.DEFINE_string('... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import csv,serial
arduino = serial.Serial('/dev/cu.usbmodem30',9600)
print("""
______________________________________________________
Proyecto Programación Estructurada
Integrantes: Ing. Juan Manuel Corza Hermosillo
... | nilq/baby-python | python |
import torch
import torch.nn.functional as F
import numpy as np
from scipy import stats
from sklearn.cluster import MiniBatchKMeans
class GMMOutput(torch.nn.Module):
def __init__(self, n_components):
super(GMMOutput, self).__init__()
self.components = n_components
def sample(self, x):
... | nilq/baby-python | python |
import numpy as np
from .estimator import Estimator
class Adaline(Estimator):
def __init__(self, learning_rate, activation_function, loss_function, loss_variation_tolerance):
super().__init__()
self.learning_rate = learning_rate
self.activation_function = activation_function
self.loss_function = l... | nilq/baby-python | python |
from os import environ, path
from telebot import TeleBot
from RPG.bot_classes.game import Game
# Импортирует все состояния игры
from RPG.consts.game_states import MAIN_MENU, INVENTORY, INVENTORY_INFO, CREATE_PLAYER_MENU, PLAYER_PROFILE, \
CABIN, CAPTAIN_BRIDGE, CARGO_HOLD, COMPUTER, CREATE_SPACESHIP_MENU, ESTRAD_PO... | nilq/baby-python | python |
import datetime
import pandas as pd
import numpy as np
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from analytics.events.utils.dataframe_builders import SupplementEventsDataframeBuilder, SleepActivityDataframeBuilder, \
... | nilq/baby-python | python |
#!flask/bin/python
# imports here
import click
from datetime import datetime
from flask import abort, Flask, g, jsonify, request
from info import info
import os
import sqlite3
### app instantiation ###
app = Flask(__name__)
app.config.update({
'JSON_SORT_KEYS':False,
'DATABASE':os.path.join(app.root_path, '... | nilq/baby-python | python |
from __future__ import division
from __future__ import print_function
import os
import random
import logging
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable as Var
import sys
# IMPORT CONSTANTS
from learning.treelstm.config import parse_args
fr... | nilq/baby-python | python |
#!python3
# Code Challenge 02 - Word Values Part II - a simple game
# http://pybit.es/codechallenge02.html
import itertools
import random
from data import DICTIONARY, LETTER_SCORES, POUCH
NUM_LETTERS = 7
def draw_letters():
"""Pick NUM_LETTERS letters randomly. Hint: use stdlib random"""
draw = random.samp... | nilq/baby-python | python |
d=[3,22,99,68,34,17,45,66,58,89,73,12,92,1,5,26,91,32,86]
print d,'\n'
p=len(d)
bin_size=raw_input('Choose the bin_size(Eg:9) ')
for i in range(int(min(d)),int(max(d)),int(bin_size)+1):
print "{:>4} - {:<4}".format(i,i+int(bin_size)),' ',
for j in range(0,p):
if d[j]>=i and d[j]<=i+int(bin_size):
print '-',
pr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# OS.FreeBSD.get_vlans
# ---------------------------------------------------------------------
# Copyright (C) 2007-2011 The NOC Project
# See LICENSE for details
# -----------------------------------------------------------... | nilq/baby-python | python |
import os
import kubectl
import pathlib
version = open(os.path.join(pathlib.Path(__file__).parent.absolute(),"../release")).read(1024)
# version = "0.9.7"
test_namespace = "test"
clickhouse_template = "templates/tpl-clickhouse-stable.yaml"
# clickhouse_template = "templates/tpl-clickhouse-19.11.yaml"
# clickhouse_tem... | nilq/baby-python | python |
from django.apps import AppConfig
class ListingsConfig(AppConfig):
name = 'listings'
verbose_name = "User Listings"
| nilq/baby-python | python |
import logging
from dojo.models import Test_Type
PARSERS = {}
# TODO remove that
SCAN_SONARQUBE_API = 'SonarQube API Import'
def register(parser_type):
for scan_type in parser_type().get_scan_types():
parser = parser_type()
if scan_type.endswith('detailed'):
parser.set_mode('detailed'... | nilq/baby-python | python |
from django.views import generic
class HomePage(generic.TemplateView):
template_name = "home.html"
class FAQPage(generic.TemplateView):
template_name = "faq.html"
| nilq/baby-python | python |
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints
class Attention(Layer):
def __init__(
self,
step_dim=65,
W_regularizer=None,
b_regularizer=None,
W_constraint=None,
b_constraint=None,
... | nilq/baby-python | python |
from .habitica_object import HabiticaObject
import attrdict
class Group(HabiticaObject):
def __init__(self, id_str):
"""A group/party in Habitica."""
assert False, "Not done yet!"
| nilq/baby-python | python |
"""Revert revision foreign key
Revision ID: 83f49fddbcb6
Revises: 55e1f2f5d706
Create Date: 2020-05-19 12:25:02.795675
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "83f49fddbcb6"
down_revision = "55e1f2f5d706"
branch_labels = None
depends_on = None
def upg... | nilq/baby-python | python |
from __future__ import division
from ..errors import InvalidParamsError
from ..utils import one_row_params_array
from .base import UncertaintyBase
from scipy import stats
import numpy as np
class NormalUncertainty(UncertaintyBase):
id = 3
description = "Normal uncertainty"
@classmethod
def validate(c... | nilq/baby-python | python |
from .global_var import *
## Python C-like struct s2 ##
from dataclasses import dataclass
# Queue for FIFO
from queue import SimpleQueue
# To save current time
from time import time
# Random replacement
from random import choice
#---------------------------#
@dataclass
class PAGE: #{{{
index: int# page index
... | nilq/baby-python | python |
"""Generalized Pauli matrices."""
import numpy as np
from toqito.matrices import shift
from toqito.matrices import clock
def gen_pauli(k_1: int, k_2: int, dim: int) -> np.ndarray:
r"""
Produce generalized Pauli operator [WikGenPaul]_.
Generates a :code:`dim`-by-:code:`dim` unitary operator. More specifi... | nilq/baby-python | python |
"""base classes to be inherited from for various purposes"""
from abc import ABC
from abc import abstractmethod
import argparse
from typing import List, Type
from ec2mc.validate import validate_perms
class CommandBase(ABC):
"""base class for most ec2mc command classes to inherit from"""
_module_postfix = "_c... | nilq/baby-python | python |
try:
import unzip_requirements
except ImportError:
pass
import json, os, sys, re
import base64
import boto3
from botocore.signers import RequestSigner
from kubernetes import client
from kubernetes.client import ApiClient, Configuration
from kubernetes.config.kube_config import KubeConfigLoader
def get_bearer_toke... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .utils import TestUtils
from .ticker import TestTicker
from .visuals import TestVisuals
from .figure import TestFigure
from .dates import TestDates
#-----------------------------------------------------------------------------
| nilq/baby-python | python |
from smexperiments import api_types
def test_parameter_str_string():
param = api_types.TrialComponentParameterValue("kmeans", None)
param_str = str(param)
assert "kmeans" == param_str
def test_parameter_str_number():
param = api_types.TrialComponentParameterValue(None, 2.99792458)
param_str =... | nilq/baby-python | python |
import socket
def validate_ip4 (address):
try:
socket.inet_aton(address)
ip4_address = address
except (socket.error, TypeError):
ip4_address = None
return ip4_address
def validate_ip6 (address):
try:
socket.inet_pton(socket.AF_INET6, address)
ip6_address = address
except (socket.error, TypeError):
i... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2020-03-04 20:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0030_skill'),
]
operations = [
migrations.AddField(
model_name='profile',
name='skills',
... | nilq/baby-python | python |
import os
import sys
from typing import List
import numpy as np
import scipy as sp
import scipy.stats
from utilities.plotting import Plot
def main():
figure_num = int(sys.argv[1])
for_print = bool(int(sys.argv[2]))
def load_and_plot(dir: str, plot: Plot, name: str):
series, means, confidences =... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.