text
stringlengths
38
1.54M
#!/usr/bin/env python # -*- coding: utf-8 -*- # # lisa.py # # Copyright 2015 Arkadiy <arkadiy@arkadiy-SVE1511T1RW> # # This program 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; either version 2 of the ...
#Author: Emil #Description: Body Mass Index Calculator using Imperial system print("Hello, welcome to your Body Mass Index(BMI) Calculator!\n") while True: try: height = float(input("Please enter your height here in inches: ")) break except ValueError: #making sure user entered number correctly print("Enter a...
import cassandra from cassandra.cluster import Cluster try: cluster = Cluster(['127.0.0.1']) #If you have a locally installed Apache Cassandra instance session = cluster.connect() except Exception as e: print(e) try: session.execute(""" CREATE KEYSPACE IF NOT EXISTS php_compute WITH REPLIC...
from pymongo import MongoClient import requests import time client = MongoClient('mongodb://localhost/', 27017) DATABASE = client.mvp lst = ['contracts','marketing', 'warranties', 'business_planning', 'conferences', 'computers', 'office_technology','electronics', 'regulations', 'correspondence', 'computers', 'sh...
from django.contrib import admin from models import Artist, Art admin.site.register(Artist) class ArtAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} admin.site.register(Art)
import math q = 0.9 def left(M, N): term1 = (M - N + 0.5) * math.log(M / (M - N)) term2 = 1 / (12 * M + 1) - 1 / (12 * (M - N)) return term1 + term2 def right(N): return N + math.log(q) for i in range(65): N = 2 ** i j = i + 1 M = 2 ** j while left(M, N) <= right(N): print(le...
from global_var import db class Customer(db.Model): __tablename__ = 'Customer' username = db.Column(db.String(32), primary_key=True) name = db.Column(db.String(32), nullable=False) password = db.Column(db.String(128), nullable=False) phone_number = db.Column(db.String(20), nullable=False) age...
### YOUR CODE HERE # import tensorflow as tf import torch import os, argparse import numpy as np #from Model_SWA import MyModel from Model import MyModel from DataLoader import load_data, train_valid_split, load_testing_images from Configure import model_configs, training_configs import utils parser = argparse.Argumen...
INTERFACE_MACS = { 'eth0': 0x00e0ed0bdc2a, 'eth1': 0x00e0ed0bdc2b, 'eth2': 0x00e0ed0bdc2c, 'eth3': 0x00e0ed0bdc2d, 'eth6': 0x00e0ed11c7f7, 'eth7': 0x00e0ed11c7f6, 'eth8': 0x00e0ed11c7f5, 'eth9': 0x00e0ed11c7f4 } RX_INTERFACE = 'eth7' TX_INTERFACES = ['eth0', 'eth1', 'eth2', 'eth3', 'eth...
from matplotlib import pyplot figure = pyplot.figure() figure.clf() pyplot.plot([1,2,3], [1,2,3]) pyplot.show()
import logging import os import urllib.request, urllib.parse, urllib.error import copy from urllib.parse import urlparse from django.conf import settings LOGGER = logging.getLogger(__name__) def get_jupyter_url(system, path, username, is_dir=False): """Translate file path and system to Jupyter URL Requires...
# Création de la classe animal class Animal: def __init__(self, poids, taille) : self.animal_taille = taille self.animal_poids = poids def se_deplacer(*args): pass # Création des sous classes Serpent et Oiseau class Serpent(Animal) : def se_deplacer(*args): print("Je rampe"...
import subprocess import os, sys import getopt BASE_DIR = os.path.dirname(os.path.dirname(__file__)) def common_clear(submodule_directory, version): dr = submodule_directory os.chdir(dr) os.system("git checkout " + version) os.chdir("..") os.system('git add '+submodule_directory) #os.system('git commit -m "move...
import os import sys import getopt from time import sleep import io import requests import html from urllib import parse headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} inputfile = "links2.txt" outdir = "../data_mons...
# 树的子结构 # 输入两棵二叉树A,B,判断B是不是A的子结构。 class node: def __init__(self, s): self.s = s self.left = None self.right = None def search(self, target): if self.s == target.s: if (target.right is None) & (target.left is None): return 1 elif target.le...
from pygame import key, K_LEFT, K_RIGHT from pygame.sprite import Group from base import GameSprite from constants import BULLET_IMG_PATH class Player(GameSprite): def __init__(self, window, img_path, sprite_x, sprite_y, size_x, size_y, player_speed): super().__init__(window, img_path, sprite_x, sprite_y...
__author__ = 'Cheng' from django.conf.urls import patterns, url import views urlpatterns = patterns('', # /pledges/ url(r'^$', views.index, name='index'), url(r'^reward/list/$', views.list_rewards, name='list_rewards'), url(r...
from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string def send_welcome_email(name,receiver): #creating message subject and sender subject = "Thanks for signing up to spy on your neighbours" sender = 'egesacollins92@gmail.com' #passing in the context va...
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 11:16:56 2020 @author: voide """ import pandas as pd import numpy as np from matplotlib import pyplot as plt import scipy.fftpack df = pd.read_csv (r'acc_tri.csv', header=None) acc_tri = df[0] del df y = acc_tri[2400000:2800000] y = np.asarray(y) Fs = 40000 T = 1 / ...
import nltk import random import pickle from nltk.tokenize import word_tokenize short_pos = open("short_reviews/positive.txt","r").read() short_neg = open("short_reviews/negative.txt","r").read() all_words = [] documents = [] allowed_word_types = ["J"] for p in short_pos.split('\n'): documents.a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: anchen # @Date: 2017-07-03 23:24:13 # @Last Modified by: anchen # @Last Modified time: 2017-08-12 12:52:22 from flask import current_app, render_template from flask_mail import Message from . import mail, celery, create_app # 启动消息服务,在manager.py所在目录下启动 # cel...
###################################################### # this functions only purpose is to ask for and # recieve user input ##################################################### def user_input(): words = input("please enter a word or sentence :") return words #######################################...
""" Plugin that allows you to manage a python virtual env ## Requirements - `pipenv` - `pipenv-setup` if you want to run the `sync_setup` operation """ import argparse import os import confu.schema import ctl import ctl.config from ctl.auth import expose from ctl.docs import pymdgen_confu_types from ctl.exceptio...
from ete3 import Tree x = Tree("((((G:9)E:5)C:7)B:7,(F:6)D:5)A;", format=1) print(x.get_ascii(show_internal = True))
# -*- coding: utf-8 -*- """ Created on Wed Feb 22 00:12:36 2017 @author: Eyal """ from CampaignClass import Campaign from UcsManagerClass import ucsManager import itertools import math def eprint(*args, **kwargs): # print(*args, file=sys.stderr, **kwargs) with open("../myLogs/sim{0}/PinePyEngine_Sim{0}.log".f...
import os import socket import threading import SocketServer SERVER_HOST = '127.0.0.1' SERVER_PORT = 0 #random port BUF_SIZE = 1024 ECHO_MSG = 'Hello Server!' class ThreadedServerRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(BUF_SIZE) currentThread...
#import odd_cluster, frequent_values, duplicate_months #import diurnal_cycle, distributional_gap, records, streaks #import spike, climatological, humidity, clouds, variance #import clean_up, winds
''' Created on Jan 9, 2015 @author: niuzhaojie ''' from Task import Task class ComputeTask(Task): ''' classdocs ''' def __init__(self, taskID, priority, resource, execTime): ''' Constructor ''' super(ComputeTask, self).__init__(taskID, priority, resource) self...
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: """ 1) O(n2) 2) O(nlong) 3) O(n) -- bit mani O(1) 4) Hashmap -- freq count O(n) """ d = {} for i in range(len(nums)): if nums[i] not in d: ...
class dotAreaPolygons_t(object): # no doc def ToStruct(self,PartIds): """ ToStruct(self: dotAreaPolygons_t,PartIds: ArrayList) """ pass aIdList=None ClientID=None nAreas=None nIdList=None
import pandas as pd import statsmodels.formula.api as sm import statsmodels.api as sma from pathlib import Path file = open('forward_output2.txt','w') def forward_selected(data, response, remaining, prev=[]): """ based upon algorithm found at: https://planspace.org/20150423-forward_selection_with_statsmod...
#!/usr/bin/python import yaml from os import path import rospy import actionlib import rosparam # Actionlib messages import lasr_pnp_bridge.msg as lpb_msg from std_msgs.msg import String, Header from sensor_msgs.msg import Image, PointCloud2 from actionlib_msgs.msg import GoalStatus from geometry_msgs.msg import Poi...
from typing import Dict, List from fastapi import Depends,File, UploadFile, APIRouter, HTTPException from sqlalchemy.orm import Session from app.authentication import models #from courses_live.database import SessionCourse, some_engine from app.talent.database import SessionLocal, engine,database import shutil import d...
import math def min(area,base): return math.ceil((2*area)/base) m,n=input().split() area = int(m) base = int(n) height = min(area,base) print("Minimum height is %d" % (height))
from keras.layers import Dense, Input, GlobalMaxPooling1D from keras.layers import Conv1D, MaxPooling1D from keras.models import Model def CNN(embedding_layer): #构建、连接其他层 label_num = {"spam":1, "ham":0} MAX_SEQUENCE_LENGTH = 50 sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32') # 占位。 ...
''' Created on 20/04/2013 @author: cristian ''' import os import unittest from app import db from app.modelo import User2 #basedir = os.path.abspath(os.path.dirname(__file__)) class UsuarioTestCase(unittest.TestCase): def setUp(self): self.db_fd, microblog.app.config['DATABASE'] = tempfile.mkstemp() ...
import json, requests, os CA_FILE = 'data-hold/california.json' if not os.path.exists(CA_FILE): print("Can't find" + CA_FILE + "so fetching remote copy...") resp = requests.get("http://stash.compjour.org/data/usajobs/california-all.json") f = open(CA_FILE, 'w') f.write(resp.text) f.close() rawdata...
level = [ "WWWWWWWWWWXXWWWWWWWWWW", "W W", "W WWWWWWWWWWWWWWWWWW W", "W W W W", "W W WWWWWW WWWWWW W W", "W W W W W W", "W W WWWW W W WWWW W W", "W W W W W W W W", "W WWWW W W WWWW W", "W W WWWW W W", "W WWWWWW WWWWWW W", "W W WXXW W W"...
from cnn import AnimalClassifier if __name__ == '__main__': classifier = AnimalClassifier() classifier.makeModel() # classifier.train('data/training', 'data/validation/') prediction = classifier.classify('data/validation/airplane/airplane01.tif') print('Image is classified as: ', prediction)
#----------------------------------------------# # Autonomous Vehicle Machine Vision System # # Machine Vision System # # machineVision.py # # Written by: # # Jeremy Beauchamp, Zhaojie Chen, # # Trenton Davis, and Xudon...
from flask import Flask, jsonify, request from flask_sqlalchemy import SQLAlchemy from flask_restful import Resource, Api import utils API_VERSION = 'v1' STARTING_BOARD = [[None, None, None], [None, None, None], [None, None, None]] VALID_COMMANDS = ['start', 'board', 'move', 'help', 'pony'] app = Flask(__name__) api...
#将接收到的FTP字节流直接发送给UE侧 #!/usr/lib/python3.4 #-*-coding:utf-8-*- import socket import os, struct def ftp_sendfile(addr,localpath = '/home/nano/openair-cn'): ftp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ftp_sock.connect(addr) print('连接上了!') while True: #file_path = input('Please E...
from django import template from django.template.defaultfilters import stringfilter from django.shortcuts import HttpResponse from django.contrib import messages register = template.Library() @register.filter(name='splitdamage') @stringfilter def splitdamage(string): spal=string.split(",") sspal=spal[-1].split...
import pandas as pd df_1=pd.read_csv("E:/Ramya/brushUps/Basics/CASE_STUDIES/GOOD_READS/Data/WorstBooks.csv") df_2=pd.read_csv("E:/Ramya/brushUps/Basics/CASE_STUDIES/GOOD_READS/Data/tempWorstBooks.csv") df_2.columns=list(df_1.columns) empty_df_2=df_2.groupby(['title']).get_group('0') for index,row in empty_df...
################################ DESCRIPTION ################################## # Description: List ALL Services deployed in OSB Domain with Regular Expression # Match. # # Author: Jesus A. Ruiz - linuxwayven@gmail.com # Place: Caracas - Venezuela - Oracle de Venezuela # Date: 16/06/15 # # History # 16/0...
from tkinter import * class Item: def __init__(self): self.__itemDictionary = {} self.__roomOneDialogue = None self.__roomTwoDialogue = None self.__roomThreeDialogue = None self.__numTries = 0 self.__roomOneAnswer = "dog" self.__itemOne = "Random" self.__itemTwo = "Pict...
# Copyright 2022 Ecosoft Co., Ltd (https://ecosoft.co.th) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html) from openerp import models, fields, api class SaleOrder(models.Model): _inherit = "sale.order" delivery_bill_count = fields.Integer( string="Delivery Bill Count", co...
import os import logging logging.basicConfig(level=logging.DEBUG, format='%(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') def clone(service, dir, remote='https://github.com/'): os.system('cd src/' + dir + ' && git clone ' + remote + service + '.git') def run(arg): logging.i...
# # IMPORTS # from snack import * from model.config import GA_VERSION # # CONSTANTS # # # CODE # class FirstScreen: """ Verify the hard disk selected is part od a LVM Volume Group """ def __init__(self, screen): """ Constructor @type screen: SnackScreen @param scree...
# -*- coding: utf-8 -*- from PIL import Image, ImageDraw, ImageFont from pibooth import fonts from pibooth.pictures import resize_keep_aspect_ratio def concatenate_pictures(pictures, footer_texts, bg_color, text_color): """ Merge up to 4 PIL images and retrun concatenated image as a new PIL image object. ...
from table_to_entity import * class Template(Object): def get_template(self, *args, **kwargs) -> str: pass class TsCypressTemplate(Template): _TEMPLATE = ''' namespace Cypress { type %s = { %s } }''' def get_template(self, *args, **kwargs) -> str: """ :param arg...
a=int(input('enter value of a:')) b=int(input('enter value of b:')) try: c=a+b d=a-b e=a/0 print(c,d,e) except Exception as e: print(e)
from utils.parse_input import fetch_input from typing import List def part1(parsed_inputs: List[int]) -> int: """ Problem: Find numbers the pairing in a list of numbers which add up to 2020, then return their product """ s = set(parsed_inputs) for n in parsed_inputs: rem = 2020 - n ...
# Generated by Django 3.0.8 on 2020-07-17 09:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('GoForHolidayApp', '0002_remove_placeinfo_experience'), ] operations = [ migrations.AddField( model_name='placeinfo', ...
from telebot import types class LotsManager: def __init__(self, bot): self.bot = bot self.connection = bot.connection def get_lots(self, user, only_created=False): cur = self.connection.cursor() show_all = user.get_property('show_all') if show_all: if not o...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.db.models.deletion from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('contentt...
#!/usr/bin/python from pylab import * import cv2 from scipy.optimize import leastsq def apply_transformation_on_points(points, H): ''' Apply the given transformation matrix on all points from input. @coords: list of input points, each is represented by (row,col) @return: list of points after transformation, eac...
from sqlalchemy import Column, Integer, String from config import Base class Book(Base): __tablename__ ="book" id = Column(Integer, primary_key=True, index=True) title = Column(String) description = Column(String)
import datetime from unittest.mock import ANY, patch from flask import Flask from src.api.v1.users import UserTrackListenCountsMonthly app = Flask(__name__) # Bypasses the @marshal_with decorator app.config["RESTX_MASK_HEADER"] = "*" START_TIME = "2020-01-01" END_TIME = "2021-01-01" @patch( "src.api.v1.users....
""" create by 2020-10-28 author hf """ import yaml, os from common.log import Logger logger = Logger(name="envconfig") class GetConfig: @classmethod def get_project_config(cls, project="idea", data="idea", env="test"): """根据请求的参环境返回不同环境数据""" path = os.path.abspath(os.path.di...
#!/bin/python3 # https://www.hackerrank.com/challenges/append-and-delete/ import sys s = input().strip() t = input().strip() k = int(input().strip()) if (len(s)-len(t)) % 2 != 0 and k %2 == 0: # special case print('No') sys.exit() a,b = (s[:], t[:]) if len(s)>=len(t) else (t[:],s[:]) i=0 while i < len(b): ...
from django.conf.urls import include, url from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('fanatics/',views.fanatics, name='fanatics'), path('fanaticsDetail/<int:id>',views.fanaticsDetail,name='fanaticsDetail'), path('fanaticsDates/',views.fanati...
#https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ def twoSum(numbers,target): l, r = 0, len(numbers)-1 while l < r: res = numbers[l] + numbers[r] if res == target: return [l+1,r+1] elif res < target: l += 1 else: r -= 1 def tw...
### ***************************************************************************************** ### Usage: ### ### cmsRun B2GEdmtExtraToTTreeNtuple_cfg.py maxEvts=N sample="file:sample.root" ttreeOutputLabel="myoutput.root" ### ### Default values for the options are set: ### maxEvts = -1 ### sample = 'file:B2GED...
# coding: utf-8 # ## Example # * This Python example shows the non-linear superposition with parameter **$2*a=alpha=0.6$, in the Bark scale**. We construct a matrix which does the actual superposition in the Bark domain, because that is most efficient: # In[1]: import numpy as np def spreadingfunctionmat(maxfreq,...
#-*-coding:utf-8 -* import random import math # from random import randrange def verifier_chiffre_correct(question): while True: try: le_biff = int(raw_input(question)) print("TOTO") except: print("La valeur n'est pas correcte") print(le_biff) if le_biff <= 0: print("La valeur n'est pas correcte"...
from lettuce import * from lxml import html from django.test.client import Client from nose.tools import assert_equals, assert_true import logging LOG_FILENAME = 'test-debug.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) @before.all def set_browser(): world.browser = Client() @step(r'I acces...
import pytest from guardian.shortcuts import get_perms @pytest.mark.django_db def test_anonymous_user_has_no_edit_perm(location, guardian_anonymous_user): assert 'change_location' not in get_perms(guardian_anonymous_user, location) @pytest.mark.django_db def test_user_has_no_edit_perm(location, user): asser...
#Import necessary libraries from pylibkml import Kml, Utilities from csv import reader from string import atof, replace import urllib2 def process_datetime(datestr): ''' Takes the string value and processes it into something that Google Earth can use in its <TimeStamp> Keyword arguments: dates...
import os import io_function as iof import signal_processing as sp input_file_dir = 'C:/Users/유정찬/Desktop/test/clean_test' noise_file_dir = 'C:/Users/유정찬/Desktop/test/noise' output_file_dir = 'C:/Users/유정찬/Desktop/test/noisy_test' snr_or_ssnr = 'ssnr' target_dB = 10 frame_size = 1600 # check input, noise directory i...
# Copyright 2018 Open Source Robotics Foundation, 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...
# 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...
""" sort the distinct chars arr first and put this in a queue sort the numbers probably using a heap """ from heapq import heapify, heappop from collections import Counter class Solution: def isPossibleDivide(self, nums: List[int], k: int) -> bool: distinct_els = list(set(nums)) heapify(distinc...
# Lab 9: Unit Converter # This lab will involve writing a program that allows the user to convert a number between units. print('Welcome to the distance converter!' + '\n') # Version 1 # Ask the user for the number of feet, and print out the equivalent distance in meters. Hint: 1 ft is 0.3048 m. So we can get the out...
#!/usr/bin/env python3 """Elementwise add two n-dimensional matrices""" def add_matrices(mat1, mat2): """Recursively construct a new sum of two matrices""" try: if (len(mat1) != len(mat2)): return None newmat = [] for row1, row2 in zip(mat1, mat2): newrow = add_...
import random import cv2 import os import argparse import numpy as np import torch from detectron2.config import get_cfg from contact_hands_two_stream import CustomVisualizer from detectron2.data import MetadataCatalog from contact_hands_two_stream import add_contacthands_config from datasets import load_voc_hand_inst...
class Value: def getAddNum(self): global val_in_mem a = input("Enter the first number that you want to add: \n") if a == 'mrc': a = float(val_in_mem) else: a = float(a) b = input("Enter the second number that you want to add: \n") if b == 'mrc...
import json def get_params(): with open('pipeline_params.json') as json_file: data = json.load(json_file) return data
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that a failing postbuild step lets the build fail. """ from __future__ import print_function import sys import TestGyp from ...
class BetOnLoserStrategy(object): def strategy(self,*args): ''' Always bets 1 token monney to the loser, which is the player 'b' ''' return 1, 'b' class BetOnWinnerStrategy(object): def strategy(self,model_odds_player_a, model_odds_player_b, average_betting_excha...
""" 9. 回文数 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: 输入: 121 输出: true 示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 示例 3: 输入: 10 输出: false 解释: 从右向左读, 为 01 。因此它不是一个回文数。 进阶: 你能不将整数转为字符串来解决这个问题吗? date : 11-13-2020 """ class Solution: def isPalindrome(self, x: int) -> bool: ...
#!/usr/bin/env python import pwn libc = pwn.ELF('libc.so') elf_Demo = pwn.ELF('Demo') attack = pwn.process('./Demo') # attack = remote('127.0.0.1', 23333) plt_write = elf_Demo.symbols['write'] print '###### plt_write = ' + hex(plt_write) got_write = elf_Demo.got['write'] print '###### got_write = ' + hex(got_write)...
import pandas df = pandas.read_csv("sin_dataset.csv") power_d = 0 power_c = 0 power_b = 0 node_d = "" node_c = "" node_b = "" find_current_powers() link_prediction() def find_current_powers(): power_d = degree_centrality() #power_c = closeness_centrality() #power_b = betweenness_centrality() message ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 24 17:33:38 2019 @author: chenhaibin """ import time import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd import lightgbm as lgb from sklearn.model_selection import StratifiedKFold from sklearn.preprocessing ...
# Copyright 2018 QuantInsti Quantitative Learnings Pvt Ltd. # # 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 la...
from reverse_dict.methods import (Method01Py2, Method01Py3, Method02Py2, Method02Py3, Method03Py2, Method03Py3) from reverse_dict.config import cfg class Argument(object): def __init__(self, option_name, short_option, long_option, **kwargs): self.args = None self....
# Week 2 # Question 1 def text_handle(n): return " ".join(n.split()) sample_text = "Hello my friend" print(text_handle(sample_text)) # Time complexity: o(1) # Space complexity: o(1)
#!/usr/bin/env python3 """ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Audiophiles Music Manager Build 20180119 VER0.0.0PREALPHA * * (C)2017 Mattijs Snepvangers pegasus.ict@gmail.com * * test.py Package Tester ...
from django.shortcuts import render from django.core import serializers from rest_framework import status, viewsets, views from .models import Category, Product, Order, Highlight, HighlightBig from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import CategoryS...
import openpyxl import numpy as np import math import matplotlib.pyplot as plt from numpy.linalg import inv alarmdata=openpyxl.load_workbook('C:\\Users\\aviza\\Desktop\\CSE 674\\Project 1\\alarm10K.xlsx') aladata=alarmdata.get_sheet_by_name('alarm10K') individualp=[] def find_pdf(a,b): facts=1 probs=1 for...
from django.core.management.base import BaseCommand, CommandError from app.models import User class Command(BaseCommand): help = 'Create test data: users' def handle(self, *args, **options): print('Start!') # clear all users User.objects.all().delete() # Insert new users ...
import flask import os import pymongo import datetime from flask import Response, jsonify, render_template, request, json, Flask, session, redirect from flask_bootstrap import Bootstrap from flask.ext.session import Session from bson import BSON, json_util, Binary, Code from bson.objectid import ObjectId from bson.er...
from loraModes import rak811P2P import utime raks = rak811P2P(1, 115200, freq=868000000, spreading=7, preamble=6, debug=True) res = raks.start() if res == "OK": print(raks.getStatus()) for count in range(100): utime.sleep_ms(500) msg = "Effevee" + str(count) raks.send(msg) raks.stop...
import unittest import lab6_LoginPageUnitTest import Lab7_CountOfWebElements # two test cases are run together class Test_Suite(unittest.TestCase): def test_main(self): self.suite = unittest.TestSuite() self.suite.addTests([unittest.TestLoader().loadTestsFromModule(lab6_LoginPageUnitTest), ...
import json import os import shutil import math import pandas as pd import cv2 import glob import numpy as np import subprocess real_path = os.path.join(os.path.curdir, 'REAL(1500)\\REAL_SENTENCE_morpheme') syn_path = os.path.join(os.path.curdir, 'SYN(1500)\\SYN_SENTENCE_morpheme') video = {} video_data...
# [Classic] # https://leetcode.com/problems/max-value-of-equation/ # 1499. Max Value of Equation # History: # Google # 1. # Aug 1, 2020 # Given an array points containing the coordinates of points on a 2D plane, sorted by the # x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length...
"""All global variables and triggers are grouped here""" from data_containers.special_cases import SituationalData from data_containers.our_possessions import OurPossessionsData from data_containers.ungrouped_data import OtherData class MainDataContainer(SituationalData, OurPossessionsData, OtherData): """This is...
import numpy as np import keras from keras.models import Model, load_model from keras.layers import Dense, Input, Concatenate, Dropout, Add, Lambda, BatchNormalization from keras import regularizers from keras import backend as K from keras.engine.topology import Layer def load_model(location=None): if(location !...
# coding=utf-8 import copy """ 581. Shortest Unsorted Continuous Subarray """ class Solution(object): def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 n = len(nums) if n == 1: retu...
# -*- coding: utf-8 -*- """ Created on Tue Feb 6 21:31:21 2018 @author: shivangi """ from __future__ import division from nltk.corpus import wordnet as wn import math import sys # Parameters to the algorithm. Currently set to values that was reported # in the paper to produce "best" results. ALPHA = 0...