text
stringlengths
38
1.54M
from flask import Flask, render_template, redirect from school_distant.data import db_session from school_distant.data.users import User from school_distant.data.test import Tests from school_distant.data.tasks import Tasks from school_distant.data.form import RegisterForm, LoginForm, TestsForm, TasksForm from fl...
import MySQLdb import random import database_creds as dbc #SQL check_query = 'SELECT * FROM raw_data LIMIT 1;' raw_data_insert = 'INSERT INTO raw_data (user_id, event_id, amount) VALUES (%s ,%s, %s);' # Constants rows_interval = (90000,100000) user_id_interval = (1,100) event_id_interval = (1,100) amount_interva...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Last-Updated : <2014/01/03 23:24:05 by samui> import webapp2 import jinja2 import os JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)+"/../.."), #loader=jinja2.FileSystemLoader("/Users/samui/temp/python/GAE/google_...
import sys sys.stdin = open("2309.txt") nine = [int(input()) for _ in range(9)] flag = 0 A= [] def seven(n, k, s, small): global flag if 7 - k > 9 - n: if k == 7: return if flag == 1: return if s >100: return if k == 7: if s == 100: small....
def combine_known_transpos(dataset,combo_transpo,normal_transpo): out = [[[] for _sentence in line] for line in dataset] for i,line in enumerate(dataset): for j,sentence in enumerate(line): for word in sentence: word=mylower(word) print(word in combo_transpo, ...
import numpy as np arr = np.array([10, 15, 25, 5]) newarr = np.diff(arr) print(newarr) ############ arr = np.array([10, 15, 25, 5]) newarr = np.diff(arr, n=2) #so vong lap print(newarr)
import os from time import sleep import tkinter.messagebox import tkinter import sato if __name__ == '__main__': ct = sato.ComThread() usb = sato.USB() vid = 0x0828 pid = 0x0159 # print(f"检查串口{ct.check_com()}") # print(f"选择串口{ct.open_com()}") dev = usb.open_usb() print(dev) barcode...
from django.shortcuts import render, get_object_or_404 from .models import * from django.db.models import Max # Create your views here. def index(request): context = { 'post' : Blog.objects.order_by('-likes'), 'sobre': Sobre.objects.last(), 'faq': Faq.objects.order_by('-publidata')[:3], ...
class Solution: def translateNum(self, num: int) -> int: s = str(num) n = len(s) if n == 0: return 1 f = [0] * (n + 1) f[0] = 1 for i in range(1, n + 1): f[i] = 0 if s[i - 1] >= '0' and s[i - 1] <= '9': f[i] += f[i -...
cargahoraria=int(input("Digite a carga horária: ")) maximofaltas=int(cargahoraria*(25/100)) print("O máximo de faltas que você pode ter é: ",maximofaltas)
print("Insert M for male and F for female:") sex = input().upper() if sex not in ["M", "F"]: print("You can insert only M for male or F for female.") exit() print(sex) print("Insert your age in years:") age = int(input()) print(age) print("Insert your height in cm") height = int(input()) print(height) print(...
from flask import Flask, jsonify, render_template, request import spidev import time import os import threading import sched import json import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) relayPin = 26 GPIO.setup(relayPin,GPIO.OUT) GPIO.output(relayPin,0) light_history = [] moisture_history = [] nameLightDataFile = 'lig...
import sys from xopen import xopen as open def filter_vcf(inVcf, outVcf, minQUAL=20, minDP=10): for line in open(inVcf): if line.startswith('#'): outVcf.write(line) continue temp = line.rstrip().split('\t') if len(temp) <= 9: continue sample = temp[9] CHROM, POS, ID, REF, ALT, QUAL, FILTER, INFO, FO...
#!/usr/bin/env python # -*- coding: utf-8 -*- """--- Day 5: Doesn't He Have Intern-Elves For This? --- Santa needs help figuring out which strings in his text file are naughty or nice. A nice string is one with all of the following properties: It contains at least three vowels (aeiou only), like aei, xazegov, or aei...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation import random def persisted_rw(nk,x0,p): a = np.zeros(nk) x=x0 a[0]=x krok=random.choice([-1, 1]) for i in range(1,nk): if random.random()>p: krok=-krok x=x+krok a[i]=x return ...
from rest_framework import serializers from .models import * class FormDSerializer(serializers.ModelSerializer): class Meta: model = FormD fields = "__all__"
import json import requests import sys import pandas as pd class gitPulls (): def __init__(self, config): with open(config) as f: data = json.load(f) self.username = data["gituser"] self.token = data ["token"] self.url = data["url"] se...
""" 聊天室机制思路(重点思想) 功能 : 类似qq群功能 【1】 有人进入聊天室需要输入姓名,姓名不能重复 * 客户端input姓名,服务端验证是否存在姓名,服务端有记录 【2】 有人进入聊天室时,其他人会收到通知:xxx 进入了聊天室 【3】 一个人发消息,其他人会收到:xxx : xxxxxxxxxxx * 经过服务器转发客户端消息 【4】 有人退出聊天室,则其他人也会收到通知:xxx退出了聊天室 * 随时发送随时接受(sendto,recvfrom)发送接收互不干扰 【5】 扩展功能:服务器可以向所有用户发送公告:管理员消息: xxxxxxxxx # 服务器有多个客户端 # 服务器向所...
array = [1,1,2,5,5,5,7,7,9,9,9,9,9,11] def upper_bound(array, target): previous = -1 for i in range(len(array)): # if array[i] == target: # if array[i] > target: # print("i") # return f"hi {i}" previous = i if array[i] > target: ...
# -*- coding: utf-8 -*- """ Created on Sat Feb 20 20:01:26 2021 @author: Aaron """ import os import pandas as pd import numpy as np import seaborn as sns #from textblob import TextBlob import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix import datetime sns.set() os.getcwd() os.ch...
from enemy import Enemy from pygame.math import Vector2 from pygame import mixer import pygame import random class Cat(Enemy): def __init__(self, game, speed): super().__init__(game, speed) self.icon = pygame.image.load('kotek.png') self.health = 5 size = self.game.scre...
cities = { 101:"Pune", 102:"Mumbai", 105 : "Delhi", 103:"Chennai" } cities[104]="Bengaluru" cities[103]="Kolkatta" print(cities) # unordered print(cities[102]) #val=cities[109] # KeyError print(cities.get(103, "NIL")) print(cities.get(107, "NIL")) print(104 in cities) print(105 not in cities) for k in citi...
import pandas as pd from datetime import datetime, timedelta # Pandas settings pd.options.display.max_rows = 200 class Parser: def __init__( self, csv_path, date_col=0, name_col=5, event_col=3, component_col=2, context_col=1, index_dtype=str, ):...
import random from sii3 import * import unittest class testClasters(unittest.TestCase): '''tests for SII3''' def setUp(self): pass def tearDown(self): '''complite test1''' pass def test_d(self): """растояние между 2 точками""" a = (1,1) b = (1,2) c = (10,1) t1 = d(a,b) t2 = d(a,c) t3 = d(c,c) ...
from mpl_toolkits.mplot3d import Axes3D from scipy.integrate import odeint import matplotlib.pyplot as plt import numpy as np import sys args = sys.argv x = np.loadtxt('norm.dat') fig = plt.figure() plt.hist(x,bins=100) plt.savefig('norm-len{}mean{:.5f}var{:.5f}.png'.format(len(x),np.mean(x),np.var(x)))
from selenium import webdriver # 获取cookie def get_cookies(): chrome_options = webdriver.ChromeOptions() driver = webdriver.Chrome(options=chrome_options) # driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { # "source": """ # Object.defineProperty(navigator, 'webdriver', { ...
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from .models import User, UserProfile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_sav...
# valueIterationAgents.py # ----------------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to ht...
class BaseProvider: def get_catalog(self, **kwargs): raise NotImplementedError() def get_merchant(self, merchant_id): raise NotImplementedError() def login(self, username, password): raise NotImplementedError() def post_order(self, **kwargs): raise NotImplementedError...
from .test_case import TestCase from infi.unittest.parameters import iterate from os import path class ConsoleScriptsTestCase(TestCase): def test_add_and_remove_a_valid_entry_point(self): from infi.projector.plugins.builtins.console_scripts import ConsoleScriptsPlugin plugin = ConsoleScriptsPlugin(...
# K-Means Clustering in OpenCV import numpy as np import cv2 as cv img = cv.imread('dcbrtg.jpg') Z = img.reshape((-1, 3)) # convert to np.float32 Z = np.float32(Z) # define criteria, number of clusters(K) and apply kmeans() criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 10, 1.0) K = 4 ret, label, cen...
{ "targets": [ { "target_name": "boost-smart_ptr", "type": "static_library", "include_dirs": [ "1.57.0/smart_ptr-boost-1.57.0/include" ], "all_dependent_settings": { "include_dirs": [ "1.57.0/smar...
''' On a Certain day, the nurses at a hospital worked the following number of hours: Nurse Howard worked 8 hours Nurse Pease worked 10 hours Nurse Campbell worked 9 hours Nurse Grace worked 8 hours Nurse McCarthy worked 7 hours and Nurse Murphy worked 12 hours. What is the average number of hours worked per nurse on ...
import sys zeefile = open(sys.argv[1], 'r') for x in zeefile: a, b = x.strip().split(',') top = int(b) bottom = int(a) mystring = '' nums = [] for p in range(2, 1000): for i in range(2, p): if p % i == 0: break else: if p >= bottom and p <= top: nums.append...
# -*- coding: utf-8 -*- from openerp import models, fields, api class Users(models.Model): _inherit = ['res.users'] _rec_name = 'display_name' _order = 'login' display_name = fields.Char(string='Display Name', compute='_compute_display_name') @api.one @api.depends('login', 'partner_id.name'...
#!/usr/bin/env python #import execjs import execjs import os path=os.path.abspath('.')+'/Library/pyjsfuck' class JSFuck(): def __init__(self): f = open(path+'/jsfuck.js', 'r') jsf_code = f.read() js = execjs.get() #print "Using Engine %s" % js.name self.jsf_int = js.compile(...
import os from flask import Flask, jsonify from flask_restful import Api # from flask_jwt import JWT from flask_jwt_extended import JWTManager from db import db from ma import ma from blacklist import BLACKLIST from authentication import authenticate, identity from resources.user import ( UserRegister, User,...
import pandas as pd import numpy as np import json def get_data(filename): with open(filename) as data_file: # print(ps.read_json(content, orient='values')) data = json.load(data_file) dates = pd.to_datetime(data['dates'], format="%Y-%m-%d") dataset = np.array(data['dataset'], dtype...
import sqlite3 as sl import os,logging import pandas as pd from peewee import * TRANSFORMED_FILENAME='mushrooms_transformed.csv' DB_NAME='mushrooms_database.db' db=SqliteDatabase(DB_NAME) class BaseModel(Model): class Meta: database=db class AllCategories(BaseModel): name=CharField(primary_key=T...
__author__ = 'tung' class Users: def __init__(self, username='', password=''): self._username=username self._password=password @property def username(self): return self._username @username.setter def username(self, name): self._username=name @property def pa...
import os import string import sqlite3 def select_authorizer(*args): return sqlite3.SQLITE_OK class SensorLog: b_steps=[] class B_step: closed_segments=[] compat_segments=[] crossing_points=[] class Joined_Segment: id_closed=0 id_compat=0 average=0 segment=None ...
def my_decorator(func): def wrap_func(x,y): print('*******') func(x,y) print('*******') return wrap_func @my_decorator def hello(greeting,emoji): print(greeting,emoji) hello('hellooo',':)') def my_decorator(func): def wrap_func(*args,**kwargs): print('*******') ...
# 输入圆的半径算周长,面积 radius = float(input('圆的半径为: ')) C = 2 * 3.14 * radius S = 3.14 * (radius ** 2) print('圆的周长为 %.1f' % C) print('圆的面积为 %.1f' % S)
import os import json import pickle import numpy as np import pandas as pd from xgboost import XGBClassifier model = pickle.load(open("model/model.pickle", "rb")) columns = pickle.load(open("model/model_columns.pickle", "rb")) def recommendation(): pass def predict_ratings(data): data2 = {} for k, v in...
import logging from collections import Sequence import numpy as np from qtpy.QtCore import QObject, Signal from qtpy.QtWidgets import QMainWindow from model.preferences import LOGGING_LEVEL from ui.logs import Ui_logsForm class LogViewer(QMainWindow, Ui_logsForm): change_level = Signal(str) set_size = Signa...
# __author__ = 'ak' import requests import json import sys def run(msg,urls,atMobiles): data1 = { "msgtype":"text", "text":{ "content":"事业部今日Bug统计:"+'\n'+msg }, "at":{ "atMobiles":atMobiles, "isAtAll":False } } header = {'Content-Type':'application/json; charset=utf-8'} print(data1) te...
def cointoss(): counttails = 0 countheads = 0 for k in range(1,5001): import random probability = round(random.random()) coin="" if(probability == 0): coin="tail" counttails+=1 else: coin="head" countheads+=1 print "Attempt #"+str(k),": Throwing a coin.... it's a",coin,"! ... Got",counthea...
import random #--TO DO--- #Make a UI #Simplify some of these features maybe using classes #reads the list of responses from 'possibleresponses.txt' #returns them in a list called responses def getResponses(): filename="possibleresponses.txt" openfile=open(filename,'r') lines=openfile.readlines() respo...
#!/usr/bin/env python # -*- coding:utf-8 -*- # undone from urllib import parse import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver import time from spider.constant import * def get_filename(keyword): pos = '../data/question_list/' form = '.csv' return pos + keyword + form ...
""" A small and convenient cross process FIFO queue service based on TCP protocol. """ import logging import threading from collections import deque from queue import Full, Empty from time import monotonic from ._commu_proto import * from .exceptions import UnknownCmd, Empty, Full from .utils import ( Unify_encodi...
from dataclasses import dataclass class Hero: name: str identity: str company: str height: float weight: float gender: str eyes_color: str hair_color: str strength: int intelligence: str def __init__(self, name, identity, company, height, weight, gender, eyes_color, hair_c...
""" lesson 1 : create the scaler """ __all__ = [ 'scaler', # 'undulator', ] from ...session_logs import logger logger.info(__file__) from apstools.devices import use_EPICS_scaler_channels from ophyd.scaler import ScalerCH scaler = ScalerCH("sky:scaler1", name="scaler") scaler.wait_for_connection() sc...
#Use of command: #It is necessary to have 10 digit pswd as replace loop below is set to have 10 digits [i4:i4+10] #So be sure that old and new paswd should have 10 digits before using this script #python proxy_set.py 'old_pswd' 'new_pswd' import sys import time import os #Below are th files that contain proxy sett...
import requests from bs4 import BeautifulSoup HEADERS = {'User-Agent': 'Mozilla/5.0'} DOMAIN = "http://synergy-journal.ru/" url = "http://synergy-journal.ru/archive/10" def parse_articles(): articles = [x for x in bs.find_all("div", "r") if x["data-record-type"] == "374"] #[x.find("a")["href"] for x in bs.f...
import requests import hashlib import imgcodeidentify from PIL import Image from aip import AipOcr import re import optparse def get_class(username,password,year,term,flag,path): header = { "Host":"bkjw.sxu.edu.cn", "Origin":"http://bkjw.sxu.edu.cn", "Content-Type":"application/x-www-form-urlencod...
from django.db import models # Create your models here. class sosmed(models.Model): judul = models.CharField(max_length = 255) postby = models.CharField(max_length = 255) lokasi = models.CharField(max_length = 255) body = models.TextField() category = models.CharField(max_length = 255) media = ...
from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential import numpy as np """ Predict the next day closing price """ def predict_one_ahead(model, data): prediction = model.predict(data) prediction = prediction.reshape((prediction.siz...
import PySide.QtCore as qc import PySide.QtGui as qg from PySide.QtGui import QPen, QColor, QBrush, QLinearGradient try: import maya.utils as utils except: pass #-------------------------------------------------------------# class CustomSlider(qg.QSlider): _pen_dark = qg.QPen(qg.QColor(0 , 1, 3),...
''' 20180126 jlhung v1.0 ''' c = 0 while True: try : n = input() except EOFError: break a = [] for i in n: if i == "\"": if c == 0: a.append("``") c = 1 else: a.append("''") c = 0 else: a.append(i) print("".join(a))
s = {"name":"cherry","idno":101,"class":10,"marks":[90,89,42,35,77,82]} print(s.items()) print(s.keys()) print(s.values()) print("------find total marks-----------") print(len(s["marks"])) print(sum(s["marks"])) print("total=",sum(s["marks"])/(len(s["marks"]))) print("---------find pass or fail-------") for x ...
#! /usr/bin/env python # def spiral_gnuplot ( header, n, x, y, u, v, s ): #*****************************************************************************80 # ## SPIRAL_GNUPLOT writes the spiral vector field to files for GNUPLOT. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: ...
class Member: def __init__(self,percentage): self.percentage_share=percentage self.spent=0 self.common_spent=0 self.debit_pending=self.spent-self.common_spent class splitwise: def __init__(self,group): self.total_member=0 self.group=group ...
import pygame from constants import * from pygame.locals import * from inventaire import Inventory class Player(pygame.sprite.Sprite): """docstring for Player""" def __init__(self, name="Coloro",x=0,y=0, image="img/player/player.png"): super().__init__() self.name = name self.x = x self.y = y sel...
# country = 'Korea' country = 'korea' if country == 'Korea': print('한국입니다.') if country != 'Korea': print('한국이 아닙니다.') print('-'*15) if 'korea' > 'japan': print('한국이 더 크다.') if 'korea' < 'japan': print('일본이 더 크다') print('-'*15) #ascii code에서 대문자가 숫자가 작다. print('Korea' > 'KoreA') print('Korea' >...
from config import get_env import requests from bs4 import BeautifulSoup import urllib.request class Actions: def __init__(self, slackhelper): self.slackhelper = slackhelper def find_image(self, website, tag, image_details): """ Grabs the website content and parses it using beautif...
from django.contrib import admin from django.db import models from .models import FacebookSession from .forms import FacebookAccessInput @admin.register(FacebookSession) class FacebookAccessAdmin(admin.ModelAdmin): list_display = ('short_token', 'is_valid',) formfield_overrides = { models.CharField: ...
# 리스트 안에 for 문 사용하기 array = [i * i for i in range(0,20,2)] # 파이썬만이 한 줄로 작성이 가능하다. # 이 구문을 리스트 내포(list comprehensions)라고 부른다. print(array)
import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from onmt.modules.dropout import variational_dropout from .gaussian import Gaussian, ScaleMixtureGaussian from .utils import flatten_list, unflatten class PositionWiseFeedForward(nn.Module): """Multi-head...
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify, render_template engine = create_engine("sqlite:///belly_button_biodiversity.sqlite") Base = automap_base() Base.prepare(engine, reflect=Tr...
#!/usr/bin/env python #this program simply removes the same records in groundtruth filein=open('groundtruth.log','r') fileout=open('groundtruth.csv','w+') prev="" for line in filein: if line!=prev: fileout.write(line) prev=line filein.close() fileout.close()
import discord import random from discord.ext import commands from discord import FFmpegPCMAudio from dotenv import load_dotenv import os load_dotenv(dotenv_path="config") bot = commands.Bot(command_prefix="!") @bot.event async def on_ready(): print("Le bot est prêt.") @bot.command() async def Bonjour(ctx): ...
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"] favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas","nobody likes monkeys"] def zipit(list1,list2): newlist = zip(list1,list2) print newlist newerlist = dict(newlist) print newerlist zipit(name,favor...
#! /usr/bin/python # -*- coding: utf-8-*- from tts import * from datetime import date import RPi.GPIO as GPIO from time import sleep, time import random classes = [u"明天是周一,课程有:班队会,语文,语文,品德与生活,校本习惯,语文,体育活动", u"明天是周二,课程有:数学,外语,体育,语文,校本或语文,校本或语文", u"明天是周三,课程有:数学,语文,音乐,美术,外语,体育", u"明天是周四...
# -*- coding: utf-8 -*- from app.obj2png.src.ObjFile import ObjFile """ Created on Sat Jul 7 00:40:00 2018 @author: Peter M. Clausen, pclausen MIT License Copyright (c) 2018 pclausen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (...
import pdfplumber table_settings = { "vertical_strategy": "lines", "horizontal_strategy": "text", "intersection_x_tolerance": 15 } def get_pdf(): pdf = pdfplumber.open("data/강상홍_voca.pdf") table_data = [] for index, page in enumerate(pdf.pages): if index < 6: continue ...
import tensorflow as tf class FocusLoss(tf.keras.losses.Loss): def __init__(self, threshold=0.5, *args, **kwargs): super().__init__(*args, **kwargs) self.threshold = threshold def call(self, y_true, y_pred): """Compute focal loss for y and y_pred. Args: y_true: [batcn, height, ...
from django.shortcuts import render_to_response from django.template.context import RequestContext from django.db.models import Count from app.models import Hit def home(request): context = RequestContext(request) template_name = 'home.html' data = {} data['all_ips_by_date'] = Hit.objects.extra({'day':...
from django.contrib import admin from locations.models import Location @admin.register(Location) class LocationAdmin(admin.ModelAdmin): list_display = ('id', 'address_info',)
#### Imports #### import numpy as np import tensorflow as tf from sklearn.datasets import make_blobs #### SKLearn Blobs #### class clusterData: def __init__(self, n_features = 2, n_classes = 2, n_training_samples = 200, n_testing_samples = 200,...
# Generated by Django 3.1.2 on 2020-11-15 03:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('payroll', '0014_deduction_ded_bef_or_after'), ] operations = [ migrations.AlterModelOptions( name='employee', option...
import matplotlib.pyplot as plt x = [3, 4, 5, 6, 7, 8, 9, 10] EER_d = [0.328, 0.316, 0.297, 0.286, 0.293, 0.278, 0.287, 0.293] EER_m = [0.292, 0.266, 0.284, 0.292, 0.295, 0.278, 0.278, 0.281] EER_s = [0.318, 0.293, 0.316, 0.307, 0.309, 0.283, 0.290, 0.301] EER_t = [0.333, 0.3, 0.29, 0.29, 0.29, 0.298, 0.287, 0.284] p...
import pyb from pyb import I2C i2c = I2C(1) i2c2 = I2C(2) i2c.init(I2C.MASTER, baudrate=400000) print(i2c.scan()) i2c.deinit() # use accelerometer to test i2c bus accel_addr = 76 pyb.Accel() # this will init the bus for us print(i2c.scan()) print(i2c.is_ready(accel_addr)) print(i2c.mem_read(1,...
import zipline from zipline.api import order, record, symbol import logging import matplotlib.pyplot as plt from datetime import datetime tickers = ['AAPL', 'NVDA', 'GOOG', 'INTC'] start = datetime(2013, 1, 1) end = datetime(2017, 1, 1) LOGGER = logging.getLogger(__name__) def initialize(context): LOGGER.info('I...
from gym.envs.registration import register register( id='boeing-safe-v0', entry_point='gym_Boeing.envs:BoeingSafe', ) register( id='boeing-danger-v0', entry_point='gym_Boeing.envs:BoeingDanger' ) register( id='normalized-danger-v0', entry_point='gym_Boeing.envs:NormalizedDanger' ) register( ...
import random def keyFinder(): try: accountKey = input("What account are you looking for?") with open('allpsswrds.txt', 'r') as file: for line in file: if accountKey in line: print("Here is your key for: " + accountKey) print(line...
import math import torch from torch.autograd import grad # probability space computations def phi(X, W): return torch.exp(X @ W - X.pow(2).sum(-1, keepdim=True) / 2) def rff(X, Y, W): A, B = phi(X, W), phi(Y, W) values = A @ B.T return values / values.sum(-1, keepdim=True) # log space computations d...
# Hint: You may not need all of these. Remove the unused functions. class Ticket: def __init__(self, source, destination): self.source = source self.destination = destination def reconstruct_trip(tickets, length): """ YOUR CODE HERE """ route = [] mapping = {ticket.source: t...
from mininet.topo import Topo from mininet.node import Docker from mininet.link import TCLink # s1 # ______| |_______________ # s2 s3 # ___| |___ ___| ...
import SCons, os sources = [ 'EvoBlockSim.cc', 'api_adapter.c', 'evoBlock.c', ] env = Environment() env.Replace(CC = 'g++') env.Append(CCFLAGS = '-O3 -fopenmp -Wall -ggdb -Wno-deprecated') env.Append(CPPPATH = ['#']) defaultTargets = [] for i in os.listdir('solutions'): filebits = os.path.splitext(i) if filebits[...
# coding=utf-8 from framework.data_proc.jsonLib import get_value_from_json from framework.http.httpLib import HttpLib from framework.support.MyLogger import log_info from project.api_call.baseApi import BaseApi from project.configuration.statusCode import status_code_200 from project.configuration.configReader import p...
import sqlite3 import time import pandas as pd import sqlite3 equityBTC = 5 equityAlt = 0 candleCount = 0 candleOpenTime = 0 candleOpen = 0 candleCloseTime = 0 candleClose = 0 candleLow = 0 canceledTrades = 0 candleHigh = 0 candlePricesList = [] candleLowList = [] candleHighList = [] ATR = 0 action = "sell" openBuyPr...
from PIL import Image import sys def strip_extension(file_name): return file_name.split('.')[0] image_one_name = sys.argv[1] image_two_name = sys.argv[2] print("merging {} with {}".format(image_one_name, image_two_name)) with Image.open(image_one_name) as image_one, Image.open(image_two_name) as image_two: ...
import asyncio from typing import Any from ..errors import InvalidCallbackTypeError def assert_sync_callback( candidate: Any ) -> None: """Assert that the candidate is a valid synchronous callback.""" if not callable(candidate) or asyncio.iscoroutinefunction(candidate): raise InvalidCallbackType...
''' 987. Vertical Order Traversal of a Binary Tree https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ Given binary tree, return vertical order traversal. This means that from root node, the vertical line is x=0, left child is on line x=-1, right child is on line x=1, and so on. Example 1: Input:...
from flask import Flask, render_template, request, jsonify from flask_mysqldb import MySQL from config import DB_CONFIG import json import numpy as np app = Flask(__name__) app.config['MYSQL_HOST'] = DB_CONFIG['host'] app.config['MYSQL_USER'] = DB_CONFIG['user'] app.config['MYSQL_PASSWORD'] = DB_CONFIG['password'] app...
from django.urls import path from .import views app_name = 'accounts' urlpatterns = [ path('edithotel/<int:id>', views.edit_hotel, name='edithotel'), path('register', views.register, name='register'), path('signin', views.sign_in, name='signin'), path('signout', views.signout, name='signout'), pat...
from PyObjCTools.TestSupport import TestCase, min_os_level import WebKit class TestWKSnapshotConfiguration(TestCase): @min_os_level("10.15") def testMethods(self): self.assertResultIsBOOL(WebKit.WKSnapshotConfiguration.afterScreenUpdates) self.assertArgIsBOOL(WebKit.WKSnapshotConfiguration.set...
class Solution: def maximumGap(self, nums: List[int]) -> int: len_nums=len(nums) if len_nums<2: return 0 nums.sort() max_=0 i=0 j=i+1 while i<len_nums-1: max_ = max(max_,abs(nums[i]-nums[j])) i+=1 j+=1 ...
from .Profile import Profile class PipeProfile(Profile): """The PipeProfile object defines the properties of a circular pipe profile. The PipeProfile object is derived from the Profile object. Notes ----- This object can be accessed by: .. code-block:: python import section ...