text
stringlengths
8
6.05M
with open('/home/cyagen1/Downloads/1','r')as f: w=''.join(f.read().split('\n')[1:]) import itertools k=4 li=list(itertools.product(['A','T','G','C'],repeat=k)) dict={} for i in li: i=''.join(i) dict[i]=0 for j in range(len(w)-k+1): if w[j:j+k] in dict.keys(): dict[w[j:j+k]]+=1 for i in sorted(d...
N = int(input()) C = [0]*(N-1) for i in range(N-1): C[i] = list( map( int, input().split())) for i in range(N-1): k = i ans = 0 while k < N-1: if ans <= C[k][1]: ans = C[k][1] + C[k][0] else: ans += (C[k][2] - ans)%C[k][2] + C[k][0] k += 1 print(ans) p...
# 594. Longest Harmonious Subsequence # # We define a harmonious array is an array where the difference # between its maximum value and its minimum value is exactly 1. # # Now, given an integer array, you need to find the length of its longest harmonious subsequence # among all its possible subsequences. # # Examp...
import Clear_Code if __name__ == '__main__': print(Clear_Code.clean_str("aaaa xcbv gfnjgh gh "))
import copy import six from collections import defaultdict from itertools import chain from parsel import SelectorList from scrapely.extraction.regionextract import TextRegionDataExtractor from scrapely.htmlpage import HtmlPageParsedRegion, HtmlPageRegion from scrapely.extractors import htmlregion from scrapy.utils....
# hello everyone! # today is a good day to learn python print("Comments are fun!") # this is a print
from message_socket import MessageSocket import json import time from weather import Weather from schedule import Schedule # -------- LOGGER SETTING -------- from logging import getLogger, StreamHandler, Formatter, DEBUG logger = getLogger(__name__) handler = StreamHandler() handler.setLevel(DEBUG) handler.setFormatt...
#import sys #input = sys.stdin.readline from itertools import accumulate def solve(k, acd, n,x,m): now = 0 cnt = 0 for p in acd: if now+p >= m: cnt += 1 now = p%m def main(): k, q = map( int, input().split()) d = list( map( int, input().split())) NXM = [ tuple(...
from rest_framework import serializers from tasks.models import Tasks, TaskRemarks class TasksSerializer(serializers.ModelSerializer): class Meta: model = Tasks fields = '__all__' read_only_fields = ('created_at', 'updated_at', 'created_by') def validate(self, data): data['cre...
def func_outer(): x = 2 print(f'x equals {x}') def func_inner(): nonlocal x x = 5 func_inner() print(f'Local x changed on {x}.') func_outer()
from PyQt5 import QtCore, QtGui, QtWidgets from GidişSeferi import Sefer import sqlite3 class Koltuk(object): def add(self): color = self.textEdit_2.toPlainText() date = self.textEdit_3.toPlainText() msgbox=QtWidgets.QMessageBox() conn = sqlite3.connect('Data.db') conn.exe...
# Copyright (c) 2019, NVIDIA Corporation. All rights reserved. # # This work is made available # under the Nvidia Source Code License (1-way Commercial). # To view a copy of this license, visit # https://nvlabs.github.io/few-shot-vid2vid/License.txt from PIL import Image import numpy as np import random import torch i...
from .DVGeo import DVGeometry from .DVGeoAxi import DVGeometryAxi try: from .DVGeoVSP import DVGeometryVSP except ImportError: pass try: from .DVGeoESP import DVGeometryESP except ImportError: pass try: from .DVGeoMulti import DVGeometryMulti except ImportError: pass
import time import colorsys import random import math import neopixel_dev ''' TODO: more meteor (bouce, random size/speeds) modify melspectrum to only pass half the data (other not needed) Vizualisers: rolling peak volume ''' DEVELOPER_MODE = True #############################################################...
""" CEASIOMpy: Conceptual Aircraft Design Software Developed by CFS ENGINEERING, 1015 Lausanne, Switzerland Test functions for 'StabbilityDynamic/dynamicstability.py' Python version: >=3.6 | Author: Loic Verdier | Creation: 2019-10-24 | Last modifiction: 2020-04-07 (AJ) TODO: * Create more tests """ #=====...
import os import random from typing import List from pathlib import Path import numpy as np from tqdm import tqdm from bonapity import bonapity from sklearn.svm import OneClassSVM, LinearSVC, SVC from sklearn.ensemble import IsolationForest, RandomForestClassifier from sklearn.linear_model import LogisticRegression...
""" ClassExpression := Class | ObjectIntersectionOf | ObjectUnionOf | ObjectComplementOf | ObjectOneOf | ObjectSomeValuesFrom | ObjectAllValuesFrom | ObjectHasValue | ObjectHasSelf | ObjectMinCardinality | ObjectMaxCardinality | ObjectExactCardinality | DataSomeValuesFrom | DataAllValuesFrom | DataH...
import numpy as np import pprint pp = pprint.PrettyPrinter(indent=4, width=120, depth=3) class Task(object): @property def n_inputs(self): return np.shape(self.input_data)[1] @property def n_outputs(self): return np.shape(self.output_data)[1] def __init__(self): pass ...
""" This file creates "test_checkpoint.pkl" that is used in test_backend.py for testing purposes """ import pickle import random from deap import base, creator, tools, algorithms import numpy as np creator.create("obj", base.Fitness, weights=(1.0,)) creator.create("Ind", list, fitness=creator.obj) toolbox = base.Tool...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys reload(sys) sys.setdefaultencoding("utf-8") import sqlite3 from pyparsing import * from random import choice from library import * import multiprocessing import socket #from lxml import html #from lxml.html.clean import clean_html sys.path.append("decruft") ...
import easytrader from datetime import datetime from datetime import timedelta import os user = easytrader.use('ht', False) user.prepare('ht.json') ##print(user.position) #获取组合最近5次调仓 #user.entrust()) #获取最近30天交割单 #print(user.exchangebill) #获取交割单 starttime = datetime(2015, 1, 1) print(starttime.strftime('%Y%m%d')...
from collections import namedtuple import conans class BuildInfo(object): def __init__(self): self.modules = [] def serialize(self): return {"modules": [module.serialize() for module in self.modules], "buildAgent": {"name": "Conan", "version": conans.__version__}} class Bu...
from sklearn.preprocessing import StandardScaler from sklearn import svm import joblib import cv2 def divide(video_classification,car1,car2,car1_num,car2_num): max_index=video_classification.index(max(video_classification)) cnt1 = 0 cnt2 = 0 label1 = 0 label2 = 0 if max_index==0: ...
#coding=utf-8 from datetime import timedelta from django.db import models from django.contrib import admin # Create your models here. from django.utils import timezone from django.utils.datetime_safe import datetime class BlogsPost(models.Model): title = models.CharField(max_length = 150) body = models.Text...
import PageRank print "Testing the page rank computer." print webgraph = { 'A' : [ 'B', 'C' ], 'B' : [ 'C' ], 'C' : [ 'B', 'D' ], 'D' : [] } print "Web graph: " print webgraph computer = PageRank.Computer(webgraph) computer.compute() result = computer.page_ranks print "" prin...
import socket import binascii def createPacket(instruction,id_param,ip_source,ip_destin,ttl,flags): version = '0010' IHL = '0000' type_service = '00000000' total_len = '0000000000000000' identif = id_param.zfill(16) flag_p = flags frag_off = '0000000000000' protoc = '00000000' header_check = '00000000000000...
from __future__ import annotations from datetime import datetime, timezone from functools import partial from uuid import UUID import attrs from attrs.converters import optional from .converters import as_aware_datetime, as_uuid from .enums import JobOutcome @attrs.define(kw_only=True, frozen=True) class Event: ...
set={"white","blue","purple","pink","red","black"} set.update(['maroon','green']) print(set) a = 20 b = 20 if b > a: print("b is greater than a") if b is a: print("b and a are equal")
import os import random import time #set the console colour os.system('color 02') def printinline(string): delay=30/1000 #this seems like a nice amount of delay n = random.randint(1,10) chunks = [string[i:i+n] for i in range(0, len(string), n)] for word in chunks: print(word,end="",f...
################################################# # DEPENDENCIES ################################################# # libraries from __future__ import print_function import os from skimage.transform import resize from skimage.io import imsave import numpy as np from keras.models import Model from keras.layers import I...
import sys sys.path.append('/home/zuofeng/projects/platform/bminfo/bminfo/scripts') from ppMapDB import ppMapMySQL, ppMapSQLite pp = ppMapMySQL('bminfo') sql = 'DROP TABLE IF EXISTS OMIM_MUTATION_INFO' pp.execute(sql) sql = ''' CREATE TABLE OMIM_MUTATION_INFO ( "INDEX" int not null, OMIM_ID ...
"""Template strings to simplify code formatting""" mapfile_layer_template = """ # LAYER: {feature} LEVEL: {layer} LAYER NAME "{feature}_{layer}" GROUP "{group}" METADATA "ows_title" "{metadata_name} {geomtype_humanreadable}" "ows_enable_request" "*" "gml_include_items" "all" ...
from dtImport import * from calculation import * import json def calc_return(filename): try: dt = readXlsData(filename) dur = dt["GazeEventDuration"] x = dt["FixationPointX (MCSpx)"] y = dt["FixationPointY (MCSpx)"] a1 = dt["AOI[Rectangle]Hit"] a2 = dt["AOI[Rectangl...
import nltk import pandas as pd import numpy as np import logging from nltk.tokenize import TweetTokenizer from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords from nltk.corpus import wordnet from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import T...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-11-30 08:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nova', '0041_accesskey_app'), ] operations = [ migrations.CreateModel( ...
"""Sudoku solver""" import numpy as np class SudokuSolver(): def __init__(self): pass def __call__(self, grid: list) -> list: """Solve the given sudoku grid using backtracking (brute force). See: https://en.wikipedia.org/wiki/Sudoku_solving_algorithms Parameters ----...
from copy import deepcopy import os class MiniMax: MIN = "min" MAX = "max" @staticmethod def __should_prune__(elem): if len(elem["actions"]) == 0 or \ elem["op"] == MiniMax.MAX and elem["score"] > elem["beta"] or \ elem["op"] == MiniMax.MIN and elem["score"] < e...
import unittest from test_smile import TestSmile from test_word_tokenize import TestWordTokenize from test_spell import TestSpell if __name__ == '__main__': unittest.main()
from django.test import TestCase from lists import views, models class NormalViewTest(TestCase): def test_index_render(self): """ Make sure URL '/' renders index.html """ # GET request to '/' response = self.client.get("/") # Test template being rendered se...
from DataReader import DataDirector class CreateDataSet: def __init__(self): self.data_director = DataDirector() self.x, self.y = self.data_director.get_X_Y(1000, 50) #create_data_set = CreateDataSet()
""" Creación del tipo especifico visualizador de nivel de bateria """ from agentes_actuadores.visualizador_bateria import * class FactoryVisualizadorBateria: @staticmethod def crear(tipo: str) -> AbsVisualizadorBateria: if tipo == "archivo": return VisualizadorBateria() elif tipo == "socket...
import pygame from pygame.locals import * from enemies import base def mainLoop(): # Star of game stuff print('\n') print('Loading pre-loop files...') clock = pygame.time.Clock() mouseBool = True gameLoop = True AntiAlias = False # Defines the mouse buttons LEFT = 1 RIGHT = 3 worldX = 0 worldY = 0 mP...
# Import libraries and dependancies from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import requests import time def init_browser(): executable_path = {"executable_path": "/usr/local/bin/chromedriver"} return Browser("chrome", **executable_path, headless=False) def news_scr...
import psycopg2 import datetime def lecturer_module_list(lecturer_id): try: conn = psycopg2.connect( host="attendance-manager.cstueihbr6n2.eu-west-1.rds.amazonaws.com", database="AttendanceManager", user="Developer", password="rainforestbuildercode" )...
import os import shutil from PIL import Image from PIL.ExifTags import TAGS """ This short script will organize the pics in current directory into year/month directories based on creation date The creation date is pulled from the EXIF data of the image """ def get_filenames_from_dir(path): image_files_list = li...
import test2 def tryThis(): print "tried this" test2.startThis()
#: Imports import mysql.connector from configparser import ConfigParser #: Get Configs config = ConfigParser() config.read("./config.ini") #: Create the database connection mydb = mysql.connector.connect(user=config["Database"]["user"], password=config["Database"]["pass"], host=config["...
from flask import Flask , render_template , request , redirect , url_for , session , flash from dbcheck import * from passlib.hash import pbkdf2_sha256 import datetime from email_verifier import * import random app = Flask(__name__) app.secret_key = 'az75z8962df1235s' @app.route('/') def home(): return render_...
""" 15. 3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], ...
#topological sorting from collections import deque def kahnSort(graph): in_deg = {u : 0 for u in graph} for u in graph: for v in graph[u]: in_deg[v] += 1 print(in_deg) q = deque() for u in in_deg: if in_deg[u] == 0: ...
from apay import app, db, models from flask import request, jsonify from datetime import datetime from sqlalchemy.exc import IntegrityError @app.route('/countries', methods=['POST', 'GET']) def countries(): if request.method == 'POST': try: country = models.Country(request.get_json()) ...
# print( # When this is written in the mu-editor, the print functions documentation pops up # Print hello world print('Hello world') # Alternately data_variable = 'Hello world' print(data_variable) # A variable named first which consists of a string. The string is the word "Hello". (print it!) first = "Hello" prin...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 22/03/2019 16:53 # @Author : karl wang # @Email: karl.wang.1991@gmail.com from itsdangerous import TimedJSONWebSignatureSerializer as Serializer APP_KEY = 'karl' def encode(data, expires_time: int = 3600) -> str: s1 = Serializer(APP_KEY, expires_in=expires...
li=[1,3,4,5,5,6,7,7,8] li.remove(5) li.remove(7) print(li)
import numpy as np import numpy.random as npr class MeasurementModel(object): def __init__(self): self.xx, self.yy = np.meshgrid(np.linspace(-0.5,0.5,21), np.linspace(-0.5,0.5,21)) self.samples = np.c_[self.xx.ravel(), self.yy.ravel()] self.n = self.s...
def checkBrackets(expression): opening = "{[(" ending = "}])" brackets_only = [x for x in expression if x in opening or x in ending] stack = [] no = 0 for x in brackets_only: if x in opening: if not(stack) or (stack and (opening.index(x)-opening.index(stack[-1]) == 1): ...
# -----------------Built-In Scope------------- from math import pi def outer(): def inner(): print(pi) inner() outer() # ------------------Global Scope---------- a = 1 def counter(): global a a = 4 print(a) counter() # ----------------Enclosed Scope--------------- def red(): ...
#import sys #input = sys.stdin.readline def main(): N = int( input()) A = list( map( int, input().split())) ans = 1000 stock = 0 stock_price = 1000 for i in range(N-1): a = A[i] # print(i, stock_price,a) if stock > 0 and stock_price <= a: ans += stock*a ...
"""empty message Revision ID: 493466ec9210 Revises: b7afce71bc6f Create Date: 2018-04-16 21:36:46.761078 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '493466ec9210' down_revision = 'b7afce71bc6f' branch_labels = None depends_on = None def upgrade(): # ...
# https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html
# Computer Programming 1 # Mini-project: Contact Manager # # Name: Jordan Houle # Date: January 30, 2017 # # Directions: # # There are 10 coding tasks for you to complete. Each is worth 3 points. # The testing portion will all be done in the shell when your program # is working. Each testing step is worth 2 points. Thi...
#! /usr/bin/env python ''' Copyright 2017-present, Airbnb Inc. 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 a...
# Generated by Django 2.2.2 on 2020-07-11 17:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jazz', '0001_initial'), ] operations = [ migrations.AlterField( model_name='band', name='slug', field=mo...
from onegov.core.security import Public, Private from onegov.org.views.ticket import ( view_ticket, handle_new_note, handle_edit_note, message_to_submitter, view_ticket_status, view_tickets, view_archived_tickets, view_pending_tickets, assign_ticket, view_send_to_gever) from onegov.ticket.collection import ...
#import sys #input = sys.stdin.readline from collections import Counter from copy import deepcopy def main(): s = list( input()) N = len(s) C = Counter(s) ans = 100 for i in range(26): S = deepcopy(s) a = chr( ord("a") + i) t = N c = C[a] if c == 0: ...
import re import argparse parser = argparse.ArgumentParser(description=""" Seq_Chop.py takes a sequence file and it will split the long sequence in the file into required max length. """) parser.add_argument('-i','--input',dest='input_file_path',action="store",required=True,help=""" The input file is a sequence fil...
# Generated by Django 2.0.4 on 2018-06-08 13:38 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TrendRepo', fields=[ ('id', models.AutoFiel...
# Convertendo uma massa em quilograma para libras quilograma = int(input('Entre com o valor em quilograma: ')) libras = quilograma / 0.45 print(libras)
#!/usr/bin/env python3 #-*- encoding: utf-8 -*- from setuptools import setup, find_packages with open('README.md') as f: desc = f.read() with open('requirements.txt') as f: install_requirements = f.read().splitlines() extras = {} combined = set() for extra in ('backtranslate', 'torch'): with open(extra ...
from __future__ import division from Constants import * import random import math """ A simulation scenario where the percentage of reads varies periodically from 50% to 100% and the capacity of each VM is proportional to that percentage. """ class ReadLoadScenario(object): def __init__(self, training...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-21 23:16 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userprofiles', '0002_auto_20170521_1727'), ] operations = [ migrations.Rena...
#! /usr/bin/env python # -*- coding: utf-8 -*- from argparse import ArgumentParser from utils import * def observed_agreement(i, c, g): """ Given a number of boundaries `i`, a coder's indexes `c`, and gold indexes `g`, calculate the observed agreement according to π. """ agreed_pos = len(set.intersection(se...
import os from functools import partial import numpy as np import pandas as pd from natsort import natsorted from .io import write_dataframe __author__ = 'Yuji Ikeda' def _transform_legendre(df, pressure): df['P'] = pressure df['G'] = df['F'] + pressure * df['V'] gmin = df['G'].min() return df[df['G'...
a=input() try: if (int(a)<=0 or int(a)>=0): print("Yes") except ValueError: print("No")
from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from.models import Subscriber from.serializers import SubscriberSerializer # Create your views here. @api_view(['GET']) def api_overview(requ...
import numpy as np from scripts import algs def test_pointless_sort(): # generate random vector of length 10 x = np.random.rand(10) # check that pointless_sort always returns [1,2,3] assert np.array_equal(algs.pointless_sort(x), np.array([1,2,3])) # generate a new random vector of length 10 x...
from django.test import TestCase from unittest.mock import patch from scheduler import views import json, shutil, os class ViewsTest(TestCase): history_data_path_for_test = 'scheduler/history_data_for_test/' history_data_path_original = 'scheduler/history_schedule_data/' @classmethod def setUpClass(...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Xinlei Chen # -------------------------------------------------------- """Compute minibatch blobs for training a Fast R-CNN ne...
def inscribirUsuario(): print('Dime la lista de matriculas de inscripcion') print('Para salir presiona: q') lista = [] alumno = input('Dime la matricula del usuario: ') while alumno != 'q': if alumno not in lista: lista.append(alumno) alumno = input('Dime la matri...
''' Track the data needed to form a linear regression for boiler distance vs top-cY ''' import cv2 import time import os import numpy try: import RPi.GPIO as GPIO except RuntimeError: print("Error importing RPi.GPIO! Probably need to run as root") ## Dirty hack to import GRIP pipeline from parent directory import ...
from constants import * import numpy as np import scipy.io.wavfile as wavfile import vectors #note: start time in seconds, not in samples # TODO: global volume control # TODO: moving sound sources! - How? class SoundObject: def __init__(self, name_, pos_, sound_file_, start_time_, loudness_=1, position_change_=la...
# Generated by Django 3.1.2 on 2020-10-24 06:44 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('email_sender', '0001_initial'), ] operations = [ migrations.AlterField( model_name='history', name='...
from flask import Flask, request, jsonify import requests from werkzeug.exceptions import HTTPException from socket import * app = Flask(__name__) @app.route('/fibonacci') def get_params(): try: hostname = request.args['hostname'] fs_port = request.args['fs_port'] number = reques...
import numpy def distancia_double(x,y,z): aux=numpy.float64(0) return ((x-aux)*(x-aux)+(y-aux)*(y-aux)+(z-aux)*(z-aux))**(0.5) def distancia_simple(x,y,z): aux=numpy.float32(0) return ((x-aux)*(x-aux)+(y-aux)*(y-aux)+(z-aux)*(z-aux))**(0.5) funcion64=numpy.float64 funcion32=numpy.float32 print "distan...
""" """ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import operator, functools from rkd.didactic.transformations import * from sympy import * from sympy.matrices import Matrix,eye from rkd.abc import * from rkd.didactic.ws import * __all__ = ["Robot", "RigidBody2D"] class Robot(object): ...
from collections import OrderedDict n = int(input()) words = OrderedDict() for _ in range(n): word = input() if(word in words): words[word] += 1 else: words[word] = 1 print(len(words)) for item in words: print(words[item], end=" ")
import time import hmac import hashlib import base64 from typing import Dict import re from wsgiref.handlers import format_date_time from datetime import datetime from time import mktime class EterbaseAuth(): """ Auth class required by Eterbase API """ _UTF8 = 'utf-8' _HTTP_METHOD_GET = "GET" ...
#y²=x³+ax +b class CourbeElliptique: def __init__(self, a, b): self.a = a self.b = b if 4*a**3+27*b**2 == 0: raise ValueError('({}, {}) n\'est pas une courbe valide'.format(a, b)) def __eq__(self, x): if self.a==x.a and self.b==x.b: return True return False def testPoint(self, x, y): if x**3+self...
''' Search in Rotated Array Given an array of numbers which is sorted in ascending order and also rotated by some arbitrary number, find if a given ‘key’ is present in it. Write a function to return the index of the ‘key’ in the rotated array. If the ‘key’ is not present, return -1. You can assume that the given arra...
from fabric.api import * from fabric.contrib.files import append from fabric.decorators import task @task def install_wget(): sudo('yum install -y wget') @task def install_anaconda(): sudo('mkdir /opt/jupyter') sudo('wget https://repo.continuum.io/archive/Anaconda3-4.3.1-Linux-x86_64.sh -P /opt') sudo...
def read_txt(filename: str ) -> dict: with open(filename, 'r') as txt_file: data = txt_file.readlines() data = [line.strip() for line in data] return data def modify_date(date_line: str ) -> dict: new_date = "" parts = date_line.split() if len(parts) == 3: day = parts[0].rst...
import re import json import uuid import hashlib from pprint import pprint from SPARQLWrapper import SPARQLWrapper, JSON, CSV from collections import Counter regex = r"[ +\/()#*²]" subst = "_" def run_query(mapping): query_params = '' for key in mapping: val = re.sub(regex, subst, mapping[key], 0)...
#!/usr/bin/env python3 # # Execute runs of tasks and put the results into the database. # import daemon import datetime import errno import multiprocessing import optparse import os import pscheduler import psutil import select import signal import socket import tempfile import time import traceback pscheduler.set_g...
""" =================================== Keyboard Control of Cursor Position =================================== Demonstrates basic usage of the cursorui package by incrementing the position of the cursor using the wasd keys. """ import sys from PyQt5 import QtCore, QtWidgets try: from cursorui.view import Cursor...
def busca_binaria(array, valor): inicio = 0 #Valor da posição 0 da lista fim = len(array) - 1 #Valor ultima posição da lista while inicio <= fim: # O loop continuara enquanto o inicio não encontrar o fim meio = (inicio + fim) // 2 # Definição do meio da l...
#!/usr/bin/python # -*- coding:utf-8 -*- # Author: Eason rows = int(input("Enter number you wanna: ")) for a in range(0, rows): if a == rows - 1: for k in range(2 * rows - 1): if k % 2 == 0: print "*", else: print " ", else: for j in range(...
#Author: Ryan Su import random x = int(input("Enter a number:")) password = [] while x > 0: password.append(random.randint(0,9)) x -= 1 print(tuple(password))
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np sns.set_theme(style="darkgrid") sns.set(rc={'figure.figsize': (12, 10)}) kmax=60 tau= [1.0, 1.5, 2.0] PSNR_30=pd.DataFrame({ "Variant 00" : [21.8325, 21.8327, 21.8327 ], "Variant 01" : [21.8561, 21.8562, 21.8562 ],...
# vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 import os import sys import ConfigParser from optparse import OptionParser import pprint from convert_this import * from log_this import Log from status_this import Status class Config: """ Description: Import configuration Return Value: NA ...
from collections import deque from datetime import datetime, timedelta import errno from io import BytesIO, FileIO import os from twitter.common.lang import Compatibility from .parsers import Line class Buffer(object): CHUNKSIZE = 65536 @classmethod def maybe_filelike(cls, filename_or_filelike): if isins...