content
stringlengths
5
1.05M
class PriceDisplayFraction(object): def __init__(self, denominator=16): self.denominator = denominator def to_display(self, cents): cents_int = int(cents) cents_flt = int((cents - cents_int) * self.denominator) return f'{cents_int/100}/{cents_flt}' def to_internal(self, dis...
# Copyright 2020 BULL SAS All rights reserved # from collections import Counter from logflow.logsparser.Pattern import Pattern from loguru import logger from typing import Dict, List class Cardinality: """A cardinality is a length of line. The length is defined as the number of words. Args: counter_g...
""" Trinket/Gemma (ATtiny85) programming example, be sure you have the '85 wired up so: Trinket Ground to CircuitPython GND Trinket USB to CircuitPythong USB or make sure the Trinket is powered by USB Pin 2 -> CircuitPython SCK Pin 1 -> CircuitPython MISO Pin 0 -> CircuitPython MOSI RESET -> CircuitPython ...
# -*- coding: utf-8 -*- """FontLab Tokenize Tokenize FontLab’s preview/metrics text into single characters respecting escaped glyph names (eg. “/A.smcp”) and providing a lossless reverse function. Sample usage (and actual test suite): >>> tokenize('/A/B/C') ['/A', '/B', '/C'] >>> tokenize('abcde/B/C') ['a', 'b', 'c'...
from datetime import datetime class SendEventAsync: @classmethod def exit_handler(cls, scheduler, debug): try: # Shut down the scheduler scheduler.remove_job('moesif_events_batch_job') scheduler.shutdown() except Exception as ex: if debug: ...
import itsdangerous from flask import request, current_app, abort, g from flask_debugtoolbar import module from flask_debugtoolbar.panels import DebugPanel from flask_debugtoolbar.utils import format_sql from jinja2 import ChoiceLoader, PackageLoader try: from django.db import connection from django.conf impor...
def f(): yield 42 f()
""" Helper functions """ import json from datetime import date, datetime, timedelta def ounce_to_grams(ounces): return ounces * 28.3495 def pretty_print_json(json_dict): print(json.dumps(json_dict, indent=2)) def get_today_date(): return date.today().strftime('%Y-%m-%d') def get_days_ago_date(days_...
import enum import os import sys import traceback from collections import defaultdict from enum import Enum from queue import Queue from typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Tuple, Union from urllib.parse import urlparse import attr import click import hypothesis import yaml from .....
import os import datetime from search_engine import reader from utils.logger import Logger from image_transfer.data_interpreter import dir as DIR class Transfer: __name__ = 'Image Transfer Module' __base_dir__ = None __dest_dir__ = None __ext_file__ = 'f.ext' __extensions__ = None # list with allo...
def soma(a, b): print(f'A = {a} e B = {b}') s = a + b print(f'A soma A + B = {s}') #Programa Principal soma(b=4, a=5) soma(7, 2) # soma(3, 9, 5) -> não pode ser calculado nessa função pois passa 3 parametros e a função só trabalha com 2
from texttable import Texttable from task_module import UtilClass class ChangeClass: """Класс для изменения данных студентов""" def __init__(self, main_obj): self.main_obj = main_obj self.new_obj = None methods_dict = { 1: self.sname_changer, 2: self.sgroup_ch...
import itertools import logging import threading from . import graph from .utils import * from . import automate from . import configuration from . import parameter_server logging.basicConfig(filename="cirrusbundle.log", level=logging.WARNING) class GridSearch(object): # All searches that are currently running. ...
import sys from typing import Tuple, Dict, List, Optional import Levenshtein import argparse from argparse import RawTextHelpFormatter import difflib from itertools import chain import asyncio import curses import logging import os from functools import reduce, partial from dataclasses import dataclass, field import cs...
#!/usr/bin/env python # # # # Autor: Michela Negro, University of Torino. # # On behalf of the Fermi-LAT Collaboration. ...
from __future__ import division from __future__ import unicode_literals from __future__ import print_function from __future__ import absolute_import from builtins import int from builtins import map from builtins import str from future import standard_library standard_library.install_aliases() import logging import su...
import random from pyecharts import options as opts from pyecharts.charts import HeatMap, Page from pyecharts.faker import Collector, Faker C = Collector() @C.funcs def heatmap_base() -> HeatMap: value = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)] c = ( HeatMap() .ad...
# @author Carey Nation # @title Chapter 2, Exercise 1 # @description Print your name and address print("Carey Nation") print("123 Nowhere Lane") print("Nope, GA") print("30303") print("404-555-1212") print("Computer Science")
# ROS IMPORTS from std_msgs.msg import Float32MultiArray # EAGERx IMPORTS from eagerx_reality.engine import RealEngine from eagerx.core.entities import ( Object, EngineNode, SpaceConverter, EngineState, ) from eagerx.core.specs import ObjectSpec from eagerx.core.graph_engine import EngineGraph import e...
#!/usr/bin/env python3 import logging import sys from .test_framework.authproxy import JSONRPCException from .connectivity import getoceand import bisect import collections from .utils import pub_to_dgld_address, PegID, Transfer class OceanWallet(): class HDKeyIDError(Exception): def __init__(self, expect...
import os import pdb from .test_gpt_plugin import TestGPTPlugin class TestToggl(TestGPTPlugin): plugin = "toggl" def test_load_plugin(self): gpt = self.gpt() gpt.gptconfig_settings("plugin", self.plugin) token = os.getenv("GP_TRACKING_TOGGL_TOKEN", "") gpt.gptconfig_s...
from math import ceil import numpy as np import torchvision.transforms.functional as F class TianchiOCRDynamicResize(object): def __init__(self, divisible_by=16): self.divider = divisible_by def __call__(self, img, label): size = img.size short_side = min(size) try_times = in...
from collections import namedtuple DDR5 = namedtuple("DDR5", "tRFW tRC tRFC cREF") DDR4 = namedtuple("DDR4", "tRFW tRC tRFC cREF") ''' Default timings for DDR5 tRFW = 32 ms (refresh window) tRC = 46 ns (minimum ACT-to-ACT gap) tRFC = 410 ns (row refresh cycle time -- timing for when no activity allowed after RE...
from rest_framework import serializers from .models import Listings class ListingsSerializers(serializers.ModelSerializer): class Meta: model = Listings fields = ('title', 'adress', 'city', 'state', 'price', 'house_type', 'sqft', 'open_house', 'sale_type', 'photo_main', 'bathroom...
import calendar def timestamp(dt): return int(calendar.timegm(dt.timetuple()))
# Copyright 2018 Google LLC # # 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, ...
import os from torch.utils.ffi import create_extension sources = ['src/lib_mpl.cpp'] headers = ['src/lib_mpl.h'] with_cuda = False this_file = os.path.dirname(os.path.realpath(__file__)) ffi = create_extension( '_mpl', headers=headers, sources=sources, relative_to=__file__, with_cuda=with_cuda )...
from typing import List from weaverbird.backends.mongo_translator.steps.types import MongoStep from weaverbird.pipeline.steps import ReplaceStep def translate_replace(step: ReplaceStep) -> List[MongoStep]: branches: List[MongoStep] = [ { 'case': {'$eq': [f'${step.search_column}', old_value]},...
# Problem: # Write a program that asks the user to input any positive integer and outputs the successive values of the following calculation: # At each step calculate the next value by taking the current value and, # if it is even, divide it by two, but if it is odd, multiply it by three and add one. # Have the pro...
# -*- coding: UTF-8 -*- # This software was developed by employees of the National Institute of # Standards and Technology (NIST), an agency of the Federal Government. # Pursuant to title 17 United States Code Section 105, works of NIST employees # are not subject to copyright protection in the United States and are #...
from models import PeakModel, DropModel, TroughModel, JumpModel, GeneralModel from models import DropModelState, JumpModelState, GeneralModelState import utils.meta import aiounittest from analytic_unit_manager import AnalyticUnitManager from collections import namedtuple TestData = namedtuple('TestData', ['uid', 'typ...
# Copyright 2017 DataCentred Ltd # # 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...
def run(line, start_panel): num_of_operands = [0, 3, 3, 1, 1, 2, 2, 3, 3, 1] program = [int(x) for x in line]+[0]*10000 i, base = 0, 0 panels, pos, outputs = {(0,0):start_panel}, (0,0), [] directions, dir_idx = [(-1,0), (0,1), (1,0), (0,-1)], 0 while program[i] != 99: modes = [int(x) for...
import datetime as dt import pytest from django.utils.timezone import now from django_scopes import scope from pretalx.schedule.models import TalkSlot @pytest.mark.django_db @pytest.mark.parametrize( "start,end,duration,has_submission", ( (None, None, "sub", True), (0, None, "sub", True), ...
import testaid testinfra_hosts = testaid.hosts() def test_testaid_ruby_role_gpg_install_packages_installed(host, testvars): gpg_packages = testvars['gpg_packages'] for debian_package in gpg_packages: deb = host.package(debian_package) assert deb.is_installed
#--------------------------------------------------------------------- # File Name : Association_apriori.py # Author : Kunal K. # Description : Implementing Stats with Z score, prob, t distribution (basics) # Date: : 5 Nov. 2020 # Version : V1.0 # Ref No : DS_Code_P_K07 #--------------------------...
import json from unittest.mock import patch, MagicMock import httpretty import pytest from buffpy.api import API from buffpy.exceptions import BuffpyRestException MOCKED_RESPONSE = MagicMock(content=json.dumps({"status": "ok"})) def test_api_get_request(): """ Should call Buffer for a given GET request. """ ...
# Leet Code 66 def plus_one(nums) # Leet Code 498 def findDiagonalOrder(mat) # Leet Code 54 def spiralOrder(matrix) # Leet Code 118 def generate_pascals_triangle(num_rows) def dominantIndex(nums): max_val = max(nums) norm_nums = [number / max_val for number in nums] count = len([i for i in norm_nums if i<=...
import requests import random from food import Food from bs4 import BeautifulSoup BASE_URL_SEARCH = 'https://streetkitchen.hu/kereses/?q=' def _get_food_articles(url: str) -> set: food_list: list = [] server_response = requests.get(url) soup = BeautifulSoup(server_response.text, 'html.parser...
import solver import yolo_solver
import math import FWCore.ParameterSet.Config as cms import RecoJets.JetProducers.AnomalousCellParameters_cfi as anom # Common definitions for FFTJet interface modules # Some useful constants fftjet_large_int = pow(2,31) - 1 # Global phi-to-eta bandwidth ratio fftjet_phi_to_eta_bw_ratio = 1.0 # Are we including the...
import cv2 import numpy as np resolution = (0, 0)#x,y capture = cv2.VideoCapture(0) capture.set(cv2.CAP_PROP_CONVERT_RGB, False)#RAW capture resolution = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))) while True: if capture.isOpened(): ret, frame = capture.read() if(re...
import argparse import os import sys import time from scapy.all import send, IP, TCP, Raw BASEPATH = os.path.dirname(os.path.abspath(__file__)) PROJECT_ROOT = os.path.dirname(BASEPATH) sys.path.append(PROJECT_ROOT) import actions.sniffer import engine from plugins.plugin import Plugin class ClientPlugin(Plugin): ...
import logging import paho.mqtt.client as mqtt import json from time import sleep from sys import exit from device.core import Core from api.config import Config from config.secrets import secrets # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, code, r...
text_dict = {} text_2_dict = {} def readFiles(f_file_path, s_file_path): with open(f_file_path, mode='r', encoding="utf-8") as read_file: f_text = read_file.readlines() with open(s_file_path, mode='r',encoding="utf-8") as read_file: s_text = read_file.readlines() return f_text,s_t...
# Copyright 2020 Toyota Research Institute. All rights reserved. """ Basic visualization utilities for depth estimation. """ import torch from matplotlib.cm import get_cmap import numpy as np def prep_tensor_for_vis(x): """Prepare tensor for visualization If only has one channel, concatenate to produce 3 c...
import logging import coloredlogs import sys from trading_bot.agent import Agent from trading_bot.method2 import train_model from trading_bot.utils import ( get_stock_data, format_currency, format_position, show_train_result, switch_k_backend_device ) from data_generator import generate def main(train_stock, w...
# -*- coding: utf-8 -*- """ Created on Fri Jul 17 23:44:40 2020 @author: SERGI """ import pymysql import time class DB: def __init__(self, params): ''' Returns ------- None. ''' print("Connecting to mysql..") time.sleep(1) self.my...
import logging from collections import defaultdict import networkx import pyvex from . import Analysis from .code_location import CodeLocation from ..errors import SimSolverModeError, SimUnsatError, AngrDDGError from ..sim_variable import SimRegisterVariable, SimMemoryVariable, SimTemporaryVariable, SimConstantVariab...
class Solution: def numTilePossibilities(self, tiles: str) -> int:
import numpy as np from PIL import Image from numpy.core.multiarray import ndarray from abc import ABC, abstractmethod class IPreprocessor(ABC): """ An abstract baseclass for a image preprocessing class """ @abstractmethod def prepare_image(self, img_name: str) -> ndarray: pass class Si...
import numpy as np import random import argparse import math # from scipy.stats import pareto, lognorm, levy, weibull_max, weibull_min, burr, loggamma, gamma from itertools import combinations class SS(): def __init__(self, args): self.name = args.name # name of the hypergraph self.t...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.ContractPeople import ContractPeople from alipay.aop.api.domain.ContractAttach import ContractAttach from alipay.aop.api.domain.ContractAttach import ContractAttach from alipay.aop....
#!/usr/bin/python ## TODO: add a dynamic event handler to handle custom triggered events ## eg: on "you died" do function_x() from lib.Logger import * import copy import pygame import random class KeyHandler(): def __init__(self, name=None): self.keydown_assignments = {} self.keyup_assignm...
# Copyright 2021 TerraPower, LLC # # 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 writi...
##################### # Custom Exceptions # ##################### class InstanceNotFound(Exception): """Instance is not found in the dictionary where environments are stored""" pass class EnvironmentMalformed(Exception): """Environment ID is not correct""" pass class EnvironmentNotFound(Exception): ...
import subprocess as sp import time import sys, os import csv import requests # from scraper import * from bs4 import BeautifulSoup # from interruptingcow import timeout from google.cloud import pubsub # from google.cloud import monitoring from sheets_util import * # https://www.howtoforge.com/tutorial/how-to-create-d...
""" Inspired and partially adopted from https://github.com/zhmiao/OpenLongTailRecognition-OLTR/blob/master/data/ClassAwareSampler.py """ import math import random import logging import torch.distributed as dist from torch.utils.data.sampler import Sampler class CycleIter: def __init__(self, data...
from django.conf.urls.defaults import * urlpatterns = patterns('madrona.help.views', url(r'^$', 'help', name="help-main"), )
# Generated by Django 4.0.3 on 2022-03-06 19:08 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
from google.appengine.ext import ndb import datetime import json import pytz import re from consts.district_type import DistrictType from consts.event_type import EventType class Event(ndb.Model): """ Events represent FIRST Robotics Competition events, both official and unofficial. key_name is like '2010...
#!/usr/bin/env python3 from iroha.primitive_pb2 import can_set_my_account_detail from iroha import IrohaCrypto, Iroha import binascii import iroha_config import sys if sys.version_info[0] < 3: raise Exception('Python 3 or a more recent version is required.') def trace(func): """ A decorator for tracing me...
from django.core.management.base import BaseCommand from corehq.util.argparse_types import date_type from dimagi.utils.chunked import chunked from corehq.apps.data_pipeline_audit.management.commands.compare_doc_ids import ( compare_cases, compare_xforms, ) from corehq.apps.hqcase.utils import resave_case from...
""" .. _tut_artifacts_reject: Rejecting bad data (channels and segments) ========================================== """ import numpy as np import mne from mne.datasets import sample data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fna...
# -*- coding: utf-8 -*- # __author__ = 'liqirong' import scrapy import time class GupiaoSpider(scrapy.Spider): name = "gupiao" start_urls = { 'http://stock.10jqka.com.cn', } gp_name = "" def parse(self, response): # print(response.text) a_list = response.xpath(r'//*[@id=...
""" Unit tests for the GA Optimiser on Cartesian spaces. -- kandasamy@cs.cmu.edu """ # pylint: disable=invalid-name # pylint: disable=abstract-class-little-used # Local from . import cp_ga_optimiser from .unittest_cp_random_optimiser import CPOptimiserBaseTestCase from ..utils.base_test_class import BaseTestClass...
""" 数据集加载,并对预处理结果进行序列化处理 """ import sys from fastNLP.core import Const from fastNLP.io import PeopleDailyNERLoader from fastNLP.io import PeopleDailyPipe sys.path.insert(0, './') # 定义搜索路径的优先顺序,序号从0开始,表示最大优先级 import myClue # noqa print('myClue module path :{}'.format(myClue.__file__)) # 输出测试模块文件位置 from myClue.core...
from ._filesdb import *
import requests, logging import pytest, json import os, re, yaml, subprocess from datetime import datetime from settings import TEST_DATA, DEPLOYMENTS from suite.custom_resources_utils import ( create_ap_logconf_from_yaml, create_ap_policy_from_yaml, delete_ap_policy, delete_ap_logconf, ) from kubernete...
__author__ = 'robertk' def read_phrase(phrase_path, thresh=0.33): if phrase_path is None: return None phrase_table = dict() probs = dict() phrase_file = open(phrase_path) phrase_lines = phrase_file.readlines() for line in phrase_lines: data = line.strip().split('\t') da...
from .base import DelayedQuerySet class DelayedIntersectionQuerySet(DelayedQuerySet): def __init__(self, *querysets): # Handle the case when a DelayedIntersectionQuerySet is passed in expanded_querysets = [] for queryset in querysets: if isinstance(queryset, DelayedIntersection...
# Generated by Django 3.2.9 on 2021-11-09 09:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tag', fields=[ ...
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
import jinja2 import markdown from resource_generator.filters import pluralise, curie_org_url # set up paths to where the templates are def register_templates(): multi_loader = jinja2.ChoiceLoader([ jinja2.FileSystemLoader(searchpath="./resource_generator/templates"), jinja2.PrefixLoader({ ...
import os from Crypto.Cipher import PKCS1_OAEP from Crypto.PublicKey import RSA def generate_random_key(bits=256): """ Generate a random encryption key. Sizes is given in bits and must be in increments of 32. """ if bits % 32: raise Exception("Invalid key size ({}). Key sizes must be in incre...
## @ingroup Components-Energy-Networks # Internal_Combustion_Propeller.py # # Created: Sep 2016, E. Botero # Modified: Apr 2018, M. Clarke # Mar 2020, M. Clarke # Apr 2021, M. Clarke # Jul 2021, E. Botero # ---------------------------------------------------------------------- # Impo...
import psutil import time import socket import argparse def RunServer(port_id: int, connection: list): sock = socket.create_server(('localhost', port_id)) rslt = sock.accept() connection.extend(rslt) def ReportStatus(online: {'online': False}): machine_status = {} cpu_count = psutil.cpu_count() ...
"""Unit test package for napari_hub_cli."""
# Definition for a binary tree node. from python.source.tree.tree import TreeNode class Solution: def maxDepth(self, root: TreeNode) -> int: return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) if root is not None else 0
################## PURPOSE ################# # This script is to do PAIR comparisons using the three 3 caller CNVs files # This script takes in the 3 caller CNVs files and put their content in to a nested dictionary. # There are 3 dictionaries within the bigger dictionary , each dictionary is the content of a singular...
import os import requests import mimetypes from IPython import embed from traceback import format_exc from django.shortcuts import render from django.views.generic import TemplateView from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from clouder.settings import N...
#!/bin/env python3 # coding:utf-8 # author bruce from qmath.geometry.c2d.lineequation import * class LineEquationGeneral: """ general form line equation """ A = None B = None C = None def __init__(self, A=None, B=None, C=None): self.A = A self.B = B self.C = C ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2019-10-23 07:29 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cmdb', '0035_netdevice_bmc_address'), ] operations = [ migrations.AddField(...
def mix(s1, s2): s1 = list(s1) s2 = list(s2) toPop = [] for i, item in enumerate(s1): if not (97 <= ord(item) <= 122): toPop.append(i) for i, currentToPop in enumerate(toPop): s1.pop(currentToPop - i) toPop = [] for i, item in enumerate(s2): if not (97 <= ord(item) <= 122): toPop.append(i) for i, c...
from django.shortcuts import render from cantiin.serializers import ProductSerializer from cantiin.views import ( UserViewSet as _UserViewSet, ProductViewSet as _ProductViewSet, OrderViewSet as _OrderViewSet, CommentViewSet as _CommentViewSet) from rest_framework.renderers import ( TemplateHTMLRenderer,JSONRender...
class Stack(list): def peak(self): return self[-1] def push(self, item): self.append(item) def empty(self): return len(self) == 0 def sort_stack(s): r = Stack() while not s.empty(): tmp = s.pop() while not r.empty() and r.peak() > tmp: s.push(r.pop()) r.push(tmp) while not s.empty() an...
#!/usr/bin/env python # Copyright (c) 2015-2016 Freescale Semiconductor, Inc. # Copyright 2016-2017 NXP # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import struct import serial import socket import threading from .crc16 import Crc16 from .client import RequestError try: from rpmsg.sysfs import...
from functions.extractnumday import ExtractNumDaysToLookBack from functions.getsymbols import GetSymbols from functions.scrapewsb import ScrapeWallStreetBetsSubreddit from functions.writeoutput_totsv import WriteOutput_ToTSV def SearchForSymbolsInSubreddit(symbolDict: dict(), numberOfDays) -> dict(): ScrapeWallStr...
from unittest import mock import mantiumapi.ai_engines AIENGINE = { "data": [ { "id": "b2ffecf7-4fee-42e7-b85d-a5e28d939396", "type": "ai_engine", "attributes": { "name": "davinci", "description": "Davinci is the most capable engine and can perform any task the other models ca...
from src.lh.config import LHConfig class TestConfigValues(object): @classmethod def setup_class(cls): cls.conf = LHConfig('config.yml') def test_config_categories(self): assert self.conf.file_only == False assert self.conf.service_probes_location == 'nmap-service-probes' as...
from django.contrib.auth.models import User from test_infrastructure import DevdataTestBase, make_photo_data, make_user_data class TestFKRestriction(DevdataTestBase): def get_original_data(self): return [ # Internal user (included) make_user_data(101, "internal", is_superuser=True)...
from django.core import signing from django.contrib.auth import get_user_model from django.conf import settings as django_settings from django.core.signing import BadSignature from .exceptions import TokenScopeError def get_token(user, action, **kwargs): username = user.get_username() if hasattr(username, "p...
# # eChronos Real-Time Operating System # Copyright (c) 2017, Commonwealth Scientific and Industrial Research # Organisation (CSIRO) ABN 41 687 119 230. # # All rights reserved. CSIRO is willing to grant you a licence to the eChronos # real-time operating system under the terms of the CSIRO_BSD_MIT license. See # the f...
from flask import Flask, request import config import os import random server = Flask(__name__) print("in bot.py") @server.route("/") def webhook(): return "ok", 200 #dvach @server.route("/wakeup") def wakeup(): #print("pinged") return "Never sleeps", 200 import NotSleeping print("in bot.py(1)") ...
import pymysql # 获取连接 def get_connection(): host = 'localhost' port = 3306 db = 'python' user = 'root' password = 'mysql' conn = pymysql.connect(host=host, port=port, db=db, user=user, password=password) return conn pass # 查询单条数据 def fetch_one(): conn...
from rest_framework import serializers from cities.models import City, Continent, Country, District, Region, Subregion class ContinentSerializer(serializers.ModelSerializer): class Meta: model = Continent fields = ['id', 'name', 'code'] class CountrySerializer(serializers.ModelSerial...
#!/usr/bin/python3 from solver import CLISolver from wordle import Game def play_game(): game = Game() game.play(CLISolver(game)) play_again = input("Play again (y/n)? ").strip().lower() if "y" == play_again: play_game() else: print("Bye!") if __name__ == '__main__': play_ga...
import pytest from .. import api_views pytestmark = pytest.mark.django_db class TestApiView: def test(self, caplog, request_factory): response = api_views.home_api_view(request_factory.get("/")) assert response.status_code == 200 assert len(caplog.records) == 1 record = caplog.re...
import tkinter as tk import tkinter.messagebox as mb class App(tk.Tk): def __init__(self): super().__init__() self.create_button(mb.askyesno, "Ask Yes/No", "Returns True or False") self.create_button(mb.askquestion, "Ask a question", "Re...
from django.core.exceptions import ValidationError from django.test import TestCase from .factories import ClientFactory, ProviderFactory, SafeAppFactory class ProviderTestCase(TestCase): def test_str_method_outputs_name_url(self) -> None: provider = ProviderFactory.create() self.assertEqual(str(...