text
stringlengths
38
1.54M
from django.contrib.auth.mixins import LoginRequiredMixin from django.views import generic class HomeView(generic.TemplateView): template_name = 'index.html' class SignUpView(generic.TemplateView): template_name = 'sign_up.html' class LoginView(generic.TemplateView): template_name = 'sign_in.html' c...
# usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = 'wangjianfeng' import requests import re import time import http.cookiejar as cookielib from selenium import webdriver from bs4 import BeautifulSoup # 构造request headers agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome...
# -*- coding: utf-8 -*- ############################################################################## # # Purchase Date Planned Update module for Odoo # Copyright (C) 2015 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # @author Sébastien Beau <sebastien.beau@a...
from django.db import models from stdimage.models import StdImageField # import uuid # def get_file_path(_instance, filename): # ext = filename.split('.')[-1] # filename = f'{uuid.uuid4()}.{ext}' # return filename """ Função para Criptografar o caminho das imagens... trocar o upload_to='serviços/imagens ...
from django.urls import path from .views import index, list_of_recommendations urlpatterns = [ path('', index), path('recommend/Stuff', list_of_recommendations), ]
from sage.categories.category_with_axiom import CategoryWithAxiom, all_axioms from sage.misc.cachefunc import cached_method class Magmas: class GAP(CategoryWithAxiom): class ElementMethods: def _mul_(self, other): r""" Return the product of self by other ...
# vim: set fileencoding=utf-8 : """ Test L{gbp.deb.changelog.ChangeLog} """ cl_debian = """git-buildpackage (0.5.32) unstable; urgency=low * [efe9220] Use known_compressions in guess_upstream_version too (Closes: #645477) * [e984baf] git-import-orig: fix --filter -- Guido Günther <agx@sigxcpu.org> Mon, 17...
"""Defines URL patterns for offers app.""" from django.urls import path from . import views ##from django.conf import settings ##from django.conf.urls.static import static app_name = 'offers' urlpatterns = [ #Home page for offers app. path('', views.index, name='index'), #New_offer page for adding new off...
def main(): t = int(input()) # read a line with a single integer for i in range(1, t + 1): r, c = map(int, input().split()) matrix = [] for j in range(r): matrix.append(input()) print("Case #{}: {}".format(i, str(solve_problem(r, c, matrix)))) def solve_problem(r, ...
#coding:utf-8 # 很差劲的sample from atexit import register from random import randrange from threading import BoundedSemaphore,Lock,Thread from time import ctime,sleep lock = Lock() MAX = 5 candytray = BoundedSemaphore(MAX) def refill(): lock.acquire() print 'Refilling candy ...' try: candytray.release() except E...
import itertools import numpy as np import pandas as pd import scaa import scipy.sparse as ss import scipy.stats as st import torch def simulate_pois(n, p, rank, eta_max=None, holdout=None, seed=0): np.random.seed(seed) l = np.random.normal(size=(n, rank)) f = np.random.normal(size=(rank, p)) eta = l.dot(f) ...
from django.contrib import messages from django.core.paginator import Paginator from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # allauth de...
import xml.etree.ElementTree as et import sys def get_depth_rec(el: et.Element, depth: int) -> int: if len(el) or el.attrib: dep = depth + 1 for child in el: if isinstance(child, et.Element) and child.attrib: d = get_depth_rec(child, depth + 1) if d > dep: ...
# coding=UTF-8 @dbRequestHandler('ABLOG-MAIN','GET-USER-INFO') def request__get_user_info(db,userid,**kwargs): reqres = db._make_request( """ SELECT user_id,user_name, user_passwd,user_email, user_reg_time,user_avatar_path, user_about_text FROM {db_name}.USERS WHERE user_id = {user_id} ""...
from numpy import genfromtxt from sklearn import linear_model path = r'./dataset1.csv' data = genfromtxt(path, delimiter=',') print(data) x_data = data[:, :-1] # 所有行 除开最后一列 最后一列为运输时间 print("x_data:\n %s" % format(x_data)) y_data = data[:, -1] # 所有行 只取最后一列 print("y_data:\n %s " % format(y_data)) # 导入线性回归分类器 regr =...
from rest_framework import serializers from .models import Notification class NotifSerializer(serializers.ModelSerializer): class Meta: model = Notification fields = ('to', 'by', 'answer',)
from django.db import models import datetime # Create your models here. class Todo(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=300) due_date = models.DateField(("Date"), default=datetime.date.today)
""" Configure test suite Test run command: py.test --cov-report term-missing --cov=api tests/ """ import pytest from api.app import create_app from api.database import db as _db from api.config import TestConfig @pytest.fixture(scope='function') def app(): _app = create_app(TestConfig) ctx = _app.test_reques...
import httplib import time from datetime import datetime from base64 import b64encode,b64decode import hmac from hashlib import sha512 from urllib import urlencode import urllib2 import json class MtgoxHttpInterface(object): def __init__(self, key, secret): self.key = key self.secret = secret self...
from lib import hashmap from nose.tools import * def test_add(): h = hashmap.HashMap() h.add('john', 'Google') assert h.get('john') == 'Google' def test_negative_capacity(): h = hashmap.HashMap(-10) assert h.size() == 0 h.add('john', 'Google') assert h.get('john') == 'Google' def test...
def validBraces(string): a = "[]" b = "{}" c = "()" while (string.find(a) != -1) or (string.find(b) != -1) or (string.find(c) != -1): if (string.find(a) != -1): string=string.replace(a,"") if (string.find(b) != -1): string=string.replace(b,"") if (str...
def coroutine(func): def start(*args, **kwargs): cr = func(*args, **kwargs) next(cr) return cr return start @coroutine def grep(pattern): print("Looking for %s" % pattern) while True: line = (yield) if pattern in line: print(line) g = grep("python") ...
from discord_webhook import DiscordWebhook from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.c...
from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders import smtplib import os import ssl import sys username = os.getenv('OUTLOOKUSER') if os.getenv('OUTLOOKUSER') else sys.exit('Missing outlook user variable') password = os...
""" Written by sourabh agrawal In this program i am implementing double linked list using python3 and concepts of classes user can perform ->insertion at beginning ->insertion at end ->insertion at any given position ->deletion from beginning ->deletion from end ->deletion after any given no ...
""" Lissajous curve sketcher (using Matplotlib.pyplot). This script plots a Lissajous figure and provides a graphical user interface to allow the user to vary the parameters in the Lissajous parametric equations. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider # Create t...
import networkx as nx import numpy as np import pandas as pd import scipy from scipy import sparse import pickle import sklearn as sk from sklearn.cluster import KMeans from sklearn.manifold import TSNE import sys import os import graphwave as gw from characteristic_functions import * FB15K237_dir = '/...
from ast import Str import sys import os from datetime import datetime tags = ['add one url','remove one'] appLogs = [] epoch = datetime.utcfromtimestamp(0) class DownloadAction: url = "" action_add = epoch action_remove = epoch def parse(self, l): if tags[0] in l: return self.ad...
#lists #all the operation of list add remove etc N = int(input()) ls=[] def insert1(pos, num): ls.insert(pos, num) def remove1(num): ls.remove(num) def append1(num): ls.append(num) def sort1(): ls.sort() def pop1(): ls.pop() def reverse1(): ls.reverse() def print1(): print(ls) w...
#!/usr/bin/env python #Hisar FRC #copyright: Terobero #Hisar School import sys import time import pygame, serial import RPi.GPIO as GPIO from pygame.locals import * import random pygame.init() sys.path.insert(0,"/home/pi/Desktop/HisArcade/pins") import gamePins gamePins.gameSetup() scoreboard = gamePins.getScores("F...
import threading import thread import time doExit = 0 class newThread (threading.Thread): def __init__(self, threadID, name, counter): self.threadID = threadID self.name = name self.counter = counter threading.Thread.__init__(self) def run(self): print "Sta...
import pytest from programmers_42578 import solution @pytest.mark.parametrize("clothes,expected", [ [[["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]], 5], [[["crow_mask", "face"], ["blue_sunglasses", "face"], ["smoky_makeup", "face"]], 3] ]) def test_solution_default_...
#!/usr/bin/python3 from flask import Flask, request, render_template from model import Model import settings app = Flask(__name__) model = Model.from_pickles(settings.MODEL_FILE, settings.VECTORIZER_FILE) @app.route('/', methods=['POST', 'GET']) def index(text='', prediction_message=''): if request.method == "...
import re import pandas as pd import boto3 import pandas as pd import numpy as np import psycopg2 import string """extract specified features from corpus of text documents""" class FeatureExtraction(object): def __init__(self, data): """ INPUT: - data = Path to data file as JSON string ...
import threading as th def hello(name): while True: print('Hello {}'.format(name)) def main(): th.Thread(target=hello, args=('Alice',)).start() th.Thread(target=hello, args=('Bob',)).start() main()
#!/usr/bin/env python # Red King Simulation Sonification # Copyright (C) 2016 Foam Kernow # # 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 3 of the License, or # (at your option)...
Emp=[] def findConnections(name1, name2): if len(Emp)==0: connect=[name1,name2] Emp.append(connect) else: found=1 for i in Emp: if name1 in i : i.append(name2) found=1 return elif name2 in i: ...
""" The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): "123" "132" "213" "231" "312" "321" Given n and k, return the kth permutation sequence. Note: Given n will be between 1...
import hdfs import pymongo import json import os import time # 启动 mongodb # sudo mongod --dbpath=/Users/h2p/Documents/Project/data/db client = hdfs.Client('http://*:50070', root='/') print('连接 hdfs') # client = hdfs.Client('http://*:50070', root='/') # client = hdfs.Client('http://*:50070', root='/') print('连接 mongo...
import numpy as np class Optimizer: def __init__(self, name="Base optimizer"): self.name = name def initialize(self, params): pass def apply(self, params, grads, step_i=None): pass class SGD(Optimizer): def __init__(self, lr=0.001, momentum=0.0, nesterov=False, bias_correc...
import os import tkinter from tkinter import filedialog cur_path=os.getcwd() root = tkinter.Tk() root.withdraw() files = filedialog.askopenfilenames(parent=root,initialdir =cur_path,title = "Choose files to be renamed") print(f'{len(files)}files selected') print() outpath = filedialog.askdirectory(parent=root,initia...
import logging from builtins import classmethod import csv import os from elastic.management.loaders.mapping import MappingProperties from elastic.management.loaders.loader import Loader import json from data_pipeline.helper.gene import Gene logger = logging.getLogger(__name__) class GenePathways(Gene): ''' Gen...
from flask import Blueprint, jsonify, Flask, redirect, request, url_for, render_template from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, PasswordField, DateField from wtforms.validators import DataRequired class ArticleForm(FlaskForm): title = StringField("Title", validators=[DataReq...
from flask import Flask,render_template,request,redirect import pickle import pandas as pd import numpy as np with open("Laura/Assets/Model/locations.txt", "r") as f: locations = f.read() locations = locations.strip()[1:len(locations)-1] locations = locations.split(',') location_data = [i.strip() for i...
import errno import gi import glob import io import logging import os import re import time import v4l2 import sdnotify import signal import sys import traceback from fcntl import ioctl from .config import * from .streamer import * from .advertise import StreamAdvert from .janus import JanusInterface gi.require_versi...
from game.game import Game HOST = '127.0.0.1' PORT = 32198 def main(): game = Game(HOST, PORT) game.run() if __name__ == '__main__': main()
from sqlalchemy import func from flask_appbuilder import Model from flask_appbuilder.models.mixins import AuditMixin, FileColumn, ImageColumn from flask_appbuilder.models.decorators import renders from sqlalchemy import (Column, Integer, String, ForeignKey, Sequence, Float, Text, BigInteger, Dat...
from itertools import chain import string alphabet = { i : str(c) for i,c in enumerate(chain(range(10), string.ascii_uppercase)) } inv_alphabet = { val : key for key, val in alphabet.items() } divmod36 = lambda r: divmod(r, 36) def to_base_36(r): def helper(r): if not r: return q, r = divmod36(r)...
""" The MIT License (MIT) Copyright (c) 2016 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
''' Lab 18: Peaks and Valleys Define the following functions: peaks - Returns the indices of peaks. A peak has a lower number on both the left and the right. valleys - Returns the indices of 'valleys'. A valley is a number with a higher number on both the left and the right. peaks_and_valleys - uses the above two fu...
import numpy as np import cv2 # This function adds 1 to the areas passed in the list of boxes to heatmap. def add_heat(heatmap, bbox_list): # Iterate through list of bboxes for box in bbox_list: # Add += 1 for all pixels inside each bbox heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1 ...
class Locator(): #Login_Page click_Sign = '//*[@id="header"]/div[2]/div/div/nav/div[1]/a' Email_addrees = '//*[@id="email_create"]' Create_an_account = '//*[@id="SubmitCreate"]/span' Mesenger01 = '//div[@id="create_account_error"]//li' # Đăng kí account Ti...
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, Activation, BatchNormalization from keras.models import Sequential def create_model(): model = Sequential() model.add(Conv2D(filters=16, kernel_size=3, input_shape=(150, 150, 3))) model.add(BatchNormalization()) model.add(Activatio...
# Asal sayının kontrol edildiği fonksiyon tanımlama from math import sqrt # * import math def AsalKontrol(n): # Fonksiyona gelen değer asal ise geriye True, değilse False döner. bolen= 2 kok = sqrt(n) # * math.sqrt(n) while bolen <= kok: if n % bolen == 0: # Kalan kontrolü yapılıyor return False # Tam bö...
startTime = [9,8,7,6,5,4,3,2,1] endTime = [10,10,10,10,10,10,10,10,10] queryTime = 5 def busyStudent(startTime, endTime, queryTime): count = 0 for i,j in zip(startTime,endTime): if i<=queryTime and j>= queryTime: count += 1 return count print(busyStudent(startTime,endTime,queryTime))
import numpy as np from sklearn.externals import joblib import time #constants isolated_models_dir='/home/kharesp/learned_models' models_dir='/home/kharesp/learned_models/600_runs' deadline=1000 threshold=100 class StaticPlacement: def __init__(self,max_topics,max_brokers): self.max_topics=max_topics self.m...
from foodAlertsAPI import ( foodAlertsAPI, Alert, Problem, ProductDetails, RelatedMedia, BatchDescription, Allergen, Business, PathogenRisk, ) from datetime import date from backports.datetime_fromisoformat import MonkeyPatch MonkeyPatch.patch_fromisoformat() f = foodAlertsAPI() #...
#!/usr/bin/python3 def safe_print_list(my_list=[], x=0): num = 0 try: for n in range(0, x): print("{}".format(my_list[n]), end='') num += 1 except IndexError: pass finally: print('') return num
''' Created on 2020-04-07 16:21:24 Last modified on 2020-09-30 11:35:23 @author: L. F. Pereira (lfpereira@fe.up.pt) Main goal --------- Show that the square root of a matrix is working properly. Notes ----- -scipy could be used in the scripts, but it does not exist in Abaqus. ''' # imports # third-party import nu...
def extra_long_factorials(in_num): """ Calculate and print the factorial of a given integer. Works well up to in_num = 998, than "RecursionError: maximum recursion depth exceeded in comparison" occurred :param in_num: an integer :return: factorial of in_num """ if n == 1 or n == 0: ...
""" stažení více souborů najednou: import wget soubory = ["https://kodim.cz/czechitas/progr2-python/python-pro-data-1/agregace-a-spojovani/assets/u202.csv", "https://kodim.cz/czechitas/progr2-python/python-pro-data-1/agregace-a-spojovani/assets/u203.csv", "https://kodim.cz/czechitas/progr2-python...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse from alipay.aop.api.domain.AccessReturnQrcodeResult import AccessReturnQrcodeResult class KoubeiSalesKbassetStuffQrcodereturnSyncResponse(AlipayResponse): def __init__(self): super...
import cv2 import numpy as np videoF = cv2.VideoCapture('video_roi.mp4') video = [] if(videoF.isOpened()): ret, frame = videoF.read() video.append(frame) while(videoF.isOpened()): ret, frame = videoF.read() if not ret: break video.append(frame) videoF.release() video = np.array(...
#!/usr/bin/python3 import socket def reciever(ip,port): re_ip=ip re_port=port # fixed with us # creating udp socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # Binding ip and port s.bind((re_ip,re_port)) # code to recieve data data=s.recvfrom(1000) data = data[0] ret...
""" Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, m...
#!/usr/bin/env python ''' Copyright (c) 2020 RIKEN All Rights Reserved See file LICENSE for details. ''' import os,sys,datetime,multiprocessing import os from os.path import abspath,dirname,realpath,join import log,traceback # http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python def which(...
import numpy as np from enum import IntEnum from operator import add from gym_minigrid.roomgrid import RoomGrid, WorldObj, fill_coords, point_in_circle, point_in_rect, COLORS, spaces from gym_minigrid.register import register from gym_minigrid.minigrid import OBJECT_TO_IDX, COLOR_TO_IDX class Reward(WorldObj): ...
from datetime import datetime import numpy as np #for numerical computations like log,exp,sqrt etc import pandas as pd #for reading & storing data, pre-processing import matplotlib.pylab as plt #for visualization #for making sure matplotlib plots are generated in Jupyter notebook itself from stat...
import os import pytest import pandas as pd from shclassify import (load_observations, load_model, DATA_DIR, generate_fake_observations, calculate_prob, choose_class_from_probs) from shclassify.core import MODEL_FILES def test_load_observations_raises_if_bad_path(): ...
import immlib import pefile import os import traceback from collections import namedtuple ExportedEntry = namedtuple("ExportedEntry", ["name", "address"]) class TargetDLL: def __init__(self, dll): self.filename = os.path.basename(dll.lower()) if not self.filename.endswith("dll"): ...
import json SECRETS_FILE = 'secrets.json' # Creating an instance of the Bittrex class with our secrets.json file with open(SECRETS_FILE) as secrets_file: secrets = json.load(secrets_file) secrets_file.close() # Setting up Twilio for SMS alerts account_sid = secrets['twilio_key'] auth_token = secrets['twil...
# Generated by Django 3.1.7 on 2021-05-30 19:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('WebApp', '0006_remove_empdetails_designation'), ] operations = [ migrations.RenameField( model_name='project', old_name='pro...
import timeit def t1(): li = [] for i in range(10000): li.append(i) def t2(): li = [] for i in range(10000): li = li +[i] def t3(): li = [i for i in range(10000)] def t4(): li = list(range(10000)) def t5(): li = [] for i in range(10000): li.insert(0, i) ...
class Solution: def simplifyPath(self, path: str) -> str: stack = [] for portion in path.split('/'): if portion == '..': if stack: stack.pop() elif portion and portion != '.': stack.append(portion) ...
from xml.sax.handler import ContentHandler from dateutil.parser import parse as parse_datetime from cve_search.lib.Toolkit import toStringFormattedCPE class CVEHandler(ContentHandler): def __init__(self): self.cves = [] self.inCVSSElem = 0 self.inSUMMElem = 0 self.inDTElem = 0 ...
from django.contrib import admin from .models import MainMenu, ChildMenu, InterFaceManageClassification,\ InterFaceManageModule, InterFaceSet, InterFaceCase, InterfaceCaseSet, \ InterFaceCaseData,RelevanceCaseSet,ExecutePlan @admin.register(MainMenu) class MainMenuAdmin(admin.ModelAdmin): list_display = (...
import sys, os, subprocess import ROOT from ROOT import TString, TFile, TTree from threading import Thread #dirsToCheck = [f for f in os.listdir(".") if os.path.isdir(f)] dirsIgnored = ["ttZctrl"] dirsToCheck = ["SigRegion","JESUpSigRegion","JESDownSigRegion","ttWctrl","JESUpttWctrl","JESDownttWctrl"] #dirsToCheck...
from itertools import islice, count from math import sqrt #islice allows for lazy slicing #range requires bounds but count doesn't #count() provides an open ended version of range def is_prime(x): if x < 2: return False for i in range(2, int(sqrt(x) + 1)): if x % i == 0: return ...
#!/usr/bin/env python3 from PIL import Image from keras.callbacks import ModelCheckpoint from keras.layers import BatchNormalization, Conv2D, Dense, Dropout, Flatten from keras.models import Sequential from sklearn.model_selection import train_test_split import argparse import glob import numpy as np import os import...
import warnings import requests def raise_connection_error(*args, **kwargs): requests.get('https://jibber.ish', timeout=0.01, *args, **kwargs) def decorate_methods(decorator, *args, **kwargs): def decorate(cls): for attr in cls.__dict__: if callable(getattr(cls, attr)): ...
# -*- coding: utf-8 -*- """ Created on Fri Oct 13 21:12:02 2017 @author: 高多奇 """ import numpy as np import pylab as pl V=4 TIME=0 deta=0.0001 x=[0] y=[0] while TIME<=100: TIME=TIME+deta V=V+400*deta/(70*V)-2*0.33*(0.00001)*V*deta/105-0.5*1.29*0.33*V*V*deta/(70) x.append(TIME) y....
#!/usr/bin/env python import sys # Log format: # - request date, time, and time zone # - request line from the client # - HTTP status code returned to the client # - size (in bytes) of the returned object def sanitize(log): output = [] for i in log.split(): i = i.strip('[').strip('"').strip(']').rstri...
import os import uuid # if you don't override the secret key, one will be chosen for you SECRET_KEY = uuid.uuid4().hex DATABASE_URL = 'postgresql://{db_user}:{db_password}@{db_host}:5432/{db_name}'.format(db_user=os.environ.get('DB_USER'), db_password=os.environ.get('DB_PASSWORD'), ...
def chkprimes(n): c = 0 if n%2 != 0: for i in range(1,n+1): if n%i == 0: c+=1 if c == 2: return(True) def primes(n): l = [2] for i in range(1,(n-1)): a=chkprimes(i) if a == True: l.append(i) return(l) def primepartition(a): n = primes(a) j =...
stopwordslist=['','\'', """can't""", """let's""", """they've""", """he's""", """she's""", """i'm""", """i'd""", """you'd""", """you've""", """i'll""", """i've""", """you're""", """you'll""", """he'll""", """he'd""", """she'd""", """it's""", """we're""", """they're""", """that's""", """it'll""", """we'll""", """they'll"...
import argparse from tgif import ( agent, friday, ) argparser = argparse.ArgumentParser() argparser.add_argument("-l", "--level", type=int, required=True) def main(): args = argparser.parse_args() result = friday.start(args.level, agent.console()) print(result) if __name__ == "__main__": ...
from feature_extraction.feature_abstract import FeatureExtraction import pandas as pd import numpy as np from general.sparray import sparray from scipy.sparse import lil_matrix class Classic(FeatureExtraction): sec_in_day = (60*60*24) sec1 = pd.to_timedelta("1s") def applyParams(self, params): se...
# Generated by Django 2.0 on 2020-05-21 00:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('orders', '0010_capitalinjection'), ] operations = [ migrations.DeleteModel( name='Extrusion', ), migrations.Remove...
# Copyright 2016 MongoDB, 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 or agreed to in writing, so...
from flask import Blueprint, current_app, make_response from flask_restful import Api, Resource from eleanor.utils.api_utils import json_response from eleanor.utils.rate_limits import ratelimit from eleanor.celery import tasks from eleanor.db import db from eleanor.utils.redis import ping, set_key from eleanor.utils.he...
from django.contrib import admin from django.conf.urls import url, include from rest_framework import routers from durgaapi_with_restframework_APP import views from rest_framework_swagger.views import get_swagger_view #from django.urls import path #____________________________________________________________________...
#Plotting functions for Python #Cetin Can Evirgen #13.02.16 #Preamble import numpy as np import matplotlib.pyplot as plt def plot_arr(freqs): N = len(freqs) sz = freqs[0].shape[0] #rets = np.zeros([N,sz]) rets = np.array([freqs[i] for i in np.arange(N)]) return rets #1D line plot def line_...
species( label = 'C#CC([CH2])C[C]=O(26509)', structure = SMILES('C#CC([CH2])C[C]=O'), E0 = (375.139,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1855,455,950,2175,525,750,770,3400,2100,2750,2850,1437.5,1250,1305,750,350,3000,3100,440,815,1455,1000,1380,1390,370,380,2900,435,216.448],'cm...
from math import * import numpy as np class Surface(object): def __init__(self, num_groups): self.current = np.zeros(num_groups) self.DDif = np.zeros(num_groups) self.DTilde = np.zeros(num_groups) self.DHat = np.zeros(num_groups) self.boundary = 'reflective'...
""" Function to teardown the openshift-logging """ import logging from ocs_ci.ocs import constants, ocp from ocs_ci.ocs.resources.pvc import get_all_pvc_objs, delete_pvcs from ocs_ci.ocs.resources.pod import get_all_pods from ocs_ci.ocs.exceptions import UnexpectedBehaviour, CommandFailed from ocs_ci.utility.retry imp...
""" Challenge #2 Write a function that takes an integer 'minutes' and converts it to seconds. Examples: - convert(5) -> 300 - convert(3) -> 180 - convert(2) -> 120 """ def convert(minutes): return minutes * 60 print(convert(5)) #300 print(convert(3)) #180
#web scrape into csv from yahoo for Weekly Projection import os, ssl if (not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None)): ssl._create_default_https_context = ssl._create_unverified_context import requests,csv import pandas as pd from bs4 import BeautifulSoup url_...
''' Copyright (C) 2017-2023 Bryant Moscon - bmoscon@gmail.com Please see the LICENSE file for the terms and conditions associated with this software. ''' import asyncio from cryptofeed.defines import ASK, BID from datetime import datetime as dt, timedelta from decimal import Decimal from cryptofeed.exchanges import D...
import numpy as np from utils.data_utils_kitti import wrap_angle class OdometryBaseline(): def __init__(self, *args, **kwargs): pass def fit(self, *args, **kwargs): pass def predict(self, sess, batch, **kwargs): seq_len = batch['s'].shape[1] prediction = np.zeros_like(b...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 5 14:50:16 2021 @author: charlescollins """ import csv import re with open('street_suffix_abbreviations.csv', mode='r') as abbr_file: reader = csv.reader(abbr_file) all_street_suffixes = {rows[0]:rows[1] for rows in reader} with open('...