text
stringlengths
38
1.54M
pessoas = [['Joao', 10], ['Leandro', 27]] for p in pessoas: print(f'O {p[0]} tem {p[1]} anos de idade')
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from flask_migrate import Migrate from config import Config db = SQLAlchemy() mi = Migrate() ma = Marshmallow() def create_app(config=Config): app = Flask(__name__) app.config.from_object(Config) db.init_...
import pandas as pd from anytree import NodeMixin, RenderTree from abc import ABC, abstractmethod from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.preprocessing import OneHotEncoder, LabelEncoder import numpy as np class DataTypes: BOOLEAN = 1 INTEGER = 2 FLOAT = 3 STRING = ...
from ..desktop import ConfigManager import unittest class TestConfigManager(unittest.TestCase): def setUp(self): self.c: ConfigManager = ConfigManager("test_data/cfg.json") def test_intime(self): self.c.setProperty("a", 5) cfg = ConfigManager("test_data/cfg.json") self.a...
from numpy import* v = array(eval(input("Vetor:"))) i = 0 while (i < size(v)): if(v[i]%2 != 0): v[i] = 0 i = i + 1 print(v)
list=[] for i in range(123,568): if i%5==0 or i%6==0: list.append(i) print(list) print(len(list)) print("sum= ",sum(list))
from snippet_analyser import SnippetAnalyser from snippet_matcher import SnippetMatcher from snippet_analysis_helper import LanguageMode import os class SnippetController: def __init__(self, snippet, task_arguments, task_comment, language_mode=LanguageMode.python, debug=False): self.task_arguments = task_...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from django.apps import apps from djangobmf.settings import CONTRIB_EMPLOYEE from djangobmf.settings import CONTRIB_TEAM def user_add_bmf(user): """ Adds ``djangobmf_employee`` and ``djangobmf_teams`` to the given user instance. """ if not hasattr(user, 'djangobmf_employee'): try: ...
##encoding=utf-8 """ This module is to teach you the basic use of wordsegmentation/tokenize (句子分词) What is tokenize? tokenize is to split sentence into word tokens and punctuations. For example: I like obama. => ["I", "like", "obama", "."] """ from __future__ import print_function from pprint import pprint ...
from pypboy import BaseModule from pypboy.modules.items import weapons from pypboy.modules.items import apparel from pypboy.modules.items import aid from pypboy.modules.items import misc from pypboy.modules.items import ammo class Module(BaseModule): label = "ITEMS" GPIO_LED_ID = 16 def __i...
# -*- coding: utf-8 -*- import unittest from mongoengine import NotUniqueError from utils import AnellaTestCase from anella.common import * from anella.model.user import User __all__ = ('UserTest', ) class UserTest(AnellaTestCase): def test_user_save(self): user = User(email='pepe@i2cat.net', auth_id...
from typing import List from arg.qck.decl import QKUnit from cache import load_from_pickle # Unfiltered candidates from top BM25 def load_qk_candidate_train() -> List[QKUnit]: return load_from_pickle("perspective_qk_candidate_train") # Unfiltered candidates from top BM25 def load_qk_candidate_dev() -> List[QKU...
import shutil from tqdm import tqdm import numpy.random as npr import numpy as np import random import glob import cv2 import PIL.Image as Image import os from threading import Thread,currentThread from multiprocessing import cpu_count cnt=0 class MyWorker(Thread): def __init__(self,imagelist,tgt,offset): ...
""" NOTE: This file is currently FUBAR. Do not look at this for anything meaningful! """ import numpy as np from gridworld import * from mdp_solver import * from sample_utils import sample_niw class Observation(object): def __init__(self, episode, state, reward, reward_stdev, goal = False): self.episode = ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #PIN configuration pinOutControl = 40 pinPIR = 38 trigSR04 = 35 echoSR04 = 37 #Global Parameters lengthCM_SR04 = 15 #距離SR04在幾公分以內, 才認定為正開始使用照護系統 timeLasted_SR04 = 5 #有人站在SR04面前持續了幾秒後, 才認定為要始用照護系統 nextWelcomeTimer = 60 #上次Welcome之後, 至少要隔多久才能再Welcome #speakerName = ["B...
#! /usr/bin/env python import unittest from sha2 import * class SingleSHA256(unittest.TestCase): def setUp(self): self.f = sha256 def test_empty(self): self.assertEqual(self.f('abc').hexdigest(), 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') # ba...
"""The Quality-time data model.""" from .meta.data_model import DataModel from .metrics import METRICS from .scales import SCALES from .sources import SOURCES from .subjects import SUBJECTS DATA_MODEL = DataModel(scales=SCALES, metrics=METRICS, sources=SOURCES, subjects=SUBJECTS) DATA_MODEL_JSON = DATA_MODEL.json(exc...
import os import sys ### Other Python Libraries import itertools import pdb from operator import itemgetter import multiprocessing as mp ### MST Imports from .NAC_Graph import NAC_Graph from .Kruskal_Class import Kruskal_MST as MST ### imports import Core.Solvers.SAA.SAA_NAC as SAA_NAC def NAC_Generator(Uncertain_...
# Generated by Django 3.2 on 2021-05-24 09:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0003_auto_20210524_0857'), ] operations = [ migrations.AddField( model_name='user', name='passcoord', ...
import httplib, urllib import json import uuid P9SERVER = 'localhost:8080' class APIException(Exception): pass import webrtc config = { iceServers: [ { "url": "stun:stun.l.google.com:19302" }, { "url": "stun:stun.services.mozilla.com" }, ] }; c...
#!/usr/bin/env python import os,sys import MySQLdb import string import re from optparse import OptionParser DBNAME = "postfix" DBUSER = "aliaser" # trick to read keyfile from same dir as actual script, even when called via symlink keyfile = os.path.dirname(os.path.realpath(__file__))+"/postfix_alias.key" f = open(ke...
import json json_data = {} def readjson(file_path): f = open(file_path) line = f.readline() # print(line) f.close() array = json.loads(line) return array def readlist(index): return json_data[str(index)] json_data = readjson("json.txt") # for i in range(0, nt): # print(readlist(i))...
from bs4 import BeautifulSoup import requests import re import requests_cache def obter_pagina(link,links): html = " " try: if permitido(link,links): response = requests.get(link) print("Baixando: %s" %link) links.append(link) html = BeautifulSoup(respons...
print("--------------Replacing a string from the sentence--------------\n") sentence = input("Enter a sentence:") final_output = sentence.replace('python', 'pythons') print(final_output)
class Stack: def __init__(self): self.stack = [] self.len_stack = 0 def push(self, e): self.stack.append(e) self.len_stack += 1 def pop(self): if not self.empty(): self.stack.pop(self.len_stack - 1) self.len_stack -= 1 de...
##By replacing the 1st digit of *3, it turns out that six of the nine possible ##values: 13, 23, 43, 53, 73, and 83, are all prime. ##By replacing the 3rd and 4th digits of 56**3 with the same digit, this 5-digit ##number is the first example having seven primes among the ten generated numbers, ##yielding the famil...
# Generated by Django 3.0.7 on 2020-06-30 00:27 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0018_auto_20200629_0314'), ] operations = [ migrations.RemoveField( model_name='records', na...
# coding: utf-8 """ 对svn命令的包装 """ import commands import traceback from tyserver.tyutils import tylog try: from lxml import etree except: tylog.error("import etree error") def svnCmd(workingpath, cmd, *svnArgs): tylog.debug('svnCmd <<| workingpath, svnCmd, svnArgs:', workingpath, cmd, '...
#encoding=utf-8 import codecs import batcher import data from collections import namedtuple bin_path = "/home/bigdata/active_project/run_tasks/query_rewrite/stable/stable_single/copy_data_format/chunked/train*" vocab_path = "/home/bigdata/active_project/run_tasks/text_sum/data/vocab/vocab.txt" data_generater = data.ex...
import os import csv #find the file we want to read file_path = os.path.join('Resources', 'budget_data.csv') #declare everything before connecting to file total_months = 0 past_total = 0 net_profits_loss = 0 greatest_increase = 0 greatest_decrease = 0 #create empty list to store data total_change = [] date = [] #ope...
import math class Solution(object): def countBits(self,num): """ :param num: :return: List[int] """ if num==0: return [0] num_1s=[0]*(num+1) for i in range(num+1): binarys = bin(i)[2:] print binarys num_1 = 0 ...
from pymongo import MongoClient import re import datetime collection_json = [ { "col_name" : "ticket_goods", "count" : 0, "list": "" }, { "col_name" : "ticket_man", "count" : 0, "list": "" } ] collection_arr = ["ticket_goods", "ticket_man"] # 방법1 - URI m...
"""Abstract base class from some SciUnit unit test cases""" from sciunit import TestSuite from sciunit.tests import RangeTest from sciunit.models.examples import UniformModel class SuiteBase(object): """Abstract base class for testing suites and scores""" def setUp(self): self.M = UniformModel ...
# Generated by Django 2.0.3 on 2018-05-31 06:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('SRTP', '0005_auto_20180531_0551'), ] operations = [ migrations.AlterField( model_name='srtp', ...
# -*- mode: python -*- import os from openal.al_lib import lib import platform from ctypes.util import find_library from ctypes import CDLL, c_void_p, c_int, c_char_p, byref, cast, POINTER, Structure import PyInstaller.depend.bindepend as bd block_cipher = None # Assumes that the libraries under Linux a...
# -*- coding: utf-8 -*- import sys from easykiwi import KiwiClient # pylint: disable=invalid-name body = ' '.join(sys.argv[1:]) or '___' client = KiwiClient() with client.connect('127.0.0.1') as comm: # send message with different sender and subject # listen by two subscriber sendr = 'bob.jones' s...
def isAnagram(s, t): # s1 # return sorted(t) == sorted(s) # s2 # if len(s) != len(t): # return False # setS = dict() # setT = dict() # for i in range(len(s)): # if (s[i] in setS): # setS[s[i]] = setS[s[i]] + 1 #...
import urllib2 import json import matplotlib.pyplot as plt def getUser(username): """ function getUser parses json page with user information returns page content in string format """ url = "http://forum.toribash.com/tori_stats.php?username=%26%2312579%3B"+username+"&format=json" response = url...
# Generated by Django 3.2.5 on 2021-07-12 04:54 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('bank', '0002_transfers'), ] operations = [ migrations.RenameModel( old_name='transfers', new_name='transfer', ...
from django.contrib import admin from django.db.models import Count from drf_api_logger.utils import database_log_enabled if database_log_enabled(): from drf_api_logger.models import APILogsModel class APILogsAdmin(admin.ModelAdmin): def added_on_time(self, obj): return obj.added_on.str...
#!/usr/bin/env python import re import struct import subprocess import sys def getsyms(fname): rgx = re.compile("([0-9a-f]+) T idt_entry_0x([0-9a-f][0-9a-f])") ret = {} out = subprocess.check_output("$NM %s" % fname, shell=True) for line in out.split("\n"): mtch = rgx.match(line) if mtc...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import logging import os import time import mshoot # Set up logging logging.basicConfig(filename='mpc_case3.log', filemode='w', level='DEBUG') # Random seed np.random.seed(12345) # Paths ms_file = os.path.join('examples', 'bs2019', 'measurements...
import os.path import util.io import util.preprocessor # import util.postprocessor import build as main def out_name(inp, lang): n, ext = os.path.splitext(inp) if main.cfg.preserve_paths: return os.path.join(main.cfg.out, os.path.relpath(n) + util.fmt_ext(lang.out_extension)) else: return ...
# ----------------------------- # File: Main # Author: Yiting Xie # Date: 2018.9.10 # E-mail: 369587353@qq.com # ----------------------------- import gym import numpy as np import argparse from agent_dqn import Agent,process_observation ''' ENV_NAME = 'MsPacman-v0' # game name EPISODES = 15000 ISTRAIN = Tr...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-09-18 12:55 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0006_auto_20170918_1252'), ] operations = [ migrations.RemoveField( ...
from processCamFrame import processCamFrame import numpy as np def getPaperCoor(cap, paperScrnMat): # read video frame _, frame = cap.read() # get the current white blob centroid cX, cY = processCamFrame(frame) if cX == 0 and cY == 0: return (0,0) else: # find the nearest point that can be mapped to di...
import streamlit as st from PIL import Image import pickle import numpy as np pickle_in = open("forest_model1.pkl", "rb") model = pickle.load(pickle_in) def main(): img=Image.open('Billboard_Hot_100.jpg') img=img.resize((267,176)) st.image(img, use_column_width=False) st.title("BillBoard Hit Predictor...
import numpy as np def get_likelihood_singledataset(x,y,err_y,m,q): L1 = 1 for err_y_i in err_y: L1 = L1 * (1/(2*np.pi*err_y_i**2))**0.5 lnL1 = np.log(L1) L2 = 0 for x_i,y_i,err_y_i in zip(x,y,err_y): model_i = m*x_i + q L2 = L2 + 0.5 * ((y_i - model_i)**2/err_y_i**2) lnL = lnL1 - L2 ...
fileName = r'D:\Python\05Example\log02.txt' str = 'Name:Lee Jack(李吉凯) \nPhoneNumber(手机号码):13600173445\n' #str类型 mem = str.encode('gbk').decode('iso-8859-1') #byte类型 with open(fileName,'w', encoding='iso-8859-1') as f: f.write(mem) print('写入成功!')
from Preprocessing import * import matplotlib.pyplot as plt dir = 'C:/Users/user/switchdrive/Wristband Comparison/Signals/' ######## E4 ########################################################### # Read the raw file and create a file in the directory related to te session (e.g session 1 , 2 ,..) only with Time and EDA...
'''思路是,每次添加一个岛屿的时候,我们就更新union find里的parent的记录,并且假设多了一个额外的岛屿count++ 然后只有当这个岛屿相邻的四个方向上存在岛屿,才会trigger union的操作,将这些岛屿连在一起,count-- [0, 0] ''' class UF(): def __init__(self, m, n): self.parent = [-1] * (m * n) self.size = [0] * (m * n) self.count = 0 self.mRows = m self.nCols = n ...
""" The ledger_closed method returns the unique identifiers of the most recently closed ledger. (This ledger is not necessarily validated and immutable yet.) """ from dataclasses import dataclass, field from xrpl.models.requests.request import Request, RequestMethod from xrpl.models.required import REQUIRED from xrpl....
# Generated by Django 3.1.3 on 2020-12-10 07:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('notesapp', '0001_initial'), ] operations = [ migrations.RenameField( model_name='notes', old_name='createdtime', ...
# coding=utf-8 # Copyright 2020 The TF-Agents Authors. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
# -*- coding: utf-8 -*- """ Created on Tue Jan 7 22:12:07 2020 @author: ingrida grigonyte """ def get_message(msg): msgs = { 'msg_1': 'Érvénytelen bemenet!', 'msg_2': 'Kérem, írjon be egy számot!', 'msg_3': 'Kérjük, csak arab vagy római számot írjon be!', 'msg_4'...
import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),'..'))) from src import utils class WeatherAlertTrigger: def __init__(self, json_dict=None, event_id=None, severities=None, zones=None, ...
import numpy as np from agent import BaseAgent from abc import ABCMeta, abstractmethod class ReplayBuffer: def __init__(self, size, minibatch_size, seed): """ Args: size (integer): The size of the replay buffer. minibatch_size (integer): The sample size. seed (...
# -*- coding: utf-8 -*- """ Created on Mon Dec 2 23:12:08 2018 @author: Ramesh """ import pandas as pd import numpy as np #Import cds data file data1 = pd.io.stata.read_stata('/Users/ramesh/Desktop/cds_spread5y_2001_2016.dta') # convert cds data to csv file data = data1.to_csv('/Users/ramesh/Desktop/cds...
list(map(lambda x: (5/9)*(x-32),F_temps)) #nâo da para executar esse comando pois não fiz ele completo,eu usei ele só para #entender como funciona map() no lambda.
# RDMA PD Configuration Spec meta: id: MR_RDMA # This count is initialized to 1000 for RTL runs count : 16 useAdmin : True
# -*- coding: utf-8 -*- """ Created on Tue May 12 20:27:19 2020 @author: slothfulwave612 Python module for i/o operations. Modules Used(3):- 1. pandas -- data manipulation and analysis library. 2. datetime -- Python library for datetime manipulation. 3. json -- Python library to work with JSON data. """ import pand...
class Solution: def maxScore(self, s: str) -> int: zeros = 1 if s[0] == '0' else 0 ones = s[1:].count('1') ans = zeros + ones n = len(s) for c in range(1, n-1): if s[c] == '0': zeros += 1 else: ones -= 1 ans...
#!/usr/bin/python3 import requests def retrieve_xml(url="", method="get", params=""): method = method.lower() if method == "get": r = requests.get(url, params) return r if method == "post": pass if method == "put": pass if method == "delete": pass ...
# 2019/08/09 n,m=map(int,input().split()) cnt=min(n,m//2) m-=cnt*2 n-=cnt if m//4>0: cnt+=m//4 print(cnt)
#!/usr/bin/env python # Handle all globals variables def init(): # ----------------------------------------------------------------------------- # Setting GPIO allocation global SERB_TOGGLE_BEC SERB_TOGGLE_BEC = 24 global SERB_TOGGLE_GIMBAL SERB_TOGGLE_GIMBAL = 23 global SERB_TOGGLE_LIGH...
""" 7. По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника, составленного из этих отрезков. Если такой треугольник существует, то определить, является ли он разносторонним, равнобедренным или равносторонним. """ storona1 = int(input('Введите длину стороны 1: ', )) storon...
import datetime import hashlib import json from flask import Flask, jsonify, request import requests from uuid import uuid4 from urllib.parse import urlparse # PART 1 ---------------------------------------------------------- # Building the blockchain class Blockchain: def __init__(self): self.chain = [] ...
# Group Anagrams # https://leetcode.com/problems/group-anagrams/ # 애너그램은 문자열을 재배열해서 다른 뜻을 가진 단어로 바꾸는 것을 말한다. # 애너그램을 판별하는 방법은 정렬하여 비교하는 것이 가장 간단해 보인다. 정렬하는 방법은 sorted 함수를 사용해 준다. # 정렬되어 나온 값은 리스트 형태이기 때문에 join 으로 합쳐서 이 값을 키로 딕셔너리를 만들어 준다. # 만약 없는 키를 넣어줄 경우 keyerror가 생겨 에러가 나지 않도록 defaultdict()으로 정리하고, # 매번 키 여부를 확인하지 ...
#!/usr/bin/env python # notify_celery is referenced from manifest_delivery_base.yml, and cannot be removed from app import notify_celery, create_app application = create_app('delivery') application.app_context().push()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 20 20:49:04 2017 @author: mmonforte Next, implement the function getGuessedWord that takes in two parameters - a string, secretWord, and a list of letters, lettersGuessed. This function returns a string that is comprised of letters and underscore...
import random random.SystemRandom() items=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] thumon=random.sample(items,1) print('Thu mon:',thumon) items2=list(set(items)-set(thumon)) hauve=random.sample(items2,4) print('Hau ve:',hauve) items3=list(set(items2)-set(hauve)) tienve=random.sample(items3,4)...
def sum_of_nested_list(x): if len(x) == 0: return 0 else: if isinstance(x[0], list): return sum_of_nested_list(x[0]) + sum_of_nested_list(x[1:]) else: return x[0] + sum_of_nested_list(x[1:]) print(sum_of_nested_list([1,2,3,[4,5]]))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #plot total wall clock time to complete AFNI_data6 https://afni.nimh.nih.gov/pub/dist/doc/htmldoc/background_install/unix_tutorial/misc/install.data.html # s01.ap.simple import pandas as pd import seaborn as sns import matplotlib.pyplot as plt #MacBook i5-8259U #Ubuntu...
import sys import os if not os.path.exists('Public'): os.makedirs('Public') if not os.path.exists('External'): os.makedirs('External') allFiles = set() for root, directories, filenames in os.walk('Sources/'): for filename in filenames: # Matching only header files if not filename.lower(...
import random import numpy as np import nn import copy from collections import deque class QLearn: def __init__(self, puzzleSize, epsilon, alpha, gamma): # exploration factor between 0-1 (chance of taking a random action) self.epsilon = epsilon # learning rate between 0-1 (0 means never u...
#!/usr/bin/python ''' DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE Version 2, December 2004 Copyright (C) 2013 Saurabh Dingolia <dinsaurabh123@gmail.com> Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as ...
""" EJERCICIO 10 El programa tiene que pedir la nota de 15 alumnos y sacar por pantalla cuantos han aprobado y cuantos han suspendido. """ cant_aprob = 0; cant_desaprob =0; for contador in range (0,15): nota = int (input (" Ingrese nota: ")) if nota >= 7: cant_aprob =+1 print (f"Cantidad de aproba...
# using random import random print(random.random()) # random number between 0 and 1 print(random.randint(5, 50)) # random int between 5 and 50 print(random.choice([1, 5, 10, 15, 20, 25])) # choose a random from this list x = 50 y = 5.5 z = x + y + 5j # printing the type of variables print(x, type(x)) print(y, typ...
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from os import environ app = Flask(__name__) # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root@localhost:3306/bubbletea' app.config['SQLALCHEMY_DATABASE_URI'] = environ.get('dbURL') app.co...
import unittest from src.calculator.calculator import Calculator class CalculatorTestCase(unittest.TestCase): def setUp(self) -> None: self.calculator = Calculator() def test_instantiate_calculator(self): self.assertIsInstance(self.calculator, Calculator) def test_result_is_zero_calcula...
import numpy as np import time from ACO import ACO from MatrixGraph import MatrixGraph mtxgraph = MatrixGraph() distances = mtxgraph.encode_to_array('example.tsp') aco = ACO(distances, 1, 1, 100, 0.95, alpha=1, beta=1) mtxgraph.normalize_answer(shortest_path) print("The shortest path in the graph is {} with length {}"...
import time # from time import timestamp from itsdangerous import TimedJSONWebSignatureSerializer as Serializer timestamp = time.time() def genTokenSeq(expires): s = Serializer(secret_key="123456789", salt="123456789", expires_in=expires) return s.dumps({"user_id": "1614010432", "user_role": "1", "iat": ti...
from django.urls import path from . import views from . import course_views from . import staff_views app_name = 'cms' urlpatterns =[ path('',views.index,name='index'), path('add_news/',views.AddNewsView.as_view(),name='add_news'), path('news_category/',views.news_category,name='news_category'), path('...
from flask import json from flask import Response from contentful import Entry from bson.objectid import ObjectId from bson import json_util from datetime import datetime def to_json(document=None, code=200): return Response( json.dumps(document, sort_keys=True, default=json_formater), status=code, mimetype...
def extended_euclidean(a, b): r_prev, r = a, b s_prev, s = 1, 0 t_prev, t = 0, 1 while r: q = r_prev // r r_prev, r = r, r_prev - q*r s_prev, s = s, s_prev - q*s t_prev, t = t, t_prev - q*t return s_prev, t_prev def find_inverse(x, p): inv, _ = extended_euclidea...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tweetclass', '0006_query_data_hm_tweets'), ] operations = [ migrations.CreateModel( name='Test_tweet', ...
import mysql.connector as sql import pandas as pd config = { 'user':'root', 'password':'AirQualityDB_2018', 'host':'localhost', 'database':'bom_data_test' } db_connection = sql.connect(**config) df = pd.read_sql("SELECT * FROM bom_data_test.066062 LIMIT 1000",con=db_connection) print(df)
"""将所有重合的地方剔除掉只留下不重合的数据""" char_list = ['a', 'b', 'c', 'c', 'd', 'd', 'd'] sentence = 'Welcome Back to This Tutorial' print(set(char_list)) # {'d', 'a', 'c', 'b'} print(set(sentence)) # 大小写区分,空格区分 # {'r', 'T', 'm', 'l', 'o', 'h', 'e', 'a', ' ', 'i', 'W', 'B', 'k', 'u', 'c', 's', 't'} """下面这句话是错误的,不能在其中使用列表和列表的形式,只...
# -*- coding: utf-8 -*- import urllib import urllib2 from urllib2 import URLError, HTTPError import json import pdb import os import sys import codecs import re p = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, p) os.environ['DJANGO_SETTINGS_MODULE'] = "sefaria.settings" from local_set...
from svglib.svglib import svg2rlg from reportlab.graphics import renderPM import PySimpleGUI as simpleGUI import re from PIL import Image # from anticaptchaofficial.imagecaptcha import imagecaptcha captcha_svgFile = './captcha/captcha.svg' captcha_pngFile = './captcha/captcha.png' captcha_gifFile = './captcha/captcha....
# https://atcoder.jp/contests/abc271/tasks/abc271_c # # def input(): return sys.stdin.readline().rstrip() # # input = sys.stdin.readline # from numba import njit # from functools import lru_cache import sys input = sys.stdin.buffer.readline # sys.setrecursionlimit(10 ** 7) N = int(input()) a = list(map(int, input().s...
import findspark from pyspark.sql import SparkSession import pyspark.sql.functions as f from pyspark.sql.functions import split # ------------------------------------ TASK ------------------------------------ # 1- Given this yearly income ranges, <40k, 40-60k, 60-80k, 80-100k and 100k>. # Generate a report that...
import sys sys.stdin = open('input.txt', 'r') N = int(input()) count = 0 for i in range(2, N+1, 2): for j in range(1, N+1-i): k = N - (i + j) if k >= j+2 and k != 0: count += 1 print(count)
import sys import math with open('./popular-names.txt', mode="r") as f: n = int(sys.argv[1]) lines = [line.rstrip() for line in f] n_split = math.ceil(len(lines) / float(n)) fs = [open(f"f_{i}.txt", mode="w") for i in range(n)] i = 0 cnt = 0 for line in lines: fs[i].write(line + "\n...
from pathlib import Path project_root = Path(__file__).parent.absolute() import os import random import math from collections.abc import Sequence from functools import partial import torch import pytorch_lightning as pl from pytorch_lightning.callbacks import Callback from munch import Munch import ray from ray im...
#Complete code below to count number of letters fav_word = "supercalifragilisticexpialidocious" # Your code below count = 0 for letter in fav_word: if letter == 'i': count = count + 1 print(count)
if __name__ == '__main__': my_number = 5 while True: user_number = int(input("Guess a number - ")) if user_number == my_number: print("Number guessed!") break elif user_number < my_number: print("Cold") elif user_number > my_number: ...
# Generated by Django 3.2 on 2021-04-09 03:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('RatingCounter', '0007_auto_20210408_1648'), ] operations = [ migrations.AddField( model_name='ratingcountermodel', ...
from ..core import db from ..models import FileModel from ..models import CommentModel from ..models import ProjectModel from ..models import EnvironmentModel # from ..models import ApplicationModel import datetime import json from bson import ObjectId class RecordModel(db.Document): project = db.ReferenceField(Pr...