text
stringlengths
38
1.54M
from collections import OrderedDict import numpy as np FACIAL_LANDMARKS_IDXS = { "mouth": (48, 68), "right_eyebrow": (17, 22), "left_eyebrow": (22, 27), "right_eye": (36, 42), "left_eye": (42, 48), "nose": (27, 36), "jaw": (0, 17), "right_side": (0), "gonion_right": (4), "menton...
import time import array import random def tlist(b, x, y, n): t1 = time.clock() for n in xrange(n): for j in range(y): for i in range(x): w = b[j][i] t2 = time.clock() print "0 - List[y][x]: ", round(t2-t1, 3) return t2-t1 def tlist2(b, x, y, n): t1 = time...
# Generated by Django 3.1.1 on 2020-09-23 10:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('testapp', '0003_auto_20200923_1518'), ] operations = [ migrations.AlterField( model_name='employee', name='resume', ...
# -*- coding: latin-1 -*- """ XML object class Hervé Déjean cpy Xerox 2009 a class for object from a XMLDocument """ from XMLDSObjectClass import XMLDSObjectClass from config import ds_xml_def as ds_xml class XMLDSTOKENClass(XMLDSObjectClass): """ LINE class ...
import socket port=8081 host='localhost' s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.sendto(b'haha!',(host,port))
import pytest import os import json import sys VALUE_WITH_CHECKSUM = 0 VALUE_INITIAL = 1 EXPECTED_CHECK_DIGIT_LENGTH = 1 EXPECTED_VALUES = [ ('1996012101289', '199601210128'), ('1960031203012', '196003120301'), ('1995050921153', '199505092115'), ('0000000000000', '000000000000') ] sys.path.insert(1, ...
from main import Node, traverse import copy def syntax(input): input.reverse() root = Node(None, 'A', 0, 'NT') # Rules def isType(type_check): if len(input) > 0: return input[-1].getType() == type_check return False def isVal(val_check): if len(input) > 0: ...
from django.shortcuts import render, redirect from .models import Product, Repair, Complaint from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic import (ListView, DetailView, UpdateVie...
from __future__ import absolute_import, unicode_literals from django.contrib.postgres.fields import JSONField from django.db import models from django.db.models import signals from django.utils.translation import ugettext_lazy as _ from django_celery_beat.models import PeriodicTask, PeriodicTasks from . import schedu...
# -*- coding: utf-8 -*- """ Created on Sat Mar 11 17:10:25 2017 @author: david """ from parsing_funs import set_type_dict, make_table, load_file, file_path import json
import pickle from collections import defaultdict from input import get_tagged_corpus from output import get_gold_from_dir from typing import List from nltk.tokenize import word_tokenize from pathlib import Path from flair.data import Sentence, Token, Corpus from flair.data_fetcher import NLPTaskDataFetcher, NLPTask ...
from abc import ABCMeta, abstractmethod from dataclasses import dataclass, field from typing import Dict, Generic, Iterable, List, TypeVar from datahub.ingestion.api.closeable import Closeable from datahub.ingestion.api.common import PipelineContext, RecordEnvelope, WorkUnit from datahub.ingestion.api.report import Re...
from __future__ import division from math import floor from collections import Counter, defaultdict from itertools import combinations, islice from magichour.api.local.util.log import get_logger, log_time logger = get_logger(__name__) def xor(s1, s2, skip_in_s2=0): """ XOR at the core of the the PARIS dist...
from selenium import webdriver import time from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC link = "http://nda.local" browser = webdriver.Chrome() #Инструкция wait нужна для того, когда элемент...
from tools.tools import cartesian_mask if __name__ == "__main__": mask_dir = 'mask' shape = (18, 192, 192) mask_8x = cartesian_mask(shape, 8, sample_n=4, centred=True) mask_8x = np.transpose(mask_8x, (1,2,0)) mask_10x = cartesian_mask(shape, 10, sample_n=4, centred=True) mask_10x = np.transpo...
""" Chương trình clone source https://600tuvungtoeic.com/ """ import os import bs4 import requests import shutil import json import codecs import cv2 SOURCE_URL = 'https://600tuvungtoeic.com/' idWord = 1 def main(): r = requests.get(SOURCE_URL) if r.ok: s = bs4.BeautifulSoup(r.content, 'lxml') ...
# Given a string containing just the characters '(' and ')', find the length of # the longest valid (well-formed) parentheses substring. # # Example 1: # # # Input: "(()" # Output: 2 # Explanation: The longest valid parentheses substring is "()" # # # Example 2: # # # Input: ")()())" # Output: 4 # Explanation: The lo...
import os def check_ping(host_name,count,waitinsec): response= os.system("ping "+host_name) # print(f" response is {response}") check_ping('www.google.com',5,2)
# 何故かわかっていないが,辞書でソートだとWAでリストでソートだとACになる def main(): n, m = map(int, input().split()) ab = [] for _ in range(n): x, y = map(int, input().split()) ab.append((x, y)) # dic_sorted = sorted(dic.items(), key=lambda x:x[0]) ab.sort() ans = 0 cnt = 0 for i in range(n): i...
# 122. Best Time to Buy and Sell Stock II # https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/ class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if not prices: return 0 profit = 0 ...
"""Example for manually working with the quantum objects classes. While manually manipulating quantum states is definitely not the focus of this simulation package (there are better tools for that), it is nonetheless a good starting point. Knowing how the quantum objects work is also essential for creating custom even...
T = int(input()) for tc in range(1, T+1): str1 = input() str2 = input() max = 0 for str in str1: if str2.count(str) > max: max = str2.count(str) print("#{} {}".format(tc, max))
for tc in range(1, 11): N = int(input()) data = input() stack = [] num_lst = [] push_prio = {'*': 2, '+': 1, '(': 3} pop_prio = {'*': 2, '+': 1, '(': 0} # Change to postfix for i in range(N): if data[i].isdigit(): num_lst.append(data[i]) else: i...
from tkinter import * from tkinter import ttk import pymysql from tkinter import messagebox from PIL import ImageTk,Image class Student: def __init__(self,root): self.root=root self.root.title("Scholar Stewardship Application") self.root.geometry("1350x700+0+0") self.root.c...
import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) import unittest from copy import deepcopy from quiz.quiz1 import closest_multiple_10 test_case = [ [22, 20], [35, 30], [37, 40] ] class MyTestCase(unittest.TestCase): def test_something(self): ...
from django.contrib import admin from .models import Cards, CardDetail # Register your models here. admin.site.register(Cards) admin.site.register(CardDetail)
from django import forms from django.forms import ModelForm from models import UserProfile from django.contrib.auth.models import User import logging from django.contrib.auth import authenticate, login class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', ...
# -*- coding: utf-8 -*- ########################################################################################### # # module name for OpenERP # Copyright (C) 2015 qdodoo Technology CO.,LTD. (<http://www.qdodoo.com/>). # ######################################################################################...
#Python Objects Exercise #1 Basics class Person: def __init__(self, name, email, phone, friends): self.name = name self.email = email self.phone = phone self.friends = [] # def greet(self, other_person): # print('Hello {}, I am {}!'.format(other_person.name, self.na...
#!/usr/bin/env python import os.path from flask import Flask from werkzeug.contrib.fixers import ProxyFix from flask.ext.sqlalchemy import SQLAlchemy from .routes import register_routes from .database import db from .animal_inventory.models import Mouse app = Flask(__name__) app.config.from_object('CloudColony.se...
import MySQLdb as sql from config import Config import sys cfg = Config() def get_connection(): """ Establish connection to database """ return sql.connect(host=cfg.dbhost, port=cfg.dbport, user=cfg.user,\ passwd=cfg.password, db=cfg.database,\ charset=cfg.charset) def create_db (): """ Initialize database ""...
import abc from typing import Dict, Iterable, Optional from oaas_registry.service_definition import ServiceDefinition class Registry(metaclass=abc.ABCMeta): """ This registry represents a simple decorator for the actual implementations. """ @abc.abstractmethod def register_service( s...
""" A test script to shut down Zookeeper. """ import logging import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib")) import monit_interface def run(): """ Shuts down Zookeeper. """ logging.warning("Stopping Zookeeper.") monit_interface.stop('zookeeper-9999', is_group=False) ...
import datetime from django.db import models from django.conf import settings from .utils import window, next_full_hour, full_hours_between ONE_HOUR = datetime.timedelta(hours=1) class Category(models.Model): title = models.CharField(max_length=1023) style = models.CharField(max_length=15) notes = mod...
"""Routines for grabbing a page, with caching.""" import hashlib import os import time from six.moves.urllib.error import HTTPError from six.moves.urllib.request import urlopen from sr.tools.environment import get_cache_dir # Number of seconds for the cache to last for CACHE_LIFE = 36000 def grab_url_cached(url): ...
import requests import random business_id = 'kApVYIWwlriVK1pqPVrOPg' API_KEY = '_5qOZHWTK4tjf0PzbSumf7l0oOgq6ZNl0cP04_zXtijrwRs-hQqs3VHUW69ok4JC2YoIPhyUOyq7tE-8TldNdfyhT8HltpV9KqCeG8jArab9rZdDxGthP--PAvY3X3Yx' ENDPOINT = 'https://api.yelp.com/v3/businesses/search' HEADERS = {'Authorization': 'bearer %s' % API_KEY} #...
from rest_framework import serializers from users.models import LeaderProfile, Teacher, Student, StudentGroup from django.contrib.auth.models import User from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from rest_framework_simplejwt.views import TokenObtainPairView class LeaderSerializer(se...
def quickSort(alist,blist): quickSortHelper(alist,0,len(alist)-1,blist) def quickSortHelper(alist,first,last,blist): if first<last: splitpoint = partition(alist,first,last,blist) quickSortHelper(alist,first,splitpoint-1,blist) quickSortHelper(alist,splitpoint+1,last,blist) def partiti...
from flask import Flask, request, abort, jsonify import json import sys import subprocess sys.path.insert(1, '../PP-01') from bill import * app = Flask(__name__) def getStatus(): subprocess.call('echo {} | sudo -S {}'.format(pwd, 'echo root'), shell=True) cpuPercentage = subprocess.getoutput("mpstat | aw...
import os import mimetypes def file_inspector(filename): 'Reports posix filesystem attributes for a file' _, ext = os.path.splitext(filename) s = os.stat(filename) content_type, encoding = mimetypes.guess_type(filename) # ignoreing ctime as rarely relevant return { #'created': [time....
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist class turtlebot_move(): def __init__(self): rospy.init_node('turtlebot_move', anonymous=False) rospy.loginfo("Press CTRL + C to terminate") rospy.on_shutdown(self.shutdown) self.set_velocity = rospy...
"""2D convolutional model for Allen data.""" layer_structure = [ { 'layers': ['_pass'], 'names': ['contextual'], 'hardcoded_erfs': { 'SRF': 1, 'CRF_excitation': 1, 'CRF_inhibition': 1, 'SSN': 9, 'SSF': 29 }, 'norma...
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 01:44:32 2019 @author: Owner """ import json from sklearn.metrics import davies_bouldin_score import numpy as np import utm from sklearn import metrics path = "\\Users\\Owner\\Desktop\\PythonCodes\\ML_Project\\FINAL_DBSCAN_200M_250p_c.geojson" with open(path) as f: ...
from django.conf.urls import url from market import views urlpatterns = [ url(r'^goods/',views.GoodsView.as_view()), url(r'^foodtype/',views.FoodTypesView.as_view()) ]
import click from rq_mantis.app import app @click.command() @click.option('--redis-url', default='redis://localhost:6379', help='Redis url eg. redis://localhost:6379') @click.option('--debug', default=False, help='Debug mode') @click.option('--host', default='127.0.0.1', help='Host') @click.option('--port', default=...
import cv2 img=cv2.imread('back.png') gray=cv2.imread('back.png',cv2.IMREAD_GRAYSCALE) cv2.imshow('dog image',img) cv2.imshow('gra dog image',gray) cv2.waitKey(0) cv2.destroyAllWindows()
# Generated by Django 3.0 on 2020-01-22 09:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('restaurants', '0004_remove_restaurant_created'), ] operations = [ migrations.RemoveField( model_name='restaurant', nam...
import sqlite3 import Tkinter window=Tkinter.Tk() con=sqlite3.connect('login.db') cur=con.cursor() # cur.execute('CREATE TABLE LoginDetails (Name TEXT , Username TEXT , Password TEXT, Account FLOAT)') # cur.execute("INSERT INTO LoginDetails VALUES('Andikan Bassey ' , 'Lambo' , 'andikan', 20000)") def search(us...
#!/usr/bin/env python # # This file is part of the Fun SDK (fsdk) project. The complete source code is # available at https://github.com/luigivieira/fsdk. # # Copyright (c) 2016-2017, Luiz Carlos Vieira (http://www.luiz.vieira.nom.br) # # MIT License # # Permission is hereby granted, free of charge, to any person obtai...
from datetime import date from rest_framework.response import Response from django.http import JsonResponse, HttpResponse from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework import pagination import jwt from restapi import ...
# Copyright 2016 Canonical Limited. # # This file is part of charm-helpers. # # charm-helpers is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 as # published by the Free Software Foundation. # # charm-helpers is distributed in the hope that ...
# -*- coding: utf-8 -*- """Global pyprof2html's environment. """ from jinja2 import Environment, PackageLoader __all__ = ['ENVIRON'] CODEC = 'utf-8' ENVIRON = Environment(loader=PackageLoader('pyprof2html', './templates', encoding=CODEC))
from tkinter import * from tkinter import ttk from datetime import datetime, date import locale locale.setlocale(locale.LC_ALL, ("es_ES", "UTF-8")) HEIGHTBTN = 50 WIDTHBTN = 68 class Header(ttk.Frame): cadena = '' def __init__(self, parent): ttk.Frame.__init__(self, parent, width=7*WIDTHBTN, height=0....
__description__ = \ """ Control a clock that displays an RGB value to represent time. """ __author__ = "Michael J. Harms" __date__ = "2018-04-30" import time, datetime, json, sys, copy, multiprocessing, math class Clock: """ Control leds to display time as a color. """ def __init__(self, ...
#%% import numpy as np import matplotlib.pyplot as plt from matplotlib import rc from scipy.misc import derivative from scipy.integrate import solve_ivp from scipy.interpolate import InterpolatedUnivariateSpline as IUS, interp1d from scipy.optimize import fsolve rc('text', usetex = True) #%% #Evolution of the scalar f...
import random import math iter = 100 avg_result = 0.0 for i in range(iter): limit = 100 first_octant = 0 for i in range(limit): x = random.uniform(-1, 1) y = random.uniform(-1 * math.sqrt(1 - pow(x, 2)), math.sqrt(1 - pow(x, 2))) z = random.uniform(-1 * math.sqrt(1...
import time import pygame class PetImage: initial = time.time() def __init__(self, screen, file, number): """初始化宠物图像并设置其初始位置""" self.screen = screen self.delay = 0 # 加载宠物图像并获取其外接矩形 self.number = number self.index = 0 self.images = pygame.image.load(fil...
import gdal import subprocess import CAMS_utils gdal.UseExceptions() def reproject(var, infname, outfname, xmin, xmax, ymin, ymax): args = ['./reprojectCAMS.sh', '-i', infname, '-o', outfname, '-p', var, '--xmin', str(xmin), '--ymin', str(ymin), '-...
"""create app_users table Revision ID: 363dec53760 Revises: 2634028c6b8 Create Date: 2015-10-25 14:22:41.435025 """ # revision identifiers, used by Alembic. revision = '363dec53760' down_revision = '2634028c6b8' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa import datetime d...
import threading import socket import sys import _thread import RPi.GPIO as GPIO import time import os import sqlite3 import grovepi GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.OUT) GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.OUT) GPIO.setup(15, GPIO.OUT) GPIO.setup(10, GPIO.OUT) GPIO.setup(16...
class Node: def __init__(self, data=None): self.data = data self.next = None class linked_list: def __init__(self): self.head = Node() def insert(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node return data def incl...
def DistinctList(arr): total = 0 numDict = {} for x in arr: if x not in numDict: numDict[x] = 1 else: numDict[x] +=1 #print(numDict) for val in numDict.values(): if val > 1: total += val -1 #print(total) return t...
from unittest import TestCase class TestLineItem(TestCase): def test_variant_id(self): self.fail() def test_title(self): self.fail() def test_quantity(self): self.fail() def test_price(self): self.fail() def test_grams(self): self.fail() def test_sk...
dict = {'test1': 93, 'test2': 95} dict['test3'] = 99 print( dict.get('test4', 100) ) print( dict.pop('test1') ) print( dict )
from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.core import serializers from django.contrib.auth.decorators import login_required from .models import Post, Comment from .forms import PostForm, CommentForm # Create your views here. def home(request): re...
# -*- coding=utf-8 -*- import os from django.db.models import FileField from django.forms import forms, MultiValueField, CharField, MultipleChoiceField, SelectMultiple from django.template.defaultfilters import filesizeformat from famille.utils.python import generate_timestamp from famille.utils.widgets import RangeW...
#-*- coding: utf-8 -*- """ Author: guohaozhao116008@sohu-inc.com Since: 13-6-13 17:45 py 中的locals()函数以及 globals()函数 """ def test(ars): x = 1 print locals() if __name__ == "__main__": test(5) test("123") print globals()
from dataclasses import dataclass @dataclass class PlayingCard: rank: str suit: str def __str__(self): return f'{self.suit}{self.rank}' queen_of_hearts = PlayingCard('Q', '♡') ace_of_spades = PlayingCard('A', '♠') ace_of_spades > queen_of_hearts # TypeError: '>' not supported between instances...
import sys sys.path.append("F:\Algorithmica\MyCodes") import spacy #F:\Algorithmica\MyCodes\NLPCodes with open('F:\Algorithmica\MyCodes\Tripadvisor_hotelreviews.txt','r',encoding='utf-8') as d: reviews = d.read() #encoding - it is nothing but ASCII version where different computer can be used to get on same p...
import numpy as np ''' T O D O THIS IS CURRENTLY A COPY OF THE NEURAL_NETWORK CLASS.. NEEDS WORK TO CONVERT TO CNN ''' # Neural Network Class for Feature Approximation in Reinforcement Learning class convolutional_neural_network(): def __init__(self, layer_sizes): # Track layersizes as a numpy array ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from flask_script import Manager, Shell from app import create_app, db # 读取配置(此配置再数据迁移中被引入) config_name = (os.getenv('FLASK_CONFIG') or 'default') app = create_app(config_name) manager = Manager(app) def make_shell_context(): return dict(app=app, db=db) m...
fname = input('Enter file name: ') if len(fname) < 1 : fname = 'clown.txt' fhand = open(fname) counts = dict() for line in fhand: line = line.rstrip() words = line.split() for word in words: counts[word] = counts.get(word, 0) + 1 temp = list() for k, v in counts.items() : newTup = (v , k) ...
def InitializeRow(entity, row): row.GetCellByName("STATUS").Tooltip = row.GetCellByName("STATUS").Text row.GetCellByName("STATUS").Text = "" if (entity["STATUS"].GetInt32() == 1): row.GetCellByName("STATUS").FontIcon = "fa fa-clock-o" row.GetCellByName("STATUS").TextColor = "#c49f47" if ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Aug 10 08:07:01 2020 @author: shino """ import numpy as np import glob import scipy from dataset import Dataset from scipy.spatial import ckdtree path = "/Volumes/ssd/nyu_2451_38586_las/T_315500_234500/*.txt" files = [] files = glob.glob(path) print(f...
""" Modules for performing conversions between file types, or for resampling a given file. In general, the naming convention follows this rule: <file_ext_in>2<file_ext_out>('filename_in', 'filename_out') for example: sww2dem('northbeach.sww', 'outfile.dem') Some f...
# Open the data and make list advent_input = open('advent_day_1/input.txt', 'r') a_list = list(advent_input) advent_input.close() # Make the list proper advent_list = [x[:-1] for x in a_list] advent_list = [int(i) for i in advent_list] # Look for the 2020 ~ part 1 for i in advent_list: for x in advent_list: ...
#!/usr/bin/env python # /**************************************************************************** # * Copyright (c) 2018 John A. Dougherty. All rights reserved. # * # * Redistribution and use in source and binary forms, with or without # * modification, are permitted provided that the following conditions # ...
from impl.labyrinth.Cell import Cell from impl.labyrinth.CellType import CellType from services.ICell import ICell class CellEmpty(Cell, ICell): """Empty cell where the player can walk""" def __init__(self): super().__init__(CellType.EMPTY) def __str__(self): return "*" def execute_...
import requests import urllib url = 'http://api-xl9-ssl.xunlei.com/sl/group_accel/motorcade_mem?' data = { 'uid':'493627929', 'send_from':'web', 'group_id':'1759602', '_uid':'493627929', '_sessid':'6F8D250C527FD37F680F7097C6915B3A', '_h[]':'Peer-Id:1C1B0D3E68A0QW7Q', '_dev':'1', '_callback':'_jsonpf7qd61x6a29gnoajbj9h...
# Escribir un programa que pregunte al usuario su edad y muestre por pantalla si es mayor de # edad o no. edad = int(input("Cuatos años tienes? ")) if edad > 18: print("Usted es mayor") else : print ("Usted es menor")
import sys def solve(): N = int(input()) print(N) print(*[1]*N, sep='\n') if __name__ == '__main__': solve()
import mido from mido import MidiFile import time print(mido.get_output_names()) port = mido.open_output() # print(port) msg = mido.Message('note_on', note=60, time=5) port.send(msg) time.sleep(msg.time) port.send(mido.Message('note_off', note=60))
print("Hello! I am going to ask you questions about your device to create a commercial.") yourObject = input("What is your object? ") yourData = input("What data does it take? ") how = input("How will you record the "+yourData+" from your "+yourObject+"?") where = input("Where will the "+how+" be located? ") cost = inp...
import re import timeit from datetime import date import requests from bs4 import BeautifulSoup from openpyxl import load_workbook from openpyxl.utils import get_column_letter # Wraper function to calculate runtime of a function (function is able to # return value if needed) def calculate_runtime(func): def inner...
PLAYER = 'PL' OWNER = 'OW' PROFILE_TYPE_CHOICES = ( (PLAYER, 'Player'), (OWNER, 'Owner'), ) PUNE = 'PUN' MUMBAI = 'BOM' DELHI = 'DEL' BANGALORE = 'BAN' CHENNAI = 'CHE' PLACE_CHOICES = ( (PUNE,'Pune'), (MUMBAI,'Mumbai'), (DELHI,'Delhi'), (BANGALORE,'Bangalore'), (CHENNAI,'Chennai'), ) DOY = ('1970', '1971', '1...
# !/usr/bin/env python # -*- coding:utf-8 -*- """ @author: Wang Ye (Wayne) @file: Maximum Profit of Operating a Centennial Wheel.py @time: 2020/09/27 @contact: wangye@oppo.com @site: @software: PyCharm # code is far away from bugs. """ from typing import * class Solution: def minOperationsMaxProfit(self, custo...
import numpy as np import matplotlib.pyplot as plt import pandas as pd import math T = np.linspace(0, 1, 81) u = pd.read_csv("Z.txt", header=None) df = pd.DataFrame(index=np.arange((u.size)/31), columns=np.arange(1)) n = 0 for i in range(0, 81): df.iloc[i, 0] = u.iloc[i*31 + n, 0] df.to_csv("Z_final.txt", header...
from django.shortcuts import render from arches.app.models.system_settings import settings from arches.app.views.base import BaseManagerView from arches.app.views.plugin import PluginView class ConsultationView(PluginView): def get(self, request, pluginid=None, slug='consultation-workflow'): return super(...
# python3 #credit to: http://personal.denison.edu/~havill/algorithmics/python/knapsack.py import sys data = list(map(int, sys.stdin.read().split())) n, cap = data[0:2] vals = data[2:(2 * n + 2):2] whts = data[3:(2 * n + 2):2] collected_value = 0 def KnapsackFrac(v, w, W): order = bubblesortByRatio(v, w) #...
import os import psutil from .base import Base class System(Base): """ Collector for system. This collector is always enabled, and you can't disable it. This is intentional, as I can't think of a reason why you'd want to collect metrics from a server without caring about ...
from . import globals class UniformModel(object): def __init__(self, b=(1., 0., 0.), e=(0., 0., 0.), **kwargs): self.model = {"model": "model", "model_name": "uniform"} if globals.sim is None: raise RuntimeError("A simulation must be declared before a model") if globals.s...
import numpy as np def rombf(a,b,N,func,param) : """Function to compute integrals by Romberg algorithm R = rombf(a,b,N,func,param) Inputs a,b Lower and upper bound of the integral N Romberg table is N by N func Name of integrand function in a string such as ...
import os import sys import pika import uuid from conversation_types import Invitation, ConversationMessage, LocalType from core.message_adapter import AMQPConversationMessageAdapter from core.conversation_interceptor import ConversationInterceptor """Start a test for monitoring an existing conversation""" def start_m...
# implement an algorithm to find the kth to last element in a linked list import random import linkedlist def kth_to_last(_list, k): _list.reverse() current = _list.head counter = 1 while counter < k: current = current.next counter += 1 return current.value if __name__ == "__m...
'''Booleans: True False Logic''' # Boolean values are the two constant objects False and True. In numeric # contexts, they behave like the integers 0 and 1, respectively. The built-in # function bool() can be used to check any value as a Boolean, if the value can # be interpreted as a truth value. a = [1, 3, 6] b = ...
import numpy as np import random import math from scipy.optimize import minimize from tabulate import tabulate import matplotlib.pyplot as plt class SVM: def __init__(self, classA, classB, C=0.1, filename='', kernel='linear', sigma=1.0, degree=3): self.inputs = np.concatenate((classA, classB)) sel...
import cv2 cap = cv2.VideoCapture(0) haar_cascade_face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') while True: ret, frame = cap.read() if ret: faces_rects = haar_cascade_face.detectMultiScale(frame, scaleFactor=1.2, minNeighbors=5) print(' ', len(faces_rects)) for ...
import AllServers import Server import sys import os import subprocess class Main: try: #print "\n\n\nNow the client will logon to the connect command. \nThere are four commands that will be run, \'connect\', \'*username*\' \'*password*\' \'cd /root\'. \n You need to press enter for each one to be run. ...
def getOrderFromDict(d): return RobinhoodOrder(d['symbol'],d['action'],d['shares'],d['price'],d['date']) class RobinhoodOrder(object): def __init__(self, symbol, action, shares, price, date): self.symbol = symbol self.action = action self.shares = shares self.price = price ...
from random import randint tentativas = escolhido = 0 sorteado = 1 while escolhido != sorteado: escolhido = int(input('Digite um número: ')) sorteado = randint(0, 10) if escolhido < 0 or escolhido > 10: print('Número inválido, digite um número de 0 a 5') elif escolhido == sorteado: prin...