text
stringlengths
38
1.54M
# Calcule a média entre dois valores va1= float(input('valor 1: ')) va2 =float(input('valor 2: ')) media = (va1 + va2)/2 print('A média entre {} e {} é igual a {:.1f}' .format(va1, va2, media))
import numpy as np import matplotlib.pyplot as plt from src.utils2 import get_path from src.data_interface import trd, L path = get_path(__file__) + '/..' for fname in L[2:]: for tid in trd.trial_id_list: v = trd.get_trial(tid).get_feature(fname).view() plt.plot(range(len(v)), v, 'b-', alpha=0.1...
# Databricks notebook source # MAGIC %md # Delta Generated Columns & buckets # MAGIC Delta now supports Generated Columns syntax to specify how a column is computed from other columns. # MAGIC A generated column is a special column that’s defined with a SQL expression when creating a table. # MAGIC # MAGIC This is use...
# coding=utf-8 from __future__ import absolute_import __author__ = "Gina Häußge <osd@foosel.net>" __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The bioprint Project - Released under terms of the AGPLv3 License" import io import unittest im...
import torch from allennlp.common.registrable import Registrable from typing import Tuple class CoverageMatrixAttention(torch.nn.Module, Registrable): """ The ``CoverageMatrixAttention`` computes a matrix of attention probabilities between the encoder and decoder outputs. The attention function has access...
for number in range(101): if number % 3==0 and number % 5 ==0: print("FizzBuzz") continue elif number % 3==0: print("Fizz") continue elif number % 5==0: print("Buzz") continue print(number)
def main(): fin = open('B-large.in','r') fout = open('output2.txt', 'w') cases = int(fin.readline()) for i in range(cases): test = (fin.readline().strip()) result = combinations(test) output = "Case #{}: {}".format((i + 1), result) print output fout.write(ou...
import os from ibm_watson import SpeechToTextV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import json def sttWatson(audio_input): authenticator = IAMAuthenticator('P3_Qv43uneTlHj47J-9YhThh0JfAzPF0EN7eooqDvrm8') speech_to_text = SpeechToTextV1( authenticator=authenticator ) ...
s=0 i=0 n=int(input("dati n: ")) for i in range(1,n): if(i%3==0) and (i%5==0): s+=i print(s)
"""Evaluate a model on the task of video corpus moment retrieval !!! This program will not run !!! We are providing it to showcase the evaluation protocol """ import argparse import json import logging from datetime import datetime from pathlib import Path import h5py import numpy as np import pandas as pd import tor...
#from oauth2_provider import __author__ = 'dmorina' from oauth2_provider.oauth2_backends import OAuthLibCore, get_oauthlib_core from oauth2client import client from oauthlib.common import urlencode, urlencoded, quote def oauth_create_client(user, client_name): #r_client = client. #r_client.save() #return r_...
'''Functions''' from datetime import datetime from time import sleep # Write a function with def() # ----------------------------------------------------------------------------- # Function names can start with letters or _ and contain only letters, numbers # and _. Pass means do noting but move on. It's a placehol...
#!/usr/bin/env python # Copyright (C) 2013 Andy Aschwanden from sys import stderr from argparse import ArgumentParser try: from netCDF4 import Dataset as NC except: from netCDF3 import Dataset as NC from osgeo import ogr # Set up the option parser parser = ArgumentParser() parser.description = "All values wi...
nn=float(input("please enter first number\n")) mm=float(input("please enter second number\n")) o=(input("pleae enter your operation\n")) if o=="+": print(f"{nn}+{mm}={nn+mm}\n") elif o=="*": print(f"{nn}*{mm}={nn*mm}\n") elif o=="/": print(f"{nn}/{mm}={nn/mm}\n") elif o=="-": print(f"{nn}-{mm}={nn-mm}\n...
""" Similar to longest-increasing-subsequence """ def get_mis(arr): n = len(arr) mis = [] for i in arr: mis.append(i) for i in range(1, n): for j in range(0, i): if arr[i] > arr[j] and (mis[j]+arr[i]) > mis[i]: mis[i] = mis[j]+arr[i] print(mis) arr = ...
from enum import Enum, unique @unique class EventType(Enum): UNKNOWN = -1 DEL = 0 NEW = 1
"""Определяем схемы URL для blogs""" from django.urls import path, re_path from .import views urlpatterns = [ path('', views.index, name='index'), path('notes/', views.notes, name='notes'), re_path(r'^notes/(?P<note_id>\d+)/$', views.note, name='note'), path('new/', views.new, name='new'), re_path...
import pymesh from pymesh.TestCase import TestCase import numpy as np import numpy.linalg class HarmonicSolverTest(TestCase): def test_linear_function(self): mesh = pymesh.generate_icosphere(1.0, np.zeros(3), 2); tetgen = pymesh.tetgen(); tetgen.points = mesh.vertices; tetgen.trian...
from io import StringIO import pandas as pd import numpy as np import sqlite3 from sklearn.impute import SimpleImputer def get_data(data_set) -> (pd.DataFrame, np.ndarray): # TODO get latest loaded csv df = pd.read_csv(StringIO(data_set)) y = np.array(df['state']) X = df.drop(['state'], axis=1) ...
from pathlib import Path import pytest from flit.common import Metadata from flit.inifile import read_pkg_ini samples_dir = Path(__file__).parent / 'samples' def test_extras(): info = read_pkg_ini(samples_dir / 'extras.toml') assert info['metadata']['requires_extra']['test'] == ['pytest'] assert info['m...
import jswRSA import pickle import hashlib class DigitalSignaturer: def __init__(self,privateKey=None,publicKey=None): if (publicKey is not None): publicKeyFile = open(publicKey, 'rb') resotredPublicKey = pickle.load(publicKeyFile) self.rsa = jswRSA.jswRSA(publicKey=reso...
from django.apps import AppConfig class TrashOSConfig(AppConfig): name = 'trashos_server' verbose_name = "Trash OS Server"
from tkinter import * from tkinter.messagebox import * from socket import * import threading,sys,json,re from MainPage import * ##socket HOST = '127.0.0.1' PORT = 8022 BUFFERSIZE = 1024 ADDR = (HOST, PORT) myre = r"^[_a-zA-Z]\w{0,}" tcpClintSock = socket(AF_INET, SOCK_STREAM) class LoginPage(object): def __init_...
from django.urls import reverse_lazy from django.views.generic import CreateView, DetailView, ListView from autos.forms import autosForm from .models import autos class autosListView(ListView): model = autos context_object_name = 'all_the_autoss' template_name = 'autos-list.html' class autosDetailView...
# robot game # use commands: right, left, up, down, fire, status and quit class Robot: def __init__(self): self.XCoordinate = 10 self.YCoordinate = 10 self.FuelAmount = 100 def move_left(self): if (self.FuelAmount <=0): print("Insufficient fuel to perform action") else: self....
# -*- coding:utf8 -*- import tornado.web import re touch_re = re.compile( r'.*(iOS|iPhone|Android|Windows Phone|webOS|BlackBerry|Symbian|Opera Mobi|UCBrowser|MQQBrowser|Mobile|Touch).*', re.I) class BaseHandler(tornado.web.RequestHandler): @property def theme(self): '''获取访问类型 ''' tr...
# -*- coding: utf-8 -*- """ Created on Tue Jun 6 10:37:06 2017 @author: Samuel """ # change just to push to github!!!!! """Introduction to Bayesian Inference""" import numpy as np from scipy import stats import matplotlib.pyplot as plt #Create a list of the number of coin tosses ('Bernoulli Trials') number_of_trial...
from alayatodo.models import Todos, Users from alayatodo import db def init_fixture(): user1 = Users(username="user1",password="user1") user2 = Users(username="user2",password="user2") user3 = Users(username="user3",password="user3") db.session.add(user1) db.session.add(user2) db.session.add(user3) db...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res, level = [...
""" pems_delete.py """ import requests from .exceptions import AgaveFilesError from ..utils import handle_bad_response_status_code def files_pems_delete(tenant_url, access_token, path): """ Remove user permissions associated with a file or folder. These permissions are set at the API level and do no...
# 11_CountVectorizer01.py from sklearn.feature_extraction.text import CountVectorizer # CountVectorizer : 문자열에서 단어 토큰을 생성하여 BOW로 인코딩된 벡터를 생성해줍니다. # df : document-frequency # min_df = 2 : 최소 빈도가 2번 이상인 단어들만 .. # stop_words = 불용어 (제외) vectorizer = CountVectorizer(min_df=2, stop_words=['친구']) print(type(vectorizer)) s...
import tensorflow as tf from tf_rl.common.utils import * from tf_rl.agents.core import Agent_atari, Agent_cartpole class DQfD_atari(Agent_atari): """ DQfD """ def __init__(self, model, optimizer, loss_fn, grad_clip_fn, num_action, params): self.params = params self.num_action = num_ac...
# This is a function for k-fold cross-validation on (X; y) # Yi Ding import numpy as np # This function return the accuracy score of the prediction for classification def my_accuracy_score_classification(ytrue, ypred, metric): ytrue = np.array(ytrue) ypred = np.array(ypred) if ytrue.shape[0] !=...
from typing import List, Optional import databricks.koalas as ks import numpy as np import pandas as pd from pyspark.ml.feature import Bucketizer from sklearn.base import BaseEstimator, TransformerMixin from data_utils.preprocessing.base import set_df_library class ColumnBinner(BaseEstimator, TransformerMixin): ...
from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from transferencia.models import Transferencia, Troca from header.validators import consultar_bi_existe, validar_comprimento_4, validar_numeros, validar_string, validar_bi, consultar_numero_agente, consultar_b...
#!/usr/bin/python import smbus import time import hd44870_lib as lcd lcd.lcd_init() lcd.lcd_clean() while(1): lcd.lcd_backlite(True) lcd.lcd_write_lines("test1","test2") time.sleep(1) lcd.lcd_write_lines("test2","test1") time.sleep(1) lcd.lcd_backlite(False) lcd.lcd_write_lines("test1","test2") time.sle...
from django.template import Context from .models import ContactInfo def contact(request): details = ContactInfo.objects.get(id=1) return {'contact_info': details}
numb=int(input("Enter the number")) if numb < 0: print("Enter a positive number") else: sum = 0 while(numb > 0): sum += numb numb -= 1 print("The sum is",sum)
from django.conf.urls import url, include from rest_framework import routers from project.api import views router=routers.DefaultRouter() router.register(r'users',views.UserViewSet) urlpatterns=[ url(r'^',include(router.urls)), url(r'^api-auth',include('rest_framework.urls',namespace='rest_framework')) ]
# convert_gui.pyw # program to convert Celsius to Farenheit using a simple graphical interface from graphics import * def main(): win = GraphWin("Celsius Converter", 400, 300) win.setCoords(0.0, 0.0, 3.0, 4.0) # Draw the interface Text(Point(1,3), " Celsius Temperature:").draw(win) Text(Point(1,...
import time import subprocess import rclpy from rclpy.node import Node from tms_msg_ts.srv import TsReq from tms_msg_ts.srv import TsStateControl class Task: def __init__(self): self.rostime = 0 self.task_id = 0 self.robot_id = 0 self.object_id = 0 self.user_id = 0 ...
from time_dependent_ssa import SSA from math import * from scipy.stats import norm dnorm = norm.rvs from utils import * from collections import defaultdict import mpmath gamma_m_rate = log(2)/15 gamma_p_rate = 0 #log(2)/20 #??? sample_kr2_rate = lambda :max(0,dnorm(0.5,0.1)) sample_kr3_rate = lambda :max(0,dnorm(2,0.4...
from sudachipy import dictionary from sudachipy import tokenizer sudachi = dictionary.Dictionary().create() mode = tokenizer.Tokenizer.SplitMode.C line = 'ゼロ様の言うとおりでいしたわ' doc = sudachi.tokenize(line, mode) doc = list(reversed(doc)) bunsetu = '' bunsetu_list = [] for i, token in enumerate(doc): print(token.surfac...
# This is created for reporting only. # The api's here should not be used by normal application code. # All api's should have the require_api_key_auth decorator and # the url should be prefixed with /reports
import numpy as np import requests from urllib.parse import urlencode import hashlib import hmac import time import json from const import ORDERBOOK_DEPTH from keys import API_KEY, SECRET_KEY BINANCE_API_V3 = 'https://api.binance.com/api/v3/' SYMBOLS_URL = BINANCE_API_V3 + 'exchangeInfo' TICKERS_URL = BINANCE_API_V3 +...
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2019-03-01 07:58 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('wildlifecompliance', '0138_auto_20190301_1513'), ] operations = [ migrations.AlterU...
def bisection(func,low,high,k,epsilon): ans = (high + low)/2.0 numGuesses = 0 while abs(func(ans,k)) >= epsilon: numGuesses += 1 if ans**2 < k: low = ans else: high = ans ans = (high + low)/2.0 return ans,numGuesses
# -*- coding: utf-8 -*- import logging as log import time import findIt import re from ga import Ga from nltk.tokenize import sent_tokenize from nltk.tokenize import word_tokenize from file import saveStats from file import readText from rouge_score import rouge_scorer # Constants reference = "Senators McClure (R) and...
success numbers of shp >>> import os ... import glob ... from arcpy import env ... env.workspace = "G:/7gaodetraffic/" ... # Open one of the files, ... folder_path = 'G:/7gaodetraffic/4delete duplicate/' ... road= glob.glob(r'G:/7gaodetraffic/4delete duplicate/*.shp') ... print len(road) ... 96 ...
# -*- coding: utf-8 -*- """ Created on Tue Nov 19 14:19:26 2019 @author: vener """ import pandas as pd from bisect import bisect_left def take_closest(myList, myNumber): """ Assumes myList is sorted. Returns closest value to myNumber. If two numbers are equally close, return the smallest num...
""" 1970. Last Day Where You Can Still Cross Hard 367 6 Add to List Share There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. Howev...
from assignment3_3 import * from sklearn_Kmeans_3 import * header = ['id','date','tweet'] df=pd.read_csv(open('foxnewshealth.txt'), sep = '|', header=None, names=header, engine='c') skdf = preprocess(df) df = preprocess(df) # sklearnKMeans(skdf) x = vectorize(df) clf = K_Means() clf.fit(x) predictions =...
import os #每次修改这个目录 d=r'D:\友高工作\发布内容要求\城堡\14' lst = os.listdir(d) n = len(lst) for a in lst: os.rename(d+"\\"+a, d+"\\"+str(lst.index(a)+1)+".JPG") print("ok")
# -*- coding: utf-8 -*- import re from .._globals import IDENTITY from ..helpers.methods import varquote_aux from .base import BaseAdapter class MySQLAdapter(BaseAdapter): drivers = ('MySQLdb','pymysql', 'mysqlconnector') commit_on_alter_table = True support_distributed_transaction = True types = { ...
import struct messageTypes = { 'Accept' : 0x1, 'Reject' : 0x2, 'Join' : 0x3, 'Status' : 0x4, 'Task' : 0x5, 'Start' : 0x6, 'Stop' : 0x7, 'Finished' : 0x8, 'Disconnect' : 0x9, #reverse 0x1 : 'Accept', 0x2 : 'Reject', 0x3 : 'Join', 0x4 : 'Status', 0x5 : 'Task', 0x6 : 'Start', 0x7 : 'Stop', 0x8 : 'Finished', 0x9 : 'Dis...
subs = int(raw_input("Enter No. of Subjects: ")); marksList = [] for i in range(0,int(subs)): sub = raw_input("Enter Subject Name: "); marks = int(raw_input("Enter Marks: ")); marksList.append({sub:marks}) print marksList print "-----------------------" for j in range(0,len(marksList)): for key,valu...
class Node(): def __init__(self, vertex): self.vertex = vertex; self.value = None; self.edge = []; class Graph(): def __init__(self): self.vertexes = []; def add_vertex(x): vertice = Node(x); self.vertexes.append(vertice) def remove_vertex(x): for vertice in self.vertexes: if vertice.vertex...
# Imports here %matplotlib inline from PIL import Image import matplotlib.pyplot as plt import numpy as np import torch from torchvision import transforms, models # Load the Data from torchvision import datasets import torchvision.transforms as transforms from torch.utils.data.sampler import SubsetRandomSampler # B...
# Generated by Django 2.2.13 on 2020-10-23 17:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shared_models', '0009_auto_20201023_0836'), ] operations = [ migrations.AlterModelOptions( name='branch', options={'orderin...
# Generated by Django 3.1.1 on 2021-04-06 18:03 import datetime from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Administrator', ...
import os import numpy as np import torch.utils.data from torchvision.datasets import ImageFolder from torchvision import transforms import functools import PIL class StoryDataset(torch.utils.data.Dataset): def __init__(self, image_path, transform, is_train = True): self.dir_path = image_path ...
from flask import Flask, render_template import util app = Flask(__name__) username='raywu1990' password='test' host='127.0.0.1' port='5432' database='dvdrental' @app.route('/') def index(): cursor, connection = util.connect_to_db(username,password,host,port,database) record = util.run_and_fetch_sql(cursor,...
import pandas as pd import numpy as np from decisiontree import DTree import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier pd.set_option('display.max_columns', 1000) pd.set_option('display.max_rows', 1000) pd.set_option('display.width', 1000) np.set_printoptions(linewidth=1000) np.set_print...
def get_summ(first, second, delimiter="&"): first = str(first).upper() second = str(second).upper() return f"{first}{delimiter}{second}" to_print = get_summ("Learn", "python", delimiter='&') print(to_print)
try: file = open("while.py") file.close() except OSError: print("打开文件失败") try: file = open("/etc/passwd") print('文件已经打开') s = file.reading() print(s, end='') file.close() except IOError: print('打开文件失败!')
from fbchat import log, Client import sys import subprocess import os, signal from subprocess import check_output # An FBChat "Echobot", set up to pass string values in/out of a local shell using Python's subprocess module class EchoBot(Client): def onMessage(self, author_id, message, thread_id, thread_type, **kwa...
from turtle import * mode('logo') clearscreen() speed(0) size = 4 # size of dots scaler = 100 # how much to zoom in screen = 200 # screen of sight in fractal depth = 10 # recursion for f(z) res = 5 # how many pixels to jump for next recursion # current = [-200, 200] pu() for a in range(-screen,screen,res)...
from parking_project.requests.models import Request from django.contrib import admin admin.site.register(Request)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20170321_1255'), ] operations = [ migrations.CreateModel( name='Data', fields=[ ...
from .books.list import book_list from .books.details import book_details from .librarians.list import list_librarians from .libraries.list import list_libraries from .home import home from .auth.logout import logout_user from .books.form import book_form, book_edit_form from .libraries.form import library_form from .l...
# -*- coding: utf-8 -*- """ Created on Sat Mar 24 19:15:13 2018 @author: atul """ def permute(s): print("s is : ",s) out =[] #Base Case if len(s) ==1: out =[s] else: #for every letter in string for i,let in enumerate(s): #for every permutat...
import unittest from bin.song import Song class TestSongAlbum(unittest.TestCase): def setUp(self) -> None: self.song = Song() def tearDown(self) -> None: del self.song def test_set_album_type(self): self.assertRaises(TypeError, self.song.set_album, album=3) self.assertRai...
#!/usr/bin/env python # Copyright (c) 2022 Project CHIP 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
import math import numpy as np import ray from ray import tune from ray.tune.suggest.bayesopt import BayesOptSearch from ray.tune.suggest import ConcurrencyLimiter import unittest def loss(config, reporter): x = config.get("x") reporter(loss=x**2) # A simple function to optimize class ConvergenceTest(unit...
# -*- coding: utf-8 -*- # See LICENSE file for full copyright and licensing details from datetime import datetime from dateutil.relativedelta import relativedelta import time from odoo import api, fields, models class commission_invoice(models.AbstractModel): _name = 'report.property_commission.commission_repo...
#https://leetcode.com/problems/divide-two-integers/discuss/837822/Python-clean-solution def divideWithExtraSteps(dividend, divisor): sign = +1 if (dividend ^ divisor) >= 0 else -1 dividend, divisor = abs(dividend), abs(divisor) ans = 0 for power in range(31, -1, -1): if (divisor << power) <= ...
import datetime list_expenses = [] list_incomes = [] list_savings = [] class Expenses: def __init__(self, cat, subcat, amount, date): self.cat = cat self.subcat = subcat self.amount = amount self.date = date def add_amount(self, new_amount): self.amount += new_amount def add_element(selection): ''' A...
#coding=utf-8 __author__ = 'JinyouHU' #define and invoke function def sum(a,b): return a+b func = sum # r = func(5,6) print r #defines functionwith default argument def add(a,b=2): #如果不给b赋值,会有一个默认的值 return a+b r = add(1) print r r = add(1,5) print r # the range() function a = range(5, 10) pr...
n=int(input()) i=1 numList=[] while True: if '666' in str(i): numList.append(i) if len(numList)==n: break i += 1 print(numList[n-1])
#!/usr/bin/python # -*- coding:utf-8 -*- import requests from distutils.version import LooseVersion from pydashie.dashie_sampler import DashieSampler class BackstageStoreVersions(DashieSampler): def name(self): return 'backstage-store-versions' def sample(self): data = [ ('QA-AP...
grades=[12,4.4,56,45.33] student_grades={"praveen":12, "chandrika":4.4, "myra":56, "pinkey":45.33} mysum=sum(student_grades.values()) mycount=len(student_grades.values()) mean=mysum/mycount print(mean)
import numpy as np import matplotlib import matplotlib.pyplot as plt import mnist import os # raise EOFError("Compressed file ended before the " # import tempfile # print(tempfile.gettempdir()) # Then go to that directory and delete train-images-idx3-ubyte.gz. # rm /tmp/train-images-* proxy = 'http://127.0.0.1:812...
import logging from aatest.summation import represent_result from oic.utils.http_util import Response, NotFound from aatest.check import ERROR from aatest.check import OK from aatest.check import WARNING from aatest.check import INCOMPLETE from aatest.io import IO from saml2test.idp_test.webio import get_test_info _...
## Jason Balkenbush 28 December 2017 ## For xls files: code to group rows based on duplicate values in the first column ## groups are converted to new sheets in the output xls file ## rows containing "Domain" in the first cell are excluded from the output ## xlwt does not work with xlsx files, only xls ## import xlrd ...
Suppose we're working with 8 bit quantities (for simplicity's sake) and suppose we want to find how -28 would be expressed in two's complement notation. First we write out 28 in binary form. 00011100 Then we invert the digits. 0 becomes 1, 1 becomes 0. 11100011 Then we add 1. 11100100 That is how one would write -28...
import numpy as np class Expression: def MainMethod(self): m1 = np.random.randint(0, 20, (3, 3)) m2 = np.random.randint(0, 20, (3, 3)) self.PrintMatrix(m1) self.PrintMatrix(m2) result = self.ExpressionMatrix(m1, m2) self.PrintMatrix(result) det_result = self....
# -*- 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 # ...
#generatore di livelli: da una bitmap si ottiene un file di testo come una matrice di numeri #legend.txt: corrispondenza tra valori a 24 bit ed elementi di gioco #formato del file di output: # - numero righe # - numero colonne # - matrice from PIL import Image import sys #creo la legenda a mano, dovrei leggerla...
from itertools import accumulate from sys import stdin input = stdin.readline n, m = map(int, input().split()) arr = list(map(int, input().split())) acc = [0] + list(accumulate(arr)) for _ in range(m): l, r = map(int, input().split()) print(acc[r]-acc[l-1])
import json import os import time from seeder import Seeder class CourseCreationException(Exception): """Raised when the creation of a course fails""" pass class CourseSeeder(Seeder): """ Class for course creation actions Will create a course in the provided studio link and the import a tarfil...
# -*- coding: utf-8 -*- # Copyright European Organization for Nuclear Research (CERN) since 2012 # # 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-...
#!/usr/bin/env python import flask import flaskext.script import database default_config = { 'DATABASE_URI': 'postgresql://localhost/reportdb', 'TESTING_DATABASE_URI': 'postgresql://localhost/reportdb_test', 'HTTP_PROXIED': False, 'FRAME_URL': None, } def create_app(): import views app = fl...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'gridGame' function below. # # The function is expected to return a 2D_INTEGER_ARRAY. # The function accepts following parameters: # 1. 2D_INTEGER_ARRAY grid # 2. INTEGER k # 3. STRING_ARRAY rules # def gridGame(grid, k, rul...
#Time comp --> o(n log n) #space comp --> o(n) class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals=sorted(intervals,key=lambda x:x[0]) out=[] for i in range(len(intervals)): if i==0: out.append(intervals[i]) else: ...
from time import sleep import requests from bs4 import BeautifulSoup URL = 'http://cs.ouc.edu.cn/news-list.aspx?nc=14' if __name__ == '__main__': while True: html = requests.get(URL).text soup = BeautifulSoup(html, 'html.parser') ul = soup.find('ul', {'class': 'border-dotted'}) li...
from base64 import b64decode, b64encode import gevent import gevent.event import json from PIL import Image, ImageDraw import StringIO import zlib import logging from ajenti.api import * from ajenti.api.http import HttpPlugin, url, SocketPlugin from ajenti.plugins.configurator.api import ClassConfigEditor from ajenti....
from django.db import models from django.conf import settings class Note(models.Model): title = models.CharField(max_length=100) #image = models.ImageField(blank= True, null= True) url = models.URLField(blank= True, null= True) timestand = models.DateTimeField(auto_now_add=True) user = models.Forei...
#!/usr/bin/env python3 import time import torch import torch.nn.functional as F from dataloader2 import get_loaders from model2 import DynamicAttention # set seed for reproducibility seed = 0 torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) def main(): """MAIN FUNCTION.""...
"""Controller do Grupo.""" class Grupo(object): """Classe responsavel por gerenciar a View e Model relacionados a Grupo. Attributes: view (View:obj): Objeto root View model (Model:obj): Objeto root Model """ def __init__(self, controller: object) -> None: """Construtor padrao...
import pickle import socket import struct import threading import cv2 class ConfigDetectSocket(threading.Thread): def __init__(self, queue, configure): super().__init__() self.connected = set() self.queue = queue self.configure = configure self.server_ip = configure.confi...