text
stringlengths
8
6.05M
import argparse import httplib2 import os import sys import json import io import os.path from os import listdir from os.path import isfile,join # simulate the 'Cloud' in local storage ROOT_DIR = '/home/ubuntu/tmp/' def upload_file(service,from_file_name,to_file_name): # try delete it first try: d...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Optional, Tuple from gym.utils import seeding from numpy.random import RandomState def np_random(seed: Optional[int]) -> Tuple[RandomState, int]: """Set the seed for numpy's random generator. Args: seed (Option...
K = 3 M = 5 A = [2, 1, 5, 1, 2, 2, 2] def solution(K, M, A): worst_rating_bound = sum(A) best_rating_bound = max(A) if K == 1: return worst_rating_bound if K >= len(A): return best_rating_bound rating = 0 while worst_rating_bound >= best_rating_bound: mid_rating = in...
import numpy as np import os import neural_network as nn import model as m import distribution as d import settings as s def prt_distribution(distribution, model=None): # Print the distribution and if available the corresponding model """ # If you want to see the 'Fritz' distribution which a specif...
from django.db import models class Titanic(models.Model): PassengerId = models.CharField(max_length=50) Survived = models.IntegerField(null=True, blank=True) Pclass = models.IntegerField(default=0) Age = models.IntegerField() Name = models.CharField(max_length=50) Sex = models.CharField(max_len...
###################################### # author ben lawson <balawson@bu.edu> # Edited by: Craig Einstein <einstein@bu.edu> ###################################### # Some code adapted from # CodeHandBook at http://codehandbook.org/python-web-application-development-using-flask-and-mysql/ # and MaxCountryMan at https://gi...
from aiogram import types easy = types.InlineKeyboardMarkup( inline_keyboard=[ [ types.InlineKeyboardButton(text="Town Portal Scroll", callback_data="Town Portal Scroll")], [types.InlineKeyboardButton(text="Ironwood Branch", callback_data="Ironwood Branch")], [types.Inli...
import sys import matplotlib matplotlib.use("Qt5Agg") from PySide2 import QtWidgets, QtGui from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import cv2 as cv # Personnal modules from drag import DraggablePoint class MyGraph(FigureCanvas): """A...
# -*- coding: utf-8 -*- """ Created on Tue Jun 25 20:32:36 2019 @author: HP """ res=[] res.append(1) n=100 def update_arr(x): carry=0 for i in range(len(res)-1,-1,-1): num=res[i]*x num=num+carry res[i]=num%10 carry=int(num/10) while carry>0: res.insert(0,carry%10) ...
# Generated by Django 3.2.3 on 2021-06-12 03:34 from django.db import migrations, models import django.db.models.deletion import pizza_app.models class Migration(migrations.Migration): dependencies = [ ('pizza_app', '0005_auto_20210610_0547'), ] operations = [ migrations.RenameField( ...
from django.test import TestCase class FetcherTestCase(TestCase): def test_DataSourceModelExists(self): """ Test if DataSource model exists """ try: from fetcher.models import DataSource except ImportError: self.fail('Cannot import DataSource')
#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- from Parser_ import HTMLParser from Loader import Loader import sys import json if __name__ == '__main__': for i in range(3092, 5900): if i != 3800: p = HTMLParser(i) p.searchCols() del p print("s") load = Loader() ...
def bread(func): def wrapper(): print("</----\>") func() print("<\____/>") return wrapper @bread def sandwich(food="--ветчина--"): return food print(sandwich())
Direcciones=input().split() contador=1 conteo=[] compacto=[] for i in range(len(Direcciones)): if i<(len(Direcciones)-1): if Direcciones[i]==Direcciones[i+1]: contador+=1 else: compacto.append(Direcciones[i]) conteo.append(contador) contador=1 else: if Direcciones[i]==Direcciones[i-1]: contado...
# # @lc app=leetcode.cn id=222 lang=python3 # # [222] 完全二叉树的节点个数 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def countNodes(self, ro...
#Q5. Define an employee class and initialize it with name and salary. # Now, make a classmethod that takes in a string parameter "name-2000" which creates an instance and returns the instance based on parameter. class Employee: def __init__(self,name,salary): self.name = name self.salary= salary ...
import os,sys import string from optparse import OptionParser import glob import json import subprocess __version__="1.0" __status__ = "Dev" def create_docker_file(prj): line_list = [ "FROM nginx:1.21.0-alpine as production" ,"ENV NODE_ENV production" ,"RUN mkdir -p /data/shared/%s" % (p...
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys import numpy as np from time import time sys.path.append("../tools/") from email_preproc...
test_case = int(input()) while test_case: n = int(input()) a = list(map(int, input().split())) odd = [] even = [] for i in range(n): if i % 2 != a[i] % 2: odd.append(i) if a[i] % 2 else even.append(i) print(-1 if (len(odd) != len(even)) else len(odd)) ...
import sys def main(): from c9hubapi.rest import api api.app.run(debug=True, host='0.0.0.0', port=3232) if __name__ == '__main__': main()
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
#!/usr/bin/env python # coding=utf-8 import os import re import sys import time import subprocess import phone from dingding import DingDing CAMMAND_GIT_CONFIG_ACCESS_TOKEN = "git config --global pushconfig.accesstoken" #连接gitlab的 token ding = None def main(): print "main" def setup(): global ding if ding...
import pyeapi from pprint import pprint import yaml from my_funcs import read_yaml,print_out yaml_device = read_yaml("device.yaml") connection = pyeapi.client.connect(**yaml_device) device = pyeapi.client.Node(connection) output = device.enable("show ip arp") print_out(output)
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-01-22 22:23 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('update...
#!/usr/bin/enc pyton3 #This script is for going in every directory and concatenating all text files in that directory import os import subprocess print("-----------------------------------------------------------Hello user------------------------------------------------------\n") #pwd=os.getcwd() #print(pwd) filenames=...
import sys sys.path.insert(0, '../../packages/WPG') # sys.path.insert(0,'/diskmnt/a/lsamoylv/WPG') # sys.path.insert(0,'/data/S2E/packages/WPG') # sys.path.insert(0,'/Users/lsamoylv/code/WPG') import os import pylab as plt import numpy as np from wpg import Wavefront def show_diagnostics(FELsource_out_number): ...
# hello worldを1文字変更した場合のエラーメッセージを調べる # 1文字削除、xを追加、1を追加 # python errormsg.py > output # grep Hello.java output | sed 's/^.*: //' | sort | uniq import sys import subprocess hello_src="""public class Hello { public static void main(String[] args) { System.out.println("hello, world"); } } """ def remove_...
import time def factorial(n):#recibimos un numero factorial respuesta = 1 #respuesta que comienza en uno while n > 1: respuesta *= n #multiplicamos respuest por n n -= 1 #va a ir decreciendo return respuesta#regresamos respuesta def factorial_r(n):#factorial recursivo if n==1: #si...
import requests import pandas as pd from bs4 import BeautifulSoup # creating empty list to store contents products = [] prices = [] ratings = [] content = requests.get("https://www.amazon.in/s/ref=mega_elec_s23_2_1_1_1?rh=i%3Acomputers%2Cn%3A1375424031&ie=UTF8&bbn=976392031",headers={'User-agent': 'Mozilla/5.0 (X11;...
from __future__ import division from __future__ import print_function from datahandling import insert_update_db, my_query from numpy import isnan, argmax, argmin, mean from pandas import ewma from tinydb import TinyDB, Query from equipment import Rheomix from logging import debug def rheomix_sva(db): Q = Query() ...
# This should be a simple word counter which give us the most common word in a file # If ran from the command line without arguments it should print out the usage: # python most_common_word.py [source] # When no argument is provided print out # No source provided # When the argument provided and the source is a file # ...
# -*- coding: utf-8 -*- """ Created on Tue Mar 13 15:09:54 2018 @author: HP """ def reverse(s): final_string = s[::-1] return final_string print(reverse('siva')) print(reverse('william')) print(reverse('tat'))#this is a palindrome def palindrome(s): s = s.replace(' ','').lower() if s[::-1]==s: ...
import pygame from . import constants as CO pygame.init() pygame.display.set_mode(CO.SRC_SIZE,pygame.FULLSCREEN) # 设置窗体大小 全屏 pygame.FULLSCREEN pygame.display.set_caption("InterstellarStronghold-星际要塞") # 设置标题
import os import re import sys filename = sys.argv[1] tmpPath = sys.argv[2] if os.path.isfile(filename): lines_tmp = [] confOpen = open(filename) confAlllines = confOpen.readlines() for lines in confAlllines: lines_tmp.append(lines) confOpen.close() if len(lines_tmp) > 0: fo...
#!/usr/bin/python import optparse import urllib import time # Parse command-line options parser = optparse.OptionParser() parser.add_option('-a', '--airport', dest='airport', default='SLC', metavar='AAA', help='retrieve data for airport AAA (default %default)') parser.add_option('-c', '--carrier', dest='carrier', def...
import sys import lyricsgenius as genius import pandas as pd import os import json dataset = "Eminem_dataset.txt" writer = "Eminem" json_str = "Lyrics_Eminem.json" if __name__ == "__main__": geniusCreds = "sTzgVYcb_lBs-WPI5q35Gf9lvZ0My3bFyzZ35-KYUp2SAHnjxjZll7rqr09HNOHV" api = genius.Genius(geniusCreds) a...
import boto3 stack = cloudformation.create_stack( StackName='string', TemplateBody='string', TemplateURL='string', Parameters=[ { 'ParameterKey': 'string', 'ParameterValue': 'string', 'UsePreviousValue': True|False }, ], DisableRollback=True|...
#!/usr/bin/python from __future__ import print_function import os import sys import requests from sys import stderr from urlparse import urlparse from threading import Thread from time import sleep import socket from select import poll, POLLIN, POLLPRI, POLLOUT, POLLHUP, POLLERR from libproxy import ProxyFactory from Q...
from django.contrib import admin from . import models # Register your models here. admin.site.register(models.Posts) admin.site.register(models.Comments)
# Copyright (c) Members of the EGEE Collaboration. 2006-2009. # See http://www.eu-egee.org/partners/ for details on the copyright holders. # # 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 # # ...
import flask from flask import Flask, url_for, render_template, redirect, request from flask import session as login_session import requests import os import sys from flask import send_from_directory from datetime import datetime, timedelta from storeutils import pool_server, pay_order, make_order, add_product_to_order...
# Generated from parity_game.g4 by ANTLR 4.8 from antlr4 import * if __name__ is not None and "." in __name__: from .parity_gameParser import parity_gameParser else: from parity_gameParser import parity_gameParser # This class defines a complete listener for a parse tree produced by parity_gameParser. class pa...
import numpy as np import pandas as pd def cleanse_data(df): """ Cleans the MTA Dataset and create some elementary features Args: df: A DataFrame with correctly formatted MTA Data Returns: A DataFrame with cleansed MTA Data """ # Strip leading and trailing spaces for Headers and...
#!/usr/bin/env python3 import scapy.all as scapy import argparse as argp def get_arguments(): parser = argp.ArgumentParser(description='Send an ARP broadcast and prints the result') parser.add_argument('--target', '-t', dest="target", type=str, help='IP address of the host which you send the packet') ...
#1059-pares-e-impares # entrada N = int(input()) impar = [] par = [] for i in range(N): numero = int(input()) if (False == (numero % 2 == 0)): impar.append(numero) elif (True): par.append(numero) impar.sort(reverse=True) par.sort(reverse=False) for i in range(len(par)): print(par[i]) f...
# -*- coding: utf-8 -*- class Solution: def minTimeToVisitAllPoints(self, points): result = 0 for i in range(len(points) - 1): result += self.distance(points[i], points[i + 1]) return result def distance(self, p1, p2): dx = abs(p1[0] - p2[0]) dy = abs(p1[1]...
class Solution(object): def rob(self, nums): prev = curr = 0 for x in nums: prev, curr = curr, max(prev + x, curr) return curr print(Solution().rob([5,5,5,0,0,0,5,5,0,5,5,5,0]))#25
def main(): b=(int(input("Enter your weight in lbs:" ))) h=(int(input("Enter your height in inches:" ))) y=(b*720)/h/h if 25 >= y >= 19 : print ("You are within the healthy range") elif y > 25 : print ("you are above the healthy range") else : print ("you are below the he...
from setuptools import setup setup( name = "represent-boundaries", version = "0.2", url='http://github.com/rhymeswithcycle/represent-boundaries', description="A Web API to geographical districts loaded from shapefiles. Packaged as a Django app.", license = "MIT", packages = [ 'boundarie...
""" File: prob1.py Author: Abraham Aruguete Purpose: i think this is a review of classes or something""" class Simplest: """ This is a simple class for simple folk.""" def __init__(self, a, b, c): self.a = a self.b = b self.c = c class Rotate: """This is a class which has...
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def add_two_numbers(self, l1, l2): carry = 0 head = ListNode(0) l = head while l1 or l2: if not l1: l1 = ListNode(0) if not l2: ...
# -*- coding: utf-8 -*- from pynginx.schedule.base import Schedule as BaseSchedule import time import traceback class Schedule(BaseSchedule): @property def index(self): if self.lock.acquire(): if 0 == self.length: self.lock.release() return -1 se...
''' You will be given the number of angles of a shape with equal sides and angles, and you need to return the number of its sides, and the measure of the interior angles. Should the number be equal or less than 2, return: "this will be a line segment or a dot" Otherwise return the result in the following format: "...
from .garmin_calculation import create_garmin_quick_look from .fitbit_calculation import create_fitbit_quick_look from .apple_calculation import create_apple_quick_look def which_device(user): if hasattr(user,"garmin_token"): return "garmin" elif hasattr(user,"fitbit_refresh_token"): return "fitbit" else: has...
list=[] while True: A=int(input()) if A != 0: list.append(A) elif A == 0: if len(list) == 0: print("0") break else: print(sum(list)) del list[:] break else: break
""" script to scrap IPEDS website for .csv files """ import argparse import zipfile import shutil import glob import re import requests from bs4 import BeautifulSoup from selenium import webdriver # from selenium.webdriver.common.keys import Keys def scrape(): """ get html page that lists its links to .zip files ...
from __future__ import division import time import numpy as np import pandas as pd import csv import itertools from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.metrics.classification import accuracy_score,precision_score from sklearn.model_selection import KFold, GridSearchCV,c...
#!/usr/bin/python import os, sys import json zdir = {} filestat=[] dirstat=[] for path, dirs, files in os.walk("/home/w1pko", followlinks=None): try: # Store files in the directory for file in files: #print os.path.join(path, file) ...
from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SECRET_KEY'] = "change this to be a more random key" app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://info3180-project1:fortis4eva@localhost/info3180-project1" app.config['SQLALCH...
from pandac.PandaModules import * #basic Panda modules from direct.showbase.DirectObject import DirectObject #event handling from Level import * class MapGen(object): maxLevel = 5 def __init__(self, player): self.curLev = 4 self.initMap(player) self.initLight() def initMap(self,...
from mod_base import* class TakeOP(Command): """Take OPs from a nick.""" def run(self, win, user, data, caller=None): args = Args(data) if data != None: users = [] for arg in args: user = self.bot.FindUser(arg) if user == False: ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('humanstxt', '0003_otherpeople'), ] operations = [ migrations.AddField( model_name='otherpeople', nam...
#!/usr/bin/env python3 from functools import reduce def solve1(in_): prev = in_ while True: new = apply(prev) if new == prev: break prev = new print("1: ", sum(1 for x in reduce(lambda a,b: a+b, prev) if x == '#')) def apply(in_): """ If a seat is empty (L) and...
# -*- coding: utf-8 -*- """ Created on Thu Jan 01 16:01:55 2015 @author: lenovo """ #score = 89 #if score >= 90: # print 'A' #else: # if score >=80: # print 'B' # else: # if score >=70: # print 'C' # else: # if score >=60: # print 'D' # els...
#-*- coding: utf-8 -*- ''' Created on Jan 8, 2011 @author: Peter ''' from numpy import * from BeautifulSoup import BeautifulSoup # 从页面读取数据,生成retX和retY列表 def scrapePage(retX, retY, inFile, yr, numPce, origPrc): # 打开并读取HTML文件 fr = open(inFile); soup = BeautifulSoup(fr.read()) i=1 ...
dias = {} def adicionarDia(posicao): if(posicao >= 1 and posicao <= 7): dia = str(input("Digite o dia da semana para ser adicionado: ")) dias[posicao] = dia print(dias) else: print("A semana tem apenas 7 dias!") return dias def exibirDias(dias): for d ...
from django.conf.urls import patterns, include, url from django.contrib import admin from app import views urlpatterns = patterns('', # Examples: url(r'^$', views.home, name='home'), url(r'^post/', views.PostView.as_view(), name='post'), url(r'^comment/', views.CommentView.as_view(), name='postComment')...
import os import pdb import random from text_data import loadPrepareData from text_data import indexesFromSentence from text_data import batch2TrainData import torch.nn as nn import torch DATA_DIR = "/home/changmin/research/steganography/data/" TEXT = "dialogues_text.txt" ALL_PATH = os.path.join(DATA_DIR, "dialogues_t...
'''Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.''' #without using function '''name=str(input("enter your name :")) agee=int(input("enter your current age:")) hundredth_yr=2021+(100-agee) print(n...
import json import pymongo import itertools from progress.bar import Bar import gzip from jsonlinewriter import TransactionWriter from anonymize import anonymize import argparse import os def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return itertools.zip_longest(*args, fi...
#!/usr/bin/python3 # -*- coding: utf-8 -*- #様々なグローバル変数群 canonb = []*CANBSIZ #削除か終了のためのバッファ coremap = []*CMAPSIZ #コア割り当てのための空き swapmap = []*SMAPSIZ #スワップ割り当てのための空き rootdir = None #rootディレクトリのinodeのポインタ cputype = None #CPUの種類 40,45,または 70 execnt = None #exec内のプロセス数 lbolt = None #time of day in 60th not in time time...
#encoding: utf-8 #Patron 1, la n especifica la altura del romboide. Debe ser mayor o igual a 5 import sys if len(sys.argv) != 2 : print 'Args: número' sys.exit(2) n = int(sys.argv[1]) if n < 5 : print 'El primer argumento debe ser mayor o igual a 5' sys.exit(1) i = 0 j = 0 c = n espacios = 0 #espacios despues del...
"""initial database migration Revision ID: 51796ab1b4e0 Revises: Create Date: 2019-12-17 13:46:53.096680 """ from alembic import op import sqlalchemy as sa import datetime import uuid import os import sys from flask_bcrypt import Bcrypt from importlib import import_module # revision identifiers, used by Alembic. re...
import numpy as np import matplotlib.pyplot as plt # f = open(r"filter_h.dat", "rb") # バイナリファイル読み込み。 # tmp = f.read() # ファイルの中身をread()メソッドで一気に読み込み。 # for idx in range(len(tmp)): # ファイルのバイト数をlen()で取り出して、その回数for文で回す、 # print(tmp[idx]) # 1バイトづつデータを出力 # print(type(tmp[10])) # with open('oto.raw', mode='rb') a...
from nfd_router_client import RouterClient from subprocess import check_output import subprocess import time import socket import json class RouterEM(object): def __init__(self, logger, vnfm_host, vnfm_port, sv_mode, probe_id): self.mode = 'no_SV' self.probe_id = probe_id self.logger = log...
GREET = 'Hello, {}!'.format def greeting_for_all_friends(friends): return [GREET(a) for a in friends] if friends else None
PW = 25 PT = 6 def split_layers(l, n): for i in range(0, len(l), n): yield l[i:i + n] f = open("input", "r") image = f.read().strip('\n') digits = PW * PT layers = list(split_layers(image, digits)) fewest = layers[0] min0 = fewest.count('0') for i in range(1, len(layers)): min_next = layers[i...
import re filename = input("enter the name of the file: ") if(len(filename)==0): filename= "regex_sum_691845.txt" handle=open(filename) summ=0 for line in handle: #print(line) line=line.rstrip() y= re.findall('[0-9]+',line) if(len(y)==0) : continue #print(y) for x in y: w = int(x) s...
import os import socket import logging from channel.connector import Connector class Client(Connector): """UNIX-socket client used to communicate with the daemon.""" def __init__(self): Connector.__init__(self) def start(self): """ Connects to the UNIX-socket if it exists. ...
import cv2 import os import numpy as np import scipy as scp import scipy.misc from enum import Enum class ClassesDef(Enum): PAVED_NONPAVED = 1 PAVED_NONPAVED_ROCK = 2 #classes = ClassesDef.PAVED_NONPAVED_ROCK def good_res_image(img): gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) imgbw = cv2.threshold(g...
"""Madlibs Stories.""" class Story: """Madlibs story. To make a story, pass a list of prompts, and the text of the template. >>> s = Story(["noun", "verb"], ... "I love to {verb} a good {noun}.") To generate text from a story, pass in a dictionary-like thing of {prompt: ans...
# -*- coding: UTF-8 -*- from System import * from collections import deque from System.Math import * from processing.segmentation.connected import * def detect_contours(segments, mask): height = segments.GetLength(0) width = segments.GetLength(1) rmask = Array.CreateInstance(bool, height, width) for i in range(...
from abc import ABCMeta, abstractmethod from UVMPMException import InvalidRequestSyntax from Client import Client class Request: __metaclass__ = ABCMeta def __init__(self, client: Client, raw_request: str): self.client = client self.raw_request = raw_request @staticmethod @abstractme...
from .BaseEditor import BaseEditor from PyQt5 import QtWidgets, QtCore class ChoicesEditor(BaseEditor): def __init__(self, parent, item, model): BaseEditor.__init__(self, parent, item, model) self.combo = QtWidgets.QComboBox(self) #self.combo.currentIndexChanged.connect(self.__selectedIt...
from spack import * import distutils.dir_util as du import sys,os sys.path.append(os.path.join(os.path.dirname(__file__), '../../common')) from scrampackage import write_scram_toolfile class Csctrackfinderemulation(Package): homepage = "http://www.example.com" url = "http://www.example.com/example-1.2....
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals import json import os from gchtheme import GchRstReader _g = globals() here = os.path.dirname(__file__) with open(os.path.join(here, 'settings.json')) as f: settings = json.load(f) for k, v in settings.iteritems(): _g[k.up...
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pathlib import Path from textwrap import dedent import pytest from pants.backend.shell.goals import test from pants.backend.shell.goals.test impo...
import datetime #Stdlib Imports from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.db import models from django.templatetags.static import static #from templated_email import send_templated_mail from .functions import unique_slugify provinces = ['Distrito Nacional', 'Altagracia', 'A...
from dataclasses import dataclass from functools import reduce from typing import Optional, Iterable, Union Rule = list[str] @dataclass class Node: value: Union[str, list[list['Node']]] def get_text_with_matching_nodes_removed(self, text: str) -> Optional[list[str]]: if text == "": # we...
class CacheUnit: def __init__(self): self.nodeList = [] self.succAccum = {} def getHost(self): """return val [ip: string, port: int]""" host = self.nodeList.pop(0) self.nodeList.append(host) return host def report(self, ip, port): """ip: string, port:...
# -*- coding:utf-8 -*- # 最长单调递增子序列 # O(n^2) def lis_len(seq_a, seq_b, dp, flag): """将序列X按非递减顺序排列,形成新序列Y,问题就转变成求解X和Y的LCS""" len_a = len(seq_a) len_b = len(seq_b) for i in range(1, len_a + 1): for j in range(1, len_b + 1): if seq_a[i - 1] == seq_b[j - 1]: dp[i][j] = d...
# -*- coding: utf-8 -*- import os import time import re import html from urllib.parse import urlencode from urllib.request import Request,urlopen from slackclient import SlackClient from slacker import Slacker from apiclient import discovery from googleapiclient.http import * from oauth2client import client, tools fr...
import itertools import json import os from collections import Counter, defaultdict from glob import glob from itertools import combinations import Levenshtein import editdistance import numpy as np from tensorflow.keras import Input from tensorflow.keras import Model from tensorflow.keras.layers import Dense, Dropout...
def dogs_age(age): if age <= 2: return age * 10.5 elif age > 2: return (2 * 10.5) + ((age - 2) * 4) print(dogs_age(5))
# import plotly.offline as py import sys import codecs import matplotlib.pyplot as plt from sklearn.manifold import TSNE import pickle as pk import numpy as np from pandas import read_csv from sklearn.cluster import KMeans file_to_save_vector = 'results/multivariate/cpu/5minutes/bnn_multivariate_uber_ver2/vector_repres...
''' Created on Dec 24, 2010 @author: jason ''' import string import bson import logging import tornado.web import datetime import simplejson import MongoEncoder.MongoEncoder import pymongo class BaseHandler(tornado.web.RequestHandler): @property def db(self): #========================================...
#!/usr/bin/env python import argparse from math import sqrt import pandas as pd import numpy as np from numpy.linalg import svd from util import read_vector_file, openfile from matrix import norm2_matrix def main(): parser = argparse.ArgumentParser( description='Computes an LSA model correlatin...
import sys sys.path.insert(0,'../sib/') import sib import csv import os import numpy as np import pandas as pd import sklearn.metrics as mm import sys import argparse # sir_inference imports from sir_model import FastProximityModel, patient_zeros_states from ranking import csr_to_list import os.path from os import path...
# -*- coding:utf-8 -*- # Utils module: useful functions to build exploits from ropgenerator.semantic.Engine import search, LMAX from ropgenerator.Constraints import Constraint, RegsNotModified, Assertion, Chainable, StackPointerIncrement from ropgenerator.semantic.ROPChains import ROPChain from ropgenerator.Database i...
# -*- coding: utf-8 -*- """ Created on Sat Apr 13 22:33:58 2019 @author: CKK1 """ import numpy as np import h5py import cv2 import matplotlib.pyplot as plt from skimage import morphology from matplotlib import cm def scale_array(dat, out_range=(-1, 1)): domain = [np.amin(dat), np.amax(dat)] def interp(x): ...