text
stringlengths
8
6.05M
from django.conf.urls import url from . import views app_name = 'documents' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<class_id>[0-9A-Za-z]+)$', views.list, name='list'), url(r'^(?P<class_id>[0-9A-Za-z]+)/upload/$', views.upload, name='upload'), url(r'^(?P<class_id>[0-9A-Za-z]+)...
import numpy as np import math import pandas as pd from sklearn.cross_validation import train_test_split from sklearn.datasets import load_iris # 高斯模型,伯努利模型,多项式模型 from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB def create_data(): iris = load_iris() df = pd.DataFrame(iris.data, columns=i...
# -*- coding: utf-8 -*- #test.py import hyperlink_fetch import re import text_manip from bs4 import BeautifulSoup hyperlink_fetch.wiki_get_all(root_link="https://en.wikipedia.org/wiki/Fury_and_Hecla_Strait", max_depth=1, input_root_folderpath="F:\Workspaces\Python\Wikipedia_closure\example", force_redo=True) # this was...
# -*- coding: utf-8 -*- """ Created on Mon May 6 23:16:31 2019 Topic : anagram method2 """ def anagramCheck(string1, string2): if len(string1) != len(string2): label = False else: label = True list1 = list(string1) list2 = list(string2) list1.sort() li...
import re def binary(data): return re.match(r'[01]', data) def binary_even(data): if re.match(r'.+0$', data): if binary(data): return True def hex(data): return re.match(r'[0-9A-F][^G-Z][^a-z]', data) def word(data): if re.match(r'.*[^0-9].*', data): if re.match(r'[^!...
#!/usr/bin/env python # coding=utf-8 from InceptionV3 import * import torch import torch.nn as nn import torch.nn.functional as F class HydraPlusNet(nn.Module): def __init__(self,num_class,is_fusion=True): super(HydraPlusNet,self).__init__() self.is_fusion = is_fusion self.MNet = Inception3...
# -*- coding: utf-8 -*- import scrapy import csv import os class RadioguideSpider(scrapy.Spider): name = 'radioguide' allowed_domains = ['radioguide.fm'] start_urls = ['https://www.radioguide.fm/countries'] def parse(self, response): datas = response.xpath('.//*[@class="col-md-4 col-xs-6 col-...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('frontend', '0006_auto_20150309_1937'), ] operations = [ migrations.AddField( model_name='article', n...
import re import logging import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.tree import plot_tree def calibration_plot( scores, target, n_bins=20 ): binned_score = pd.qcut(scores, n_bins) bin_centres = sorted(pd.Series(scores).groupby(binned_score).mean().values)...
# Alternative to_sql() *method* for DBs that support COPY FROM import csv from functools import partial, reduce from getpass import getpass from io import StringIO from operator import add, iadd from typing import Callable import psycopg2 from sqlalchemy import MetaData, Table, bindparam, create_engine, func, text fro...
#use the print() method to display somthing in the terminal print("Hello World") #Like java you can concatenate strings in this method print("Hello" + " Tomi" + " welcome to python") #If you want to concatenate numbers in a print() expression wrap the number in str() #str is used to convert an object into a string p...
from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=20) birthday = models.CharField(max_length=20) phone_number = models.CharField(max_length=15) address = models.CharField(max_length=50, blank=True) mail = models.CharField(max_length = 50, blank = ...
import numpy as np class LinearRegression: def __init__(self, x, y, learning_rate=0.001, num=1000): arr = np.ones(x.shape) x = np.append(arr, x, axis=1) self.x = x self.y = y self.row = x.shape[0] self.col = x.shape[1] self.learning_rate = learning_rate ...
import ee # ====================== # Functions to calculate NDVI, NBR, SAVI bands and add band to original image # for harmonized and merged landsat collection (all_LS) where band names have been changed # NDVI = (NIR - RED) / (NIR + RED) # NBR = (NIR - SWIR)/(NIR + SWIR) (Lopez, 1991; Key and Benson, 1995) # SAVI = ...
import argparse import bencodepy import os import tracker import peer_node import client_node parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-tp", "--torrent-path", dest="torrent_path", required=True, help="Path to Torrent File", metavar='\b') parser.add_argument(...
__author__ = "Narwhale" def bubble_sort(alist): """冒泡排序""" n = len(alist) #外循环 for j in range(0,n-1): #内层循环 count = 0 for i in range(0,n-1-j): if alist[i] > alist[i+1]: alist[i],alist[i+1] = alist[i+1],alist[i] count += 1 if 0...
""" general_plots -------------------------------------------------------------------------------- GENERATE PLOTS FOR WORKSHOP David T. Milodowski, 25/03/2019 """ """ import libraries needed """ import numpy as np import matplotlib.pyplot as plt # plotting package import seaborn as sns # another usef...
from database import Database from notifier import Notifier import typer, arrow, dotenv from plan import Plan CONFIG = dotenv.dotenv_values('.env') DATABASE: str = CONFIG['database'] USERNAME: str = CONFIG['username'] PASSWORD: str = CONFIG['password'] db = Database(DATABASE) app = typer.Typer() @app.command() def ...
from urllib import request from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options url = r"https://www.nvinq.jra.go.jp/jra/servlet/JRAVotereference" dp = r"C:\driver\94\chromedriver.exe" options = Options() # options.add_argument('--headless') driver = webdriv...
# 冻结 # VGG19模型训练网络 from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import numpy as np from keras.applications import ResNet50,VGG19 import matplotlib.pyplot as plt # tf.test.gpu_device_name() model_name = "Frozen" # 模块命名,用于绘图时 train_epochs0 = 10 # 设置训练轮次 def sh...
class Solution: def generate(self, numRows) if numRows == 0: return [] elif numRows == 1: return [[1]] elif numRows == 2: return [[1],[1,1]] tangle_list = [[1],[1,1]] for i in range(2,numRows): temp_list = [] temp_li...
from tornado.ioloop import IOLoop from log import logger from server import Server from echo import Echo class EchoServer(Server): def __init__(self): Server.__init__(self) self.register(Echo, self.on_echo) def on_echo(self, connection, header, msg): logger.info('connection:{0}, msg...
import math class Solution: def numSquares(self, n: int) -> int: a = [0]*(n+1) for i in range(1,n+1): r = math.sqrt(i) if r.is_integer(): a[i] = 1 else: r = int(r) ind = i - (r*r) v1 = 1+a[ind] ...
# https://www.youtube.com/watch?v=CqvZ3vGoGs0&list=PL-osiE80TeTt2d9bfVyTiXJA-UTHn6WwU&index=9 import random import sys import math import os import datetime import antigravity import calendar sys.path.append('/home/maxh/Python/My-Modules/') from my_module import find_index, test # from my_module import * # import my...
from itertools import groupby str = input() print(*[(len(list(c)), int(k)) for k, c in groupby(str)])
#!/usr/bin/env python import argparse import math import sys from collections import Counter import numpy as np import sklearn.metrics as metrics from sklearn import cross_validation from sklearn.metrics.pairwise import cosine_similarity import pandas as pd import codecs import os from sklearn.ensemble import GradientB...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 26 05:56:17 2019 @author: kanchana """ import pandas as pd import numpy as np import seaborn as sns; sns.set(color_codes=True) import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split fb=pd.read_csv('dataset_Facebook.c...
''' Created on Jan 24, 2016 @author: Andrei Padnevici @note: This is an exercise: 10.1 ''' try: fName = input("Enter file name: ") if fName == "": fName = "mbox-short.txt" file = open(fName) except: print("Invalid file") exit() emailsDict = dict() email = None for line in file: words = line....
import scipy as sp class kernel(object): def __init__(self): pass def __call__(self, x1,x2): return 0. class sqexp1d(kernel): """ 1d squared exponential kernel k = A exp(-0.5(x2-x1)**2/l**2) dn methods are k( x1, d^n x2/dx^n) the caller is responsible for sign changes for othe...
#Create Flower #Date August 22, 2018 #Udacity Python exersise #Dipen Patel import turtle def draw_circle(circle): circle.circle(100) circle.left(120) def draw_line(line): line.right(90) line.forward(350) def draw_multiple_triangle (): window = turtle.Screen () window.bgcolor ("white") wi...
"""Device Group Services Classes.""" import logging from .devicegrouprecords import DeviceGroupRecords from .devicegrouprecords import DeviceGroups logging.debug("In the device_group_services __init__.py file.") __all__: ["DeviceGroupRecords", "DeviceGroups"]
# -*- coding: utf-8 -*- """ Created on Mon Mar 16 15:44:54 2015 @author: LIght """ from sklearn.decomposition import FactorAnalysis import pandas as pd class FactAnalysis: @staticmethod def groupMovieGenre(user_item_matrix,item_df): genre_num = 5 fa_model = FactorAnalysis(n_components=g...
#!/usr/bin/env python3.6 # -*- coding: iso-8859-15 -*- import numpy as np A = np.array([[0.86, 0.08], [-0.12, 1.14]]) start_points = np.array([[10, 50], [100, 200], [50, 100], [70, 120]]) start_points = np.random.randint(0, 30...
from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class Category(models.Model): class Meta: verbose_name_plural = 'Categories' name = models.CharField(max_length=254) friendly_name = models.CharField(max_length=254, null=True, blank=T...
import numpy as np from ..kernels.kernelsForNum import linear_kernel, polynomial_kernel, rbf_kernel from ..kernels.kernelsForString import get_spectrum_kernel,get_mismatch_kernel class baseKernel(object): dict_numeric_kernels = {'linear': linear_kernel,'polynomial': polynomial_kernel,'rbf': rbf_kernel,} dict_...
# Copyright 2017 The Forseti Security Authors. 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 ap...
import json from flask import Flask from flask import request app = Flask(__name__) @app.route('/', methods = ['POST']) def reg(): dict = json.loads(request.get_data()) a = [1, 2, 3, 4] return json.dumps(a) if __name__ == '__main__': app.run(debug=False)
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, with_statement from revolver.core import sudo from revolver import command, package def install(): package.ensure(["curl", "git-core"]) url = "https://raw.github.com" \ + "/nvie/gitflow/develop/contrib/gitflow-installer.sh" ...
""" <Reinforcement Learning and Control>(Year 2020) by Shengbo Eben Li @ Intelligent Driving Lab, Tsinghua University ADP example for lane keeping problem in a circle road [Method] Model predictive control(MPC) as comparison """ from Solver import Solver from Config import DynamicsConfig,...
import numpy as np from scipy import sparse """ Calculate spectral radius of whole weight matrix """ def getSpectralRadius(self, weights): # Stack top and bottom row of weight matrix horizontally top = sparse.hstack([weights.exex, weights.inex]) bottom = sparse.hstack([weights.exin, weights.inin]) # S...
import cvxpy as cvx import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse def show_ellipse(A, b, color, ax): sigma = np.linalg.inv(A.dot(A.T)) mu = b vals, vecs = np.linalg.eigh(sigma) # Compute "tilt" of ellipse using first eigenvector x, y = vecs[:, 0] the...
# -*- coding: utf-8 -*- from __future__ import absolute_import __author__ = """Walter Treviño""" __email__ = 'walter.trevino@gmail.com' __version__ = '0.1.0' from .pycfdi import Cfdi
from _typeshed import Incomplete def min_weighted_dominating_set(G, weight: Incomplete | None = None): ... def min_edge_dominating_set(G): ...
from __future__ import division import datetime class Helper(): def __init__(self): self.err_count = 0 pass def daytime_only(self, data): # s2 = datetime.strptime(s, '%Y%m%d%H%M') for k, v in data.items(): try: timest = datetime.strptime(k, '%Y%m%d%H%M') if timest.hour not in range(6,19): ...
import csv import pdb from datetime import date, datetime import json from movie_tracker.models import * import pandas as pd import tmdbsimple as tmdb MOVIES = 'tmdb-5000-movie-dataset/tmdb_5000_movies.csv' CREDITS = 'tmdb-5000-movie-dataset/tmdb_5000_credits.csv' tmdb.API_KEY = '3cfdb6d49ad9aa0736b9e2c49d6b20ab' sea...
import requests r = requests.get("http://192.168.1.178:4567/mark") print(r)
__author__ = "Narwhale" # import time # # for i in range(1,21): # print(i) # # # #---------------------------- # # ls = [i for i in range(1,1000001)] # # print(type(ls)) # # for r in ls: # # print(r) # # starttime = time.time() # s = sum(ls) # stoptime = time.time() # t =stoptime - starttime # print(sum(ls)) ...
from app import app, db from app.model_types import GUID from sqlalchemy.sql import func from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import event from sqlalchemy.orm.attributes import InstrumentedAttribute from Crypto.Cipher import AES import binascii import uuid import frontmatter import re key...
import urwid from diary import Diary shortcuts = { "save": "ctrl o", "toggle-edit": "ctrl x", "back": "esc", "discard": "ctrl r", } class DiaryWidget(urwid.WidgetWrap): signals = ["close"] def __init__(self, diary: Diary): self._diary = diary w = urwid.WidgetPlaceholder(urwi...
def myFunc (): a = int(input("Введите первое число: ")) b = int(input("Введите второе число: ")) if a < b: print("Плохой негативный текст!") elif a > b: print("Хороший позитивный текст!") else: print("Баланс в природе не нарушен!"); myFunc()
import os import torch from models.resnet import resnet50, resnet101, resnet152 from models.densenet import densenet121, densenet161 from models.senet import senet154, se_resnext101_32x4d, se_resnet101 from models.inception_v4 import inceptionv4 from models.xception import xception from models.inceptionresnetv2 import ...
#Data Types """ Python has multiple data types Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview """ #To get the data type of a variable use the type() method x=5 print(type...
from django.contrib import admin from django.urls import path,include from .views import render_pdf_view,GeneratePdf, generate_pdf urlpatterns = [ path('pdf', render_pdf_view,name='pdf'), path('newpdf', generate_pdf, name='pdf'), path('new', GeneratePdf.as_view(),name='pdf'), ]
import cv2.cv as cv import random im = cv.LoadImage('meinv.jpg') thumb = cv.CreateImage((im.width / 2, im.height / 2), cv.CV_8UC2, 3) cv.Resize(im, thumb) for k in range(5000): i = random.randint(0, thumb.height-1) j = random.randint(0, thumb.width-1) color = (random.randrange(256), random.randrange(256),...
#!/bin/python3 import sys def divisibleSumPairs(n, k, ar): count = 0 arrPairs = [] for x in range(len(ar)): j = 1 while j < len(ar): pair = [] if x < j and ((ar[x] + ar[j]) % k == 0): pair.append(x) pair.append(j) i...
import cv2 as cv2 import numpy as np image = cv2.imread('filtr.jpg') b,g,r = cv2.split(image.copy()) _, contours, hierarchy = cv2.findContours(b, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnt = contours[0] img=image.copy() for c in contours: x,y,w,h = cv2.boundingRect(c) img+=cv2.rectangle(image,(x,y),(x+w,y+h),(243,2...
from collections import OrderedDict from datetime import datetime from uuid import uuid4 from django.contrib import messages from django.core.urlresolvers import reverse, reverse_lazy from django.shortcuts import render, get_object_or_404 from django.http import Http404 from django.http.response import HttpResponse, H...
#!/usr/bin/env python from asyncdnspy.dns_message_header import Header from asyncdnspy.dns_message_question import Question from asyncdnspy.dns_message_resourcerecord import ResourceRecord class DNSMessage(object): __header = None __questions = None __answers = None __authority = None __addition...
#!/usr/bin/env python3 if __name__ == '__main__': x = int(raw_input()) y = int(raw_input()) z = int(raw_input()) n = int(raw_input()) print([[i, j, k] for i in range(0, x+1) for j in range(0, y+1) for k in range(0, z+1) if i + j + k != n])
import math add_up = lambda x, y: x + y print(add_up(2, 5)) first_time = lambda my_list: my_list[0] print(first_time(['cat', 'dog', 'mouse'])) names = ['Magda', 'Jose', 'Anne'] lengths = [] lengths = list(map(len, names)) print(sum(lengths) / len(lengths)) nums = [-3, -5, 1, 4] print(list(map(lambda x: 1 / (1 ...
# ****************************************************************** # # ************************* Byte of Python ************************* # # ****************************************************************** # ######################## # backup_ver1 ######################## # import os # import time # sou...
import numpy as np x_stop = -2.5 x_brake = -38.5 def braking_spec(time_gap, speed, x_stop=x_stop, x_brake=x_brake): if x_brake >= x_stop: return 0, np.inf, np.inf v0 = speed x0 = -time_gap*v0 brake_dist = x_stop - x_brake a = -v0**2/(2*brake_dist) brake_dur = -v0/a t_b...
#!/usr/bin/env python from importlib import * is_package("os") # ImportError
''' 152. Maximum Product Subarray Medium Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6. Example 2: Input: [-2,0,-1] Output: 0 Explanation: T...
"""Top-level project Main function.""" import sys import pickle import xmlSheetSearch import xmlStaticOperators sys.path.append('../../../runtime_data/') import RunTimeData def main(): """Top-level project Main function.""" def construct_paths(lower_bound, upper_bound): """Construct list of file pat...
#!/usr/bin/env python3 # # This file is part of LUNA. # # Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com> # SPDX-License-Identifier: BSD-3-Clause import os from amaranth import Elaboratable, Module, Signal from usb_protocol.types import USBTransferType from usb_pr...
import unittest from katas.kyu_8.validate_code_with_simple_regex import validate_code class ValidateCodeTestCase(unittest.TestCase): def test_true(self): self.assertTrue(validate_code(123)) def test_true_2(self): self.assertTrue(validate_code(248)) def test_true_3(self): self.as...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Base [TrendAV]', 'version': '1.0.1', 'category': 'Hidden', 'author': 'Ing. Rigoberto Martínez', 'maintainer': 'TrendAV', 'website': 'http://www.trendav.com', 'sequence': 1, 'de...
import os import sys import logging import datetime import collections from api import ApiClient import auth from utils import * from .remotecontent import get_remote_content_loader import db from flask import Flask, render_template, request, \ abort, g, session app = Flask("BlockedFrontend", subdomain_matchin...
class house(): house_type = 'dwelling' location = 'terrestrial' def __init__(self, name, material, size, storeys): self.name = name self.material = material self.size = size self.storeys = storeys def get_mat(self): return self.material def get_size(self):...
from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('authsystem.urls', namespace = 'auth')), path('home/', include('home.urls', namespace = 'home'...
# Generated by Django 3.1.7 on 2021-03-24 13:58 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='systemuser', ...
from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import AbstractUser class DiskUser(AbstractUser): class Meta(AbstractUser.Meta): pass
#!/usr/bin/env python from lab_mc import experiments, null_experiment from lab_defs import teaching_length from weeks import all_dates from loadstore import load_pairs from assign_students import get_students, match_students from get_students_by_week import get_students_by_pair, get_pairs_by_week from sys import argv ...
def merge(line): length = len(line) prev = -1 result = [] for i, a in enumerate(line): if a == 0: continue elif prev < 0: prev = a if length == i + 1: result.append(a) elif a == prev: result.append(a * 2) ...
from rest_framework import serializers from .models import Comments class CommentsSerializer(serializers.ModelSerializer): """Serializers for comments""" class Meta: model = Comments fields = ('id', 'content', 'name', 'email', 'created_at', 'parent', 'user', 'post') read_only_fields =...
from flask import Flask from flask_restful import reqparse, abort, Api, Resource from collections import OrderedDict from flask_restful import fields, marshal_with app = Flask(__name__) api = Api(app) TODOS = { 'todo1': {'task': 'build an API'}, 'todo2': {'task': '???'}, 'todo3': {'task': 'profit!'}, } ...
import pygame print("Program Starting...") pygame.init() display_height = 720 display_width = 1280 displayWindow = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption("Test") clock = pygame.time.Clock() black = [0, 0, 0] white = [255, 255, 255] grey = [20, 20, 20] running = True presse...
import fileinput class KeyMapper(object): def __init__(self): self._build_keymap() self._build_wordtrie() def _build_keymap(self): self.keymapping = {} keys = {'2' : 'ABC', '3' : 'DEF', '4' : 'GHI', ...
import ex12_2 from tabulate import tabulate ipaddress_test_list = ['10.0.4.1','10.0.1.68-10.0.1.72', '10.0.2.2', '192.168.2.14-20'] def ip_table(reachable_list, unreachable_list): dict_ipaddress = {'Reachable':[], 'Unreachable':[]} for ipaddress in reachable_list: dict_ipaddress['Reachable'].append(ipaddress) fo...
import asyncio from unittest.mock import Mock import pytest from sc2.ids.unit_typeid import UnitTypeId from sc2.unit import Unit from .context import add_unit_to_bot, initial_bot_state @pytest.mark.asyncio async def test_does_nothing_on_empty_bo(): bot = initial_bot_state([]) await bot.on_step(0) @pytest....
from . import character from . import alliance from . import corporation
def download(): """ Downloads ESA list from the ESRD site""" import ftplib # Connect to FTP Client and cd to directory containing brownfields` ftp = ftplib.FTP('ftp.gov.ab.ca') ftp.login() ftp.cwd('/env/ESAR') # Create a list of all ESA entries # Note: Each index in the l...
########### sample of calling FaceAPI from Python 3.6 ############# ## @fujute : March4,2018 ## This is modified version from original code from " https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236 " ## import http.client, urllib.request, urllib.parse,...
from script.base_api.service_user.masterKey import * from script.base_api.service_user.permission_groups import * from script.base_api.service_user.verificationCode import * from script.base_api.service_user.teachers import * from script.base_api.service_user.metrics import * from script.base_api.service_user.ding...
from django.db import models from mongoengine import Document, StringField, DictField class Researcher(Document): lattes_id = StringField() researcher_cv = DictField() def __unicode__(self): return self.lattes_id
""" Convenience class to help accomplish common tasks with the Roomba. Created on Oct 13, 2015. Written by: Valerie Galluzzi, Mark Hays, and Muqing Zheng. """ # TODO 1: write your name above import safest_create as create import time def main(): """ Calls the TEST functions in this module. """ # TODO 2:...
import re # open paragraph f = open("paragraph_2.txt", "r") # breaks into sentences sentences = re.split(r"[.!?;]", f.read()) # initialize lists & variables sentence = [] words = [] word_count = 0 character_count = 0 # split into words for i in range(0, len(sentences) - 1): sentence.append(sentences[i]) wor...
import pandas as pd from datetime import date from os import path from tkinter import * from tkinter import ttk from tkcalendar import DateEntry from Echo import Echo from util import * class Client(ttk.Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent se...
from .forum_views import bp_forum from app.models import User from app import db IDENTIFIER = "forum" NAME = "Forum Plugin" VERSION = "v0.1" AUTHOR = "Asyks @ EU-Blackhand" def init(): setattr(User, "forum_replies", db.relationship("ForumReply", backref="user", lazy="dynamic")) def install(): setattr(User,...
def sayhi(): print("Hello User") #this function will print Hello User print("Top") sayhi() print("Bottom") def say_hi(name): print("Hello " + name) say_hi("Mike") say_hi("Steve") def say_hi_with_age(name, age): print("Hello " + name + ", you are " + age) say_hi_with_age("Mike", "3...
from ixnetwork_restpy import SessionAssistant session_assistant = SessionAssistant(IpAddress='172.31.194.141', LogLevel=SessionAssistant.LOGLEVEL_INFO, ClearConfig=True) ixnetwork = session_assistant.Ixnetwork #create vport to physical port mapping using PortMapAssistant port_map = session_assistant.PortMa...
class Queue: def __init__(self): self.queue = [] # инициализация хранилища данных def enqueue(self, item): self.queue.insert(0,item) # вставка в хвост def dequeue(self): if self.size() < 1: return None # если стек пустой return self.queue.pop(self....
""" This function allows you to query your Wallet balance. If you enable notify by email, you will receive an email every time the url is called with your APP Key. URL : https://greydotapi.me/?k=[APP Key]&do=[FID] [**APP Key**] Your APP Key [**FID**]The function ID for Wallet balance is 2 Example url : https://gre...
# @Time :2019/8/4 10:41 # @Author :jinbiao from Python_0802_job.ddt import ddt, data import unittest from Python_0802_job.operation_log import log from Python_0802_job import operation_config from Python_0802_job import operation_excel from Python_0802_job import send_request @ddt class TestRegister(unittest.TestCas...
import time import datetime from huey import RedisHuey, crontab from extractors import data_collector from model import Crypto, db huey = RedisHuey('jobs', host='localhost', port=6379) @huey.periodic_task(crontab(minute='*/1')) def request_coin_price(): coin_prices = data_collector() with db.atomic(): ...
from decimal import Decimal, getcontext from django.utils.text import slugify from django.db import models from django.contrib.auth.models import User from django.urls import reverse from apps.basic import dictionary mm_ft = 304.8 cm_inch = 0.39370079 class ProfileMaster(models.Model): group_id = models.CharFie...
# coding utf-8 from data_helpers import words from word2vec import w2vm from data_split import pre_train, pre_evl pre_train() pre_evl() words.cut_train_file() words.cut_test_file() words.clean_words_file() w2v = w2vm.train_model()
# Write a function that calculates the average over all elements in a matrix. import numpy as np def avemat(a): numbers = [] for x in np.nditer(a): numbers.append(x) return sum(numbers)/len(numbers)
from datetime import datetime from collections import defaultdict def solution(input): input = sorted(input, key=lambda x: x[0]) guard = None guard_states = defaultdict(lambda: defaultdict(int)) for i, (dt, msg) in enumerate(input): if '#' in msg: guard = int(msg.split()[1][1:]) ...