text
stringlengths
38
1.54M
import time from messages import Message class Command(object): def __init__(self, message=None): self._message = message @property def message(self) -> Message: return self._message @message.setter def message(self, message: Message): self._message = message class Bar...
from os.path import join import numpy as np def write_normalized_spectra(shard_dict, normed_bstar_path): norm_fs = {} for order, shard in shard_dict.items(): for fname, spectrum in shard.spectra.items(): if fname not in norm_fs: norm_fs[fname] = {} norm_fs[fname]["{}.lin_x".for...
"""Print the following pattern Pattern for N = 4 1 23 345 4567 """ n= int(input()) for i in range(1,n+1): temp=i for j in range(1, n-i+1): print(" ",end="") for k in range(n-i, n): print(temp,end="") temp=temp+1 print()
#encoding=utf-8 import requests from bs4 import BeautifulSoup import os from random import choice from time import sleep url = "http://www.zhuoku.com/" header_list = [ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36", "Mozilla/5.0 (Windows; U; Win...
#!/usr/bin/python from job import * from tool import * m = Job(300, 300, 5) t1 = Tool(TYPE_DRILL) t1.setDiameter(6) m.drill(200, 200, 5, t1) m.export("demo.scad") m.export("demo.svg") #m.export("demo.dxf") #m.export("demo.vcarve") #m.export("demo.nc")
import pandas as pd import numpy as np import networkx as nx import pickle dataset_edges = pd.read_csv('enrondatasetfinal.csv') dataset_nodes = pd.read_csv('Enron.true', sep = ';') node_from = dataset_edges.iloc[:,0].values node_to = dataset_edges.iloc[:,1].values num_nodes = len(dataset_nodes) print num_nodes # C...
import os import pickle from pathlib import Path from typing import Sequence, Union import numpy as np import skimage.io as io from skimage.util import img_as_float from constants import * ToImgArray = Union[os.PathLike, np.ndarray] ZeroOneFloatArray = np.ndarray UbyteArray = np.ndarray ToPoints = Union[os.PathLike...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-26 18:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( ...
import aiohttp.web import asyncio import json import re import typing import uuid from . import multi_queue class Task: def __init__(self, type: str, result_future: asyncio.Future, payload): self.type = type self.result_future = result_future self.payload = payload self.task_id: ty...
from tasks import add from celery import group r = group(add.s(i, i) for i in range(1000000)).apply_async() print(r.get())
# -*- coding: utf-8 -*- """ Created on Sun Jul 30 19:42:55 2017 @author: qxd """ import tensorflow as tf import data_preparation import model_generation import numpy as np N_CLASSES = 2 IM_W = 256 IM_H = 256 BATCH_SIZE = 50 CAPACITY = 10000 def evaluation(): cat_dir = 'D:\\machine_learning_py...
import datetime import unittest from twisted.python.threadable import registerAsIOThread import mock import sys from mock import Mock from dispersy.candidate import LoopbackCandidate from dispersy.dispersy import Dispersy from dispersy.endpoint import ManualEnpoint from dispersy.member import DummyMember, Member from...
# -*- coding=utf-8 -*- import re import random import string import ConfigParser def load_cfg(): return cfg = ConfigParser.ConfigParser() cfg.read(r"D:\PycharmProjects\Hellow\venv\cfg.ini") # 加载ini配置文件 def get_option(key): if cfg.has_option('cfg1',key): return cfg.get('cfg1',key) Img_path = get_...
# -*- coding: utf-8 -*- from twisted.protocols import basic from twisted.internet import protocol, reactor from binascii import unhexlify import psycopg2 from socket import inet_aton from struct import pack import crc16 # bit mask to check if memory in smartbox is empty f_key_empty_memory = 128 # bit mask - smartbox s...
from flask import Flask from marshmallow import Schema, fields, pre_load, validate from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy ma = Marshmallow() db = SQLAlchemy()
from EPICS_serial_CA import Serial port = Serial("14IDB:serial3") # loop back connector string = "SET:TEMP 4.000\n" port.query(string) # generates reply 'SET:TEMP 4.000\nUT' from CA import caput encoded_string = repr(string)[1:-1] ##caput("14IDB:serial3.AOUT",encoded_string,wait=True) caput('14IDB:serial3.AOUT','SET:...
def prime(n): cont = 0 for c in range(1, n+1): if n % c == 0: cont += 1 if cont == 2: return f'{n} is prime' else: return f'{n} not prime' print(prime(6))
import matplotlib.pyplot as plt from libpysal.weights.contiguity import Queen import libpysal as lp from libpysal import examples import geopandas as gpd import numpy as np from nose.tools import assert_raises, assert_warns from esda.moran import (Moran_Local, Moran, Moran_BV, Moran_Local_BV, M...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import signal from PyQt5.QtWidgets import QApplication from .gui.MainWindow import MainWindow from .storage.Storage import Storage from .shared import get_storage TMP_STORAGE = "/home/nia/Development/_Python/_DCat/ExportA/gz" class AppQT(object): def __init__...
#!/usr/bin/python import socket import sys if len(sys.argv) != 4: print("Usage: %s server_ip server_port prediction_file" % (sys.argv[0])) # MUST BE A VALID IP AND VALID PORT exit(1) CHUNK_SIZE = 8 * 1024 SERVER_IP = sys.argv[1] # "10.10.55.100" SERVER_PORT = int(sys.argv[2]) # 1337 sock = socket...
from distutils.core import setup, Extension x12_hash_module = Extension('x12_hash', sources = ['x12module.c', 'x12.c', 'sha3/blake.c', 'sha3/bmw.c', 'sha3/groestl.c', 'sha3/jh.c', 'sha3/...
# Auto generated configuration file # using: # Revision: 1.19 # Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v # with command line options: step3 --conditions auto:phase1_2017_realistic -n 10 --era Run2_2017 --eventcontent RECOSIM,MINIAODSIM,DQM --runUnscheduled -s RAW2DIGI,L1Re...
# การเพิ่มข้อมูลใน list โดยใช้ while list1 = [] i = 0 n = 10 while i < n: x = int(input()) list1.append(x) i=i+1 print(list1) # การเพิ่มข้อมูลใน list โดยใช้ for range lists2 = [] for i in range(0, 10, 1): x = int(input()) lists2.append(x) print(lists2)
from qiniu import QiniuMacAuth, http import requests, time # 密钥队初始化 access_key = 'your_AK' secret_key = 'your_SK' q = QiniuMacAuth(access_key, secret_key) url = 'http://ai.qiniuapi.com/v3/video/censor' # 请求url data = {"data": {"uri": "http://cdn.vcore.hk/1528336770927592712019-02-181550474493.mp4"}, "params": {"sc...
Low = 1 Normal = 2 High = 3 Magic = 4 PartOfSet = 5 Rare = 6 Unique = 7 Crafted = 8 byName = { "ERR_QUALITY": 0, "Low": 1, "Normal": 2, "High": 3, "Magic": 4, "PartOfSet": 5, "Rare": 6, "Unique": 7, "Crafted": 8, } byId = map(lambda t:t[0], sorted(byName.items(), key=lambda t:t[1]))
# Richard Xie 915505564 # Kneser-Ney Smoothing import math, collections def bigram(sentence, i): word1 = sentence[i].word word2 = sentence[i+1].word return '%s %s' % (word1, word2) discount = 1 class CustomModel: def __init__(self, corpus): """Initial custom language model and structures needed by this...
def stringToList(s): l = [] for e in s: if e == '+': l.append(True) elif e == '-': l.append(False) return l def removePlusAtTheEnd(l): while len(l) > 0 and l[-1] == True: l = l[:len(l)-1] return l def reverseCookies(l,iFinal): lbis = [] for i in range(len(l)): if i <= iFinal: ...
class Solution(object): def grayCode(self, n): """ :type n: int :rtype: List[int] """ size = 0 res = [0] while len(res)>size: size += 1 for i in range(0, n): ans = res[-1] ^ (1 << i) if ans not in res: ...
# An implementation of a graph in matrix format for CMPT435. __author__ = 'Tim Polizzi' __email__ = 'Timothy.Polizzi1@marist.edu' class GraphMatrix(object): def __init__(self): self.inner_list = [] self.filled = False def add_vertex(self, vertex_num: int): """ Adds a new vertex to t...
# Copyright (c) 2019 Western Digital Corporation or its affiliates. import logging import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm from mmcv.runner import load_checkpoint from mmcv.cnn import constant_init, kaiming_init from mmdet.models.utils import YoloConvLayer from ..registry import BACK...
from flask import Flask, render_template, redirect from flask_restful import Api from modules.search_store_resource import SearchStoreResource import os from modules.send_message_resource import SendMessageResource from modules.config_generator import config_generator app = Flask(__name__) api = Api(app) api.add_resou...
# app.py import os from flask_script import Manager from flask_migrate import Migrate, MigrateCommand from app import create_app, db #config_name = os.getenv('FLASK_CONFIG') config_name = "development" app = create_app(config_name) manager = Manager(app) migrate = Migrate(app, db) manager.add_comm...
# Name: globals.py # Purpose: XRC editor, global variables # Author: Roman Rolinsky <rolinsky@mema.ucl.ac.be> # Created: 02.12.2002 # RCS-ID: $Id: globals.py,v 1.31 2007/03/08 15:49:34 ROL Exp $ import wx # Global constants progname = 'XRCed' version = '0.1.8-4-admin4' # Minimal wxWidge...
""" Description ----------- Implements query and status report functionality for C1 use cases. :Authors: - Johannes Schlatow """ import logging from mcc.framework import * from mcc.model import SimplePlatformModel from mcc import parser as cfgparser from mcc import lib from mcc.configurator import GenodeConfigu...
# 110. Balanced Binary Tree class Solution(object): def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True left = self.MaxHeight(root.left) right = self.MaxHeight(root.right) return abs(left - right) < 2 and self...
#!/usr/bin/env python #encoding:utf-8 import os import signal from pwn import * __all__ = [ 'factor', 'gcd', 'ext_euclid', 'SET_PAD_CHAR', 'NOPS', 'LEFT_PAD', 'RIGHT_PAD', 'debug' ] ############################# ### utils for calculation ### ############################# def factor(n): """分解质因数""" while (...
import base64 import random import time import string import urllib.parse import json def get_payload(signupURL): UBASessionID = generate_uba_sessionID() pageID = random.randint(1000000000000000, 9999999999999999) events = get_events(signupURL, pageID, UBASessionID) return { "eventSource":"we...
# -*- coding: utf-8 -*- import json import requests from django.core.management.base import BaseCommand from products.models import Store, Product from .url_settings import TOP_URL class Command(BaseCommand): def handle(self, *args, **options): """ scrapes and stores product availability "...
n=int(input("enter the number of rows")) k=ord("A") for i in range(n): for j in range(n-i-1): print(" ",end=" ") for j in range(i+1): print(chr(k),end=" ") print()
from cffi import FFI import numpy as np import pdb ffi = FFI() keepalive = [] def zero_cffiarray(nz): tab_np = np.zeros((nz)) keepalive.append(tab_np) tab = ffi.cast("double*", tab_np.__array_interface__['data'][0]) return tab def morrison_2momNc_simplewarm(nx, ny, nz, qc_np, qr_np, nc_np, nr_n...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings from django.apps import apps from django.utils.translation import ugettext as _ from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from ord...
import heapq import sys #Read given from file filer = sys.argv[1] fp = open(filer, "r") #Determine the dimensions of the given lines = fp.read().splitlines() checkdim = lines[0].split(" ") truedim = len(checkdim) #Determine which heuristic to use def chooseH(chooser, curr, goal, glist, zind): h = 0 if choose...
from pylab import * figure() title("Graded inhibitory synapse: granule-|mitral") # adjust activation curve so that all the dynamics happens between -52 and -28mV. act = [0.0] # at -52mV act.extend( [1/(1+math.exp(-(vm + 40.5e-3)/1.0e-3)) for vm in arange(-50e-3,-30.00001e-3,2e-3)] ) act.extend([1.0]) # for -28mV plot(...
""" ============================ Author:柠檬班-木森 Time:2020/2/25 21:54 E-mail:3247119728@qq.com Company:湖南零檬信息技术有限公司 ============================ """ """ linux命令 os模块中的方法 pwd: os.getcwd() cd os.chdir() ls os.listdir() mkdir ...
import os from pathlib import Path from imblearn.over_sampling import SMOTE from sklearn.linear_model import SGDClassifier from sklearn.model_selection import KFold, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC from tqdm import tqdm import numpy as np from config impor...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- """MSTICPy...
#!/usr/bin/env python2 from __future__ import print_function import enum import math import rospy import threading import tf from geometry_msgs.msg import Twist, Vector3 from sensor_msgs.msg import Imu from std_msgs.msg import UInt8, Empty class Pose(enum.Enum): REST = 0 FIST = 1 WAVE_IN = 2 WAVE_OUT...
import os SECRET_KEY=os.getenv('SK') SQLALCHEMY_DATABASE_URI="postgresql://postgres:@localhost:5432/postgres" SQLALCHEMY_TRACK_MODIFICATIONS=False DEBUG_TB_TEMPLATE_EDITOR_ENABLED=False DEBUG_TB_INTERCEPT_REDIRECTS=False FLASK_ADMIN_SWATCH='yeti'
#coding=utf-8 #author=godpgf from ctypes import * from pyalphatree.libalphatree import alphatree import numpy as np class AlphaPic(object): def __init__(self, sign_name, feature_list, daybefore, sample_size): features_cache = self.decode_features(feature_list) self.picid = alphatree.useAlphaPic(c_...
#!/usr/bin/env python3 import sys from PySide import QtGui, QtCore import os from os import path import logging #class ImageViewer(QtGui.QWidget): class ImageViewer(QtGui.QMainWindow): def __init__(self): super(ImageViewer, self).__init__() self.initUI() def initUI(self): self.is_image...
class Solution: def minCostToMoveChips(self, position: List[int]) -> int: total_odd_value = total_even_value = 0 for index in position: if index % 2 == 1: total_odd_value += 1 else: total_even_value += 1 if total_even_value < total_o...
# coding=utf-8 import numpy as np from scipy import stats from scipy import special from scipy.stats import chi2 class Statistic: """ Класс для нахождения всяких статистических величин. """ def __init__(self, ): self.data = [] self.n = 0 def load_data(self, file): ""...
import string letters = list(string.ascii_uppercase) print letters with open('in.txt') as f: lines = f.readlines() lines = [l.split('\n')[0] for l in lines] t = int(lines[0]) def find_plan(np): ans = [] n = len(np) paties = letters[:n] d = dict(zip(paties, np)) while d: pd = {} ...
# Python3 program to find minimum number # of swaps required to sort an array # Function returns the minimum # number of swaps required to sort the array def minSwaps(arr): n = len(arr) # Create two arrays and use # as pairs where first array # is element and second array # i...
#!/usr/bin/python from opyscad import * import bearing, screw, config import math, copy l = 30.0 t = 4.0 belt_gap = 2 w = bearing.D1 + t * 2 + belt_gap * 2.0 dx = bearing.D1 / 2 lip_t = 1.5 lip_d = bearing.d + 4.0 bearing_gap = 0.0 cap_gap = 0.2 h = t + bearing.B + lip_t + bearing_gap bearing_nut = screw.m3 bearing_...
from graphics import * from random import randint class Pig: '''a movable pig''' def __init__(self,win): self.circ = Circle(Point(0,0),10) self.pcent = self.circ.getCenter() self.cy = self.pcent.getY() self.cx = self.pcent.getX() self.circ.setFill('pink') self.ci...
#!/usr/bin/python # -*- coding:utf-8 -*- #Filename: iterator.py colors = [ 'red', 'green', 'blue', 'yellow' ] for i in range(len(colors)): print (colors[i]) # >>> red # green # blue # yellow for color in colors: print(color)
s = set() s.add(1) s.add(2) s.add(3) s.add(4) s.add(5) print(s) #each elements in a set are unique if: s = set() s.add(1) s.add(2) s.add(3) s.add(3) s.add(5) print(s) #the set will print s = {1, 2, 3, 5}
def Main(): # Having brackets is the python 3.X way print("test") # Loose typing means python figures out the type in run time also means you #don't need to define it as you would in C languages. numOfLoops = askuser() x = 1 #white space is important in python since there is no brackets! (n...
def removeRed(): my_pict = makePicture(pickAFile()) explore(my_pict) for px in getPixels(my_pict): x = getX(px) y = getY(px) # set the boundary for left eye if 100 <= x <= 112 and 168 <= y <= 178: color_red = makeColor(170,75,120) # choose the...
import pandas as pd import itertools import numpy as np # Read the Excel file into a DataFrame df = pd.read_excel('example.xlsx') # Get the column names column_names = df.columns.tolist() # Define the suffixes for permute and spread columns permute_suffix = '_P' spread_suffix = '_S' # Get the column names for permu...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', one_hot = True) def add_layers(inputs, in_size,out_size,activation_function = None): Weights = tf.Variable(tf.random_normal([in_size, out_size])) biases = tf.Variable(tf.zeros([1...
import numpy as np x = np.array([[0, -6], [4, 4], [0, 0], [-5, 2]]) z = np.array([[-5, 2], [0, -6]]) assignment = np.zeros(x.shape[0]) def assign_points(x, z): distances = np.zeros([x.shape[0], z.shape[0]]) for i in np.arange(x.shape[0]): for k in np.arange(z.shape[0]): distances[i, k] = ...
# -*- python -*- load( "@drake//attic:build_macros.bzl", drake_cc_googletest = "attic_drake_cc_googletest", drake_cc_library = "attic_drake_cc_library", ) load("//tools/skylark:test_tags.bzl", "gurobi_test_tags") load("//tools/lint:lint.bzl", "add_lint_tests") drake_cc_library( name = "global_inverse_...
import tax.tax_calculator as txc def test_tax_calcation(): tc = txc.CA_MARRIED assert tc.agi_to_tax(0) == 0 assert tc.agi_to_tax(8472) == 0 # state deduction assert round(tc.agi_to_tax(24000)) == 155 # federal deduction (some state) assert round(tc.agi_to_tax(40000)) == 2060 # low fed rate asse...
import csv import requests import urllib import json import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from stem import Signal from stem.control import Controller # spoof a real browser as jstor et al don't take kindly to bots headers = { 'User-Agent': 'Mozilla/5.0 (X11; ...
from django.shortcuts import render, get_object_or_404,redirect from django.views.generic import ListView, DetailView, View from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Recipe, Ingredient, Like, User from .forms import RecipeForm, NewUserForm, IngredientForm from django...
class Rectangle: def __init__(self,length,width): self.length = length self.width = width def perimeter(self): peri = (self.length + self.width) *2 return peri def area(self): space = self.length * self.width return space class Parallelepipede(Rectangle):...
def main(): bulldog() def bulldog(): print('feed me!') if __name__ == '__main__': main() # __name__ is a special variable that returns the name of the current module ##### def main(): bulldog(3) def bulldog(n): print(f'{n}feed me!') if __name__ == '__main__': main() # FUNCTION ARGUMENTS def...
""" @Time : 2020-07-07 23:11 @Author : QDY @FileName: 166. 分数到小数.py 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。 如果小数部分为循环小数,则将循环的部分括在括号内。 示例 1: 输入: numerator = 1, denominator = 2 输出: "0.5" 示例 2: 输入: numerator = 2, denominator = 1 输出: "2" 示例 3: 输入: numerator...
import unittest from scpidev.value import SCPIValue, SCPIValueList test_vectors = [ { "value_string": "{<resolution>|MINimum|MAX|DEF}", "expected_values_list": [ "<resolution>", ("MIN", "imum", ""), ("MAX", "", ""), ("DEF", "", "") ], "match_test": [ ...
# -*- coding: utf-8 -*- """ Created on Sat Apr 28 17:20:02 2018 @author: mathe """ import pygame,sys,time,random from pygame.locals import * import Jogo def menu(): pygame.init() pygame.mixer.init() fonte=pygame.font.Font("moonhouse.ttf", 40) fonte_titulo=pygame.font.Font("moonhouse.tt...
from tensorboardX import SummaryWriter class Plotter(): def __init__(self, folder): self.writer = SummaryWriter(folder) self.last_written = {} def plot(self, tag, name, x, y): key = tag + '/' + name if key in self.last_written.keys() and x <= self.last_written[key]: ...
#!/usr/bin/env python #-*- coding: utf-8 -*- def my_insert(indeks, eleman): liste = [1, 2, 3, 'a', 'b'] print liste[:indeks] + list(eleman) + liste[indeks:] my_insert(3, "2")
#! /usr/bin/python import socket import math s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) RIFLE_V = 853 PISTOL_V = 350 GRAVITY = -9.81 PI = 3.14159 HOST = 'zombies_8977dda19ee030d0ea35e97ad2439319.2014.shallweplayaga.me' PORT = 20689 s.connect((HOST, PORT)); i = 0; s.recv(1024) s.send('1\n') s.recv(1024) s....
import logging import pymysql from pymongo import MongoClient import pymongo from bson import ObjectId def op_db_query(sql, host, user, password, database): """ 不需要跳板机,连接mysql :param sql: 需要执行的命令 :param host: 机器地址 :param user: sql登陆用户 :param password: sql登陆密码 :param db: 需要连接的数据库 :retur...
import math import time import os from random import shuffle import matplotlib.pyplot as plt import numpy as np import torch import torch.optim as optim import nni import logging import networkx as nx from loggers import EmptyLogger, CSVLogger, PrintLogger, FileLogger, multi_logger from model import GCN, GatNet from pr...
import os import json import re import pickle from maintain_data import Extract_Label as el def load_needed_label(file_path): label_list = [] with open(file_path,'r') as op: for data in op: label_list.append(data.strip('\n')) op.close() return label_list def load_verdict_label...
import requests_cache import typer from typing import Optional from src.scrape.scrape import ( query_website, extract_job_offers, collate_jobs_data, filter_results ) # Set up caching for use with all requests as default requests_cache.install_cache('scraping-cache', backend='sqlite') scrape_app = typer.Typer() ...
""" 共通関数 """ import datetime from logging import Logger, getLogger, StreamHandler, handlers, Formatter, \ INFO import os from .const import LOGGER_DIR, LOG_LEVEL def get_default_logger(initial_talk:bool=False) -> Logger: """ デフォルトロガーを返す Parameters ---------- initial_talk: bool デフォルトロガ...
import json from datetime import datetime from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): balance = models.FloatField(default=0) sale_price = models.FloatField(default=0) def __str__(self): return self.email ...
#!/usr/bin/env python # coding: utf-8 # Author: Chris Harris # Class: BU CS 767 - Machine Learning # # This notebook builds off of Stefan Bergsteins CNN model using Keras. I liked his approach and my goal is to add to it and to compare performance from his CNN to an RNN: https://www.kaggle.com/crayharris/keras-deep-l...
from os import environ, pathsep from pathlib import Path from .utils import Util for path in environ["PATH"].split(pathsep): for util in Path(path).glob("*"): globals()[util.name] = Util(util.name)
from django.views.generic import TemplateView from django.conf import settings class LidarView(TemplateView): template_name = "lidar/potree/data/viewer.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['BUCKET_URL'] = settings.LIDAR_BUCKET ...
import atexit import os import signal from abc import ABCMeta, abstractmethod from os.path import abspath, dirname, join, exists from utils import log class Socket(object): __metaclass__ = ABCMeta DEFAULT_NAME = join(abspath(dirname(__file__)), 'test.socket') EMPTY_MESSAGE = '[empty message]' def __...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Make example datasets. """ from __future__ import absolute_import, division, print_function, unicode_literals import os import numpy as np from astropy.units import Quantity from astropy.time import Time, TimeDelta from astropy.coordinates import SkyCoo...
"""Model classes""" from app.types.User import User from app.types.Role import Role from app.types.Machine import Machine from app.types.Manufacturer import Manufacturer from app.types.Tournament import Tournament from app.types.Division import Division from app.types.Player import Player from app.types.Entry import En...
# -*- coding: utf-8 -*- # setup.py # author : Antoine Passemiers from setuptools import setup setup( name='rmm', version='1.0.0', description='Realistic mouse movements', url='https://github.com/AntoinePassemiers/Realistic-Mouse', author='Antoine Passemiers', author_email='apassemi@ulb.ac.be',...
# This program generates for each userid, 5 nearest neighbors, by using collaborative filterting. In particular, the sparse matrix # of userid/event is generated, then one takes the dot product of this matrix (normalized) with itself. # This program should load csv files generated by RASparse_rowcol_generator.py (ther...
from django.db import models from datetime import datetime # Create your models here. class Modulation(models.Model): modulation_name = models.CharField(max_length=100) def __str__(self): return (self.modulation_name) class Encryption(models.Model): encryption_name = models.CharField(max_length=1...
import unittest from app.models import Pitch,User from app import db class PitchModelTest(unittest.TestCase): def setUp(self): self.user_manow = User(username = 'manow',password = '1234') self.new_pitch = Pitch(name='zee',title='Money',description='moneyreview',user =self.user_manow, category='Fina...
# _*_ coding: utf-8 _*_ __author__ = 'Melon' __date__ = "18/07/09" from flask import Blueprint home = Blueprint("home",__name__) from . import views
''' Logic: A function of filename logic is a key component of whole snippet. Takes input as m, n and a matrix on which logic is to be performed and returns the same matrix after the operation ''' # logic takes m, n and deeeply copied matrix l2 as parameter # operations are performed on l2 def logic(m, n, l2): j = ...
import streamlit as st import pandas as pd import numpy as np import os import joblib from PIL import Image from titanic_req.titanic_model import titanic def titanic_data(sidebar_slots, predict_button): model_titanic = titanic() dtree, svc, name = model_titanic.input(sidebar_slots, predict_button) if pre...
# coding=utf-8 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import scoped_session from sqlalchemy.schema import Index import DBBase from FlightFixInfoModel import FlightFixInfo from CompanyInfoModel import CompanyInfo from CompanyInfoAllModel import CompanyInfoAll f...
# Alex Bello # 2/11/2020 # The list of methods used for the Operation project. def sums(lists): sum = 0 for i in lists: sum += i return sum def product(lists): total = 0 for i in lists: total *= i return total def mean(lists): avg = sums(lists) return avg / len(list...
strhr = input("Input Hours: ") hr = float(strhr) strrate = input("Input Rate: ") rate = float(strrate) if hr<=40 : pay = hr * rate print("Gross pay is :",pay) else : exhr = hr-40 pay = (40 * rate) + (exhr * rate * 1.5) print(pay)
# Generated by Django 2.0 on 2018-01-04 10:14 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tyre', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tyre_without_issue', ...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2007, TUBITAK/UEKAE # # 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 License, or (at your # option) any later...
# Copyright (c) 2016, Xilinx, Inc. # SPDX-License-Identifier: BSD-3-Clause import os import pytest from pynq import PL from pynq import Overlay from pynq import Clocks from pynq.pl import BS_BOOT from pynq.ps import DEFAULT_CLK_MHZ bitfile1 = BS_BOOT bitfile2 = PL.bitfile_name ol1 = Overlay(bitfile1) ol2 = Ov...