text
stringlengths
38
1.54M
from sys import argv def load_input(splitstring = "\n"): if len(argv) > 1: filename = "examples.txt" print("Using test cases...\n") else: filename = "input.txt" print("Using input...\n") with open(filename, "r") as f: return list(filter(bool, f.read().split(splitstri...
from werkzeug.exceptions import Conflict, NotFound, Unauthorized class JSONException(Exception): """Custom JSON based exception. :param status_code: response status_code :param message: exception message """ status_code = NotFound.code message = '' def __init__(self, message=None, status...
from UI.MainWindow import Ui_MainWindow from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from UI.proc import proc import cv2 import time import os # from interface.Detection import detector class ui(QMainWindow, Ui_MainWindow): def __init__(self): super(ui, self).__init...
import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html from sqlalchemy import create_engine from dash.dependencies import Input, Output, State import dash_table_experiments as dt engine = create_engine("mysql+pymysql://eums:eums00!q@133.186.146.142:3306/eums-poi?charset...
import sys def validate_empty_fields(data, field): if not data: print(f"ERROR: '{data}' is not a valid {field}!") sys.exit(1) validate_empty_fields('{{ cookiecutter.project_short_description }}', "project_short_description")
import requests from bs4 import BeautifulSoup url = "https://www.nba.com/players/jalen/adams/1629824" html = requests.get(url) soup = BeautifulSoup(html.text,'lxml') hight = soup.find_all('p', string='\n HEIGHT\n ') print(hight) # url = 'HEIGHT # '
import os import json from renjuu.game.const import Color class Scoreboard: def __init__(self, filename): self.filename = filename @staticmethod def parse_data(data): text = "Score table\n" for key in data: text += "%s : %s \n" % (key, data[key]) return text ...
import argparse import math import os import numpy as np import torch from PIL import Image from torch import optim from torch.nn import functional as F from torch.utils import data from torchvision import transforms from tqdm import tqdm from model import Generator from train import data_sampler, sample_data from ut...
## # base exceptions ## # base exception class BaseException(Exception): def __init__(self, *args, **kwargs): super(BaseException, self).__init__(args, kwargs) # db base exception class DbBaseException(BaseException): def __init__(self, *args, **kwargs): super(DbBaseException, self).__init__(args, kwargs) # db...
import torch.nn as nn from torch.distributions import Normal import torch import numpy as np class MLPPolicy(nn.Module): def __init__(self, state_dim, action_dim): super(MLPPolicy, self).__init__() self.fc1 = nn.Linear(state_dim, 100) self.relu1 = nn.ReLU() self.fc_mean = nn.Linear...
def interface_error_msg(interface, error_msg="Erro: Desconhecido"): interface.label_erro.setText(error_msg) def interface_status_msg(interface, status_msg="Desconhecido"): interface.label_status.setText(status_msg) def interface_scan_start(interface): interface.botao_vai.setEnabled(False) interface.bo...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import blog, Author, Category from .forms import PostForm, SignUpForm from django.shortcuts import redirect from django.utils import timezone from django.contrib.auth.decorators import login_required from django.con...
from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() setup( name='game-of-life', version='0.1.0', description='Sample Game of Life', long_description=readme, author='mpoqq', author_email='matthias.poqq@gmail.com', license=license, packages=find...
#!/usr/bin/env python """Mandelbrot set renderer. @author: Stephan Wenger @date: 2012-03-23 """ from numpy import linspace, array, minimum, maximum, cos, pi from matplotlib import cm from glitter import ShaderProgram, get_fullscreen_quad, Texture1D from glitter.contexts.glut import GlutWindow, main_loop, get_elapse...
#!/usr/bin/python import PTY_Interface import PowerSupply pty = PTY_Interface.Interface() pty.addDevice(PowerSupply.PowerSupply(), 5) pty.addDevice(PowerSupply.E3631A(), 3) pty.printFilename() pty.run()
import sys import timeseries.ArrayTimeSeries as ts import simsearch.SimilaritySearch as ss import numpy as np import simsearch.database as rbtreeDB from storagemanager.FileStorageManager import FileStorageManager def load_ts_data(file_name): "load timeseries data form given file name" ts_raw_data = np.loadtx...
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Department from .form import DepartmentForm from django.shortcuts import redirect from django.con...
from ftplib import FTP import os host = 'office.ai4health.com' port = 8021 username = 'zjjm' password = 'ftp_123_zjjm' def ftpconnect(host, port, username, password): ftp = FTP() # ftp.set_debuglevel(2) ftp.connect(host, port) ftp.login(username, password) return ftp def downloadfile(ftp, remot...
# 평범한 배낭 """ dynamic programming - 2차원 dp 생성 - 점화식 : dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weight[i]] + value[i]) if j - weight[i] >= 0 else dp[i][j] = dp[i - 1][j] """ import sys sys.stdin = open('C:\github\Algorithm\Dynamic-Programming\input.txt', 'rt') # input = sys.stdin.readline n, k = map(int, input().spl...
import abc from typing import Dict, List from job_search.domain.jobs.value_objects.job_type import JobInfo from job_search.domain.jobs.value_objects.simple_objects import ContactInfo, LocationInfo import job_search.repository.jobs.entities.job_entity as entities class JobRepository(metaclass=abc.ABCMeta): @abc.a...
from setuptools import setup from tumblr_reader import __version__ setup( name='django-tumblr-reader', version=__version__, author='Zach Snow', author_email='z@zachsnow.com', packages=['tumblr_reader', 'tumblr_reader.templatetags'], include_package_data=True, url='http://zachsnow.com/projec...
# Copyright (c) 2011 Alun Morgan, Michael Abbott, Diamond Light Source Ltd. # # 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 ver...
#!/usr/bin/env python # -*- coding: utf-8 -*- import collections class HeadersDict(collections.MutableMapping): """ A mapping class suitable as HTTP headers. All the keys are compared lower-case and with all the ``_`` replaced by ``-``. """ def __init__(self, headers=None): self.hea...
#!/usr/bin/env python3 from typing import cast import torch from torch import Tensor from captum.attr._utils.gradient import ( apply_gradient_requirements, compute_gradients, compute_layer_gradients_and_eval, undo_gradient_requirements, ) from .helpers.basic_models import ( BasicModel, Basic...
from .load import scHiCs from .analysis import kmeans, spectral_clustering, HAC from .analysis import scatter, interactive_scatter from .embedding import PCA, MDS, tSNE, SpectralEmbedding, PHATE
#warna termux birutua = "\033[0;34m" putih = "\033[0m" kuning = "\033[1;33m" hijau = "\033[1;32m" merah = "\033[1;31m" biru = "\033[0;36m" ungu = "\033[1;35m"
from __future__ import unicode_literals from django.db import models import re import bcrypt # Create your models here. class UserManager(models.Manager): def basic_validator(self, postData): errors = {} if len(postData['name']) < 3: errors["name"] = "name must be at least 2 chars" ...
import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() x=range(2) y=[214, 17] y1=[188 , 31 ] y2=[213 , 13 ] y3=[175 , 19 ] y4=[205 , 10] plt.axis([-0.2, 1.2, 0, 250]) ax.set_xticks(x) ax.tick_params('both',direction='in', which='both', pad=1, bottom = 'on', top = 'on', left = 'on'...
d1 = {} d2 = {} n = int(input("Enter the number of values in dictionary 1: ")) for i in range(n): key = int(input("Enter the key : ")) value = int(input("Enter the value : ")) d1[key] = value n = int(input("Enter the number of values in dictionary 2 : ")) for i in range(n): key = int(input("Enter the k...
s=input("Enter any string:") k=s.lower() count=0 for i in k: if(i=='o' or i=='a' or i=='i' or i=='e' or i=='u'): count+=1 print("number of o:",count)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This experiment was created using PsychoPy2 Experiment Builder (v1.74.00), Fri Jan 17 14:46:44 2014 If you publish work using this script please cite the relevant PsychoPy publications Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscie...
@dataclasses.dataclass class Nodes(Variable): name: str = 'nodes' def __post_init__(self): self.yr = self.g.shapes_yr self.level = self.g.level self.attrs = listify(self.g.node_attrs) + listify(Districts) super().__post_init__() def get(self): exists = super().get(...
N, M = map(int, input().split()) # N = total number of trees, M = Target total lenght of trees trees_length = list(map(int, input().split())) max_tree = max(trees_length) cut_heigth = [] for i in range(1, max_tree): cut_heigth.append(i) total_cut_lengths = [] for j in cut_heigth: cut_tot_len = 0 for k in ...
""" Program: customer.py Author: Paul Ford Last date modified: 07/1/2020 Purpose: Create my first class """ class Customer: """Customer Class""" # Constructor def __init__(self, cust_id, lname, fname, pnumber): # check to see if first and last name is alpha characters, if not throw exception ...
""" How it works / Logic flow 1a. Bot listens to the keyword "rtindru" - Tweepy returns list of tweets 1b. Bot checks if the tweet is about "recommend movie" 2. Bot asks the user "what's your favorite movie?" - we got the movie_name inside the main function - User responds with the movie name 3a.Takes 3b.Bot gets rec...
import unittest from unittest.mock import MagicMock from .. import query_api class QueryAPITest(unittest.TestCase): def test_defines(self) -> None: pyre_connection = MagicMock() pyre_connection.query_server.return_value = { "response": [ { "name": "...
''' Create a BMI calculator, BMI which stands for Body Mass Index can be calculated using the formula: BMI = (weight in Kg)/(Height in Meters)^2. Write python code which can accept the weight and height of a person and calculate his BMI. note: Make sure to use a function which accepts the height and weight value...
import tensorflow as tf import numpy as np from sklearn import preprocessing trees = np.loadtxt('Data/Data/trees.csv', delimiter=',', dtype=np.float32, skiprows=1) # trees = preprocessing.add_dummy_feature(trees) trees = np.insert(trees, 0, np.ones(31), axis=1) xx = trees[:, :-1] y = trees[:, -1:] print(x...
# FAZENDO OS IMPORTS NECESSARIOS PARA A APLICACAO import json import sys import os, urlparse import paho.mqtt.client as mqtt import pymysql #import cgitb from datetime import datetime ipMV = sys.argv[1] # CONEXAO COM O BANCO - DATABASE, USUARIO, SENHA E HOST conn = pymysql.connect( db='dbru', user='admin', ...
class Sentinel: """A sentinel which is always bigger than anything""" def __lt__(self, other): return False def __le__(self, other): return False def __gt__(self, other): return True def __ge__(self, other): return True if __name__ == '__main__': s = Sentine...
#!/usr/bin/python import os,sys mss = os.environ['MSS'] outpath = os.environ['VOL']+'/data' imax = 0 run = '' action = 'request' args = sys.argv if len(args)<2: sys.exit('no arguments') for i,a in enumerate(args): if a in ['-r','-run']: run = args[i+1].zfill(6) elif a in ['-m','-max']: imax = int(args[i+1]) ...
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import Column, Integer, ForeignKey, Table, String, Date, UniqueConstraint from models.base_model import Base teacher_subject_links = Table('teacher_subject', Base.metadata, Co...
# -*- coding: utf-8 -*- import logging, uuid from itertools import groupby class Offices: def _convertToDict(self,off): return {'id':off[0],'parent':off[1],'name':off[2],'telephone':off[3],'email':off[4]} ''' obtiene las oficinas hijas de las oficinas pasadas como parámetro ''' def...
from rest_framework import serializers from camera.models import Camera class CameraSerializer(serializers.ModelSerializer): class Meta: model = Camera fields = '__all__'
from collections import namedtuple from copy import deepcopy from hashlib import md5 class Node(object): def __init__(self, pos, size, used, source=False): self.pos = pos self.size = size self.used = used self.source = source def __repr__(self): contains_data = 'X' if ...
from fastapi.testclient import TestClient from unittest import TestCase from unittest.mock import MagicMock, patch from requests import Response from src.server import app @patch('src.server.Monitoring', autospec=True) @patch('src.server.FactorialSolver', autospec=True) @patch('src.server.RedisCache', autospec=True) ...
import pygame import random from os import path import os # инициализируем pygame pygame.init() # Единственный звуковой эффект в игре, это звук столкновения управляемого шарика со вражеским # Этот звуковой эффект здесь мы и добавляем pygame.mixer.init() snd_dir = path.join(path.dirname('Bump.wav'), 'snd') boom_snd =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import math import random import time def Two_norm(x): # x 为 n*1 矩阵 return math.sqrt(x.T*x) def Alpha_beta(x,y,z): # x,y,z 为 n*1 矩阵 xT = x.T yT = y.T zT = z.T s1 = (xT * x).item(0) # 数 s1 s2 = (yT * y).item(0) ...
from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from smtplib import SMTP import win32crypt import base64 import os import winreg import urllib.request firefox = os.path.join(os.environ['APPDATA'], 'Mozilla', 'Firefox', 'Profiles')...
while True: print("\n" * 100) print("BMI Calculator") print("--------------") height = int(input("Height (cm): ")) weight = int(input("Weight (kg): ")) BMIR = weight / ((height / 100) ** 2) BMI = str(round(BMIR, 2)) print("") if BMIR < 18.5: print ("BMI: " + str(BMI) + ", Under Weight") elif BMIR >= 18...
from allauth.utils import get_username_max_length, email_address_exists from django.contrib.auth import get_user_model, authenticate from rest_auth.models import TokenModel from allauth.account import app_settings as allauth_settings from allauth.account.adapter import get_adapter from django.utils.translation import u...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-08 04:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobs', '0031_auto_20170908_1345'), ] operations = [ migrations.AlterField( ...
import unittest from tests.unit_test_helper import is_answer from tests.unit_test_helper.console_test_helper import execfile class TestOutput(unittest.TestCase): def test(self): if is_answer: from lab.lab12.ch012_t02_make_a_list_ans import board else: from lab.lab12.ch0...
from .lib import open_browser from .pages import LoginPage browser = open_browser() page = LoginPage(browser) # Mensagens do formulário page.open() page.formulario.focar_email() assert page.formulario.get_texto_label_email() == 'Tá certo?' page.formulario.focar_senha() assert page.formulario.get_texto_label_senha()...
def bubble_sort(num_list, reverse=False): global result for _ in num_list: if reverse > 0: result = num_list[::-1] elif reverse < 0: result = num_list[::1] else: return num_list return result print(bubble_sort([2, 5, 8, 6, 4, 2], 2))
# Generated by Django 3.0.3 on 2020-04-21 01:43 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Group', fields=[ ('group_id', models.AutoFi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('conteudo', '0003_auto_20150413_1007'), ] operations = [ migrations.AlterField( model_name='pagina', ...
# coding=utf-8 # Phase reconstruction with the Griffin-Lim algorithm # # Copyright (C) 2019 Robin Scheibler, MIT License # # 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,...
# -*- coding: utf-8 -*- import os import unittest import numpy as np from pola.machine.topic_model import Document from pola.machine.topic_model import GTopicModel from pola.machine.topic_model import resource as rs class TestGTopicModel(unittest.TestCase): def test_model(self): model = self.create_test_...
# Generated by Django 2.2.4 on 2021-02-26 18:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('registration_app', '0001_initial'), ] operations = [ migrations.CreateModel( name='Book', ...
# encoding: utf8 from __future__ import absolute_import, division, print_function, unicode_literals import fnmatch import random import os import re from base64 import urlsafe_b64encode, urlsafe_b64decode from datetime import datetime, timedelta from aspen import Response, json from aspen.utils import to_rfc822, utcn...
''' module face_recognizer.py Purpose: identify a face ''' import time from enum import Enum from numpy import load, expand_dims, asarray, dot, transpose, sqrt, linalg, array as np_array from sklearn.preprocessing import LabelEncoder, Normalizer from sklearn.svm import SVC from utils import LEARNED_FACE_EMBEDDI...
# Generated by Django 3.0.6 on 2020-10-12 17:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0004_auto_20201012_2008'), ] operations = [ migrations.AlterField( model_name='brand', name='test', ...
# -*- coding: utf-8 -*- import pytest from lib import ttbjson def test_constructor(): bjson_obj = ttbjson.TwoTribesBinaryJSON() assert bjson_obj.header == 'BJSON' assert bjson_obj.version == 1 assert bjson_obj.data is None with pytest.raises(TypeError, match=r'^header must be str$'): bj...
# coding=utf-8 # import unittest2 from itertools import takewhile, count from py_functional_learning.list_problems import head, tail, numElements \ , firstNelements, elementAt, reverse class TestList(unittest2.TestCase): def __init__(self, *args, **kwargs): super(TestList, self).__init__(*args, **kwargs) ...
from django.contrib import messages from django.core.paginator import Paginator from django.shortcuts import render, redirect from .models import Contact, post, Catagory, BlogComment from django.http import HttpResponse from shop.models import MyProfile from blog.templatetags import extras from .serializers import post...
import os, sys, time, datetime, random, hashlib, re, threading, json, getpass, urllib from multiprocessing.pool import ThreadPool try: import mechanize except ImportError: os.system('pip2 install mechanize') else: try: import requests except ImportError: os.system('pip2 install requests'...
''' Последний максимум Найдите наибольшее значение в списке и индекс последнего элемента, который имеет данное значение за один проход по списку, не модифицируя этот список и не используя дополнительного списка. Выведите два значения. ''' num_list = list(map(int, input().split())) max_val = num_list[0] max_ind = 0 ...
from lib import weeks from lib import tigergraphAPI from lib import mongoAPI import pandas as pd import numpy as np ''' Classificazione utenti Influenti e non e salvataggio su MongoDB distribuito ''' def main(): ## Connessione MongoDB print("Connessione MongoDB...") mongo_conn = mongoAPI.ge...
from display import * from matrix import * import math def add_circle(points, cx, cy, cz, r, step): x0 = cx + r y0 = cy for i in range(step): x1 = cx + r * math.cos(2 * math.pi * (i + 1) / step) y1 = cy + r * math.sin(2 * math.pi * (i + 1) / step) add_edge(points, x0, y0, cz, x1, ...
import random, sys, os, math, numpy #Eggholder Function def run(Arr): x=Arr[0] y=Arr[1] return -(y+47)*numpy.sin(numpy.sqrt(numpy.fabs(x/2+y+47)))-x*numpy.sin(numpy.sqrt(numpy.fabs(x-y-47))) #print run(512,404.2319) def check(Arr,T,Z=[0]): xmax=512 xmin=-512 if T==0: return 1 elif T==1: Range=numpy.zero...
from data.constants import * from data.sprites import * menu_sprites_dir = path.join(SPRITES_DIR, "menu/") length_line = 20 line_point = 200 // 100 volume_size = 10 class MainImage1: def __init__(self): self.image = transform.scale(image.load(menu_sprites_dir + "main_image1.png"), (175, 250)) sel...
"""def floating(n) : x = 1 for i in n : x = x * i print(x) s = 0 m = 0 for i in n : m = x/i print(m) s = s + m print(s) m = [1, 2, 3, 6] floating(m) """ for i in range(1, 10) : print(pow(i , 2))
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright © 2007 TUBITAK/UEKAE # Licensed under the GNU General Public License, version 2. # See the file http://www.gnu.org/copyleft/gpl.txt. import os def postInstall(fromVersion, fromRelease, toVersion, toRelease): os.system("chmod 777 -R /opt/TurquazLinux08Beta5/d...
import numpy as np from tqdm import tqdm import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import os import cv2 import matplotlib.pyplot as plt REBUILD_DATA = True class HindiAlphabets(): IMG_SIZE = 50 KA = "C:/Users/Divesh/pytorch proj/Hindi-Alphabet...
import random from lab8.logic import * from lab8.repository import * from lab8.network import NeuralNetwork class Controller: def __init__(self, repo): self.repo = repo self.network = NeuralNetwork(3) def train(self, iterations): points = self.repo.fetchEntries() for i in range...
# Script for scraping website # import Python module to deal with websites import urllib2 # import BeautifulSoup to scrape websites from bs4 import BeautifulSoup # these next lines read the website into BeautifulSoup url = "http://www.house.gov/representatives" page = urllib2.urlopen(url) soup = BeautifulSoup(page) ...
# cards have four fields: # t : type from f', 'm', 'p' (free format, multiple choice, pattern matching) # q : the question they initially present with # a : the correct answer <-- IF MULTIPLE CHOICE THE CORRECT CHOICE GOES HERE # m : the other choices (if multiple choice) # n : any info displayed AFTER the answer is su...
#!/usr/bin/env python3 import dns.resolver import mysql.connector import concurrent.futures import keys def a_lookup(record): try: answers = dns.resolver.query(record, 'A') for ip in answers: return ip except Exception as e: return "0.0.0.0" def main(domain,...
from random import randint import pytest from bson import ObjectId from faker import Faker from pymongo.collection import Collection from module_11.personal_app.db import get_db _FAKE_TASK_ID = str(ObjectId()) fake = Faker() def _get_test_user_collection() -> Collection: db = get_db() user_collection: Coll...
def test__classify_score_with_score_eq_ineligible(calculator): assert calculator._RiskCalculator__classify_score("ineligible") == "ineligible" def test__classify_score_with_score_lt_zero(calculator): assert calculator._RiskCalculator__classify_score(-1) == "economic" def test__classify_score_with_score_eq_z...
from numpy import* nm = array(eval(input("n de matriculas:"))) impar = 0 for i in range(0,size(nm)): if(nm[i] % 2 == 1 ): impar = impar + 1 g2 = zeros(impar, dtype=int) a = 0 for i in range(0,size(nm)): if(nm[i] % 2 == 1): if(a < size(g2)): g2[a] = nm[i] a = a + 1 print(g2)
def 소수판별함수(n) : success = True for t in range( 2, n, 1) : if n%t == 0 : return False return True n = int(input("어떤 수를 판별해줄까요? ")) result = 소수판별함수( n ) if result==True : print("소수입니다.") else : print("소수가 아닙니다.")
from typing import List class Solution: def diffWaysToCompute(self, input: str) -> List[int]: res = [] N = len(input) for i in range(N): if input[i] in "+-*": lefts = self.diffWaysToCompute(input[:i]) rights = self.diffWaysToCompute(input[i+1:]) ...
List = ['chocolate','biscuit','cola','water','noodles','flour','icecream','sugar'] user = { 'user_id' : 101, 'cart' : [] } while True: print('\nMain Menu\n') menu = ['list of items','your cart'] for i in range(len(menu)): print(f"{i+1}.{menu[i]}") print('0.exit') choice = int(input('\nselect an...
from rest_framework import serializers from .models import Item, Notification, Sale, SaleItem, Customer, Report, Staff class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Item fields = ('id', 'code', 'name', 'price', 'quantity', 'warning_quantity', '...
#!/usr/bin/env python # Use joystick input to launch object-tracking nodes in jackal # # Intro to Robotics - EE5900 - Spring 2017 # Assignment #6 # # Project #6 Group #2 # Prithvi # Aswin # Akhil (Team Lead) # # version: v1.3 # define imports import rospy import roslaun...
"""Setup source space. Set up source space for forward and inverse computation. """ from types import SimpleNamespace import mne from ..._config_utils import get_fs_subject, get_fs_subjects_dir, get_subjects from ..._logging import logger, gen_log_kwargs from ..._run import failsafe_run, save_logs, _prep_out_files ...
#coding:utf-8 import sublime, sublime_plugin import json import webbrowser import zipfile import os import threading def is_st3(): return sublime.version()[0] == '3' if is_st3(): import urllib.request import io else: import urllib2 import cStringIO class DriveSelector: def __init__(self, window, callback):...
# Question:- # The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems # branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime. # Input:- # The input...
#!/usr/bin/python """ Date .......: 01/06/2019 Developer ..: Waldirio M Pinheiro (waldirio@redhat.com / waldirio@gmail.com) Purpose ....: Collect information from Satellite Server and show hypervisor versus Content Host - Subscription information """ import sys import datetime import ur...
setpoint = 11 Kp=5 Ki=2 Kd=0.2 DT = 0.02 #Best values ''' 10,5,0.22 ''' #Driver for the LSM303D accelerometer and L3GD20H magnetometer and compass #First follow the procedure to enable I2C on R-Pi. #1. Add the lines ic2-bcm2708 and i2c-dev to the file etcmodules #2. Comment out the line blacklist ic2-bcm2708 (with a #...
import os import datetime import hashlib from nova import app, db from sqlalchemy_utils import PasswordType, force_auto_coercion from itsdangerous import Signer, BadSignature force_auto_coercion() class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Colu...
from astropy.io import fits import numpy as np import matplotlib.pyplot as plt import sys evtorg=sys.argv[1] org=fits.open(evtorg) obsid=evtorg.split('_')[2] orbitno=evtorg.split('_')[3].split('c')[0] noisy_detx=int(sys.argv[2]) noisy_dety=int(sys.argv[3]) fig=plt.figure() for qid in range(1, 5): pixdata=org[qid]....
import time import math import pytest import pleasehold def test_duration(): duration = 5 begin = time.time() with pleasehold.hold(): time.sleep(duration) total = time.time() - begin assert math.isclose(total, duration, rel_tol=0.01)
from flask import Flask, render_template from config import Config from flask_sqlalchemy import SQLAlchemy from flask_mysqldb import MySQL #from flask_migrate import Migrate from flask_babel import Babel, lazy_gettext as _l import json import pandas as pd import numpy as np import os, base64, re, logging Ap...
# This file is used for generating label files in experiments with Caffe. import os images=[] def maketrainList(imageFile, pathFile): fobj = open(pathFile, 'a') for root,dirs,files in os.walk(imageFile): files.sort() for f in files: images.append(f) num = len(images) ...
from unittest import TestCase import unittest.mock from unittest.mock import patch from pygtop.interactions import Interaction, get_all_interactions from pygtop.ligands import Ligand from pygtop.targets import Target import pygtop.exceptions as exceptions import xml.etree.ElementTree as ElementTree class InteractionTe...
#!/usr/bin/python -O import sys from codecs import open def extract(fname): print(fname) try: f = open(fname) except: print('Unable to open ' + fname) return for l in f: if not l: continue for x in l.split('href=')[1:]: if x[0] == '"': x = x[1:].split('"', 1)[0] else: x = x.split()[0] print(x) f...
## Author: Mitch Holley ## Date: 08/30/2016 ## Version: 2.7.8 ## ## This script is meant to be imported into an ArcGIS script. The purpose of the tool is to delete duplicate ## records in a specific field. A checkbox is included in the script to check for duplicate geometries. ## Both a specific field AND t...