text
stringlengths
38
1.54M
import asyncio import random from aiotftp.packet import Ack, Mode, Opcode, parse, Request import pytest class DelayedAckClient(asyncio.DatagramProtocol): """Let each packet go unACKed at least twice before ACKing.""" def __init__(self, request, loop): self.request = request self.received = b...
import sys cartezyen = [] def beforeIndis(flag,onceki): if(flag[onceki]==0): return True else: return False def findIndis(multArray,array): assistans = [] ### nValue=len(multArray[0]) index = len(array) while(index!=nValue): value = max(array) indis = array.i...
# -*- coding: utf-8 from __future__ import absolute_import import unittest from oaxmlapi import commands, datatypes try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET class TestAddClass(unittest.TestCase): def test_str(self): project = datatypes.Datat...
def findMissingRanges(nums, lower, upper): res = [] low = lower - 1 nums.append(upper+1)#pay attention to the board for num in nums: dif = num - low if dif == 2: res.append(str(low+1)) elif dif >2: res.append(str(low+1)+ "->" + str(nums-1)) low = num return res
import pandas as pd from crawl_utils.bot_utils import * from crawl_utils.html_request import * from crawl_utils.url_extractor import * from crawl_utils.table_parser import * from crawl_utils.column_regularization import * def get_html_table(main_sub_pages, depth=1): ''' input : list having tuples (text, lisf ...
from tkinter import * window=Tk() def converter(): grams=float(e1_value.get())*1000 pounds=float(e1_value.get())*2.20462 ounces=float(e1_value.get())*35.274 t1.delete("1.0", END) t1.insert(END, grams) t2.delete("1.0", END) t2.insert(END, pounds) t3.delete("1.0", END) t3....
import asyncio import logging from queue import Queue import threading import time from typing import * from uuid import uuid4 import stopit from citrine_daemon import errors, package from citrine_daemon.server.json import CitrineEncoder logger = logging.getLogger(__name__) primary_job_queue = Queue(maxsize=1000) ...
# Copyright 2004-present, Facebook. All Rights Reserved. from django import forms class FbeOnboardingForm(forms.Form): business_name = forms.CharField( label="Business Name", max_length=100, widget=forms.TextInput(attrs={"class": "form-control py-4"}), disabled=True, )
import numpy as np from matplotlib import pyplot as plt %matplotlib inline import seaborn as sns sns.set() import os, requests fname = [] for j in range(3): fname.append('steinmetz_part%d.npz'%j) url = ["https://osf.io/agvxh/download"] url.append("https://osf.io/uv3mw/download") url.append("https://osf.io/ehmw2/...
from flask import Flask, render_template, make_response, request, after_this_request, g import sys import random sys.path.insert(1, '../') from search import Search from bert_serving.server.helper import get_args_parser from bert_serving.server import BertServer args = get_args_parser().parse_args(['-model_dir', '../.....
import pandas as pd import numpy as np import matplotlib.pyplot as plt from basic.bupt_2017_11_28.type_deco import prt import joblib from sklearn import preprocessing from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from basic.bupt_2017_11_28.type_deco import prt import se...
#Time complexity - O(n*k) #Space complexity - O(n) #Works on leetcode - yes #Approach - The idea here is for each new element, we look back upto k elements in array and keep track of the maximum #in that segment. We get the segment sum, once we have the maximum for this segment when we either reack k back or the start...
"""Support for ELV WS980Wifi weather station""" import logging from datetime import timedelta import voluptuous as vol # Import the device class from the component that you want to support from homeassistant.const import CONF_DEVICES, CONF_NAME, CONF_HOST, CONF_PORT import homeassistant.helpers.config_validation as ...
""" This script is used under the project "Universal Transcriptome" Input: Output directory generated by invoking query_2 executable Output: TSV with final components {col1: finalCompID, col2: list_of_original_components} A. Column(1): final Component ID B. Column(3:): list of original components Run: python constru...
bl_info = { "name" : "Gradient Painter", "author" : "Martin Durhuus", "version" : (0,2), "blender" : (2,78,0), "location" : "3d view", "description" : "A simple tool to quickly texture a mesh through a color ramp. Export currently gives you an .fbx and albedo map", "warning" : "Highly unstab...
from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window MILE_TO_KM = 1.609344 class ConvertMilesApp(App): """ ConvertMilesApp is a Kivy App for converting Miles to Kilometres """ def build(self): Window.size = (500, 200) self.title = "Convert Miles to Kilomet...
# -*- coding: utf-8 -*- # @Time : 2020/11/9 7:01 # @Author : ihyf # @File : test1.py # @Software: PyCharm # @ Desc : 音视频工具 import os import unittest class VideoTools(object): """ -loop 1 参数表示图片无限循环 -shortest参数表示音频文件结束,输出视频就结束。 相关链接 http://www.ruanyifeng.com/blog/2020/01/ffmpeg.html http...
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to ...
from lib.template.template import TemplateUtils, Template class TestTemplate(Template): def __init__(self, datas): super(self.__class__, self).__init__(datas) def execute(self): datas = self.getDatas() name = datas["name"] privates = "" for data in self.getProperties()...
import face_recognition import cv2 import numpy as np imgMe = face_recognition.load_image_file('assets/persons/Mert.png') imgMe = cv2.cvtColor(imgMe, cv2.COLOR_BGR2RGB) encodedMe = face_recognition.face_encodings(imgMe)[0] cap = cv2.VideoCapture(0) cap.set(3, 640) cap.set(4, 480) while True: success, img = cap.r...
import os from blur.build import * path = os.path.dirname(os.path.abspath(__file__)) # Replace revision numbers in the nsi template svnnsi = WCRevTarget("blurdlx_svnrevnsi",path,".","blurdlx-svnrev-template.nsi","blurdlx-svnrev.nsi") # Create the nsi installer All_Targets.append( NSISTarget( "blurdlx", pa...
# -*- coding: utf-8 -*- import config import psycopg2 from psycopg2 import extensions from psycopg2.extras import DictCursor class DbConnection(object): def __init__(self): self.connection = None def get(self): if self.connection: conn = self.connection else: ...
import myNetwork_settings import sys import utime as time from BMP180 import BMP180 from machine import I2C, Pin # create an I2C bus object accordingly to the port you are using from micropython import const import gc import ssd1306_i2c import uasyncio as asyncio LIVE_LED_BLINK_INTERVA...
"""Dependency Injector example.""" import sys import sqlite3 from boto.s3.connection import S3Connection from dependency_injector import catalogs from dependency_injector import providers from dependency_injector import injections from example import services class Platform(catalogs.DeclarativeCatalog): """Ca...
import cv2 import numpy as np #np.set_printoptions(threshold=np.nan) image = cv2.imread('/home/frkn/Desktop/fotolar/maze_threshold1.jpg') image_gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) image_gray = np.float32(image_gray) dst = cv2.cornerHarris(image_gray,2,29,0.04) dst = cv2.dilate(dst,None) #coordinates = np.z...
''' Типы данных: 1. int - integer - целое число 2. float - floating point number - десятичные числа 3. bool - логический тип 4. str - string - строка ----- 5. date/time - тип даты и времени ''' print(3 + 5) # выводит что-то на экран print(3 - 5) print(3.0 * 5) # <- умножить print(3.45 ** 5) # <- возвести в степень ...
from models import * from django.contrib import admin class problemAdmin(admin.ModelAdmin): list_display = ('problem_id','priority','description','status','related_tickets','current_owner','affected_components','currect_impact','user_experience','root_cause','workaround','workaround_status','long_term_solution','long...
# ===================== Python Numbers ======================== no_of_students = 45 print(type(no_of_students)) #? price_of_drink = 45.78 print(type(price_of_drink)) #? type(no_of_students) #? result_sum = no_of_students + price_of_drink #? type(result_sum) #? # ========================== string ===============...
from django.db import models from django.utils import timezone # TO RUN MIGRATION IN TERMINAL: # cd pythonapp/main # python3 manage.py makemigrations && python3 manage.py migrate class UserManager(models.Manager): def basic_validator(self, postData): errors = {} try: if len(postData['name']) < 3: errors["...
import numpy as np import matplotlib.pyplot as plt import pandas as pd import scipy.stats as ss fig=plt.figure() ax1=fig.add_subplot(311) x=np.linspace(0,10,100) ax1.plot(x,np.cos(x)) ax2=fig.add_subplot(312) ax2.plot(x,np.cos(x+1)) ax3=fig.add_subplot(313) ax3.plot(x,np.cos(x+2)) ax=[ax1,ax2,ax3] names=['signal 1','s...
from django.shortcuts import render #Render means you don't need the HttpResponse, or HttpResponseRedirect. from django.http import HttpResponseRedirect from my_books_app.models import Book, BookForm #This line changed. PM # import pdb #This line is new. AM def index(request): return HttpResponseRedirect('/books')...
T = int(input()) for test_case in range(1, T + 1) : n,m = input().split() print("#%d"%test_case, end= ' ') for t in m : if t <= '9': t = ord(t) - ord('0') else: t = ord(t) - ord('A') + 10 # print(t) print(bin(t)[2:].zfill(4), end = '') print()
#!/usr/bin/python3 import numpy as np import math EPS = 1e-6 def solve(A, b): if np.linalg.matrix_rank(A) < len(A): return np.array([np.nan] * len(A)) return np.linalg.solve(A, b) def system_from_file(filename): fin = open(file=filename, mode="r") n = int(fin.readline()) data = np.ar...
# -*- coding: UTF-8 -*- from json_parser.json_parser import JsonParser import unittest import json import csv import os import pandas as pd class TestParser(unittest.TestCase): csv_path = 'test.csv' json_parser = JsonParser() @classmethod def setUpClass(cls): with open(cls.csv_path,...
from graphene_django import DjangoObjectType import graphene from ..common.types import PaginationType from ...apps.post.models import PostModel class PostType(DjangoObjectType): class Meta: model = PostModel class PostListType(graphene.ObjectType): status = graphene.Int() msg = graphene.String...
import git import pandas as pd import warnings import plotly.graph_objs as go import plotly.offline as po import datetime warnings.simplefilter("ignore") pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', 5) pd.set_option('display.max_colwidth', 37) pd.set_option('display.width', 600) def a...
import random import string def get_random_string(length): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(length)) def get_random_email(length): letters = string.ascii_lowercase upper = ''.join(random.choice(letters) for i in range(length)) return upper+'@gma...
import stanfordnlp import spacy text = "Chris Manning is a nice person. Chris wrote a simple sentence. He also gives oranges to people." #text = "Apple is looking at buying U.K. startup for $1 billion" text = u"But Google is starting from behind. The company made a late push into hardware, and Apple Siri, available on...
""" File: Field_generator.py This module generates field for game Created by Ivan Kosarevych 07.02.16 13:50:56 """ def generate_ship(size): """ :param size: int :return: list(list) Generates coordinates for ship of given size Example for size 4: [(1,2),(1,3),(1,4),(1,5)] """ import ran...
#!/usr/bin/env python # coding: utf-8 # In[1]: from kafka import KafkaProducer import pandas as pd import json import csv from time import sleep # In[2]: df = pd.read_csv (r'C:/Users/bharath desktop files/updated newyrk.csv',dtype=str) df1=df.to_json (r'C:/Users/91893/Desktop/SRH project works module 1/baywtchjs...
import game_interface import random import time import cPickle import neural_net import neural_net_impl filename = "moves.txt" #def get_move(view): # return (random.randint(0,3), False) # DEFAULT GET_MOVE def get_move(view): # Choose a random direction. # If there is a plant in this location, then try and eat it...
#coding:utf-8 from flask import Flask import sys reload(sys) sys.setdefaultencoding('utf8') # 因为程序内部有中文参数,gunicorn直接调用这个文件的app,在入口把编码转好 app = Flask(__name__) app.secret_key = "UIsadl;oi3&*(&9023sd" import login import demo import idc import cabinet import server import mem import log import cmd import jobs
# Enter your code here. Read input from STDIN. Print output to STDOUT def createPhonebook(num_entries): address_book={} for i in range(num_entries): name_and_phone=(raw_input()) name,phone_no=name_and_phone.split(" ") address_book[name]=phone_no return address_book def getphoneNum...
import pandas as pd df = pd.read_excel('Rekap_OnlineCourse.xlsx') print(df.head(10),'\n') # Periksa kolom yang mengandung data kosong # print(df.isnull().sum(),'\n') # Hapus baris tidak digunakan data = df.drop([0,1,1296]) #print(data.head()) # Ubah sebuah kolom menjadi index data = data.set_index('Rek...
from rest_framework import serializers from .models import Libro, Autor class LibroSerializer(serializers.ModelSerializer): class Meta: model = Libro fields = ('id', 'nombre', 'editorial', 'genero', 'autor',) class AutorSerializer(serializers.ModelSerializer): model = Autor class Meta: mod...
import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) host = socket.gethostname() port = 54321 s.sendto(str.encode("Hello", 'utf-8'), (host, port)) print(bytes.decode(s.recv(1024))) s.close()
# Generated by Django 3.0.6 on 2020-06-04 09:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('summerschool', '0006_auto_20200527_0733'), ] operations = [ migrations.DeleteModel( name='SchoolLoginCode', ), ]
from flask import Flask, redirect, request, abort, render_template, session from flask_cors import CORS from flask_socketio import SocketIO import json import os app = Flask(__name__, template_folder="templates/") CORS(app) socketio = SocketIO(app) app.secret_key = "gator-semantic-annotator" ### / - routes for the...
import os import re import tempfile import pytest from alphabot import app @pytest.fixture def client(): db_fd, app.config['DATABASE'] = tempfile.mkstemp() app.config['TESTING'] = True client = app.test_client() yield client os.close(db_fd) os.unlink(app.config['DATABASE']) def root(clie...
#coding:utf-8 import json import os goods = [["iphone1",111],["iphone2",222],["iphone3",333],["iphone4",444],["iphone5",555]] users_info ={'user1':'1','user2':'2','user3':'3'} path_dir = "/root/python/user/%s" user_shopping_info_path = path_dir+"/shopping_info" def get_history_info(user): user_path_dir = path_...
import re value = "cyberdyne" g = re.search("(dy.*)", value) if g: print("search: ", g.group()) s = re.match("(vi.*)", value) if s: print("match:", m.group()) value = "two 2 four 4 six 6" res = re.split("\D+" , value) for elements in res: print (elements)
import copy import json import os from dconn import Conn import load from psycopg2.extras import Json with open(os.environ['FILE_RECORD_TEMPLATE']) as f: file_record_format_d = json.loads(f.read()) source_data = { "home_url": "http://www.p12.nysed.gov/", "source_name": "nysed", "publisher": "New Yor...
m,n=map(str,input().split()) l=[] for in range(int(m)+1,int(n)): a=0 x=len(str(i)) for b in str(i): a=a+int(b)**x if str(a)==str(i): l.append(i) for b in l: print(b,end=" ")
import torch import torch.nn as nn import torch.nn.functional as F import torchaudio import numpy class ComplexConv2d(nn.Module): def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, **kwargs): super().__init__() ## Model components ...
import numpy as np from sklearn.utils import compute_class_weight from keras.models import Sequential, Model from keras.layers import BatchNormalization, Dense, Input, Concatenate from keras.layers import Conv1D, Flatten, Activation, MaxPooling1D from keras.layers import LSTM from keras.optimizers import Adam from EB...
#!/usr/bin/python3 import sys if __name__ == "__main__": arg = int(sys.argv[1]) for line in sys.stdin: updated_line = line.replace("\n", "") print(updated_line + "\t" + "Key " + str(arg) + " " + updated_line, end="\n") sys.stdout.flush()
score = input('學生分數: ') sco = int(score) if sco <= 100 and sco >= 90: print('A+') elif sco <90 and sco >=85: print('A') elif sco <85 and sco >=80: print('A-') elif sco <80 and sco >=77: print('B+') elif sco <77 and sco >=73: print('B') elif sco <73 and sco >=70: print('B-') elif sco <70 and sco >=67: print('C...
class robot: def __init__(self, name, age): self.name = name self.age = age def intro(self): print("\nName is "+ self.name) print("Age is "+ str(self.age)) if __name__ == "__main__": r1 = robot("Max Kashyap", 21) r1.intro() r2 = robot("Ananya Talukdar", 21)...
# Created by B. Huiskamp. import pprint import cal_functions as cal # cal_functions is the name of the library. We are aliasing it as cal pp = pprint.PrettyPrinter(indent=4) # Populate All Days # cal is referencing the cal_functions library (We alias cal_functions as cal) cal.everyday_task_from_until("00:00", "0...
try: import pkg_resources except: pass import sys sys.path[:0] = ['.'] import sgetasks import numpy as np from numpy import s_,r_,c_,pi import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt
import threading import requests from requests.exceptions import RequestException, Timeout from bs4 import BeautifulSoup import frontier import web_crawler class SingleCrawler(threading.Thread): """ Implementation of a single thread within a pool of workers. It inherits from threading.Thread, extending t...
'''program to accept a number and determine whether it is prime''' import math num = int(input("enter the number")) is_prime = True if num < 2: is_prime = False else: for i in range(2,int(math.sqrt(num))+1): if num %i == 0: is_prime = False break if is_prime: print("number i...
#!/usr/bin/env python import struct import roslib; roslib.load_manifest('AER') import rospy from sensor_msgs.msg import Image from sensor_msgs.msg import LaserScan from std_msgs.msg import String class Kinect_LIDAR(): def __init__(self): rospy.init_node('AER_Kinect_Navigator') self.horizscan =...
#------------------------------------------------------------------------------ # Name: Visualizing a Neural Network Learn # Description: # # Author: Robert S. Spencer # # Created: 2/20/2017 # Python: 2.7 #------------------------------------------------------------------------------ import tenso...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: fastnode = head while True: if fastnode == None or fastnode.next == None: re...
#!/usr/bin/python """Simple HTTP Server. This module builds on BaseHTTPServer by implementing the standard GET and HEAD requests in a fairly straightforward manner. """ PORT = 9999 __version__ = "0.3" import BaseHTTPServer from MaslenRequestHandler import MaslenRequestHandler def test(HandlerClass = MaslenRequest...
""" На вход подается ссылка на HTML файл. Необходимо скачать этот файл, затем найти в нем все ссылки вида <a ... href="..." ... > и вывести список сайтов, на которые есть ссылка. """ import re import requests link = input().strip() resurs = requests.get(link) matchs = re.findall(r"(<a.*?)(href *?= *?[\"|\'])([\w:/]...
from flask import render_template, redirect, url_for, abort, request from flask_login import login_required, current_user from . import main from .forms import UpdateProfile, PitchForm, CommentForm from .. import db, photos from ..models import User, Pitch, Comment, Upvote, Downvote @main.route('/') def index(): ...
"""Finish all TODO items in this file to complete the isolation project, then test your agent's strength against a set of known agents using tournament.py and include the results in your report. """ import random class SearchTimeout(Exception): """Subclass base exception for code clarity. """ pass def custo...
# # AUTHOR: Krist Pornpairin # KEYWORD: Stirling numbers # https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind # import functools __import__('sys').setrecursionlimit(2100) @functools.lru_cache(maxsize=None) def recur(n: int, k: int): if not n and not k: return 1 if not n o...
import matplotlib.pyplot as plt import plotly.plotly as py import collections import operator import sys import csv D = {} with open(sys.argv[1]) as csvfile: reader = csv.reader(csvfile) for row in reader: date = row[1] if date != "date": if date in D: D[date] += 1 ...
import re import AccessLogInput array_to_print = [] def search(file_name, search_word): """ This function is for searching the search word(s) inside the file args : file_name : file name in the same directory return : array_to_print : the array with lines ...
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Field class ChecktradeScraperItem(scrapy.Item): company_name = Field() unique_name = Field() email = Field() mobile_phone = Field() ...
from django.urls import path,include from . import views urlpatterns = [ path('FertilityAPI/',views.FertilityAPIView.as_view()) ]
from selenium.webdriver.support.ui import Select from selenium import webdriver link=" http://suninjuly.github.io/selects2.html" browser=webdriver.Chrome() browser.get(link) x=browser.find_element_by_id("num1").text y=browser.find_element_by_id("num2").text z=int(x)+int(y) select = Select(browser.find_element_by_tag...
""" Django settings for mxshopnew project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os im...
import os import pandas as pd """ Count image files in folders to describe training set size """ ipath = r"E:\UNPROCESSED\train1_1000_test_3rd" totalfiles = 0 df = pd.DataFrame(columns=["Folder", "Count"]) folders = ([name for name in os.listdir(ipath) if os.path.isdir(os.path.join(ipath, name))]) for fo...
# given an array nums of n integers and an integer target # find three integers in nums such that the sum is closest to target # return the sum of the three integers class Solution: def threeSumClosest(self, nums, target): # with sum issues => always sort array first nums = sorted(nums) res...
import config from gpiozero import LED, MotionSensor from time import sleep import telepot sensor = MotionSensor(4) alarma = LED(14) def aviso(): bot.sendMessage(config.id, "Ojo! Alguien ha entrado a la habitacion!") alarma.on() # Start bot bot = telepot.Bot(config.token) while True: if sensor.motion_detected: ...
#为什么要重写,父类不能满足子类的需求,那么子类可以重写父类或者完善父类 class Dog: def __init__(self,name,color): self.name=name self.color=color pass def bark(self): print('汪汪叫。。。。') pass pass class kejiquan(Dog): def __init__(self,name,color):#属于重写父类的方法 #针对这种诉求 我们就需要调用父类的函数了 Do...
''' @Author: Sankar @Date: 2021-04-06 09:46:25 @Last Modified by: Sankar @Last Modified time: 2021-04-06 16:10:09 @Title : Test Deck of Cards ''' import pytest from src.Cards import Card, Deck, Player def test_card(capsys): ''' Description: Test Creation of a Card Parameter: ...
from tests import TestCase class TestViews(TestCase): def test_read_or_404(self): self.login('main-gateway1@example.com', 'admin') response = self.client.get('/api/networks/unknown-network') self.assertEqual(404, response.status_code)
from rest_framework import serializers from user_movie_collection.models import Collections, Movies class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collections fields = ['id', 'title', 'description'] class MovieSerializer(serializers.ModelSerializer): class Meta:...
class Solution(object): def maxSubarraySumCircular(self, A): """ :type A: List[int] :rtype: int """ ''' 思路: dp_max[i]: 以 nums[i] 结尾的最大子数组和 dp_min[i]: 以 nums[i] 结尾的最小子数组和 由于所有数的和相同, 计算跨越数组边界的子数组最大值, 等同于计算不跨越数组边界子数组的最小值 --- 转移方程: ...
# -*- coding:utf-8 -*- # sigular, left eigenvector, right eigenvector def restore(sigma, u, v, k): print k m = len(u) n = len(v[0]) a = np.zeros((m, n)) for k in range(k + 1): for i in range(m): a[i] += sigma[k] * u[i][k] * v[k] b = a.astype('uint8') Image.fromarray(b).s...
#!/usr/bin/env python import asyncio import ssl import os import config import time def ssl_ctx(): ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE if config.cert.file: ctx.load_cert_chain(config.cert.file, password=config.cert.password) return ctx class IRC: de...
import importlib from .interface import InterfaceService BUILTIN_SERVICES = [ 'fs', 'sys', ] FACTORIES = {} for name in BUILTIN_SERVICES: mod = importlib.import_module('.{}'.format(name), __name__) FACTORIES[name] = mod.factory
from __future__ import annotations from typing import Optional from datetime import datetime from bson import ObjectId from pydantic import BaseModel, Field class PyObjectId(ObjectId): @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): if...
import copy from textwrap import dedent import numpy as np import pandas from matplotlib import pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.patches as patches import matplotlib from . import plotutils from matplotlib.transforms import blended_transform_factory from matplotlib...
def partOne(data): pass def partTwo(data): pass def task(data): print(partOne(data)) print(partTwo(data))
import socket, struct, ssl, time, collections from packets import * class TCPConnection(object): __eof = "\r\n" __connections = {} @staticmethod def get_connection(address): try: return TCPConnection.__connections[address] except: return None @staticmethod def g...
import random import article_collection_pb2 from barnum import gen_data """ Random generated data for demo """ names = [gen_data.create_name() for _ in range(0, 15)] emails = [gen_data.create_email() for _ in range(0, 15)] titles = [gen_data.create_nouns() for _ in range(0, 15)] contents = [gen_data.create_paragraphs(...
def build_request(method='empty', data={}): request = { 'method': method, 'data': data } return request def build_response(status=-1, data={}, error_msg=''): response = { 'status': status, 'data': data, 'error_msg': error_msg } return response
from nltk import word_tokenize import string import dill as pickle import re import emoji from sklearn.base import BaseEstimator, TransformerMixin from sklearn.pipeline import Pipeline # Cette fonction ne prends en charge que les lettres latines def MyCleanText(X, removeEmoji=False, #Emojis ...
#! /usr/bin/env python import rospy import serial import time from std_msgs.msg import UInt8 ############################################################# class MotorDriver: ############################################################# ############################################################# def __init__(sel...
# _*_coding:utf-8_*_ from mysplit import my_split # def my_split(line, types=None, delimiter=None): # """ # splits a line of test and optionally performs type conversion # :param line: # :param types: # :param delimiter: # :return: list # """ # fields = line.split(delimiter) # if t...
# -*- coding: utf-8 -*- # ritch_text_box : # none_effect_publicitys : # publicitys : def View( ritch_text_box, keishou, publicitys ): for p in publicitys: counter = "" if p.counter > 1 : counter = " x" + str(p.counter) ritch_text_box.Text += p.name + keishou ...
nin,k=map(int,input().split()) din=[] for i in range(nin): s1=set(map(int,input().split())) din.append(s1) c=s1.intersection(*din) print(*c)
# coding:utf-8 import json import os, sys import signal import warnings import curses import argparse # local try: # need when 「python3 gfzs/cmd/demo.py」 if __name__ == "__main__": # https://codechacha.com/ja/how-to-import-python-files/ sys.path.append(os.path.dirname(os.path.abspath(os.path....
import sys # Read file fname = sys.argv[1] f = open(fname, "r") raw = f.read() # Clean data s = raw.split() n, k = int(s[0]), int(s[1]) f1 = 1 f2 = 1 for i in range(n - 2): f3 = f1 * k + f2 f1, f2 = f2, f3 print(f3)