text
stringlengths
38
1.54M
from functions import toString from models import * def printMenu(): print("Menu:") print("1.Add a new expense into the list") print("2.Insert a new expense into the list") print("3.Remove all the expenses for a day") print("4.Remove all the expenses between two days") print("5.Remove all the e...
import numpy as np input_data = open('input.txt') input_config = [] for line in input_data: input_config.append(line) # input_config = [ # '.#.#.#', # '...##.', # '#....#', # '..#...', # '#.#..#', # '####..', # ] input_as_array = np.zeros((100, 100)) # input_as_array = np.zeros((6, 6)) #...
# Generated by Django 3.0.2 on 2020-02-16 06:52 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='admin', fields=[ ('admin_id', models.AutoFi...
# -*- coding: utf-8 -*- from urllib import request import tempfile import uuid from datetime import datetime from google.cloud import datastore from google.cloud import storage PROJECT_ID = "persian-172808" DATA_STORE_KEY_PATH = "/home/vagrant/.json_keys/persian-3a9988725cae.json" STORAGE_STORE_KEY_PATH = "/...
biner = input() while len(biner)%3!=0 : biner = "0"+biner hls = "" for i in range(0,len(biner),3): if biner[i:i+3] == "000" : hls+="0" elif biner[i:i+3] == "001" : hls+="1" elif biner[i:i+3] == "010" : hls+="2" elif biner[i:i+3] == "011" : hls+="3" elif biner[i:i+...
""" Module with logic to handle different types of payloads in Slack """ import abc import logging from slackviews import View from werkzeug.datastructures import ImmutableDict # -- helper def get_obj_attr(object, item, missing_value=None, join_with=None, transform=None): """ Returns the value of an object's...
class movies: def __init__(self,moviename,runtime,Genres,lang): self.moviename=moviename self.runtime=runtime self.Genres=Genres self.lang=lang def famous(self): if self.lang=='Telugu': print "Ultimate BlockBuster" else: print "Marvel...
from django.db import models from django.contrib import admin from django.utils.translation import ugettext_lazy as _ # Create your models here. class Order(models.Model): user = models.ForeignKey('base_user.MyUser', related_name='user_orders', on_delete=models.CASCADE, null=True, bla...
from flask.ext.sqlalchemy import get_debug_queries from app.core.logging import Logging from app.core.ansible import Ansi from app.modules.domains.models import Domains, DomainDetails, DomainSSLDetails from app.core.common import ModuleController from passlib.hash import sha512_crypt from sqlalchemy import func, distin...
from model.group import Group import random import string from builtins import * def random_string(prefix, maxlen): symbols=string.ascii_letters+string.digits+string.punctuation+" "*10 return prefix+ "".join([random.choice(symbols) for i in range(random.randrange(maxlen))]) testdata=[Group("", "", ""...
from ballet import Feature import ballet.eng input = "Screen Porch" transformer = ballet.eng.SimpleFunctionTransformer(lambda ser: ser > 0) name = "Has screen porch" feature = Feature(input=input, transformer=transformer, name=name)
#!/usr/bin/env python PACKAGE = "particle_filter_cuda" from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() gen.add("angular_map_offset", double_t, 0, "Angular offset of map - needed "+ "to integrate map with IMU. That value is angle in degrees "+ "between geographica...
""" Implements some common tasks for every type of postgresql relation. """ from ops.framework import Object class PostgresqlRelation(Object): def __init__(self, charm, relation_name, peer_rel): super().__init__(charm, relation_name) self._unit = charm.unit self._charm = charm ...
from django.shortcuts import render from django.http import HttpResponseRedirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.paginator import Paginator from .models import category ,post,tag # Create your views here. def showposts(request): testcat=category.objects.all(...
class Solution(object): def kthSmallest(self, root, k): """ https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/ :type root: TreeNode :type k: int :rtype: int """ if not root: return [] ans, level = [], [root] wh...
from openbabel import OBMol, OBConversion, OBResidueIter import pyplif as pp import operator from IOhandle.models import Protein, Molecule from LLOOMMPPAA.models import PlifMethod,PlifRes,PlifBit,Plif,SynthPoint,PlifBitInstance from django.core.exceptions import ValidationError import os import ast import sys ...
import signal import sys import asab from .service import BSPumpService from .__version__ import __version__, __build__ class BSPumpApplication(asab.Application): """ Application object for BSPump. """ def __init__(self, args=None, web_listen=None): super().__init__(args=args) # Banner print("BitSwan BS...
import threading import time from colorama import Fore count = 0 def increment(lock, delay,color): global count print(color, threading.currentThread().getName(), '\t-> Worker_1 starting') while count < 100: lock.acquire() count += 1 print(color, threading.currentThread().getName(...
#Albion Burrniku #180714100040 #Rrjetat Kompjuterike #Prof:Blerim Rexha #Ass:Haxhi Lajqi import socket import threading import _thread from socket import gethostname import time import random import math import sys import string # IPADRESA def IPADDRESS(IP): return IP[0] # PORTI def PORT(p...
# # MLDB-1030_apply_stopwords.py # mldb.ai inc, 2015 # This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. # import datetime import unittest from mldb import mldb, MldbUnitTest, ResponseException class Mldb1030Test(MldbUnitTest): @classmethod def setUpClass(self): dataset_conf...
from home import app from flask import render_template,request,redirect,url_for,session,flash,jsonify #from mysql import MySQL from flaskext.mysql import MySQL from datetime import datetime import os from flask_mail import Mail,Message mysql = MySQL() mysql.init_app(app) db = mysql.connect() mail = Mail(app) #APP_RO...
from PyQt5 import QtWidgets from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox import sys, os import string import json import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neighbors import KNeighborsClassifier from sklearn.cluster import KMea...
#!/bin/env python #coding:utf-8 import sys import thread reload(sys) sys.setdefaultencoding('utf-8') import mseg class MsegAnalyzer: initialized = False __lock = thread.allocate_lock() def __init__(self,path = '/data0/home/xiulei/workspace/mseg/dict/mseg.conf'): if not MsegAnalyzer.initialized: ...
__author__ = 'tabby' import Responses response = '' while not Responses.is_farewell(response): response = raw_input('Your turn: ') response = response.lower() print Responses.respond(response)
import tensorflow as tf import numpy as np from tensorflow import square, exp, divide, log, scalar_mul, to_float, cast from tensorflow.python import reduce_sum """ Exercise 1.1: Diagonal Gaussian Likelihood Write a function which takes in Tensorflow symbols for the means and log stds of a batch of diagonal Gaussian...
from django.contrib import admin from body.models import * # Register your models here. class ProfileAdmin(admin.ModelAdmin): list_display = ('name', 'phone', 'user','user_type') class TrainerAdmin(admin.ModelAdmin): list_display = ('trainer', 'name', 'phone', 'age', 'gender','experience','skills') class Me...
import cv2,time,pandas as pd import numpy as np from datetime import datetime first_frame= None status_list = [None,None] times=[] df=pd.DataFrame(columns=["Start","End"]) video=cv2.VideoCapture(0) while True: check, frame=video.read() status=0 gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) ...
""" This type stub file was generated by pyright. """ import vtkmodules.vtkCommonCore as __vtkmodules_vtkCommonCore class vtkAbstractPicker(__vtkmodules_vtkCommonCore.vtkObject): """ vtkAbstractPicker - define API for picking subclasses Superclass: vtkObject vtkAbstractPicker is an abstract ...
import pickle from preprocess.utils import create_action_object path_data = "/home/ximenes/Desktop/openpose/data/" print("[INFO] Cretating object list ...") action_list = create_action_object(path_data) print("[INFO] Creating pickle file ...") pik = "database.dat" with open(pik, "wb") as f: pickle.dump(action...
from __future__ import unicode_literals import frappe import json import frappe.utils from frappe.utils import cstr, flt, getdate, comma_and from frappe import _ def item_query(doctype, txt, searchfield, start, page_len, filters): response = [['']] if filters.get('location'): data = frappe.db.sql(''' select item f...
import network import usocket as socket from machine import Pin, Timer, PWM import machine from switch import Switch import time import _thread import math # Setup wlan = network.WLAN(network.STA_IF) status_led = Pin(2, Pin.OUT) led_red = Pin(21, mode=Pin.OUT) led_green = Pin(22, mode=Pin.OUT) led_blue = Pin(23, mod...
# -*- coding: utf-8 -*- ''' My Accounts ''' import sys from urllib.parse import parse_qsl from myaccounts.modules import control control.set_active_monitor() params = {} for param in sys.argv[1:]: param = param.split('=') param_dict = dict([param]) params = dict(params, **param_dict) action = params.get('actio...
""" Streaming twitter API example """ from __future__ import print_function import sys import tweepy from ConfigParser import ConfigParser class TwitterListener(tweepy.StreamListener): """ Twitter stream listener. """ def __init__(self,filename,nooflines): print ('Twitter Listener constructed') supe...
from collections import OrderedDict from dataclasses import dataclass from enum import Enum from typing import Dict import torch from torch.utils.tensorboard import SummaryWriter from distributed import comm class TaskState(Enum): INIT = 1 TRAIN = 2 EVAL = 3 DONE = 4 @dataclass class TaskR...
import time import numpy as np import math def rand_time_gen(): mu, sigma = 12, 3 start_time = np.random.normal(mu, sigma, 1) return start_time print(rand_time_gen())
import datetime logged_in_user = False while True: task = input("\nWelcome to the wackiest notepad ever \nPlease enter : \n# su for signup\n# si for signin\n# wr to add journal\n# r to read journal\n# del to delete jornal\n# stats to get stats\n\n> : ") if task == "su": ############# Sign UP ######...
from django.contrib import admin from planes.models import estadoPersonaPlan, personaPlan, plan # Register your models here. admin.site.register(estadoPersonaPlan) admin.site.register(personaPlan) admin.site.register(plan)
import tools print(tools.PI) print(tools.GRAVITY) print(tools.get_extension("test.txt")) print(tools.highest_number([1,2,698,-5978,654,-65])) # https://docs.python.org/3/py-modindex.html lista de modulos em python ja disponiveis para usar
#!/usr/bin/env python3 from utils import db_connect # make bson ObjectId class available for referencing # bson objects inside a mongo query string from bson.objectid import ObjectId # connect to database db = db_connect() # output some header html print("Content-Type: text/html\n") print("""<!DOCTYPE html> <html...
import torchvision as tv from PIL import Image import requests import numpy as np from configuration import Config config = Config() transform = tv.transforms.Compose([ tv.transforms.Resize((config.test_size, config.test_size)), tv.transforms.ToTensor(), tv.transforms.Normalize([0.485, 0.456, 0.406], ...
#!/usr/bin/env python # # Usage: # ./autocommit.py path ext1,ext2,extn cmd # # Blocks monitoring |path| and its subdirectories for modifications on # files ending with suffix |extk|. Run |cmd| each time a modification # is detected. |cmd| is optional and defaults to git commit all and push. # # Example: # ./autocom...
class StudentOrder: def func(self, n: int, high: str, weight: str) -> str: weight_ary = list(map(int, weight.split(" "))) high_ary = list(map(int, high.split(" "))) dp = [] for i in range(n): dp.append((i + 1, high_ary[i], weight_ary[i])) dp = sorted(dp, key=lambd...
import netCDF4 as nc from netCDF4 import Dataset import numpy as np def load_data(filename): ds = nc.Dataset(filename) return ds def save_data(filename, max_values_ta, ds): ncfile = Dataset('data/max_ta.nc',mode='w',format='NETCDF4_CLASSIC') print(ncfile) lat_dim = ncfile.createDimension('lat...
# Samuel Veloso - Instituto Federal de Alagoas # Estrutura de dados - Prof. Ricardo # Simulação de um atendimento de uma fila. # A cada um segundo um cliente novo chega. # A cada dois clientes chegarem (dois segundos), um cliente é atendido. import collections import time from random import * import string ...
cities = ["New York ", 'Kiev', "new dehli", 'Toronto'] print(cities) print(len(cities)) print(cities[0]) print(cities[:-2]) print(cities[2].upper()) cities[2] = "Tula" print(cities) cities.append('Lvov') print(cities) cities.insert(0, "Turka") print(cities) del cities[1] print(cities) cities.remove("Kiev") print(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class KbAdvertCommissionClauseQuotaResponse(object): def __init__(self): self._quota_amount = None @property def quota_amount(self): return self._quota_amount @quota_amoun...
from PyQt5 import QtWidgets, uic, QtGui import sys import cv2 import numpy as np #1. qt를 사용하여 GUI 프로그램 환경 구축 class Ui(QtWidgets.QDialog): def __init__(self): super(Ui, self).__init__() uic.loadUi('test4.ui', self) self.loadBtn = self.findChild(QtWidgets.QPushButton, 'loadBtn') sel...
from flask import render_template, request, redirect, url_for, session, abort from sqlalchemy import or_ from app import app, db from app.models.students import Student from app.models.needs import Need from app.models.speakers import Speaker @app.route('/student/need/<int:id>') def get_need_page_student(id): ...
from WebLogAnalysis.logAnalysis import TotalPUv from WebLogAnalysis.logAnalysis import TotalTopIp from WebLogAnalysis.logAnalysis import TotalCode import requests import json import pymysql import time def intoMysql(host,user,password,db,allpath): date = time.strftime('%Y%m%d%H%M%S') client = pymysql.connect(h...
import View.CloudStorgeView import View.DomainView import View.Platform import View.WeixingDelegate def config(app, api): View.CloudStorgeView.route_config(app, api) View.DomainView.route_config(app, api) View.Platform.route_config(app,api) View.WeixingDelegate.route_config(app, api)
from xicam.gui.widgets.imageviewmixins import XArrayView, DepthPlot, BetterTicks, BetterLayout, BetterPlots class CatalogViewerBlend(BetterPlots, BetterLayout, DepthPlot, XArrayView): def __init__(self, *args, **kwargs): # CatalogViewerBlend inherits methods from XArrayView and CatalogView # super...
from .. import effects from .. import colors from ..skills import Skill from .hero import Hero import random class Skill1(Skill): name = "Магическое восстановление" description = "Некромант восстанавливает себе HP на величину, равную его магии (magic). После этого он увеличивает свой показатель магии на 1." ...
# 35. Write a Python program to iterate over dictionaries using for loops. def dict_loop(data): dict = {data[i]: data[i + 1] for i in range(0, len(data), 2)} for key, value in dict.items(): print(key, 'corresponds to ', dict[key]) newsDictData = input("Enter a list elements separated by space: ") user...
# Generated by Django 3.2.6 on 2021-08-26 12:53 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('book', '0001_initial'), ] operations = [ migrations.CreateModel( name='CartCoupon', ...
from corefunctions import core import pandas as pd def get_company_list(): df_company_list = pd.read_csv("./sg_company_list.csv") return df_company_list def sg_research_analysis(): filename= "/home/kasun/Documents/mvp/data/sginvestors.csv" df = core.getData_fromcsv(filename) #all research analysis on ...
# -*- coding: utf-8 -*- #Given an array of size n, find the majority element. #The majority element is the element that appears more than ⌊ n/2 ⌋ times. #You may assume that the array is non-empty and the majority element always exist in the array. class Solution: # @param {integer[]} nums # @return {integer...
#! /usr/bin/env python #Calculation of dynamic IR spectra import h5py import numpy as np import matplotlib.pyplot as pt from molmod.units import * from molmod.constants import * from yaff import * from molmod.periodic import periodic from yaff.pes.ext import Cell f1 = np.genfromtxt('../dipole/E0/dipole.txt') data = ...
import json import os import re from datetime import datetime, timedelta from statistics import mean import requests import mskai.globals as globals from mskai.DxLogging import print_debug from mskai.veconfig import loadveconfig import subprocess class virtualization(): def __init__(self, config, **kwargs): ...
stooges = [ "curly","larry","moe",] bankbal = [ 200,300,150,] for indx in range (len(bankbal)): print(stooges[indx],bankbal[indx]) print("---------------------------------------------") stooges = stooges + ["shemp","curly jo"] bankbal = bankbal + [400,1159] print(stooges,bankbal) ## ##p...
# Generated by Django 2.2.5 on 2019-11-05 12:50 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('VCS', '0002_thongtin'), ] operations = [ migrations.AddField( model_name='teach', name='File', field=mod...
"""Bitccoin ticker module for ppbot. @package ppbot Displays the current bitcoin pricing from mtgox @syntax btc """ import requests import string import json from xml.dom.minidom import parseString from modules import * class Bitcoin(Module): def __init__(self, *args, **kwargs): """Constructor""" ...
from cmath import exp import pytest from puzzles.ransom_note import can_construct @pytest.mark.parametrize( "random_note, magazine, expected", [ ("a", "b", False), ("aa", "ab", False), ("aa", "aab", True), ], ) def test_can_construct(random_note, magazine, expected): assert c...
# BubbleSort Using Recurssion def solution(array): def BubbleSort(i, j, array): if len(array) == 1: return array if array[j] > array[j + 1]: array[j], array[j+1] = array[j+1], array[j] if j < len(array) - 2: j += 1 BubbleSort(i, j, arr...
from django.test import TestCase from django.utils import timezone from django.contrib.auth import get_user_model from .forms import CookieForm from .models import Cookie # Create your tests here. class CookieFormTest(TestCase): def setUp(self): user = get_user_model().objects.create_user('beezlebub') ...
import math global a, b def check(a, b): print("Euclidean distance from the points a and b to the origin (0, 0)") print(math.sqrt(a * a + b * b)) check(7, 5) check(2, 4) check(4, 5) check(3, 2)
import sys import os from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras import optimizers from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Dropout, Flatten, Dense, Activation from tensorflow.python.keras.layers import C...
# --------------------------- IMPORTS --------------------------- # import mail_machine import excel_machine import word_machine import corresponding_date from prettytable import PrettyTable # --------------------------- CONSTANT VARIABLES --------------------------- # # Word: WORD_TEMPLATE = r"C:\Users\Frederico...
import os import random from datetime import datetime import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F def fix_seed(seed: int) -> None: torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.d...
''' Created on Feb 23, 2013 @author: nino ''' import unittest from marx import __version__ from distutils.version import StrictVersion class Test(unittest.TestCase): def test_version(self): assert StrictVersion(__version__) > StrictVersion('0.0.0')
from opentera.forms.TeraForm import * from flask_babel import gettext from opentera.db.models.TeraSessionType import TeraSessionType class TeraSessionTypeConfigForm: @staticmethod def get_session_type_config_form(session_type: TeraSessionType): # Handle session type configs for non-services session t...
import os import pickle import argparse import numpy as np from tqdm import tqdm # Configs cifar10_dict = { 'list': ['data_batch_1', 'data_batch_2', 'data_batch_3', 'data_batch_4', 'data_batch_5'], 'sizes': [4, 25, 100, 400], # per-class 'num_classes': 10, 'val_size': 20 # per-class } def extract(...
#!/usr/bin/python #coding=utf-8 import threading from Queue import Queue class ThreadUrl(threading.Thread): ''' 封装多线程库,用来多线程跑啊 ''' def __init__(self,queue,site): threading.Thread.__init__(self) self.queue = queue self.site = site #传递的是一个class的实例或者引用 def run(self): while True: ...
# Copyright 2018 Deep Topology All Rights Reserved. # # 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 o...
# The implementation is based on ULFD, available at # https://github.com/Linzaer/Ultra-Light-Fast-Generic-Face-Detector-1MB from ..transforms import Compose, Resize, SubtractMeans, ToTensor class PredictionTransform: def __init__(self, size, mean=0.0, std=1.0): self.transform = Compose([ Resi...
import numpy as np import commp as cp import itertools import subprocess as sp from scipy.cluster.hierarchy import linkage, fcluster from scipy.spatial.distance import squareform # cmd call tmalign (tmscore.sh) # input two gene names (in string) def _tmscore(param): return sp.Popen(['tmscore.sh', para...
from django.contrib import admin from django.contrib.admin import ModelAdmin from django.contrib.auth.models import User from django.db import models from django.views.generic import TemplateView from whwn.models import ItemCategory, Item, UserProfile, Message from adminplus import AdminSitePlus class ItemAdmin(admi...
import click import time import gym import os import numpy as np import gym_goal from agents.qpamdp import QPAMDPAgent from agents.sarsa_lambda import SarsaLambdaAgent from common.wrappers import ScaledStateWrapper, QPAMDPScaledParameterisedActionWrapper from gym_goal.envs.config import GOAL_WIDTH, PITCH_WIDTH, PITCH_L...
# Generated by Django 3.1.6 on 2021-02-14 15:28 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resume', '0003_post_date'), ] operations = [ migrations.CreateModel( name='Form', fields=[ ('id', mo...
from __future__ import with_statement, division import subprocess, sys from memoize import memoize GOOD = True BAD = False INVALID = None # http://python3porting.com/problems.html if sys.version_info < (3,): def b(x): return x def s(x): return x else: def b(x): return x.encode() ...
# Sort a linked list in O(n log n) time using constant space complexity. # Merge sort # https://www.geeksforgeeks.org/merge-sort-for-linked-list/ class Node(object): def __init__(self, data): self.data = data self.next = None def sort(head): if not head or not head.next: return fi...
#!/usr/bin/python3 # Data reading, cleaning, and processing import pandas as pd import csv import os import re # Database access import sqlite3 # Get file path cwd = os.getcwd() file_path = cwd + r'/data/stem_center_sign_in' # Takes in the name of a file, and returns the pandas dataframe containing that file's dat...
from django.dispatch import receiver from django.db.models.signals import post_save from lawyer.models import UserPermission, Role, ContentType from django.contrib.auth.models import Permission, Group @receiver(post_save, sender=UserPermission) def auto_create_Permission(sender, instance, created, **kwargs): if cr...
_no_value = object() def spam(a, b=_no_value): if b is _no_value: print('No b value supplied') return b spam(1) # No b value supplied spam(1, 2) spam(1, None) # 默认值是变量的话,只生效一次 x = 42 def spam(a,b=x): print(a, b) spam(1) # 1 42 x = 43 spam(1) # 1 42 # 默认值只传None, True,False, numbers, string这些,不要...
"""block chain and smart contract helpers""" import logging import time from binascii import hexlify, unhexlify import eth_utils import eth_abi from web3 import Web3 import queue from concurrent.futures import ThreadPoolExecutor # const CHAIN_FUNC_CALL_TIMEOUT_IN_S = 120 CHAIN_EVENT_GET_FAILED_WAIT_TIME_IN_S = 5 CHAI...
#!/usr/bin/python3 import time import sys import os import random import numpy as np from execute.sequentialEvaluation import sequentialEvaluation #function from execute.generateBatches import generateBatches #function from execute.generateBehaviour import generateBehaviour #function from execute.startHttpServer imp...
import itertools import struct from binascii import unhexlify from codecs import getincrementaldecoder from typing import Dict, Optional, Tuple, Union import pytest from wsproto import extensions as wpext, frame_protocol as fp class TestBuffer: def test_consume_at_most_zero_bytes(self) -> None: buf = fp...
import codecs import csv import numpy as np import pandas as pd import xlrd from numpy.random import choice class Data(): def __init__(self): pass '''数组写入excel表''' def excelWriter(A, headers): data = pd.DataFrame(columns=headers, data=A) writer = pd.ExcelWriter('b.xlsx') # 写入Ex...
#!/usr/bin/env python import ROOT import math from functools import partial import CombineHarvester.CombineTools.plotting as plot import json import argparse import os.path import os import sys ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.gROOT.SetBatch(ROOT.kTRUE) plot.ModTDRStyle(width=700, l=0.13) ROOT.gSty...
import unittest import file_under_test class TestIt(unittest.TestCase): def test_something(self): assert file_under_test.is_leap_year(2000) == True if __name__ == '__main__': unittest.main()
# Generated by Django 2.0.1 on 2019-02-26 03:12 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('autoTest', '0030_auto_20190226_0858'), ] operations = [ migrations.DeleteModel( name='Encryption', ), migrations...
import sys import numpy as np import cv2 import pymysql import time import serial # ser = serial.Serial('/dev/ttyACM0', 115200) model = './data/res10_300x300_ssd_iter_140000_fp16.caffemodel' config = './data/deploy.prototxt' eye_cascade = cv2.CascadeClassifier('./data/haarcascade_eye.xml') eye_cascade...
""" Author: Isaac Lance, Weigang An Date: 03/11/19 CIS422 GoalTracker """ #Standard imports: pytest and the file to be tested import pytest from Goal import Goal, SubGoal from datetime import datetime as dt, timedelta from GErrors import FlagError from Model import Model from AnalysisGenera...
import spacy import pandas as pd import numpy as np from spacy.lang.en import English import nltk from nltk.stem.wordnet import WordNetLemmatizer import random spacy.load("en_core_web_sm") #clean our texts and return a list of tokens parser = English() def tokenize(text): lda_tokens = [] ...
import numpy as np import matplotlib.pyplot as plt class System: def __init__(self): self.state = np.array([[0], [0]], dtype="float") # (pos, vel)T self.acc = [0] self.dt = 0.01 self.A = np.array([[1, self.dt], [0, 1]], dtype="float") self.B = np.array([[0], [self.dt]], dt...
import datetime from datetime import timedelta from django.db import models from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from django.conf import settings from django.core.mail...
#Algoritmo que imprima los 15 primeros números impares negativos (iniciando en -1) #Para variar un poco vamos a declarar un inicio y final para poder utilizar la función for mediante declarando los valores de x , muy parecido al primer ejercicio x = [-1,-3,-5,-7,-9,-11,-13,-15,-17,-19,-21,-23,-25,-27,-29] for x in x: ...
from math import floor from random import randint, random def optimize(regionDemands, numServicesRunning, debug=True): """ Function optimize, :param regionDemands: [demand1, demand2, demand3, ...] :param numServicesRunning: 0 < numServices < 1000 :return newState: [region1Running, region2Running, ....
#!/usr/bin/env python # Import required modules from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str import os import argparse import subprocess import ICA_AROMA_functions as aromafunc import shutil # Change to script directory cwd = os....
_base_ = '../htc/htc_x101_64x4d_fpn_16x1_20e_coco.py' # learning policy lr_config = dict(step=[24, 27]) runner = dict(type='EpochBasedRunner', max_epochs=28)
# coding: utf-8 # In[1]: import xml.etree.cElementTree as ET import pprint import re from collections import defaultdict import csv import codecs import cerberus import sqlite3 import schema # In[20]: #!/usr/bin/env python #Section 1: Get partial records from original xml file OSM_FILE = "shanghai_china.osm" ...