text
stringlengths
8
6.05M
#!/usr/bin/env python3 #fonction Counter() pour compter les élements dans un tableau from collections import Counter def p_pair( b_array): #b_array doit être un bytearray bit = bytearray() #boucle pour parcourir le tableau for i in range(len(b_array)): #convertion en binaire octet = bin(b_array[i])[2:] ...
import os HOST = os.getenv('HOST') PORT = os.getenv('PORT') MONGODB = os.getenv('MONGODB') PANINI_DB = 'panini' SYNOPSIS_COLLECTION = 'synopsis' REPOSITORY = 'https://github.com/jallysson/PaniniApi'
#!/usr/bin/python3 import actuator actuator.Actuator("COOL", 1.5)
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Nombre: visorImagenes.py # Autor: Miguel Andres Garcia Niño # Creado: 15 de Noviembre 2018 # Modificado: 15 de Noviembre 2018 # Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018 # Licens...
import os import pandas as pd import numpy as np from pickle import loads from src.trainModel import trainModel from sklearn.impute import SimpleImputer class evalModel: def __init__(self): self.path = "../data/input/" self.root = "../data/predict/" # for traits self.name = list() ...
#!/usr/bin/python from cStringIO import StringIO from boto.s3.connection import S3Connection from boto.s3.connection import OrdinaryCallingFormat from boto.s3.key import Key as S3Key from utils.linda import * import os import zipfile import sys import json import base64 import time import threading import random de...
''' 数据来源:东方财富网-行情中心 http://quote.eastmoney.com/center ''' import requests import re import json #用get方法访问服务器并提取页面数据 def get_stocks(page): url = "http://42.push2.eastmoney.com/api/qt/clist/get?cb=jQuery11240574199433107409_1590886830210&pn={0}&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid...
import MySQLdb # Open database connection db = MySQLdb.connect("localhost","root","toor","CARRENTALDB" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Drop table if it already exist using execute() method. #cursor.execute("DROP TABLE IF EXISTS CUSTOMER") # Create table as per requirement s...
import time import random from MSExploit import MSExploit class MSExploit_Buffer_Overflow(MSExploit): def __init__(self, name): MSExploit.__init__(self, name) #Create def Create(self): print "Assessing overflow type...\n" time.sleep(0.75) print "Stack buffer overflow detected.\nApproach: NOP-Sled.\n" tim...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import statsmodels.api as am #read the data set into a pandas DataFrame wine = pd.read_csv('winequality-both.csv',sep=',',header=0) wine.columns = wine.columns.str.replace(' ','_') # display descriptive statistics for quality by wine type prin...
from ruamel.yaml import YAML import os import json def load_yaml(yaml_in:str)->dict: """ Read a YAML file and return the result as a dictionary. """ yaml = YAML(typ='safe') yaml.preserve_quotes = True with open(yaml_in) as file: return yaml.load(file) def write_yaml(filename:str, d...
#!/usr/bin/env python # coding: utf-8 # #******************************************************************************\ # * # * Copyright (C) 2006 - 2014, Jérôme Kieffer <imagizer@terre-adelie.org> # * Conception : Jérôme KIEFFER, Mickael Profeta & Isabelle Letard # * Licence GPL v2 # * # * This program is free softw...
""" Tests for the module firecrown.parameters. """ import pytest import numpy as np from firecrown.parameters import RequiredParameters, parameter_get_full_name, ParamsMap from firecrown.parameters import ( DerivedParameterScalar, DerivedParameterCollection, create, InternalParameter, SamplerParamet...
#------------------------------------- # Project: Lightweight Industrial Image Classifier based on Federated Few-Shot Learning # code is based on https://github.com/floodsung/LearningToCompare_FSL #------------------------------------- import torch import torch.nn as nn import torch.nn.functional as F from torch.autogr...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- t=int(input()) for i in range(t): n=int(input()) print("YES" if (n//2020>=n%2020) else "NO")
import numpy as np from sklearn.datasets import load_iris from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split, KFold, cross_val_score from sklearn.metrics import accuracy_score from sklearn.svm import LinearSVC, SVC from sklearn.neighbors import KNeighbor...
#!/usr/bin/env python3 from sensor_msgs.msg import Image from nav_msgs.msg import Odometry from rospy_wrapper import ros_wrapper class SLAMWrapper(): RGB_RAW='rgb' DEPTH_RAW='depth' INFRA1_RAW='infra1' INFRA2_RAW='infra2' ODOMETRY='odom' def __init__(self): self.topics={self.RGB_RAW: ...
class Persona(): def __init__(self,vCedula,vNombre,vEdad): self.cedula=vCedula self.nombre=vNombre self.edad=vEdad def __str__(self): return ("El objeto es {0},{1},{2}".format(self.cedula,self.nombre,self.edad)) class IngSistemas(Persona): def __init__(self,vCedula,vNombre,v...
__author__ = 'pschiffmann' import pandas as pd import numpy as np from random import randint class smartkitdata(object): def __init__(self): self._data = self.gen_data() def get_data(self, length=60): return pd.DataFrame(self._data)[-length:] def get_data_smooth(self, length=60, smooth=...
# collecting relation surfaces from OpenIE # http://openie.allenai.org/search?arg1=book&rel=&arg2=entertainment&corpora= import requests import re from multiprocessing.dummy import Pool import time surface_dict = None def get_relation(subj, obj): global surface_dict url = "http://openie.allenai.org/search?arg1...
#!/usr/bin/python import random, sys, string import argparse class shuf: def __init__(self, filename): if filename=="-" or filename=="": self.lines = "" else: f = open(filename, 'r') self.lines = f.readlines() f.close() def shuffling(self): ...
'''Question 6 Level 2 Question: Write a program that calculates and prints the value according to the given formula: Q = Square root of [(2 * C * D)/H] Following are the fixed values of C and H: C is 50. H is 30. D is the variable whose values should be input to your program in a comma-separated sequence. Exa...
from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=128,unique=True) password = models.CharField(max_length=258) def __str__(self): return self.name+','+self.password class Score(models.Model): name = models.CharField(max_length=...
from networkx import write_gpickle, DiGraph from pandas import read_csv #logging import logging logging.basicConfig(filename='../log/graph_optimize_log.log', \ format='%(asctime)s\t%(levelname)s,\t%(funcName)s\t%(message)s', \ level=logging.DEBUG) ''' class Graph: de...
def checkio(number): result = "" x = 0 while len(str(number)) > 1: temp = x for n in range(9,1,-1): print("nnnn:",n) if number % n == 0: result += str(n) number = int(number / n) x += 1 break prin...
#!/usr/bin/env python # coding: utf-8 # In[3]: from PIL import Image import numpy as np import glob import tensorflow as tf from tensorflow import keras from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten from keras.utils import to_categorical import matplotlib.pyplot a...
import os import sys import traceback import math import cProfile import torch import torch.nn as nn from torch.utils.data.dataloader import DataLoader import torch.nn.functional as F from torch.autograd import Variable import IPython import numpy as np from tensorboardX import SummaryWriter import dat...
import argparse def start(): parser = argparse.ArgumentParser() parser.add_argument("logfile", type=str) args = parser.parse_args() return Logger(args.logfile) class Logger: def __init__(self, logfile): self.logfile = logfile file_to_create = open(self.logfile, "a") file_...
from restaurant import Restaurant restaurant_one = Restaurant("McDonalds", "Fast Food") restaurant_two = Restaurant("Burger King", "Burgers") restaurant_three = Restaurant("Healthy Cuisine Restaurant", "Salad") restaurant_one.describe_restaurant() restaurant_two.describe_restaurant() restaurant_three.describe_restaur...
from django.urls import path from . import views from django.views.decorators.csrf import csrf_exempt urlpatterns= [ path('', views.index, name= 'expenses'), path('add_expenses/', views.add_expense, name="add_expenses"), path('update_expense/<int:id>', views.update_expense, name ='update_expense'), pat...
import pandas as pd import matplotlib.pyplot as plt import numpy as np file = pd.read_csv("pima_indians_diabetes_original.csv") #QUES1 print("\n******QUESTION-1*******") file1 = pd.read_csv("pima_indians_diabetes_miss.csv") Df = file1.isnull().sum() y = Df.values[0:9] x = ["pregs","plas","pres","skin","test","BMI",...
import torch w = torch.tensor(1.0, requires_grad=True) # requires_grad=True 하면 w.grad 에 gradient 가 자동저장된다. # 단, 사용하려면 element 가 float 이어야 한다. a = w*3 l = a**2 l.backward() # backward 하는 객체는 scalar 이어야 한다. print(w.grad) print('l을 w로 미분한 값은 {}...
from cardmodel import Card from solitairemodel import SolitaireModel class SolitaireView: def __init__(self, model): self.model = model def draw(self): # get data from model stock = self.model.getStock() # limit waste to last 3 cards waste = self.model.getWaste() waste = waste[(-1*(min(3, ...
import random def hangman(): lists = [ " O ", " | ", " ======= ", "/ | \ ", " / \ ", " | | " ] print("========================") print("Welcome to Hangman Game.") print("========================") #...
# -*- coding: utf-8 -*- """evaluate.py This is a simple ad-hoc bulk evaluator of the pre trained corpora matching the path: pretrained/{language_code}/{1,..,4}-gram.pickle Once ran, this file will start printing the Json-encoded resulting counters after concluded experiments to the STDOUT. It will also notify reachin...
#-*- coding:utf-8 -*- # setup.py from distutils.core import setup import py2exe setup(console=['hello.py'])
# 通过 if 和 else 来完成不同分支流程执行不同的任务 people = 20 cars = 30 buses = 15 if cars > people: print "We should take the cars." elif cars < prople: print "We should not take the cars." else: print "We can't decide." if buses > cars: print "That's too many buses." elif buses < cars: print "Maybe we could take...
track = [ '#ToqueDeQueda', '#RenunciaPiñeraCuliao', '#ChileEnResistencia', '#ToqueDeQuedaTotal', '#EstadoEmergencia', '#EstadoDeExcepcion', '#ChileDesperto', '#ChileResiste', '#Valparaiso', '#Coquimbo', '#FuerzaChile', '#ChileSeCanso', '#ChileProtests', '#ChileEnM...
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
import logging import logging.handlers import datetime class cls_logger: __inst = None name = 'cls_logger' handler=None @staticmethod def init_logger(log_level): ''' :param log_level: CRITICAL = 50 FATAL = CRITICAL ...
def solve(): s = input().lower() count = [s.count(c) for c in "aeiou"] print(sum(count)) if __name__ == "__main__": solve()
from flask import Flask, render_template, send_file, send_from_directory, request import json from flask_tus import tus_manager from flask_cors import CORS import bcrypt from flask_sqlalchemy import SQLAlchemy import os import redis from file_storage import FileStorage from s3_storage import S3Storage from elasticsearc...
import yaml from utils.apiLib import * from utils.utilGetJson import * import json global app_data app_data = yaml.load(open("../settings/config.yml")) app_data2 = yaml.load(open("../data/data.yml")) def before_all (context): print("************************ BEFORE ALL *********************************************...
""" WIP """ import sys import os import fbx from brenpy.qt.bpQtImportUtils import QtWidgets from brenpy.qt import bpCollapsibleWidgets from brenfbx.core import bfCore from brenpy.qt import bpQtWidgets from brenfbx.qt.scene import bfQtSceneModels from brenfbx.items import bfSceneItems from brenfbx.qt.object import...
# Generated by Django 3.2.3 on 2021-07-08 12:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userapp', '0005_auto_20210708_1259'), ] operations = [ migrations.CreateModel( name='orders1', fields=[ ...
for i in range(3): num = input() sum = 0 if(int(num)<0): a1=int(num[0:2]) sum+=a1 for j in range(2,len(num)): sum+=int(num[j]) else: for j in range(len(num)): sum+=int(num[j]) print(sum)
from tkinter import * from tkinter import ttk import random #メイン窓枠設定等 root = Tk() root.title("0518.py GUI") #文字書込み部 write_frame = ttk.Frame(root) write_frame.grid() write_label = ttk.Label( write_frame, text = "何かお話してください", ) write_label.grid(row = 0, column = 0) write = StringVar() write_entry = ttk.Entry...
from conversion.conversion_utils import fixed_attribute from .base import BaseEnaConverter PROJECT_SPEC = { '@center_name': ['center_name'], 'NAME': ['study_name'], 'TITLE': ['short_description'], 'DESCRIPTION': ['abstract'], 'SUBMISSION_PROJECT': { 'SEQUENCING_PROJECT': ['', fixed_attribu...
from turtle import Turtle UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 MOVE_DISTANCE = 20 class Snake: # initializes the snakes body with 3 squares def __init__(self): self.width = 0 self.snake_segment = [] self.create_snake() self.head = self.snake_segment[0] # The create fu...
import cv2 from threading import Thread import socket import struct import time import sys import argparse import os import zlib import base64 as b64 from datetime import datetime, timedelta try: import cPickle as pickle except ImportError: import pickle class VideoCamera(object): def __init__(self, width...
import configparser def get_config(title: str, key: str): """ 获取配置文件的值,title是[]里的内容,key是某一项的键 :param title: 配置文件中[]中的值 :param key: 配置文件的key :return: """ config = configparser.ConfigParser() config.read("static/config.ini") print(config.sections()) return config.get(title, key) ...
# Generated by Django 3.0.1 on 2019-12-24 00:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('FinaceNote', '0001_initial'), ] operations = [ migrations.AlterField( model_name='upload', name='user_city', ...
import time import openpyxl import os from utilities import ExcelUtil import datetime from win32com import client from utilities.readProperties import ReadConfig excel = client.Dispatch(dispatch="Excel.Application") wb = excel.Workbooks.Add() today = datetime.date.today() d1 = today.strftime("%d-%m-%Y") t = time.lo...
#-------------------------------------------------------------------------------- # G e n e r a l I n f o r m a t i o n #-------------------------------------------------------------------------------- # Name: Exercise 5.1 # # Usage: python "Exercise 5.1.py" # # Description: Calculate and plot distance traveled using g...
class Vector: def __init__(self,*coeffs): self.coeffs=coeffs def __repr__(self): return 'Vector(*{!r})'.format(self.coeffs) def __add__(self,other): return Vector(*(x+y for x,y in zip(self.coeffs,other.coeffs))) #Vector object is returned def __len__(self): return len(s...
from collections import OrderedDict from all import setting import requests import simplejson as json import xlrd # region Data into db def write_service_facility(): auth_data = {"code": "666666", "mobile": "09207869164"} auth = requests.post(f"{setting.base_api_uri}/authenticates", json=auth_data) get_i...
# Generated by Django 2.2 on 2019-08-09 07:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inventory', '0003_auto_20190809_0548'), ] operations = [ migrations.AddField( model_name='category', name='category_co...
'''Code to query, create and edit Entry data ''' from logging import getLogger from openspending.lib.aggregator import update_distincts from openspending.ui.lib.browser import Browser from openspending.model import Dataset, Entry, mongo log = getLogger(__name__) def facets_for_fields(facet_fields, dataset_name=None...
import os import wget from workflow.task import Task from workflow.utils.ansible import Ansible from workflow.utils import env as ENV ''' 从制品库拉,然后push到部署服务的机器 ''' class Push(Task): def __init__(self, *args, **kwargs): self.src = kwargs.get('src') self.dst = kwargs.get('dst') self.servers = ...
#!/usr/bin/env python # this runs as separate ROS node and publishes messages from joystick - generally working fin import rospy from sensor_msgs.msg import Joy joybuttons = [] joyaxes = [] def listen_joystick(): rospy.Subscriber('xwiimote_node/joy', Joy, callback) def callback(data): global joybuttons, jo...
# ---------------------------------------------------------------------------- # Copyright 2014 Nervana Systems 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.o...
import pandas as pd from mvmm.multi_view.block_diag.graph.bipt_community import get_block_mat from mvmm.clustering_measures import MEASURE_MIN_GOOD from mvmm_sim.simulation.run_sim import get_n_blocks def get_bd_mvmm_model_sel(mvmm_results, select_metric='bic', user_best_idx=None): """...
# -*- coding: utf-8 -*- # Generated by Django 1.9.10 on 2016-11-10 22:03 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('reportng', '0021_auto_20161110_2159'), ] operation...
# Generated by Django 2.2 on 2019-06-12 07:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_nginx_access', '0004_auto_20190612_0733'), ] operations = [ migrations.AddIndex( model_name='urlsagg', index=mo...
import sys from math import log10 def calculate_prob(string, gc): ''' Calculate the probability that a random string matches string exactly :param string: string to compare :param gc: GC content to construct random strings :return: log(probability) that a random string constructed with the GC content m...
# Definition for singly-linked list. class ListNode: def __init__(self, x,nextNode=None): self.val = x self.next = nextNode class Solution: def swapPairs(self, head): last = pre = ListNode(0) last.next = pre.next = head while last.next!=None and last.next.next!=None: ...
from django.urls import path from authors.apps.reports.views import ReportArticleViewSet urlpatterns = [ path( "<str:slug>/report-article/", ReportArticleViewSet.as_view({'post':'create'}), name="report" ), path( "report-article/<int:report_id>/", ReportArticleViewSet.as_v...
import errno import io import json import logging import os import subprocess from builtins import ValueError from json import JSONDecodeError from typing import List, Tuple, Callable from definitions import CLI_SIMULATOR_FILE_PATH, CDE_API_USER_PASSWORD_ENV_VAR logging.basicConfig(format="%(asctime)s %(levelname)s %...
#!/usr/bin/env python import os import sys import inspect import re import argparse import random parser = argparse.ArgumentParser(description=""" Description ----------- This script merges close alignement generated by promer. """,formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Authors ---...
import numpy from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from keras.callbacks import ModelCheckpoint import json import word_table as w_t from keras.utils import np_utils from erro...
import pandas as pd import glob def parse_path(p): parsed = [pair.split('_') for pair in p.split('.csv')[0].split('__')] return pd.Series({k:v for k,v in parsed}) def get_stage_results(stage): stage_results = pd.concat([ pd.read_csv(f).assign(path=f.split(f'STAGE{stage}__')[1]) \ for f in ...
import pytest from ioweb.request import BaseRequest def test_default_meta(): req = BaseRequest() assert req.meta == {} # pylint: disable=use-implicit-booleaness-not-comparison def test_custom_default_config(): class CustomRequest(BaseRequest): def get_default_config(self): return {...
# -*- coding:utf-8 -*- import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import Lasso,Ridge from sklearn.model_selection import GridSearchCV if __name__ == "__main__": data = pd.read_csv('...
from django.contrib import admin from django.urls import path, include from drf_yasg import openapi from drf_yasg.views import get_schema_view """JWT auth""" schema_view = get_schema_view( openapi.Info( title="Booking API", default_version="v1", ), public=True, ) urlpatterns = [ path("...
import torch import torch.nn as nn import torch.nn.functional as F from lib.pointnet2 import pointnet2_utils as pointutils class FlowEmbedding(nn.Module): def __init__(self, radius, nsample, in_channel, mlp, pooling='max', corr_func='concat', knn=True, use_instance_norm=False): super(FlowEmbedding, self)....
import cStringIO from Scapy_Control import * from scapy.all import * from SMB_COM import * class ReadAndx(): def ReadAndxRequest(self, Flow = 'SMB', **kwargs): raw = self.SMBHeader(command=SMB_COM_READ_ANDX, flags=24, ...
#!/usr/bin/env python import sys import rospy import moveit_commander import geometry_msgs.msg import math import tf.transformations def main(): moveit_commander.roscpp_initialize(sys.argv) rospy.init_node('move_group_mover', anonymous=True) group = moveit_commander.MoveGroupCommander("al5d_joints") ...
import psycopg2 from openpyxl.workbook import Workbook import pandas as pd import logging # importing packages class Total_compensation: # function to list total compensation given at Department level till date def compensation(self): try: # trying to connect to postgresql database ...
# -*- coding: UTF-8 -*- import MySQLdb from scipy import stats __author__ = 'Eric huizh' # ============================= rule 1 ================================= """ function: 对销售记录表的数据单价跟销售数量进行乘积,求出最初数据表中的每个商家或者特定商家每条销售记录的销售额 @para: tag = 1:全部商家 tag = 1:特定商家 """ def sql_fee(table, **kw): ...
# Generated by Django 2.2.4 on 2020-05-13 17:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('property', '0013_auto_20200513_1958'), ] operations = [ migrations.AlterField( model_name='owner', name='flats', ...
#!/bin/python3 rcvd = input().strip() orig = "SOS" * (len(rcvd) // 3) count = 0 for i in range(len(rcvd)): count += 1 if orig[i] != rcvd[i] else 0 print(count)
""" _WMWorkloadTools_ Define some generic tools used by the StdSpecs and WMWorkload to validate arguments that modify a WMWorkload and/or WMTask. Created on Jun 13, 2013 @author: dballest """ import json import logging from Utils.Utilities import makeList, strToBool from WMCore.DataStructs.LumiList import LumiList ...
def mentor_successful_interaction(soft_skills): return soft_skills*2 + 10 def idea_generation_time(percent, team_soft_skills): return (percent*10 + 300)*4*2/team_soft_skills def final_score(soft_skills, idea, programming, design): return (idea*1.5 + programming + design)*(soft_skills + 5) / 30
''' Created on Apr 24, 2016 BST Sequences: A binary search tree was created by traversing through an array from left to right and inserting each element. Given a binary search tree with distinct elements, print all possible arrays that could have led to this tree. @author: chunq ''' def getBSTSequences(t...
from django.conf import settings if settings.DEBUG: # Development environment app_id = '88726' app_key = '1751ee3d48c493fa8347' app_secret = 'e332918120e6efe62095' else: # Production enviroment (Heroku app) app_id = '88725' app_key = '3dc3533a2828e91bd034' app_secret = '4fd4201ee58cb...
from pydantic import BaseModel from datetime import datetime from typing import List, Optional # =================================== # Organization Models start here # =================================== class OrganizationBase(BaseModel): name: str class OrganizationCreate(OrganizationBase): pass class O...
from cleo import Application from myapp.commands.hello_world_command import HelloWorldCommand app = Application() app.add(HelloWorldCommand()) if __name__ == '__main__': app.run()
""" Author: JiaHui (Jeffrey) Lu ID: 25944800 """ import numpy as np import matplotlib.pyplot as plt import time def my_log1p(x): """ The function takes in x value then uses taylor expansion formula to generate the value for log1p :param x: the input to the function log(1+x) :return: ans: the result of...
from copy import deepcopy from readability import Document from .abstract_extractor import AbstractExtractor from ..article_candidate import ArticleCandidate class ReadabilityExtractor(AbstractExtractor): """This class implements Readability as an article extractor. Readability is a subclass of Extractors a...
import sys sys.path.append('../STANDAR_LIBRARIES') from URL_Lib import descargarResultadoData, descargarResultado, descargarResultadoDataSinBeautiful from File_Lib import saveFile, saveFileExc, loadFile import re import requests from bs4 import BeautifulSoup # pip install beautifulsoup4 import http.client http.clie...
from tensorflow.keras.applications import InceptionV3 from tensorflow.keras import layers from tensorflow import keras def build_model_with_flatten(img_h, img_w): """ Build a model with a flatten layer @type img_h: int @param img_h: Height of the images (nb of pixels) @type img_w: int @param i...
from django.db import models # Create your models here. class Customer(models.Model): device = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return f'name: {self.device}'
import game import random from node import Node import time import math import util class MCTS(object): """Base routine of MCTS method. Attributes: PLAYOUT_NUM: paremter to define maximum iteration times of MCTS """ # flg to specify computational budget of MCTS search TIME = 0 ...
def tr(srcstr, dststr, string, lowup=0): if lowup == 1: srcstr = srcstr.lower() dststr = dststr.lower() string = string.lower() return string.replace(srcstr, dststr) else: return string.replace(srcstr, dststr) print(tr('Abc', 'Mno', 'abcDef', lowup=1))
from datetime import timedelta, datetime from email.mime.text import MIMEText from smtplib import SMTP_SSL as SMTP from sys import exc_info from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from emailr.models import Event from emailr.settings.config import DB_USERNAME, DB_PA...
import torch.utils.data as data from PIL import Image import os import os.path import numpy as np class CocoDetection(data.Dataset): """`MS Coco Detection <http://mscoco.org/dataset/#detections-challenge2016>`_ Dataset. Args: root (string): Root directory where images are downloaded to. annFi...
#TLE from functools import reduce class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: out = 0 for _ in range(1, len(nums)+1): start = 0 end = _ while end <= len(nums): if end == 1: f...
#!/usr/bin/env python import os,sys,gzip,re,json,pickle from datetime import datetime """Example of the log lines we are looking for: 3bfcc1ecaa7b79a1f8ab596ecb0b59b89d08560e 2012-11-18 00:00:56.578 21767 21767 I PhoneLabSystemAnalysis-Location: {"Action":"edu.buffalo.cse.phonelab.LOCATION_UPDATE","Location":"Lo...
#!/usr/bin/env python3 import math def solve_quadratic(a, b, c): return (-b + math.sqrt(b*b - 4*a*c))/(2*a), (-b - math.sqrt(b*b - 4*a*c))/(2*a) def main(): solve_quadratic(1,2,3) if __name__ == "__main__": main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Dict Methods ============================================================================== """ import time from pyclopedia.deco import run_if_is_main keys = ["n%s" for i in range(1000000)] @run_if_is_main(__name__) def fromkeys(): """dict.fromkeys is a very fa...