text
stringlengths
38
1.54M
import sys import struct memory_file = "WinXPSP2.vmem" sys.path.append("/Downloads/volatility-2.3.1") import volatility.conf as conf import volatility.registry as registry registry.PluginImporter() config = conf.ConfObject() import volatility.commands as commands import volatility.addrspace as addrspace con...
#-------------------------------------------------------# # Una clase es un constructor de objetos # # Class es la palabra reservada de Python para # crear una clase. # # Las clases pueden contener variables, funciones # y constructores. # # Las funciones y los constructores pueden estar # sobrecargados. # # __init__ e...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-11-16 03:58 from __future__ import unicode_literals from django.db import migrations, models import webapp.models class Migration(migrations.Migration): dependencies = [ ('webapp', '0003_auto_20171115_0851'), ] operations = [ ...
from GO4StructuralPatterns.FlyweightPattern.UnitFactory import UnitFactory from GO4StructuralPatterns.FlyweightPattern.Target import Target if __name__ == '__main__': unit_factory = UnitFactory() unit_tank_1 = Target() unit_tank_1.unit = unit_factory.get_unit('tank') unit_tank_2 = Target() unit_t...
"""Add and subtract""" import cv2 as cv import numpy as np img = cv.imread('fish.jpg') img = cv.resize(img, None, fx=0.5, fy=0.5, interpolation=cv.INTER_CUBIC) M = np.ones(img.shape, dtype='uint8') * 40 brighter = cv.add(img, M) darker = cv.subtract(img, M) img2 = np.hstack([img, brighter, darker]) cv.imshow('windo...
N = int(input()) wordlist= [] seclist = [] for i in range(N): wordlist.append(input()) seclist.append(wordlist[i]*2) existcnt = 0 for i in range(0, N): cnt = 0 for j in range(0, N): if (len(wordlist[i]) == len(seclist[j])/2) and (str(wordlist[i]) in str(seclist[j])): secli...
from enum import unique, Enum @unique class LambdaInvocationType(Enum): RequestResponse = 1, Event = 2
from rest_framework import serializers from processes.models import Process,Process_User from queues.serializers import QueueSerializer class ProcessSerializer(serializers.ModelSerializer): queues =QueueSerializer(many=True) class Meta: model=Process fields='__all__' class CreateProcessSerializ...
from sqlalchemy import or_ from lib.util_sqlalchemy import ResourceMixin from app.extensions import db class Table(ResourceMixin, db.Model): __tablename__ = 'tables' # Objects. id = db.Column(db.Integer, primary_key=True) table_id = db.Column(db.String(255), unique=False, index=True, nullable=True,...
import time import pytest import logging from selenium import webdriver from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener from selenium.webdriver.common.keys import Keys import json from OpenCart.Drivers import get_driver_path @pytest.fixture def chrome_browser(request): o...
import copy from typing import List from aiosmb.dcerpc.v5.common.connection.connectionstring import DCERPCStringBinding from asysocks.unicomm.common.proxy import UniProxyTarget from asysocks.unicomm.common.target import UniTarget, UniProto class DCERPCTarget(UniTarget): def __init__(self, connection_string:str, ip,...
# ~~~~parameters~~~~~ # the src file with answer test_file = '/home/vistajin/Desktop/test-001.txt' flag = False with open(test_file, 'r', encoding='UTF-8') as f: all_content = f.readlines() for line in all_content: if line.startswith("*Question"): flag = True print("===========...
user_input = int(input('Введите первое число: ')) user_input2 = int(input('Введите второе число: ')) result = user_input + user_input2 result2 = user_input * user_input2 if result < 1000: print(f'Сумма {user_input} и {user_input2} = {result}') else: print (f'Произведение {user_input} и {user_input2} = {r...
import math import sys from os import rename import requests print("This is a test") r = requests.get( "https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwjh2rWO5o3oAhUtxosKHdW6AigQPAgH" ) print(r.ok) print(r.status_code) a = "asdas"
s = float(input('Qual o salário do funcionário? R$ ')) if s > 1250.00: print('Quem ganhava R$ \33[33m{:.2f}\33[m, passa a ganhar R$ \33[36m{:.2f}\33[m agora.'.format(s, (s * 1.10))) elif s <= 1250.00: print('Quem ganhava R$ \33[33m{:.2f}\33[m, passa a ganhar R$ \33[31m{:.2f}\33[m agora.'.format(s, (s * 1.15...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('oilstandart', '0016_auto_20170913_1430'), ] operations = [ migrations.AlterField( model_name='contacts', ...
import urllib3 url = "http://www.baidu.com" http = urllib3.PoolManager() # type: urllib3.poolmanager.PoolManager print(http.__class__) response1 = http.urlopen('GET', url) # type: urllib3.response.HTTPResponse print("####### 方法1 #######") # 获取状态码,200表示成功 print(response1.status) # 获取网页内容的长度 print(response1.version) pr...
# WHY ARE THERE NO ++ AND -- OPERATORS IN PYTHON? ''' Simple increment and decrement aren't needed as much as in other languages. You don't write things like for(int i = 0; i < 10; ++i) in Python very often; instead you do things like for i in range(0, 10) More in the following link: http://stackoverflow.com/question...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from maths.math_lib import int_nthroot def isprimepower(n: int): x = n power = 1 while x >= 2: power += 1 x = int_nthroot(n, power) if x ** power == n: return x, power return n, 1
# 최대값을 만들기 위해서 곱하기 또는 더하기를 선택해야 하는데 # 0, 1이 피연산자인 경우에는 곱하기보다 더하기를 선택하는 것이 맞다. nums = list(map(int, input())) result = nums[0] for i in range(1, len(nums)): if nums[i] <= 1 or result <= 1: result += nums[i] else: result *= nums[i] print(result)
#!/usr/bin/env python """ Implementation of the CarlaHandler class. CarlaHandler class provides some custom built APIs for Carla. """ __author__ = "Mayank Singal" __maintainer__ = "Mayank Singal" __email__ = "mayanksi@andrew.cmu.edu" __version__ = "0.1" import random import time import math import numpy as np impo...
import re # 匹配.com或.cn后缀的URL网址 pattern = "[a-zA-Z]+:// [^\s]*[.com|.cn]" string = "<a href='http:// www.baidu.com'>百度首页</a>" print(re.search(pattern, string)) # 匹配电话号码 pattern = "\d{4}-\d{7}|\d{3}-\d{8}" string = "021-6728263653682382265236" print(re.search(pattern, string)) # 匹配电子邮件地址 pattern = "\w+([.+-]\w+)*@\w+(...
# Generated by Django 3.0.8 on 2020-07-10 10:50 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Drainase', ...
# -*- coding: utf-8 -*- """ Created on Mon Sep 14 13:17:40 2020 @author: 60342 """ # In[1]: Import several important libs. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from patsy import dmatrices from sklearn import metrics from sklearn.metrics import co...
from __future__ import unicode_literals import os import zipfile import time from django.contrib.auth.models import User from django.db import models # Create your models here. from django.db.models.signals import post_save from django.dispatch import receiver from judge import config def get_image_path(instance...
#!/usr/bin/python # -*- coding: UTF8 -*- import pymongo import sys # Homework 3.1 · Course M101P # # Write a program in the language of your choice that will remove # the lowest homework score for each student. Since there is a single # document for each student containing an array of scores, you will # need to updat...
""" Motorola 68k chip definition """ from .memory import Memory from ..core.enum.register import Register, FULL_SIZE_REGISTERS, ALL_ADDRESS_REGISTERS from ..core.enum.condition_status_code import ConditionStatusCode from ..core.models.list_file import ListFile import typing import binascii from ..core.models.memory_va...
import pygame import sys from pygame.locals import * import Danji_Game_Part import json from game import * import os class Game_page_C(): def __init__(self,mordern): self.load() self.Black = (0,0,0) self.size = 1012, 596 self.bg_imag = "source/background/Back_Ground3~1.png" ...
''' 思路: 1、单个api请求能成功 request进行请求 2、用unittest 获取key,syestemd的请求独立成一个函数,方便调用 每个接口写成一个单独的类 3、htmlrunner生成测试报告 ''' # # #time # # # import unittest,requests,hashlib,time,json # class Api_all(unittest.TestCase): # def setUp(self): # self.time =str(int(time.time()*1000)) # m2 =hashlib.md5() # scr = '72...
__author__ = 'Leandru' from kivy.app import App from kivy.core.audio import SoundLoader from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.floatlayout import FloatLayout from kivy.uix.popup import Popup from kivy.uix.image import Image from kivy.uix.button import Button from kivy.ui...
#! /usr/bin/python """ Driver program for L1-mock. """ import argparse import sys import logging import yaml from ch_L1mock import manager logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) main_parser = argparse.ArgumentParser( description="Run the CHIME FRB L1 processing mock...
"""Email pages.""" import operator import flask from dnstwister import app, emailer, repository, stats_store import dnstwister.tools as tools import dnstwister.tools.email as email_tools from dnstwister.configuration import features ERRORS = ( 'Email address is required', ) def raise_not_found_if_not_flagged_...
# Create your views here. # -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response from django.template.context import RequestContext import adb,os import settings #处理url里的creat def index(request): print 'in Chane' #return HttpResponse('test index') data ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 19/8/6 下午4:01 # @Author : liaozz # @File : forms.py """ 自我介绍一下 """ from django import forms from captcha.fields import CaptchaField class UserForm(forms.Form): captcha = CaptchaField(label='验证码') username = forms.CharField(label="用户名", max_len...
import os import csv import sys from PySide.QtGui import * from PySide.QtCore import * from ui_EventList import Ui_EventList from EventWindow import EventWindow if sys.version_info >= (3,0): from builtins import str as text else: def text( data ): return unicode( data ) class EventListWindow(QDialo...
# kkeras.py import numpy as np #np.random.seed(1337) # for reproducibility from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.layers import Convolution1D, Flatten from keras.optimizers import RMSprop #,SGD, Adam, from keras.utils import np_utils from keras import callb...
from django.db import models from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager from django.conf import settings from django.utils.text import Truncator class UserProfileManager(BaseUserManager): """Manager for uswer profiles""" def _create_user(self,email,name,password,**...
# # Copyright (c) 2010 BitTorrent Inc. # import BaseHTTPServer import logging import SimpleHTTPServer import os import urllib import apps.command.base class GriffinRequests(SimpleHTTPServer.SimpleHTTPRequestHandler): def address_string(self): # Non-localhost calls get timeouts in getfqdn # (why ...
import model import view # TODO update print statements for trader menu 3 + 7 def main_menu(): """main menu for account creation/login""" while True: print() view.welcome() print() view.main_menu_options() try: mm_choice = int(view.menu_input()) ...
"""Statistics Tool for Answerable This file contains the functions used to analyze user answers. """ # # TAG RELATED METRICS (USING QA) # _tags_info = None def tags_info(qa): """Map each tag to its score, acceptance and count""" global _tags_info if _tags_info is not None: return _tags_info ...
from array import * def dupli(n): n_set=set() n_dupli=-1 for i in range(len(n)): if n[i] in n_set: return n[i] else: n_set.add(n[i]) return n_dupli n=array('i',[1,3,5,4,32,65,53,243,3]) print(dupli(n))
import re import io import deckstat_interface as deckstat import logging from utils import set_boosters from time import sleep from random import shuffle from filters import restrict, SealedConv, UserType from functools import partial from model import session, Cube, CubeList, Game, Player, Card, Deck, DeckLi...
# while <불 표현식> # 명령어 # i =0 # while i < 10 : # print(i) # i += 1 # numbers =[1,3,1,5,18,1,0] # while 1 in numbers: # numbers.remove(1) # print(numbers) # 특정 시간 동안 대기하는 프로그램 작성 # import time # fi = time.time() # while fi + 3 >= time.time(): # pass # print("3초가 지났습니다.") # import time # fi...
import pygame, enemy, random, graph FULLSTORYTIME=10000 def happen(storytime, surface, scr): t = storytime if t == 0: FULLSTORYTIME=12000 graph.dMP = 0.2 elif t <= 1000: if t//200 == t/200: enemy.OrdinEne(random.choice(['L', 'R', 'U', '...
import pandas as pd import numpy as np import time import matplotlib.pyplot as plt dataset= pd.read_csv('HR.csv') X=dataset.iloc[:,1:13] y=dataset.iloc[:,-1] m= np.shape(X)[0] n= np.shape(X)[1] #Age bin from sklearn.preprocessing import KBinsDiscretizer est = KBinsDiscretizer(n_bins=6, encode='ordinal', strategy='uni...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import time from time import strftime from datetime import datetime import digitalocean import sys try: import keyring keychain = True except ImportError: keychain = False import logging import argparse __version__ = '0.1' ############################################...
#%% import tensorflow as tf import itertools import numpy as np from random import randint from math import ceil def utiltest(): print('Utilitie function test.') #region Multivariate gaussian distribution # class for substituting package tensorflow_probability.MultivariateNormalDiag class MultivariateNormalDiag: ...
''' FizzBuzz challenge: - For multiples of 3 print "Fizz" - for multiples of 5 print "Buzz" - If the number is a multiple of 3 and 5 print "FizzBuzz" ''' class FizzBuzz: def fizz_buzz(self, num): if num % 3 and num % 5 == 0: print("FizzBuzz") elif num % 3 == 0: print("Fizz...
# -*- coding:utf-8 -*- __author__ = 'angelwhu' import binascii import requests import sys session = requests.Session() def test(input): url = "http://202.120.7.197/app.php?action=search&keyword=&order=if(" + input + ",name,price)" print url headers = {"Accept-Encoding": "gzip, deflate", "A...
#!/usr/bin/python from PageRankIter_W import PageRankIter_W from PageRankDist_W import PageRankDist_W from PageRankSort_W import PageRankSort_W from helper import getCounter, getCounters from subprocess import call, check_output from time import time import sys, getopt, datetime, os # parse parameter if __name__ == "...
from django.core.cache import cache from rest_framework import serializers from thenewboston.constants.network import BALANCE_LOCK_LENGTH, VERIFY_KEY_LENGTH from thenewboston.serializers.network_block import NetworkBlockSerializer from v1.cache_tools.cache_keys import CONFIRMATION_BLOCK_QUEUE from v1.tasks.confirmatio...
from rest_framework import serializers from .. import models class ResourcesSerializer(serializers.ModelSerializer): class Meta: model = models.Resources fields = ('money', 'hydrocarbon')
# Longest Collatz sequence ''' The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this sequence (starting at ...
import tweepy import time from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener import json from http.client import IncompleteRead import csv consumer_key = None consumer_secret = None access_token = None access_secret = None auth = OAuthHandler(consumer_key, consumer_s...
import matplotlib.pyplot as plt import seaborn as sns def plot_bar(data, x, y, title, label_x_axis='', label_y_axis='', with_annotation=True, save_as=''): sns.set_style('whitegrid') bar,ax = plt.subplots(figsize=(10,6)) ax = sns.barplot(x=x, y=y, data=data, ci=None, palette='muted',orient='v', ) ...
# tuple data structure # tuples can store any data type # most imporatant is tuples are immuatable, it cant be changed once created # example = ('one','two','three') # # no append, no insert , no pop, no remove # For better practice, should be used only if we know, data is not going to change # Why to use t...
from collections import Counter def calculate_gc_content(sequence): """ Receives a DNA sequence (A, G, C, or T) Returns the percentage of GC content (rounded to the last two digits) """ joined = "".join(sequence.lower()) count = Counter(joined) return round((count['g'] + count['c']) / ...
import random from prefect.utilities.annotations import unmapped class TestUnmapped: def test_always_returns_same_value(self): thing = unmapped("hello") for _ in range(10): assert thing[random.randint(0, 100)] == "hello"
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @copyright: icekredit Tech, LTD file_name:guang_dong_fa_yuan_wang.py description: 广东法院网 author:crazy_jacky version: 1.0 date:2018/9/19 """ import re import time import json import traceback from lxml import etree from ics.utils import get_ics_logger from ics.utils.exc...
import csv import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.feature_extraction import DictVectorizer from sklearn.cross_validation import train_test_split from sklearn import cross_validation from sklearn.model_selection import cross_val_predict from sklearn import tree from sklear...
from tkinter import * from tkinter import messagebox w=Tk() w.geometry("400x300") w.title("login") w.config(bg="pink") Label(text="username").grid(row=0,column=0) username=Entry() username.grid(row=0,column=1) Label(text="password").grid(row=1,column=0) password=Entry(show="*") password.grid(row=1,column=1) ...
import pandas as pd from pyArango.connection import * movies = pd.read_csv('http://bit.ly/imdbratings') conn = Connection(username='root', password='1234') db_filmes = conn["Filmes"] col_filmes = db_filmes.createCollection(name="filmesAmericanos") db_filmes['filmesAmericanos'] doc1 = db_filmes["filmesAmericanos"]....
# -*- coding: utf-8 -*- """ Created on Tue Jul 14 10:03:29 2020 @author: user """ 華氏溫度 = input("輸入華式溫度:") 攝氏溫度 = int(華氏溫度) * 5 / 9 - 32 print(攝氏溫度)
"""1. 아래와 같이 숫자를 두번 물어보게 하고 ★을 출력해서 사각형을 만드시오 가로의 숫자를 입력하시오 : 세로의 숫자를 입력하시오 : """ import numpy as np a= int(input('가로의 숫자를 입력하시오:')) b= int(input('세로의 숫자를 입력하시오:')) for i in range(b): for j in range(a): print('*', end='') print()
#coding: utf-8 __author__ = 'lufee' import os basedir = os.path.abspath(os.path.dirname(__file__)) class Config: SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' FLASKY_ADMIN = 'lufeewu@gmail.com' # 注册管理员的用户 FLASKY_POSTS_PER_PAGE = 20 @staticmethod def init_app(app): p...
import bs4 import re import urllib.request from urllib.request import Request, urlopen #Url utilisée pour le scraping url="https://www.monpetitgazon.com" req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) web_byte = urlopen(req).read() webpage = web_byte.decode('utf-8') soup = bs4.BeautifulSoup(webpage, 'html...
""" This type stub file was generated by pyright. """ from .vtkObject import vtkObject class vtkDebugLeaks(vtkObject): """ vtkDebugLeaks - identify memory leaks at program termination vtkDebugLeaks is used to report memory leaks at the exit of the program. Superclass: vtkObject It us...
# -*- coding: utf-8 -*- import logging import zmq class AdhsClient(object): def __init__(self): self.logger = logging.getLogger(self.__class__.__name__) self._active_servers = [] self.context = zmq.Context() self.requester = self.context.socket(zmq.REQ) self.requester.se...
import json with open('neighbor-districts.json') as f: data = json.load(f) f.close() assam_districts = {'c': 'as', 'd' : ['baksa','barpeta','bishwanath','bongaigaon','cachar','charaideo','chirang','darrang','dhemaji', 'dhubri','dibrugarh', 'dima hasao', 'goalpara', 'golaghat', 'hailakandi', 'hojai', 'jorhat','kamru...
from cnoid.Base import * from cnoid.BodyPlugin import * sr1 = Item.find("SR1").body() floorLink = Item.find("Floor").body().rootLink() simulator = Item.find("AISTSimulator") handler = simulator.collisionHandlerId() simulator.setCollisionHandler(sr1.link("LLEG_ANKLE_R"), floorLink, handler) simulator.setCollisionHandl...
from sklearn.preprocessing import Imputer impute = Imputer(missing_values = 0, strategy='mean', axis=0) impute.fit_transform(X_train)
import pandas import wget #wget.download("https://kodim.cz/czechitas/progr2-python/python-pro-data-1/zakladni-dotazy/assets/staty.json") staty = pandas.read_json("staty.json") staty = staty.set_index("name") #print(staty.info()) #print(staty.loc["Czech Republic":"Dominican Republic"]) #print(staty.loc["Uzbekistan":]) ...
from unittest import TestCase, main def soma(a, b): return a + b class Testes(TestCase): def test_soma01(self): self.assertEqual(soma(2,2), 4) if __name__ == '__main__': main()
def checkio(number): m = 1 nums = [int(i) for i in str(number) if i != "0"] for num in nums : m *= num return m #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio(123405) == 120 assert checkio(999) == 729 assert ch...
""" This directory holds 2 files: currentWeather.py pastFutureWeather.py currentWeather.py accesses what is currently happening, uses owm.weather_manager() and a city ID pastFutureWeather.py accesses yesterday's and the next 7 day's weather using owm.one_call() and Latitude and Longitude """
# -*- coding: utf-8 -*- { 'name': "aikchin_modifier_access_right", 'summary': """ Aik Chin Access Right""", 'description': """ Aik Chin Access Right """, 'author': "Hashmicro / Luc", 'website': "http://www.hashmicro.com", # Categories can be used to filter modules in modu...
import pytest from selenium import webdriver from selenium.webdriver.chrome.options import Options from pages.basePage import BasePage from data.dataRedirects import TEST_DATA_ABPO from data.dataRedirects import TEST_DATA_DIFFERENT_DOMAIN import utils.global_functions as gf @pytest.fixture def driver(): optio...
#反转字符串 def all(): name = input('输入文件名字') f = open(name,'w') f.write('123abcdefg') con = name.rfind('.') ff = open(name[0:con]+'_copy'+name[con:],'w') def r_string(): book = f.rread(1) if ff.rread=='': return '' else: return ff.write(book) r_string() f.close() ff.close() all()
from django.contrib import admin from .models import Article, Location admin.site.register(Article) admin.site.register(Location)
#!/usr/bin/env python3 """Runs the ReQTL analysis using MatrixEQTL Created on Aug, 29 2020 @author: Nawaf Alomran This module is based off the sample code from Shabalin, et al (2012) which is an R package "designed for fast eQTL analysis on large datasets that test for association between genotype and gene expressi...
import json from zipfile import ZipFile from .resources import PebbleResources class PebbleSystemResources(object): def __init__(self, firmware_path): self._firmware_path = firmware_path self._zipfile = ZipFile(firmware_path) self._manifest = json.loads(self._zipfile.read('manifest.json')...
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np from tqdm import tqdm from collections import Counter import logging class Vocab(object): def __init__(self): self.token2id, self.id2token, self.token_cnt = {}, {}, {} self.pad_token = '<PAD>' self.unk_token = '<UNK>' self...
from functools import reduce quiz_grades = [98, 94, 96, 97, 99, 97] print(reduce(lambda total, element: total+element, quiz_grades)) user_string = input('String:').split(',') sorted_string = sorted(user_string) print(sorted_string) def char_counter(string_to_count): char_counts = {} for char in string_to_count:...
import inspect import re import time from abc import ABC, abstractmethod from contextlib import suppress from typing import Any, Callable, Union, List, Dict import decorator class JunitDecorator(ABC): _func: Union[Callable, None] _start_time: Union[float, None] _stack_locals: List[Dict[str, Any]] d...
#!/usr/bin/env python # encoding: utf-8 import os import numpy as np import time from configparser import RawConfigParser, NoSectionError import matplotlib.ticker import matplotlib.dates as mpd class ExperimentConfigFile(RawConfigParser, matplotlib.ticker.Formatter): ...
from typing import Tuple, List class Dice: def __init__(self, top, left, front, cost=0): self.top = top self.bottom = 7 - top self.left = left self.right = 7 - left self.front = front self.back = 7 - front self.cost = cost def __repr__(self): re...
from flask import Flask, jsonify, request from sklearn.externals import joblib from flask_cors import CORS # for printing to console for testing import sys from helpers import create_df from helpers import prep_df from helpers import groupby_to_dict from sklearn.linear_model import LogisticRegression from sklearn.line...
from functools import reduce def transformar_lista(elemento) -> list: salida = [] aux = [] for elementox in elemento[1:]: aux.append(elementox[1]) temp = [elemento[0], reduce(lambda acumulador = 0, elemento = 0: acumulador + elemento, aux)] salida= temp return salida def inf...
from pyspark.streaming.kafka import KafkaUtils from pyspark import SparkContext from pyspark.streaming import StreamingContext import sys import json sc = SparkContext.getOrCreate() sc.stop() sc = SparkContext(appName = "PythonStreamingReciever") ssc = StreamingContext(sc, 5) kafkaStream = KafkaUtils.createStream(ssc...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import sleep driver=webdriver.Chrome() add='https://web.wh...
import win32gui def list_window_names(): def winEnumHandler(hwnd, ctx): if win32gui.IsWindowVisible(hwnd): print(hex(hwnd), win32gui.GetWindowText(hwnd)) win32gui.EnumWindows(winEnumHandler, None) list_window_names()
import numpy as np import tensorflow as tf import math from dataset import MnistDataset IMG_SIZE = 28 class CNNMnistLayer: def __init__(self, filters: list, kernel_size: int = 3, name: str = None): self.layers = [] self.name = name for index, filter_count in enumerate(filters): ...
from urllib import request, parse url = 'http://httpbin.org/post' header = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Host': 'httpbin.org' } dict = { 'name': 'test' } data = bytes(parse.urlencode(dict), encoding='utf8') req = request.Request(url=url, data=data, headers=header, method='POS...
from dao.abstractDAO import AbstractDAO from entidades.aluno import Aluno class AlunoDAO(AbstractDAO): def __init__(self) -> None: super().__init__('alunos.pkl') def get(self, key): if isinstance(key, int): return super().get(key) def add(self, matricula, aluno): if...
import turtle,random turtle.width(10) turtle.speed(0) x=0 colors=["red","blue","cyan","magenta","gold","gray","black","yellow","orange","green"] while True: color=random.choice(colors) turtle.color(color) x=x+5 turtle.forward(x) turtle.right(170)
class testClass(object): print "Creating New Class\n==================" number=5 def __init__(self, string): self.string = string def printClass(self): print "Number = %d"% self.number print "String = %s"% self.string tc = testClass("Five") tc.printClass() tc.number =...
import math import json import yaml import curses import traceback import websocket from pprint import pprint from websocket import create_connection from termcolor import colored BASEURL_SHITMEX = 'wss://www.bitmex.com/realtime' BASEURL_COINBASE = 'wss://ws-feed.pro.coinbase.com' def coinbase_sock_connect(): ws = ...
#!/usr/bin/env python #_*_coding:utf-8_*_ import re import numpy as np from sklearn.model_selection import StratifiedKFold import tensorflow as tf from tensorflow import keras from tensorflow.python.keras.callbacks import EarlyStopping def Second_Model_DNN_One_HOT(blend_train_data,blend_train_label,blend_test...
import matplotlib.pyplot as plt import numpy as np import matplotlib import pandas as pd import os import ObjEval_ES_ILS as obj import pylab as pl import itertools ''' to compute all possible permutations # using itertools.product()''' def get_score(parameter, lib, res): key = tuple(parameter) return res[li...
import csv from sklearn.cluster import KMeans K = 5 data_arr = [] url_name_arr = [] MY_FILE = 'output.csv' top_row = [] errors = {"HttpError": 1, "DNSLookupError": 2, "TimeoutError": 3, "Other": 4} with open(MY_FILE, 'rb') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i == 0: ...