text
stringlengths
38
1.54M
""" Script criado para customizar conversores de URL. Após isso, é necessário importar no script principal (app.py), e acrescentar nossos conversores no app.url_map.converters """ from werkzeug.routing import BaseConverter # Customizar o regex class RegexConverter(BaseConverter): def __init__(self, url_map, *items...
# -*- coding: utf-8 -*- """ 执行脚本main.py 描述: 该demo是展示如何计算带约束的离散型变量的单目标优化问题 本案例通过调用sga_real_templet算法模板来解决该问题 其中目标函数写在aimfuc.py文件中 """ import numpy as np import geatpy as ga # 获取函数接口地址 AIM_M = __import__('aimfuc') # 变量设置 ranges = np.vstack([np.zeros((1, 4)), np.ones((1, 4))]) # 生成自变量的范围矩阵 borders = np.vstac...
#!usr/bin/python import cv2 import numpy import matplotlib as plt img = cv2.imread('Wolverine.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows()
# Generated by Django 2.2.6 on 2019-11-03 04:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('work', '0005_auto_20191102_1556'), ] operations = [ migrations.AlterField( model_name='progressqty', name='dtr_100',...
import random import time from threading import Thread, Lock import numpy from prometheus_client import Info from constants import tick_time, seed, high_quality, related_product, sentiment_sensitive from google_ads import GoogleAds from market import Market from twitter import Twitter import logging import mysql imp...
from smartshark.mongohandler import handler from server.base import SUBSTITUTIONS from django.contrib import messages def create_substitutions_for_display(): display_dict = {} for substitution, value in SUBSTITUTIONS.items(): display_dict[value['name']] = value['description'] return display_dict ...
#! /usr/bin/python #! encoding: UTF-8 import numpy as np import matplotlib.pyplot as plt x=np.arange(-10,10,0.1) y=4/(1+x²) plt.plot(x,y) plt.show()
# Generated by Django 3.0.7 on 2020-06-26 11:31 import django.core.validators from django.db import migrations, models import django.db.models.deletion import phonenumber_field.modelfields class Migration(migrations.Migration): dependencies = [ ('Account', '0001_initial'), ] operations = [ ...
#Program for buble sort def buble_sort(arr): length=len(arr) for index in range(length): print("index",index) for inside_index in range(0,length-index-1): print("index for",inside_index) if arr[inside_index]>arr[inside_index+1]: print("inside_ind...
import tensorflow as tf import tensorflow.contrib.slim as slim class Digit_model(): def __init__(self, config): self.config = config self.build_model() self.init_saver() # init the global step self.init_global_step() # init the epoch counter self.init_cur_e...
#!/usr/bin/python # # SetConfig.py # # Copyright (c) 2008-2009 Apple, Inc. All rights reserved. # from config import ConfigurationError from config import Config class commandLineSettings: configPath ="/Library/Preferences/com.apple.securityproxy_mail.plist" list = False tag = "" value = "" debu...
""" Copyright (C) 2012 Alan J Lockett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,...
#Dirt House program written by Caleb Barnwell #Computer Science, 11-8-15 import turtle wn=turtle.Screen() epic=turtle.Turtle() epic.fillcolor("brown") epic.speed(7) def Block(t): t.begin_fill() for i in range(4): t.forward(20) t.left(90) t.end_fill() def fourBlockSquare(t)...
import sys import hashlib from django.core.files.uploadedfile import InMemoryUploadedFile import json def collapse_white_spaces(value=None): value_retorned = None if value is not None and value.__class__ is str and value.strip(): value_retorned = value.strip() return value_retorned def hash_file(f...
''' Implementa funciones que permiten animar pendulos con matplotlib. ''' # ---Imports--- # matplotlib.pyplot (plt): impresion grafica 2D import matplotlib.pyplot as plt # matplotlib.animation (anim): animacion grafica import matplotlib.animation as anim # mpl_toolkits.mplot3d.Axes3D: impresion grafica 3D from mpl_too...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import time from graph_nets import utils_np from graph_nets import utils_tf from graph_nets.demos_tf2 import models import numpy as np import sonnet as snt import tensorflow as tf SEED = 1 np.random.seed...
import sys import os import random import json import string from flask import Flask, render_template, url_for, flash, redirect, request, jsonify, session, make_response from flask_bcrypt import Bcrypt #package for password encryption from pyArango.connection import * from oauthlib.oauth2 import WebAp...
# Python2.7 Flask app for libraries not compatible with 3.6+ # Requires: # - nltk.download('punkt') # - nltk.download('averaged_perceptron_tagger') # - nltk.download('stopwords') from flask import Flask, jsonify, abort, request, send_from_directory app = Flask(__name__) default_data = {} default_data['web64']...
import sys from PyQt5 import uic from PyQt5 import QtCore, QtMultimedia from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QDialog, QMessageBox import sqlite3 import hashlib class RegistrationWindow(QMainWindow, QDialog): def __init__(self): super().__init__() uic.lo...
import itertools file = open('euler011.txt') str = ''.join([line.lstrip() for line in file]) file.close() GRIDSIZE = 20 def grouper(n, iterable, fillvalue = None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.zip_longest(*args, fillvalue = fillvalue) def ...
from django.core.validators import RegexValidator import re comma_separated_float_list_re = re.compile('^([-+]?\d*\.?\d+[,\s]*)+$') validate_comma_separated_float_list = RegexValidator(comma_separated_float_list_re, (u'Enter only floats separated by commas.'), 'invalid')
import os import sys import math import numpy as np import tensorflow as tf from keras.datasets import imdb from keras.models import Sequential from keras.callbacks import History from keras.models import load_model from keras.optimizers import RMSprop from keras.preprocessing import sequence from keras.layers import D...
import os import time import random i = 0 race_length = 40 leading_horse = 0 horse1_active_pos = 0 ## horse active positions are declared here so += is able to work horse2_active_pos = 0 horse3_active_pos = 0 horse_speed_list = [] horse_names = [] horse_stats = eval(open("horses/temp_horses.txt").read()) horse_names_...
import torch from ceit import CeiT from module import LeFF def testCeit(): img = torch.ones([1, 3, 224, 224]) model = CeiT(image_size = 224, patch_size = 4, num_classes = 100) out = model(img) print("Shape of out :", out.shape) # [B, num_classes] model = CeiT(image_size = 224, patch_size = ...
from django.core.exceptions import ValidationError import os def validate_file_type(f): ext = os.path.splitext(f.name)[1] valid_extensions = ['.docx'] if ext.lower() not in valid_extensions: raise ValidationError('file must be .docx formate!') def validate_project_name(value): if value == '': raise Validatio...
from openmdao.api import Problem from omtools.api import Group import omtools.api as ot import numpy as np class ExampleMatrix(Group): def setup(self): # Declare mat as an input matrix with shape = (4, 2) mat = self.declare_input( 'M1', val=np.arange(4 * 2).reshape((4, 2))...
from os import system # Header title print("GIST-CLI.py by Matt \'TheFrostlixen\' Fredrickson 2015\n--------") # Program loop while True: cmds = input('$ ') if len(cmds) > 0: system("gist.py " + cmds)
#!/usr/bin/env python ''' Script para unescape de caracteres especiais ISO-8859-1 Autor: Mayron Cachina Contato: mayroncachina@gmail.com Site: http://cachina.wordpress.com Egg mantainer & unescape digits Autor: Vsevolod Balashov mail/xmpp: vsevolod@balashov.name site: http://vsevolod.balashov.name ''' import htmlent...
from stk_data_flow import * class stk_tcp_server: def __init__(self,env,name,id,options,ref=None): if ref == None: self._df = stk_tcp_server_create_data_flow(env.ref(),name,id,options.ref()) if self._df == None: raise Exception("Failed to create tcp server data flow") else: self._df = ref self._id =...
from django.contrib import admin from django.urls import path from django.contrib.auth.views import LoginView from django.contrib.auth.views import LogoutView from blog.views import BlogListView from blog.views import BlogDetailView from blog.views import BlogCreateView from blog.views import BlogUpdateView from blog....
""" @dsikka - Script to experiment with different feature selection methods and compare/contract methods in terms of outputs given """ import os import pandas as pd import sklearn.feature_selection import matplotlib.pyplot as plt import numpy as np from os import path from sklearn.ensemble import RandomForestClass...
import re import base64 import numpy as np from PIL import Image from io import BytesIO def base64_to_pil(img_base64): """ Convert base64 image data to PIL image """ image_data = re.sub('^data:image/.+;base64,', '', img_base64) pil_image = Image.open(BytesIO(base64.b64decode(image_data))) re...
import openpyxl from openpyxl.utils import get_column_letter with open('atum.txt') as file: atum = file.readlines() with open('chinelos.txt') as file: chinelos = file.readlines() with open('cabelo.txt') as file: cabelo = file.readlines() wb = openpyxl.Workbook() sheet = wb.active column = 1 ...
import importlib from peewee_migrate import Router from colibris import persist from colibris.conf import settings from .base import BaseCommand class MakeMigrationsCommand(BaseCommand): def add_arguments(self, parser): parser.add_argument('name', help='An optional migration name', type=str, default='...
# -*- coding: utf-8 -*- import os from os.path import dirname, join SECRET_KEY = os.urandom(16) # configure file based session SESSION_TYPE = "filesystem" SESSION_FILE_DIR = join(dirname(__file__), "cache") # configure flask app for local development ENV = "development"
from bson.objectid import ObjectId from ml_forest.core.utils.docs_init import root_database from ml_forest.core.constructions.io_handler import IOHandler from ml_forest.core.constructions.core_init import CoreInit from ml_forest.pipeline.nodes.stacking_node import FNode, LNode # TODO: need a much better way to inspe...
from flask_restplus import Api, Resource, fields from flask import Flask, request, jsonify import os app = Flask(__name__) api = Api(app, version='1.0', title='Simple Flask App', description='This is a flask app for flasking things and apping') ns = api.namespace('Flask-Space', description='Methodical methods') singl...
import json from pathlib import Path from typing import Dict, Generator, Tuple from mowgli_etl._transformer import _Transformer from mowgli_etl.model.benchmark import Benchmark from mowgli_etl.model.benchmark_answer import BenchmarkAnswer from mowgli_etl.model.benchmark_answer_explanation import BenchmarkAnswerExplana...
#!/usr/bin/python import sys def main(args): f = open(args[1], 'r') lf = open(args[2], 'r') feats = open(args[3], 'r') o = open(args[4], 'w+') feat_list = [] for line in feats: ls = line.strip().split(' ') num_feats = len(ls) feat_list.append(ls) o.w...
mylist = [] mylist.append("a") mylist.append(12) mylist.append(20) print(mylist) print(len(mylist)) del mylist[2] print(mylist) # [a, 12, 20] # [0 1 2] mylist[2]=30 #mengedit isi list print(mylist) a = int(input("Masukkan data ke dalam mylist : ")) mylist.append(a) print(mylist) print(len(mylist))
#!/usr/bin/env python from __future__ import division, print_function import numpy as np import rospy from rospkg.rospack import RosPack from copy import deepcopy from tf2_ros import TransformListener, Buffer from bopt_grasp_quality.srv import bopt, boptResponse from bayesian_optimization import Random_Explorer from b...
num_1 = 10 num_2 = 3 divisao = num_1 / num_2 nome = 'Ivander' sobrenome = 'Salvador' print(f'{divisao:.2f}') print(f'{num_1:.2f}') print(f'{num_1:0^10}') print(f'{nome:#^20}') print(f'{num_1:0>10.2f}') print('{:@>30}'.format(nome)) print('{n:@>30} {n:@<20}'.format(n=nome)) print('{1:!^15}'.format(nome, sobrenome)) p...
# 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 # distrib...
import cv2 import numpy as np import time import os # Load YOLO, pretrained with COCO dataset # If you have GPU available, change "yolov3-tiny" to "yolov3" in both lines. # That way you get to use the heavier and more accurate version of YOLO. # You have to also download the weights for this model, which can be foun...
def fibo(n): fibo_atual = 0 fibo_anterior = 1 for numero in range(n): # antes da comparação vale que fibo_atual == F(i) fibo_prox = fibo_anterior + fibo_atual fibo_anterior = fibo_atual fibo_atual = fibo_prox numero = numero + 1 return fibo_atual def main(): prin...
import logging import sys, os root = logging.getLogger() root.setLevel(logging.DEBUG) log = logging.getLogger(__name__) handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) roo...
""" vision.py handels communications with the Google Vision API """ import json import requests from numpy import interp from src import app URL = 'https://vision.googleapis.com/v1/images:annotate?fields=responses&key=' KEY = app.config.get('VISION_KEY') EMOTION_MATRIX = json.loads(app.config.get('EMOTION_MATRIX')) E...
########################################################## # Zusammenfassung: Überprüfung folgender Klassifikationsverfahren: # KNN - KNearest Neighbor # Random Forest # Gradient Boosting # SVM - Support Vector Machine # # In diesem File wurde bei allen Verfahren (KNN, Random Forest, Gradient Boosting, SVM) # jeweils e...
a = input("Name: ") b = input("Age: ") b = input("Marks: ") class Student: def __init__(self, n, a, **m): self.name = n self.age = a self.marks = m def display(self): print("Hi", self.name) print("Your age", self.age) print("Your marks:", self.marks) s1 = St...
import json import pytest import requests from tests.acceptance.helpers import ENDPOINT_CONFIG from tests.acceptance.helpers import create_and_validate_request_and_response expected_config = """{ "environmentKey": "production", "sdkKey": "KZbunNn9bVfBWLpZPq2XC4", "revision": "131", "experimentsMap": { "a...
import images import pygame import pymunk import math DEBUG = False # Change this to set it in debug mode def physics_to_display(x): """ This function is used to convert coordinates in the physic engine into the display coordinates """ return x * images.TILE_SIZE class GameObject: """ Mostly handles vis...
import cv2 import numpy as np img=cv2.imread('wifi.png') gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) sift=cv2.SURF() cv2=sift.detect(gray,None) img=cv2.drawKeypoints(gray,img) cv2.imshow(",",img)
# Assignment Not Easy on Leap Year # https://repl.it/@appbrewery/day-3-3-exercise#README.md # What is a leap year? https://www.youtube.com/watch?v=xX96xng7sAE # Leap Year Flow chart https://bit.ly/36S1PHK year = int(input("Which year do you want to check? ")) if year%100==0: if year%400==0: print("Leap yea...
# Create Grid colCell = '+ - - - - + - - - -+' rowCell = '| + |' print(colCell) print(rowCell) print(rowCell) print(rowCell) print(rowCell) print(colCell) print(rowCell) print(rowCell) print(rowCell) print(rowCell) print(colCell)
from tkinter import * root = Tk() root.title('Kalkulator') root.configure(bg="black") e = Entry(root,width=14,font=("Verdana", 18),bg="black", fg="white", border=0) e.pack(pady=10,padx=16) my_frame = Frame(root, bg="black") my_frame.pack(padx=16, pady=14) def button_click(number): e.insert(len(e.get()), str(num...
""" Module for retrieving appnexus reporting data """ import requests from reportloader.utils.config import Config class AccountInterface(): """The 'AccountInterface' class declares the interface that must be implemented by all account. """ def getToken(self): """ it's the service t...
# -*- coding: UTF-8 -*- import unittest from DAPOS.utils.norm.cleaner import remove_diacritics class CleanerTest(unittest.TestCase): def test_remove_diacritics(self): self.assertEqual(remove_diacritics(u''), u'') self.assertEqual( remove_diacritics(u'بسم الله الرحمن الرحيم'), ...
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: if len(board)==0 or len(board[0])==0: return [] #rule 1. if a mine is revealed, change it to 'X', end the game i, j = click[0],click[1] if board[i][j]=='M': ...
""" The L1 Regularization Class """ import numpy as np from .regularizer import Regularizer class L1Regularizer(Regularizer): """ The L1 Regularizer Class to reduce overfitting. Attributes: lambd (float, optional): The hyper-parameter lambda for the L1 or L2 regularization. """ def forward...
"""Classify images using shared representation. See `test/fusion.py` for example use. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from multimodal.gesture.basics import TrainColorDepth, EvaluateColorDepth from classify.train...
import arcpy from arcpy import env sgid10 = r'C:\ZBECK\BlueStakes\testDB.gdb' stageDB = r'C:\ZBECK\BlueStakes\stagingBS.gdb' env.workspace = sgid10 fipsDict = {'Beaver': 'par49001', 'BoxElder': 'par49003', 'Cache': 'par49005', 'Carbon': 'par49007', 'Daggett': 'par49009', \ 'Davis': 'par49011', 'Duchesne': 'par49013'...
# Generated by Django 3.1.4 on 2020-12-04 07:03 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_menu_item_type'), ] operations = [ migrations.AlterField( model_name='menu', ...
# -*- coding: utf-8 -*- """ Created on Mon Mar 1 12:12:20 2021 @author: MGB """ a = 42 # Create object <42> b = a # Increase ref. count of <42> c = [a] # Increase ref. count of <42> del a # Decrease ref. count of <42> b = 100 # Decrease ref. count of <42> c[0] = -1 # Decrease ref. count of <42>
if __name__ == '__main__': #字符串 klist = [ "good ", "good ", "study", " good ", "good", "study ", "good ", " good", " study", " good ", "good", " study ", "good ", "good ", "study", " day ", "day", " up", " day ", "day", " up", " day ", "day", " up"...
from random import randint t= randint(0,100) if t<30 : print("I'm very Sad now") elif t<60: print("I'm ok") else: print("I'm Happy Now <3")
# -*- coding: UTF-8 -*- __author__ = 'zy' __time__ = '2019/12/1 21:27' from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC # 两种方法任选其一,都是指向同一个文件 from selenium.webdriver.suppor...
from tornado import gen from tornado import web from opnfv_testapi.common import raises from opnfv_testapi.db import api as dbapi from opnfv_testapi.ui.auth import base class ProfileHandler(base.BaseHandler): @web.asynchronous @gen.coroutine def get(self): openid = self.get_secure_cookie('openid'...
import math def area(r): return math.pi * (r**2) radii = [2, 5, 7.1, 0.3, 10] print(list(map(area, radii))) #### map applies the function (1st parameter) to the list (2nd parameter) #### and returns an interable. This is passed to the list contrsuctor ### filter works in a similar fashion impo...
import datetime import os import pickle from pprint import pprint from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from src.data.enums import Constants from src.data.repository import Repository class Gmail: SCO...
#!/usr/bin/python import sys import socket import threading import SocketServer import time # Since all UDP listeners are 50000 + ID, here's base port BASE_PORT = 50000 # Based on code from Python Docs here: # https://docs.python.org/2/library/socketserver.html # Base Request Handler Doc: # http://docstore.mik.ua/or...
import socket import select from _thread import * import threading import sys from datetime import datetime def chat_server(): def thread_receive(c): while True: x=c.recv(500) print(x.decode('UTF-8')) def client_thread(c): receive = threading.Thread(target=thread_receive, ...
#!/usr/bin/python3 #!-*-coding:utf-8-*- ''' #装饰器实例1(不知怎么运行正确) def logging_tool(level): def decorator(func): def wrapper(*arg,**kwargs): if level=='error': logging.error('%s is running...' % func.__name__) elif level=='warn': logging.warn('%s is runnin...
""" Allows you play the rocker lander environment using the keyboard. Up arrow: Increase throttle Down arrow: Decrease throttle Left / Right arrow: Move the throttle left and right 1 and 2: Use left and right control thrusters Credit: This is based on: https://github.com/openai/gym/blob/master/examp...
import random def netherlands(list, L, R, item): """将小于mun的放在左边大于mun的放在右边""" left, right, cur = L - 1, R + 1, L while cur < right: if list[cur] < item: list[cur], list[left + 1], cur, left = list[left + 1], list[cur], cur + 1, left + 1 elif list[cur] > item: list[cur], list[right - 1], right = list[right...
cs_courses = {'History','Math','Physics','CompSci'} art_courses = {'History', 'Math', 'Art', 'Design'} print(cs_courses.union(art_courses)) ''' Output: {'Design', 'CompSci', 'Math', 'Physics', 'Art', 'History'} '''
""" This program contains the Gaussian Elimination method For solving a system of linear equation (SoLE) In many fields of physics and mathematics we will end up having to solve a system of equations [linear or non linear depending on the physics] which can also be huge in size. The system is on the form Ax =...
#!/usr/bin/env python #regionsLegacytest1 import ROOT import os import math import pickle import argparse argParser = argparse.ArgumentParser(description = "Argument parser") argParser.add_argument('--logLevel', action='store', default='INFO', nargs='?', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', '...
#Actualizar datos import sqlite3 conexion = sqlite3.connect("Bases de datos/Ejemplos/base_datos1.db") cursor = conexion.cursor() cursor.execute("UPDATE PERSONAS SET nombre = 'Marcos' WHERE nombre = 'Javichu'") conexion.commit() conexion.close()
number = int(input("Введите целое положительное число: ")) arr = [] while number > 1: variant = number % 10 arr.append(variant) number = number // 10 print(max(arr))
# -*- coding: utf-8 -*- from __future__ import division from odoo import models, fields, api, _ import time import pytz from datetime import date, datetime, timedelta, time, date import calendar from odoo.exceptions import UserError, ValidationError, Warning from unittest2.test.test_program import RESULT from odoo.too...
from PIL import Image import boto3 bucketname = 'bucket_name' s3 = boto3.resource('s3') for i in range(5): try: s3.Bucket(bucketname).download_file('%s.jpg' % i, 'downloaded_from_aws%s.jpg' % i) img = Image.open('downloaded_from_aws%s.jpg' % i) img.show() except: continue
#!/usr/bin/python import graph_gen from collections import defaultdict as ddict def get_winner(graph): win_count = ddict(int) nodes = graph['nodes'] for node in nodes: won = True for edge in graph['edges']: if edge['source'] == node: win_count[node] += 1 ...
from sqlalchemy import Column, Integer, String, Boolean, ForeignKey, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import relationship metadata = MetaData() Base = declarative_base() """A definition of the database data of the application""" ...
"""myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-bas...
# Implementation of classic arcade game Pong import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGHT = PAD_HEIGHT / 2 LEFT = False RIGHT = True ball...
# -*- coding: utf-8 -*- import re import sys import pywikibot import savepagenow from datetime import datetime from pywikibot import pagegenerators from urllib.request import Request, urlopen def uploader(filename, link=True): """User that uploaded the file.""" history = (pywikibot.Page(SITE, filename)).revisi...
#!/usr/bin/env python # -*- coding: utf-8 -*- from slackclient import SlackClient __author__ = "JM Leroux <jmleroux.pro@gmail.com" __license__ = "OSL 3.0" class Slack: STATUS_OK = 'ok' STATUS_SENT = 'sent' STATUS_ERROR = 'error' STATUS_CHANNELS_RELOAD = 'channels_reload' def __init__(self, user...
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 selenium.webdriver.common.action_chains import ActionChains import time...
from BiRNN import BiRNN from BiRNN import BiRNN3 import torch input_size = 235 hidden_size = 128 num_layers = 2 num_classes = 2 # TODO: Determine this from the data def create_model(): rnn = BiRNN3(input_size, hidden_size, num_layers, num_classes) rnn.load_state_dict(torch.load('webapp/GRU.pkl', map_location...
import pyperclip Einglish_letter = list("qwertyuiopasdfghjkl;zxcvbnm,.") Hebrow_letter = list(("/'קראטוןםפשדגכעיחלךףזסבהנמצתץ")) text = pyperclip.paste() newText = [] for c in text: if c in Einglish_letter: index = Einglish_letter.index(c) newText.append(Hebrow_letter[index]) elif c in Hebro...
import os import yaml class Config: with open(os.path.dirname(os.path.abspath(__file__)) + "/../config.yml", "r") as f: config = yaml.load(f, Loader=yaml.SafeLoader) data_directory = config["data_directory"] image_size = config["image_size"]
# Accepted # Python 3 def findHead(num): if type(par_list[num]) == list: return num return findHead(par_list[num]) def join_two(a, b): u = type(par_list[a]); v = type(par_list[b]) if (u==list) and (v==list): p = a; q = b l = len(par_list[q]); le = len(par_list[p]) if...
# -*- coding: utf-8 -*- # Copyright 2017 Google 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 ...
from asyncio.events import AbstractEventLoop from collections import namedtuple from typing import Generator, List, Union from .base import BaseResource from .missiondesign import (MissionDesignDVLowThrust, MissionDesignObject, MissionDesignSignature) __all__ = [ 'MissionDesignResource...
import math import os import random import re import sys def plusMinus(arr): positive = 0 negative = 0 zeroes = 0 for i in arr: if i > 0: positive += 1 elif i < 0: negative += 1 else: zeroes += 1 Length = len(arr) print(positive/Lengt...
def foo(x): print("executing foo(%s)" % (x)) class A(object): def foo(self, x): print("executing foo(%s,%s)" % (self, x)) @classmethod def class_foo(cls, x): print("executing class_foo(%s,%s)" % (cls, x)) @staticmethod def static_foo(x): print("executing static_foo(%s...
#!/usr/bin/env python3 from typing import List #reference : https://zxi.mytechroad.com/blog/sp/kmp-algorithm-sp19/ def Build(p: str) -> List[int]: m = len(p) nxt = [0, 0] j = 0 for i in range(1, m): while j > 0 and p[i] != p[j]: j = nxt[j] if p[i] == p[j]: j += ...
import math from carParking import CarRules from agent import AgentState import copy from collections import Counter from twoStepAgents import TwoStepAgent class GameState: def getLegalActions_Middle(self, index=0): if self.isLose(): return [] actionSet = [] for action in CarRules.getLegalActions(self):...
""" Geo_tools ========= Package to deal with geodata. TODO ---- geo_retrieve? pyproj? fiona? """ from geo_transformations import general_projection, radians2degrees,\ degrees2radians, ellipsoidal_projection, spheroidal_projection from geo_filters import check_in_square_area
import serial import pickle import time Port = "COM4" BaudRate = 115200 PointFile = open("Points.data", "rb") HexList = [] MCU = serial.Serial(Port, BaudRate, timeout=5) PointData = pickle.load(PointFile) PointFile.close() # Code for Frame in PointData: CurrentFrame = b"" for page in range(8): for c...