text
stringlengths
38
1.54M
import unittest import os from unittest.mock import MagicMock from . import * class TestProjectEntry(unittest.TestCase): entry = None def setUp(self): entry = ProjectEntry() entry.head_line = '[[Statik:Intern:0589 interner Support]]' entry.content.append('\n\n[*] Ubutu auf Altem lap...
from __future__ import division from __future__ import print_function from builtins import str from builtins import range from builtins import object from past.utils import old_div import sys, time, argparse import tensorflow as tf import numpy as np from sklearn.model_selection import train_test_split from sklearn.met...
import ROOT import lib.plotter import argparse def ParseOption(): parser = argparse.ArgumentParser(description='submit all') parser.add_argument('--t1', dest='tag1', type=str, help='for each plot') parser.add_argument('--t2', dest='tag2', type=str, help='for each plot') parser.add_argument('--plotfile1...
# trainer.py from __future__ import absolute_import from __future__ import division from __future__ import print_function from base.base_dataset import BaseDataset from base.base_logger import BaseLogger from base.base_model import BaseModel from base.base_trainer import BaseTrainer from tqdm import tqdm from typing ...
from django.contrib import admin from holiday.models import Holiday # Register your models here. admin.site.register(Holiday)
#!/var/www/vhosts/munichmakerlab.de/status/env/bin/python import paho.mqtt.client as paho from threading import Timer import logging import os import config PATH=os.path.dirname(os.path.realpath(__file__)) STATUS_FILE= "%s/%s" % (PATH, "current_status") def on_connect(mosq, obj, rc): logging.info("Connect with RC "...
# Generated by Django 2.1 on 2018-08-03 13:31 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_auto_20180727_0304'), ] operations = [ migrations.AlterField( model_name='userprofi...
''' Пользователь вводит трехзначное число. Программа должна сложить цифры, из которых состоит это число. ''' input_number = int(input('Введите трехзначное число')) sum_of_digits = 0 for i in range(3): last_digit = input_number%10 sum_of_digits += last_digit input_number //= 10 print(sum_of_digits)
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 20:30:42 2019 @author: Michael """ import numpy as np import lab3_functions as fun import basic_functions as bf import cv2 # Section 2.2 Testing # Question 1 and 2 # Histogram Equalize img1 = cv2.imread(r"Images\testing\contrast\7.2.01-small.png", 0) img2 = cv2.im...
## Exercício Python 048: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500. s = int(0) for c in range(1, 501, 2): if c % 3 ==0: s = s + c print(c) print('A soma dos números ímpares multiplos de 3 é {}'.format(s))
# -*- coding: utf-8 -*- """ Define SampleTemplates using a Builder pattern """ from typing import Optional, Sequence, Union, List from urllib.parse import urlparse import numbers import datetime as dt from rspace_client.inv.quantity_unit import QuantityUnit class TemplateBuilder: """ Define a SampleTemplate ...
import requests url = 'https://www.ipea.gov.br/geobr/metadata/metadata_gpkg.csv' a = requests.get(url).content # requests.get(url, verify=False) # # content = requests.get(url).content
## Python Project - Section A2 Group 1 - MyMovie ## This is KNN_DecisionTree_Regressions. This contains the functions for working through the KKN and Decision tree regressions. ## Made by Shayne Bement, Jeff Curran, Ghazal Erfani, Naphat Korwanich, and Asvin Sripraiwalsupakit ## Imported by myMovie import pandas as pd...
import numpy def spin_words(sentence): words = sentence.split(" ") output = "" for word in words: aux = word if len(word) > 4: aux = "" while len(word) > 0: aux = word[0] + aux word = word[1:] output += aux + " " output =...
#!/usr/bin/env python import argparse import copy import time import sys import utils from cognition.newest_decision_making import DecisionMaker from location.location import Location from motion.motion_subsystem import MotionSubsystem from radio.radio_subsystem import RadioSubsystem from route.new_path import ...
import numpy as np def redraw_scatter(drawn_object, new_x, new_y): positions = np.vstack((new_x, new_y)).transpose() drawn_object.set_offsets(positions) return None def redraw_line(drawn_line, new_x, new_y): drawn_line.set_xdata(new_x) drawn_line.set_ydata(new_y) return None
import socket as mysoc import sys def fileLineCount(path): with open(path) as fileIn: for index, element in enumerate(fileIn): pass val = index + 1 return val print ('Number of arguments:', len(sys.argv), 'arguments.') print ('Argument List:', str(sys.argv)) # FIRST Socket | to RS server try: rs = mysoc...
from django.shortcuts import render from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from rest_framework import status from rest_framework.decorators import api_view from restapp.models import MyService from restapp.serializers import MyServiceSerializer from restapp.models ...
import os import argparse import random import json import logging import pandas as pd import numpy as np import torch from torch.utils.data import Dataset, DataLoader from collections import defaultdict from transformers import * from utils import seed_everything, DialogueDataset, create_mini_batch, read_test_data ...
#!/usr/bin/env python2 import roslib roslib.load_manifest('mobot_control') import rospy from mobot_control.msg import Keyboard import sys, select, termios, tty msg = """ Reading from the keyboard and Publishing to Keyboard.msg ! --------------------------- (1-7) or shift+(1-7) for position control of the manipulator ...
# 블랙잭 # 쌉 노가다 풀이 def blackJack(): n, m = map(int, input().split()) cards = list(map(int, input().strip().split())) res = 0 for i in range(len(cards)-2): for j in range(i+1,len(cards)-1): for k in range(j+1,len(cards)): sum = cards[i]+cards[j]+cards[k] ...
#!/usr/bin/evn python # coding=utf-8 BROKER_URL = 'redis://127.0.0.1:6379' # 指定 Broker CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # 指定 Backend CELERY_TASK_SERIALIZER = 'msgpack' CELERY_RESULT_SERIALZER = 'json' CELERY_ACCEPT_CONTENT = ['json', 'msgpack'] CELERY_TIMEZONE='Asia/Shanghai'...
import urllib2, json from django.db import models from h1ds_summary.utils import delete_attr_from_summary_table from h1ds_summary.utils import update_attribute_in_summary_table from h1ds_summary.tasks import populate_attribute_task sa_help_text={ 'slug':"Name of the attribute as it appears in the URL.", 'name...
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("tfrecords_dir","./tfrecords/captcha.tfrecords","验证码tfrecords文件") tf.app.flags.DEFINE_string("captcha_dir","../data/Genpics/","验证码图片路径") tf.app.flags.DEFINE_string("letter","ABCDEFGHIJKLMNO...
from odoo import models, fields, api from odoo import http class HelpdeskTicket(models.Model): _inherit = 'helpdesk.ticket' description = fields.Html() attachment_id = fields.One2many('ir.attachment','helpdesk_ticket_ids', string="Attachments") @api.model def default_get(self,default_fiel...
#@author: Bharath HS from PIL import Image from io import BytesIO import os import datetime import sys import time from PIL import Image, ImageChops from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average import traceback import sys class Image_Processing(): #def __init__(...
""" [Homework] 1. Write a Python program to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). e.g. User inputs 5 Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 2. Write a program to sort a dictionary by key in both ascending and descending order. 3. Write a program to s...
#!/usr/bin/python #### print "=========================" print "testing udp using sockets" print "=========================" import socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) print sock.sendto('[{"name":"udp_test", "columns": ["value"], "points":[[69]]}]', ('127.0.0.1', 5454))
#!/usr/bin/python # -*-coding:utf-8-*- # Description: get new user_account info from weixin.sogou.com # Version: 1.0 # History: 2014-07-04 Created by Hou import os import time from threading import Thread from bs4 import * from config import * from connect_with_proxy_ip_and_fake_ua import get_connect_by_proxyip_ua f...
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) # based largely on https://djangosnippets.org/snippets/261 from django.contrib.gis.db import models class Topic...
# Generated by Django 2.2.7 on 2019-11-25 19:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gallery', '0008_auto_20191125_2044'), ] operations = [ migrations.AlterField( model_name='uploadss', name='file', ...
#!/user/bin/env python3 #----------------------------------------------------------------------# # Script Name Ops Challenge 13 # Author Kimberley Cabrera-Boggs # Date of last revision October 21, 2020 # Description of purpose Network Security Tool w/Scapy Part 1, 2 & 3 #----...
# -*- coding:utf-8 -*-# # -------------------------------------------------------------- # NAME: for # Description: for循环 # Author: xuezy # Date: 2020/6/19 17:17 # -------------------------------------------------------------- """ for循环实现1~100求和 range(101) 可以产生一个0~100的整数序列 range(1,100)...
from flask import Flask, request, jsonify import os import logging import time import json app = Flask(__name__) with open('decoder.json') as _file: decoder = json.load(_file) with open('encoded.txt') as _file: encoded_text = _file.read() @app.route("/") def index(): app.logger.info(vars(request)) r...
import errno import socket import select import sys HEADER_LENGTH = 10 IP = '127.0.0.1' PORT = 1234 my_username = input('username: ') client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((IP, PORT)) client_socket.setblocking(False) encoded_username = my_username.encode('utf-8') e...
from nltk.tokenize import sent_tokenize, word_tokenize #nltk.download() #tokenizers #word tokenizer - seperating by word #sentence tokenizer - seperated by sentences #lexicon and corporas #corpora - body of text ex: presenditial speech, a paragraph from your book. #lexicon - word and their mean (dictionary) #words ...
import pygame as py import math import cmath import numpy as np import os import cv2 # Complex number Plane class Plane: # Create a pygame window where different objects can be graph # Plane initialization def __init__(self, grid, center, win_scale): self.rows = grid[0] ...
def fasta_reader(bestand): """Extract sequences from FASTA file""" seqs = [] seq = [] with open(bestand) as inFile: for line in inFile: if not line.startswith(">"): seq.append(line.strip()) else: if seq != []: ...
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from django.forms import * class RegistrationForm(UserCreationForm): username = CharField(min_length=5, label='Логин') password1 = CharField(min_length=8, widget=PasswordInput, label='Пароль'...
# -*- coding: UTF-8 -*- import requests import re, json, os def word2string(url, filename): print("filename: ", filename.encode('utf-8').decode()) payload = {} files = [ ('file', open(filename.encode('utf-8').decode(), 'rb')) ] headers = {} response = requests.request("POST", url, headers=headers, dat...
# -*- coding: utf-8 -*- def social_pant(entity, argument): return True #- Fine Funzione -
from constructors.htmlObj import HTMLObject from constructors import htmlSnippets from functions.printFunctions import inputClear from functions.misc import locationParse from datetime import datetime from bs4 import BeautifulSoup import os import time def fileHandling(): PROJECT_NAME = inputClear('W...
from sklearn.neural_network import MLPClassifier ''' class MLPClassifier(hidden_layer_sizes=(100,), activation="relu", solver='adam', alpha=0.0001, batch_size='auto', learning_rate="constant", learning_rate_init=0.001, power_t=0.5, max_iter=200, shuffle=True, random_state=None, tol=1e-4, verbose=False, warm_start...
som=0 count=-1 while True: getal=eval(input("noem een getal: ")) som+= getal count+=1 if getal == 0: break print("Er zijn "+str(count)+" getallen ingevoerd, de som is: "+ str(som))
# -*- coding:utf-8 -*- ''' pytorch 0.4.0 data: https://download.pytorch.org/tutorial/faces.zip tutorials: https://pytorch.org/tutorials/beginner/data_loading_tutorial.html ''' from __future__ import print_function, division import os import torch import pandas as pd # 用于解析csv文件 from skimage import io, transform # 用...
from tkinter import * from V_windows.V_search.V_SearchMain import V_Search from V_windows.V_readerEntrance.V_ReaderEntrance import V_ReaderEntrance from V_windows.V_adminEntrance.V_AdminEntrance import V_AdminEntrance class V_Home(): def __init__(self): self.size = '450x250' self.locate = '+10+10' ...
import numpy as np lats = np.arange(-90, 91, 1) #268 longs = np.arange(-180, 181, 1) #381 #102108 lats, longs = np.meshgrid(lats, longs) lats = lats.flatten() longs = longs.flatten() types = np.ones(len(lats), dtype=np.int64) coors = np.concatenate((lats, longs, types)) coors = coors.reshape((3, len(lats)))...
import schedule import time import datetime import threading import os from googlemaps import Client from time import gmtime, strftime def partial(func, *args, **kwargs): def f(*args_rest, **kwargs_rest): kw = kwargs.copy() kw.update(kwargs_rest) return func(*(args + args_rest), **kw) return f def format_tim...
import numpy as np def store_number(coords, board): #x = which row, y = which column, z = what number print(coords) z = coords[0] x = coords[1] y = coords[2] #xy[x][y] = z #stores number (z) in x,y for i in range(9): #places -1 in locatinos numbers can't be. board[i][x][y] = -1 board[z-1][i][y] = -1 board[...
from django.urls import path from chinook.views import ( AlbumListAPIView, PlaylistListAPIView, ReportDataAPIView, GenreListAPIView, TrackListAPIView, CustomerSimplifiedAPIView, TotalPerCustomerAPIView, ) urlpatterns = [ path("albums/", AlbumListAPIView.as_view()), path("genres/", G...
from datetime import datetime def current_date(): return datetime.now().strftime("%Y/%m/%d") def current_time(): return datetime.now().strftime("%H:%M:%S")
from pyengine.common.components.component import Component class ScriptComponent(Component): def __init__(self, game_object): super().__init__(game_object) self.name = "ScriptComponent " def to_dict(self): return { "name": self.name, } @classmethod def fro...
def divisors(integer): divs = [ divider for divider in range(1, integer) if integer % divider == 0 and divider != 1 ] return "{} is prime".format(integer) if len(divs) == 0 else divs
from selenium import webdriver from bs4 import BeautifulSoup import xlwt dr=webdriver.Chrome() for i in range(0,10): dr.get('https://www.pagalworld.mobi/home/updates?page='+str(i)) g=dr.page_source soup=BeautifulSoup(g,'html.parser') #f=soup.find_all('ul') urls = [] for a in soup.find_all('a', href=True): ...
###################################################################### # **Medial axis skeletonization** # # The medial axis of an object is the set of all points having more than one # closest point on the object's boundary. It is often called the *topological # skeleton*, because it is a 1-pixel wide skeleton of the ...
import logging import os from collections import OrderedDict from functools import partial import matplotlib.pyplot as plt import numpy as np from PyQt5 import QtCore, QtWidgets, QtGui import io from matplotlib.colors import LogNorm from module.Module import ProcModule from module.OneDScanProc import OneDScanProc fro...
from sqlmodel import Session, select from warehouse import engine from warehouse.models import Product, Supplier from warehouse.ultis import update_attr def get_all(): with Session(engine) as session: statement = select(Product, Supplier).join(Supplier, isouter=True) results = session.exec(stateme...
#!/usr/bin/python3 # openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes # run as follows: # python myssl.py # then in your browser/curl -k, visit: # https://localhost:5000 # from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import urlparse import ssl class ...
lado = input("Digite o valor correspondente ao lado de um quadrado: ") x = float(lado) * 4 y = float(lado) ** 2 print("perímetro:", int(x), "-", "área:", int(y))
import numpy as np import tensorflow as tf import cv2 import time import os class DetectorAPI: def __init__(self, path_to_ckpt): self.path_to_ckpt = path_to_ckpt self.detection_graph = tf.Graph() with self.detection_graph.as_default(): od_graph_def = tf.GraphDef() w...
# # Tested on following pretrained models: # mask_rcnn_inception_v2_coco_2018_01_28 # # import cv2 import sys import argparse import imutils from detection_boxes import DetectBoxes def arg_parse(): """ Parsing Arguments for detection """ parser = argparse.ArgumentParser(description='Pytorch Yolov3') pars...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import common_pb2 as common__pb2 import ether_service_pb2 as ether__service__pb2 class ether_serviceStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. ...
#_*_ coding:utf-8 _*_ ''' map ''' # list01 = [1,2,3,4,5,6,7,8,9] # list02 = [1,2,3,4,5,6,7,8,9] # map = map(lambda x,y : x * y,list01,list02) # print(list(map)) ''' filter ''' # list01 = [1,2,3,4,5,6,7,8,9] # filter = filter(lambda x : x > 5,list01) # print(list(filter)) ''' reduce ''' from functools import reduce li...
""" AbstractStack is an abstract data type for stack implementation. CONSTANTS POP_NIL = 0 # pop() not called yet POP_OK = 1 # last pop() call completed successfully POP_ERR = 2 # stack storage is empty PEEK_NIL = 0 # peek() not called yet PEEK_OK = 1 # last call peek() returned corre...
from django.views.generic import TemplateView from prices.models import PriceTable, SecondPriceTable from ceilings.models import Ceiling class PriceView(TemplateView): template_name = 'prices/price.html' def get_context_data(self, **kwargs): context = super(PriceView, self).get_context_data(**kwa...
import cashtag_analyzer # Import the modules from the __init__ script. import ccxt # Import ccxt to connect to exchange APIs. import collections # Import collections to create lists within dictionaries on the fly. import datetime # Import datetime for the timedelta and utcfromtimestamp functions. import numpy...
#!/usr/bin/env python import json import visit """Visits ns_server metadata and emits flat metadata on the fast-changing time-series metrics to stdout as JSON.""" first = True def store_conv_fast(root, parents, data, meta, coll, key, val, meta_val, meta_inf, level): global first if no...
# -*- coding:utf-8 -*- __author__ = "leo" # 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverse_print(self, head): return self.reverse_print(head.next) + [head.val] if head else [] class Solution1: ...
import unittest import os from robot.utils import * from robot.utils.asserts import * class TestNormalizing(unittest.TestCase): def test_normpath(self): if os.sep == '/': inputs = [ ('/tmp/', '/tmp'), ('/tmp', '/tmp'), ('/tmp/foo/..', '/tmp'), ...
# _*_coding: utf-8_*_ # Created by yls on 2020/10/27 21:16 import tools.DoExcel # class ReplaceRelyOnValue(): # def replace_rely_on_value(self):
from __future__ import division import numpy as np import matplotlib.pyplot as plt x = np.arange(-1,1,1e-3) x1=np.arange(-0.999,0.9999,1e-1) f=np.arctan(x) f1=[] for x2 in x1: y=0 for j in range(1,1000): y=y+((-1)**(j+1))*(x2**j/(2*j-1)) f1.append(y) plt.plot(x,f) plt.plot(x1,f1,'o') plt.grid() plt.xlabel('$x$') p...
#!/usr/bin/env python3 import logging import argparse import os from pathlib import Path import re import time import traceback import glob from unittest import result import psycopg2 import psycopg2.extras import psycopg2.pool from datetime import datetime, timedelta from filenames import filename_parser from image_...
import random class Game: def __init__(self, teamA, teamB, extra=True): self.teamA = teamA self.teamB = teamB self.extra = extra if (teamA != None and teamB != None): self.teamAHOS, self.teamBHOS = self.getNormalHardness() def play(self): if (self.teamA == N...
biggest = 0 def triangle(z): global biggest list = [] for c in range(1,int(z**.5) + 1): if z % c == 0: list.append(c) if c**2 != z: list.append((z / c)) length = len(list) if length >= biggest: biggest = length print "%r is the triangle with the most divisors (at %r) so far" % (z, length) a = 2...
import datetime from unittest import mock import pytest import pytz from django.core import mail from django.utils import timezone from freezegun import freeze_time from customers.services import SMSNotificationService from payments.enums import OrderStatus from payments.models import Order @freeze_time("2020-10-20...
from flask import Flask, render_template import os import threading , time import cv2 import numpy as np cap = cv2.VideoCapture(0) webcam_flag = False def webcamCap(): while(True): global webcam_flag ret , frame = cap.read() # RGB -> Grey Conversion (Optional) gray_frame = cv2.cvt...
import http.client import importlib import os import re import urllib.parse from wsgiref.headers import Headers from wsgiref.simple_server import make_server class Request: def __init__(self, environ): self.environ = environ @property def args(self): get_args = urllib.parse.parse_qs(self....
import cv2 as cv def input_boolean(prompt): while True: print(prompt) retval = input('> ') switch = { 'y': True, 'yes': True, 'n': False, 'no': False } if retval in switch: return switch[retval] def print_predi...
""" HSC-specific overrides for FgcmBuildStarsTable """ import os.path from lsst.utils import getPackageDir # Minimum number of observations per band for a star to be considered for calibration config.minPerBand = 2 # Match radius to associate stars from src catalogs (arcseconds) config.matchRadius = 1.0 # Isolation ...
#!/usr/bin/env python3 # coding=utf-8 """ githubAutomatic takeover """ import json import base64 import requests from config import settings HEADERS = { "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Language": "zh-CN,zh;q=0.9", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 1...
def handler(doc): from quart import Blueprint, request from quart.json import jsonify swagger_blueprint = Blueprint( doc.blueprint_name, __name__, url_prefix=doc.url_prefix, static_url_path=doc.static_uri_relative, static_folder=doc.static_dir, root_path=doc....
#! /usr/bin/env python ########################################################################## # Hopla - Copyright (C) AGrigis, 2015 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.ht...
#!/usr/bin/env python3 """Numerical integration in python using the Lotka-Volterra model""" __appname__ = "LV1.py" __author__ = "Joseph Palmer <joseph.palmer18@imperial.ac.uk>" __version__ = "0.0.1" __license__ = "License for this code/" __date__ = "Nov-2018" ## imports ## import sys import scipy as sc import scipy.st...
from typing import Any, Dict, List, Union from app.interpreter.interpreter import ALL_ASSERTIONS, ALL_RULES, Interpreter from app.parser import AST def ast_to_string(ast_dict: Dict[str, List[AST]]) -> Dict[str, List[Union[str, List[Any]]]]: def to_string(tree: AST) -> List[Union[str, List[Any]]]: str_ast...
import numpy as np import tensorflow as tf from sklearn.utils import shuffle from sklearn.model_selection import train_test_split import scipy.io as scio import h5py import time LOG = open("/home/hyli/Data/InternData/log_full_sgd_lr0002.txt", "w") rng = np.random.RandomState(1234) random_state = 42 par = scio.loadma...
# # Python program to find maximum product of two # # non-intersecting paths # # Returns maximum length path in subtree rooted # # at u after removing edge connecting u and v # def dfs(g, curMax, u, v): # # To find lengths of first and second maximum # # in subtrees. currMax is to store overall # # maximum...
#!/usr/bin/env python # license removed for brevity import rospy import time from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError #import numpy as np import cv2 def talker(): global cap global frequency global video_resolution image_size = video_resolution / 2 bridge...
from src.Public import Public class GamePlay(object): def __init__(self, status, message): self.pb = Public() self.status = status self.message = message def login(self): self.pb.color("login......", "cyan") lss = self.pb.find(self.status, self.message) ...
from functools import lru_cache class LargePower: def __init__(self, n): self.a = int(n[0]) self.b = int(n[1]) @lru_cache def compute(self): return pow(self.a, self.b, int(1e9+7)) def get(self): if self.a == 0: return str(0) if self.b == 0: ...
import shutil import os # for line in open(r"G:\list_bbox_celeba2.txt"): # print(line) # exit() import glob import os # path = r"G:\list_bbox_celeba2.txt" # f = r"G:\list_bbox_celeba3.txt" # # file = open(path) # for line in file.readlines(): # print(line) # strs = line.strip().split(" ") # print(...
""" Copyright 2013 Rackspace 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, software dist...
def spiralOrder(matrix): if not matrix: return [] rowbegin=0 rowend=len(matrix) columnbegin=0 columnend=len(matrix[0]) res=[] while rowend>rowbegin and columnend>columnbegin: for i in range(columnbegin,columnend): res.append(matrix[rowbegin][i]) for j in ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('urly_app', '0016_auto_20161130_2154'), ] operations = [ migrations.AddField( model_name='link', name...
#!/usr/bin/env python3 """xev output data parser to get mouse polling rate. Usage: $ chmod a+x mouserate $ xev | mouserate """ import sys import re previous = 0 time_re = re.compile('time (\d+)') while True: line = sys.stdin.readline() match = time_re.search(line) if match: time = int(mat...
array = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 0, 5, 2] def count_sort(array): sorted_list = [] count = [0] * (max(array)+1) for i in range(len(array)): count[array[i]] += 1 # 각데이터에 해당하는 인덱스의 값 증가 for i in range(len(count)): for j in range(count[i]): sorted_list.append(i) ...
# Problem Code: CCISLAND T=int(input()) while T!=0: X,Y,x,y,D = map(int,input().split()) if D*x <=X and D*y<=Y: print("YES") else: print("NO") T-=1
# pylint: disable=W0613 # w0613 coresponde a "unused argument" import random import pygame import collision_bullshit as Fuck import math import numopers as ops import sfx as sfx _bbGrace = 60*1.5 def _moveBounce(ent, gs, momx, momy): if ent.x + ent.width + momx > gs.scrsq - gs.hbound: ent.momx = -ent.momx...
ganhoPorHora = float(input('Digite seu ganho por hora: ')) horasTrabalhadas = int(input('Digite a quantidade de horas trabalhas: ')) salarioBruto = ganhoPorHora * horasTrabalhadas ir = salarioBruto * 11 / 100 inss = salarioBruto * 8 / 100 sindicato = salarioBruto * 5 / 100 salarioLiquido = salarioBruto - ir - inss -...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0026_auto_20151108_1530'), ] operations = [ migrations.AddField( model_name='speakerlist', n...
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from helperFunctions import * import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np torch.set_default_tensor_type('torch.cuda.FloatTensor') def to_cate...