text
stringlengths
38
1.54M
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ActivityStat(object): def __init__(self): self._contract_count = None self._finished_count = None self._lose_efficacy_count = None self._participator_count = None ...
# import the necessary packages from imutils.face_utils import FaceAligner from imutils.face_utils import rect_to_bb import argparse import imutils import dlib import cv2 import os def align_and_crop_face(image, shape_predictor='shape_predictor_68_face_landmarks.dat'): # initialize dlib's face detector...
""" URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. """ def urlify(string, length): """Return an input string with all spaces replaced with...
#!/usr/bin/env python import pyfits,sys,json if len(sys.argv)<5 : print sys.argv[0],"spec.fits image.fits psf.xml extract.json" sys.exit(12); spec_filename=sys.argv[1] image_filename=sys.argv[2] psf_filename=sys.argv[3] json_filename=sys.argv[4] hdulist=pyfits.open(spec_filename) (nspec,nwave) = hdulist[0...
""" Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists). Return a array containing all the linked lists.   Example: Input: [1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 ...
''' Database module author: 10zinten ''' from pathlib import Path import sqlite3 import csv from xml.dom import minidom Labels = Path('Labels').resolve() class LabelDB(object): def __init__(self): self.conn = sqlite3.connect('label.db') print("[ INFO ] database created successfully ... ") ...
from utils import econf_compile, econf_foreach_hcm, module_and_mapping_manifests, SUPPORTED_ENVOY_VERSIONS import pytest def _test_hcm(yaml, expectations={}): for v in SUPPORTED_ENVOY_VERSIONS: # Compile an envoy config econf = econf_compile(yaml, envoy_version=v) # Make sure expectations...
from sklearn import svm #print("SVM imported successfully") ##to import the default iris datasets from sklearn import datasets ## to split training and test data from sklearn.model_selection import train_test_split #for getting accuracy score from sklearn.metrics import accuracy_score ##load iris datasets from datasets...
import click import matplotlib.pyplot as plt from pathlib import Path @click.group() def cli(): pass def sensitivity(results_path, output_path, baseline_path, xticks, xlim): parameters = [] accuracies = [] with open(baseline_path) as f: _, baseline_acc = f.read().strip().split() basel...
# coding: utf-8 from django.contrib import admin from info.models import org,group,person class OrgAdmin(admin.ModelAdmin): pass #list_display = ('name', 'des', 'password') class GroupAdmin(admin.ModelAdmin): pass #list_display = ('name', 'des', 'org') class PersonAdmin(admin.ModelAdmin): pass #list_...
# -*- coding: utf-8 -*- # # Copyright 2018 Amir Hadifar. 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 req...
#-*- coding:utf-8 -*- import json import hprose class test: def hello(self,name): return 'Hello %s!' % name def main(): server = hprose.HttpServer(host="tcp://0.0.0.0",port = 8181) server.addMethod("hello",test()) server.start() if __name__ == '__main__': main()
#!python3 #encoding:utf-8 import requests import json class AccessTokenRequester: def __init__(self): pass def get_token(self, client_id, client_secret, refresh_token, is_debug_output=False): data = { "client_id": client_id, "client_secret": client_secret, ...
from django.contrib import admin from django.contrib.gis.admin import OSMGeoAdmin from .models import Hotel @admin.register(Hotel) class HotelAdmin(OSMGeoAdmin): list_display = ('name', 'location', 'address')
def dfs(start, visited, n, computers): S = [] S.append(start) while S: now = S.pop() visited[now] = 1 for i in range(n): if computers[now][i] == 1 and visited[i] == 0: S.append(i) def solution(n, computers): visi...
import json, os, random, datetime from work_data.eps_printer import Receipt def dummy_print(items, opts): curdir = os.path.dirname(os.path.abspath(__file__)) pic = 'tux.jpg' receipt = Receipt() clogo = 'uploads/'+pic clogo = os.path.join(os.path.dirname(curdir),clogo) # opts['clogo'] = clogo ...
# To run this script, run # `python studentized_range_mpmath_ref.py` # in the "scipy/stats/tests/" directory # This script generates a JSON file "./data/studentized_range_mpmath_ref.json" # that is used to compare the accuracy of `studentized_range` functions against # precise (20 DOP) results generated using `mpmath`...
from zope.interface import alsoProvides from zope.globalrequest import getRequest try: from plone.protect.interfaces import IDisableCSRFProtection except ImportError: from zope.interface import Interface class IDisableCSRFProtection(Interface): pass def disableCSRFProtection(): alsoProvides(g...
from typing import Optional import pandas as pd from pathlib import Path from blackbox.offline import evaluations_df from blackbox.load_utils import error_metric path = Path(__file__).parent def postprocess_results(df): # keeps only 70 iteration for NAS and 100 for other blackboxes as described in the paper ...
from django.contrib import admin from .models import * # Register your models here. admin.site.register(BlogPosts) admin.site.register(PostCategory) admin.site.register(PostComment)
# coding: utf-8 from mbclient import mb from random import choice import re,json,urllib,urllib2,traceback wiki="wiki\s+(?P<r>random\s+)?(?P<what>.+)" html_tags = re.compile(r'<[^>]+>') def wiki_func(nick,match,target): what = urllib.urlencode({"srsearch":match.group("what")}) r=match.group('r') req = urllib2.Reque...
import sqlite3 import os # import pandas as pd def get(q): db_folder = os.path.join('assets', 'database') conn = sqlite3.connect(os.path.join(db_folder, 'sqlite.db')) cur = conn.cursor() cur.execute(q) rows, columns = cur.fetchall(), [i[0] for i in cur.description] cur.close() ...
from django.db import models from django.forms import fields from django.utils.translation import ugettext as _ import re from south.modelsinspector import add_introspection_rules MAC_RE = r'^([0-9a-fA-F]{2}([:-]?|$)){6}$' mac_re = re.compile(MAC_RE) add_introspection_rules([], ["^network\.models\.MACAddressField"]) ...
#!/usr/bin/env python3 import os def my_ls(path): print(path) l = os.listdir(path) print(l) for filename in l: filename = path + '/' + filename if os.path.isdir(filename): my_ls(filename) print("目录:", filename) else: print("文件:", filename) if ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-10-28 10:14 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('OnlineJudgeApp', '0004_auto_20171027_0031'), ] operations = [ migrations.Al...
import pyAesCrypt buffersize = 100 *1024 fileName = input("What's your file name: ") password = input("password: ") cipher = fileName+'.enc' print("Encrypting {} ...".format(fileName)) pyAesCrypt.encryptFile(fileName,cipher,password,buffersize) print("{} Encrypted succesful".format(fileName))
from keras.layers import Flatten, Dense, Dropout, GlobalAveragePooling2D from keras.layers import Lambda, Activation from keras.models import Model from network.rnn import TimeDistributed_CuDNNLSTM as TD_BiLSTM from network.rnn import Bidirectional_CuDNNLSTM as BiLSTM from keras_layer_normalization import LayerNormaliz...
# coupon_code = "@小助手 兑换码ccvt-sfmf86h8" # # # coupon_code = coupon_code.replace('@小助手', '') # # # "28EBFAE0-C750-C811-E6E0-6B89DFAA2A53"+"_check_login" # # # if "ccvt-" in coupon_code: # print(''.join([i if ord(i) < 128 else ' ' for i in coupon_code]).replace(' ', '')) # else: import json import urllib from urllib ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Persona', fields=[ ('id', models.AutoField(verb...
import numpy as np import torch from torch import nn, optim from .loss_functions import samplewise_loss_function class RobustInference(nn.Module): """Takes a trained ABS model and replaces its variational inference with robust inference.""" def __init__(self, abs_model, device, n_samples, n_iterations, ...
""" This file provides functions for dumping from memory to disk, useful for persistence. """ from os import path ROOT = path.normpath(path.join(path.abspath(__file__), "..")) def _store(fname, content): full = path.join(ROOT, fname) open(full, "w").write(content.hex()) def store_disk(entries): for k,...
# Copyright 2021 Hathor Labs # # 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, s...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from coreapp.models import Book, Profile from dal import autocomplete class SearchForm(forms.Form): search = forms.CharField( max_length=100, widget=autocomplete.ModelSelect2(url='co...
#!/usr/bin/env python def fact(x): if x == 1: return 1 while x != 1: return x*fact(x-1) print fact(1) print fact(10) print fact(5)
# -*- coding: utf-8 -*- # @Author: WuLC # @Date: 2016-12-17 11:35:46 # @Last modified by: WuLC # @Last Modified time: 2016-12-29 18:15:57 # @Email: liangchaowu5@gmail.com # greddy, get wrong answer for some solution ,like # strs = ["111","1000","1000","1000"], m = 9, n=3 class Solution(object): def findMaxF...
# -*- coding: utf-8 -*- import os, sys lib_path = os.path.abspath(os.path.join('..')) sys.path.append(lib_path) import numpy as np from tools import utils from data_accessors.interview import interview def is_stable_matching(matching_a, matching_e, u_applicant, u_employer): isinstance(matching_a, list) isin...
from PySide6.QtWidgets import QListWidget, QGridLayout, QVBoxLayout, QPushButton, QHBoxLayout from vue.user.party_info import PartyInfoQt from vue.window import BasicWindow from model.store import Store from controller.party_controller import PartyController class PartyList(BasicWindow): def __init__(self, user...
from functions.project_fn.utils import get_shape as get_shape from scipy.ndimage.interpolation import map_coordinates from scipy.ndimage.filters import gaussian_filter import cv2 as cv import tensorflow as tf import numpy as np class Preprocessing: @staticmethod def _fp32(tensor_or_list): """ ...
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from .import views app_name = 'cart' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^update/(?P<variant_id>\d+)/$', views.update, name='update-line'), url(r'^summary/$', views.summary,...
import json from source.domain.user import User class Student(User): def __init__(self, name="", password="", email="", address="", contactNumber="", studentId=""): super().__init__(name, password, email, address, contactNumber) self.studentId = studentId def setStudentId(self, stu...
from rest_framework.pagination import PageNumberPagination class DefaultPagination(PageNumberPagination): """Use pagination for responses with lists to prevent performance issues in the backend""" page_size = 10 page_size_query_param = 'page_size' max_page_size = 100
from crontab import CronTab cron = CronTab(user='ujwaltadur') job = cron.new(command='python3 Documents/Learning/Python/Alert.py') job.minute.every(5) cron.write() print(job.enable())
from vim_turing_machine.machines.merge_overlapping_intervals.decode_intervals import decode_intervals def test_encode_intervals(): assert decode_intervals('{}{}'.format('01010', '11111'), 5) == [[10, 31]]
from django.http import HttpResponseRedirect from django.contrib.auth.models import User from app_users.models import UserProfile #========================================================================= # INTERCEPT CONNECTION WITH ALREADY CONNECTED ACCOUNTS #==========================================================...
"""Tests for certbot_dns_shellrent.dns_shellrent.""" import unittest import mock import json import requests_mock from certbot import errors from certbot.compat import os from certbot.errors import PluginError from certbot.plugins import dns_test_common from certbot.plugins.dns_test_common import DOMAIN from certbot...
""" Web Registration Author : Kevin Liu Date of last modification : 30 May 2021 This was written on MacOs Sierra Version 10.12.6 (16G2136) """ # import different modules from tkinter import * import random from tkinter import messagebox # def functions def confirm(): password = password_E.get() confirmation_...
import os import webbrowser import pandas as pd from highcharts import Highchart def create_histogram(src_csv, dst_html, title=None, subtitle=None, x_axis_header=None, y_axis_header=None, x_axis_name=None, y_axis_name=None): """Creates basic histogram using Highcharts Args: ...
# """ Modules of texar losses. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from texar.losses.losses_utils import * from texar.losses.mle_losses import * from texar.losses.pg_losses import * from texar.losses.adv_lo...
# Professor David Crandall # B551 Elements of Artificial Intelligence # Yue Chen, Siddharth Jayant Pathak, and Raghottam Dilip Talwai # October 1st, 2017 # Problem 2 class Survey: count = 0 def __init__(self, name, number, prefer, notPrefer): self.name = name self.number = number sel...
from simpletransformers.question_answering import QuestionAnsweringModel import json import os import logging logging.basicConfig(level=logging.INFO) transformers_logger = logging.getLogger("transformers") transformers_logger.setLevel(logging.WARNING) # training parameters; given below is the default setting used for ...
print('Calculador de tinta!') a = float(input('Digite a altura da parede em metros: ')) l = float(input('Digite a largura da parede em metros: ')) ar = a*l t = ar / 2 print('Você precisará de {} litros de tinta para pintar esta parede, pois ela tem {} metros quadrados.'.format(t, ar))
import pdb from pykalman import KalmanFilter import constants import numpy as np class Track(): def __init__(self, meas): self.meas = meas self.timesSeenTotal = 1 self.timesUnseenConsecutive = 0 self.filter = None self.selected = False def predict(self, predTime): ...
import argparse import os class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser() self.initialized = False self.isTrain = False def initialize(self): self.parser.add_argument('--workdir', type=str, required=True, help='work directory') self.pars...
import os, sys, platform import shutil import subprocess import string import glob import gzip import codecs import time import build_number from . import config def remkdir(n): if os.path.exists(n): print(n, 'exists, clearing it...') shutil.rmtree(n, True) os.mkdir(n) def deltree(n): if ...
import numpy as np # linear algebra def convolute(X, orig_x_size, orig_y_size, patch_x_size, patch_y_size, x_stride, y_stride): """Given input X (n x m), an array of stacked vectorized images, return a matrix of vectorized patches horizontally patched per image""" n_x, m = X.shape patch_size = patch_...
# -*- coding: utf-8 -*- """ alias on EulerProject - 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ import time def gcd(a, b): """gcd(int, int) -> ret...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 left_min = prices[0] right_max = prices[-1] length = len(prices) left_profits = [0] * length # ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-04-11 14:13 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Crea...
balance = 150 annualInterestRate = 0.2 def calculator (x, r, n, p): """ Inputs: x = initial balance r = annual interest rate Outputs: The monthly fixed payment to reduce x to <=0 in 12 months """ for n in range(0,12): if (n == 0): balUnpaid = x - p ...
#Provenance Domain: f = open("myfile.txt","w") print("Fill in the prompts to create a BCO" ) print("Provenance Domain \n") f.write( "\"provenance_domain\": { \n") embargo_yn = input(" Does your BCO have an Embargo Period? yes or no: ") if embargo_yn == "yes": start_time = input(" Embargo Start Time: ") e...
# -*- coding:utf-8 -*- # ------------------------------- # ProjectName : autoDemo # Author : zhangjk # CreateTime : 2020/9/29 11:19 # FileName : stocks # Description : # -------------------------------- # 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 # 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。 # 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 de...
from threading import Thread from constants import BOLTEK_NAME, LIDAR_NAME, MULTISENSOR_NAME from sensors import ElectricFieldMonitor, Lidar, MultiSensor def main() -> None: sensors = [Lidar(LIDAR_NAME), ElectricFieldMonitor(BOLTEK_NAME), MultiSensor(MULTISENSOR_NAME)] for thre...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import os import imaplib import subprocess import configparser config = configparser.ConfigParser(interpolation=None) config.read(os.path.join(os.environ["XDG_CONFIG_HOME"], "aerc", "accounts.conf")) count = [] for section in config.sections(): source = config[secti...
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays" user_table_drop = "DROP TABLE IF EXISTS users" song_table_drop = "DROP TABLE IF EXISTS songs" artist_table_drop = "DROP TABLE IF EXISTS artists" time_table_drop = "DROP TABLE IF EXISTS time" # CREATE TABLES songplay_table_create = (""" CREATE TABLE...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 19 16:23:20 2020 @author: Evan """ #%% import talib if __name__ == '__main__': from TechnicalFeatureBase import TechnicalFeatureBase else: from .TechnicalFeatureBase import TechnicalFeatureBase #%% class CCI(TechnicalFeatureBase): # se...
#!/usr/bin/python # -*- coding: utf-8 -*- import os import re from cloudshell.networking.brocade.autoload.brocade_snmp_autoload import BrocadeSnmpAutoload from cloudshell.networking.autoload.networking_autoload_resource_attributes import NetworkingStandardRootAttributes from cloudshell.networking.autoload.networking_...
# from django.forms import widgets from django.forms import widgets from rest_framework import serializers from notas.models import Usuario from notas.models import Nota __author__ = 'braiNotes' class UsuarioSerializer (serializers.ModelSerializer): class Meta: model = Usuario fields = ('id','nom...
from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User import simplejson as json RESOURCE_CHOICES = ( ('B', 'Biologicals'), ('M', 'Minerals'), ('C', 'Culture'), ('A', 'Any'), ) JOB_CHOICES = ( ('P', 'Produce'), ...
import numpy as np with open("_17.txt", encoding="utf-8") as f: lines = f.read().splitlines() line_len = len(lines[0]) for y, line in enumerate(lines): if(len(line) != line_len): print("The floor is not a square") exit(1) def get_vacume_coordinates(): vacume = """ sss sssss sssssss sss...
def splits(getal): d = getal % 10 getal = getal // 10 c = getal % 10 getal = getal // 10 b = getal % 10 getal = getal // 10 a = getal % 10 getal = getal // 10 return d,c,b,a def oplopende_cijfers(a , b , c, d): s1 = min(a,b,c,d) s4 = min(a,b,c,d) k23 = max(min(a,b),m...
#!/usr/bin/python import sparql import itertools def read_list_attributes(): list_attributes = [] f = open('listProperties.txt', 'r') for line in f: list_attributes.append(line.strip()) return list_attributes def count_result_from_query(subset): value = 0; endpoint = 'http://130.235.1...
from parsing import parsing_utils from parsing import parsing_args def is_count_funct(serialization_list): '''is_count_funct(serialization_list)''' is_count = False for element in serialization_list: if element in parsing_args.count_ner_tags: is_count = True break ...
# -*- coding: utf8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'name': 'uarango', 'description': 'UNIST arangoDB Restful Python Library', 'author': 'Kyunghoon Kim', 'author_email': 'preware@gmail.com', 'url': 'https://github.com/koo...
#!/usr/bin/python3 name="SID" print(name) print(name*2) print(name + "is awesome") print(name[1]) print([2])
#!/usr/bin/env python3 import unittest import torch from captum.attr._core.deep_lift import DeepLift from captum.attr._core.feature_ablation import FeatureAblation from captum.attr._core.gradient_shap import GradientShap from captum.attr._core.layer.grad_cam import LayerGradCam from captum.attr._core.layer.internal_...
import requests import json import csv i = 0 while i <22000: stations_url = 'http://www.snirh.gov.br/arcgis/rest/services/SGH/REDE_HIDROMETEOROLOGICA_NACIONAL_2018/MapServer/0/query?where=FID>{FID_count}&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelInterse...
from flask import Flask from .main.schema import ms from .main.models import db import os from .main.config import config_by_name from flask_migrate import Migrate from .main.bp import exbp def createApp(config_name): app = Flask(__name__) app.config.from_object(config_by_name[config_name]) db.init_ap...
from Solver import * from VRP_Model import Model m = Model() m.build_model() s = Solver(m) sol = s.solve()
# Generated by Django 3.1.3 on 2020-11-07 20:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('blogs', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='blogs', options={'ordering': ['-date']}, ...
from src.dice import is_drop_instruction, is_math_expression, is_roll_instruction def test_is_roll_instruction(): assert is_roll_instruction("4d6") == True assert is_roll_instruction("20d5") == True assert is_roll_instruction("2d50") == True assert is_roll_instruction("40d50") == True assert is_ro...
# Copyright 2017 Google Inc. 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 applicable law or ag...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest import inspect import os import stat import shutil from pathlib import Path from pyrepogen import logger _logger = logger.create_logger(name=None) from pyrepogen import colreqs from pyrepogen import settings from pyrepogen import PARDIR TESTS_SETUPS_PATH ...
from selenium.webdriver.support.wait import WebDriverWait from webdriver_manager.firefox import GeckoDriverManager from webdriver_manager.chrome import ChromeDriverManager from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from...
#!/usr/bin/python3 import time from datetime import datetime, timedelta import xml.etree.ElementTree as ET import paho.mqtt.client as mqtt import requests import config next_alarm = None repeat_counter = 0 ringing = False active_alarm = False # sets up the MQTT client mqtt_client = mqtt.Client(config.HOSTNAME) mqtt...
#!/usr/bin/env python __author__ = "LIU YongChu" __update__ = "2010-09-05" __update__ = "2012-06-11" import pre import sys, os, traceback from string import * from subprocess import * from OftenUsedFun import * global is_win if 'win' in sys.platform: is_win = 1 else: is_win = 0 #############################...
#!/usr/bin/python3 """ This module contains a Python script that fetches https://intranet.hbtn.io/status """ import urllib.request if __name__ == '__main__': url = "https://intranet.hbtn.io/status" with urllib.request.urlopen(url) as myurl: data = myurl.read() print("Body response:") ...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: Interpreter.py # Purpose: # # Author: wukan # # Created: 2019-01-10 # Copyright: (c) wukan 2019 # Licence: GPL-3.0 #-----------------------------------------------------------...
from dataclasses import dataclass, field import perde import pytest from util import FORMATS """rust #[derive(Serialize, Debug, new)] struct DefaultConstruct { a: String, c: u64, } add!(DefaultConstruct {"xxx".into(), 3}); """ @pytest.mark.parametrize("m", FORMATS) def test_default(m): @perde.attr(default=T...
try: def start(): global d, d2, d3 d = int(input('Digite valor onde iniciará o intervalo:\n')) d2 = int(input('Digite valor onde terminará o intervalo:\n')) d3 = int(input('Digite valor que deseja verificar:\n')) start() def r(x,y): global intervalo intervalo...
import re import requests import urllib.parse from bs4 import BeautifulSoup from csdn.CsdnFlow import follow, unFollow headers = { 'Host': 'my.csdn.net', 'Connection': 'keep-alive', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36...
# import requests, re # # req = requests.get("https://www.siteprice.org/website-worth/vnexpress.net") # # result = re.search('<span id="lblDailyPageviews" class="SiteDetailLabel">', req.text) # # result1 = req.text.split('<span id="lblDailyPageviews" class="SiteDetailLabel">') # result2 = result1[1].split('</span>') # ...
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
data1 = map(int,l(raw_input())) out = 1 for i in range(len(data1)): out = out*data1[i] print out
#Calculadora #input #2 numeros y operaicon def suma(a, b): return a+b def resta(a, b): return a-b def mult(a, b): return a*b def div(a, b): assert (b != 0), "No se puede divir por 0, melón." return (a/b) def pow(a, b): return a**b op = 0 print("\n\n") operacion = {1: suma, ...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. from openerp import models, fields class GesPark(models.Model): _name = "gestorparking" user_id = fields.Many2one('res.users','Empleado'...
# valueIterationAgents.py # ----------------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to ht...
import utils from collections import OrderedDict KEY = utils.ByteArray.random(16) def parse(s): res = OrderedDict() fields = s.split("&") for field in fields: k, v = field.split("=") res[k] = v return res def unparse(d): res = [] for k in d: v = d[k] if typ...
from collections import Iterable,Iterator,Container class bothIterAndNext: def __iter__(self): pass def __next__(self): pass # a = isinstance(bothIterAndNext(), Iterable) # print(a) # b = isinstance(bothIterAndNext(), Iterator) # print(b) class onlyNext: def __next__(self): pass # a...
#version 2 #improve initial version by calculating maxL dynamically class Solution(object): def longestValidParentheses(self, s): """ :type s: str :rtype: int """ stack = [] maxL = 0 for i in range(len(s)): if s[i] == ')' and stack and s[stack[-1]]...
# from typing import Optional # # from fastapi import APIRouter, Depends, HTTPException # from starlette.requests import Request # from starlette.status import HTTP_404_NOT_FOUND, HTTP_409_CONFLICT # from rearq import ReArq, constants # from rearq.job import JobStatus # from app.api.depends.depends_ import get_rearq, g...