text
stringlengths
8
6.05M
import numpy as np import re from math import log2 q = [np.array([[1, 0]]), np.array([[0, 1]])] def parse_string(value): if (value[0] == '~'): value = value[1:] return (int(value), None) if (re.search(r'[2-9]', value) is None): return (int(value, base=2), len(value)) return (int(va...
def sum_series1(i): if i == 1: return 1 else: return 1/i + sum_series1(i-1) print(sum_series1(5))
from setuptools import find_packages, setup with open("README.md", "r") as fh: long_description = fh.read() setup( name="webapp", version="0.0.1", author="Ben", description="Raspberry-Pi webapp project", long_description=long_description, long_description_content_type="text/markdown", ...
import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression import statsmodels as ssm df = pd.read_csv("data\world-happiness-report-2021.csv") y_feature = ["Ladder score"] * 6 features = ["Logged GDP per capita", "Social support", "Healthy life expectancy",...
def f(x): import math return 10*math.e**(math.log(0.5)/5.27 * x) def radiationExposure(start, stop, step): ''' Computes and returns the amount of radiation exposed to between the start and stop times. Calls the function f (defined for you in the grading script) to obtain the value...
from mlpnn.Import.Data import Data class Samples(object): def __init__(self, file, ratio=1.0, shuffle_data=False): self.ratio = ratio self.data = Data(file, shuffle_data) def input_neurons(self): return self.data.samples_count() - 1 def output_neurons(self): return self.d...
N, M = map( int, input().split()) ans = "-1 -1 -1" for i in range(M//3+1): if (M-i*3)%2 == 0 and M >= i*3: y = (M-i*3)//2 - (N-i) x = (N-i) - y if x >= 0 and y >= 0: ans = str(x) + " " + str(i) + " " + str(y) break print( ans)
# -*- coding: utf-8 -*- from matplotlib.pylab import * from collections import defaultdict data = defaultdict(lambda:[]) for line in open("data.txt").readlines(): if not line.strip(): continue (label, n, time) = line.strip().split(",") data[label].append((n, time)) n = 0 clf() type = ["o-", "*--", "s-", "x-...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' Pentagonal numbers are generated by the formula, Pn=n(3n−1)/2. The first ten pentagonal numbers are: 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal. Find the pair of...
######################################### ## ## JetRecConfig ## ## This file is a prototype module for a jet configuration system compatible ## with RootCore. ## The system is based on a hierarchy of keywords which describe top-level full configuration ## down to individual tool configuration ## An example of keyword h...
import json class QuestionController(): def getallquestions(self): allquestions = ( { 'question': "What is your name?", "answer": "Priscilla Kyei Danso", }, { 'question': "How old are you?", "answer": "Why...
r"""*CLI module for* ``sphobjinv``. ``sphobjinv`` is a toolkit for manipulation and inspection of Sphinx |objects.inv| files. .. note:: This module is NOT part of the public API for ``sphobjinv``. Its entire contents should be considered implementation detail. **Author** Brian Skinn (bskinn@alum.mit.edu...
""" xlwings - Make Excel fly with Python! Homepage and documentation: http://xlwings.org See also: http://zoomeranalytics.com Copyright (C) 2014-2015, Zoomer Analytics LLC. All rights reserved. License: BSD 3-clause (see LICENSE.txt for details) """ import os import sys import re import numbers import itertools impo...
"""Kiran the Discow Bot.""" import asyncio import os import re import subprocess import tempfile import traceback import discord from discord.ext import commands # import sympy # from sympy.parsing import sympy_parser from dotenv import load_dotenv from gtts import gTTS import c4board load_dotenv() with open("bad_...
from .visulization import Visulizer
import json #test variables to store varInt = 16 varReal = 5.0 varString = "Test" varBool = True varList = [1,2,3,4,5] varList2 = [[1,2,3,4,5],[6,7,8,9,0]] varTuple = (1,2,3) varDic = {1:'s',3:'4',2:'a'} varDic2 = {1:5,3:6,2:7} ''' # https://docs.python.org/3/library/pickle.html#comparison-with-json 12.1.1.2. Compari...
import reptile.data from orun.data.datasource import DataSource, Param class ReportConnection: """ Default report db connection """ def datasource_factory(self, **kwargs): """ Create a datasource instance compatible with reptile engine :param kwargs: :return: "...
from django.shortcuts import get_object_or_404, render from django.urls import reverse_lazy, reverse from django.views.generic import CreateView, UpdateView, DeleteView, TemplateView, View from django.http import HttpResponse import json from planner.models import Garden, Bed class GardenView(TemplateView): temp...
from twisted.trial.unittest import TestCase from .. import c_zlib class CZlibTest(TestCase): def testRoundTrip(self): dictionary = 'foobar' compressed = c_zlib.compress('foobar', level=9, dictionary=dictionary) decompressed = c_zlib.decompress(compressed, dictionary=dictionary) sel...
from utils import ( get_guard_periods, lines_to_records, read_input ) def get_sleepiest_guard(guard_periods): return sorted( [guard_id for guard_id in guard_periods.keys()], key=lambda guard_id: sum(guard_periods[guard_id]) )[-1] if __name__ == '__main__': records = lines_to_r...
import requests import json class GetAddress: def __init__(self, postcode: str): postcode = postcode.replace(" ","") info = requests.get("https://api.postcodes.io/postcodes/" + postcode) json_variable = info.json() result = json_variable["result"] self.country = result["co...
"""Cluster Mass Module abstract class to compute cluster mass function. ======================================== The implemented functions use PyCCL library as backend. """ from __future__ import annotations from typing import final, List, Tuple, Optional from abc import abstractmethod import numpy as np import sacc ...
# -*- coding: utf-8 -*- import codecs import os def word_split(words): new_list = [] for word in words: if '-' not in word: new_list.append(word) else: lst= word.split('-') new_list.extend(lst) return new_list def read_file(file_path): f = codecs.open(file_path,'r',"utf-8") lines = f.readlines() ...
import sys import os from Crypto.Hash import SHA256 from Crypto.Signature import pss from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes from Crypto.Cipher import AES from Crypto.Cipher import PKCS1_OAEP from Crypto.Util.Padding import pad from typing import Tuple def sign_buffer(da...
import re print("===================================================================") print("================== SELECCIONE UNA OPCION ==========================") print("===================================================================") print("1: X = 2 + 5 * y") print("2: X = a / a + b * b") print("3: X =...
from django.test import TestCase from backend.user_service.user.infra.adapter.user_create_command_handler \ import UserCreateCommandHandler from backend.common.command.user_create_command \ import UserCreateCommand class UserCreateCommandHandlerTestCase(TestCase): def test_when_message_has_no_email_or_p...
################################################################### # File Name: train.py # Author: Zhongdao Wang # mail: wcd17@mails.tsinghua.edu.cn # Created Time: Thu 06 Sep 2018 10:08:49 PM CST ################################################################### from __future__ import print_function from __future__...
# Generated by Django 3.2 on 2021-05-19 15:25 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('user', '0001_initial'), ] operations = [ migrations.CreateModel( name='User', fields=[ ...
from django.db import models from django.utils.translation import ugettext_lazy as _ from apps.user.models import CustomUser class Experience(models.Model): """ Address Model which holds all the address data for a user """ class Meta: db_table = 'experience' verbose_name = _('experie...
from about_action import AboutAction from edit_preferences_action import EditPreferencesAction from exit_action import ExitAction
################################################################################### # Title : KSE526 project baseline # Author : hs_min # Date : 2020.11.25 ################################################################################### #%% import tensorflow as tf from tensorflow.keras import Model from t...
#!/bin/python import sys import re infile = open(sys.argv[1], "r") program = [] lineNo = 1 for line in infile: line = line.rstrip() lineRE = re.match(r"(acc|jmp|nop) (\+|-)(\d+)", line) if not lineRE: print "SHIT" argument = int(lineRE.group(3)) if lineRE.group(2) == '-': argu...
#encoding:utf-8 import matplotlib.pyplot as plt input_values=[1,2,3,4,5] squares = [1, 4, 9, 16, 25] plt.plot(input_values, squares, linewidth = 5) #设置图标标题,并给坐标轴加上标签 plt.title("Square Numbers", fontsize=24) plt.xlabel("Value", fontsize=14) plt.ylabel("Square of Value", fontsize=14) #设置刻度标记的大小 plt.tick_params(axis='b...
# -*- coding: utf-8 -*- import logging from datetime import datetime from dateutil.relativedelta import relativedelta from operator import itemgetter import time from openerp import SUPERUSER_ID from openerp import pooler, tools from openerp.osv import fields, osv from openerp.tools.translate import _ from openerp.to...
# def dollarize(fcount): # fcount = round(fcount, 2) # sfcount = format(fcount, ',') # if fcount < 0: # sfcount = sfcount.split('-')[1] # return '-' + '$' + sfcount # else: # return '$' + sfcount class MoneyFmt(object): def __init__(self, fcount): self.fcount = flo...
string = input() string2 = '' for i in string: if ((i >= 'a' and i <= 'z') or (i >= 'A' and i <= 'Z')): if (i not in string2): string2 += i print(len(string2))
#import sys #input = sys.stdin.readline def main(): N = int( input()) ans = 0 for i in range(1,N): ans += (N-1)//i print(ans)D. if __name__ == '__main__': main()
from auxilaryFunctions import np from auxilaryFunctions import calIntegralImage from auxilaryFunctions import Grey_img,integralImage,Image,np,io,get_integral_image from classifiers import getLayers import time,math from stages import * def computerFeatureFunc(box,featureChosen,integralImg): #scaling features b...
# modified config_10gbe_core function from katcp_wrapper.py from the corr library to include a subnet hack def config_10gbe_core(self,device_name,mac,ip,port,arp_table,gateway=1): """Hard-codes a 10GbE core with the provided params. It does a blindwrite, so there is no verifcation that configuration was su...
NUM_OF_ROWS = 6 NUM_OF_COLS = 7 DEPTH = 4 BLUE = (61, 164, 171) YELLOW = (246, 205, 97) RED = (254, 138, 113) BLACK = (74, 78, 77) SQUARE = 100 CIRCLE = 45
from sklearn.cluster import KMeans import numpy as np import matplotlib.pyplot as plt def cluster_images(container): positive = np.asarray([element[1] for element in container]) negative = np.asarray([element[2] for element in container]) ratings = np.asarray([element[3] for element in container]) ...
# from collector.Collector import Collector # c = Collector() # data = c.collect() # print("\n\n\nFound data...\n\n\n") # for i in data: # print(i.content.text) # print(i.label) # print() import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_...
from sklearn.datasets import load_breast_cancer from sklearn.cluster import KMeans from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from sklearn.preprocessing import scale import pandas as pd bc = load_breast_cancer() print(bc) x = scale(bc.data) print(x) y = b...
from django.contrib import admin from django.urls import path,include from home import views urlpatterns = [ path('',views.index,name="home"), path("notes/",views.about, name="notes"), path('delete/<int:id>',views.delete,name= "delete"), path('update/<int:id>',views.update,name = "update"), path('e...
# !/uer/bin/env python3 # coding=utf-8 import smtplib import logging import configparser from email.mime.text import MIMEText from email.utils import formataddr LOGGER = logging.getLogger(__name__) conf = configparser.ConfigParser() conf.read("conf.ini") def send_email(msg): mail_host = conf.get("EMAIL", "mail_...
from datetime import datetime import pytz as pytz from marshmallow_dataclass import dataclass from src.core.datastructures.base import BaseDataStruct @dataclass class CoinPrice(BaseDataStruct): time: datetime = pytz.utc.localize(datetime.utcnow()) currency: str = "" quote: float = 0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. from django.http import HttpResponse,JsonResponse import os from django.conf import settings from models import * from django.core.paginator import * import json from django.views.decorators.c...
from flask import Flask, render_template, url_for, request from util import json_response import util import data_handler app = Flask(__name__) # Joel: joel123 # Adam: adam123 # Alex: alex123 # Gergő: gergo123 @app.route("/") def index(): return render_template('index.html') @app.route("/get-boards") @json_...
from harkpython import harkbasenode class HarkDebug(harkbasenode.HarkBaseNode): def __init__(self): print("-!!!!HarkDebug!!!!-" * 3) self.outputNames = ("OUTPUT",) self.outputTypes = ("prim_float",) self.c = 0 def calculate(self): self.outputValues["OUTPUT"] = 1 ...
#__author: "Jing Xu" #date: 2018/1/23 import json dict1 = {'name':'alex','age':'18'} data = json.dumps( dict1 ) with open('JSON_text','w') as f: f.write(data) with open('JSON_text','r') as f1: data1 = json.loads( f1.read() ) print(data1['name']) def foo(): print("ok") # data2 = json.dumps( foo ) # Object of...
import os import pandas as pd class BlockData(): def __init__(self, download_folder, file_name, db): self.file = os.path.join(download_folder, file_name) self.db = db pass def parse_data(self): data = pd.read_csv(self.file) if not data["Date"][0] == "NO RECORDS": save_data = data.to_dic...
class Hero: def __init__(self, name, title, health, mana, mana_regen, weapon = None, spell = None): self.name = name self.title = title self.health = health self.mana_regen = mana_regen self.max_health = health self.max_mana = mana def known_as(self): re...
from math import factorial arr = [] n = int(input().strip()) for i in range(n): arr.append(int(input().strip())) ans = 1 + n + (factorial(n) // (factorial(2)*factorial(n-2))) for base_i in range(n): for delta_i in range(base_i+1, n): D = arr[delta_i] - arr[base_i] search_val = arr[delta_i] + ...
# -*- coding: utf-8 -*- import hashlib import os # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import pymysql.cursors import redis import requests from pymongo import MongoClient from .items imp...
import maya.cmds as cmds #create joints (body chain) cmds.joint(p=(-0.063,102.695,0),n=('root_jnt')) cmds.joint(p=(-0.188,111.843,0),n=('stomach_jnt')) cmds.joint(p=(0.188,129.763,0),n=('chest_jnt')) cmds.joint(p=(-0.063,143.799,0),n=('neck_jnt')) cmds.joint(p=(0.188,161.969,0),n=('head_jnt')) #deselect c...
import boto3 import time # Change these values, make them constant variables? # EvaluationId # MLModelId # EvaluationDataSourceId # s3 = boto3.resource('s3') # s3.create_bucket(Bucket='dee-bucket-test', CreateBucketConfiguration={'LocationConstraint': 'us-west-1'}) # # bucket name has to be unique and all lowercase. ...
from _typeshed import SupportsItemAccess from datetime import datetime, timedelta from typing import Any from wtforms.csrf.core import CSRF, CSRFTokenField from wtforms.form import BaseForm from wtforms.meta import DefaultMeta class SessionCSRF(CSRF): TIME_FORMAT: str form_meta: DefaultMeta def setup_form...
import sys import json import boto3 from random import randint from pprint import pprint import requests import discord from discord.ext import commands from discord_commands import get_message, get_thumbnail_url, get_attachment_link from anagrams import recursiveAnagrams # OLD # @client.event # async...
import time from threading import Thread def myfun(): time.sleep(1) a = 1 + 1 print(a) t1 = time.time() for i in range(5): myfun() t2 = time.time() print(t2-t1) ths = [] for _ in range(5): th = Thread(target=myfun) th.start() ths.append(th) for th in ths: th.join() t3 = time.time() print(t3-t2)
# Generated by Django 3.2 on 2021-04-14 11:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0003_alter_role_options'), ] operations = [ migrations.AlterModelOptions( name='profile', options={'ordering': ['user']...
from selenium import webdriver import unittest class GetCurrentPageUrlByChrome(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() def test_getCurrenPageUrl(self): url = "https://www.baidu.com/" self.driver.get(url) self.driver.maximize_window() #获取当前...
from freqtrade.strategy.interface import IStrategy from pandas import DataFrame #from technical.indicators import accumulation_distribution from technical.util import resample_to_interval, resampled_merge import talib.abstract as ta import freqtrade.vendor.qtpylib.indicators as qtpylib import numpy from technical.indic...
import pytest from freezegun import freeze_time from onegov.election_day.layouts import ElectionLayout from tests.onegov.election_day.common import login from tests.onegov.election_day.common import MAJORZ_HEADER from tests.onegov.election_day.common import upload_majorz_election from tests.onegov.election_day.common ...
import torch from torchvision import datasets, transforms def read_data(data_path="", batch_size=1): train_loader = torch.utils.data.DataLoader( datasets.MNIST(data_path, train=True, download=True, transform=transforms.Compose([ transforms.ToTensor...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('pmtool', '0016_auto_20150212_1046'), ] operations = [ migrations.RemoveField( model_name='activity', ...
# login/views.py from django.http import HttpResponseRedirect from django.shortcuts import render, redirect from mainWindow.models import House from . import models from .forms import UserForm from .forms import RegisterForm from .forms import ChangeForm from .models import User # 作者:王皓平 创建时间:2019.8.27 最后更新时间:2019.9....
import json import requests def get_weather_data(): url="https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22" response = requests.get(url) json_data = response.json() return json_data if __name__ == '__main__': weather_data = get_weather_data() ...
import os, re def main(): os.chdir(os.path.dirname(os.path.abspath(__file__))) input = open("day20_input.txt").read().splitlines() print(solve(input)) class Particle: def __init__(self, position, velocity, acceleration): self.position = position self.velocity = velocity sel...
from django.apps import AppConfig class SocialsAppConfig(AppConfig): name = "socials" def ready(self): from socials.signals.post_save import post_save_keyword
import requests import random import time import json import pandas as pd download_path = 'http://static.cninfo.com.cn/' saving_path = 'D:/中信证券暑期/2020年报' User_Agent = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6...
from django import template register = template.Library() @register.filter def get_key_value(some_dict, key): """ Provides a filter to be used in Django Jinja2 templates. Filter allows lookup of values within a dictionary {} via a key. :param some_dict: Dictionary object :param key: key value to ...
from adapters.adapter_with_battery import AdapterWithBattery from devices.sensor.temperature import TemperatureSensor class TemperatureSensorAdapter(AdapterWithBattery): def __init__(self, devices): super().__init__(devices) self.devices.append(TemperatureSensor(devices, 'temp', 'temperature', 'te...
from django.shortcuts import render,HttpResponseRedirect from faculty.models import Leave from django.http import JsonResponse from django.contrib.auth.decorators import login_required from faculty.models import LoadShift,Leave, OD from django.core.mail import EmailMultiAlternatives from django.template.loader import r...
# Standard imports import ROOT import pickle import array # TopEFT from TopEFT.Tools.WeightInfo import WeightInfo # RootTools from RootTools.core.standard import * # rw_cpQM -10 ... 30 # rw_cpt -20 ... 20 sample = Sample.fromFiles("ttZ_current_scan", ["/afs/hephy.at/data/rschoefbeck02/TopEFT/skims/gen/v2/fwlite_ttZ_l...
from sqlalchemy import Column, Integer, String, DateTime, Sequence from sqlalchemy.ext.declarative import declarative_base __author__ = 'cloudbeer' Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) email = Column(String, nu...
import unittest from Bio.Seq import Seq from Bio.Alphabet import generic_dna from codon_tools.lookup_tables import opt_codons_E_coli, reverse_genetic_code class TestLookupTables(unittest.TestCase): def test_reverse_genetic_code(self): tested_codons = {} for aa, codons in reverse_genetic_code.items...
print('Welcome to the tip Calculator!') total_bill = float(input('What was the total bill? $')) tip_percentage = int(input('What persentage of tip you would like to give? 10, 12, or 15? ')) people_number = int(input('How many people to splitt the bill? ')) personal_bill = (total_bill + (total_bill * (tip_percentage/1...
from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from PIL import Image # Create your models here. class AccountManager(BaseUserManager): def create_user(self, email, username, password=None, is_manager=False): if not email: r...
from .processor import Processor, FilteredProcessor from .color_mean import ColorMeanProcessor from .chrom import ChromProcessor
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2019 Gert Kanter. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must r...
import discord from discord.ext import commands import urllib.request import os bot = commands.Bot(command_prefix =".", description = "yolooooooooooooooooooooooooooooo") @bot.event async def on_ready(): print("prêt!") @bot.command() async def coucou(ctx): await ctx.send("yo c est le test") @bot.comman...
import os import copy import sys import run import evaluator from config import KNOWLEDGE_NET_DIR which = sys.argv[1] if len(sys.argv) > 1 else "dev" if which == "dev": filename = "train.json" fold = 4 elif which == "test": filename = "test-no-facts.json" fold = 5 else: sys.exit('Invalid evaluation set') ...
from rich import print def banner(): with open('design/banner.txt') as file: content = file.read() print(f"[cyan]{content}[/]")
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class HrPayslip(models.Model): _inherit = 'hr.payslip' expense_sheet_ids = fields.One2many( 'hr.expense.sheet', 'payslip_id', string='Expenses', help="Exp...
# coding: utf-8 def sieve(n): """筛法得到n以内的素数""" primes = [True] * (n + 1) primes[0] = primes[1] = False i = 2 while i * 2 <= n: if primes[i]: primes[i * 2:n + 1:i] = [False] * (int((n - i * 2) / i) + 1) # 等同于如下句子,但是更快 # for j in range(i * 2, n + 1, i): ...
from django.core.management.base import BaseCommand from django.conf import settings import os # import pwd, grp class Command(BaseCommand): help = "backs up the current sqllite db on an s3 bucket" def handle(self, *args, **options): # get database db_file = os.path.abspath(settings.DATABASES['...
print("hi i am abhinav")
""" Download a file from iamresponding.com. Then, annotate the model with new data. Finally, email the generated report. """ import json import argparse from apiclient.discovery import build from httplib2 import Http from cvac.fetch_data import download from cvac.misc_io import get_newest_file, wait_for_file_to_finish ...
# coding: utf-8 """ LoRa App Server REST API For more information about the usage of the LoRa App Server (REST) API, see [https://docs.loraserver.io/lora-app-server/api/](https://docs.loraserver.io/lora-app-server/api/). # noqa: E501 OpenAPI spec version: 1.0.0 Generated by: https://github.co...
import logging from django.conf import settings from share import exceptions from share.models import RegulatorLog from share.util.extensions import Extensions logger = logging.getLogger(__name__) class RegulatorConfigError(exceptions.ShareException): pass class InfiniteRegulationError(exceptions.ShareExcep...
import os questions = ["Whether or not someone's action showed love for his or her country", "Whether or not someone showed a lack of respect for authority", "Whether or not someone violated standards of purity and decency", "Whether or not someone was good at math", "Whether or not someone cared for someone weak or v...
import os import errno def file_picker(): file_path = raw_input("Please enter the file to check: ") file_path = str(file_path) print("Attempting to open file: "+file_path) try: file = open(file_path,"r") #open file for 'r' READing except IOError as e: if e.errno == errno.ENOENT: return "unusable input" r...
#-*-coding: utf-8 -*- print("반복문 디버그") task=0 for i in range(1,101): print("반복문 실행") task += 1 print("%d번째 업무 실행"%task) #반복문에서 변수값이 루프를 돌면서 잘못된 값으로 변경되는 것을 찾을시 #alt+f9으로 디버깅하면 루프 단위로 디버깅이 가능하다. print("해당 업무 종료\n") if task ==10: task -= 1 print("반복문 종료")
from pathfinder.algorithms import ( a_star_search, breadth_first_search, dijkstra_search, reconstruct_path, ) from pathfinder.grids import SquareGrid, WeightedGrid from pathfinder.views import ascii_drawer grid = SquareGrid(30, 15) grid.walls = [] grid.walls.extend((x, y) for x in range(3, 5) for y in ...
a,b=input().split() c=int(a)^int(b) d=c^int(b) e=c^d print(e,d)
with open('matrix.txt', 'r') as f: matrix = [map(int, line.strip('\n').split(',')) for line in f] dp = [[None for i in range(len(matrix[0]))] for j in range(len(matrix))] for j in range(len(matrix[0])): dp[0][j] = sum(matrix[0][:j+1]) for i in range(1, len(matrix)): dp[i][0] = sum([matrix[k][0] for k in ...
# -*- coding: utf-8 -*- from rest_framework import serializers from api.models import Employee from rest_framework.validators import UniqueValidator class EmployeeSerializer(serializers.ModelSerializer): """Serializer to map the Model instance into JSON format.""" name = serializers.CharField(min_length=3, m...
""" This file download the latest data for Myanmar """ import pandas as pd from autumn.settings import INPUT_DATA_PATH from pathlib import Path INPUT_DATA_PATH = Path(INPUT_DATA_PATH) COVID_MMR_TESTING_CSV = INPUT_DATA_PATH / "covid_mmr" / "cases.csv" URL = "https://docs.google.com/spreadsheets/d/1VeUof9_-s0bsndo8t...
# -*- coding:utf-8 -*- import unittest import mock class UsingMockDatetimeTest(unittest.TestCase): def _callFUT(self): import mydatetime return mydatetime.now() def test(self): with mock.patch("datetime.datetime") as M: M.now.return_value = 10 self.assertEqual(...
import math import numpy as np class OffloadSVM: def __init__(self, model, scaler): self.scaler = scaler self.class0 = model.__dict__['classes_'][0] self.class1 = model.__dict__['classes_'][1] if model.__repr__().split('(')[0] == 'SVC' and model.__dict__['kernel'] != 'linear': ...