text
stringlengths
8
6.05M
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' get_notification_type_list_query = """ SELECT * FROM public.notification_type AS nt WHERE nt.deleted is FALSE AND nt.active is TRUE AND ( $1::VARCHAR is NULL OR nt.name ILIKE $1::VARCHAR || '%' OR nt.name ILIKE '%' || $1::VA...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2015 DevIntelle Consulting Service Pvt.Ltd (<http://www.devintellecs.com>). # # For Module Support : devintelle@gmail.com or Skype : devintelle # ...
import pandas as pd import csv original_csv = pd.read_csv('./Fuzzy_dataset.csv') normal_csv = open('./fuzzy_normal_dataset.csv', 'w', newline='', encoding='utf-8') normal_csv_file = csv.writer(normal_csv) abnormal_csv = open('./fuzzy_abnormal_dataset.csv', 'w', newline='', encoding='utf-8') abnormal_csv_file = csv.w...
'''VoidFinder - Hoyle & Vogeley (2002)''' ################################################################################ # # IMPORT MODULES # ################################################################################ import sys sys.path.insert(1, '/home/oneills2/VoidFinder/python/') #sys.path.insert(1, '/U...
import subprocess from functools import lru_cache import ffmpeg from audiotsm import phasevocoder from audiotsm.io.wav import WavReader, WavWriter from scipy.io import wavfile import numpy as np import math from shutil import copyfile, rmtree import os import argparse from pytube import YouTube from toolz import first...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from native import name if __name__ == "__main__": print(f"Hello {name.get_name()}")
from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin from passlib.hash import bcrypt db = SQLAlchemy() # User class class User(UserMixin, db.Model): # single fields id = db.Column(db.Integer, primary_key=True) first = db.Column(db.String(127), nullable=False) last = db.Column(db...
from setuptools import setup, find_packages import os name = "piecemaker" version = "0.0.1" def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name=name, version=version, author='Jake Hickenlooper', author_email='jake@weboftomorrow.com', description...
from bot import * import requests CONST_URL = "https://api.telegram.org/bot708914610:AAFtLSerk5aw-72yKKvljZbrrRSmd4yHV8I/" from time import sleep #admin id 60201964 class functional: def __init__(self): self.bot = bot() def send_message(self, id, message): bot.send_message( id, message) sen...
# coding: utf-8 #geling修改注释 20180421 #liuyubiao修改策略输出为多策略输出 import numpy as np import pprint import sys import PolicyEvaluationSolution if "../" not in sys.path: sys.path.append("../") from lib.envs.gridworld import GridworldEnv # 进行多策略的输出 # 定义两个全局变量用来记录运算的次数 v_num = 1 i_num = 1 # 根据传入的四个行为选择值函数最大的索引,返回的是一个索引数组和...
""" This is a script showing how to use os to get the names of subdirectories and files started with specific letter""" import subprocess import os import sys """define main function""" def main(argv): # Use the subprocess.os module to get a list of files and directories # in your ubuntu home directory ...
# coding=utf-8 import sys,os from time import sleep from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException from selenium.webdriver.support.ui import Select import win32com.server.util, win32com.client sys.path.append(os.environ.get('PY_DEV_HOME')) from we...
class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.data = [] self.minstack = [] def push(self, x): """ :type x: int :rtype: nothing """ self.data.append(x) if (not self.minstack) or...
# Copyright 2017 Google 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 law or agreed to in writin...
import numpy as np import lasagne from copy import deepcopy def combine_temporal_spatial_weights(temporal_weights, spatial_weights): # Compute combined the weights. # We have to reverse them with ::-1 to change convolution to cross-correlation temporal_weights = temporal_weights[:,:,::-1,::-1] spat_...
import sys import matplotlib import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator majorLocatorX = MultipleLocator(2) minorLocatorX = MultipleLocator(1) majorLocatorY = MultipleLocator(0.5) minorLocatorY = MultipleLocator(0.25) filename = 'PR_final.dat' filename2 = 'EOM_IMSR...
programmer = True if programmer is True: print('You are awesome!') is_programmer = False if is_programmer is True: print('You are awesome!') else: print('Learn some programming!') if is_programmer: print('You are awesome!') if is_programmer is False: print('Learn some programming!') else: print('You ar...
""" Game Development basic project. A character stays in the centre of the screen and the environment moves around him. Author : Pranay Venkatesh """ import pygame # Basic pygame parameters pygame.init() win = pygame.display.set_mode((500, 500)) pygame.display.set_caption("pranay.io") # Background parameters b...
import unittest from katas.kyu_8.count_the_monkeys import monkey_count class MonkeyCountTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(monkey_count(5), [1, 2, 3, 4, 5]) def test_equals_2(self): self.assertEqual(monkey_count(3), [1, 2, 3]) def test_equals_3(self): ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf def tensors_filter(tensors, filters, combine_type='or'): assert isinstance(tensors, (list, tuple)), '`tensors` shoule be a list or tuple!' assert isinstance(filters, (str, list...
from django.conf.urls import include, url, patterns import sentiment.views as view urlpatterns = patterns('', url(r'^yahoo/(?P<symbol>[a-zA-Z]+)/$', view.YahooArticleListView.as_view(), name='search'), url(r'^article_sentiment/$', view.ArticleSentiment.as_view(), name='sentiment'), url(r'^text...
from rest_framework import routers from django.urls import path from . import views ROUTER = routers.SimpleRouter() ROUTER.register(r"logs", views.ApiLogViewSet) urlpatterns = ROUTER.urls + [ path(r"login/", views.ObtainTokenView.as_view(), name="login"), path(r"workerlog/", views.CeleryDebugTaskView.as_view(...
#!/usr/bin/python3 #Auth: Kube, James #AuthDate: 20200705 # -------------------------------------------------------------------------- # |Purpose: | # |--------------------------------------------------------------------------| # |Check Kubra outage...
from django.urls import path from .views import CategoriesView,CategoriesViewDetail,CategoriesAdd,CategoriesUpdate,CategoriesDelete urlpatterns = [ path('view/', CategoriesView.as_view()), path('viewDetail/', CategoriesViewDetail.as_view()), path('create/' ,CategoriesAdd.as_view()), path('update/<str:pk>/'...
from django.shortcuts import render from django.template import RequestContext from .models import data_locality def BeersAll(request): beers = data_locality.objects.all().order_by('name') #beers = Beer.description.maketrans().order_by('name') context = {'data': data_locality} return re...
# Copyright 2014 Google. # # 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...
# -*- coding: utf-8 -*- # @Time : 2019-12-20 # @Author : mizxc # @Email : xiangxianjiao@163.com import os from flask import current_app, request, flash, render_template, redirect, url_for from flask_login import login_required, current_user from . import bpHome from project.model.blog import * from project.commo...
#!/usr/bin/env python27 #-*- coding:utf-8 -*- #print 'hello,%s!welcome my house'%'jack' #r=72 #print '%d' % r # arr=['zhangsanfeng','lisinan'] # arr.append('jiangyuan') #末尾追加 # print arr # arr.insert(1,'zhaowu') #指定位置追加 # print arr # arr.pop(1) #删除指定位置 # print len(arr)#长度 # str="1111111111" # print len(str) # tup...
from operator import attrgetter,itemgetter, methodcaller from sets import Set class Edge(): def __init__(self,source,dest,weight): self.source=source self.dest=dest self.weight=weight def __repr__(self): return str(self.source)+" "+str(self.dest)+" "+str(self.weight) def conn...
import re from subprocess import Popen, PIPE from django.http import HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.views import View from django.views.generic import TemplateView from jyutping.jyutping import get_jyutping from synthesizer.models import Transcript from .forms impor...
def find_runner_up_score(): number_of_scores = int(input()) set_of_scores = set() scores = input().split(' ') for index in range(len(scores)): set_of_scores.add(int(scores[index])) list_of_scores = sorted(set_of_scores, reverse=True) return list_of_scores[1] print(find_runner_up_score...
import treadmill from treadmill.infra.setup import base_provision from treadmill.infra import configuration, constants import polling import logging _LOGGER = logging.getLogger(__name__) class IPA(base_provision.BaseProvision): def __init__(self, *args, **kwargs): self._instances = None super()....
t = int(input()) while t > 0: n = int(input()) arr = [0] + list(map(int,input().strip().split()))[:n] stor = [] f = [1 for i in range(n+1)] for i in range(1,n+1,+1): for j in range(i*2,n+1,+i): if arr[j] > arr[i]: f[j] = max(f[j],f[i]+1) ...
#!/usr/bin/env python # -*- py-indent-offset: 2; indent-tabs-mode: nil; coding: utf-8 -*- import pocketsphinx as ps decoder = ps.Decoder(lm="../model/lm/en_US/hub4.5000.DMP") nsamps = decoder.decode_raw(file("../test/data/goforward.raw", "rb")) (segments, score) = decoder.segments() for seg in segments: word ...
#tipe data skalar => tipe data sederhana print('tipe data skalar => tipe data sederhana') anak1 = 'Eko' anak2 = 'Dwi' anak3 = 'Tri' anak4 = 'Catur' print (anak1) print (anak2) print (anak3) print (anak4) #tipe data list/array/daftar print('\ntipe data list/array/daftar') anak = ['Eko', 'Dwi', 'Tri', 'Catur'] print (a...
from __future__ import division import numpy as np import pandas as pd import itertools import pickle from mypipeline import MultinomialNaiveBayesLogProbs, CleanTable, test_pipeline from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from tqdm import tqdm mnb_lr_pipe = Pipeline(st...
from django.test import TestCase from django.shortcuts import reverse from . import create_question class QuestionDetailViewTests(TestCase): def test_detail_view_should_return_404_when_question_in_future_is_requested(self): # Given future_question = create_question(question_text='Future question'...
import unittest import groupcheck class TestUserIsValidMethod(unittest.TestCase): def setUp(self): self.valid = ["1", "2", "3"] def testTrue(self): user = groupcheck.User("ellen", "1") self.assertTrue(user.is_valid(self.valid)) def testFalseString(self): user = groupcheck...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' ''' NOT USABLE CODE STATE CALCULATED ON POSTGRESQL SIDE update_hw_module_command_state_element_query = """ UPDATE public.hw_module_command_state AS hmcs SET hw_module_id = COALESCE($2, hw_module_id), sound_buzzer_state = COALESCE($3::BOOLEAN, s...
import sqlite3 import time import datetime import random def create_table(): ## c.execute('DROP TABLE stuffToPlot') c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL,datestamp TEXT,keyword TEXT,value REAL)') def data_entry(): c.execute("INSERT INTO stuffToPlot VALUES(145123542,'2016-01-01','Python',5)"...
from game_master import GameMaster from read import * from util import * import pdb class TowerOfHanoiGame(GameMaster): def __init__(self): super().__init__() def produceMovableQuery(self): """ See overridden parent class method for more information. Returns: ...
from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Category(models.Model): category_title = models.CharField('Заголовок', max_length=50) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): ...
# Library imports import pyautogui import time import json import sys import os # Execute one mouse event def execute_mouse_event(event): # If down direction if event['direction'] == 'down': # Pause python time.sleep(2) pyautogui.mouseDown(button=event['button'], x=event['position'][0]...
import os import glob import subprocess import shlex # pyfr import couette_flow_2d.msh couette_flow_2d.pyfrm def msh2pyfrm(filename=None): input_msh = os.path.join('mesh', filename) name = os.path.splitext(input_msh)[0] output_msh = name + '.pyfrm' os.system("pyfr import " + input_msh +" " + output_msh...
#!/usr/bin/env python import hashlib data = 'hi' h = hashlib.md5() h.update(data) print h.hexdigest() print hashlib.md5(data).hexdigest()
from OFS.DTMLMethod import DTMLMethod from Products.Five import BrowserView from zope.interface import Interface from topp.featurelets.base import BaseFeaturelet success = "SUCCESS!!" class IDummyFeatureletInstalled(Interface): """ Signifies that a dummy featurelet has been installed. """ class Object...
from __future__ import division import numpy as np import os import warnings warnings.filterwarnings("ignore") import sklearn.datasets as datasets import scipy.io as spio import RewardProcess from sklearn.model_selection import train_test_split import sklearn.metrics.pairwise as Kern import KernelCalculation.GaussianKe...
# -*- coding: utf-8 -*- import xmlrpclib import base64 url = "http://127.0.0.1:8069" db = "rim" uid = 1 password = "Antonio230" sock = xmlrpclib.ServerProxy('http://127.0.0.1:8069/xmlrpc/object') model = "product.template" products_ids = sock.execute(db, uid, password, model, 'search', []) products = sock.execute(...
#coding=utf-8 ''' # The modules contains PiApp's models # Any issues or improvements please contact jacob-chen@iotwrt.com ''' from django.db import models from django.contrib.auth.models import AbstractUser import os class Applist(models.Model): id = models.IntegerField(primary_key=True) title = models.Cha...
import urllib2 import pprint import pandas as pd import json def get_data(url): """ Get html file from url :param url: string :return: string (json) """ response = urllib2.urlopen(url) json = response.read().decode('latin-1') return json def parse(json): json.dumps(json) p...
import threading import socket import sys import struct import random lock = threading.Lock() def checkchecksum(checksum,data): tempdata=0 newchcksum = 0 i=0 n = len(data) % 2 for i in range(0, len(data) - n, 2): tempdata += ord(data[i]) + (ord(data[i + 1]) << 8) if n: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 16/4/27 下午7:42 # @Author : ZHZ line1 = raw_input() n = line1.strip().split()[0] K = line1.strip().split()[1] string_list = [] all_str_list = [] count = 0 #得到所有字符串字典 for i in range(0,int(n)): line = raw_input().strip() string_list.append(line.strip()) ...
capets={ 'name': 'Элегия', 'size': '120x80', 'color': 'Серый', 'stock': 1 } print (capets) capets ['stock']=2 capets ['price']=7900 print (capets) print (capets ['name']) print (capets.get('place', 'Москва')) # .get используем,чтобы не получить ошибку, # если запрашиваем несуществующий ключ. Посл...
from django.shortcuts import render # Create your views here. from .serializers import * from .models import * from film.models import categories_film from film.serializers import FilmSerializer,FilmOneSerializer,FilmTilte from film.models import actors # Create your views here. from rest_framework.views import APIVi...
import unittest from katas.beta.denumerate_string import denumerate class DenumerateTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(denumerate([ (4, 'y'), (1, 'o'), (3, 't'), (0, 'm'), (2, 'n') ]), 'monty') def test_equal_2(self): self.assertEqual(de...
import tkinter as tk from tkinter import ttk win=tk.Tk() win.title('Label Frame') label_frame=ttk.Labelframe(win,text="Enter your details below: ", ) label_frame.grid(row=0,column=0) labels=["What is your name: ","What is your age: ","What is your gender: ","Country:","state:","city:","address:"] #labels for i in ran...
from distutils.core import setup setup( name="pykefcontrol", packages=["pykefcontrol"], version="0.6.2", license="MIT", description="Python library for controling the KEF LS50 Wireless II", long_description="Python library for controling the KEF LS50 Wireless II. It supports basic commands for ...
from pynamodb.models import Model from pynamodb.attributes import UnicodeAttribute, NumberAttribute, BooleanAttribute, UTCDateTimeAttribute from weibo import get_config config = get_config() class UserModel(Model): """ A DynamoDB User """ class Meta: table_name = "weibo-user" aws_acce...
from jinja2 import FileSystemLoader, StrictUndefined from jinja2.environment import Environment env = Environment(undefined=StrictUndefined) env.loader = FileSystemLoader('.') nxos1 = { "interface": "Ethernet1/1", "ip_address": "10.1.100.1/24" } nxos2 = { "interface": "Ethernet1/1", "ip_address": "10...
from abc import ABC, abstractmethod from pygame import key class Button(ABC): @abstractmethod def check_pressed(self): pass # We'll have a general controller with only the buttons we need # That can be checked uniformly across the code class Controller: # Buttons that can be pressed...
""" Admin panel for CardControl Django application. """ from django.contrib import admin from .models import Message admin.site.register(Message)
import unittest from jousting.player.knight import Knight from jousting.util.rps import SHIELD class KnightTest(unittest.TestCase): def setUp(self): self.knight = Knight("Lancelot") def test_move(self): knight = self.knight self.assertEquals(0, knight.get_current_position()) ...
from tkinter import Tk from hello_view2 import HelloView # HelloView 的 Controller 類別 class HelloController: # 設定初值 def __init__(self): self.app = HelloView(master=Tk()) self.app.button["command"] = self.action self.app.mainloop() # 按下按鈕的事件 def action(self): self.app.result["text"] = "按鈕被按" # ...
class Currency(object): def __init__(self, name, low, high): self.name = name self.low = low self.high = high #enter any new coinmarket cap listed currency in the following format: Currency(name of currency, low limit (integer), high limit (integer)) ethereum = Currency('ethereum', ...
from flask_script import Manager from exts import db from flask_migrate import Migrate,MigrateCommand from manage_run import app #迁移的话必须导入 models下的 from models import User,Question,Answer manager=Manager(app) #使用migrte绑定app,db migrate=Migrate(app=app,db=db) #添加迁移脚本的命令到manager中 manager.add_command('db',MigrateComman...
# SPDX-License-Identifier: BSD-3-Clause # Copyright (C) 2017-2020, SCANOSS Ltd. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import hashlib def parse_diff(src): """ Parse a commit diff. This function parses a diff string and generat...
## # wrapping: A program making it easy to use hyperparameter # optimization software. # Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer # # 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 Found...
#################################################################################################### # game_of_three.py # # ------------------------------------------------------------------------------------------------ # # Takes a number ...
class Parametrization(object): BASEPT_AND_DIR_VECTORS_MUST_BE_IN_SAME_DIM_MSG = ( 'the basepoint and direction vectors should all live in the same dimension') def __init__(self,basepoint,direction_vectors): self.basepoint = basepoint self.direction_vectors = direction_vectors ...
import numpy import statsmodels.sandbox.stats.multicomp import scipy.stats import sys ifile = open("gene_names") gene_names=[] for line in ifile: gene_names.append(line.replace("\n","")) ifile.close() file_name="TE_result_all.csv" ifile = open(file_name) cutOff=0 source=[] TE=[] target=[] for line in ifile: t...
""" This file is used for storage of database credentials. """ DATABASE = { 'host': '127.0.0.1', 'user': 'demouser', 'passwd': 'demopassword', 'database': 'blueairdb', 'table': 'airdata' }
import socket target_host = "192.168.0.12" target_port = 80 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) client.sendto("AAABBBCCC", (target_host, target_port)) data, addr = client.recvfrom(4096) print data
n = float(input("Enter a first number: ")) n1 = float(input("Enter a second number: ")) print(n ** n1)
import sys import re def consolidate_CSV(csv_path, outputFile): """ Takes the csv file located at csv_path that was downloaded from https://api.bitcoincharts.com/v1/csv/ and consolidates the duplicate timestamps into one entry with the price and volume values being the average of all entries with th...
import socket from pynput import keyboard from threading import Thread serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() print("Hostname:",host) port = 8184 coordinates = []#player locations bullets = []#bullet locations serversocket.bind((host, port)) No_Clients = 0...
#!/usr/bin/env python3 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Template loader and preprocessor. # # Preprocessor language: # # //$ Comment li...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json import pytest from pants.backend.javascript import resolve from pants.backend.javascript.package_json import NodeThirdPartyPackageTarget, P...
import os import z from shutil import copyfile, copytree dest = "/mnt/c/Users/Zoe/Documents/dest/split" #z.gsavedir = dest z.getp("dates") path = z.getPath("split") try: copytree(path, dest) except: pass print ("finished split") dest = "/mnt/c/Users/Zoe/Documents/dest" getpd = z.getp("getpd") for name in get...
from django.urls import path from .views import ( ProducersList, ProducerDetails ) urlpatterns = [ path('', ProducersList.as_view()), path('<int:pk>/', ProducerDetails.as_view()) ]
from tkinter import * from tkinter.filedialog import askopenfilename # from tkinter import ttk from PIL import Image, ImageTk#import Image, ImageTk calibUnitChoices = { 'um': 1e6, 'mm': 1e3, 'cm': 1e2, 'm': 1, 'km': 1e-3, 'in': 39.3701, 'ft': 3.28084, 'mi': 0.000621371, } def cali...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-20 03:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0007_auto_20160520_0110'), ] operations = [ migrations.AlterField...
import cgi form = cgi.FieldStorage() # send to server instead print form["username"]
class Node: def __init__(self, data): self.data = data self.nextreference = None self.previousreference = None class DoublyLinkedList: def __init__(self): self.head = None def print_LL(self): print() if (self.head is None): print('...
from oauth2helper.version import __version__ from oauth2helper._token import validate, decode from oauth2helper._content import user_name, get
v = int(input('Qual a velocidade atual do carro? ')) if v > 80: m = 7 * (v - 80) print('MULTADO! você excedeu o limite de 80km/h' '\nVocê deve pagar uma multa de R${}.'.format(m)) print('Tenha um bom dia! Dirija com segurança.') else: print('Tenha um bom dia! Dirija com segurança.')
import dash_bootstrap_components as dbc from dash import Input, Output, State, html alert = html.Div( [ dbc.Button( "Toggle alert with fade", id="alert-toggle-fade", className="me-1", n_clicks=0, ), dbc.Button( "Toggle alert withou...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('categories', '0002_auto_20160205_2046'), ] operations = [ migrations.CreateModel( name='Good', field...
#!coding:utf-8 from django.shortcuts import render # Create your views here. from Web.models import * from django.http import HttpResponse,HttpResponseRedirect,JsonResponse from django.shortcuts import render from django.core import serializers from django.views.decorators.csrf import csrf_exempt from Web.cookiechec...
#!/usr/bin/env python # -*- coding: utf-8 -*- import rospy import serial from math import sin, pi from std_msgs.msg import Float64 from nav_msgs.msg import Odometry from Lab1.msg import GPS import utm def parse_gps(line_split): ''' Given pressure (in m fresh) and latitude (in radians) returns ocean depth (in...
def maker(n): def action(x): return x**n; return action f = maker(2) print(f(3)) print(f(4))
''' Created on Nov 9, 2013 @author: surendra requirement: python 3 ''' import random import time def empty_board(): board = [] for i in range(0,3): row = [] for j in range(0,3): row.append("") board.append(row) return board def board_copyof(board): newboar...
#from temporario import * from resolucao import * from gabarito import * from criar import * from exibir import * from listar import *
from timsort import timsort import random # Emtpy array lst1 = [] # Single element lst2 = [1] # Two elements lst3 = [1, 2] # Alternating elements lst4 = [-1,2] * 1000 # Ordered elements with pos and neg values lst5 = [i for i in range(-1000, 1000)] # Inversely ordered elements with pos and neg values lst6 = [i for i i...
from models import Item, Label, update_label, BagCount, Setting from django.db.models import Count from django.http import Http404, HttpResponse, HttpResponseBadRequest from django.core.paginator import Paginator, EmptyPage from django.core.paginator import InvalidPage, PageNotAnInteger from django.template import Req...
from action import Action import kodi_baselibrary as kodi class LoadSharedLanguageAction(Action): def __init__(self): super().__init__( name = "Load Kodi (shared) language file", function = self.loadsharedlanguagefile, description = "Load the Kodi standard (shared) l...
from app import app from flask import render_template, request from ..controllers import users import helper @app.route('/login', methods = ('GET', 'POST')) def login(): if request.method == 'GET': return users.log_out() elif request.method == 'POST': return users.log_in() @app.route('/create', methods = ('GET', 'P...
# try tries to run a code and if an error (of a certain type) occured the program runs except print("How funny are we?") m = "default" n = 0 m = str(input("Input name: ")) try: n = int(input("Input number: ")) except(ValueError): print("not a number ValueError") pwrmsg = "" try: pwrmsg = "{0}s power ...
def scratch(lottery): return sum(int(x[-x[::-1].index(' '):]) for x in lottery if len(set(x.split()))==2) ''' Task You got a scratch lottery, you want to know how much money you win. There are 6 sets of characters on the lottery. Each set of characters represents a chance to win. The text has a coating on it. W...
import cv2 import numpy as np import imutils def crop_and_rotate(im): ROTATE_ANGLE = -9 rotated = imutils.rotate(im, angle=ROTATE_ANGLE) # rotate return rotated[810:950, 680:2000] # clip def read_road_image(path): im = cv2.imread(path) if im is None: return None flipped = cv2.flip(im, ...
#!/usr/bin/env python3 import io import csv import openpyxl import utils def download(): utils.download_file('https://doi.org/10.1371/journal.pone.0058321.s001', '../data/pmid_23520498/journal.pone.0058321.s001.XLSX') def convert_to_csv(): workbook = openpyxl.load_workbook('../data/...