text
stringlengths
38
1.54M
# this is a simple example import logging import time # define the log file, file mode and logging level logging.basicConfig(filename='keepwriting.log', filemode="a", level=logging.DEBUG,format='%(asctime)s - %(levelname)s - %(message)s') logging.debug('This message should go to the log file') logging.info('So should t...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class MyspidersItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass class CompanyItem(scrapy.Ite...
from __future__ import print_function print("===== abelfunctions Demo Script =====") from abelfunctions import * from sympy.abc import x,y #f = y**3 + 2*x**3*y - x**7 f = y**2 - (x-1)*(x+1)*(x-2)*(x+2) X = RiemannSurface(f, x, y) print("\n\tRS") print(X) print("\n\tRS: monodromy") base_point, base_sheets, branch_poi...
import os import rq_dashboard from flask import Flask, Response # We need to use an external dependency for env management because pycharm does not currently support .env files from flask_cors import CORS from flask_talisman import Talisman import recommender.utilities.json_encode_utilities from recommender.api.util...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jan 24 14:55:44 2019 @author: zwala """ ##Conversions of int() num1=raw_input("Please enter x: ") num2=raw_input("Please enter y: ") num=num1+num2 print "The Concatenation: ",num #Concatenation num1=int(num1) num2=int(num2) num=num1+num2 print "The A...
def Primefactors(N):# Nより小さい自然数の素因数の個数と約数の個数を返すO(Nlog(N)) Ints = [ i for i in range(N)] Primefactors = [0]*N Factors = [1]*N for i in range(2, N): if Ints[i] == 1: continue for j in range(1, N): if i*j < N: t = 1 while Ints[i*j]%i =...
import json import jsonschema import uuid import unittest import websockets from tornado.testing import AsyncHTTPTestCase from tornado.httpclient import AsyncHTTPClient import broadway.api.definitions as definitions from broadway.api.utils.bootstrap import ( initialize_global_settings, initialize_database, ...
import webbrowser class Movie: """This class provides information about the movies""" VALID_RATINGS = ["G", "PG", "PG-13", "R"] def __init__( self, movie_title, movie_storyline, poster_image, trailer_youtube): """Initiating with the matched information :param movie_title: The...
# -*- coding: utf-8 -*- """ Created on Sat May 28 20:08:05 2016 @author: Liberator """ import numpy as np import matplotlib.pyplot as plt #formula opisujaca ewolucje populacji USA def ewolucjaPopulacji(rok): potega = -0.03137 * (rok - 1913.25) P = 19727300 / (1 + (np.e**potega)) return P #zakres lat mied...
from django.db import models class Salas(models.Model): sal_id = models.AutoField(primary_key=True) sal_codigo = models.CharField(max_length=250) salas_sal_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
a=int(input("enter the value of a:")) b=int(input("enter the value of b:")) if(a>b):print("a is greater than b") if(b>c):print("b is greater than a") else:print("b is equal a")
import math import sys try: r = int(raw_input("Please enter radius of a circle ")) except ValueError as e: print "Invalid radius value" print e sys.exit(-1) except IOError as e: print "IOError" print e sys.exit(-1) area = math.pi * r * r print area
#!/usr/bin/env python from __future__ import print_function import sys from eTraveler.clientAPI.connection import Connection myConn = Connection('jrb', 'Dev', localServer=False) #myConn = Connection('jrb', 'Dev', localServer=True, debug=True) #myConn = Connection('jrb', 'Raw', prodServer=True) rsp = {} try: run...
from pymem import Pymem fileStruct = (0x6d9100) bufferOffset = (3-1)*4 pm = Pymem('Rebels.exe') bufferPtr = pm.read_uint(fileStruct + bufferOffset) content = [] idx = 0 while True: ch = pm.read_uchar(bufferPtr + idx) if ch in [0x0D, 0xF0, 0xAD, 0xBA]: break content.append(ch) idx += 1 print(...
from setuptools import setup with open('README.rst', encoding='utf-8') as file: long_description = file.read() install_requires = [ 'aiohttp', 'aioredis', 'click', 'structlog[dev]', 'websockets', ] tests_require = install_requires + [ 'aioresponses', 'pytest', 'pytest-asyncio', ]...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- from decimal import Decimal def bmi(weight,height): return weight/(height*height) weight = Decimal(input("Введіть вагу (в кг): ")) height = Decimal(input("Введіть зріст (в м): ")) print(bmi(weight,height))
# Copyright 2012 Sam Kleinman # # 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, sof...
# -*- coding: utf-8 -*- """ Created on Wed Sep 16 10:00:45 2020 @author: cpcle """ from os import listdir from os.path import isfile, join import re from cloudant.client import Cloudant from cloudant.error import CloudantException from cloudant.result import Result, ResultByKey serviceUsername = "afd...
#!/usr/bin/env python #coding:utf-8 from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait,Select from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.commo...
import feedback, utilities, constants furthersubcomponents = feedback, utilities def initialize(client): for furthersubcomponent in furthersubcomponents: furthersubcomponent.client = client feedback = feedback.feedback
# -*- coding: utf-8 -*- """ Задание 9.3 Создать функцию get_int_vlan_map, которая обрабатывает конфигурационный файл коммутатора и возвращает кортеж из двух словарей: * словарь портов в режиме access, где ключи номера портов, а значения access VLAN (числа): {'FastEthernet0/12': 10, 'FastEthernet0/14': 11, 'FastEther...
import unittest import numpy as np from scipy.linalg import norm from flowFieldWavy import * # K=2, L=7, M=3, N=21 ind1 = np.index_exp[2,3,1,2,11] # k= 0, l=-4, m=-2, y=yCheb[11] ind2 = np.index_exp[1,9,2,0,5] # k=-1, l= 2, m=-1, y=yCheb[5] ind3 = np.index_exp[3,4,0,2,10] # k= 1, l=-3, m=-3, y=0. ind4 = ...
# Thompson's contstruction # Johnathan Joyce def shunt(infix): """The Shunting yard algorithm - infix to postfix""" # special characters precedence specials = { '*': 50, '.':40, '|':30} pofix = "" # operator stack stack = "" for c in infix: ...
"""Utility functions for [pygame.Rect]s.""" import pygame def create(center, size): """Create Rect given a [center] and [size].""" rect = pygame.Rect((0, 0), size) rect.center = center return rect
import os from configurations import Configuration class Dev(Configuration): # Stripe keys will be blank for pushing to GitHub # Fill out the test mode keys here before running STRIPE_PRIVATE_KEY = "" STRIPE_PUBLIC_KEY = "" DEBUG = True TEMPLATE_DEBUG = DEBUG SECRET_KEY = 'a_v@l1i4s0$v...
import os import time import shutil from conans.client import tools from conans.model.env_info import EnvInfo from conans.model.user_info import UserInfo from conans.paths import CONANINFO, BUILD_INFO, RUN_LOG_NAME, long_paths_support from conans.util.files import save, rmdir, mkdir, make_read_only from conans.model.r...
#!/usr/bin/env python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) # Define LEDs led_6 = 8 led_5 = 10 led_4 = 12 led_3 = 16 led_2 = 18 led_1 = 22 leds = (8, 10, 12, 16, 18, 22) # Setup LEDs GPIO.setup(led_1, GPIO.OUT) GPIO.setup(led_2, GPIO.OUT) GPIO.setup(led_3, GPIO.OUT) GP...
import datetime from django.db import models from django.contrib.auth.models import User class EventManager(models.Manager): def get_subscriptions(self, subscriber): event_subscriptions = EventSubscription.objects.filter(subscriber=subscriber) return super().get_queryset().filter(eventsubscriptio...
from flask import current_app, url_for, flash from werkzeug.utils import redirect from view_models.forms.login import LoginForm from x_app.identity_provider import WrongPasswordError, UserNotFoundError from x_app.navigation import XNavigationMixin, XNav from x_app.view_model import XFormPage class LoginViewModel(XFo...
#!/usr/bin/env python import pandas as pd from miran import Character, battle cs = [Character.rand() for i in range(0, 200)] df = pd.DataFrame(((c.str, c.dex, c.d) for c in cs), columns=['str', 'dex', 'def']) df['wins'] = 0 for i in range(0, len(cs)): for j in range(i + 1, len(cs)): assert i != j ...
def extractEachKth(inputArray, k): newInputarray = [] for i in range(1, len(inputArray)+1): if i % k != 0: newInputarray.append(inputArray[i-1]) return newInputarray inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] k = 3 result = extractEachKth(inputArray, k) print(result)
""" Cloud component This program act as the component that has to run on the centralised cloud environment. Currently, it receives a customisable number of images and temporarily stored them in a provided repository. This component can be further extended for any excessive computational task. """ from socket import * ...
from __future__ import print_function import os,sys from struct import unpack,pack f = open('test.caj','rb') header = f.read(9*16) pages_string = f.read(8) pages = [] contents = [] [pages_count,unknown] = unpack('ii', pages_string) print('pages: '+str(pages_count)) # extract content index f.seek(12*16, os....
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'modificacionSectorDePersonal.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): ...
from django import template from django.utils.safestring import mark_safe import markdown register= template.Library() @register.filter def field_type(bound_field): return bound_field.field.widget.__class__.__name__ @register.filter def input_class(bound_field): css_class='' if bound_field.f...
import sys #sys.stdin=open("in5.txt","r") k,n=map(int,input().split()) base=[int(input()) for _ in range(k)] start=1 end=max(base) max_len=-100 while start<=end: mid=(start+end)//2 nn=0 for j in range(k): nn+=base[j]//mid if nn>=n: max_len=mid start=mid+1 e...
# -*- coding: ISO-8859-15 -*- # Copyright (c) 2004 Nuxeo SARL <http://nuxeo.com> # Author: Encolpe Degoute <edegoute@nuxeo.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as published # by the Free Software Foundation. # # Th...
import os import re from Person import Person class Displayer(): def __init__(self, simulator, medicalModel, config_isolation, config_preventions, log=None, showDetails=False): self.simulator = simulator self.medicalModel = medicalModel self.isolationTag = config_isolation['sign'] s...
import random import base64 class Config: SECRET_KEY = base64.b64encode(bytes(random.randint(100000, 19999999))) DEBUG = True # 关闭debug
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel from torch.nn.utils import spectral_norm from torchvision.models.video.resnet import r2plus1d_18 from miscc.config import cfg from torch.autograd import Variable import numpy as np import pdb if torch.cuda.is_available(): T ...
""" Ansible action plugin to ensure inventory variables are set appropriately and no conflicting options have been provided. """ import collections import six from ansible.plugins.action import ActionBase from ansible import errors FAIL_MSG = """A string value that appears to be a file path located outside of {} has...
n, m = 5, 5 mylist = [[1, 3], [1, 4], [4, 5], [4, 3], [3, 2]] # 플로이드워셜 import sys input = sys.stdin.readline n, m = map(int, input().split()) mylist = [list(map(int, input().split())) for _ in range(m)] graph = [[99999999]*n for _ in range(n)] for a, b in mylist: graph[a-1][b-1] = 1 graph[b-1][a-1] = 1 for ...
import pandas as pd ufo = pd.read_csv('http://bit.ly/uforeports') ufo.shape ufo.head() ufo.drop('City', axis=1).head() # city column did't gone ufo.head() ufo.drop('City', axis=1, inplace=True) ufo.head() ###### ufo.dropna(how='any') ufo.dropna(how='any').shape # now yet inplaced ufo.shape # can be done by assig...
from modules.FlaskModule.FlaskModule import flask_app from opentera.modules.BaseModule import BaseModule, ModuleNames from opentera.config.ConfigManager import ConfigManager # Same directory from .TwistedModuleWebSocketServerFactory import TwistedModuleWebSocketServerFactory from .TeraWebSocketServerUserProtocol impo...
import subprocess def webcam_make_screenshot(): """ Returns: The screenshot filename """ subprocess.call("fswebcam -r 320x240 --jpeg 85 -D 1 -S 2 webcam.jpg", shell=True) return "webcam.jpg"
import numpy as np import pandas as pd import time import argparse from sklearn.metrics import f1_score, confusion_matrix, matthews_corrcoef, classification_report,\ balanced_accuracy_score, roc_auc_score from flair.models import TextClassifier from flair.data import Sentence import statistics import sys import os ...
from flask import Flask, render_template app = Flask(import_name=__name__, static_url_path='/', static_folder='static', template_folder='templates') # 添加html访问路由 @app.route('/') def blog(): return render_template('index.html') if __name__ == "__main__": app.run() # 默认设置host:0.0.0.0 port:5000
from .simdis import sdinput, sdstart, sdprint, sdstop __ALL__ = ["sdstart", "sdstop", "sdprint", "sdinput"]
import random from time import sleep import sys import threading import os import argparse import platform import subprocess REQUIRED_PACKAGES = ["selenium", "feedparser", "beautifulsoup4", "setuptools"] def updateDependencies(dependencies): for dependency in dependencies: try: subprocess.che...
# import argparse # parser = argparse.ArgumentParser() # parser.add_argument("--record", help="Record the demo and store the outcome to `temp` directory") # parser.add_argument("--prepare", help="Get `data,csv` and screenshots of the game, then prepare features and labels in `data` directory") # args = parser.parse_arg...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from db.BOW_DB import BOW_DB from db.LDA_DB import LDA_DB from vis.TermTopicMatrix2 import TermTopicMatrix2 def index(): with BOW_DB() as bow_db: with LDA_DB() as lda_db: handler = TermTopicMatrix2(request, response, bow_db, lda_db) return handler.Gener...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- cases = int(input().strip()) for i, line in enumerate(range(cases), 1): number = input().strip() if int(number) == 0: print("Case #{0:s}:".format(str(i)), 'INSOMNIA') else: current_L = list(map(int, number)) current_S = ''.join(str(x)...
# -*- coding: utf-8 -*- ''' This function calls the org_netcdf_files function (which organizes the files by date) and returns the file that matches with the date. It is meant specifically for soundings and prints the file name for reference. author: Grant Mckercher ''' import datetime def gather_sounding_files(dat...
import numpy as np import matplotlib.pyplot as plt from model.constant_variables import ( D0, k_i, k_a, rho_a, rho_i, C_i, C_a, ka0, ka1, ka2, L_Cal, mH2O, kB, T_ref_L, a0, a1, a2, f, rho_ref, T_ref_C, c1, ...
import requests, sys, re, configparser from docx import Document from urllib.parse import urljoin from bs4 import BeautifulSoup from docx.shared import Pt from docx.oxml.ns import qn from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.enum.style import WD_STYLE_TYPE class Article(object): def _...
# -*- coding: utf-8 -*- """ Created on Fri Nov 2 14:11:18 2018 @author: jacky """ #import libraries import sys import tweepy from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener #import json #import re #import matplotlib.pyplot as plt #import pandas as pd #from nltk.to...
class Solution: def isValid(self, s: str) -> bool: open_brackets = {'(': ')', '[': ']', '{': '}'} stack = [] for c in s: if c in open_brackets: # open bracket stack.append(c) else: # close brakcet if len(stack) == 0: ...
Arr=[10,23,45,67,89,24,68,59,39,36,20] n=len(Arr) K=int(input()) def SL(Arr,n,K): L,Arr[n-1]=Arr[n-1],K i=0 while(Arr[i]!=K): i+=1 Arr[n-1]=L if(i<n-1) or (Arr[i]==K): return i else: return False I=SL(Arr,n,K) if(I): print("Position=",I) else: p...
# -*- coding: utf-8 -*- ###################################################################################################### # # Copyright (C) B.H.C. sprl - All Rights Reserved, http://www.bhc.be # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
#!/usr/bin/python3 import os #import time import configparser from gpiozero import Button #from gpiozero import LED from signal import pause config = configparser.ConfigParser() config.read('/opt/vougen/vougen.conf') gpio = config['gpio'] #led_number = gpio['led'] key_number = int(gpio['key']) def send_request(): ...
from funcs import readHTTP # Get the page and print an error if not HTTP 200 addCheck, e = readHTTP("http://172.16.0.198") if e != "": print(e) else: print("Retrieved page successfully")
import math def newtonsAlgorithm(func, funcder): """ Newtons method :param func: Equation :param funcder: Derivative of the equation :return: """ x0 = float(input('x0')) m = int(input('M')) delta = float(input('delta')) epsilon = float(input('epsilon')) v = func(x0) pri...
# Simple CNN model for CIFAR-10 import numpy from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.constraints import maxnorm from keras.optimizers import SGD from keras.layers.convolutional import Conv3D from keras.layers.convolu...
import socket import time import os import subprocess import threading import re import signal from tools import connect_to_host, client_thread, get_ip func_dict = {"firewall" : '0', "monitor": '1', "nat": '2', "ids": '3', "vpn": '4', "firewall_setget" :...
# -*- coding: utf-8 -*- # __author__ = 'zs' # 2018/12/4 下午2:20 print(len('')) print('abc'[0:1]) print('abc'[1:2]) print('abc'[2:3]) l1 = [1, 2, 3] print(l1[:]) # 返回[1, 2, 3] print(l1[::]) # 返回[1, 2, 3] print(l1[:-1]) # 返回[1, 2] print(l1[::-1]) # 列表反转,返回[3, 2, 1] def factorial(n): """return n!""" retu...
#Dropouts from tensorflow.keras.wrappers.scikit_learn import KerasClassifier from tensorflow.keras.layers import Dropout from sklearn.model_selection import GridSearchCV def build_model(d1, d2): model = Sequential() model.add(Dense(32, input_shape=(X_train.shape[1],), activation='relu')) model.add(Dropout...
# 导包 import requests class LoginApi: def __init__(self): self.login_url="http://ihrm-test.itheima.net"+"/api/sys/login" def loginapi(self,jsonData,headers): repons = requests.post(url=self.login_url, json=jsonData, # 发送登录请求 ...
#use snake case naming convention although camel case also works but prefer snake case # name_second_name -> snake case & nameSecondName->camelcase #no special symbol #firstcharacter is either character or _ only _name="vimal lohani" number1 =5 print(_name) print(number1) print(_name *3) name,age ="vimal",28 p...
''' Created on Feb 15, 2012 @author: mjbommar ''' import dateutil.parser import lxml.html import nltk import nltk_contrib.readability.readabilitytests import re class Document(object): ''' The Document class handles parsing and storing data about a GPO document. ''' def __init__(self, buffe...
def is_prime(num): if num == 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True n = int(input()) data = list(map(int, input().split())) count = 0 for i in data: if is_prime(i): count += 1 print(count)
#!/usr/bin/env python3 """ This module extends Python's re module just a touch, so re will be doing almost all the work. I love the stock re module, but I'd also like it to support extensible regular expression syntax. So that's what this module does. It is a pure Python wrapper around Python's standard re module that...
import json countries=countries=[ { "id": "male", "active": True, "defaultOption": True, "optionText": "Singapore", "optionValue": "Singapore" }, { "id": "male", "active": True, "defaultOption": True, "optionText": "Malaysia", "optionValue": "Malaysia" }, ...
# Time Complexity : O(N + mlogm) # Space Complexity : O(n) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No ''' 1. Store sentences ad thier occurence time in hashmap 2. To sort these sentences according to their ocuurence I have use max heap 3 Maximum priority is given t...
## 2018/01/12 basic_Tkinter_2 ## Entry & Text import tkinter as tk window = tk.Tk() window.title('my window') window.geometry('300x150') #show輸入後顯示為* #entry e = tk.Entry(window,show='●') e.pack() def insert_point(): var = e.get() t.insert('insert',var) def insert_end(): var = e.get() ...
"""AppAssure 5 REST API""" from appassure.api import AppAssureAPI class IReplicationManagement(AppAssureAPI): """Full documentation online at http://docs.appassure.com/display/AA50D/IReplicationManagement """ def setAgentReplicationSettings(self, data, agentId): """Set replication settings in...
\1、什么是线程 # 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程。线程才是真正的执行单位。 # 线程顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程。 # 车间负责把资源整合到一起,是一个资源单位,而一个车间内至少有一个流水线。流水线的工作需要电源,电源就相当于cpu。 # 所以,进程只是用来把资源集中到一起(进程只是一个资源单位,或者说资源集合),而线程才是cpu上的执行单位。 # 多线程(即多个控制线程)的概念是,在一个进程中存在多个控制线程,多个控制线程共享该进程的地址空间,相当于一个车间内有多条流水线,都共用一个车间的资源。 # 例如,北京地铁与...
# turime sarasa pasikartojanciu elementu (skaiciu) skaiciai = [1, 2, 3, 4, 67, 132, 3, 1, 1, -1 , -1, 1.3, 1.3 , 2.2] # skaiciuojam kiekvieno saraso elemento pasikartojimus for elementas in skaiciai: pasikartojimai = skaiciai.count(elementas) # ismetam pasikartojancius is skaiciai saraso # paliek...
import pandas as pd import pickle import numpy as np import torch # Loading DataSet db = pd.read_csv('Pickles/tadpole-preprocessed - Tadpole dataset - Sheet1.csv') y_pred = db["DX_bl"].to_numpy() to_add = 0 add_dict = dict() # Converting predictions to numbers for i in range(len(y_pred)): if y_pred[i] not in ad...
import sys, inspect, hashlib from abc import ABCMeta, abstractmethod from collections import namedtuple from exceptions import * class BoxList(list): ''' variant of Python's list to store Box contents ''' # methods we need; then we disable the rest - throw error if called implement = [ '__new__', '__init__', '_...
import numpy as np import time as time import os from datetime import datetime from random import shuffle import tensorflow as tf from tensorflow.keras.applications.vgg16 import VGG16 from tensorflow.keras.models import Model, load_model from tensorflow.keras.layers import Dense, Flatten, Dropout from tensorflow.keras....
#На основе нейрона из видео https://www.youtube.com/watch?v=SEukWq_e3Hs сделать однослойный перцептрон import numpy as np import matplotlib.pyplot as plt import os D = None Y=None w = np.zeros((5, 25)) a = 0.2 b = -0.4 c = lambda x: 1 if x > 0 else 0 def f(x,i): s = b + np.sum(x @ w[i]) return c(s) def train(...
from django.urls import path from . import views from rest_framework import routers urlpatterns = [ path('', views.index_page, name='index_page'), # index page path('todos/', views.todos, name='todo'), path('api/v1/todos/', views.Todos.as_view(), name='api_todo'), path('api/v1/todos/<int:pk>/', vi...
import schedule import threading import time # this is a class which uses inheritance to act as a normal Scheduler, # but also can run_continuously() in another thread class ContinuousScheduler(schedule.Scheduler): def run_continuously(self, interval=1): """Continuously run, while executing pending j...
from django.urls import path from .views import ( TaskListView, TaskDetailView ) urlpatterns = [ path('', TaskListView.as_view(), name='task-list'), path('<pk>/', TaskDetailView.as_view(), name='task-detail'), ]
import numpy as np import tensorflow as tf from functools import partial class Actor(object): def __init__(self, n_observation, n_action, name='actor_net'): self.n_observation = n_observation self.n_action = n_action self.name = name self.sess = None self.build_model() ...
import unittest import json from collections import OrderedDict from nltk import pos_tag from testResolvit import WordFrequencyAnalyzer class Test(unittest.TestCase): def setUp(self): self.wfa = WordFrequencyAnalyzer() def test_remove_stopwords(self): result = self.wfa.removeStopwords(["be", "honest"]) self...
#REST API: from flask import Flask app = Flask(__name__)#referance the file @app.route("/patient_report/<string:id>/<int:du>") def hello(id , du): #!/usr/bin/env python # coding: utf-8 # In[1]: import datetime import pandas as pd import numpy as np import firebase_admin f...
import sys import collections from p4_hlir.main import HLIR from function import * def parseControlFLow(): #h = HLIR("./stateful.p4") h = HLIR("./l2_switch.p4") #h = HLIR("../../tutorials-master/SIGCOMM_2015/flowlet_switching/p4src/simple_router.p4") #h = HLIR("../../tutorials-master/SIGCOMM_2015/source_routing...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import Formulario, FormularioCursos, TestForm from django.core.files.storage import FileSystemStorage from .models import Cursos,Usuarios, CursosDDAF, Cursos_Alumno, asistencia from django.contrib.auth.models impo...
import os import threading import json from core import core from flask import Flask, render_template, request, redirect, url_for from flask_restful import Resource, Api bn_config = { 'action' : 'config', 'name' : 'Config', 'class' : 'btn btn-outline-secondary' } bn_start = { 'action' : 'start', ...
import simplejson as json from index_preprocess import * from features import * with open('xda_posts.json') as f: posts = json.load(f) posts = sorted(posts, key=lambda k: len(k['thanks']), reverse=True) top_posts = posts[0:250] with open('xda_threads.json') as f: thread_lookup = build_thread_lookup(json.load...
from semmatch.data.fields.field import Field from semmatch.data.fields.label_field import LabelField from semmatch.data.fields.text_filed import TextField from semmatch.data.fields.index_field import IndexField from semmatch.data.fields.numerical_field import NumericalField from semmatch.data.fields.vector_fields impor...
#!/usr/bin/env python3 import argparse from util.base_util import * from util.file_util import * BUILDBOT_CONFIG = [path.join('testing', 'buildbot', 'chromium.gpu.json'), path.join('testing', 'buildbot', 'chromium.gpu.fyi.json'), path.join('testing', 'buildbot', 'chromi...
class Customer: def __init__(self, name, fund): self.name = name self.fund = fund self.bike = None class Bicycle: def __init__(self, model, weight, cost): #Method to sell bicycles with a margin over the cost self.model = model self.weight = weight self.cost =...
import sublime import sys import io from datetime import datetime as dt from unittest import TestCase from unittest.mock import Mock, patch from code.SublimePlugin import codeTime codeTime1 = sys.modules["SE_Fall20_Project-1.code.SublimePlugin.codeTime"] class TestFunctions(TestCase): @patch('time.time', retur...
def celsius_2_fahrenhit(celsius): if celsius < -273.15: return "the lowest possibletemperature that physicalmatter can reach is -273.15C not allowed less than" else: fahrenhit = celsius * (9/5) + 32 return fahrenhit #print(celsius_2_fahrenhit(-32433)) temprature_list = [10,-20,-289,100] for i in temprature_l...
from Heap import MinHeap def k_heap_sort(conjunto, k): """ Dado un conjunto y un indice k, devuelve el k elemento mas chico. Si k es mas grande que el tamanio del conjunto devuelve None. """ heap = MinHeap() heap.heapify(conjunto) for i in xrange(k - 1): heap.sacar_primero() return heap.sacar_primero()
import matplotlib.pyplot as plt trainFileStr = "D:/Research/Dataset/checkin/user_checkin_above_10x10x5_us_train - Copy.txt" testFileStr = "D:/Research/Dataset/checkin/user_checkin_above_10x10x5_us_test - Copy.txt" counts = [] trains = [] trainSets = [] docTrainLens = [] tests = [] testSets = [] docTestLens = [] a = ...
from docassemble.base.functions import define, defined, value, comma_and_list, word, comma_list, DANav, url_action, showifdef from docassemble.base.util import Address, Individual, DAEmpty, DAList, Thing, DAObject, Person from docassemble.assemblylinewizard.interview_generator import map_names class AddressList(DALis...
def func(): n=int(input()) l=[int(x) for x in input().split()] a=[] for i in range(n-1): max=l[i+1] for j in range(i+1,n): if(max<=l[j]): max=l[j] a.append(max) a.append(0) print(*a) op=func()