text
stringlengths
8
6.05M
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> import copy import ast from util import debug from walker import NodeWalker from liveout ...
import pygame # Constantes de jeu MAX_TIRS = 5 # nombre maximum de boulets sur l'ecran MAX_ALIEN = 3 PROBA_ALIEN = 17 # probabilité qu'un alien apparaisse PROBA_HEAL = 95# probabilité qu'un heal pack apparaisse NOUVEL_ALIEN = 12 # Rafraichissement de l'ecran entre chaque alien ECRAN = pygame.Rect(0, 0, 1750,900) S...
try: txt = input('Text something: ') num = int(txt) except ValueError as e: print(e) except EOFError: print('You did EOF') else: print('You input:' + txt) finally: print('The End')
from django.core.management.base import BaseCommand from django.conf import settings import boto3 import botocore import os class Command(BaseCommand): help = "backs up the current sqllite db on an s3 bucket" def handle(self, *args, **options): # get database db_file = os.path.abspath(settings....
side = 5 Area = (22/7)*side*side print "Area of circle is %s", %Area
from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate import json from datetime import datetime from guardian.shortcuts import assign_perm from django.shortcuts import render from djan...
from numpy import * from sigmoid import sigmoid def sigmoidGradient(z): # SIGMOIDGRADIENT returns the gradient of the sigmoid function evaluated at z g = zeros(z.shape) # =========================== TODO ================================== # Instructions: Compute the gradient of the sigmoid function e...
from .neuralnet import neuralnet from .io import * import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc from itertools import cycle from optparse import OptionParser from itertools import cycle import random #Setting options for arguments parser = OptionParser() parser.add_opt...
import cv2 cap = cv2.VideoCapture(0) # cap.set(cv2.CV_CAP_PROP_FPS, 10) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 640) while True: ret , inputImage = cap.read() cv2.imshow(' frame ' , inputImage) if cv2.waitKey(1) & 0xFF == ord ( 'q'): break # cv2.imwrite("outpu...
import math from util import create_array class DCT(object): N = 8 QUALITY = 80 QUANTUM_LUMINANCE = [ 16, 11, 10, 16, 24, 40, 51, 61, 12, 12, 14, 19, 26, 58, 60, 55, 14, 13, 16, 24, 40, 57, 69, 56, 14, 17, 22, 29, 51, 87, 80, 62, 18, 22, 37, 56, 68, 109, 103, 77, 24, 35...
import sys from PyQt5.QtWidgets import QWidget, QApplication, QPushButton from PyQt5.QtCore import QThread class Loop(QThread): def run(self): while True: print("Estamos no loop") class MainWindow(QWidget): def __init__(self, parent=None): super(MainWindow, self).__init__() ...
class Library(object): def __init__(self): self.shelf_list = [] self.book_list = [] def callShelf(self): print "The shelves are categorized by: " for x in self.shelf_list: print x print "for a total of ", len(self.shelf_list), "shelves in the library." def callBook(self): print "The books that we cu...
#!/usr/bin/env python3 # Created by: Luke Beausoleil # Created on: May 2021 # This program finds the sum of all integers from 1 - an inputted number def main(): # this function finds the sum of the integers # variables loop_counter = 0 sum_of_integers = 0 # input number_as_string = input("E...
class Attr: file_name = list() file_attr = list() def __init__(self): f = open('list_attr_img.txt', 'r') self.lines = f.readlines()[2:] def parsing(self): for line in self.lines[:200]: line = line.rstrip('\n') jpg_position = line.find('jpg') ...
from subprocess import Popen, PIPE import paramiko import time import sys import getopt from getpass import getpass from Options import Options from Processing.Steps import * def stochastic_snapshot(snapshot_number, starting_round, n_round, table, probing_rate, options): ''' Entire routine :return: '''...
# If you add a new network you should append the network name and the object related from networkNames import * from Aeronet import * from Ceilometer import * # from Conaf import * from DMC import * from eSampler import * from LaObra import * from McPhee import * from MeteoCamp import * from MMA import * ...
from django.urls import include, path from . import views app_name = 'riddles' urlpatterns = [ path('', views.index, name='index'), path('category/<int:pk>/', views.category, name='category'), path('type/<int:pk>/', views.riddle_type, name='type'), path('riddle/<int:pk>/', views.riddle, name='riddle...
#!/usr/bin/python import sys, re if len(sys.argv) == 1: sys.stderr.write("Usage: " + sys.argv[0] + " Not enough arguments") exit() elif len(sys.argv) > 3: sys.stderr.write("Usage: " + sys.argv[0] + " Too many arguments") exit() elif not re.match(r'^[0-9]+$', sys.argv[1]): sys.stderr.write("UsageL ...
#! /usr/bin/env python3 import os from glob import iglob from collections import defaultdict # data # resum part resum_part = ['lumi0', 'lumi1', 'lumi', 'll', 'nll', 'nnll', 'nllexpd', 'nnllexpd'] # Higgs processes Higgs_case = ['WHbbar', 'ZHbbar', 'qq_tth', 'tottth', 'HWW_4l', 'HWW_tb', 'HWWint', 'HWWHpi', 'ggWW4l...
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import mock from oauth2py.client import OauthClient class TestTwitter(unittest.TestCase): def setUp(self): self.config = { 'name': 'twitter', 'client_id': '1234567', 'client_secret': 'secret_abcefg', ...
from bfimpl.bfunc import generateId PATTERN = """//Start:Declarations Mat cv_close_%ID%(%ARGS%); //Stop:Declarations //Start:Definitions Mat cv_close_%ID%(%ARGS%) { Mat result; morphologyEx(arg1, result, MORPH_CLOSE, arg1); return result; } //Stop:Definitions """ def generate(n): identification = g...
def makeVerbDictionary(fileName): verbDict = dict() lines = [] with open(fileName) as tagged_file: lines = tagged_file.readlines() for i in range(0, len(lines)): # print lines[i] if lines[i].rstrip("\n").strip(" ") == "<vc>": for j in range(i + 1, len(line...
#_*_coding:utf-8_*_ from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$','apps.kx.tongji.views.tongji',name='tongji'), url(r'^tongji/$','apps.kx.tongji.views.tongji',name='tongji'), url(r'^record/?$','apps.kx.api.views.record'), url(r'^lan_record/?$','apps.kx.api.vie...
import pandas as pd from flask import current_app from models import Base from models import User def __find_and_add_new_rows(connection, new_rows_dataframe): current_app.logger.info(' - Adding new rows to master table') new_rows_dataframe = new_rows_dataframe.where(pd.notnull(new_rows_dataframe), None) ...
#!/usr/bin/python3 # -*- encoding: utf-8 -*- ''' @File : testxshell.py @Time : 2018/11/24 10:32:59 @Author : BaiYang @Version : 1.0 @Contact : yang01.bai@horizon.ai @License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA @Desc : 交互式xshell ''' import socket import sys import paramiko has_termio...
from config import cfg import yaml import os def generate_surahs(): surahs_file = open(cfg['directory']['surahs_mapping']) surahs_yaml = yaml.safe_load(surahs_file) surahs = [surah for surah in surahs_yaml['surah_name']] return surahs def generate_qari(): qari_name = os.listdir(cfg['directory'][...
def maxGameByWinner(N): dp = [0 for i in range(N)] dp[0] = 1 dp[1] = 2 i = 1 while dp[i] <= N: i = i + 1 dp[i] = dp[i - 1] + dp[i - 2] return (i - 1) N = 10 print(maxGameByWinner(N))
################################################################################ # Copyright (c) 2021 ContinualAI. # # Copyrights licensed under the MIT License. # # See the accompanying LICENSE file for terms. ...
from django.contrib import admin from .models import Article, Comment # Register your models here. class ArticleAdmin(admin.ModelAdmin): fieldsets = [ ('Title', {'fields':['title']}), ('Author', {'fields':['author']}), ('Category', {'fields':['category']}), ('Publication Date', {'fields':['pub_date']}), ('B...
__author__ = 'lpa' import MySQLdb import SQLDataCollector import RedmineFormatter print "script started" #TODO externaliser les parametres de connection a la base connection = MySQLdb.connect(host="localhost",db="ac_job",user="root",passwd="") data = SQLDataCollector.MySQLData(connection) table_comment_list = data...
#!/usr/bin/env python # encoding:utf-8 import asyncio import requests import time async def download(url): """ 同步函数,加上async关键字,宣称为awaitable :param url: :return: """ response = requests.get(url) print(response.text) async def wait_download(url): """ 包装同步函数为一个原生的协程对象,等待同步函数完成 ...
#! /usr/bin/env python # -*- encoding: UTF-8 -*- """Main class to handle the Vasttrafik application""" import qi import time import sys import argparse import os import paramiko import threading from scp import SCPClient from Applications.Vasttrafik import Vasttrafik IP = "192.168.1.102" class HumanGreeter(object)...
from datetime import datetime ,date,timedelta # get current date def print_today(): today = date.today() dstr = 'Today is {0}. Have a good time, sir!'.format(today.strftime("%Y-%m-%d, %A")) print(dstr) def date_guardian(d): '''check if d belongs to datetime.date, if not try to convert it. Re...
__author__ = 'chen' import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import scipy.io as sio def getData(): labelName = ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp....
import requests from bs4 import BeautifulSoup import json from urllib import request, parse import pandas as pd import os import time import shutil import csv from pprint import pprint #把目標資料夾所有csv轉成json Folder_Path = r'E:\csv' #要拼接的所有文件 SaveFile_Path = r'E:\json' # 保存路徑 os.chdir(Folder_Path) #換工作路徑 f...
import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib from scipy import signal import seaborn as sns import glob DATAPATH='/media/jeonghn/C684587984586E45' train_labels=pd.read_csv(DATAPATH+'/data/train.csv') train_labels.head() print(f"Total segment files: {len(train_labels['segmen...
from django.apps import AppConfig class YoutubeflowConfig(AppConfig): name = 'YoutubeFlow'
def jisuan(): a = 7 L=[] for x in range(1,100): for n in range(1,100): if ((7*x)-(26*n) == 1): L.append(x) print(L[0]) jisuan()
# coding: utf-8 """ NiFi Rest API The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, ...
import logging import sys import datetime import time from pathlib import Path Path('logs/').mkdir(parents=True, exist_ok=True) timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d_%H%M%S') file_handler = logging.FileHandler(filename=('logs/test_{}.log'.format(timestamp))) stdout_handler = loggin...
# Generated by Django 2.2.6 on 2019-10-25 22:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('techei', '0027_auto_20191025_2008'), ] operations = [ migrations.AlterField( model_name='eventmodel', name='end_date...
#'Enter two numbers and divide them with a comma. #Second number will be added that many time as the first numbers value. first = eval(input('Enter first number:')) second = eval(input('Enter second number:')) x = first y = second print(x*y)
import os import pytest from day_4 import main current_dir = os.path.dirname(os.path.abspath(__file__)) test_input_file = os.path.join(current_dir, 'test_input.txt') test_input_file_simple = os.path.join(current_dir, 'test_input_simple.txt') def test_transform_data(): expected_list = [ {"ecl": "gry", ...
import os import subprocess import json from config import torrent_path items = [] def dl_torrent_file(torrent_url): owd = os.getcwd() os.chdir(f"{owd}/scripts/dl_torrent_from_ygg/parse_ygg/ygg") subprocess.call(["scrapy", "crawl", "ygg", f"-a torrent_url={torrent_url}"]) os.chdir(owd) item_file...
import subprocess import os PATH_TO_THIS_DIR = os.path.dirname(os.path.abspath(__file__)) FLAMEGRAPH_PL = os.path.join(PATH_TO_THIS_DIR, 'flamegraph.pl') def stats_to_svg(stats): proc = subprocess.Popen( args=[FLAMEGRAPH_PL, '--title', ' '], stdout=subprocess.PIPE, stdin=subprocess.PIPE,...
# Copyright 2016 Husky Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
import pandas as pd import pickle import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from sklearn.preprocessing import MinMaxScaler from sklearn import...
import time from ulugugu import drawings, vec2 from ulugugu.events import ACK from ulugugu.widgets import Widget, WidgetWrapper from ulugugu.utils import cursor_over_drawing class DebugBoundingBox(WidgetWrapper): def get_drawing(self): return drawings.DebugBoundingBox(super().get_drawing()) class MouseoverWid...
''' Name: Darius Sandford and Brandon Dickens Date Assigned: 02-22-2018 Course: 1384 Sec 11 Date due: 02-22-2018 File Name: feetInchesTest.py Description: A program to test the class. ''' from FeetInches import FeetInches def main(): ...
WORLD = 'World'
cost = float(input("Enter the cost of the item in dollars: ")) money = float(input("Enter the amount of money you have paid: ")) change = cost - money q = 0 d = 0 n = 0 p = 0 while q < change: q += 0.25 if q > change: q -= 0.25 break change -= q while d < change: d += 0.10 if...
from msedge.selenium_tools import EdgeOptions from msedge.selenium_tools import Edge opts = EdgeOptions() opts.use_chromium = True opts.add_argument("--log-level=3") browser = Edge(executable_path=r"C:\Users\atharv\Documents\Python\webdrivers\edgedriver_win64\msedgedriver.exe", options=opts) browser.set_window_size...
from orm_classes import sess from flask import session, request, jsonify from orm_classes import Users from app import cfapp @cfapp.route('/_update_basemap_pref', methods=['GET']) def update_basemap_pref(): basemap = request.args.get('basemap', 0, type=int) v = sess.query(Users).filter_by(userid=session['user...
from django.db import models class Professor(models.Model): nome = models.CharField(max_length = 100) notaCat1 = models.FloatField(default = 0) notaCat2 = models.FloatField(default = 0) notaCat3 = models.FloatField(default = 0) numVotos = models.IntegerField(default = 0) media = models.FloatField(default = 0) a...
from string import Template import subprocess import sys import os # Games will be generated in `experiments/experiment_name/games` # Config files will be generated in `experiments/experiment_name/configs` # Train scripts will be generated in `experiments/experiment_name/scripts` try: model_name = sys.argv[1] ...
from datetime import date def GetDays(date1, date2): splittedDate1 = date1.split(',') splittedDate2 = date2.split(',') date_obj1 = date(int(splittedDate1[0]), int(splittedDate1[1]), int(splittedDate1[2])) date_obj2 = date(int(splittedDate2[0]), int(splittedDate2[1]), int(splittedDate2[2])) # print(...
# -*- coding: utf-8 -*- { 'name': 'Filter Supplier', 'version': '1.0', 'category': 'Res Partner', 'author': 'Econube | Jose Pinto, Pablo Cabezas', 'summary': 'Gestor de filtros', 'description': """ For personalize filters. """, 'depends': ["base","account",...
from BetterSudoku import BetterSudoku class MinimumValueSudoku(BetterSudoku): def __init__(self, line, verbose=False): BetterSudoku.__init__(self, line, verbose) self.available=list() complete=set(range(1,self.n+1)) for i in range(self.n*self.n): forbidden=set(self.forbidden[i]) self.available.append(...
from django.shortcuts import render, redirect from .models import Candidato from human_resources.models import Puesto from .forms import CandidateForm, ExperienciaForm def new_view(request): if request.method == 'POST': form = CandidateForm(request.POST) if (form.is_valid()): form.s...
from django.test import TestCase class DRFJSONAPITests(TestCase): def test_settings(self): """ Test that the tests run. """ self.assertTrue(True, 'Test environment has wrong settings')
# Some data work # Tuples # - fixed sized # - immutable # - elements can contain mutable objects like list, other tuples etc. # creating a tuple tpl = 1,2,5,6 print(tpl) # printing out how many 2s exist in our tuple print(tpl.count(2)) # unpacking tupple x, y, z, t = tpl print("Our tupple is unpacked:") prin...
# # Stat hook module # # This module is responsible for maintaining execution stats of # strategies included in a plan. All hooks are stateless by # design. But most hooks except for the most trivial needs to # maintain some data during plan execution, such as this one. # Hook data is stored in the plan as hook attribu...
""" Created on Tue Apr 14 18:10:04 2020 @author: Sivaraman Lakshmipathy """ from textProcessor import * from mrr import * class pagerank: #class to build word graph and perform page rank on individual documents pos_list = ["NN", "NNS", "NNP", "NNPS", "JJ"] #valid pos tags alpha = 0.85 beta = 0 no_of_...
import webbrowser from datetime import datetime import time file = open('ZoomLinks.csv', 'r') # Read and print the entire file line by line lst = [] while True: mydata = file.readline() if mydata == "": break mydata = mydata[:-1] if mydata[-1] == '\n' else mydata lst.append(mydata)...
#! /usr/bin/env python3 """ Utility script: find the module corresponding to the problem number given on the command line, then execute its doctests. """ import argparse import doctest from importlib import import_module # set up terminal printing WARN = '\033[93m' GREEN = '\033[92m' RED = '\033[91m' END_COLOR = '\0...
from E160_config import * from E160_state import * from E160_PF import * from E160_UKF1 import * from E160_MP import * import math import datetime import time import random CONFIG_PARTICLE_FILTER = "PF" CONFIG_UNSCENTED_KALMAN_FILTER = "UKF" CONFIG_FILTER = CONFIG_UNSCENTED_KALMAN_FILTER TEST_PATH_1 = [E160_state(0...
from sklearn import * from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error,r2_score,accuracy_score from matplotlib.pyplot import * import matplotlib.pyplot as plt import numpy as np X,Y=datasets.make_regression(n_samples=200,n_features=1,n_targets=1,random_state=0,noise=4.0) X_tra...
#Print each item in teh following list: #["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]. shows = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] for show in shows: print(show)
#!/usr/bin/env python3 """NCC Performance Analyser API to ElasticSearch coupler""" import os from setuptools import setup setup( name='ncc_paapi', version='0.0.8', description='Abstraction classes to access the PA API', author='NCC Group', license="Apache License 2.0", packages=['paapi'], ...
# -*- coding: utf8 -*- from Tkinter import * from math import sqrt from numpy import linalg from time import sleep def validatePoint(x, y): # возвращает true, если точка принадлежит области, определенной неравенствами if (x >= 0 and y >=0 and x <= 8 and y <= 6 and ((x - 5)**2 + (y - 3)**2 <= 3**2 or x <= 5 or y <=...
#!/usr/bin/env python # coding: utf-8 # <img src='assets/Flowers.png' width=500px> # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") import matplotlib.pyplot as plt import torch from torch import nn from torch import op...
from nose.tools import * from ex49_sentence_parsing import parser from ex49_sentence_parsing import lexicon def test_sentence(): s = parser.Sentence(('noun', 'princess'), ('verb', 'kills'), ('noun', 'bear')) assert_equals(s.subject, 'princess') assert_equals(s.verb, 'kills') assert_equals(s.object, 'bear') def t...
# Paul Glenn # MTH 437 # Book exercise # Section 9.1 Problem 3 from numpy import * def MCarea(myf,xi,xf,numpoints): '''Compute the area under the curve of f in the interval (a,b) using random numbers uniform on (0,1) and the specified number of points.''' a = 4; m = 9; b = 1 x = empty(numpo...
from datetime import date from freezegun import freeze_time from onegov.ballot.models import Election from onegov.ballot.models import ElectionCompound from onegov.ballot.models import Vote from onegov.election_day.collections import NotificationCollection from tests.onegov.election_day.common import DummyRequest def...
import sys; print("---day 2 --");
# Python imports import os, math, pdb, re, time from glob import glob from tqdm import tqdm import argparse import numpy as np import logging # ML imports from scipy.ndimage.interpolation import zoom from scipy.spatial.distance import dice import torch from torch import nn import torch.nn.functional as F torch.backend...
# According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." # Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizonta...
import machine #import network import webrepl import uWiFiConnection #import time import uInternetTest import uAP import esp import gc from ntptime import settime #import uOnlineLogger gc.collect() AP_NAME = "Lolin32" AP_PASSWORD = "12345678" WIFI_CONF_FILE = "/wifi_conf.txt" WIFI_ATTEMPTS = 2 logger = None connec...
import scrapy from bookscrapy.items import EbookItem class AbitelSpider(scrapy.Spider): name = "abitel" allowed_domains = ["abitel.gsm.pl"] patt='http://ebooki.abitel.gsm.pl/index.php?option=com_booklibrary&task=showCategory&catid=52&Itemid=509&limitstart=' start_urls = [patt+str(start) for start in x...
foo = [3,1,2] bar = sort(foo) print(foo) # [1,2,3] # Make a sequence from 0 to 10^18 gen1 = range(1, 1000000000000000000) # Square them all gen2 = (i ** 2 for i in gen1) # Include only odd numbers gen3 = (i for i in gen2 if i % 2 == 0) # Enumerate them all gen4 = enumerate(gen3) for i, value in gen4: print(i, v...
from googleapiclient.discovery import build import pprint def search_for_tag(tag): my_api_key = 'AIzaSyBUQQ4MeC8N6wDwxmHS8-FEqVGWUtfl754' my_cse_id = "018007238419152413196:g_1r4bqw2i0" def google_search(search_term, api_key, cse_id, **kwargs): service = build("customsearch", "v1", developerKey=a...
#Author: Ryan Su x = int(input("Give me a number:")) y = x while y > 0: if x % y == 0: print(y) y -= 1
#!/usr/bin/env python import subprocess import re class Package(object): def __init__(self, pname): self.pname = pname self.paths = subprocess.check_output(['pacman', '-Qlq', self.pname]).\ decode('UTF-8').split('\n')[:-1] def find_paths(self, regex): items = set...
from django.conf.urls import patterns, url from django.contrib.auth.views import login from django.contrib.auth.views import logout_then_login from .views import home, RegisterView urlpatterns = patterns( '', url(r'^login/$', login, {'template_name': 'accounts/login.html'}, name='login'), url(r'^logout/$'...
import base64 import urllib from Crypto.Cipher import AES from taskstopipeline.settings import BLOCK_SIZE, CRYPTO_SALT, PADDING def truncate(string, length): return string[:length] + '...' if len(string) > length else string def user_id_encoder(decoded_uid): pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_...
from django.db import models class Image(models.Model): zillow_id = models.CharField( max_length=15, help_text="The Zillow ID from the original JSON.") category = models.CharField( max_length=15, choices=( ('Interior', 'Interior'), ('Exterior', 'Exterior...
def fibo_gen(maxi=4 * 10 ** 16): a, b = 0, 1 while a < maxi: yield a a, b = b, a + b fib = [] for i in fibo_gen(): if i % 2 == 0: fib.append(i) for i in range(int(input())): n = int(input()) total = filter(lambda x: x <= n, fib) print(sum(fib))
from google.appengine.ext import ndb import json import codecs class Agency(ndb.Model): agency_id=ndb.IntegerProperty() agency_name=ndb.StringProperty() @staticmethod def readFromGtfsAgency(): fo = codecs.open('./resources/JER/agency_JER.txt', "r", "utf-8-sig") for line in fo: ...
from ast import Module from typing import MutableMapping, Union, List from public import public from .coordinates import CoordinateModel, AffineCoordinateModel from .mod import Mod from .model import CurveModel from .point import Point @public class EllipticCurve(object): model: CurveModel coordinate_model:...
# Copyright (C) 2016 The TensorFlow Authors. # Copyright (C) 2019 Alibaba Group Holding Limited. # All Rights Reserved. # ============================================================================== """A factory-pattern map which returns classification dataset iterator.""" from __future__ import division from __futur...
from .elektra import *
import numpy as np import math import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt class RansacPointGenerator: """generates a set points - linear distributed + a set of outliers""" def __init__(self, numpointsInlier, numpointsOutlier): self.numpointsInlier = numpointsInlier ...
#!/usr/bin/python3 str = "Holberton School" print(3*str) print(str[:9])
from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import redirect,get_object_or_404 from .forms import PostForm from django.http import HttpResponseRedirect from .forms import UserForm from django.shortcuts import render from django.utils import timezo...
from solver.solver_basic import SokobanSolverBasic from queue import Queue from heapdict import heapdict import numpy as np from scipy.optimize import linear_sum_assignment import satnet class GameState(object): def __init__(self, boxes, worker, parent): self.boxes = boxes self.worker = worker ...
import sys from pyspark import SparkContext, SparkConf from pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating import time,math from operator import add file_path = sys.argv[1] test_file = sys.argv[2] output_file = "Piyush_Umate_ModelBasedCF.txt" t = time.time() def user_movie_map(line): l =...
import os import sys import csv def main(argv): path = './data/' if len(argv) != 0: path = argv[0] driving_log_path = path + 'driving_log.csv' with open(driving_log_path) as data_file: reader = csv.reader(data_file) for line in reader: for i in range(3): file_name = path + 'IMG/' + line[i].split('/')...
cars = ['audi', 'renault', 'mercedes', 'bmw'] for car in cars: if (car == 'bmw'): print(car) else: print('not a bmw') cars[1].upper() print(cars[1]) print('audi' not in cars) print("Is car == 'subaru'? I predict True.") if cars: print('cars is a list') else: print('cars list is empt...
''' Created on 2Sep.,2016 @author: Alex Ip ''' import os import sys import errno import logging import re import subprocess import tempfile from shutil import rmtree import glob from osgeo import gdal, gdalconst import netCDF4 from geophys_utils import array_pieces import numpy as np from functools import reduce from ...
from django.contrib import admin from .models import Produto # Register your models here. @admin.register(Produto) class ProdutosAdmin(admin.ModelAdmin): list_display = ['titulo', 'referencia', 'preco']