text
stringlengths
38
1.54M
import logging from collections import deque from combo import Combo from ability import Ability class Rotation(): deck = deque() def use(self, action): """ This method is designed for fully formed combos that manage their own hotkey callbacks and doesn't require a copy to be made. ...
import png from node import Node from color import Color # Takes in a color list and creates a png def listToPNG(colorList, directory, filename): # Create a writer object picheight = 80 # the height of the pic bandwidth = 2 # The width each color gets outputer = png.Writer(size=(bandwidth*len(colorList), picheigh...
#!/usr/bin/python import sys import sip from PyQt4.Qt import * #wrap raw pointer to specified Qt-class def wrap(type, ptr): return sip.wrapinstance(ptr, type) #def main(): # ts_raw - loaded from C++ environment print("raw value:", ts_raw); ts_wrapped = ts_raw; ts_wrapped.trigger_str("hello from python!") app = ...
# import the random module import random while(True): # creating a loop because user can play this game as his or her wish times print("Dear user you have option!, they are:") print("'rock','paper','scissors'") # take input from the user using input() function in python. # Then create the computer choice ...
import tensorflow as tf import numpy as np c = tf.constant([[1,2,3], [4,5,6]]) print("Python list input: {}".format(c.get_shape())) c = tf.constant([[[1,2,3],[4,5,6]], [[1,1,1], [2,2,2]]]) print("3d NumPy array Input: {}".format(c.get_shape())) # One method to avoid constantly refe...
def currentModule(request): from django.conf import settings from menu.models import Entry # Get candidates and current path candidates = [] for menuEntry in Entry.objects.all(): candidates.append({ 'name': menuEntry.name, 'path': menuEntry.path, }) path ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-02 21:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('eBedTrack', '0004_auto_20171002_1140'), ] operations = [ migrations.AlterFi...
from codetiming import Timer # code snippet which using decorators to calculate function execution time # the code prints Elapsed Time - saying hello: 0.0001265000000000016 secs @Timer(name='saying hello', text='Elapsed Time - {name}: {} secs') def say_hello(): print('Hello World!') say_hello()
import argparse import torch import torch.nn as nn import torch.nn.functional as F class RejectionCrossEntropyLoss(nn.Module): """ Based on https://arxiv.org/pdf/1907.00208.pdf o (payoff) should be between 1 < o < num_classes """ def __init__(self, o, out_vocab, rejection_index, reduction="none"...
import requests from bs4 import BeautifulSoup from datetime import datetime, timedelta import locale locale.setlocale(locale.LC_ALL, 'ID') import re import pandas as pd from selenium import webdriver from selenium.webdriver.chrome.options import Options import html import json import time from requests.exceptions impor...
# Generated by Django 3.2.3 on 2021-05-31 13:56 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bis', '0001_initial'), ] operations = [ migrations.CreateModel( name='Hizlaria', fi...
from common import db, ma from flask import jsonify from flask_restful import Resource # reading workload simple class ReadingWorkloadSimple(db.Model): id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(10)) amount = db.Column(db.Float) intercept = db.Column(db.Float) def __i...
#### This problem will be graded manually. #### Please ignore the points given out by Tutor. def addRowMulByC(matA,i,c,j): nl =[] nnl = [] for k in matA[i]: nl.append(k*c) for c in range(len(matA[0])): nnl.append(matA[j][c]+nl[c]) del matA[j] matA.insert(j,nnl) r...
# -------------------------------------------------------------- # # Daily Code 03/04/2021 # "Name Greeting!" Lesson from edabit.com # Coded by: Banehowl # -------------------------------------------------------------- # Create a function that takes a name and returns a greeting in the form of a string. #...
__author__ = 'tan' import socket import fcntl import struct from juliabox.jbox_util import LoggerMixin, JBoxPluginType, JBoxCfg import random class JBPluginCloud(LoggerMixin): """ Interfaces with cloud service providers or provides similar services locally. - `JBPluginCloud.JBP_BUCKETSTORE`, `JBPluginCloud....
WHITE = (255, 255, 255) BLACK = (0, 0, 0) DARKGREY = (40, 40, 40) LIGHTGREY = (100, 100, 100) GREEN = (0, 255, 0) DARKGREEN = (160, 255, 160) RED = (255, 0, 0) YELLOW = (255, 255, 0) BLUE = (0, 0, 255) NIGHT_COLOR = (20, 20, 20) LIGHT_RADIUS = (500, 500) LIGHT_MASK = "light_350_soft.png" WIDTH = 1024 HEIGHT = 768...
import functools @functools.lru_cache(maxsize=2) def expensive(a, b): print('called expensive({}, {})'.format(a, b)) return a * b def make_call(a, b): print('({}, {})'.format(a, b), end=' ') pre_hits = expensive.cache_info().hits expensive(a, b) post_hits = expensive.cache_info().hits if...
from django.shortcuts import render, redirect from .models import Order, Product from django.db.models import Sum def index(request): context = { "all_products": Product.objects.all() } return render(request, "store/index.html", context) def buy(request): quantity_from_form = int(request.POST[...
import pygame pygame.init() # initialize # set the size of screen screen_width = 480 # width size screen_height = 640 # height size screen = pygame.display.set_mode((screen_width, screen_height)) # set the title of game pygame.display.set_caption("Nado Game") # game title # FPS clock = pygame.time.Clock() # L...
''' Experiment class for unified model ''' import config import torch from experiment import Experiment from torch import nn from misc import unified_ans_acc, calc_bleu_scores_unified from itertools import cycle class ExperimentUnified( Experiment ): def __init__( self, args ): super(ExperimentUnified, s...
# -*- coding: utf-8 -*- import re from openerp import api, models, _ from openerp.exceptions import UserError class ResBank(models.Model): _inherit = 'res.bank' @api.one @api.constrains('bic') def _check_bic(self): # ISO 9362:2009 bic_check = re.compile(r'^[A-Z]{4}[A-Z]{2}[A-Z0-9]{2...
from django.http import HttpRequest from django.urls import resolve from django.test import TestCase from .views import home_page class HomePageTest(TestCase): def test_root_url_resolves_to_home_page_view(self): self.assertEqual(resolve('/').func, home_page) def test_home_page_returns_welcome_html(s...
# coding:utf-8 import matplotlib import numpy as np import matplotlib.pyplot as plt import cv2 #ファイルの入出力 file = open("file.txt","r") for line in file: print(line) file = open("file.txt", "w") file.write("Hello world") file.write("This is out new text file") file.write("and this is another line.") file.close() pri...
def rotate_array(array, N): if N == 0: return if N > 0: while N > 0: # TOREAD: insert(position, value) # this is perpend array.insert(0, array.pop()) N -= 1 return if N < 0: while N < 0: array.append(array.pop(0)) ...
def to_c(from_f): celsius = (from_f - 32) * (5 / 9) return celsius # Main Routine temperatures = [0, 40, 100] converted = [] for item in temperatures: answer = to_c(item) ans_statement = "{} degrees C is {} degrees F".format(item, answer) converted.append(ans_statement) print(converted)
def matrix_mul(a, b): m = len(a) # number of rows of A n = len(a[0]) # number of cols of A r = len(b) # number of rows of B s = len(b[0]) # number of cols of B c = [[0] * s for _ in range(m)] # allocate empty result # cycle over all the rows of C (== rows of A) for i in range(m): ...
import re import sys import shutil from subprocess import check_call from setuptools import setup, find_packages if sys.argv[-1] == 'cheeseit!': check_call('nosetests -v') check_call('python setup.py sdist bdist_wheel') check_call('twine upload dist/*') shutil.rmtree('dist') sys.exit() elif sys.ar...
import unittest from com.ea.pages import fangkuan_taizhang_report_page from com.ea.common import tools, web_login from com.ea.resource import globalparameter as gl import time import os import sys class MyTestCase(unittest.TestCase): u"""贷款审批报表""" screenshot_path = os.path.join(gl.screenshot_path, os.path.spl...
import unittest import os from dotenv import load_dotenv import nlpaug.augmenter.audio as naa from nlpaug.util import AudioLoader class TestAudio(unittest.TestCase): @classmethod def setUpClass(cls): env_config_path = os.path.abspath( os.path.join(os.path.dirname(__file__), "..", "..", "....
""" Utility methods. - Methods: - clean_array: returns input array with nan and infinite values removed - controlled_compute: performs computation with Dask - rescale_array: performs edge trimming on values of the input vector - show_progress: performs computation with Dask and shows progress bar -...
import logging import os from evaluator import unit from evaluator.attributes import UNDEFINED from evaluator.datasets import MeasurementSource, PhysicalPropertyDataSet, PropertyPhase from evaluator.properties import EnthalpyOfVaporization from evaluator.substances import Substance from evaluator.thermodynamics import...
from notebook.notebookapp import NotebookApp, flags from traitlets import Unicode from .config import NteractConfig nteract_flags = dict(flags) nteract_flags['dev'] = ( {'NteractConfig': {'asset_url':'http://localhost:8080/'}}, "Start nteract in dev mode, running off your source code, with hot reloads." ) cl...
"""A UnitTestController Module.""" from masonite.request import Request from masonite.controllers import Controller class UnitTestController(Controller): """UnitTestController Controller Class.""" def __init__(self, request: Request): """UnitTestController Initializer Arguments: ...
import png import zlib import string def get_decompressed_data(filename): img = png.Reader(filename) for chunk in img.chunks(): if chunk[0] == "IDAT": print len(chunk[1]) return zlib.decompress(chunk[1]) data = get_decompressed_data("ninth.png") len_data = str(len(data)) print ...
def mutate_string(string, position, character): l = list(string) l[position]=character s="" s=s.join(l) return s
#Leetcode 682. Baseball Game class Solution: def calPoints(self, ops: List[str]) -> int: result = [] for i in ops: if i == "C": del result[-1] elif i == "D": result.append(2*int(result[-1])) elif i == "+": ...
#!/usr/bin/env python3 # LoRaMaDoR (LoRa-based mesh network for hams) project # Mesh network simulator / routing algorithms testbed # Copyright (c) 2019 PU5EPX # Modifiers of packets that are going to be forwarded class Rreqi: @staticmethod def match(pkt): return ("RREQ" in pkt.params or "RRSP" in pkt.params) an...
import sys, os reader=open("Input5000fa","r") writer=open("corpusFile.txt","w") x=reader.readlines() for i in range(1,len(x)): line = x[i].strip("\n") ids = line.split("- ",1)[0] sen = line.split("- ",1)[1] size = len(sen.split(" ")) print ids + " " + str(size)
name = input('enter a file name') try: fin = open(name) except: print('file cannot open ', name) exit() r = dict() for line in fin: line = line.rstrip() for w in line.split(): r[w] = r.get(w, 0) + 1 print(r)
from bs4 import BeautifulSoup import requests import time import os def get_time_slot(path, locations): for id in locations: url = path + str(id) response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') try: appt_list = soup.find(id='timeslots'...
#!/usr/bin/env python3 """Compare Strings by Count of Characters. Create a function that takes two strings as arguments and return either True or False depending on whether the total number of characters in the first string is equal to the total number of characters in the second string. Source: https://edabit.com/c...
import AuthenticationServices from PyObjCTools.TestSupport import TestCase, min_sdk_level import objc class TestASAuthorizationProviderExtensionRegistrationHandlerHelper( AuthenticationServices.NSObject ): def beginDeviceRegistrationUsingLoginManager_options_completion_(self, a, b, c): pass def b...
from IPython import embed # Load the Pima Indians diabetes dataset from CSV URL import numpy as np import pandas as pd import urllib import matplotlib import pylab import matplotlib.pyplot as plt from pandas import DataFrame df = pd.read_csv('users 3.csv') embed() #df.plot(x='followers_count', y='followings_count', s...
import unittest import os from python.housinginsights.ingestion.Cleaners import ProjectCleaner, PYTHON_PATH from python.housinginsights.ingestion.Manifest import Manifest from python.housinginsights.ingestion.functions import load_meta_data class CleanerTestCase(unittest.TestCase): def setUp(self): # use ...
import datetime from decimal import Decimal from django.test import TestCase from django.utils.timezone import make_aware from chat_wars_database.app.business_exchange.management.commands.calculate_statistics import apply_regex_for_each_line from chat_wars_database.app.business_exchange.management.commands.calculate_...
from flask import Blueprint tagsBP = Blueprint('tagsBlueprint', __name__) tagsAdminBP = Blueprint('tagsAdminBlueprint', __name__) tagsApiBP = Blueprint('tagsAPIBlueprint', __name__) from . import views,admin,api
# *** RECURSOS *** import time import msvcrt import random as ran from os import system # *** FUNCIONES BASE *** def clean(): # Limpia la consola system("cls") def time1(var): # Pausa de tiempo time.sleep(var) # *** DATOS *** # Intro intro = ("El juego consiste en un tablero...
#!/usr/bin/env python import os import re import sys from prettytable import PrettyTable # Paths script_root_directory = sys.path[0] nmap_output_path = script_root_directory + "/nmap_output.txt" dictionary_ref_path = script_root_directory + "/dictionary_reference.txt" # Configuration ip_range = "10.0.0.1-20" ip_rang...
from Simulator import Simulator, Packet, EventEntity from enum import Enum from struct import pack, unpack import sys # In this class you will implement a full-duplex Go-Back-N client. Full-duplex means that this client can # both send and receive data. You are responsible for implementing a Go-Back-N protoco...
#EJERCICIO 8 numCliente = input("Ingrese número de cliente: ") facturaTotal = int(input("Ingrese el total de la factura: ")) descuento = (facturaTotal * 2)/100 interes = (facturaTotal * 10)/100 if(120 < descuento): importeDescuento = facturaTotal - 120 else: importeDescuento = facturaTotal - descuento if(1...
# coding: utf-8 from ConfigParser import ConfigParser from datetime import datetime import requests import matplotlib.pyplot as plt from watson_developer_cloud import AlchemyLanguageV1 as alchemy class Sentimental(): def __init__(self): self.alchemy_client = self._get_alchemy_client() self.prev...
#!/usr/bin/env python # # Major mods by Roger Burnham January 2012 # from the rov_joystick module started by Steve Phillips # import argparse import logging import platform import pygame import serial import sys import time from ArduinoPorts import findServoPort from math import floor sysPlatform = platform.system() ...
import urllib2, urllib, json, csv import scraperwiki headers = {'X-Requested-With': 'XMLHttpRequest'} data = urllib.urlencode({ 'Position': '0,0', 'Bounds': '-100,-100,100,100', }) url = 'https://www.greggs.co.uk/home/shop-finder' # run the request raw_res = urllib2.urlopen(urllib2.Request( url, data...
import urllib.request, json from .models import News_Update from .models import Article api_key = None base_url = None articles_url = None def configure_request(app): global api_key, base_url, articles_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] articles_url =...
from threading import RLock from typing import Any, Callable, Dict, List, Optional import optuna from optuna.study import Study from tune import ( Choice, NonIterativeObjectiveFunc, NonIterativeObjectiveLocalOptimizer, Rand, RandInt, TransitionChoice, Trial, TrialReport, ) from tune._ut...
''' Когда Павел учился в школе, он запоминал таблицу умножения прямоугольными блоками. Для тренировок ему бы очень пригодилась программа, которая показывала бы блок таблицы умножения. Напишите программу, на вход которой даются четыре числа a, b, c и d, каждое в своей строке. Программа должна вывести фрагмент таблицы у...
obs_functions = [ # lambda x, v: math.pow(x, 2) / 20 + v, # lambda x, v: math.pow(x, 2) / 20 + v, # lambda x, v: math.pow(x, 2) / 20 + v lambda x, v: x / 2 + v, lambda x, v: x / 2 + v, lambda x, v: x / 2 + v ]
def rm(nums, con): for i in con: nums.remove(i) def check(nums, index, value, con): if index >= len(nums) or value < nums[index]: return False elif nums[index]==value: con.append(nums[index]) return True elif check(nums, index+1, value, con)==True: return True ...
### List lst = [1,2,"ram","tom",1.3,7+2j,True,"A"] #making a list (using square brackets) lst[2] # accessing a list element lst[2:] # accessing multiple list elements together lst[2]="rem" # updating an element cities = [[1,2,3],[5,[4,6,7],8],9] cities[1][1][1] #inherent index accessing # List methods lst.append...
from django.conf import settings from django.db import models from django.utils import timezone class job (models.Model): job_title = models.CharField('Заголовок', max_length=200) job_list = models.TextField('Текст') def __str__(self): return self.job_title class Meta: verbose_name = '...
import scrapy #run file by 'scrapy crawl <name_of_the_spider> -o <output_file_name>.json' class EventSpider(scrapy.Spider): name = "event" #every spider needs a name def start_requests(self): url = "https://www.tapology.com/fightcenter/events/54138-ufc-fight-night-143" yield scrapy.Request(url...
import functools from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, make_response ) from flask_adventure_game.map import Map from flask_adventure_game.lexicon import scan bp = Blueprint('engine', __name__) @bp.route('/', methods=('GET', 'POST')) def game(): if (req...
def format_number(s): new_s = '' for c in s: if c.isdigit() or c in (',', '.'): if c == ',': new_s += '.' else: new_s += c return new_s
# addition print "5+4=",5+4 # subtraction print "5-4=",5-4 # division print "5/4=",5/4 # multiplication print "5*4=",5*4 # modulo print "5%4=",5%4 # less than print "Is 5<4?",5<4 # greater than print "Is 5>4?",5>4 # less than or equal to print "Is 5<=4?",5<=4 # greater than or equal to print "Is 5>=4?",5>=4
""" Test atom.py Example feed: <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Example Feed</title> <link href="http://example.org/"/> <updated>2003-12-13T18:30:02Z</updated> <author> <name>John Doe</name> </author> <generator uri="/myblog.php" version="1.0">...
#-----------------------------------------------------METHOD 1--------------------------------------------------------------------# def height(root): if not root: return 0 return 1 + max(height(root.left),height(root.right)) def printLeftView(root,level,flag): if root and not flag[0]: i...
#Ch.2: Challenge 2 # Favorite foods program def fav_food(): fav_food1 = input("Enter your favorite food: ") fav_food2 = input("Enter your second favorite food: ") combined = fav_food1 + fav_food2 print("\nYour favorite foods combined equals", combined.replace(" ", "")) fav_food()
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html from datetime import datetime from scrapy.item import Field from scrapy.item import Item from scrapy.loader.processors import MapCompose from scrapy.loader.processors i...
import unittest from my_dict import Dict class TestDict(unittest.TestCase): def test_init(self): d = Dict(a = 1,b = 'test') self.assertEqual(d.a,1) self.assertEqual(d.b,'test') self.assertTrue(isinstance(d,dict)) def test_key(self): d = Dict() d['hong'] = 1 ...
from sanic.response import json, text from sanic import Blueprint bp_cookie = Blueprint('cookie_blueprint', url_prefix='/cookie') @bp_cookie.route('/') async def bp_root(request): return json({'Bluprint': 'cookie'}) @bp_cookie.route('/set') async def set_cookie(request): response = text("There's a cookie up ...
#MenuTitle: 擴大選取範圍到完整外框 # -*- coding: utf-8 -*- # # (c) But Ko, 2021. # https://zi-hi.com/ # https://github.com/ButTaiwan/GlyphsTools # https://www.facebook.com/groups/glyphszhtw # from GlyphsApp import Glyphs if Glyphs.font.selectedLayers is not None and len(Glyphs.font.selectedLayers) == 1: layer = Glyphs.font.se...
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 21:12:57 2018 @author: praveen kumar """ #Grid search # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('C:/Users/praveen/Desktop/machine-learning udemy a-z/Machi...
import logging logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO) class PanCalculator: def __init__(self, fov, image_width): self.__fov = fov self.__image_width = image_width self.__gradient = (fov / float(image_width)) self.__camera_x = image_width / 2.0 ...
import re import numpy as np import sys TIME_UNIT = 1e-06 FILE_SIZE = 1024 PATTERN = '[1-9][0-9]+' with open(sys.argv[1], 'r') as f: # first line is the thread number s = f.readline() thread_num = int(s) # every thread_num lines we find a maximum second count = 0 total_arr = [] tmp_ls...
N = int(input()) answer_list = [input() for _ in range(N)] my_set = set(answer_list) answer_list = list(my_set) answer_list.sort() # 사전순 정렬 answer_list.sort(key=lambda x: len(x)) for i in answer_list: print(i, end='\n')
k= 0 #Coefficient de raideur du ressort l0= 0 #Longueur a vide m= 0 #Masse d'une maille dt= 0.01 class Vec3f: def __init__(self): self.x = 0 self.y = 0 self.z = 0 def dot_product(self, vec): return self.x*vec.x + self.y*vec.y + self.z*vec.z def cross_product(self, vec): ret = Vec3f() ret.x =...
from django import forms from django.core.exceptions import ValidationError from django.db.models import fields from .models import * from django.utils.translation import ugettext_lazy as _ class ArticleForm(forms.ModelForm): class Meta: model = blogs fields = "__all__" class SignupForm(forms....
"""Flower: Celery monitoring and management app Usage: celery-flower.py [options] Options: -h --help Show this screen. """ from web_backend.server import IUBackendService from web_backend.server import ConfigParser from web_backend.server import CONFIG_FILE as SERVER_CONFIG_FILE from docopt ...
import pandas as pd import numpy as np data = { 'group': np.random.randint(1,5,(100,)), 'actual': np.random.random((100,)), 'predict': np.random.random((100,)), } # np.random.random((20,)) # np.random.randint(1,5,(20,)) df = pd.DataFrame(data) df = df.sort_values(["group", "predict"], ascending=[True, True]...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'schedular.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, Qt...
class state(): name = "" transition = [] def __init__(self, name): self.name = name self.transition = [] def setTransition(self, transition): self.transition.append(transition) class transition(): end = "" events = [] def __init__(self, end): self.end = en...
# -*- coding: utf-8 -*- import json undefined = object() class JSONFormEncoder(json.JSONEncoder): def default(self, obj): if obj == undefined: return None else: return super(JSONFormEncoder, self).default(obj) def parse_path(path): """ http://www.w3.org/TR/2014/W...
"""This file contains 2 functions to multiprocessor analysis""" from myfunction import * from netCDF4 import Dataset import urlparse import csv import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt from matplotlib.patches import Polygon as po from matplotlib.collections import PatchCollection from sh...
# !/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/11/29 18:09 # @Author : duanhaobin # @File : douban_book_data_collection.py # @Software: PyCharm # @desc: 豆瓣图书数据采集练习 # 爬虫逻辑:【分页网页url采集】-【数据信息网页url采集】-【数据采集】 import requests import time from bs4 import BeautifulSoup def get_urls(n): '...
#산술 연산자 : +, =, *, /, //, %, ** #문제 10000초는 몇시간 몇분 몇초인가? s=10000 m=s//60 M=s//60%60 r=s%60 h=m//60 print('{0}시간 {1}분 {2}초,'.format(h,M,r)) #산술연산자 우선순위 : () # 지수** # 곱셈, 나눗셈, 나머지, 몫 # 덧셈, 뺄셈 #할당 연산자 : = #대입 연산자 : +=, -=, *=, /=, //=, %=, **= a=100 a = a + 10 # a += 10 a = a + 10 a = a + 10 sum = 1 sum = sum + 2 # 1+2 s...
from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) # nickname = models.CharField(max_length = 50) # I added without DataBase settings # Unless nickname is deleted, it occurs errors when using queryset. ...
# Course: CS261 - Data Structures # Student Name: Jordan Hendricks # Assignment: # Description: class Stack: """ Class implementing STACK ADT. Supported methods are: push, pop, top, is_empty DO NOT CHANGE THIS CLASS IN ANY WAY YOU ARE ALLOWED TO CREATE AND USE OBJECTS OF THIS CLASS IN YOUR SOLUTI...
#!/usr/bin/env python # -*- coding:utf-8 -*- # !/usr/bin/env python # -*- coding:utf-8 -*- def main(): MAX = 9999999999 N, P = map(int, input().strip().split()) table = list(map(int, input().strip().split())) dp = [MAX] * N for i in range(N - 1, -1, -1): if table[i] == 0: dp[i]...
# This file is part of spot_motion_monitor. # # Developed for LSST System Integration, Test and Commissioning. # # See the LICENSE file at the top-level directory of this distribution # for details of code ownership. # # Use of this source code is governed by a 3-clause BSD-style # license that can be found in the LICE...
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8 from selenium.common.exceptions import WebDriverException from selenium.webdriver.remote.webelement import WebElement class TextBox(WebElement): def __init__(self, textBoxWebElement): super(TextBox, self).__init__(textBoxWebElement.parent, textBoxWebEle...
""" Pre-Programming 61 Solution By Teerapat Kraisrisirikul """ def main(): """ Main function """ print(function_1()) print(function_2()) print(function_1()) print(function_2()) print(function_3()) print(function_1()) print(function_2()) print(function_1()) print(function_2()) ...
from django.db import models from accounts.models import User, Project class Scrum(models.Model): """ User's scrum report model """ date_created = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delet...
import dpkt import socket import json import collections as cl import re def main(): # define node f = open ("/root/pcap/cbnoc_node.json") json_data = json.load(f) # read pcap filename = u'/root/pcap/test.pcap' pcr = dpkt.pcap.Reader(open(filename,'rb')) packet_count = 0 flow_list = ...
# -*- coding: utf-8 -*- import xbmc import os import time import shutil import xbmcvfs USERDATA = xbmc.translatePath('special://masterprofile') SMASHINGFOLDER = os.path.join(USERDATA, "smashing") SMASHINGTEMP = os.path.join(USERDATA, "smashing", "smashingtemp") updatefile = os.path.join(SMASHINGTEMP, "miscfiles", "upd...
import pytest from qtpy import PYQT6, PYSIDE6 @pytest.mark.skipif(PYQT6, reason="Not complete in PyQt6") @pytest.mark.skipif(PYSIDE6, reason="Not complete in PySide6") def test_qt3dcore(): """Test the qtpy.Qt3DCore namespace""" Qt3DCore = pytest.importorskip("qtpy.Qt3DCore") assert Qt3DCore.QPropertyValu...
import tempfile import pathlib import asyncio from minikerberos.common.ccache import CCACHE from minikerberos.common.kirbi import Kirbi import pytest import shutil import os from .config import * def test_ccacheroast(): from minikerberos.examples.ccacheroast import ccacheroast ccache = CCACHE() with tempfile.NamedT...
import numpy as np import mnist #Get data set from import matplotlib.pyplot as plt #Graph import tensorflow as tf import timeit from keras.models import Sequential #ANN architecture from keras.layers import Dense #The layers in the ANN from keras.utils import to_categorical from keras.layers import Activation, Dense ...
import json def read_json(path): try: with open(path, 'r') as f: data = json.load(f) return data except FileNotFoundError: return list()
from django.apps import AppConfig class ViewratingsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'viewRatings'
from .base import ( # noqa load_middlewares, ) from .blockchain.base import ( # noqa NoFurtherBlockchainMiddlewares, StopReceiveBallot, BaseBlockchainMiddleware, ) from .consensus.base import ( # noqa NoFurtherConsensusMiddlewares, StopStore, StopBroadcast, BaseConsensusMiddleware, ...