content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""pysat URL Configuration for User.Info
"""
from django.urls import path
from utils.views import view_maker
from utils.params import ParamType
from utils.permission import ActionType
from user.views import info
urlpatterns = [
path('get', view_maker(info.get_info, 'GET', [
ParamType.UsernameWithDefault
... | nilq/baby-python | python |
"""Helpers for Roku Client."""
from ipaddress import ip_address
from socket import gaierror as SocketGIAError
from .exceptions import RokuConnectionError
from .resolver import ThreadedResolver
def is_ip_address(host: str) -> bool:
"""Determine if host is an IP Address."""
try:
ip_address(host)
ex... | nilq/baby-python | python |
import asyncio_redis
from vibora import Vibora
from vibora.hooks import Events
from vibora.sessions import AsyncRedis
from vibora.responses import Response
app = Vibora(
sessions=AsyncRedis()
)
@app.route('/', cache=False)
async def home(request):
print(request.session.dump())
await request.load_session... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.urls import reverse_lazy
from django.views.generic import View
from django.http import HttpResponse
from django.core import serializers
from djangoSIGE.apps.base.custom_views import CustomCreateView, CustomListView, CustomUpdateView
from djangoSIGE.apps.vendas.forms import Condica... | nilq/baby-python | python |
import numpy as np
import pandas as pd
from scipy.stats import poisson
from cooltools.api.dotfinder import (
histogram_scored_pixels,
determine_thresholds,
annotate_pixels_with_qvalues,
extract_scored_pixels,
)
# helper functions for BH-FDR copied from www.statsmodels.org
def _fdrcorrection(pvals, al... | nilq/baby-python | python |
import unittest
from flatten import flattener
class FlattenTests(unittest.TestCase):
def test_single_small_nested_list(self):
calculated = flattener([1, [2, 3]])
expected = [1, 2, 3]
self.assertEqual(calculated, expected)
if __name__ == "__main__":
unittest.main()
| nilq/baby-python | python |
# Generated by Django 3.2.6 on 2021-08-30 14:52
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('todo', '0002_alter_profile_unique_together'),... | nilq/baby-python | python |
categories = [
{"name": "Action"},
{"name": "Drama"},
{"name": "Comedy"},
{"name": "Fantasy"},
{"name": "Sci-fi"},
] | nilq/baby-python | python |
# Copyright (c) 2021 China Unicom Cloud Data Co.,Ltd.
# 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
#
... | nilq/baby-python | python |
import os
from operator import itemgetter
import fpdf
def gen_report(target, rep):
print("[=] Creating PDF...")
class PPDF(fpdf.FPDF):
def footer(self):
self.set_y(-15)
self.set_font("Arial", style="I", size=8)
self.cell(0, 10, "soc_recon report", align="C")
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Physics Guided Neural Network python library."""
import os
from .model_interfaces import PhygnnModel, RandomForestModel, TfModel
from .phygnn import PhysicsGuidedNeuralNetwork, p_fun_dummy
from .utilities import Layers, HiddenLayers, PreProcess, tf_isin, tf_log10
from phygnn.version import __... | nilq/baby-python | python |
import numpy as np
class BodyModel:
def __init__(self, mapping, pairs) -> None:
self.mapping = mapping
self.pairs = pairs
BODY18 = BodyModel(
mapping=[
"nose",
"left_eye",
"right_eye",
"left_ear",
"right_ear",
"left_shoulder",
"right_sh... | nilq/baby-python | python |
from datetime import datetime as dt
from . import __version__
import typing as t
def client_imports_f() -> str:
"""
Creates the string to import the client dependencies and
a default module doc string. Usually the first part
of the client module.
Returns:
str: import statements string rea... | nilq/baby-python | python |
from django.utils import timezone
from rest_framework import serializers
from .models import Client
class ClientSerializer(serializers.ModelSerializer):
class Meta:
model = Client
fields = (
'id',
'business_owner',
'first_name',
'last_name',
... | nilq/baby-python | python |
from django.apps import AppConfig
class PhoneCodeConfig(AppConfig):
name = 'phonecode'
| nilq/baby-python | python |
from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
QParams = namedtuple('QParams', ['range', 'zero_point', 'num_bits'])
_DEFAULT_FLATTEN = (1, -1)
_DEFAULT_FLATTEN_GRAD = (0, -1)
def _deflatt... | nilq/baby-python | python |
from invoke import Collection
from tasks import build
ns = Collection()
ns.add_collection(build)
| nilq/baby-python | python |
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from app.config import Config
# Init
db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()
login_manager.login_view = 'users.login'
login_manager... | nilq/baby-python | python |
search_customizations = {
## The name of the variable to contain the list of results (default 'search_results')
# 'context_object_name': '',
## The list of models to exclude from search results (default empty list)
# 'exclude': (),
## The page to redirect to if the user enters an empty search term (... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Created on : 2019-03-06 17:36
# @Author : zpy
# @Software: PyCharm
import logging
from logging.handlers import RotatingFileHandler
import functools
import inspect
from datetime import datetime
from collections import defaultdict
import os
from config import LOGPATH as ... | nilq/baby-python | python |
from copy import deepcopy
import dendropy
from iterpop import iterpop as ip
import itertools as it
import numpy as np
from sortedcontainers import SortedSet
def dendropy_tree_to_scipy_linkage_matrix(tree: dendropy.Tree) -> np.array:
# scipy linkage format
# http://docs.scipy.org/doc/scipy/reference/generated/... | nilq/baby-python | python |
from __future__ import absolute_import
from .ABuGridSearch import ParameterGrid, GridSearch
from .ABuCrossVal import AbuCrossVal
from .ABuMetricsBase import AbuMetricsBase, MetricsDemo
from .ABuMetricsFutures import AbuMetricsFutures
from .ABuMetricsTC import AbuMetricsTC
from .ABuMetricsScore import AbuBaseScorer, Wr... | nilq/baby-python | python |
#!/usr/bin/env python3
'''
Helper script to clean up some Redis keys
This should probably become part of the regular scheduler code!
'''
import click
import random
import redis
import collections
@click.command()
@click.argument('redis-host')
@click.argument('redis-port')
def main(redis_host, redis_port):
r = ... | nilq/baby-python | python |
import math
print(math.pi) | nilq/baby-python | python |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | nilq/baby-python | python |
"""
arguments.py
Handles the arguments of training and scoring Hasse diagrams.
"""
from tempfile import TemporaryDirectory
from tap import Tap
from typing import List
from typing_extensions import Literal
import json
class CommonArgs(Tap):
"""
CommonArgs contains arguments that are used in both TrainArgs and... | nilq/baby-python | python |
# (c) Copyright IBM Corp. 2021
# (c) Copyright Instana Inc. 2020
"""
Host Collector: Manages the periodic collection of metrics & snapshot data
"""
from time import time
from ..log import logger
from .base import BaseCollector
from ..util import DictionaryOfStan
from .helpers.runtime import RuntimeHelper
class HostC... | nilq/baby-python | python |
# Tests invocation of the interpreter with various command line arguments
# All tests are executed with environment variables ignored
# See test_cmd_line_script.py for testing of script execution
import test.test_support
import sys
import unittest
from test.script_helper import (
assert_python_ok, assert_python_fa... | nilq/baby-python | python |
from AutoMxL.__main__ import AML
import unittest
import pandas as pd
from AutoMxL.Preprocessing.Categorical import CategoricalEncoder
from AutoMxL.Preprocessing.Date import DateEncoder
from AutoMxL.Preprocessing.Missing_Values import NAEncoder
from AutoMxL.Select_Features.Select_Features import FeatSelector
import nump... | nilq/baby-python | python |
from django import forms
from .models import GonderiModel
class GonderiForm(forms.ModelForm):
class Meta:
model = GonderiModel
fields = ("tur","baslik","yazi","olusturzaman") | nilq/baby-python | python |
import unittest
from utils import VCRTestBase
import utils
from pyVim import connect
import sys
sys.path.insert(0, '../')
import inventory
class InventoryTests(VCRTestBase):
@VCRTestBase.my_vcr.use_cassette('test_inventory_run.yaml',
cassette_library_dir=utils.fixtures_path... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import random
# Pulling data from Data sets
datafile_1 = np.genfromtxt('data_1.csv', delimiter=',')
# print(datafile_1)
datafile_2 = np.genfromtxt('data_2.csv', delimiter=',')
# print(datafile_2)
datafile_1 = datafile_1[1:]
datafile_2 = datafile_2[1:]
# Least square... | nilq/baby-python | python |
#!/usr/bin/env python3
import inspect
import sys
from xml.etree import ElementTree
def match(text, *queries):
doc = ElementTree.parse(text)
return [doc.findtext(query) for query in queries]
def _main(argv=None):
"""
Usage: python3 -m pup.xpath QUERY [QUERY...]
Where
- Each QUERY is a val... | nilq/baby-python | python |
import pytest
from pybuildkite.agents import Agents
def test_get_agent(fake_client):
"""
Test the get_agent method
"""
agents = Agents(fake_client, "base")
agents.get_agent("org_slug", "agent_id")
fake_client.get.assert_called_with(agents.path.format("org_slug") + "agent_id")
def test_stop_... | nilq/baby-python | python |
# Copyright (c) 2015 Microsoft Corporation
"""
>>> from z3 import *
>>> v = BitVecVal(0xbadc0de, 32)
>>> v.sexpr()
'#x0badc0de'
>>> v
195936478
>>> v.as_long() == 195936478
True
"""
if __name__ == "__main__":
import doctest
if doctest.testmod().failed:
exit(1)
| nilq/baby-python | python |
def main():
print("Not implemented yet.")
| nilq/baby-python | python |
import tensorflow_datasets as tfds
import config
def load_dataset():
imdb, info = tfds.load('imdb_reviews',
data_dir=config.DATA_PATH,
with_info=True,
as_supervised=True)
return imdb, info
if __name__ == '__main__':
load_da... | nilq/baby-python | python |
'''
作者:邱少一
日期:2018/03/06
1、准备:
python版本:python3 --version
选择Web异步的框架aiohttp:pip3 install aiohttp(比较底层,需要再次封装)
前端模板引擎jinja2:pip3 install jinja2
MySQL的Python异步驱动程序aiomysql:pip3 install aiomysql
监控目录文件变化:pip3 install watchdog
2、流程:
1、编写web 骨架
2、编写ORM 和 Model
3、编写 web框架(基于aiohttp)
4、编写配置文件
5、编写MVC
6、构建前端
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import sys
import codecs
import unittest
from StringIO import StringIO
# We include <pkg_root>/src, <pkg_root>/lib/python
extend_path = lambda root_path, folder: sys.path.insert(
0, os.path.join(root_path, folder))
ROOT = os.path.dirname(os.pat... | nilq/baby-python | python |
# """
# Modul containing import methods from different packages / repositories.
# """
#
# import copy
# import json
# import os.path
# import tempfile
# from multiprocessing import Process
#
# import arff
# import networkx as nx
# import numpy as np
# import openml as oml
# import pandas as pd
# import pypadre.pod.back... | nilq/baby-python | python |
# This code is part of the epytope distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""
.. module:: EpitopePrediction.ANN
:synopsis: This module contains all classes for ANN-based epitope prediction methods.
.. moduleauthor:: schubert,... | nilq/baby-python | python |
from django.conf import settings
def init_permission(request, obj):
# 保存登录状态
request.session['is_login'] = True
# 查询出当前用户的权限
# 去除权限为空的权限
ret = obj.roles.filter(permissions__url__isnull=False).values(
'permissions__id',
'permissions__url',
'permissions__title',
'perm... | nilq/baby-python | python |
import sys
import yaml
import logging
import typing
from typing import Dict
import clingo
from PyQt5.QtSvg import QSvgRenderer
from . import actions
from .visualizeritem import *
from .visualizerabstract import VisualizerDemand, VisualizerGoods
from .spritecontainer import SpriteContainer
from .model import *
def p... | nilq/baby-python | python |
def check_close(input_string):
OPENS = ('(', '<', '[', '{')
CLOSES = (')', '>', ']', '}')
PAREN = ('(', ')')
ANGLE = ('<', '>')
SQUARE = ('[', ']')
CURLY = ('{', '}')
mem = []
for character in input_string:
try:
if character in OPENS:
mem.append(c... | nilq/baby-python | python |
"""Password Policy tests"""
from django.test import TestCase
from guardian.shortcuts import get_anonymous_user
from authentik.lib.generators import generate_key
from authentik.policies.password.models import PasswordPolicy
from authentik.policies.types import PolicyRequest, PolicyResult
class TestPasswordPolicy(Test... | nilq/baby-python | python |
from .unet import *
from .metric import * | nilq/baby-python | python |
# Simple and compound interest
P = float(input("Enter principal: "))
R = float(input("Enter annual RoI (%): ")) / 100
T = float(input("Enter time (years): "))
C = int(input("Compounds per annum: "))
# Calculate simple interest
SI = P*R*T
# Calculate compound interest
R = R/C
T = int(T*C)
CI = (P*(1+R)**T) - P
# ... | nilq/baby-python | python |
import torch
import torch.distributions
import numpy as np
import matplotlib.pyplot as plt
from pkg_resources import resource_filename
import activelo
def generated_example():
N = 20
truth = torch.randn(N)
n = torch.randint(1, 50, (N, N))
d = truth[:, None] - truth[None, :]
w = torch.distributions... | nilq/baby-python | python |
def binary_search(l, value, low = 0, high = -1):
if not l: return -1
if(high == -1): high = len(l)-1
if low == high:
if l[low] == value: return low
else: return -1
mid = (low+high)//2
if l[mid] > value: return binary_search(l, value, low, mid-1)
elif l[mid] < value: return binary... | nilq/baby-python | python |
# from file_path import ClassName
# class Car:
# wheels = 4
#
# def __init__(self, make, model, year, color):
# self.make = make
# self.model = model
# self.year = year
# self.color = color
#
# def drive(self):
# return f"The {self.model} is driving"
#
# def stop... | nilq/baby-python | python |
from graphql_relay.node.node import from_global_id
from django_filters import FilterSet, CharFilter
from django_filters.filters import ModelMultipleChoiceFilter, ModelMultipleChoiceField
class BaseFilterSet(FilterSet):
"""
Base filter set for Movie and Person
"""
search = CharFilter(method='filter_by_... | nilq/baby-python | python |
#!/usr/bin/env python
# author: d.koch
# coding: utf-8
# naming: pep-0008
# typing: pep-0484
# docstring: pep-0257
# indentation: tabulation
""" canp_view_enaml.py
Enaml view
"""
# --- IMPORT ---
# Standard libraries (installed with python)
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__f... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# File: base.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
from abc import ABCMeta, abstractmethod
import signal
import re
from six.moves import range
import tqdm
import tensorflow as tf
from tensorpack.utils.utils import get_tqdm_kwargs
from .config import TrainConfig
from ..utils import *
fro... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:Description: Implementation of the Louvain algorithm using igraph framework with input/
output formats adapted to the NMIs evaluation.
:Authors: Artem Lutov <luart@ya.ru>
:Organizations: eXascale lab <http://exascale.info/>, ScienceWise <http://sciencewise.info/>,
Lu... | nilq/baby-python | python |
#!/usr/bin/env python3
# Custom imports
from .help import showHelp
from .cfg import (
MIN_WIDTH, MIN_HEIGHT,
MIN_BIG_WIDTH, MIN_BIG_HEIGHT,
CONF_FILEPATH,
MAX_COLORS,
startTime, stopSeconds,
arrNumBig, arrNumSmall,
helpMenu
)
from .utils import get_terminal_size
# External imports
import sys
import os
import c... | nilq/baby-python | python |
'''
@author: Aeolus
@url: x-fei.me
@time: 2019-04-08 21:26
'''
from os.path import join, dirname, abspath
from src import tool
# Basic project info
AUTHOR = "Felix"
PROGRAM = "Robust"
DESCRIPTION = "Defense against adversarial attacks. " \
"If you find any bug, please new issue. "
# Main CMDs. This deci... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Helio de Jesus and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _, msgprint, throw
from frappe.model.document import Document
from frappe.model.naming import make_autoname
from datet... | nilq/baby-python | python |
from Source import ModelsIO as MIO
import numpy as np
from h5py import File
def E_fit(_cube: np.ndarray((10, 13, 21, 128, 128), '>f4'),
data: np.ndarray((128, 128), '>f4'),
seg: np.ndarray((128, 128), '>f4'),
noise: np.ndarray((128, 128), '>f4')) -> np.ndarray((10, 13, 21), '>f4'):
... | nilq/baby-python | python |
from kivymd.uix.carousel import MDCarousel
class StaticCarousel(MDCarousel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_touch_down(self, touch):
return False
| nilq/baby-python | python |
"""
Create a single inheritance class and use one method from a parent class.
"""
class Animal:
def __init__(self, breed):
self.breed = breed
self.living = True
def is_alive(self):
if self.living:
return f'{self.breed} is alive.'
return f'{self.breed} ... | nilq/baby-python | python |
import torch
from torch import nn
from src.config import data
from src.utils import init_weights
class ClassifierModel(nn.Module):
def __init__(self):
super().__init__()
self.process = nn.Sequential(
nn.Linear(data.x_size, 64, bias=False),
nn.BatchNorm1d(64),
... | nilq/baby-python | python |
import numbers
from bisect import bisect_right
from .. utils.cache import Cache
class NodeRefGroup:
"""
NodeRefGroup class
Members
-------
_ref_lists: dict
dictionary with keys as optimisation key and value as references to nodes sorted by that optimisation key
_temp_list: list
... | nilq/baby-python | python |
# Building a List
# Generate all possible combinations of a string
#
# https://www.hackerrank.com/challenges/building-a-list/problem
#
import itertools
def combo(s):
n = len(s)
def lex():
for i in range(1, 2 ** n):
j = i
w = ''
k = 0
while j != 0:
... | nilq/baby-python | python |
from utils import timer_decorator
@timer_decorator
def fact_1(n: int) -> int:
product = 1
for i in range(n):
product = product * (i+1)
return product
@timer_decorator
def fact_2(n: int) -> int:
if n == 0:
return 1
return n * fact_2(n-1)
| nilq/baby-python | python |
from phreedf import *
name = 'phreedf'
| nilq/baby-python | python |
import os
from fnmatch import fnmatch
import pandas as pd
class ReadFile:
def __init__(self, corpus_path, iters_bulk_size=1000000):
self.corpus_path = corpus_path
list_of_files_to_read = self.find_data_paths_in_corpus()
self.data_paths = [file_path for file_path in list_of_files... | nilq/baby-python | python |
import os.path
import json
from prjxray import grid
from prjxray import tile
from prjxray import tile_segbits
from prjxray import site_type
from prjxray import connections
def get_available_databases(prjxray_root):
""" Return set of available directory to databases given the root directory
of prjxray-db
"... | nilq/baby-python | python |
"""Wordlists loaded from package data.
We can treat them as part of the code for the imperative mood check, and
therefore we load them at import time, rather than on-demand.
"""
import re
import pkgutil
import snowballstemmer
from typing import Iterator, Dict, Set
#: Regular expression for stripping com... | nilq/baby-python | python |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RBase64(RPackage):
"""Compatibility wrapper to replace the orphaned package by Romain
... | nilq/baby-python | python |
from emanager.hr.worker import *
import emanager.utils.file_ops as fop
# fop.init_attendance_sheet(HR_DATA_DIR, ["WO2106242355"])
# test worker.py
worker_name = "Worker 1"
id_ = check_stakeholder_existance(WORKER_DATA_FILE, worker_name)
if id_ is None:
address = "address2"
age = 46
mobile_no = "79087953... | nilq/baby-python | python |
# 使用__slots__限制类可定义的属性
class Student(object):
__slots__ = ("name","age")
#测试绑定其它属性
s = Student()
s.score = 90
| nilq/baby-python | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Bruce_H_Cottman"
__license__ = "MIT License"
import pandas as pd
from pydataset import data
from flask import Flask, request, render_template
from flask_bootstrap import Bootstrap
app = Flask(__name__)
app.debug = True
Bootstrap(app)
@app.route('/show', ... | nilq/baby-python | python |
class MegaCoolNumbersEasy:
def count(self, N):
def is_mega(s):
return len(set(ord(s[i]) - ord(s[i - 1]) for i in range(1, len(s)))) < 2
return sum([is_mega(str(e)) for e in xrange(1, N + 1)])
| nilq/baby-python | python |
#joel Lee
#3/21/2021
#creates a due date for a task
from driver import driver, Keys
import time
#connects to website
driver.get("http://localhost:8080")
#finds the create task button
findtask_button = driver.find_element_by_xpath('//*[@id="tasklist"]/div[1]/h2/span[1]/button').click()
time.sleep(2)
#finds the tas... | nilq/baby-python | python |
import json
import requests
import base64
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA
#from Crypto import Random
public_key = RSA.importKey(open('/tmp/duetpublickey.pem').read())
message = "1,27"
# default hash Algorithm is SHA1, mask generation func... | nilq/baby-python | python |
#!/bin/python
import sys
import math
def _pal2(n):
h = n / 1000 + 1
while True:
p = str(h)
p += p[2::-1]
yield int(p)
h -= 1
def ifact(i):
f1 = int(math.sqrt(float(i))) + 1
while f1 > 99:
f2,r = divmod(i,f1)
if f2 > 999:
return None
... | nilq/baby-python | python |
#
# -*- coding: utf-8 -*-
#
# @Author: Arrack
# @Date: 2020-05-25 17:25:12
# @Last modified by: Arrack
# @Last Modified time: 2020-06-08 15:27:48
#
from wtforms import BooleanField
from wtforms import Form
from wtforms import PasswordField
from wtforms import StringField
from wtforms import SubmitField
from wtform... | nilq/baby-python | python |
numero1 = float(input("primeiro numero: "))
numero2 = float(input("segundo numero: "))
numero3 = float(input("terceiro numero: "))
numero4 = float(input("quarto numero: "))
numero5 = float(input("quinto numero: "))
lista = [numero1,numero2,numero3,numero4,numero5]
soma = sum(lista)
print (soma)
| nilq/baby-python | python |
"""
Python definitions used to help with plotting routines.
*Methods Overview*
-> geo_scatter(): Geographical scatter plot.
"""
import matplotlib.pyplot as plt
from warnings import warn
from .logging_util import warn
import numpy as np
def r2_lin(x, y, fit):
"""For calculating r-squared of a linear fit. Fit... | nilq/baby-python | python |
from direct.directnotify import DirectNotifyGlobal
from src.connection.protocol import *
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from src.messagedirector.ChannelWatcher import ChannelWatcher
class MDParticipant(ChannelWatcher):
notif... | nilq/baby-python | python |
# NOTE THAT 'data' IN THIS CODE IS TRANSPOSE, COMPARED WITH THE MANIFOLDER CODE
# data is shaped [13848,8] here ... ogm ...
# loads in data, dimlist, n_channels, npts, x
# file_location_in_data
# file_location_out_data
import numpy as np
# Coweb, if not installed, can 'pip install -U concept_formation'
# https://git... | nilq/baby-python | python |
from django.conf import settings
from django.core.mail import send_mail
from chatbot.models import Notification
class NotificationProcessor:
def __init__(self, notification: Notification):
self.notification = notification
self.notification_map = {
'welcome': {
'subje... | nilq/baby-python | python |
from django.shortcuts import render
from django.views.generic import (
ListView,
)
from .models import (
Event,
EventPhoto,
)
class AllEventsView(ListView):
model = Event
queryset = Event.objects.all().filter(status = True)
template_name = "event/all_events.html"
context_object_name = "cont... | nilq/baby-python | python |
from tests.utils.owtftest import OWTFCliTestCase
class OWTFCliExceptTest(OWTFCliTestCase):
categories = ['cli']
def test_except(self):
"""Run OWTF web plugins except one."""
self.run_owtf('-s', '-g', 'web', '-e', 'OWTF-WVS-006', "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT))
sel... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 14})
mpl.rc('text', usetex=True)
#V1 = np.genfromtxt('Heat.txt')[::-1]
V2 = np.genfromtxt('Heat_b25.txt')[::-1]
'''
N = len(V1)
plt.figure(figsize=(7,7))
plt.title(r'... | nilq/baby-python | python |
import time
import json
from random import choice, randrange, shuffle
class Citation:
"""
Notre objet Citation est composé de :
- Le contenu (un texte càd str)
- Un auteur (le nom de l'auteur càd str)
- Une origine (titre de l'oeuvre dont elle est extraitre càd str)
- Année de publication càd ... | nilq/baby-python | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe, json
no_cache = True
def get_context(context):
token = frappe.local.form_dict.token
if token:
paypal_express_payment = frappe.get_doc("Paypal Express Payment", token)
... | nilq/baby-python | python |
from tensorflow.keras import layers
from tensorflow.keras.layers import TimeDistributed, LayerNormalization
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
import kapre
from kapre.composed import get_melspectrogram_layer
import tensorflow as tf
import os
def Conv1D(N_CLASSES=10,... | nilq/baby-python | python |
"""Stack Analysis Load test."""
import os
import datetime
import time
from requests_futures.sessions import FuturesSession
start_time = datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
print("TEST START TIME: {}".format(start_time))
three_scale_token = os.getenv('THREE_SCALE_PREVIEW_USER_KEY', '')
api... | nilq/baby-python | python |
from flask import render_template, flash
from flask_login import login_required
from mcadmin.config import CONFIG, _F_USE_JAR
from mcadmin.forms.config.version_form import SetVersionForm
from mcadmin.io.files.server_list import SERVER_LIST
from mcadmin.io.server.server import SERVER
from mcadmin.main import app
@app... | nilq/baby-python | python |
import os
import math
import torch
import pickle
import argparse
# Data
from data.data import add_data_args
# Model
from model.model import get_model, get_model_id
from model.baseline import get_baseline
from survae.distributions import DataParallelDistribution
# Optim
from optim import get_optim, get_optim_id, add_... | nilq/baby-python | python |
"""
Copyright 2020 Hype3808
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... | nilq/baby-python | python |
import os
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_dir, "README.rst"), "r") as f:
long_description = f.read()
setup(
name="flake8parser",
description=(
"A public python API for flake8 created by parsing the command line output.... | nilq/baby-python | python |
import typing
import unittest
from m3c import mwb
from m3c import prefill
List = typing.List
class TestPrefill(unittest.TestCase):
def setUp(self):
self.olddb = [
prefill.db.add_organization,
prefill.db.find_organizations,
prefill.db.get_organization,
pre... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from stateful_simulator.datatypes.DataTypes import FeatureVector
from typing import List
class StatelessModel(ABC):
@abstractmethod
def predict(self, fv: FeatureVector) -> float:
pass
@abstractmethod
def train(self, fvs: List[FeatureVector]):
pass | nilq/baby-python | python |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from turtle import *
import os
import shutil
class Recorder(object):
def __init__(self, func, fps=30):
self.func = func
self.fps = fps
def __enter__(self):
self.record()
... | nilq/baby-python | python |
import unittest
from unittest import mock
from flumine.events import events
class BaseEventTest(unittest.TestCase):
def setUp(self) -> None:
self.mock_event = mock.Mock()
self.base_event = events.BaseEvent(self.mock_event)
def test_init(self):
mock_event = mock.Mock()
base_ev... | nilq/baby-python | python |
import json
import requests
class Gen3FileError(Exception):
pass
class Gen3File:
"""For interacting with Gen3 file management features.
A class for interacting with the Gen3 file download services.
Supports getting presigned urls right now.
Args:
endpoint (str): The URL of the data com... | nilq/baby-python | python |
"""
setup.py: Install IsCAn
"""
import os
import sys
import re
import subprocess
from os.path import join as pjoin
from glob import glob
import setuptools
from distutils.extension import Extension
from distutils.core import setup
from Cython.Distutils import build_ext
import numpy
# --------------------------------... | nilq/baby-python | python |
from setuptools import find_packages, setup
setup(
name="typer", packages=find_packages(),
)
| nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.