content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from django.conf.urls import url from . import views # The API URLs are now determined automatically by the router urlpatterns = [ url(r"^$", views.index, name="index_page"), url(r"^projects/create$", views.project_creat...
nilq/baby-python
python
from flask import Flask, render_template from flask_cors import CORS from prometheus_client import Summary, MetricsHandler, Counter from agaveflask.utils import AgaveApi, handle_error from controllers import MetricsResource, CronResource from errors import errors app = Flask(__name__) CORS(app) api = AgaveApi(app, ...
nilq/baby-python
python
#!/usr/local/bin/python import SimpleHTTPServer, SocketServer, logging, subprocess, sys, glob, re, mimetypes import argparse as argparse # Stop traceback on ctrl-c sys.tracebacklimit = 0 parser = argparse.ArgumentParser() parser.add_argument("-p", nargs='?', default=8000) parser.add_argument("-d", nargs='?', defaul...
nilq/baby-python
python
import os import time import numpy as np import paddle.fluid as fluid import config as cfg from nets.attention_model import attention_train_net from nets.crnn_ctc_model import ctc_train_net from utils import data_reader from utils.utility import get_ctc_feeder_data, get_attention_feeder_data def main(): """OCR tr...
nilq/baby-python
python
#Importing Libraries import os import cv2 import time import struct import socket import pyaudio import freenect import wikipedia import playsound import numpy as np from gtts import gTTS from scripts.rhino.rhino import * from scripts.porcupine.porcupine import * #Fucntion to get images def get_image(type, client): ...
nilq/baby-python
python
from .publish_measurement_handler import PublishMeasurementTransactionHandler from .issue_ggo_transaction_handler import IssueGGOTransactionHandler from .transfer_ggo_handler import TransferGGOTransactionHandler from .split_ggo_handler import SplitGGOTransactionHandler from .retire_ggo_handler import RetireGGOTrans...
nilq/baby-python
python
__author__ = 'guorongxu' import sys import re import math import logging def parse_correlation(correlation_file): correlation_list = {} with open(correlation_file) as fp: lines = fp.readlines() for line in lines: fields = re.split(r'\t+', line) correlation_list.update({...
nilq/baby-python
python
"""Create grid-based spatial indexes. Basic Usage =========== Calculate the grid index or indices for a geometry provided in well-known binary format at a given resolution: Example: >>> from shapely.geometry import Point >>> pnt = Point(555000, 185000) >>> bng_pnt = calculate_bng_index( wkb = pn...
nilq/baby-python
python
from enum import IntEnum class Finger(IntEnum): Thumb = 0 Index = 1 Middle = 2 Ring = 3 Little = 4 @staticmethod def get_array_of_points(finger): finger_array = None if finger == Finger.Thumb: finger_array = [(0, 4), (4, 3), (3, 2), (2, 1)] elif fing...
nilq/baby-python
python
import torch import os import sys import re import logging from os.path import isfile import copy import threading import time import enum from torch.multiprocessing import Pool, Process, set_start_method, Manager, Value, Lock try: set_start_method('spawn') except RuntimeError: pass class CFMode(enum.Enum): MANU...
nilq/baby-python
python
""" Expose PV data """ # # import logging # from datetime import datetime, timedelta # from typing import List # # from fastapi import APIRouter, Depends # from nowcasting_datamodel.models import PVYield # from nowcasting_datamodel.read.read_pv import get_latest_pv_yield, get_pv_systems # from sqlalchemy.orm.session im...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class HostManagementConfig(AppConfig): name = 'host_management'
nilq/baby-python
python
import numpy as np from scipy.io import readsav class fts: ll = None ii = None cc = None nu = None datafile = './fts_disk_center.idlsave' def __init__(self): # watt / (cm2 ster AA) as emitted at solar surface t = readsav(self.datafile) # convert to ...
nilq/baby-python
python
# Copyright (c) 2019 Cisco and/or its affiliates. # 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 ag...
nilq/baby-python
python
import discord from itertools import cycle from discord.ext import commands, tasks status = cycle(['Add ur text here','ur text here','ur text here','ur text here']) # you can add as much as you want EX: 'Stiizzy cat is hot','Name' bot = commands.Bot(command_prefix="!") # prefix will not be used for changng status @...
nilq/baby-python
python
import logging from datetime import datetime from pprint import pprint from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import text from opennem.db import db_connect from opennem.db.load_fixtures import update_existing_geos from opennem.db.models.opennem import Fac...
nilq/baby-python
python
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 # from http://stackoverflow.com/questions/15896217/django-loading-a-page-that- # has-external-authentication-changes-the-session-key class PersistentSessionMiddleware(object): """ Injects the username into REMOTE_USER so that ...
nilq/baby-python
python
# -*- coding: UTF-8 -*- from mpi4py import MPI from sympy import pi, cos, sin from sympy.abc import x, y from sympy.utilities.lambdify import implemented_function import pytest from sympde.calculus import grad, dot from sympde.calculus import laplace from sympde.topology import ScalarFunctionSpace from sympde.topolog...
nilq/baby-python
python
# Solution of; # Project Euler Problem 226: A Scoop of Blancmange # https://projecteuler.net/problem=226 # # The blancmange curve is the set of points $(x, y)$ such that $0 \le x \le 1$ # and $y = \sum \limits_{n = 0}^{\infty} {\dfrac{s(2^n x)}{2^n}}$, where # $s(x)$ is the distance from $x$ to the nearest integer. ...
nilq/baby-python
python
from aiohttp import ClientSession from asyncio import get_event_loop class ManagedHTTP: def __init__(self): self.session = ClientSession() async def ensure_session(self): if self.session.closed: self.session = ClientSession() async def request(self, method: str, url: str, *ar...
nilq/baby-python
python
"""Test the functions exposed at the top level of the module. This isn't a full test of each method's capabilities, just checking that the method is exposed at the top level namespace. """ import warnings import pytest import uk_politics import uk_politics.exceptions def test_color(): """Check that...
nilq/baby-python
python
# Copyright 2018 Google Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
nilq/baby-python
python
# Generated by Django 3.1.2 on 2020-10-25 14:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
nilq/baby-python
python
name = 'membercount' aliases = ['members'] async def run(message): 'Lists the number of people that are in this server' true_member_count = message.guild.member_count await message.channel.send( f'There are **{true_member_count:,}** people in this server.' )
nilq/baby-python
python
import subprocess as sp import os import shutil import tempfile import logging logger = logging.getLogger(__name__) class AutoLoader(object): """Base class for automatic loaders (e.g. Git)""" pass class Git(AutoLoader): def __init__(self, url, import_as=None, branch=None): "Creates a temporary di...
nilq/baby-python
python
"""Filex.""" import random from utils import timex MIN_INT, MAX_INT = 10 ** 15, 10 ** 16 - 1 def read(file_name): """Read.""" with open(file_name, 'r') as fin: content = fin.read() fin.close() return content def write(file_name, content, mode='w'): """Write.""" with open(f...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ fudcon.ui ------ fudcon ui application package """
nilq/baby-python
python
from enigma import eRect, eServiceReference, iServiceInformation, iPlayableService from Screens.Screen import Screen from Screens.ServiceInfo import ServiceInfoList, ServiceInfoListEntry from Components.ActionMap import ActionMap, NumberActionMap from Components.Pixmap import Pixmap from Components.Label import Label f...
nilq/baby-python
python
''' Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2018 Sergio Rojas (srojas@usb.ve) http://en.wikipedia.org/wiki/MIT_License http://creativecommons.org/licenses/by/4.0/ Created on march, 2018 Last Modified on: may 15, 2018 ''' def myfuncPrimeFactors(n): """ This f...
nilq/baby-python
python
import hashlib from settings import SIZE class Address: def __init__(self, ip, port): self.ip = ip self.port = port def __key(self): return f"{self.ip}{self.port}".encode() def __hash__(self): """ Python uses a random hash seed to prevent attackers from tar-pitti...
nilq/baby-python
python
# -*- coding:utf-8 -*- import logging from time import sleep import bigsuds from networkapi.plugins import exceptions as base_exceptions from networkapi.system.facade import get_value as get_variable log = logging.getLogger(__name__) class Lb(object): def __init__(self, hostname, username, password, session=T...
nilq/baby-python
python
import image, touch, gc, time from machine import I2C from board import board_info from fpioa_manager import fm from Maix import GPIO import time from machine import SPI from micropython import const from sx127x import SX127x board_info=board_info() i2c = I2C(I2C.I2C3, freq=1000*1000, scl=24, sda=27) # amigo devices =...
nilq/baby-python
python
#!/usr/bin/env python import boto3 import botocore import argparse import sys parser = argparse.ArgumentParser(description='Check if the given AWS VPC exists.') parser.add_argument('--region_name', dest='region_name', action='store', required=True, help='AWS Region name, e.g. eu-west-1') parser.add_argument('--vpc_nam...
nilq/baby-python
python
def arrays(arr): # complete this function # use numpy.array return(numpy.array(arr,float))[::-1]
nilq/baby-python
python
# Copyright 2004-2018 Tom Rothamel <pytom@bishoujo.us> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, m...
nilq/baby-python
python
# # -*- coding: utf-8 -*- from collections import Counter from tests.testapp.tests.base_tests import BaseRedisTestCase from tests.testapp.tests.multi_server_tests import MultiServerTests from django.test import TestCase, override_settings LOCATION = "unix://:yadayada@/tmp/redis0.sock?db=15" LOCATIONS = [ "unix:/...
nilq/baby-python
python
import os import logging # (windows only for now) if os.name == 'nt': try: logging.info('Looking for CUDA and adding it to path...') # some python versions fail to load the path variables, so we're doing it manually here before importing tf loaddir = "C:/Program Files/NVIDIA GPU Comput...
nilq/baby-python
python
import os import getpass import hashlib os.system('cls') print("Done...") if 'MainDrive' in os.listdir('.'): os.rmdir("MainDrive") os.mkdir('MainDrive/') os.mkdir('MainDrive/Users/') username = input("Username: ") password = getpass.getpass("Password (No echo): ") encp = password.encode() d = hash...
nilq/baby-python
python
# -*- encoding: utf-8 -*- """ @File : Surprise_SGD.py @Time : 2020/11/21 14:41 @Author : biao chen @Email : 1259319710@qq.com @Software: PyCharm """ from surprise import Dataset from surprise import Reader from surprise import BaselineOnly, KNNBasic from surprise import accuracy from surprise.model...
nilq/baby-python
python
######## # Copyright (c) 2016 GigaSpaces Technologies 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 # # Unless...
nilq/baby-python
python
######################################################################### # Copyright/License Notice (Modified BSD License) # ######################################################################### ######################################################################### # Copyright (c) 2008, Da...
nilq/baby-python
python
from .test_helper import argv_kiwi_tests import sys import mock from mock import patch import azurectl from pytest import raises from azurectl.commands.storage_account import StorageAccountTask from azurectl.azurectl_exceptions import AzureInvalidCommand class TestStorageAccountTask: def setup(self): sy...
nilq/baby-python
python
def mySqrt(x): r = x precision = 10 ** (-10) print(precision) while abs(x - r * r) > precision: r = (r + x / r) / 2 return r print(mySqrt(25)) print(mySqrt(36))
nilq/baby-python
python
from restkit.handlers.http_mrg_handlers import query_handler as chandler_0 # noqa from restkit.handlers.http_mrg_handlers.http_report_handlers import report_csv_handler as chandler_1 # noqa __all__ = [ 'chandler_0', 'chandler_1', ]
nilq/baby-python
python
from dart_fss.api import filings def test_get_corp_code(): res = filings.get_corp_code() actual = res[0].keys() expected = ['corp_code', 'corp_name', 'stock_code', 'modify_date'] for act in actual: assert act in expected def test_get_corp_info(): se = filings.get_corp_info('00126380') ...
nilq/baby-python
python
from urllib.parse import urlencode import requests from module_pipedrive.pipedrive import exceptions from module_pipedrive.pipedrive.activities import Activities from module_pipedrive.pipedrive.deals import Deals from module_pipedrive.pipedrive.filters import Filters from module_pipedrive.pipedrive.leads import Leads...
nilq/baby-python
python
#!/usr/bin/python """ Copyright (C) International Business Machines Corp., 2005 Author: Dan Smith <danms@us.ibm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; under version 2 of the Licen...
nilq/baby-python
python
r"""Analyze Traffic Images This executable is used to annotate traffic images to highlight vehicle types and to produce stats and graphs for the amount of time bicycle lanes and bus stops are blocked by vehicles: Example usage: ./analyzeimages \ -path_images ./data/rawimages/ -path_labels_map dat...
nilq/baby-python
python
import json import random from locoloco.models.db_orm import db from locoloco.models.db_models import User from locoloco.models.db_models import Country from locoloco.models.db_models import DistributionCenter from locoloco.models.db_models import StoreStatus from locoloco.models.db_models import Store from locoloco....
nilq/baby-python
python
from pdfrw import PdfObject, PdfReader, PdfWriter import os defaultlang = 'en-US' #read all files in the folder called 'files' files = os.listdir('files') for file in files: print(file) fixlist = [] trailer = PdfReader('files\\'+file) print("Lang: ",trailer.Root.Lang) if trailer.Root.Lang == None: fixlist.appe...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8; -*- # Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ import oci import os from ads.common import utils def api_keys( oci_config: str = os.path.join(os.path....
nilq/baby-python
python
import sys def print_line(to_file=None): if to_file: print("--------------------------------------------------", file=to_file) else: print("--------------------------------------------------") def print_header(): print_line() print("NAS Parallel Benchmark v3.2") print...
nilq/baby-python
python
import asyncio import os from telethon import TelegramClient TELETHON_SESSION_FILE: os.path = input("Please insert path to telethon session file: ") API_ID: int = int(input("Please insert session api id: ")) API_HASH: str = input("Please insert session api hash: ") TG_USERNAME_RECIPIENT: str = input( "Please inse...
nilq/baby-python
python
import logging from sklearn.dummy import DummyClassifier, DummyRegressor from amlb.benchmark import TaskConfig from amlb.data import Dataset from amlb.results import save_predictions from amlb.utils import Timer, unsparsify log = logging.getLogger(__name__) def run(dataset: Dataset, config: TaskConfig): log.in...
nilq/baby-python
python
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli...
nilq/baby-python
python
from PLC.Faults import * from PLC.Method import Method from PLC.Parameter import Parameter, Mixed from PLC.Persons import Person, Persons from PLC.Auth import Auth class DeletePerson(Method): """ Mark an existing account as deleted. Users and techs can only delete themselves. PIs can only delete thems...
nilq/baby-python
python
#------------------------------------------------------------------------------- # # An abstract base class implementation of the ITemplateDataNameItem interface # that looks for all specified values in its input context or optionally any of # its sub-contexts and outputs a context containing all such values found. ...
nilq/baby-python
python
import itertools import math def Solution(): N: int T = int(input("테스트 수행횟수 입력:")) # 갯수 for i in range(0, T): N = int(input("입력데이터: ")) sData = str(input("값 추가 \n")) ans = math.trunc(sortMaxMin(sData, N)) print(ans) def sortMaxMin(inputData: str, N: int): maxNumber : ...
nilq/baby-python
python
#!/usr/bin/python3 """ We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only be true or false. The root node represents the whole grid. For each node, it will be subdivided into four children nodes until the values in the region it represents are all the same. Each node has another t...
nilq/baby-python
python
#!/usr/bin/env python # Small web app to allow a user to top up their personal PaperCut balance # Add a custom URL to the PaperCut user web page, which is used by end users # when they want to add credit to their PaperCut personal account. The url # should refer to this small web app When the user clicks on the URL l...
nilq/baby-python
python
#!/usr/bin/python #-*- coding: utf-8 -*- from distutils.core import setup, Extension import os import sys prefix = os.environ.get("prefix", "/usr") from distutils.core import setup, Extension import subprocess as S setup(name="polkit", version="1.0.2", description="Python bindings for polkit-1", l...
nilq/baby-python
python
""" Loading data and events submodule. """ from ..signal import find_events #from .eeg_preprocessing import * import numpy as np import pandas as pd import mne import os # ============================================================================== # =================================================================...
nilq/baby-python
python
import json your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]' parsed = json.loads(your_json) print(type(your_json)) print(type(parsed)) #print(json.dumps(parsed, indent=4, sort_keys=True))
nilq/baby-python
python
# Time complexity: O(n) # Approach: Implementation using 2 arrays. class MinStack: def __init__(self): """ initialize your data structure here. """ self.stack = [] self.minStack = [] def push(self, val: int) -> None: if len(self.minStack)==0: self.s...
nilq/baby-python
python
from celery.utils.log import get_task_logger from flask.ext.celery import Celery from datetime import datetime, timedelta import time from app import app, db from models import Agency, Prediction from nextbus import Nextbus """ Celery is a task queue for background task processing. We're using it for scheduled tasks, ...
nilq/baby-python
python
""" Контекстный процессор для меню. """ from .utils import get_menus def menu_processor(request): """ Контекстный процессор для возможности отображения всех меню на сайте. Меню обычно распологаются на нескольких страницах, поэтому вынесено сюда. """ current_path = request.path context = { ...
nilq/baby-python
python
from typing import Union import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn from torch import Tensor from .functions import ActivationModule from activations.utils.utils import _get_auto_axis_layout def tent_activation(x, delta): """ Functional implementation of TentActivati...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division from __future__ import print_function import numpy as np import operator as op from NumPyNet.exception import LayerError from NumPyNet.utils import check_is_fitted from NumPyNet.layers.base import BaseLayer __author__ = ['Mattia Ceccarelli...
nilq/baby-python
python
try: from libs.layers import * from libs.utils_ft import * except: from layers import * from utils_ft import * import copy import os import sys from collections import defaultdict from typing import Optional import torch import torch.nn as nn from torch import Tensor from torch.nn import MultiheadAtte...
nilq/baby-python
python
from django.conf.urls import url from authen import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ url(r'^api/user/(?P<pk>[0-9]+)/$', views.person_detail), url(r'^api/add_group/(?P<pk>[0-9]+)/$', views.add_group), url(r'^api/user/$', views.person_list), url(r'^$', vi...
nilq/baby-python
python
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli...
nilq/baby-python
python
# Copyright (c) 2021, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root # or https://opensource.org/licenses/BSD-3-Clause import os import unittest import numpy as np import torch from warp_drive.managers.data_manager im...
nilq/baby-python
python
# Copyright (c) 2017 OpenStack Foundation. # # 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...
nilq/baby-python
python
import re from model.contact import Contact def test_contact_info_from_home_page(app, db): app.navigation.open_home_page() contact_from_home_page = sorted(app.contact.get_contact_list(), key=Contact.id_or_max) def clean(contact): return Contact(id=contact.id, firstname=contact.firstname.strip(), ...
nilq/baby-python
python
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define array print(type(x)) x.pop(2) #remove third element print(x) x.remove(2.5) #remove element equal to 2.5 print(x) x.append(1.2) #add an element at the end print(x) y = x.co...
nilq/baby-python
python
import datetime import itertools import functools import io import os import pathlib import string import tqdm import pytz import requests import apiclient.http import fuzzywuzzy.fuzz from .info import Conference, ConferenceInfoSource, Session from apiclient.discovery import build from google_auth_oauthlib.flow impo...
nilq/baby-python
python
from microbit import display from microbit import Image from KitronikClipDetector import Detector sensor = Detector() while True: if sensor.readDigitalSensor("P2", "Dark") is True: display.show(Image.HAPPY) else: display.show(Image.SAD)
nilq/baby-python
python
"""Urls for the Zinnia entries short link""" from django.conf.urls import url from django.conf.urls import patterns from zinnia.views.shortlink import EntryShortLink urlpatterns = patterns( '', url(r'^(?P<pk>\d+)/$', EntryShortLink.as_view(), name='zinnia_entry_shortlink'), )
nilq/baby-python
python
''' SOLED Scrapy settings For simplicity, this file contains only settings considered important or commonly used. You can find more settings consulting the documentation: http://doc.scrapy.org/en/latest/topics/settings.html http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html http://s...
nilq/baby-python
python
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
nilq/baby-python
python
# Copyright 2017-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
nilq/baby-python
python
# required for test discovery
nilq/baby-python
python
# Copyright 2021 Victor I. Afolabi # # 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 wri...
nilq/baby-python
python
# Created By: Virgil Dupras # Created On: 2009-04-23 # Copyright 2013 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import unittest from nltk.classify.naivebayes import NaiveBayesClassifier class NaiveBayesClassifierTest(unittest.TestCase): def test_simple(self): training_features = [ ({'nice': True, 'good': True}, 'positive')...
nilq/baby-python
python
# -*- coding: utf-8 -*- import os from youtube_title_parse import get_artist_title class MetaTestSequence(type): def __new__(mcs, name, bases, attrs): def should_skip(test_params): if not test_params: return False if "skip" in test_params and test_params["skip"] is ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import pickle import numpy as np import pandas as pd import pystan import os, sys import stan_utility import patsy import arviz as az GLMEdata = pd.read_csv('GLMEdata.csv') GLMEdata = GLMEdata[GLMEdata.exp == 1] GLME = stan_utility.compile_model('GLME.stan', model_name="GLME") fixeff_form = "...
nilq/baby-python
python
from django.db import models # Create your models here. MALE = 'M' FEMALE = 'F' UNKNOWN = 'U' GENDER_CHOICES = ( (MALE, 'Male'), (FEMALE, 'Female'), (UNKNOWN, 'Unknown')) class AdmissionsByGender(models.Model): PRIMARY = 'P' SECONDARY = 'S' DIAGNOSIS_CHOICES = ( (PRIMARY, 'Primary'),...
nilq/baby-python
python
# !/usr/bin/env python # -*- coding:utf-8 -*- # @Project : stock_quant # @Date : 2022/1/18 23:29 # @Author : Adolf # @File : info_push.py # @Function: import json import requests import logging def post_msg_to_dingtalk(title="", msg="", token="", at=None, type="text"): if at is None: at = [] ur...
nilq/baby-python
python
import unittest import json from mock import patch from provider.utils import unicode_encode from provider.execution_context import S3Session from tests.activity.classes_mock import FakeS3Connection from tests import settings_mock class TestS3Session(unittest.TestCase): @patch("provider.execution_context.S3Sessio...
nilq/baby-python
python
import pyopencl as cl import numpy as np np.set_printoptions(linewidth=128) BOARD_SIZE = 10 SHIP_SIZES = [5,4,3,3,2] STATE_MISS = 0 STATE_HIT = 1 STATE_UNKNOWN = 2 def bool2IntArray(boolArray): ret = [] for array in boolArray: ret.append(np.packbits(array)) return ret def int2BoolArray(boolArray): ret = [] ...
nilq/baby-python
python
from sklearn.metrics import mean_absolute_percentage_error as mape from sklearn.metrics import r2_score def mean_absolute_percentage_error(actual, forecast) -> float: """ calculate mean absolute percentage error (MAPE) :param actual: actual values :param forecast: forecast (prediction) values :ret...
nilq/baby-python
python
################################################################################ # # # RUN ALL TESTS AND CHECK FOR ACCURACY # # ...
nilq/baby-python
python
from typing import Any, Dict import numpy import scipy.special from mlxtk.util import memoize @memoize def binom(n: int, k: int) -> int: return int(scipy.special.binom(n, k)) # @jit def build_number_state_table_bosonic(N: int, m: int) -> numpy.ndarray: number_of_states = binom(N + m - 1, m - 1) number...
nilq/baby-python
python
from nltk import word_tokenize from nltk.stem import WordNetLemmatizer import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel import numpy as np import nltk from nltk.corpus import stopwords nltk.download('punkt') stop_words = set(stopwords.w...
nilq/baby-python
python
import torch.nn as nn from .torch_helpers import NamedTensor class Module(nn.Module): def register_parameter(self, name, tensor): if isinstance(tensor, NamedTensor): param = nn.Parameter(tensor.values) super(Module, self).register_parameter( "_" + name + "_named", p...
nilq/baby-python
python
import json from django.core.urlresolvers import reverse, NoReverseMatch from django.contrib.admin.templatetags.admin_static import static from django.template import Template, Context from django.utils.encoding import force_text from django.template.loader import get_template from django.forms.models import BaseModel...
nilq/baby-python
python
import ray import torch from models import Model import numpy as np import random from atari_wrappers import make_atari, wrap_deepmind @ray.remote class Player: def __init__(self, checkpoint, replay_buffer, share_storage, test_mode): self.game = make_atari(checkpoint["game"]+"NoFrameskip-v4") self...
nilq/baby-python
python
# Generated by Django 3.0.9 on 2020-08-17 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('filer', '0011_auto_20190418_0137'), ] operations = [ migrations.AddField( model_name='file', name='description_en', ...
nilq/baby-python
python
import unittest import test, app import nltk from nltk.tokenize import word_tokenize import json class TestGetRAD(unittest.TestCase): def test_word_classifier(self): keyword = 'I coughed a lot and vomited. I also have a headache.' words = word_tokenize(keyword) # returns tag name of part ...
nilq/baby-python
python