text
stringlengths
8
6.05M
# CHALLENGE: https://www.hackerrank.com/challenges/30-2d-arrays def build_arr(): arr = [] for arr_i in range(6): arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] arr.append(arr_t) return arr def is_square_arr(arr): for e in arr: if len(e) != len(arr): ...
"""cryptarchive server""" from twisted.internet import threads from twisted.internet.defer import inlineCallbacks, returnValue from twisted.internet.protocol import Factory from twisted.protocols.basic import IntNStringReceiver from cryptarchive.challenge import Challenge from cryptarchive import constants from crypta...
num = int(input("enter a number: ")) count = 0 while True: if num == 0: break temp = num % 10 num = num//10 flag = 0 if temp == 1: continue else: for j in range(2,(temp//2+1)): if temp % j ==0: flag = 1 if flag == 0: count...
import json import re from django import forms from django.core import validators from gim.core.models import (LabelType, LABELTYPE_EDITMODE, Label, GITHUB_STATUS_CHOICES, Milestone, Repository) from gim.front.mixins.forms import LinkedToRepositoryFormMixin, LinkedToUserFormMixin from gi...
"""CRUD operations.""" from model import db, User, Comment, FavRecycler, connect_to_db import materials def create_user(name, email, password): """Create and return a new user.""" user = User(name=name, email=email, password=password) db.session.add(user) db.session.commit() return user def g...
from string import ascii_letters, digits from random import choice def random_str(str_len=32): base = ascii_letters + digits str = '' for i in range(str_len): str += choice(base) return str
#!/usr/bin/env python import cgi form = cgi.FieldStorage() import sqlite3 db = sqlite3.connect('todo.db') id = form.getvalue('id') sql = "delete from story where id = %s" % id cursor = db.cursor() cursor.execute(sql) db.commit() db.close() print "Content-type: text/html\n" print "<meta http-equiv='refresh' conten...
class Solution: def sumOfLeftLeaves(self, root: TreeNode) -> int: self.x = 0 def traverse(root): if not root: return if root.left and not root.left.left and not root.left.right: self.x += root.left.val traverse(root.left) ...
#apollonean_gasket.py """ ----------------------------------------------------------------------------------------------------- Generates a visualization of a region of the Apollonean Gasket by printing spheres in space in Maya ---------------------------------------------------------------------------------------...
import gen from language import * from macropy.experimental.pattern import macros, _matching, switch, patterns, LiteralMatcher, TupleMatcher, PatternMatchException, NameMatcher, ListMatcher, PatternVarConflict, ClassMatcher, WildcardMatcher from itertools import * def compile2SHA(ha): return gen.preprocess(ha) ...
#coding=utf-8 """ Created on Tue Apr 9 12:33:43 2019 @author: murillon2003_00 """ import utils import operations import bank_account_variables as acc from file import load_bank_data def main(): load_bank_data() print(acc.money_slips) print(acc.accounts_list) utils.header() account_auth = oper...
import pytest from model_objects import Product, SpecialOfferType, ProductUnit from shopping_cart import ShoppingCart from teller import Teller from tests.fake_catalog import FakeCatalog def test_ten_percent_discount(): catalog = FakeCatalog() toothbrush = Product("toothbrush", ProductUnit.EACH) catalog....
## Requires Python v3 and pandas (pip install pandas) ## This script takes the newcastle membership csv and attempts ## to reduce the file size as much as possible through aggregation and lookups ## Two lookup files to provide library names and dates are also created. import csv import os import re from datetime impor...
# coding:utf-8 import abc import iconfig class Command(object): """ 指令基类 """ sub_cmd_list = None def __init__(self, cmd, args): self.cmd = cmd self.args = args @abc.abstractmethod def execute(self): raise Exception(u"指令尚未实现") @staticmethod def real_cmd(c...
from django.conf.urls.defaults import patterns, include, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # u...
import logging import os.path import numpy as np from poap.controller import BasicWorkerThread, ThreadController from pySOT.experimental_design import SymmetricLatinHypercube from pySOT.optimization_problems import Ackley from pySOT.strategy import SRBFStrategy from pySOT.surrogate import CubicKernel, LinearTail, ...
DEAD_VALUE = '.' LIVE_VALUE = '*' class Cell(object): def __init__(self, x, y, value): self.x = x self.y = y self.value = value self.nextValue = None def live(self, nextloop=False): if nextloop: self.nextValue = LIVE_VALUE else: self.val...
""" Contains business logic tasks for this order of the task factory. Each task should be wrapped inside a task closure that accepts a **kargs parameter used for task initialization. """ def make_task_dict(): """ Returns a task dictionary containing all tasks in this module. """ task_dict = {} retu...
import os import cv2 import dlib import numpy as np import matplotlib as mat image = cv2.imread("Test/finger.png") #contrast and brightness to 0.8 and 25 brightness = 25 contrast = 0.8 img = np.int16(image) img = img * (contrast/127+1) - contrast + brightness img = np.clip(img, 0, 255) img = np.uint8(img) #Gray gray...
from Books import Books from Users import Users from UserController import UserController from BookController import BookController from LoanController import LoanController from Loans import Loans from Database import Database print("Welcome to the library\n") database = Database() books = Books(database) users = Us...
'''Кортеж - то же самое, что и список, только в круглых скобках и не может изменяться''' my_tuple = ('param1', 'param2', 'param3', 'param4') # ^ - это кортеж try: my_tuple[1] = 'parametr' print(my_tuple) except: print('Заменять элементы нельзя!') my_tuple = ('new_param1', 'new_param2', 'new_param3', 'new_...
from django.shortcuts import render, redirect, render_to_response from django.http import HttpResponse, JsonResponse from django.template.loader import render_to_string from .models import Rate from .forms import PostRateForm from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from dateutil.r...
from re import findall def main(): # Find a small letter surrounded by 3 capital characters on each sides message = open('3.txt', 'r').read() pattern = '[^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z]' answer = findall(pattern, message) print(answer) if __name__ == '__main__': main()
#!/usr/bin/env python3 import requests import json import logging import argparse import time import sys import datetime def sendTriggerQuery2Server(deviceState = 1): logger = logging.getLogger(__name__) basicTriggerFieldName = "which_light_is_turned_on" payload = { "triggerFields" : { ...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from pathlib import Path from qbstyles import mpl_style DR = Path(__file__).parent def main(): '''Main.''' mpl_style(dark=True) fig = plt.figure() ims = [] for i in range(10): rand = np.random.r...
a = int(input("Please input the first number: ")) b = int(input("Please input the second number: ")) print(a + b) print(a - b) print(a * b) print(a / b) print(a % b) # 檔名: exercise0502.py # 作者: Kaiching Chang # 時間: July, 2014
# -*- coding: utf-8 -*- from ciscoconfparse import CiscoConfParse def check_for_list(obj): if type(obj) == list: return obj[0] return obj config = CiscoConfParse("cisco_ipsec.txt") crypto = check_for_list(config.find_objects("^crypto map CRYPTO")) # Print output print crypto.text for child in crypto....
############################################## # # # # # # # # # # # ...
# -*- coding: utf-8 -*- from collections import Counter class Solution: def countLargestGroup(self, n: int) -> int: groups = Counter() for i in range(1, n + 1): groups[self.sumOfDigits(i)] += 1 return list(groups.values()).count(max(groups.values())) def sumOfDigits(self,...
import datetime import json import ntpath import time import os import math from watchdog.observers import Observer from watchdog.events import (FileModifiedEvent, PatternMatchingEventHandler) observer = Observer() # checks when file is modified class Handler(PatternMatchingEventHandler): def on_modified(self, ev...
'''Tic Tac Toe Game for 2 players or player vs bot''' import random def get_input(cor_h): '''Getting coordinates of the player move with validation if move is allowed. Expected input - 'x,y' in range 1 to 3 (game board is 3x3) Validation checks if: -input is in proper format -input corresponds...
""" Rename 1kpilot gene alignements as family.msa """ import os import sys import shutil def convert(raw_data_dir, output_ali_dir): os.mkdir(output_ali_dir) for f in os.listdir(raw_data_dir): family = f.split(".")[1] src = os.path.join(raw_data_dir, f) dest = os.path.join(output_ali_dir, family + ".ms...
""" Copyright 1999 Illinois Institute of Technology 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, modify, merge, publis...
1.分数出现以下情况怎么处理没有列出来: (一共有R、I、A、S、E、C) (假设R=I>A>S>E>C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R=I=A>S>E>C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R=I=A=S>E>C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R=I=A=S=E>C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R=I=A=S=E=C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R>I>A>S>E>C) 需要显示的结果是什么,以及如何判断得出该结果的 (假设R>I=A=S=E=C) 需要显示的结果是什么,以及如何判断得出该结果的 (假...
#!/usr/bin/env python # This file downloads and sets up all the library dependencies for the game, # including Lua, SFML (Window toolkit), and Box2D (physics engine). import urllib2 import zipfile import os import subprocess import errno import shutil import sys import platform import tarfile msbuild = 'C:\\Windows\\...
from elasticsearch import Elasticsearch, RequestsHttpConnection, serializer, compat, exceptions, helpers from datetime import timedelta, datetime import utils _es_host = '10.200.102.23' _es_index = 'mimic' _doc_type = 'eprdoc' _concept_type = 'ctx_concept' _patient_type = 'patient' _es_instance = None _page_size = 200...
# Import DQoc HTML from lp:ubuntu-ui-toolkit import os import simplejson from django.core.files import File from django.core.files.storage import get_storage_class from ..models import * from . import Importer __all__ = ( 'CordovaImporter', ) SECTIONS = { 'org.apache.cordova.battery-status': 'Device and S...
""" A container for all information about the field: geometry and labels, as well as convenient API. """ from .base import Field
print("LETTER A HAS BEEN SUCCESSFULLY EXECUTED") #
from item_project import * from map_project import rooms inventory = [] #For example: item_id # Start game at the reception current_room = rooms["Reception"] #==================================== # Player status energy_min = 0 #Minimum energyof player energy_max = 100 #Maximum energy of player project_process = 0 ...
web: python ml_backend.py
#!/usr/bin/env python3 # Marcos del Cueto # Import libraries import math import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLocator) import numpy as np # Initialize lists list_x = [] list_y = [] # Generate dataset as 10 points from x=5 to x=6.8, with y=exp(x) for x in np.arange(5, 7, 0.2): y = m...
from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email') class CustomUserChangeForm(UserChangeF...
############################################################################### # Team List retrieval for FIRST Robotics FRC using The Blue Alliance API # ############## # INVOCATION # ############## # The program can be invoked from the command line with two arguments. # The first argument is the year of the event...
from django.db import models from django.contrib.auth.models import User """ class Platos: id Plato str descriprcion class Menu: id menu id plato date fecha class pedido plato seleccionado id pedido id plato seleccionado class pedido customizacion id pedido id customizacion clas...
#!/usr/bin/env python # -*- coding:utf-8 -*- class C1(object): def meth1(self): self.__x = 88 def meth2(self): print(self.__x) class C2(object): def metha(self): self.__x = 99 def methb(self): print(self.__x) class C3(C1, C2): pass a = C3() a.meth1() a.metha...
#!/usr/bin/python3 import os import zipfile import sys import glob import gzip import time from subprocess import call from operator import itemgetter task_name = sys.argv[1] root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) logs_dir = os.path.join(root, "logs") asterixdb = os.path.join(root, "aste...
''' Created on Nov 11, 2016 @author: micro ''' import wpilib class Test_Run (wpilib.IterativeRobot): def robotInit(self): self.motor = wpilib.CANTalon(1) self.motor = wpilib.CANTalon(2) self.motor = wpilib.CANTalon(3) self.motor = wpilib.CANTalon(4) ...
# coding: utf-8 from stiffsquare import nambu_square_coexistence_vers2 as periodize_nambu from stiffsquare import stiffness_square import numpy as np #=========== DEBUT de definition de la self-fictive, juste pour demo, PAS IMPORTANT ====================== beta = 40.0 znvec_tmp = np.array([(2.0*n + 1.0)*np.pi/beta fo...
''' AuthHandler encapsulates the logic to authenticate users on the server-side. ''' import base64 import json import threading import time import urllib import urllib2 from base64 import encodestring from codalab.common import PermissionError class User(object): ''' Defines a registered user with a unique na...
import pygame import time import random pygame.init() list = [0, 0] display_width = 800 display_height = 600 black = (0, 0, 0) white = (255, 255, 255) red = (200, 0, 0) green = (0, 200, 0) bright_red = (255, 0, 0) bright_green = (0, 255, 0) block_color = (53, 115, 255) gameDisplay = pygame.display.set_mode((dis...
from django.db import models from django.contrib.auth.models import User #po文 class Post (models.Model): content = models.TextField('內文') #user撰寫文章 #建立User和Post之間一對多的關係(一個user可以寫多篇文章) creator = models.ForeignKey(User, on_delete=models.PROTECT, ...
import numpy as np import pandas as pd import torch as torch class Preprocess: def __init__(self, max_sequence_length, truncation_side): self.__max_sequence_length = max_sequence_length self.__truncation_side = truncation_side def truncate(self, sequence: np.array) -> np.array: trunc...
pc=rs.pointcloud() pc.map_to(aligned_depth_frame) points = pc.calculate(aligned_depth_frame) pcl_points=pcl.PointCloud() point_to_pcl(pcl_points,points) vox = plc_msg.make_voxel_grid_filter() LEAF_SIZE = 0.01 # Set the voxel (or leaf) size vox.set_leaf_size(LEAF_SIZE, LEAF_SIZE, LEAF_SIZE) downsampled = vox.filter() ...
#julia_set.py """ ----------------------------------------------------------------------------------------- Generates a visualization of the Julia set by printing cubes in space in Maya ----------------------------------------------------------------------------------------- One function named run() Parameters: ...
# -*- coding: utf-8 -*- """Main Controller""" from tg import expose, tmpl_context from outages.lib.base import BaseController from outages.decorators import with_moksha_socket import moksha.utils __all__ = ['RootController'] from moksha.api.widgets.live import LiveWidget from tw2.polymaps import PolyMap from tw2...
''' Created on Jul 11, 2013 @author: christian ''' import os import mne import numpy as np from mne.io import Raw from eelbrain import datasets, plot, testnd from eelbrain.plot._base import Figure from eelbrain.plot._utsnd import _ax_bfly_epoch def test_plot_butterfly(): "Test plot.Butterfly" ds = datasets...
import numpy as np import matplotlib.pyplot as plt import csv import statistics index_collumn = [] speed1_collumn = [] speed2_collumn = [] speed3_collumn = [] speed4_collumn = [] speed5_collumn = [] speed6_collumn = [] speed7_collumn = [] speed8_collumn = [] speed9_collumn = [] speed10_collumn = [] mea...
import pandas as pd from sklearn import neighbors, datasets from numpy.random import permutation import matplotlib.pyplot as plt import numpy as np import string from sklearn import svm from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import precision_recall_fscore_support from sklearn.feature_e...
import math def checkColFill(col, lst, centerRow=1): if lst[centerRow-1][col] == 1 and lst[centerRow][col] == 1\ and lst[centerRow+1][col] == 1: return True return False noOfCols = lambda x: math.ceil(x/3) if math.ceil(x/3) >= 3 else 3 def do(lst): for col in range(1, len(lst[0])-1): ...
from .rank_and_suit_validator import RankAndSuitValidator from .royal_straight_flush_validator import RoyalStraightFlushValidator from .straight_flush_validator import StraightFlushValidator from .four_of_a_kind_validator import FourOfAKindValidator from .full_house_validator import FullHouseValidator from .flush_vali...
from rest_framework import serializers from contas.models import Contas, Deposito class ContaSerializer(serializers.ModelSerializer): class Meta: model = Contas fields = ['agencia', 'conta','saldo', 'get_ultima_movimentacao'] class DepositoSerializer(serializers.ModelSerializer): class Meta:...
# -*- coding: utf-8 -*- """ Created on Sat Mar 23 14:18:11 2019 @author: Ananthan """ import numpy as np import math import pandas as pd import process as sp # import re import os def t_n_d(file): """ gets title and description from a file """ s = file.read() # des = re.findall(r'\"([^]]*)\"', s)...
""" http://2018.igem.org/wiki/images/0/09/2018_InterLab_Plate_Reader_Protocol.pdf """ import json from urllib.parse import quote import sbol3 from tyto import OM import labop import uml from labop.execution_engine import ExecutionEngine from labop_convert.markdown.markdown_specialization import MarkdownSpecialization...
import os from GAN import GAN from utils import show_all_variables from utils import check_folder import tensorflow as tf import argparse import os def str2bool(v): return v.lower() in ('True', '1') """parsing and configuration""" def parse_args(): desc = "Tensorflow implementation of GAN collections" ...
#!/usr/bin/env python # D. Jones - 9/1/15 """BEAMS method for PS1 data""" from __future__ import print_function import numpy as np fitresheader = """# VERSION: PS1_PS1MD # FITOPT: NONE # ---------------------------------------- NVAR: 30 VARNAMES: CID IDSURVEY TYPE FIELD zHD zHDERR HOST_LOGMASS HOST_LOGMASS_ERR SNR...
#ASSIGNMENT13 #QUESTION:1 Name and handle the exception occured in the following program: # a=3 # if a<4: # a=a/(a-3) # print(a) #SOLUTION: #in above code there is an indentation error in line if a<4: and print(a).after resolving the #indentation e...
import pygame, sys, time from pygame.locals import * pygame.init() Display_Width = 800 Display_Height = 600 DW_Half = Display_Width / 2 DH_Half = Display_Height / 2 Display_Area = Display_Width * Display_Height DS = pygame.display.set_mode((Display_Width, Display_Height)) x = 0 y = 0 def event_handler(): for eve...
unit=int(input("enter no.of units consumed=")) if(unit>=1 and unit<=50): Rate=unit*3 elif(unit>=51 and unit<=100): Rate=unit*6 elif(unit>=100 and unit<=150): Rate=unit*9 elif(unit>=151 and unit<=200): Rate=unit*12 else: Rate=unit*15 print("unit=",unit) print("Rate=",Rate) ...
import sys import mysql.connector import base64 try: connection = mysql.connector.connect(host='localhost', database='laravel', user=base64.b64decode('cm9vdA=='), password=base64.b64decode('Y...
import unirest from core.models import SMSOutgoing from core.models import Transaction import functools import urllib import SMS_MESSAGES import re SMS_URL= 'http://shahz.pagekite.me/sendsms' def resend_sms(sms): unirest.get(SMS_URL, params = {'phone':urllib.pathname2url(sms.reciever), 'text':sms.message}, callback = ...
n = int(input("Digite um numero inteiro: ")) divisor = 2 condicao = True while divisor < n and condicao: if n%divisor == 0: condicao = False divisor=divisor+1 if n%divisor == 0: print("primo") else: print("não primo")
"""Module containing the sender alias API of the v1 API.""" from flask import abort from flask.views import MethodView from .root import API_V1 from .models import SenderAlias from ...db import DB from ...db.models.sender_alias import SenderAlias as SenderAlias_DB @API_V1.route("/sender_alias/") class SenderAliasL...
def Create(Database, Cursor, table, dict, log=False): SQLStatement = "" columns = [] values = [] for column, value in dict.items(): columns += [column] values += [f"'{value}'"] SQLStatement = f"INSERT INTO {table} ({','.join(columns)}) VALUES ({','.join(values)})" if log: ...
# *_* coding=utf8 *_* """ 描述:Unreal Proxy 安装脚本。 作者:Tang Wanwan """ import setuptools setuptools.setup( requirements = ["eventlet, tornado"], name="unreal", version="2013.8", author="Tang", description="Tang Wanwan's Unreal proxy for bad things.", packages=setuptools.find_packages(exclude=['te...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' PROBLEMA: Projete (design) uma animação de um semáforo. Seu programa deve mostrar um semáforo que é vermelho, depois verde, depois amarelo, depois vermelho, etc. Para este programa, a definição de dados do estado mutável do mundo deve ser uma enumeração. Para fazer as ...
#!/usr/bin/env python3 from datetime import datetime, timedelta import sys input_file = sys.argv[1] output_file = sys.argv[2] TIME_JUMP_IN_SECONDS = int(sys.argv[3]) with open(input_file) as src, open(output_file, 'w') as dest: for line in src: line = line.strip() if "-->" not in line: ...
import unittest from value_objects import EntityMixin from value_objects.util.testing import assert_unequal_objects_but_equal_strings, assert_unequal_objects_and_strings # ============================================================================ # Person # =========================================================...
x= "150905" result = [i for i in filelist if x in i]
# _*_ coding:UTF-8_*_ from bs4 import BeautifulSoup from multiprocessing import Process, Queue, Event import requests, random, codecs, time, re, os DIR_PATH = 'G:\\crawl\\zhihu\\content' PAGE_QUEUE = Queue(25) IMG_QUEUE = Queue(80) class DerivedProcess(Process): ''' Derived from multiprocessing subclas...
import random N = 5000 B = 926 C = 937 chance_0 = 1 chance_1 = 1 chance_2 = 2 choices = [] for i in range(chance_0): choices.append(0) for i in range(chance_1): choices.append(1) for i in range(chance_2): choices.append(2) def gen_num(i): return random.choice(choices) with open("../subtasks/02_bonus/05.in", 'w...
import tarefas import escalonador from random import randint # Definindo a lista para enviarmos ao sistema. listaTeste = [] # Declarando as quatro tarefas que precisaremos escalonar. tarefa1 = tarefas.Tarefa() tarefa2 = tarefas.Tarefa() tarefa3 = tarefas.Tarefa() tarefa4 = tarefas.Tarefa() # Estamos atribuindo valor...
from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput from kivy.uix.floatlayout import FloatLayout from kivy.uix.label import Label from kivy.core.text import LabelBase #font file needs to be in the folder LabelBase.register(name="Dodger", fn_regular= "dodger3condital.ttf"...
import boto3 def create_sns(sns_name): """ A function to create sns """ conn = boto3.client('sns', region_name='ap-south-1') # create topic response = conn.create_topic( Name=sns_name) # get arn topic_arn = response['TopicArn'] # subscribe to topic response = conn.su...
# Import APM package from apm import * # define server and application s = 'http://byu.apmonitor.com' a = 'drill' # Clear prior application apm(s,a,'clear all') # Load model file apm_load(s,a,'drilling.apm') # Global settings apm_option(s,a,'apm.solver',1) apm_option(s,a,'apm.max_iter',200) # Adju...
#!/usr/bin/env python # # Copyright (c) 2019 Opticks Team. All Rights Reserved. # # This file is part of Opticks # (see https://bitbucket.org/simoncblyth/opticks). # # 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...
from flask import Flask import os from blueprints.movies import movies from model.movies import Movies app = Flask(__name__) app.movies = Movies() @app.route('/') def hello_world(): return 'Hello continuous delivery' app.register_blueprint(movies, url_prefix='/movies') if __name__ == '__main__': ...
from django import forms from django.db.models import fields from django.forms import DateInput from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Empleado, Equipo, Ticket #La creacion del formulario de Empleado class EmpleadoForm(forms.ModelForm): ...
import numpy as np import scipy as sp import matplotlib.pyplot as py import random as rd import math as m global ylim global xlim global nb_cust global kNN global clim global Capacity global Error ylim = 200 xlim = 200 clim = 30 nb_cust = 10 kNN = 5 Capacity = 175 Error = (0, (0, 0), ([[0], 0], [[0], 0])) # Creatio...
#!/usr/bin/env python # -*- coding: UTF-8 -*- u""" This example produces two arrows whose scale stays fixed with respect to the distance from the camera (i.e. as you zoom in and out). Standard spheres are drawn for comparison. """ import sys import os.path from PyQt4 import QtCore, QtGui QtCore.Signal = QtCore.pyqt...
# This code generates the fibonacci serie from 1 to 1000 # This single line set a = b and in that point b = 0; then set b = 1 a,b=0,1 while b<1000: # print("a="+str(a)), # print("b="+str(b)), # print("a+b="+str(a+b)), print(b), a,b=b,a+b,
# ToDo : update_record_model not implemented # NOTE : Moved config into pui import configuration import wizard import utils import gtk , gobject try : import hildon except : hildon = False import time delay_quit_interval = 10 def delete_event ( widget , event , data=None ) : locator = None if d...
import json from django.views.generic import View from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q from django.core.serializers.json import DjangoJSONEncoder from django.conf import settings from apps.master_file import models ...
# # GRPC Server for NK Shapelet Classifier # # Uses GRPC service config in protos/grapevine.proto # from flask import Flask, request import time import pandas as pd import numpy as np import configparser from Sloth.classify import Shapelets from Sloth.preprocess import events_to_rates from tslearn.preprocessing im...
"""Write a function (with helper functions if needed) called to Excel that takes an excel column value (A,B,C,D,...,AA,AB,AC,..., AAA...) and returns a corresponding integer value (A=1,B=2,..., AA=26). """ import unittest A = ord('A') - 1 Z = ord('Z') def col2int(col): "Calculates the index of an Excel column" s...
import numpy as np import mxnet as mx import cv2, time from collections import namedtuple def load_inception_model(): with open('./synset.txt', 'r') as f: synsets = [l.rstrip() for l in f] sym, arg_params, aux_params = mx.model.load_checkpoint('Inception-BN', 0) model = mx.mod.Module(symbol=sym, co...
from app import db class Plugin(db.Model): __table_args__ = {"extend_existing": True} pid = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) identifier = db.Column(db.String(16), nullable=False) name = db.Column(db.String(32), nullable=False) version = db.Column(db.Strin...
import numpy as np import os, sys, csv, random def read_labels(labels_filename): names = [] with open(labels_filename, "rt") as f: reader = csv.reader(f, delimiter=";") for line in reader: names.append(line[0].strip()) print('labels:', names) vectors = np.eye(len(names)) def vector_by_name(name): i =...
import tensorflow as tf import config from tensorflow.compat.v1 import placeholder, Variable, get_variable from tensorflow.contrib import slim def Input(input_shape): return placeholder(tf.float32, input_shape) def Conv2D(inputs, kernel=3, output_channel=64, stride=1): return slim.conv2d(inputs...
#!/usr/bin/env python """ Script for testing out basic functionality of Eads' adaboost implementation. Software dependencies can be found at: svn checkout http://svn.eadsware.com/tinyboost svn checkout http://convert-xy.googlecode.com/svn/trunk/ convert-xy-read-only/ ##### help(tiny_boost) : ...