text
stringlengths
8
6.05M
import tkinter as tk import tkinter.font as tkFont import easygui from graphSolveGain import SolveFinalGain from graphRender import RenderSignalFlowGraph import Maison import Structs maxNoOfNodes = 20 appName = 'Signal Flow Graph' class App (tk.Frame): def __init__(self, root=None, splashWindow=None): ...
import re def read_common_words(filename): ''' Reads the commmon words file into a set. If the file name is None returns an emtpy set. If the file cannot be opened returnes an empty set: ''' words = set() if filename != None: try: with open(filename) as fp: ...
import numpy from tigger.helpers import * TEMPLATE = template_for(__file__) def find_local_size(device_params, max_workgroup_size, dims): """ Simple algorithm to find local_size with given limitations """ # shortcut for CPU devices if device_params.warp_size == 1: return [max_workgroup_s...
#!/usr/bin/env python # -*- coding: utf-8 -*- class ImplResourceAttributes(object): DESCRIPTION = 'description' DEPRECATED = 'deprecated' RESULT_TYPE = 'result_type' FIELD_DESCRIPTION = 'fields_description'
import simplegui import random import math num_range = 100 # helper function to start and restart the game def new_game(): # initialize global variables used in your code here global allowed_guesses if num_range == 100: allowed_guesses = 7 elif num_range == 1000: allowed_guesses =...
#Python Module: ''' * Modules are used to categorize python code into smaller parts. * A module is simply a python file, where classes, functions and variables are defined. * Grouping similar code into a single file makes it easy to access. Python module advantage: 1. Reusability: Module can be used in some other pyth...
# -*- coding: utf-8 -*- import re, os.path import urllib, urllib2, urlparse, cookielib import string, json def removeDuplicates(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def stripHtml(text): return re.compile(r'(<!--.*?-->|<[^>]*>)').sub('', text)...
import collections with open('news.txt', 'r',encoding='utf-8') as f: line = f.read() #type str token = line.split() token2idx = collections.defaultdict(lambda: -1) for word in token: if word not in token2idx: token2idx[word] = len(token2idx) print(token2idx)
""" Draw a simple, perfectly self-similar tree, ideally using recursion. Each branch splits off into 2 smaller branches, of half the length and 2/3 of the thickness, separated by 30 degrees. Go 6 layers deep. """ import turtle def draw_simple_tree(start_heading, width, length, depth_remaining): turtle.setheading...
import subprocess proc = subprocess.Popen(['echo', 'to stdout'], stdout=subprocess.PIPE) stdout_val, _ = proc.communicate() print 'stdout:', repr(stdout_val) # stdout: 'to stdout\n'
import os import sys import time import braindecode.hyperopt.hyperopt as hyperopt __authors__ = ["Katharina Eggensperger"] __contact__ = "automl.org" import logging def parse_cli(): """ Provide a generic command line interface for benchmarks. It will just parse the command line according to simple rules...
#! /usr/bin/python import pandas as pd import matplotlib.pyplot as plt import numpy as np #c1 S3(cache) #c2 S3(cache) + S4(cache) + S5(cache) #c3 S2(cache) + S3(cache) + S4(cache) + S5(cache) #c4 S2(cache) + S3(cache) + S4-5(cache) #c5 S2(cache) + S3(cache) + S4(cache) + S5(2way-cache) raw_data = {'graph': ['Youtube...
#!/usr/bin/env python import os import re def main(): cleanup_puzzle('easy') cleanup_puzzle('simple') cleanup_puzzle('intermediate') cleanup_puzzle('expert') def cleanup_puzzle(level): file = open('design/puzzles_%s.txt' % level, 'rb') buffer = "" with open('res/puzzles_%s.txt' % level, 'w') as f: ...
from django.contrib.syndication.views import Feed from .models import Post class LatestPosts(Feed): title = "Q Blog" link = "/feed/" description = "Latest Posts of Q" def items(self): return Post.objects.published()[:5] def item_title(self, item): retu...
# Generated by Django 3.1 on 2020-10-16 09:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('theblog', '0011_profile_website_url'), ] operations = [ migrations.RenameField( model_name='profile', old_name='pinterest_url'...
#!/usr/bin/python import os import select class Counters(object): counters = { 'storetokenandreturn' : 4, 'handledata' :5, 'overflow' : 6, 'ignorepacket' : 7, 'sendnakandreti' : 8, 'handlein' : 9, 'handlein1' : 10, 'handlein3' : 11, 'se0' : 12, 'soferror': 13 } def __init__(self,instring): #in...
#!/usr/bin/env python3 import pandas as pd import argparse def crime_corr(target='net'): """correlation of crime rate with number of moves in or out of a ward.""" crime = pd.read_csv("data/Burglary_LAD_2016.csv") migration = pd.read_csv("data/sales_"+target+"_LAD_2016.csv").set_index('lad16cd') migr...
import math x1, y1 = map(float, input().split(' ')) x2, y2 = map(float, input().split(' ')) distancia = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2)) print("{:.4f}". format(distancia))
def part(arr): ap = ["Partridge","PearTree","Chat","Dan","Toblerone","Lynn","AlphaPapa","Nomad"] result = sum([arr.count(x) for x in ap]) if result == 0: return "Lynn, I've pierced my foot on a spike!!" else: return "Mine's a Pint{}".format('!' * result) ''' To celebrate today's launc...
#!/usr/bin/env python # # Sample Usage: # # ./m2o-analysis.py enw.words.gz enw.pos.gz # # > perp>1.75 # # dance 1.75 12 # # Crowd 1.75 8 # # meltdown 1.75 4 # # Personnel 1.75 4 # # ... # # > # # from collections import defaultdict as dd import gzip from itertools import izip import math import re import sys def read...
from settings import settings from tests import random_seed from tests.graph_case import GraphTestCase from office365.directory.user import User from office365.directory.userProfile import UserProfile class TestGraphUser(GraphTestCase): """Tests for Azure Active Directory (Azure AD) users""" test_user = Non...
""":mod:`bikeseoul.web.user` --- User pages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ from flask import Blueprint, render_template, request from ..station import Station from .db import session bp = Blueprint('user', __name__) @bp.route('/') def home(): """Home.""" stations = session.query(Station)....
import cv2 from PIL import Image from io import BytesIO import numpy as np from multiprocessing import Process, Array, Value from time import sleep as bsleep from time import time from asyncio import sleep, get_event_loop from loguru import logger TARGET_FPS = 15 TARGET_FRAMETIME = 1 / TARGET_FPS MAX_W, MAX_H = MAX_RE...
#! /usr/bin/python # -*- coding: utf-8 -*- class DBMetadata: def __init__(self, connection, executor): self.connection=connection self.executor=executor class Datos: def __init__(self,name,lastname,phone,email): self.name=name self.lastname=lastname self.phone=phone self.email=email
#!/usr/bin/python import os.path import datetime import ipaddress import subprocess import csv import ipwhois import re from ipwhois import IPWhois from pprint import pprint from IPy import IP # Pre-condition: Ran ZMAP to scan internet: # zmap -p 80 -o results.csv -b blacklist.txt -t 7200 # --output-filter="success =...
n = int(input()) print(n // 2, '\n', '2 ' * (n // 2 - 1), 2 + n % 2, sep='')
# you'll notice that after we generate a list of media files from the conversion of Wiki pages to static pages, there are tons of duplicates. # we'd like to regenerate the list so that no duplicates are included # script should only take about 0.1 seconds to complete infilename = 'lists/listInfoBoxImgs.txt' outfilenam...
import os from filelock import FileLock def check_if_exists(path): if not os.path.exists(path): os.makedirs(path) return path here = os.path.dirname(__file__) data_dir = check_if_exists(os.path.join(here, '../../data')) locks_dir = check_if_exists(os.path.join(here, '../../locks')) trajectories_dir = os.pat...
""" Train a supervised classifier based on an IQR session state dump. Descriptors used in IQR, and thus referenced via their UUIDs in the IQR session state dump, must exist external to the IQR web-app (uses a non-memory backend). This is needed so that this script might access them for classifier training. Getting an...
#Quiz Two Part Two #I pledge my honor that I have abided by the Stevens honor system -Maya O def main(): print("Hello!") print("Please enter 1 if you would like to access the mathematical funtions") print("Please enter 2 if you would like to access the string operations") m = int(input("Choice: ")) ...
''' Created on Jan 24, 2016 @author: Andrei Padnevici @note: This is an exercise: 12.2 ''' import re import urllib.parse import urllib.request import validators addressStr = str(input("Enter address: ")) if addressStr is "" or addressStr is None: addressStr = "http://www.py4inf.com/code/romeo.txt" addressStr = a...
import random from model.vehicle_handling.vehicle import Enemy from model.vehicle_handling.collision_and_boundaries import check_all_collision import global_variables as gv spawn_rate = 40 # higher is a lower spawn_rate spawn_max = 20 def spawn_chance(vehicles, movement_pattern="random", x=None, y=None, w=gv.ENEMY_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 24 08:08:28 2019 @author: imad """ from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import Perceptron from sklearn.metrics import accuracy_s...
""" Canned response for fastly """ from __future__ import absolute_import, division, unicode_literals import random import string import uuid class FastlyResponse(object): """ Canned response for fastly. See docs here https://docs.fastly.com/api/config """ fastly_cache = {} def get_current...
from django.urls import path from .import views urlpatterns = [ path('', views.index, name='home'), path('posts/<str:category_name>/', views.post_list, name='post_list'), ]
"""Created by nasim zolaktaf, 2019 This file plots the MSE vs iteration, (such as fig 4 and fig 5 of the paper). To run this file, first run map.py to do parameter estimation once with FPEI, once with SSAI and to generate neccessary files. Then in this file set dc1 and dc2 to correct flies. Run 'plot_ssavsFPE...
from django.shortcuts import render, get_object_or_404, redirect from .models import Person from . import models from django.views.generic import View,TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView # from .forms import PersonForm from . import forms def homepage(request): return render(request,...
# # Copyright © 2021 Uncharted Software Inc. # # 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 l...
from __future__ import absolute_import import math import torch from torch import nn from torch.nn import functional as F from torch.nn import init from torch.autograd import Variable import torchvision # from torch_deform_conv.layers import ConvOffset2D from reid.utils.serialization import load_checkpoint, save_check...
from sklearn.metrics import roc_curve, auc import json import numpy as np import pandas as pd from sklearn.preprocessing import MultiLabelBinarizer import os import pdb import matplotlib.pyplot as plt outputs = pd.read_csv('validation_outputs.csv') mean_out = np.mean(outputs.values) print(mean_out) print(max(outputs....
from django.contrib.auth.models import User, Group from rest_framework import viewsets from .models import Record, List from .serializers import UserSerializer, GroupSerializer, RecordSerializer, ListSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edite...
""" Http API for the mypaas daemon. """ import os import io import time import queue import shutil import logging import datetime import asyncio import zipfile from mypaas.server import get_deploy_generator, get_public_key logger = logging.getLogger("mypaasd") # Fix encoding os.environ.setdefault("LC_ALL", "C.UTF-...
class BoundingBox: def __init__(self): pass def createFromPoints(self): pass
from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=64) surname =models.CharField(max_length=64) description = models.TextField() class Adress(models.Model): city = models.CharField(max_length=64) street = models.CharField(max_le...
# -*- coding: utf-8 -*- class Solution: def defangIPaddr(self, address): return address.replace(".", "[.]") if __name__ == "__main__": solution = Solution() assert "1[.]1[.]1[.]1" == solution.defangIPaddr("1.1.1.1") assert "255[.]100[.]50[.]0" == solution.defangIPaddr("255.100.50.0")
import json from sqlalchemy import create_engine, pool from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.orm import sessionmaker from chalicelib.config.settings import (ENV, PROD, DATABASE) class ConferenceDatabaseConnection: ENGINE = None @staticmethod def engine(default_database=...
import functools from flask import ( Blueprint, redirect, render_template, request, session, url_for, flash, g ) from werkzeug.security import check_password_hash, generate_password_hash from ISRS.model import db, User from ISRS.color import colors bp = Blueprint('auth', __name__, url_prefix='/auth') @bp.route('/...
import random magic_number = random.randrange(1,10,1) cont = 0 play = input("Wanna guess the number? (yes/no) ") if (play == 'no'): print("The times you try where: " + str(cont)) else: while (play != 'exit'): guess = int(input("Give me a number:")) if (guess > magic_number): cont += 1 print ("Your number...
from __future__ import division, print_function import numpy as np import tensorflow as tf from vgg19.vgg import Vgg19 from PIL import Image import time from closed_form_matting import getLaplacian import math from functools import partial import copy import os # try: # xrange # Python 2 # except NameErr...
import pandas as pd import numpy as np def build_q_table(n_states, actions): # q_table 全 0 初始 # columns 对应的是行为名称 table = pd.DataFrame(np.zeros((n_states, len(actions))), columns=actions, ) return table acs = ['l', 'r'] q = build_q_table(10,acs) q.iloc[3, 0] = 0.1 q.iloc[3, 1] = 0.9 d1 = q.iloc[3,:]...
array = [1, 1, 1, 1, 1] for i in range(len(array)): if i%2 != 0: array[i] = 0 print(array)
# encoding: utf-8 from src.config import AnnoyConfig from src.utils import singleton import logging.config import logging from annoy import AnnoyIndex import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../')) logging.config.fileConfig(fname='log.config', disable_existing_loggers=False) #...
from random import shuffle aluno1 = str(input('Digite o nome do Aluno 1:')) aluno2 = str(input('Digite o nome do Aluno 2:')) aluno3 = str(input('Digite o nome do Aluno 3:')) aluno4 = str(input('Digite o nome do Aluno 4:')) lista = [aluno1, aluno2, aluno3, aluno4] shuffle(lista) print('A ordem de Apresentação será:') pr...
# -*- coding: utf-8 -*- from .utils import SlotDefinedClass, merge_dicts from .defaults import BASE_INDENT_SIZE class Type(SlotDefinedClass): __slots__ = ("name", ) __types__ = {"name": str} def __str__(self): return self.name def __eq__(self, other): return isinstance(other, Type) ...
import numpy as np print("Input n:") n = int(input()) a = np.array([[i+j for i in range(n)] for j in range(n)]).reshape(n, n) print(a)
import copy import math # This class is used to store a move. class Move: def __init__(self, the_place_board: int, the_position: int, the_twist_board: int, the_direction: str): self.place_board = the_place_board self.position = the_position self.twist_board = the_twist_board self.d...
import logging import random from fastapi import APIRouter import pandas as pd from pydantic import BaseModel, Field, validator log = logging.getLogger(__name__) router = APIRouter() @router.post('/healthCheck') async def healthCheck(): """ Returns 200 for a healthcheck for AWS """ return {'ok'}
#!/usr/bin/python3 def best_score(a_dictionary): maximo = 0 llave = "" if a_dictionary is None or len(a_dictionary) == 0: return None else: for clave, valor in a_dictionary.items(): if valor > maximo: llave = clave maximo = valor return...
#!/usr/bin/python3 """ module containts unittests for our console """ import unittest import json from .models.base_model import BaseModel from .models.engine.file_storage import FileStorage class testconsole(unittest.TestCase): """ unittests for console """ def test_created_console(self): """ Dat...
import os import pickle from copy import deepcopy from util import * class Client(object): def __init__(self, torrent, args): self.save_path = os.path.join(args.save_path, os.path.basename(os.path.splitext(args.torrent_path)[0])).encode() if not os.path.exists(self.save_path): os.make...
from django.shortcuts import get_object_or_404, render from django.urls import reverse_lazy from django.views.generic import ListView, CreateView, UpdateView, DeleteView from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.db.models import Q from .form import GiftForm from .filters impo...
import time x1=int(input("Please enter the x-xordinate of point 1 :")) y1=int(input("Please enter the y-xordinate of point 1 :")) x2=int(input("Please enter the x-xordinate of point 2 :")) y2=int(input("Please enter the y-xordinate of point 2 :")) print("Calculating mid-points ...") point_x=(x2+x1)/2 point_y=(y2+y1)/...
import matplotlib as mpl import pandas as pd # https://www.tensorflow.org/tutorials/structured_data/time_series mpl.rcParams['figure.figsize'] = (8, 6) mpl.rcParams['axes.grid'] = False df = pd.read_csv("jena_climate_2009_2016.csv") print(df) # TS 10 min )> 1 hour df = df[5::6] # Replace -9999 => 0 wv = df['wv (m/...
""" Train and generate models for the SMQTK IQR Application. """ import argparse import glob import json import logging import os.path as osp import six from smqtk import algorithms from smqtk import representation from smqtk.utils import bin_utils, jsmin, plugin __author__ = 'paul.tunison@kitware.com' def cli_pa...
#!/usr/bin/env python3 from time import sleep, monotonic, process_time, time from ctypes import CDLL from sys import stdout, stderr, argv, exit def mlockall(): """ """ MCL_CURRENT = 1 MCL_FUTURE = 2 MCL_ONFAULT = 4 libc = CDLL('libc.so.6', use_errno=True) libc.mlockall(MCL_CURRENT | MCL_F...
import unittest import numpy as np from core.game import Game from core.player import Player from core.turn import Turn class GameTest(unittest.TestCase): def test_game_state_is_empty_for_new_game(self): game = self.create_game() empty_matrix = np.matrix('0 0 0; 0 0 0; 0 0 0') assert (gam...
""" author songjie """ from flask import render_template from app.api import api from app.libs.email import send_test from app.libs.reply import Reply from tool.lib.function import curl_data, debug @api.route('/test') def test(): data = {"title": "测试页"} return render_template("test/test.html", data=data) @...
#!/usr/bin/env python3 import inspect global debugging debugging = False #debugging = True def err(msg): print("Error: {0}(): {1}".format(inspect.stack()[1][3], msg)) def show(*s): """Print but only when debugging""" if debugging: print(*s) def test_func(function, outputs, *inputs): """Test...
import numpy as np import pandas as pd import pylab as pl import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier %matplotlib inline df = pd.read_csv("https://s3.amazonaws.com/demo-datasets/wine.csv") df.head() test_idx = np.random.uniform(0, 1, len(df)) <= 0.8 train = df[test_idx==True] te...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Imports import torch import random from IPython.display import clear_output from glob import glob import pandas as pd cuda = torch.cuda.is_available() import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Rectangle import sys import os import...
s, sub, x = input(), input(), 0 for i in range(len(s)): if s[i:i+len(sub)] == sub: x += 1 print(x)
from sqlite3 import connect db_name = ":memory:"
from datetime import datetime from datetime import timedelta from django.shortcuts import render, redirect from django.core.paginator import Paginator from django.db.models import Count from django.core.mail import send_mail from django.contrib import messages from django.urls import reverse from django.http import Ht...
# Copyright 2017 The Forseti Security Authors. 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 ap...
# -*- coding: utf-8 -*- from flask import Blueprint, render_template, request star = Blueprint('star', __name__) @star.route('/<name>/<reponame>/star', methods = ['POST']) def index(): return render_template('')
import tarfile import os import sys import pickle #import tensorflow as tf from datetime import datetime from multiprocessing import Pool import getopt from itertools import repeat nr_of_cpus = 16 def get_all_tar_filenames(tar_file_dir): tar_files = list() ### check if dir exists if not os.path.isdir...
# -*- coding: utf-8 -*- import webapp2 import cgi import logging import datetime from webapp2_extras import json from google.appengine.api import users from config import jinja_enviroment from models import * class MainHandler(webapp2.RequestHandler): def __init__(self, request, response): self.initiali...
# Simple CNN model for CIFAR-10 import numpy as np from keras.datasets import cifar10 from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.constraints import maxnorm from keras.wrappers.scikit_learn import KerasClassifier from ke...
#Este está bien print('while loop') fruit = 'banana' index=0 while index < len(fruit): print(index,fruit[index]) index=index+1 #pero siempre un for funciona mejor print('for loop') for letter in fruit: print(letter) #slicing avanza hasta tonde le digamos pero no incluye complete = 'Richard' slice1=complet...
from itertools import permutations from time import time from GenerateDict import GenerateDict # Function: CombineLetters # Dependency: itertools.permutations # Input: a list such as ['a', 'b', 'c'] # Output: a set such as {'ab', 'bac', 'b', 'c', 'acb', 'ca', 'bc', 'cb', 'cba', 'ba', 'bca', 'ac', 'cab', 'abc', 'a'} # ...
import io import random import aiounittest import itchat from collections import namedtuple from forklift.config import STICKERS_FOR_SPAM, ANIMATED_QUERY_TYPE from forklift.util import get_file, match_query_from_text, is_spam_msg class TestUtil(aiounittest.AsyncTestCase): async def test_get_file(self): fi...
t = int(input()) area = [] for i in range(t): n,b = input().split() n,b = int(n),int(b) area.append(0) for j in range(n): l,h,p = input().split() l,h,p = int(l),int(h),int(p) if(p<=b) and (l*h>=area[0]): area[i]=(l*h) for i in range(t): if(area[i]==0):...
import sys import re n=input() if(re.match('[0-9]{2}[A-Za-z]{3}[0-9]{4}',n)): print("valid") else: print("invalid")
import pandas as pd import copy import random def combine_interval_points(fun_result, data, just_first_one=False): if len(fun_result) == 0: return fun_result # combine need_combine = [] inter = [] len_fun_result = len(fun_result) for index, i in enumerate(fun_result[:-1]): if f...
from pyxnat import Interface def get_XNAT(username, password, xnat_cache, xnatUrl='https://xnat.hdni.org/xnat'): xnat = Interface(server=xnatUrl, user=username, password=password, cachedir=xnat_cache) return xnat
from kivy.app import App from kivy.uix.button import Button from kivy.uix.textinput import TextInput class TestApp(App): def build(self): return Button(text='Hello World') def on_enter(instance, value): print("User pressed enter in", instance) textinput = TextInput() textinput.bind(te...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 28 17:02:27 2021 @author: kaydee """ import flask from flask import Flask, redirect, url_for, request, render_template, send_file from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage import os from Alignment imp...
from pupil_parse.preprocess_utils import config as cf from pupil_parse.preprocess_utils import extract_session_metadata as md from pupil_parse.preprocess_utils import edf2pd as ep from pupil_parse.preprocess_utils import visualize as vz from pupil_parse.analysis_utils import summarize_amplitude as amp import time i...
#### Takes bilstm model and evaluates it on an eval file ## ## Usage: ./evaluate_taggingmodel.py PATH_TO_MODEL PATH_TO_EVAL_FILE from simplebilty import SimpleBiltyTagger from simplebilty import load_tagger, save_tagger from lib.mio import read_conll_file from vocab import Vocab import os from collections import nam...
from storm.locals import * class Node(Storm): __storm_table__ = "node" id = Int(primary=True) identifier = Unicode() properties = ReferenceSet(id, "NodeProperty.node_id") inbound = ReferenceSet(id, "Edge.target_id") outbound = ReferenceSet(id, "Edge.source_id") def __repr__(self): ...
#!/usr/bin/python import smbus import time import math bus = smbus.SMBus(1) address = 0x1e mpu6050address = 0x68 def read_byte(adr): return bus.read_byte_data(address, adr) def read_word(adr): high = bus.read_byte_data(address, adr) low = bus.read_byte_data(address, adr+1) val = (hi...
# BABY QUAKEBOT! # # https://source.opennews.org/en-US/articles/how-break-news-while-you-sleep/ # # # This is a python file, so you're going to run them from the # command line by going to the folder it's in and running this terminal # command... # # python eq_homework.py # # Then a little magic will happen! Unfortu...
num =1 num2 = 233 num3 = 433 lulala num4 = 2344455 num5 = 234567
def soma(L): total = 0 for e in L: total += e return total L=[1,7,2,9,15] print(soma(L)) print(soma([7,9,12,3,100,20,4]))
#!/usr/bin/env python # -*- coding: utf-8 -*- # # weather_for_conky.py # same as weather.py, but small fix for static location and print to use with conky # # Copyright 2013 Raymond Aarseth <raymond@lappy> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU ...
""" Brazil Data Cube Configuration You can define these configurations and call using environment variable `ENVIRONMENT`. For example: `export ENVIRONMENT=ProductionConfig` """ # pylint: disable=too-few-public-methods import os BASE_DIR = os.path.abspath(os.path.dirname(__file__)) def get_settings(env): """Re...
import daft import jax import jax.numpy as np import mcx import mcx.distributions as dist from matplotlib import rc from IPython.display import display, Math from infer.model import Model class NaiveBayes(Model): """Naive Bayes classifier. We note :math:`x_{jc}` the value of the j-th element of the data vec...
import unittest from katas.kyu_7.discover_the_original_price import discover_original_price class DiscoverOriginalPriceTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(discover_original_price(75, 25), 100) def test_equal_2(self): self.assertEqual(discover_original_price(...
from collections import namedtuple n = int(input()) student = namedtuple('student', input()) print('{:05.2f}'.format(sum(map(lambda x: int(x.MARKS), [ student(*input().split()) for i in range(n)])) / n))
import xml.etree.ElementTree as ET from django.core import serializers from django.shortcuts import render,redirect from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import Aparcamiento, AparcaSeleccionado, Comentario, Css from django.contrib.auth import logout, logi...