content
stringlengths
5
1.05M
from django.http import HttpResponse from drf_yasg.utils import swagger_auto_schema from rest_framework.views import APIView from django.views.decorators.csrf import csrf_exempt from json import dumps from .Public import content_type_tmp class Logout(APIView): @swagger_auto_schema( operation_description='...
from datetime import datetime from rest_framework.serializers import ( ModelSerializer, SerializerMethodField, ) from .models import Book, Author from django.contrib.auth.validators import UnicodeUsernameValidator class AuthorSerializer(ModelSerializer): class Meta: model = Author fields ...
from enum import Enum from core.enums.tesseract_language_code import LanguageCode class DefaultSettings(Enum): SEARCH_MIN_PRECISION = 0.8 SEARCH_THRESHOLD = 0.99 WAIT_TIMEOUT = 10.0 HIGHLIGHT_DURATION = 0.4 HIGHLIGHT_THICKNESS = 5 OCR_MIN_CONFIDENCE = 50 OCR_LANGUAGE = LanguageCode.ENGLIS...
# @Author: allen # @Date: May 06 14:36 2020 import math import os import random import time from datetime import timedelta from functools import wraps from prettytable import PrettyTable def print_table(title, items): table = PrettyTable(title, border=True, hrules=1, header_style='upper', align='m') for item...
# -*- coding: utf-8 -*- import subprocess as sp import sys import os import ete3 import glob import pandas as pd from ftplib import FTP # Run bash commands def run_command(cmd, ommit=False): if ommit: try: process = sp.Popen(cmd, shell=True) except: pass process.comm...
from PIL import Image img = Image.open(r"C:\Users\Henry\Documents\Code\Python\SpotDiff\img.jpg") pixels = img.load() otherimg = Image.open(r"C:\Users\Henry\Documents\Code\Python\SpotDiff\testimg.jpg") otherpx = otherimg.load() diffimg = Image.new( 'RGB', (img.size[0] , img.size[1]), "black") diff = diffimg....
from __future__ import absolute_import, division, print_function import os.path import torch import torch.utils.data as data import numpy as np from torchvision import transforms as vision_transforms from .common import read_image_as_byte, read_calib_into_dict, read_png_flow, read_png_disp, numpy2torch from .common i...
import paho.mqtt.client as mqtt #import the client1 import time import smtplib, ssl import config smtp_server = "smtp.gmail.com" port = 587 # For starttls sender_email = config.EMAIL_ADDRESS1 password = config.PASSWORD receiver_email=config.EMAIL_ADDRESS2 ######################################## def on...
import traceback from altfe.interface.root import classRoot class handleRoute(classRoot): """ Altfe 指令处理核心。 """ @classmethod def do(cls, cmd): # 指令选择 rCMD = cmd if cmd not in cls.AVALS["PLUGIN"]: rCMD = None for x in cls.AVALS["PLUGIN"]: ...
# -*- coding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2019 Philippe Faist # # 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 t...
import os import requests from bs4 import BeautifulSoup from pdf2image import convert_from_path def get_flyers_url(url: str) -> list: """ ロヂャースの店舗のチラシページからチラシpdfのURLを取得する """ ret = [] res = requests.get(url) html = BeautifulSoup(res.content, "html.parser") sid = html.find_all("script")[6]....
# Generated with SMOP 0.41-beta try: from smop.libsmop import * except ImportError: raise ImportError('File compiled with `smop3`, please install `smop3` to run it.') from None # Script_Cliquets_EIA.m ################################################################## ### Cliquet/Equity Index Annui...
import numpy as np def get_review_chance(X, y): # Inputs: # - X is the number of reviews # - y is the number of sales # Output: # - chance to write a review return np.divide(X, np.asarray(y)) def invert_review_chance(X, chance): # Inputs: # - X is the number of reviews # - c is t...
""" unit test """ import inspect import json import logging import os import tempfile from random import random from unittest.case import TestCase from bzt.cli import CLI from bzt.modules.aggregator import DataPoint, KPISet from bzt.utils import run_once, EXE_SUFFIX @run_once def setup_test_logging(): """ set up...
#!/usr/bin/env python import rospy import math import tf from std_msgs.msg import Float64 from geometry_msgs.msg import Twist class Locomotion(): def __init__(self): # Get the locomotion joints controllers from the yaml file self.controllers = rospy.get_param("controllers") # Values are ...
import re from evennia.utils.ansi import ANSIString from athanor.gamedb.scripts import AthanorOptionScript from athanor.gamedb.models import PlotBridge, EventBridge class AthanorPlot(AthanorOptionScript): re_name = re.compile(r"") lockstring = "" def create_bridge(self, key, clean_key): if hasa...
# -*- coding: utf-8 -*- import re import os from worker import * from pymongo import MongoClient mongodb_host = os.environ['MONGODB_PORT_27017_TCP_ADDR'] client = MongoClient("mongodb://%s/" % (mongodb_host)) db = client["datasets"] def build_revisions(): for page_url in open("/data/sources/wicrimea-seeds.exte...
# -*- coding: utf-8 -*- """ module.name ~~~~~~~~~~~~~~~ Preamble... """ from __future__ import absolute_import, print_function, unicode_literals from django.views.generic import TemplateView class ParameterisedTitleView(TemplateView): def post(self, *args, **kwargs): return self.get(*args, *...
# This is a script that scrapes all the data from espncricinfo.com, based on user's input of class (Tests, ODI's, T20's, # etc.) for all types (Batting, Bowling, Fielding, etc.), and dumps all the data into separate CSV files. import requests import os from bs4 import BeautifulSoup classes = { 'tests': 1, 'od...
from tkinter import * from tkinter import ttk import time import requests url = "https://alpha-vantage.p.rapidapi.com/query" headers = { 'x-rapidapi-host': "alpha-vantage.p.rapidapi.com", 'x-rapidapi-key': "8668b5ea1emsh169c17e6f62fa97p1a4b8fjsn71477ee0f336" } class application(ttk.Frame): def __init__(s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2020/1/3 20:04 # @Author : 王洋 # @FileName: map.py # @Software: PyCharm import pymysql import pandas as pd from pandas.core.frame import DataFrame import re,time,random import config db = pymysql.connect( host="localhost", port=3306, user=config....
import elechouse import pid import comms import sensors import time import micropython # in case we crash during an interrupt, this lets more be printed micropython.alloc_emergency_exception_buf(100) # --"constants"-- LOOP_DELAY = 1 # microseconds to sleep between main loops SER_BUS = 6 # which h...
#!/usr/bin/python # -*- coding: utf-8 -*- """TeNOR Virtual Network Function Representation Class and Client""" import requests import json from jinja2 import Template from tenor_dummy_id import TenorDummyId from tenor_vdu import TenorVDU import ConfigParser CONFIG = ConfigParser.RawConfigParser() CONFIG.read('config....
class Solution(object): def multiply(self, num1, num2): a,b=eval(num1),eval(num2) c=a*b c=str(c) return c
from openapi_core.validation.response.datatypes import ( # type: ignore OpenAPIResponse, ResponseValidationResult, ) from openapi_core.validation.response import validators # type: ignore from tornado.httpclient import HTTPResponse # type: ignore from .requests import TornadoRequestFactory from .util import...
# SPDX-License-Identifier: Apache-2.0 # # The OpenSearch Contributors require contributions made to # this file be licensed under the Apache-2.0 license or a # compatible open source license. # Modifications Copyright OpenSearch Contributors. See # GitHub history for details. # Licensed to Elasticsearch B.V. under one ...
#!/usr/bin/env python2 # Waits for one of the daemons to write to /srv/res(t) # and executes '/srv/daemons/runfunc.groovy' as user 'mallory(t)'. # Must be running as root to work. from time import sleep from timeit import timeit from subprocess import call from sys import argv fp = open("/srv/whoami") whoami = fp.rea...
from rest_framework.serializers import ModelSerializer from contacts.models import Contact class ContactSerializer(ModelSerializer): class Meta: model = Contact fields = ['id', 'country_code', 'first_name', 'last_name', 'phone_number', 'contact_picture', 'is_favorite']
from collections import defaultdict, Counter, deque class Solution: def alienOrder(self, words): # Step 0: create data structures + the in_degree of each unique letter to 0. adj_list = defaultdict(set) in_degree = Counter({c : 0 for word in words for c in word}) ...
# -*- coding: utf-8 -*- # This file is part of modulemd-zanata # Copyright (C) 2018 Stephen Gallagher # # Fedora-License-Identifier: MIT # SPDX-2.0-License-Identifier: MIT # SPDX-3.0-License-Identifier: MIT # # This program is free software. # For more information on the license, see COPYING. # For more information on ...
""" Module `chatette.cli.interactive_commands.show_command`. Contains the strategy class that represents the interactive mode command `show` which shows information about a unit definition and lists a bunch of its rules (all if possible). """ from chatette.cli.interactive_commands.command_strategy import CommandStrate...
import time import copy import numpy as np import pandas as pd import jacinle.random as random from jacinle.utils.meta import notnone_property from jaclearn.rl.env import SimpleRLEnvBase from .grid import get_random_grid_generator from .grid import get_solved_grid __all__ = ['Grid', 'randomly_generate_grid_from_data'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 26 13:14:05 2021 @author: guo.1648 """ # Use CKDTree to approximate NN here, instead of using sklearn NN. from tqdm import tqdm import pandas as pd import numpy as np #from sklearn.neighbors import NearestNeighbors from scipy.spatial import cKDTre...
import numpy as np import pandas as pd import matplotlib.pylab as plt import seaborn as sns def load_and_process(csv_file): df = pd.read_csv(csv_file) df1=(df.dropna(axis=0) .sort_values("player_name") .reset_index(drop=True) ) return df1
from pytensor.network.graph import * from pytensor.network.gradient import * from pytensor.network.optimizer import * class Trainer: def __init__(self, model): """ A trainer example using graph for autodiff :param model: """ self.model = model self.optimizer = SGD(...
import logging.config from settings2 import logger_config logging.config.dictConfig(logger_config) logger = logging.getLogger('app_logger') def main(): logger.debug('Enter in to the Main()') if __name__ == "__main__": main()
import pandas as pd import pathlib from typing import Union from sggm.data.uci import UCIDataModule from sggm.data.shifted import DataModuleShifted, DataModuleShiftedSplit DATA_FILENAME = "winequality-white.csv" """ Link to get the concrete.csv file: https://archive.ics.uci.edu/ml/datasets/Wine+Quality Note that I c...
import numpy as np import os # # define some custom parameters, not defined in the DNS code # iseek = 0 # number of bytes to skip relative to the origin of the binary file (0 for CaNS) iprecision = 8 # precision of real-valued data r0 = np.array([0.,0.,0.]) # domain origin non_uniform_grid = ...
""" organize -- The file management automation tool. Usage: organize sim [--config-file=<path>] organize run [--config-file=<path>] organize config [--open-folder | --path | --debug] [--config-file=<path>] organize list organize --help organize --version Arguments: sim Simulate...
""" Copyright (c) Facebook, Inc. and its affiliates. """ import random import re import numpy as np from typing import List, Tuple, Union, Optional # TODO with subinterpret from droidlet.lowlevel.minecraft.craftassist_cuberite_utils import block_data from droidlet.interpreter.craftassist import size_words from .block...
import numpy as np # remarks : official openpose includes more parts JOINT_NAMES = ['Nose', 'Neck', 'Shoulder right', 'Elbow right', 'Hand right', 'Shoulder left', 'Elbow left', 'Hand left', 'Hip center', 'Hip right', 'Knee right', 'Foot right', ...
import pandas as pd import numpy as np from .common import Context # Define type aliases DF = pd.DataFrame S = pd.Series def add_gws_ago(players_gw_team: DF) -> DF: return (players_gw_team .sort_values(['Season', 'Game Week'], ascending=False) .assign(**{'GWs Ago': lambda df: (~df['Expect...
# (C) Copyright 2019-2020 Hewlett Packard Enterprise Development LP. # Apache License 2.0 from pyaoscx import common_ops, interface import json import logging def get_port(port_name, depth=0, selector=None, **kwargs): """ Perform a GET call to retrieve data for a Port table entry :param port_name: Alph...
import argparse import csv import json import os import sys from urs.utils import Export, Global ### Function names are pretty self-explanatory, so I will not be adding comments ### above the functions. ### Includes a total of 26 tests. class MakeArgs(): """ Making dummy args to test Export.py functions. ...
class LoggerInterface: def log(self, to_log: str) -> None: pass def publish(self) -> None: pass
#!/usr/bin/python2 import ddirparse ##### http://stackoverflow.com/questions/2526815/moon-lunar-phase-algorithm import datetime import ephem def get_phase_on_day(year,month,day): """Returns a floating-point number from 0-1. where 0=new, 0.5=full, 1=new""" #Ephem stores its date numbers as floating points, which ...
from Module import AbstractModule class Module(AbstractModule): def __init__(self): AbstractModule.__init__(self) def run( self, network, antecedents, out_attributes, user_options, num_cores, out_path): import os from genomicode import filelib from genomicode im...
 # -*- coding: utf-8 -*- from microMLP import MicroMLP mlp = MicroMLP.Create( neuronsByLayers = [2, 2, 1], activationFuncName = MicroMLP.ACTFUNC_GAUSSIAN, layersAutoConnectFunction = MicroMLP.LayersFullConnect ) nnFalse = MicroMLP.NNValue.FromBool(Fals...
import pythoncom, sys, os, time, win32api from win32com.taskscheduler import taskscheduler task_name='test_addtask.job' ts=pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None, pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler) tasks=ts.Enum() for task in tasks:...
# Saltbot # Copyright 2015 Adam Greig # Released under the MIT license. See LICENSE file for details. __author__ = "Adam Greig" __version__ = "0.0.1" __version_info__ = tuple([int(d) for d in __version__.split(".")]) __license__ = "MIT License" import sys import time import signal import logging import multiprocessin...
# Copyright 2020 QuantumBlack Visual Analytics Limited # # 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 # # THE SOFTWARE IS PROVIDED "AS IS",...
import requests import json import codecs from urllib.parse import parse_qs from typing import List, Dict from ytmusicapi.helpers import * from ytmusicapi.parsers.playlists import * class BrowsingMixin: def search(self, query: str, filter: str = None, limit: int = 20) -> List[Dict]: """ Search You...
#!/usr/bin/python3 """Parses data from fault injection runs stored in JSON files.""" import os import sys import json import argparse import statistics as stats from datetime import timedelta import matplotlib.pyplot as plt import resources.elfUtils as elfUtils from resources.utils import reverseFormatTime, centerT...
"""userservice URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-b...
import pandas as pd import argparse from collections import OrderedDict import numpy as np def main(input_csv, amount, partition=False): df = pd.read_csv(input_csv) if 'youtube_id' in df.columns: columns = OrderedDict([ ('youtube_id', 'video-id'), ('time_start', 'start-time'), ...
#/usr/bin/env python from ..ast_object import ASTObject class SpecFrame(ASTObject): ''' self.astObject is of type starlink.Ast.SpecFrame. ''' def __init__(self): pass
from django import template from django.conf.urls import * from django.views.decorators.cache import cache_page from django.views.generic import RedirectView from canvas.shortcuts import direct_to_template from canvas.url_util import re_slug, re_int, re_group_slug, re_year, re_month, re_day, maybe from canvas.view_gua...
from __future__ import absolute_import, print_function, division, unicode_literals import unittest from xcessiv import models from sklearn.ensemble import RandomForestClassifier class TestReturnTrainDataFromJSON(unittest.TestCase): def setUp(self): self.extraction = models.Extraction() self.extrac...
# Run with: # # $ gunicorn flaskapp:app # from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!"
import bandit import re import ast from bandit.core import test_properties as test @test.checks('Str') @test.test_id('B502') def string_decode(context): if isinstance(context.node._bandit_parent, ast.Attribute): if context.node._bandit_parent.attr == 'decode': return bandit.Issue( s...
""" Problem link: Solution By Keshav Mishra """ from sys import stdin,stdout def input(): return stdin.readline().strip() # def print(s): stdout.write(str(s)+'\n') from collections import Counter # Constants YES = 'YES' NO = 'NO' yes = 'yes' no = 'no' true = 'true' false = 'false' def solve(t): n = int(inp...
from ._base import _rule class Empty: reserved = {} tokens = () @_rule('empty :') def p_empty(self, p): pass
""" 38 - Leia um salário de um funcionário. Calcule e imprima o valor do novo salário sabendo que ele recebeu um aumento de 25%. """ salario = float(input("Qual o seu salário? $: ")) aumento = salario + (salario * 25 /100) print(f"Com o aumento de 25% o seu salário passou a ser: {aumento:.2f}")
VERSION = '2.9.0' VM_TEMP_DIR = 'temp' VM_TEMP_DIR_SOURCE = VM_TEMP_DIR + '/Source' LIBRARIES = [ 'Audio', 'Base64', 'BrowserInterop', 'Cookies', 'Core', 'CrayonUnit', 'CryptoCommon', 'CryptoMd5', 'CryptoSha1', 'Csv', 'DateTime', 'Easing', 'Environment', 'FileIO', 'FileIOCommon', 'G...
import re import pywikibot def frame_year(year): if int(year.group(0)) > 1945: return "'''" + year.group(0) + "'''" else: return year.group(0) wiki = pywikibot.Site() page = pywikibot.Page(wiki, "Paulys Realencyclopädie der classischen Altertumswissenschaft/Autoren") raw = page.text finding =...
import pytest from e2e import SERVICE_NAME class TestBucket: def test_bucket(self): pytest.skip(f"No tests for {SERVICE_NAME}")
from typing import Any, Dict, List, Text import spacy from rasa.nlu.tokenizers.tokenizer import Token, Tokenizer from rasa.shared.nlu.training_data.message import Message class BlankSpacyTokenizer(Tokenizer): """ A simple spaCy tokenizer without a language model attached. This tokenizer implements the t...
import string, sys, threading import scratch class ScratchHandler: #----------------------------------------- def __init__(self, scratchIO_): self.__scratchIO = scratchIO_ # Functions that can be parsed self.availableFunctions = ['config','read','write'] # Set the defaults for the connection ...
import urllib.parse import logging import dataclasses import datetime import dateutil.parser import lxml.html import requests LOGGER = logging.getLogger("meetupscraper") @dataclasses.dataclass(frozen=True) class Venue: name: str street: str @dataclasses.dataclass(frozen=True) class Event: url: str ...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # ConfigValidation check # ---------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # -------------------------------------------------------...
# encoding: utf8 from rest_framework import filters, exceptions as rest_exceptions from pyparsing import ParseException from django.core import exceptions as django_exceptions from django.db.models import Q, F from rest_framework.serializers import as_serializer_error from .exceptions import BadQuery from . import p...
import bisect as bi t = int(input()) assert(1<=t<=10) for _ in range(t): n,m = map(int,input().split()) assert(1<=m<=10**5) assert(1<=n<=10**4) books = list(map(int,input().split())) for i in range(m): assert(1<=books[i]<=10**5) l = list(map(int,input().split())) r = list(...
import json import logging import os import socket import threading log = logging.getLogger(__name__) class SocketResource: def __init__(self, socket_file): self.socket_file = socket_file try: os.remove(self.socket_file) except OSError: pass self.server = s...
import evdev import time import struct class appcodec(): def __init__(self): self.device = evdev.InputDevice("/dev/input/event2") self.capabilities = self.device.capabilities(verbose=True) self.capaRAW = self.device.capabilities(absinfo=False) self.config = {} self.state = {...
""" test_numpy.Quickstart_tutorial-03.py * References Quickstart tutorial https://docs.scipy.org/doc/numpy/user/quickstart.html TODO: Start from A frequent error consists in calling array with multiple numeric """ import numpy as np a = np.array( [2,3,4] ) """ >>> a array([2, 3, 4]) >>> a.dtype dtype('int64...
import os import json import unittest import pytest from datetime import datetime from unittest.mock import MagicMock from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.markets.models import * from py_client.modules.markets import endpoints from .commo...
from views_test import ViewsTest __test__ = { 'views_test': ViewsTest, }
# -*- coding: utf-8 -*- """ Created on Sat May 8 2021 @author: Markus Borg """ import sys import os.path from datetime import date from swesesci.scholar import SSSScholar from swesesci.affiliation import SSSAffiliation from swesesci.scholar_miner import ScholarMiner from swesesci.scholar_analyzer import ScholarAnalyz...
import logging from anubis.env import env from anubis.utils.data import is_debug def _get_logger(logger_name): """ For any of the anubis services that use the API, the logger name should be specified. In prod, container logs will be captured by filebeat and pushed into elasticsearch in the elasti...
# -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui board_keys= {} board_keys[16777235] = "UP" board_keys[16777237] = "DOWN" board_keys[16777234] = "LEFT" board_keys[16777236] = "RIGHT" board_keys[32] = "SPACE" class QLineEdit_keyDetecter(QtGui.QLineEdit): def keyPressEvent(self, event): key = event.k...
from django.contrib import admin from django import forms from .models import Article from .models import Language class PostAdmin(admin.ModelAdmin): ...
data = ( 'Tani ', # 0x00 'Jiao ', # 0x01 '[?] ', # 0x02 'Zhang ', # 0x03 'Qiao ', # 0x04 'Dun ', # 0x05 'Xian ', # 0x06 'Yu ', # 0x07 'Zhui ', # 0x08 'He ', # 0x09 'Huo ', # 0x0a 'Zhai ', # 0x0b 'Lei ', # 0x0c 'Ke ', # 0x0d 'Chu ', # 0x0e 'Ji ', # 0x0f 'Que ', # 0x10 '...
# Tambahkan nilai default untuk name def print_hand(hand, name='Tamu'): print(name + ' memilih: ' + hand) # Tambahkan argument ke print_hand print_hand('Batu')
import inspect import os from pandas.util.testing import network import pytest from pvlib._deprecation import pvlibDeprecationWarning from pvlib.iotools import tmy from conftest import fail_on_pvlib_version test_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) tmy3_testfile = os.path...
from ortools.linear_solver import pywraplp def ShowResults(solver, variable_list, constraint_list): """Solve the problem and print the solution.""" print('# of variables = %d' % solver.NumVariables()) print('# of constraints = %d' % solver.NumConstraints()) result_status = solver.Solve() # check ...
import scrapy class AuthorSpider(scrapy.Spider): name = 'authors-details' start_urls = [ 'http://quotes.toscrape.com/', ] def parse(self, response): for href in response.css('.author + a::attr(href)').extract(): yield scrapy.Request( response.urljoin(href),...
"""Platform for switch integration.""" import logging from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from .const import DOMAIN from .devolo_device import DevoloDeviceEntity _LOGGER = logging.getL...
###################### # Processing irregular data is usually rather tricky. # One of the best bits about Neural CDEs is how it is instead really straightforward. # # Here we'll look at how you can handle: # - variable-length sequences # - irregular sampling # - missing data # - informative missingness # # In every cas...
class Other: def __init__(self, name): self.name = name def get_name(self): return self.name @staticmethod def decode(data): f_name = data["name"] if not isinstance(f_name, str): raise Exception("not a string") return Other(f_name) def encode(self): data = dict() if sel...
import base64 import bz2 import hashlib import plistlib from django import forms from django.conf import settings from django.contrib.auth.decorators import login_required, permission_required from django.core.urlresolvers import reverse from django.db.models import Count, Q from django.http import (Http404, HttpReque...
import os import sys import subprocess import logging import json from pathlib import Path from json import load, dump from discord.ext import commands from cogs.utils.config import * if not os.path.exists('settings/'): os.makedirs('settings/') def setup(): config = {} print("Welcome to the...
from mesh.exceptions import OperationError from scheme import * from spire.support.logs import LogHelper from flux.engine.product import Product from flux.engine.rule import RuleList from flux.engine.step import Step from flux.exceptions import * log = LogHelper('flux') Layout = Sequence(Structure({ 'title': Tex...
import argparse import copy import json import warnings import numpy as np import pytest import tabmat as mx from git_root import git_root from scipy import sparse from glum import GeneralizedLinearRegressor, GeneralizedLinearRegressorCV from glum._glm import TweedieDistribution from glum_benchmarks.data import simul...
from django.urls import path from django.urls import path from . import views # Эта строчка обязательна. # Без нее чуда не произойдет и namespace работать не будет app_name = 'posts' urlpatterns = [ # Главная страница path('', views.index, name='index'), # Страница со списком сортов мороженого path('...
# -*- coding: UTF-8 -*- """ 此脚本用于如何使用统计方法解决模型幻觉 """ # 保证脚本与Python3兼容 from __future__ import print_function import os import numpy as np import statsmodels.api as sm import matplotlib.pyplot as plt import pandas as pd def generateRandomVar(): """ """ np.random.seed(4873) return np.random.randint(2,...
#!/usr/bin/env python3 # pylint: disable=missing-docstring import unittest import hypothesis import hypothesis.strategies import numenc MIN_SIGNED_INT8 = -128 MAX_SIGNED_INT8 = 127 MAX_UNSIGNED_INT8 = 255 class TestEncodingInt8(unittest.TestCase): @hypothesis.given( hypothesis.strategies.integers( ...
import os from aoc.utils.file_reader import read_file_line from aoc.utils.file_reader import path_join from string import ascii_lowercase directory_path = os.path.dirname(os.path.realpath(__file__)) input_filename = "input.txt" start = "shiny gold" # "Solve it like BFS " """ """ def problem_part1(bags): holding ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import JsonResponse from django.shortcuts import render from rest_framework import generics from .serializers import TickSerializer from .models import Ticks import re class ListView(generics.ListAPIView): """ Returns all the...
try: from detect_simd.core import detect except ImportError: raise ImportError("Run setup.py to build library before importing.") __all__ = ["detect_simd.core"]
# The "fake" article entry point # no dependencies etc. class FakeArticle: def __init__(self): pass def get_article(self, idx): return { "id": idx, "title": "The test title" }