text
stringlengths
8
6.05M
#While Loop counter program #THIRD PROGRAM counter = 0 x = input ("How high do you want to count up to? ") while counter <= x: print counter counter = counter + 1 raw_input("\n\nPress the enter key to make 2 number sets count down:") #Nested Loops example a = 4 while a > 0: a = a-1 ...
import sys def debug(*args): if False: print(*args) instruction_pointer = 0 # short: ip def jump(address): global instruction_pointer instruction_pointer = address def add(program, ip): left_value = resolve_param(program, ip, 1) right_value = resolve_param(program, ip, 2) out_address...
class Settings(): def __init__(self,width=1000,height=800,color=(230,230,230)): self.screenWidth = width self.screenHeight = height self.bgColor = color #self.shipSpeedFactor = 2.5 #飞船速度 self.shipLimit = 3 # 设置子弹 #self.bulletSpeedFactor = 5 self.b...
from loguru import logger from tacticalrmm.celery import app from django.conf import settings import pytz from django.utils import timezone as djangotime from .models import AutomatedTask from logs.models import PendingAction logger.configure(**settings.LOG_CONFIG) DAYS_OF_WEEK = { 0: "Monday", 1: "Tuesday",...
from werkzeug import abort from flask import Blueprint from flask import render_template, url_for, send_from_directory import my_app.movie.model as bd import my_app as app import json from random import shuffle movie_blueprint = Blueprint('movie',__name__) categories = sorted(bd.get_all_categories()) @mo...
#this is a python sample code x = 1 y = 2
''' Purpose: The aim of this simulation is to analyze the probabilities of different combinations in a random draw for big 2. Author: Kevin Ta Date Created: 2018 December 29th ''' ########################################### # Libraries #########################################...
import copy class Cloneable: def clone(self, **overrides): klone = copy.copy(self) for k, v in overrides.items(): if not hasattr(self, k): raise AttributeError("%r has no attribute %r" % (self, k)) setattr(klone, k, v) return klone
import re import requests from collections import OrderedDict from typing import List, Dict, Optional, cast from .game_version import GameVersion class Game: BUILDS_URL = '' def __init__(self) -> None: self.versions = self._versions_from_json( requests.get(self.BUILDS_URL).json()) @p...
# decides whether person is eligible to be donor # constants MIN_AGE = 18 MIN_WEIGHT = 45 # ask user for age and weight age = int(input("Enter your age: ")) weight = int(input("Enter your weight in kg: ")) # check if eligible to be donor # both age and weight must OK to be eligible if age >= MIN_AGE and weight >= ...
from bfimpl.bfunc import generateId PATTERN = """//Start:Declarations Mat cv_thresh_%thresh%_%ID%(%ARGS%); //Stop:Declarations //Start:Definitions Mat cv_thresh_%thresh%_%ID%(%ARGS%) { Mat result; threshold(arg1, result, %thresh%, 255, THRESH_BINARY); return result; } //Stop:Definitions """ def generate...
import pygame import sys from time import sleep from game_stats import Gamestats from Settings import Settings from ship import ship from bullet import Bullet from button import Button from alien import Alien from score_board import scoreboard class AlienInvasion: # Display settings as adding ali...
#!/usr/bin/python # -*- coding: utf-8 -*- import fileinput import sys class SeatPair: SEAT_LEFT = 1 SEAT_RIGHT = 2 def __init__(self): self.clear_seats() def clear_seats(self): self._current_seats = [SeatPair.SEAT_LEFT, SeatPair.SEAT_RIGHT] self._is_both_empty = True de...
from timeit import default_timer as timer class CookedFilesHandler(object): """ Takes care about all trained and prepared in advance (aka the models and the songs!) """ def __init__(self, settings, autoload=True): self.settings = settings if autoload: self.prepare_songs_mo...
class Vehicle: def __init__(self,regno,color): self.color = color self.regno = regno class Car(Vehicle): def __init__(self,regno,color): Vehicle.__init__(self,regno,color) def getType(self): return "Car"
"""Arquivo principal que será interpretado pelo interpretador.""" def main(): """Função principal que será rodada quando o script for passado para o interpretador.""" # COLOQUE SEU CÓDIGO AQUI a = float(input('Digite o primeiro número:')) b = float(input('digite o segundo número:')) m = max(a,b) ...
import matplotlib.pyplot as plt x=[1,2,3,4,5,6,7,8,9,10,11,12,13,14] y=[8.17*(10**-5),4.88*(10**-5),0.0001,0.0005,0.0009,0.003,0.0108,0.247,0.0838,0.264,0.858,2.95,9.77,30.82] plt.plot(x,y) plt.xlabel('Taille de la séquence observée ') plt.ylabel('Secondes') plt.title('Complexité du code Naif') plt.show()
from rest_framework import serializers from goods.models import SKU from users.models import User,Address from django_redis import get_redis_connection import re from rest_framework_jwt.settings import api_settings from celery_tasks.mail.tasks import send_verify_email """ 用户名,手机号,密码,确认密码,短信验证码,是否同意协议 """ class Reg...
NT = 512 deltaT = 128e-15 lambdaZero = 800e-9
from tkinter import * from tkinter import messagebox import math ####GUI###window###setup window=Tk() window.title("Rishabh_calc") window.maxsize(width=357,height=300) window.minsize(width=290,height=300) window.geometry('290x300') window.configure(bg='powderblue') window.iconbitmap('Blackvariant-Shadow135-Sy...
from django.shortcuts import render from django.http import HttpResponse from .models import Human from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy def index(request): return render(request, 'practice.html') def detail(request): if request.method =...
import os import io from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools store = file.Storage('_token.json') creds = store.get() service = build('drive', 'v3', http=creds.authorize(Http())) file_id = os.environ.get('GOOGLEDRIVE_FILEID') request = service.f...
import lcm import os import time import threading import collections import bisect class History: def __init__(self, ts, values): self.capacity = ts.maxlen self.ts = ts self.values = values @staticmethod def with_capacity(capacity): return History(collections.deque(maxl...
# -*- coding: utf-8 -*- """ Created on Mon Aug 21 10:27:45 2017 无线网转固资源相关操作 @author: lenovo """ '''==============================================================''' from property.jntele_import_property import LteImport from property.jntele_web_resource import LteWebResource from property.jntele_print_property impor...
import socket ##MISSING CODE #Code to create client socket #Code to connected client socket to server socket print("Welcome to Battleship! Try to guess where the ship is!\n") while True: ##MISSING CODE #Code to store data received into a variable named 'datareceived' datareceived = print(datareceive...
import random # 解法二 def more_than_half_num(li): num = li[0] num_count = 1 for i in li[1:]: if num_count == 0: num = i num_count = 1 else: if i == num: num_count += 1 else: num_count -= 1 return num if __n...
import unittest import json from Message import Message # assertEquals(a, b, msg=None) a == b # assertNotEqual(a, b, msg=None) a != b # assertTrue(x) bool(x) is True # assertFalse(x) bool(x) is False # assertIs(a, b) a is b # assertIsNot(a, b) a is not b # assertIsNone(x) x is None # assertIsNotNone(x) x is not None #...
from flask import render_template import re import json from .. import db from ..work import views from flask import current_app as app from ..models import Work, Chapter, Tag, User, TagType, Bookmark, BookmarkLink from .search_wrapper import BookmarkSearch def get_work_from_bookmark(data): work = Work.query.filter_b...
# Fig. 22.3: List.py # Classes List and Node definition class Node: "Single node in a data structure" def __init__( self, data ): "Node constructor" self.data = data self.nextNode = None def getData( self ): "Get node data" return self.data def setData( self, data ): "Set node data" ...
import pandas as pd df1 = pd.read_csv('amazon.csv', usecols=('Date', 'Order','Line item', 'Total units sold', 'Total sales USD' )) df2 = pd.read_csv('google.csv', header=2, usecols=('Day', 'Campaign', 'Ad group', 'Impressions', 'Clicks', 'Avg. CPC', 'Cost')) print(df1) #print(df2) def amazon(): new = df1.loc[df1....
from googletrans import Translator class GoogleTranslator(): def __init__(self, source_language, destination_language): self.source_language = source_language self.destination_language = destination_language def translate(self, sentence): translator = Translator() return tran...
from collections import namedtuple Info = namedtuple('Info', 'left, up, max_size') # O(n*m) solution class Solution(object): def maximalSquare(self, matrix): if len(matrix) == 0 or len(matrix[0]) == 0: return 0 nrows = len(matrix) ncols = len(matrix[0]) data_matrix = [[...
from django.apps import AppConfig class GluttonyConfig(AppConfig): name = 'gluttony' verbose_name = 'Блюда и аллергены'
#coding=utf-8 import MySQLdb import os from bs4 import BeautifulSoup import time class html_guangdong(object): def __init__(self): self.update_time = time.strftime("%Y-%m-%d") self.field = [{'nsrsbh': u'纳税人识别号,税务登记号,NSRSBH'}, {'nsrmc': u'企业名称,纳税人名称,企业或单位名称,NSRMC'}, {'fddbr': ...
# Project Euler Problem 48 # What are the last 10 digits of the series 1^1+2^2+...+1000^1000 sum=0 for i in range(1,1000): a = pow(i,i) sum+= a B = str(sum) for j in range(len(B)-10,len(B)): print(B[j]) #Correct!
""" foxtail/clinics/models.py """ from datetime import datetime from django.contrib.auth import get_user_model from django.db import models from model_utils.models import TimeStampedModel from guardian.shortcuts import get_objects_for_group from foxtail.organizations.models import Organization from foxtail.users.mode...
import sys import string if len(sys.argv) != 3: print("ERROR") quit() try: nb = int(sys.argv[1]) print("ERROR") quit() except ValueError: arg_str = sys.argv[1] try: nb = int(sys.argv[2]) except ValueError: print("ERROR") quit() return_lst = [] word_lst = arg_str.split() for word in word_lst: word = word.tran...
data = { 'key_1':1, 'key_2':2, 'key_3':[ { 'key_4': [4,5], 'key_5': [6,7] }, { 'key_4': [8,9], 'key_5': [10,11] } ], 'key_6':12 } key = input() def find_key(data,key): if key in data: print(data[key]) return ...
import argparse import numpy as np import os, sys import torch import torch.nn as nn from torch.autograd import Variable from torchvision import datasets, transforms from compute_flops import print_model_param_nums, print_model_param_flops import models from models import * #from models.preresnet_imagenet import Basi...
#!encoding=utf-8 import os import shutil train_filenames = os.listdir('train') train_cat = filter(lambda x:x[:3] == 'cat', train_filenames) train_dog = filter(lambda x:x[:3] == 'dog', train_filenames) # train_cat = [x for x in train_filenames if x[0:3]=='cat'] # train_dog = [x for x in train_filenames if lambda x:x[...
# Copyright 2016 James Sodini # # 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,...
# -*- coding: utf-8 -*- import nysol._nysolshell_core as n_core from nysol.mcmd.nysollib.core import NysolMOD_CORE from nysol.mcmd.nysollib import nysolutil as nutil class Nysol_Writedict(NysolMOD_CORE): _kwd ,_inkwd,_outkwd = n_core.getparalist("writelist",3) _kwd[0].append("dtype") _kwd[1].append("dict") def ...
import random import argparse import os parser = argparse.ArgumentParser(description='Parser for all the training options') parser.add_argument('--train_ratio', type=float, default=0.9) parser.add_argument('--csv_source', type=str, default='./data/image_scene_training/training-list-0511.csv') parser.add_argument('--ds...
import os import re from io import BytesIO import transaction from datetime import datetime from freezegun import freeze_time from openpyxl import load_workbook from onegov.core.csv import convert_list_of_dicts_to_xlsx from onegov.core.utils import Bunch from onegov.newsletter import RecipientCollection, NewsletterCo...
# 整理到目前为止学到的东西 # 1.打印格式字符类型,%d %r %s 等 # 2.变量的定义 使用=号 # 3.读取文件 read readline close write 等操作 # 4.函数定义 def return 返回结果 # 5.解构 通过=号 来解构参数 # 6.导入包 import # 7.输入方法 raw_input # 8.单行注释 多行注释 就是每行前都用#注释 # 9.格式化输出方式 %r 主要用于调试,输出原格式 %s主要用在正式代码中,为希望用户看到的结果
#!/usr/bin/env python import glob import sgf try: from StringIO import StringIO # pragma: no cover except ImportError: # pragma: no cover from io import StringIO # pragma: no cover for filename in glob.glob("examples/*.sgf"): with open(filename) as f: sgf.parse(f.read()) example = "(;FF[4]G...
# My_Picture Predict import numpy as np import matplotlib.pyplot as plt import cv2 from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.models import load_model model = load_model('../data/h5/k67_img.h5') pred_datagen = ImageDataGenerator(rescale=1./255) pred_data = pred_datagen...
# -*- coding: utf-8 -*- from settings import FIELD_LIST # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class FangPipeline(object): def __init__(self): self.city_files = {} def proce...
import yaml with open('config.yaml') as f: cfg = yaml.safe_load(f)
# -*- coding: utf-8 -*- # Подсчитать статистику по буквам в романе Война и Мир. # Входные параметры: файл для сканирования # Статистику считать только для букв алфавита (см функцию .isalpha() для строк) # # Вывести на консоль упорядоченную статистику в виде # +---------+----------+ # | буква | частота | # +--------...
class Cluster: """ Cluster instance. Params: - nodes: nodes (i.e. sites) that belong to cluster """ def __init__(self, nodes): self.nodes = nodes def size(self): """ Returns cluster size, i.e. number of nodes in cluster """ return len(self.node...
from django.shortcuts import render from django.http import HttpResponse def results(request): if request.method == "POST": print("wewewewewewewe") return render(request, 'results.html', {})
# Generated by Django 3.1 on 2020-11-20 22:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Comprador', fields=[ ...
from Tree import Tree def print_tree_by_level(item): if item.root is None: return queue = [item.root] # 记录下一层需要打印的数目 next_level = 0 # 当前还需要打印的数目 to_be_print = 1 while queue: cur = queue.pop(0) to_be_print -= 1 print(cur.item, end=' ') if cur.lchild i...
# Import the Secret Manager client library. from google.cloud import secretmanager def get_secret(secret_id='client_secret'): """ To enable iam role access (for service accounts) to the secret, run the following: gcloud beta secrets add-iam-policy-binding client_secret --role roles/secretmanager.secre...
import base64 import binascii from OpenSSL import crypto class PKCS12(object): def __init__(self, file, pwd): """ :param file: bytes :param pwd: str """ self.p12 = crypto.load_pkcs12(file, pwd) def get_privatekey(self): """ 获取私钥 :return: str ...
import numpy as np import cv2 import argparse def get_args(): parser = argparse.ArgumentParser(description='Process image using YOLO.') parser.add_argument('-i', dest='image', required=True, help='The image to be processed') parser.add_argument('-cl', dest='classes', required=True, help='The classificatio...
from test_runner import * from random import randint import sys class_name = 'Fibonacci' def all_tests(c): base_test(c) correctness_test(c) recursion_depth_test(c) single_timeout_test(c) multi_timeout_test(c) @test() def base_test(c): f = c() check = f.get_nth_fibonacci(1) if check ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import os from pwn import * context(arch="amd64", os="linux") if not args["REMOTE"]: binary = ELF("./heap_heaven_2-x86_64-2.28-4") # https://github.com/integeruser/bowkin libc = ELF("libs/x86_64/2.28/4/libc-2.28.so") argv = [binary.path] envp = {"PWD":...
from flask import Flask,render_template, request import sqlite3 app=Flask(__name__) db=sqlite3.connect('airline.db') @app.route('/') def index(): db=sqlite3.connect('airline.db') c=db.cursor() c.execute('''SELECT id,origin,destination FROM flights''') flights=c.fetchall() return re...
from spotify.commands.albumart import AlbumArt from spotify.commands.work import DoWork from spotify.commands.flash import PingFlash2 __all__ = ['AlbumArt', 'DoWork', 'PingFlash2']
# Method for handling the registration of conversion modules from __future__ import print_function import os import json import tempfile from general_tools.file_utils import write_file from aws_tools.dynamodb_handler import DynamoDBHandler from aws_tools.s3_handler import S3Handler VERSION = 3 # gets the existing...
#!/usr/bin/env python from typing import NamedTuple from hummingbot.strategy.market_trading_pair_tuple import MarketTradingPairTuple class ArbitrageMarketPair(NamedTuple): """ Specifies a pair of markets for arbitrage """ first: MarketTradingPairTuple second: MarketTradingPairTuple
class RunEnvironment(object): """ - PATH: pointing to the bin/ directories of the requires - LD_LIBRARY_PATH: requires lib_paths for Linux - DYLD_LIBRARY_PATH: requires lib_paths for OSx """ def __init__(self, conanfile): """ :param conanfile: ConanFile instance """ ...
import pickle import os from tqdm import tqdm import copy import gc import sys sys.path.append('../') from Config import config from Config import langconv from Config import tool from Preprocessing.WordDict import * from Preprocessing.Tokenizer import * class Preprocessor(): def __init__(self)...
#! /usr/bin/env python import numpy as np PRINT_INTERVAL = 10 class SGDWithMomentum: def __init__(self, lr=0.01, momentum=0.0, decay=0.0, nesterov=False, num_epochs=100, batchsize=64, l2_reg=1e-3): self.lr = lr self.momentum = momentum self.decay = decay self.nesterov = nesterov self.num_epochs = num_epoch...
from django import template register = template.Library() @register.filter def name(querydict): name = querydict.get("name") return "" if name is None else name @register.filter def count(querydict): count = querydict.get("count") return "" if count is None else count @register.filter def buy_date(q...
from ED6ScenarioHelper import * def main(): # 玛诺利亚间道 CreateScenaFile( FileName = 'R2111 ._SN', MapName = 'Ruan', Location = 'R2111.x', MapIndex = 100, MapDefaultBGM = "ed60084", Flags = 0, ...
from django.shortcuts import render from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .models import News, ImageNews, FavouriteNews, LawType, Law, Publication from .serializers import NewsListSerializer, NewsItemSerializer, LawTypeSerializer, LawsByTypeSerializer,...
from ED6ScenarioHelper import * def main(): # 社团大楼 学生会室 CreateScenaFile( FileName = 'T2521 ._SN', MapName = 'Ruan', Location = 'T2521.x', MapIndex = 1, MapDefaultBGM = "ed60014", Flags = 0, ...
from telnet import TelnetTool RouterHost = { 'RTB': '192.168.3.1', 'RTC': '192.168.3.2' } # # 访问控制-死命令:无返回 # def setACLAction(): # commandList = [ # 'config terminal', # 'access-list 1 deny 192.168.254.0', # 'access-list 1 permit any', # 'router rip', # 'distribute-...
import subprocess wifi_connect = False try: wifi_connect = subprocess.check_output(["pgrep", "wii-connec"]).strip().decode('UTF-8') # import code; code.interact(local=dict(globals(), **locals())) except subprocess.CalledProcessError: pass print(wifi_connect)
from django.urls import path, re_path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), path('goals/', views.goals_list, name='goals_list'), # Need a pk value for getting instances path('goal/edit/<str:pk>/', views.goal_edit, name='goal_edit'), ...
from math import atan2, degrees, radians, sin, cos class Force: def __init__(self, magnitude, angle): self.magnitude = magnitude self.angle = angle def get_horizontal(self): horizontal = self.magnitude*cos(radians(self.angle)) return horizontal def get_vertical(self): ...
import logging def parse_text_mt_name(name): system, sent_split = name.split("_") ssplit_ver = sent_split.split("v")[-1] ssplit_name = sent_split.rsplit("-", 1)[0] system_name, system_ver = system.rsplit("-v", 1) if system_name == "scriptsmt-systems": site = "edi" type = "nmt" ...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.8 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('None数据类型实验') a = None print('a:',a) print(type(a))
#! /usr/bin/env python import sys import os import csv import random import math import re from pprint import pprint import cPickle as pickle from nltk.stem.wordnet import WordNetLemmatizer from nltk import PorterStemmer,FreqDist import numpy as np import itertools import string CRAWL=True if CRAWL==False: pri...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time import sys import io import re import math import itertools import collections import bisect #sys.stdin=file('input.txt') #sys.stdout=file('output.txt','w') #10**9+7 mod=1000000007 #mod=1777777777 pi=3.141592653589 IS=float('inf') xy=[(1,0),(-1,0),(0,1),(0,-1)] ...
# -*- coding: utf8 -*- import traceback import time import socket import urllib ERR_OK = 0 ERR_WARNING = 1 ERR_CRITICAL = 2 ERR_UNKNOWN = 3 def check(check_url, warning_time, critical_time): global ERR_OK, ERR_WARNING, ERR_CRITICAL socket.setdefaulttimeout(critical_time) ...
""" Catching Car Mileage Numbers "7777...8?!??!", exclaimed Bob, "I missed it again! Argh!" Every time there's an interesting number coming up, he notices and then promptly forgets. Who doesn't like catching those one-off interesting mileage numbers? Let's make it so Bob never misses another interesting number. We'...
from app_def import app from choroplethmapbox import get_choroplethmap_fig from pre_process import * import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output from utils import create_horizontal_bar_plot_with_annotations, options_map, stat_zones_names_dict, optio...
#這是一個密碼輸入程式 password = 'a123456' x = 2 enter_password = input('請輸入密碼') while enter_password != password: print ('密碼錯誤') print ('您還可以輸入', x,'次') if enter_password != password: if x == 0: print ('密碼錯誤三次,系統將自動關閉') SystemExit break else: x = x - 1 enter_password = input('請輸入密碼') if enter_password == ...
# -*- coding: utf-8 -*- """ Created on Mon Feb 17 14:53:04 2020 @author: zirklej """ import numpy as np from matplotlib import pyplot as plt from scipy.stats import linregress from random import gauss from sklearn.linear_model import LinearRegression # generate random data points about line y=2x+0.5 nu...
from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.decorators import action from rest_framework.mixins import ListModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin from rest_framework.response import Response from rest_framework.viewsets import Generic...
def is_palindrome(num): num_as_string = str(num) # print num_as_string[1] i = 0 palindrome = True while palindrome and i < (len(num_as_string) / 2): if num_as_string[i] != num_as_string[len(num_as_string) - 1 - i]: palindrome = False else: i += 1 return palindrome def is_largest_palindrome(): max_num ...
from django.core.exceptions import PermissionDenied from rest_framework import permissions from rest_framework import generics from rest_framework.serializers import ValidationError from apiv1.serializers import EndRideSerializer, PassengerSerializer, AcceptRequestSerializer from apiv1.permissions import IsDriver, Is...
# 670. Maximum Swap # Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. # Return the maximum valued number you could get. # # Example 1: # Input: 2736 # Output: 7236 # Explanation: Swap the number 2 and the number 7. # Example 2: # Input: 9973 # Output: 9973 # Exp...
from django.contrib import admin # Register your models here. from .models import Movie, Product, Category, Tag, Review, Genre, PrReviews, PrTag admin.site.register(Movie) admin.site.register(Review) admin.site.register(Product) admin.site.register(Tag) admin.site.register(Category) admin.site.reg...
import re __all__ = [ 'Survey', 'Recipient', 'Collector', 'EmailMessage' ] class Survey(dict): def __init__(self, survey_title, template_id=None, from_survey_id=None): params = { 'survey_title': survey_title } if template_id: params['template_id'] = template_id...
#!/usr/bin/env python3 # # Ping another pScheduler host to see if it responds # import optparse import pscheduler pscheduler.set_graceful_exit() # # Gargle the arguments # class VerbatimParser(optparse.OptionParser): def format_epilog(self, formatter): return self.epilog opt_parser = VerbatimParser( ...
from operator import itemgetter from time import sleep from gevent import monkey monkey.patch_all() import sys import webbrowser import argparse import difflib import gevent import sqlite3 import subprocess from datetime import datetime, timedelta import arrow import requests from bs4 import BeautifulSoup from dateu...
#!/usr/bin/python3 def multiple_returns(sentence): tuple_sent = (len(sentence), sentence[0] if sentence else "None") return tuple_sent
from django.urls import path from rest_framework.routers import DefaultRouter from sale.views import SaleViewSet, SaleStatisticsView router = DefaultRouter(trailing_slash=False) router.register("sales", SaleViewSet, basename="sales") urlpatterns = router.urls urlpatterns += [ path("sale_statistics", SaleStatis...
nums = set([int(n) for n in open('in').readlines()]) for num1 in nums: for num2 in nums: if num1 == num2: continue if 2020 - num1 - num2 in nums: print(num1 * num2 * (2020 - num1 - num2)) break
#!/usr/bin/env python import re import sys from subprocess import Popen, PIPE ignore = ",".join ( [ "C0103", # Naming convention "I0011", # Warning locally suppressed using disable-msg "I0012", # Warning locally suppressed using disable-msg "W0511", # FIXME/TODO "W0142", # *args or **kwargs ...
def getPrime(): __name__ prime_list=[] start =int(input("enter start number: \t")) for num in range(start,start+100): isPrime =True for i in range(2,num): if(num % i) == 0: isPrime =False if isPrime: prime_list.append(num) print(prime_list) if __name__ == "__main__": getPrime()
#!/usr/bin/env python3 import json import os import string import re import dbus from pathlib import Path import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import toml # Subscribe inject topics def on_connect(client, userdata, flags, rc): print("MQTT connected") client.subscribe("hermes/asr...
from typing import Dict, List, Optional class Label(): __name: str __group: Optional[str] def __init__(self, data: Dict): self.__name = data["name"] self.__group = None split = self.__name.split("/", 1) if len(split) > 1: self.__group = split[0] @property ...
from fastapi import APIRouter from app.api.v1.endpoints import domains api_router = APIRouter() api_router.include_router(domains.router, prefix="/domains", tags=["domains"])
# -*- coding: utf-8 -*- ######################################################### # python import os import sys import logging import traceback import json import re import urllib import requests import threading # third-party # sjva 공용 # 패키지 from .plugin import logger, package_name from .model import ModelSetting, ...