index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
13,400
66b05fcc12f1a35173c8529051a0fbffed291a4e
from operator import itemgetter #Needed funcion to sort all scheduled trips input_file = open('c_no_hurry.in') #File to open first_line = input_file.readline() #Gets the first information from the file n_rows, n_columns, n_vehicles, n_rides, bonus, max_steps = tuple(map(int, first_line.split(' '))) def greate...
13,401
069ae919ec3ace8b76fc919b8afd465e5762307b
from django.db import models from datetime import datetime, date class Article(models.Model): title = models.CharField(max_length=500) date = models.DateField(auto_now_add=False, auto_now=False) description = models.CharField(max_length=2000) def __str__(self): return self.title
13,402
ec0336135f8464f0e17b6eec00293cebf55a9fb9
from django.urls import path from .views import ProductListView, ProductDetailView urlpatterns = [ path('', ProductListView.as_view(), name='products-list'), path('details/<str:slug>', ProductDetailView.as_view(), name='products-details'), ]
13,403
d30600e5e49ef563d721b34e9164a512d7061c03
class Dependence: def __init__(self, x, p): self.x = x # integer self.p = set(p) # set def __repr__(self): s = str(x) + " <-"; for item in p: s += " " + str(item) return s def __eq__(self, obj): if (obj is None): return False ...
13,404
7f3d11976e29f89ab765e720e01a4396fbe3dd15
import datetime import os import pickle import h2o.automl import pandas as pd import xgboost as xg from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler, P...
13,405
0fa8c506baf3973f362efe7a888323475d10e270
from django.urls import re_path from . import views urlpatterns = [ re_path(r'^reg$',views.reg_view), re_path(r'^login',views.login_view), re_path(r'^logout',views.logout_view), re_path(r'^register$',views.register_view), ]
13,406
f94b461d8932761cf0f50be8a13b47f9c9286055
{ 'name': 'Fleet asset', 'version': '8.0.1.0.0', 'license': 'AGPL-3', 'category': 'Generic Modules/Fleet Asset', 'author': 'Andrean Wijaya', 'website': '-', 'depends': ['account','fleet','account_asset'], 'data': [ 'views/fleet_asset_view.xml', ], 'installable'...
13,407
2ab49eee147eb66a4d68953d6ae1dbbb15b67cc3
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.item import Item, Field class MusicItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() song = F...
13,408
44bee7009a10419851132b42fcad2401b5f22a8b
num=input() rev=num[::-1] if num==rev: print('yes') else: print('no')
13,409
dcd321144436a1da130f16c05ac41b2c49c16cb5
items=list(range(11,21)) for index, item in enumerate(items): print(index, item)
13,410
bac42a3e34f14106548df2dce672ca976eadd41e
from __future__ import annotations import requests import time from typing import List, TypedDict, Generator from dataclasses import dataclass @dataclass class RedditComment: """ A basic reddit comment. This class excludes much of the data that comes with a reddit comment in favor of simplicity. ...
13,411
3a5f832d44c6a55004dc94ec1b25a485ceb5d8eb
# -*- coding: utf-8 -*- # Resource object code # # Created: ๅ‘จๆ—ฅ 11ๆœˆ 29 16:49:48 2015 # by: The Resource Compiler for PyQt (Qt v4.8.6) # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore qt_resource_data = "\ \x00\x00\x14\x1c\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x4...
13,412
a398975505e8363b3fcf339a2a23af33ec555463
import numpy as np from SenselUse import sensel import threading import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import os enter_pressed = False plt.figure(figsize=(15, 7)) COUNT = 1 # my_cmap = plt.cm.RdBu(np.arange(plt.cm.RdBu.N)) # my_cmap[:,0:3] *= 0.5 # my_cmap = ListedColormap(my...
13,413
e7591b2c55992ba48026d012d75a9febac41ac39
#DEPENDENCIES #Allow Path Access to the Prelude's Directory import sys if not(".." in sys.path): sys.path.append("..") #Utilities Dependencies from Py_Preludes import * #Typing Dependencies from typing import List #Enum Dependencies from enum import Enum,auto,unique #Context Extension Dependencies from SimpleT...
13,414
be72e722f1cdb71fe1987559eab0826dfac5c8c5
a=int(input("Enter limit:")) b=1 c=1 print(b) print(c) for i in range(1,a-1): d=c+b print(d) b=c c=d
13,415
ede30aa8afbc9bdbbaa47b3c9729615df1d5e802
from sys import stdin def busquedaBinaria(n, item): primero = 0 ultimo = len(n)-1 while primero<=ultimo: mid = (primero + ultimo)//2 if n[mid] == item: return "esta",mid else: if item < n[mid]: ultimo = mid-1 else: ...
13,416
79fab049a6737b93da1d48b9880e8ff6944f0c5f
import matplotlib.pyplot as plt from matplotlib import cm import numpy as np def speed_up(a): speed_up = a[0]/a return speed_up P = np.array([1,4,16,24,36]) P_square = np.array([1,4,16,25,36]) run_time_square = np.array([1143.29, 298.748,93.9222, 84.9656, 46.224]) run_time_vert = np.array([1140.44,300.6...
13,417
b331efb2a21f4ea7b57e24c40a7faf8aaea786f6
# # a1pr1.py - Assignment 1, Problem 1 # # Indexing and slicing puzzles # # This is an individual-only problem that you must complete on your own. # # # List puzzles # pi = [3, 1, 4, 1, 5, 9] e = [2, 7, 1] # Example puzzle (puzzle 0): # Creating the list [2, 5, 9] from pi and e answer0 = [e[0]] + pi[-2:] print(an...
13,418
e705c35aaa083db2245f815310a9874ddd42f7b8
from typing import Tuple, Any from dataset import Dataset from relevance_engines.criage_engine import CriageEngine from link_prediction.models.model import Model from explanation_builders.explanation_builder import NecessaryExplanationBuilder class CriageNecessaryExplanationBuilder(NecessaryExplanationBuilder): "...
13,419
3b99a4d2366b5717708af53c885b60b489799f84
# Generated by Django 2.2.1 on 2019-05-16 00:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myApp', '0002_auto_20190516_0021'), ] operations = [ migrations.AlterField( model_name='customuser', name='profile_i...
13,420
9c3dce4d6e8fd58197b83dc188ad2b1a474bfb7a
import sqlite3 conn = sqlite3.connect("SnackBar.db") def initiate_leiding_table(conn): cursor = conn.cursor() cursor.execute("""CREATE TABLE leiding ( first text, last text, schuld float )""") def initiate_snackbar_table(conn): cursor = conn.cursor() ...
13,421
744e67a418647dd88fcec020f9d38546ba4723dc
# -*- coding: utf-8 -*- ''' ้กต้ข่งฃๆžๅ™จ ''' __author__ = 'Evan Hung' import urlparse import re from bs4 import BeautifulSoup class HtmlParser(object): def parse(self, page_url, html_cont): if page_url is None or html_cont is None: return soup = BeautifulSoup(html_cont, 'html.parser', f...
13,422
2a2bd3714d4b2805a43416861951e615c5e1eb07
import pyttsx3 engine = pyttsx3.init() ssound = engine.getProperty('voices') for sound in ssound: print('voice') print('id %s' %sound.id) print('gender %s' %sound.gender) print('**************************')
13,423
83f8c193a287a07e096a190df7736b4c103aeaa4
#!/usr/bin/env python ## Create a schema for the table and then create the table. from google.cloud import bigquery client = bigquery.Client() table_id = "innate-entry-286804.rns_sample_dataset.rns_db_4" schema=[ bigquery.SchemaField('itemid','STRING',mode='REQUIRED'), bigquery.SchemaField('quantity','STRI...
13,424
0aa1e216b5f136bd30251a4d3b1b1b24f6c8466f
# Used by the network to perform actions and getting new states from Grab_screen import grab_screen class Game_state: def __init__(self, agent, game): self._agent = agent self._game = game # get_state(): Accepts an array of actions and performs the action on the Dino # Returns...
13,425
43d0988b7f6e79345bae3f48040486a00b7a49d5
from rest_framework import serializers from .models import * class ForecastSerializer(serializers.ModelSerializer): class Meta(): model = Forecast fields = ('place_name','cyclone_id','cyclone_name','image_link','time_of_last_forecast','created_at')
13,426
de81d6098282e7e405bcacc9f5d518ceb8f3a881
import sys infile = sys.argv[1] with open(infile) as inputf: lines = inputf.readlines() dna = lines[0].strip() k = int(lines[1].strip()) matrix = [] for line in lines[2:]: values = line.strip().split() linevals = [] for val in values: linevals.append(float(val)) matrix.append(linevals) trans = {'A': ...
13,427
595297e304abd3ecd44084e0584a2387176bc2cb
import sys from PySide6 import QtWidgets from productiveware.widgets.main_window import MainWidget if __name__ == '__main__': app = QtWidgets.QApplication() main_window = MainWidget() sys.exit(app.exec())
13,428
1e11380d8b13bd2a60fcd53e1116dba06d51bc38
#!/usr/bin/python3 # coding = utf-8 """ @author:m1n9yu3 @file:main.py @time:2021/01/12 """ import threading from tmp.get_data import * from tmp.keyword_get import ask_url, search_key ''' target : ็›ฎๆ ‡ http://floor.huluxia.com/post/detail/ANDROID/2.3?platform=2&market_id=tool_baidu&post_id={ๅธ–ๅญid}&page_no={้กตๆ•ฐ} ๅธ–ๅญid ไพๆฌก้€’ๅขž...
13,429
6efb43fc22c94ece22322f6a841a9e07df8fe06a
from help import * import math import re import sys def settings(str): return dict(re.findall("\n[\s]+[-][\S]+[\s]+[-][-]([\S]+)[^\n]+= ([\S]+)",str)) def coerce(s1): """ Converts value to Boolean, if value is not a boolean string it converts it to integer. Parameters --------...
13,430
e638123ed947787fc611d5580f5908e93fea8afc
''' ะคะพั€ะผะฐั‚ะธั€ะพะฒะฐะฝะธะต ัั‚ั€ะพะบ ''' name = 'John' age = 34 # print('My name is ' + name + '. I\'m ' + str(age )) # print('My name is % (name)s. I\'m %(age)d' %{'name': name, 'age': age}) #ะฝะต ั€ะฐะฑะพั‚ะฐะตั‚!!! #print('My name is %s. I\'m %d' % ('David', age)) print('Title: %s, Price: %f' %('Sony', 40)) #Title: Sony, Price: 40....
13,431
e924c622706ed88627ff31dba68fb4a620a65a6b
import predictor import pandas as pd active_drivers = [['Daniel Ricciardo','McLaren'], ['Mick Schumacher','Haas F1 Team'], ['Carlos Sainz','Ferrari'], ['Valtteri Bottas','Mercedes'], ['Lance Stroll','Aston Martin'], [...
13,432
dda07b23dc1fa4266a687b5cbab4d6e19f710ffc
# Copyright (c) 2020, Vladimir Efimov # All rights reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import sys import modules.text_processor_normalize as tpn from modules.term_scoring import get_term_score def count_term_entries(s...
13,433
96adad4aa658cd8f0a06f33ef3294b1d9f15eb35
import streamlit as st import pandas as pd import os from PIL import Image from datetime import datetime import streamlit.components.v1 as stc import base64 import time timestr = time.strftime("%Y%m%d-%H%M%S") import sqlite3 conn = sqlite3.connect('data.db') c = conn.cursor() metadata_wiki = """ """ HTML_BANNER ...
13,434
269db89ad962d2707c4dd8bc6d8fec63a37851e1
from .base import BaseResourceTest from test.factories import DatasetGenerationJobFactory from src.master.resources.dataset_generation_job import DatasetGenerationJobResource, DatasetGenerationJobListResource import os from src.master.resources.datasets import load_dataset_as_csv from src.models import Dataset, Dataset...
13,435
9066aa06aef0e1f77c7f902aa3d4822923b06092
#doing linear searches names = ["Bill", "Charlie", "Fred", "Alien"] if "Aunty" in names: print("Found") else: print("Not Found")
13,436
cfb3de6ff3c83ed3cef2527064a1a1d9151c1ef8
import pandas.tools.plotting as pdplt import matplotlib.pylab as plt import seaborn as sns import subprocess import pandas as pd import numpy as np import serial from sklearn.tree import DecisionTreeClassifier, export_graphviz from Tkinter import * import Tkinter as Tk class EnterInterface: def __init__(self, ma...
13,437
ed6645a367407c554fd8aad9dc14b038d3cb4626
#!/usr/bin/env python # coding: utf-8 import os import re import time import json defaults = "--single-transaction --skip-lock-tables --compact --skip-opt --quick --no-create-info" \ "--master-data --skip-extended-insert" # ignore_tables = ["soccerda.ndb_apply_status"] def dump_mysql(conn, schemas, misc = defau...
13,438
5dd88a0800664d6e8d42caef784f2751ed44b2f1
from models.detector import face_detector import numpy as np from models.parser import face_parser import cv2, os part_colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 0, 85], [255, 0, 170], [0, 255, 0], [85, 255, 0], [170, 255, 0], [0, 255, 85], [0, 255, 170], ...
13,439
0a45ac8d436f16359163b89b9ad21a855c5d4b3f
class LogUtil: def __init__(self): """ Initiate Log Util. This Class contains utilities for helping with Logging """ self.META_AE_IP = 'HTTP_X_APPENGINE_USER_IP' self.FORWARDED_FOR = 'HTTP_X_FORWARDED_FOR' print('{} - Initialized'.format(__name__)) def...
13,440
7edd2d284ec6ee1c2f70fb5aac9fadee7fcec5b1
import cv2 import numpy as np kernel = np.ones((5,5),np.uint8) print(kernel) path = './archivos/futbol.jpg' img = cv2.imread(path) img = cv2.resize(img,(0,0),fx=0.3,fy=0.3) imGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) imgBlur = cv2.GaussianBlur(imGray,(7,7),0) imgCanny = cv2.Canny(imgBlur,100,200) imgDilation = cv2....
13,441
8e18c7fed9d67ef518950b5490ef7703c537b947
#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np np.set_printoptions(linewidth=500) np.set_printoptions(precision=8) import random # In[ ]: #ๅคงใใ•ใ‚’่ฟ”ใ™ def norm(r): return(np.sqrt(np.real(np.dot(r.conjugate(),r)))) # In[ ]: #ใ‚นใƒ”ใƒณ๏ผ‘ใ€ใ‚นใƒ”ใƒณ๏ผ’ใฎใ‚นใƒ”ใƒŽใƒซใ‚’ไฝœใ‚‹๏ผˆ่ฆๆ ผๅŒ–่พผใฟ๏ผ‰ def spin1(s1,s0,sm1): a=np.array([s1,...
13,442
064432b66e4882c5b9ab0e544ce2971aba4bd16d
#1.ํ•จ์ˆ˜ print('#################### 1.ํ•จ์ˆ˜ ###################') def add(num1,num2): return num1 + num2 print(add(1,2)) def add_mul(num1,num2): #๋‹ค์ค‘ ๋ฆฌํ„ด๊ฐ’์„ ํŠœํ”Œํ˜•ํƒœ๋กœ ๋ฐ˜ํ™˜ return num1 + num2 , num1*num2 print(add_mul(1,2)) my_add , my_mul = add_mul(1,2) #ํŠœํ”Œ ์–ธํŒจํ‚น print(my_add) print(my_mul) #2.๋ชจ๋‘˜ print('#############...
13,443
9a5d8aff68f1cc9b436294114d5b632eb83cbbd6
# Bill Karr's Code for Assignment 3, Problem 1 from __future__ import division import numpy as np def qr_iteration(A, tol): n = len(A) for i in range(n-1,0,-1): while np.linalg.norm(A[i-1,:i-1]) >= tol: sigma = A[i][i] Q,R = np.linalg.qr(A - sigma*np.eye(n,n)) A = n...
13,444
1fa35d0d288b5464dbb6da4f654b93f39c847535
''' ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” 0๊ณผ 1๋กœ ์‹œ์ž‘ํ•œ๋‹ค. 0๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” 0์ด๊ณ , 1๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋Š” 1์ด๋‹ค. ๊ทธ ๋‹ค์Œ 2๋ฒˆ์งธ ๋ถ€ํ„ฐ๋Š” ๋ฐ”๋กœ ์•ž ๋‘ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์˜ ํ•ฉ์ด ๋œ๋‹ค. ์ด๋ฅผ ์‹์œผ๋กœ ์จ๋ณด๋ฉด Fn = Fn-1 + Fn-2 (n>=2)๊ฐ€ ๋œ๋‹ค. n=17์ผ๋•Œ ๊นŒ์ง€ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋ฅผ ์จ๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597 n์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, n๋ฒˆ์งธ ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค. ์ฒซ์งธ ์ค„์— n์ด ์ฃผ์–ด์ง„๋‹ค. n์€ 20๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ž์—ฐ์ˆ˜ ๋˜๋Š” 0์ด๋‹ค. ''' ...
13,445
a84e61d28571af1d0f51591745022556bc234ea8
import numpy as np from smart.ops import SealOps from smart.seal_matrix import CipherMatrix class SealKernel: def __init__(self, vectors, gamma, coef0, degree, kernel_name, seal_ops: SealOps): self.coef0 = coef0 self.gamma = gamma self.degree = degree self.vectors = vectors ...
13,446
925d220066b3902f44a9645b1ac59f152025dcd3
import requests import time import datetime from Send_Notifications import Get_Technical_Owner ,First_mail from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from DBConnection_Sagar import Base,cert_data_sagar import logging logger_Insert_db_error = logging.getLogger('Certrenewal_Insert_db_er...
13,447
70e458602947075475efae3d984038ac70dcce33
import serial.tools.list_ports import urllib from md5 import md5 from time import time import socket IPADDR = '209.20.80.141' PORTNUM = 11311 def usage(): print 'Usage: cicada.py <serial device> "me@example.com" "My Name" "160 Varick, New York, NY 10031"' print print "Run cicada.py to upload your senso...
13,448
8a59fe51813b23d00a0f55a603a18a2a3bd93554
import random def numero_aleatorio(): lista=[] while len(lista)!=5: num=random.randrange(0,9) if num not in lista: lista.append(str(random.randrange(1,9))) numero="".join(lista) return numero def comprueba(secreto,numero): #Creamos diccionario para guardar los valores ...
13,449
56312a8ac462a5e62acd84aa4459b659ee9bba3f
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Author: David Beam, db4ai Date: 18 January 2018 Description: """ # Include files import gym import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from random import uniform # Include custom files import functions as func impo...
13,450
4e1e078cdd8a892e5523c32bafb48f48f1ad347b
def str_rev(str): rstr = '' index = len(str) while index > 0: rstr += str[ index - 1 ] index = index - 1 return rstr print(str_rev('string'))
13,451
b4745c4fce15537556d9906216ddb979934937a7
#!/usr/bin/python import matplotlib.pyplot import matplotlib.mlab import collections def Import(filename): datas=matplotlib.mlab.csv2rec(filename,delimiter='\t') print "LogCan20:", filename, "OK n=", len(datas) return datas def PlotT(datas ): matplotlib.pyplot.figure() ax1 = matplotlib.pyplot.subplot(1,1,1) i...
13,452
8439fca8bd57db3b86645f8d6d154be74d8bb377
import json import logging log = logging.getLogger(__name__) sh = logging.StreamHandler() log.addHandler(sh) def test_rule_access(as_user): r = as_user.get('/rules') assert r.status_code == 403 r = as_user.post('/rules', json={'test': 'rule'}) assert r.status_code == 403
13,453
d401eeedfee373acc0953abbb318a551c6509d90
input = open('allvectors.in', 'r') output = open('allvectors.out', 'w') s=int(input.read()) b=[] for i in range(2**s): j=2 while(j<=2**s): if (i%j<=(j/2-1)): b.append(0) else: b.append(1) j*=2 for k in range(s): output.write(str(b[s-k-1])) output.w...
13,454
a6a7924aa8e329ca4caa47e69b0063fa76bf7b0f
#!/usr/bin/env python3 import sys from markup_processor import process from formatters.html import HtmlFormat def main(): process(HtmlFormat, sys.stdin, sys.stdout) if __name__ == '__main__': main()
13,455
b9dd9907dd3bd0dbfd91cc2e5a2a07daafa2634e
# 10.SQL IS NULL Query: # IS NULL Syntax: ''' SELECT column_names FROM table_name WHERE column_name IS NULL; ''' # The IS NULL Operator: # Always use IS NULL to look for NULL values. # IS NULL operator is used to test for empty values (NULL values). ''' SELECT CustomerName, ContactName, Address FROM...
13,456
764c08e08cda7355219352dd3e5ecd2aa6d66d84
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin from django.views.generic import RedirectView admin.autodiscover() urlpatterns = patterns('', url(r'', include('social_auth.urls')), url(r'^$', RedirectView.as_view(url='/acc...
13,457
18cf94acdd3ad8c9968909428b8598d019d9867e
#-------------------------------- # Functions for plotting #-------------------------------- import numpy as np import matplotlib.pyplot as plt from matplotlib import cm def plot_dist_3p( hst, xi, yi, ax=None, filled=False, fcolors=None, **kwargs, ): ...
13,458
ddbdb452c9053c042391cb2c246eaac1665441c8
import unittest from config.config import Config TEMPLATE_CONFIG_FILE = 'config/config.ini.template' class TestConfig(unittest.TestCase): def setUp(self): self.config = Config(TEMPLATE_CONFIG_FILE) def test_get_mongo_url(self): self.assertEquals(self.config.get_mongo_url(), 'mongodb://USER:PA...
13,459
87076944a9c5f77061eae8120cc7d8536c944421
# -*- coding: utf-8 -*- """ Created on Fri May 24 09:46:47 2019 @author: CDEC """ import cv2 import numpy as np kernel = np.ones((5,5),np.uint8) for i in range(1,21): path = 'D:\Documents\OPENCV\Placas\Placa ('+str(i)+").jpg" img = cv2.imread(path) numero = 0 caracteres = [] ...
13,460
ee95a54f73b3c68ff1d2dcd386b972f7b3d51dc5
from PIL import Image w = 640 h = 480 image = Image.open('/home/pi/0.jpg') pixels = image.load() for i in range(0,w): for j in range(0,h): white = True for each in pixels[i,j]: if not (each < 80 or each > 155): white = False if(white): pixels[i,j] ...
13,461
065bb34ed1cd9a4e2037f9492a6e3cca6892f787
# time: O(nlogn) # space: O(n) from collections import Counter class Solution: def findLHS(self, nums: List[int]) -> int: counter = Counter(nums) max_len = 0 keys = set(list(counter.keys())) for key in counter.keys(): if key+1 in keys: max_len = max(max_...
13,462
dcf26389c0f841e33f9a2ecc759db2a16e88a295
# Copyright 2019 Markus Liljergren # # 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 wri...
13,463
ffa669bb82cae0d7b8436040849409a61b4e024b
''' Task: Jump over numbers You are given a list of non-negative integers and you start at the left-most integer in this list. After that you need to perform the following step: Given that the number at the position where you are now is P you need to jump P positions to the right in the list. For example, if you are ...
13,464
04996dc529114fa67376ae400c0def154ffe6ede
from astropy import cosmology as cosmo import logging from autoconf import conf import autofit as af import autoarray as aa import autogalaxy as ag from autolens.lens.model.analysis import AnalysisDataset from autolens.lens.model.preloads import Preloads from autolens.interferometer.model.result import Resu...
13,465
e6ba87b2b552723a46c7a8a3e005a520fae25bf6
import json def hash_str(x): return abs(hash(json.dumps(x, sort_keys=True))).to_bytes(8, "big").hex()
13,466
bc32faadb10d168466977da0825e7ef4e1b6002e
height = [int(input()) for _ in range(9)] check = [False] * 9 result = [] def recursive(index): global result if index == 9: answer = 0 count = 0 demo = [] for i in range(9): if check[i]: answer += height[i] count += 1 d...
13,467
4231d0b652ab9071d0443d91d93b89bcbfba615b
import torch import torch_geometric from torch_geometric.profile import benchmark from torch_geometric.testing import ( disableExtensions, onlyFullTest, onlyLinux, withCUDA, withPackage, ) from torch_geometric.utils import scatter # Basic "Gather-Apply-Scatter" patterns commonly used in PyG: def ...
13,468
7441555938981f54f76db26f8bf7201306bf6080
import pytest from scripts.use_pd_array_in_core import use_pd_array BAD_FILE_0 = "import pandas as pd\npd.array" BAD_FILE_1 = "\nfrom pandas import array" GOOD_FILE_0 = "from pandas import array as pd_array" GOOD_FILE_1 = "from pandas.core.construction import array as pd_array" PATH = "t.py" @pytest.mark.parametriz...
13,469
ed241a66598331db5e9a5e74dc819614bd9aa89c
print ("Learn the steps of hte 5 sequence tango.") print ("What step do you wish to learn?") whichStep = int(input()) if whichStep == 1: print ("Leader takes a step back.") elif whichStep == 2: print ("Side step towards centre of floor.") elif whichStep == 3: print ("Leader steps outside of follower.") e...
13,470
19747cea3b21d22a495f9ada22bfef7bc7efafe8
def login_disponivel(login,lista): login = input('Qual รฉ o seu login? ') i=1 if login in lista: login1 = login + str(i) lista.append(login1) else: lista.append(login)
13,471
db4b1431be679f2484c1f6bc2e1b74ac7a3ee45b
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright https://github.com/VPerrollaz # # Distributed under terms of the %LICENSE% license. """ Gรฉnรฉration du graphe permettant de coder un algorithme glouton. """ import random as rd from enum import Enum, auto class Genre(Enum): """Enum pou...
13,472
06c424dc5adf8d87e932159faa2ccba85d68dc80
# Copyright 2018 The TensorFlow Authors 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 applicab...
13,473
b4fc575a56530582016e5b7044169e033c5a976d
#!/usr/bin/env python from __future__ import print_function import pdb import tracer_func as tracer import ConfigParser import argparse import sys import os import subprocess import pipes import glob import shutil import re from collections import defaultdict, Counter from time import sleep import warnings import pick...
13,474
0358674298b2f64a864a58fcee4bf25de745d5b1
# 4/2009 BAS # read() replicates behavior of pyserial # readexactly() added, which is probably more useful # readbuf() dumps current buffer contents # readpacket() has old broken behavior of read() - lowest level / fastest import socket import time MOXA_DEFAULT_TIMEOUT = 1.0 # Socket modes: # Nonblocking # s.se...
13,475
bf0300b9271eadd489dd1579ad47fa8cca8cdfb2
from . import views from django.urls.conf import include, path import debug_toolbar urlpatterns = [ path('register', views.register, name='register'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), path('__debug__/', include(debug_toolbar.urls), name='logout'), ...
13,476
4c0d61fe0c2233b9b09ddf313e0396aa9fc87e23
# Generated by Django 2.1.5 on 2019-02-09 14:23 from django.db import migrations, models import django_mysql.models class Migration(migrations.Migration): dependencies = [ ('whoweare', '0003_whowearefields_fourthsectionmissionvisionvaluesdescriptionsinlist'), ] operations = [ migrations...
13,477
2eb0eb97b9ca727e6d002ac2929a0d9771631ff9
from models import * from constants import * from utils import MyDataset import matplotlib.pyplot as plt import random import torch import itertools vae_type = 'conv' dataset = 'Total' subset = True model_name = 'Total_VAE__2021-02-04 11:05:04.531770.pt' model_path = MODELS_ROOT + model_name if subset: if dataset...
13,478
a95dc47f786c33ffc3b523d45bd418c9e4656a0a
import math def calcula_trabalho (F,teta,s): trabalho = F * math.cos(teta) * s return trabalho
13,479
5517b041a7ee292d1c00b6c3bd7acf4ad6bf42e0
# Create your views here. from django.shortcuts import render, redirect, get_object_or_404 from sculptqr.models import QRCode from django import forms from django.http import HttpResponse from django.conf import settings # For image upload import os import shutil import Image as PILImage import ImageFilter import Stri...
13,480
2347d1d881781ddbf231e164a511edef0c66ef65
from urllib.request import urlretrieve import os from os.path import exists, join import tarfile if not exists("data"): os.mkdir("data") csv_tar_file = "https://storage.googleapis.com/track_data_ncar_ams_3km_csv_small/track_data_ncar_ams_3km_csv_small.tar.gz" nc_tar_file = "https://storage.googleapis.com/track_da...
13,481
f8124ff68bbed7e3633b3f9473bf0eaa9816c03b
''' 240. Write a program to Read a Text File and Print all the Numbers Present in the Text File '''
13,482
c89081083dfcb1eb21fc5252abe25fb922209ef4
from django.apps import AppConfig class BizzConfig(AppConfig): name = 'bizz'
13,483
4223de2c4bc64fb1b06900f7b98f112c136b2686
from django.contrib import admin from .models import Album, Song #username : admin #password : admin1234 admin.site.register(Album) admin.site.register(Song)
13,484
9b2e32e481f57e7e901bd7881fba4e9c170048de
#!/usr/bin/env python prime=[2,3,5,7] n=10000 for i in xrange(11,n): l=len(prime) flag=0 for j in xrange(l): if i % prime[j] == 0: flag=1 if flag == 0: prime+=[i] print len(prime) print max(prime)
13,485
68e227171d80be555b737f95fc15ee21367ed784
from sqlalchemy import Column from sqlalchemy import Date from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import relationship from wewallet.application.models import Model class Billing(Model): __tablename__ = 'billings' id = Column(Integer, ...
13,486
05084057b80c237ef12f749eb4bd25e2264fd6bb
# ๅ“ˆๅฐ”็‰นๅพ https://zh.wikipedia.org/wiki/%E5%93%88%E5%B0%94%E7%89%B9%E5%BE%81 import numpy as np from skimage.feature import haar_like_feature_coord from skimage.feature import draw_haar_like_feature feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4') image = draw_haar_like_feature(np.zeros((2, 2)), ...
13,487
c9ec8624aa734f68254c1ca27da802247557698e
import time, sys, os from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from wifi24 import Wifi24 sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "{}/{}".format(os.path.pardir,os.path.pardir)))) from assertion import Assert from networ...
13,488
ac76d43729ff54487238008aaed7ff2f9a01c7de
import notes_pakets.corp_notes as modelo class Action: def new_note(self, usuario): print(f"Hola {usuario[1]}\nIniciamos") title = input("Introduce el titulo de nota: ") description = input("Ingrese la nota a guardar: ") nota = modelo.Note(usuario[0], title, description) ...
13,489
b5644dc2ff6701ea7774832d523db37e91c8efb0
import json from pathlib import Path import cv2 import pandas as pd from tqdm import tqdm def load_web_icon_dataset(dataset_path): dataset_path = Path(dataset_path) images = [] alt_texts = [] for json_path in tqdm(list(dataset_path.glob('*.json'))): try: with open(str(json_path),...
13,490
d5cdb46b01411bd58d69f1cb1437ecdf730a21ed
# coding: utf-8 import sys import web import url sys.path.append('./controllers') urls = url.urls if __name__ == "__main__": app = web.application(urls, globals()) app.run()
13,491
84093f2c0f5bed38cba70de6282953a3764b2a3c
# -*- coding: utf-8 -*- from setuptools import setup with open('README.rst') as f: long_description = f.read() setup( name='dj-email-url', version='0.1.0', url='https://github.com/migonzalvar/dj-email-url', license='BSD', author='Miguel Gonzalez', author_email='migonzalvar@gmail.com', ...
13,492
5cc2c95d912ba6692a2f9827f192a05b2e3c6b82
from datetime import datetime from flask import jsonify, make_response, request, render_template from flask_httpauth import HTTPTokenAuth from flask_login import login_required import json from app.mod_user.models import AuthorizationError, User, UserEntry from . import api_module as mod_api from . import controllers a...
13,493
9561c85e08a529b565b5e6da9e5d22e79b3c42b4
import pandas as pd import numpy as np import logging import os import tarfile from tempfile import TemporaryFile from kgx.utils import make_path from .transformer import Transformer from typing import Dict, List, Optional LIST_DELIMITER = '|' _column_types = { 'publications' : list, 'qualifiers' : list, ...
13,494
f92603209d8d298a8858bbd6cba8d72ac58253b9
import random p = 0.5 max_unanswered_calls = 4 max_nr_days = 100 successes = 0 for d in range(max_nr_days): if random.random() > p and random.random() > p and random.random() > p and random.random() > p and random.random() <= p: successes += 1 print(successes/max_nr_days) ...
13,495
2641713d05c390402c4ef075bc672335462e63ef
''' 1. ๋ฌธ์ œ ๋ถ„์„ - ํ• ์ธ๋ฐ›์€ ๊ธˆ์•ก์ด ์–ผ๋งˆ์ธ๊ฐ€? - ํ• ์ธ๋œ ๊ธˆ์•ก์ด ์–ผ๋งˆ์ธ๊ฐ€? 2. ํ• ์ธ๋ฐ›์€ ๊ธˆ์•ก : ๊น์•„์ค€ ๊ธˆ์•ก์„ ์˜๋ฏธ 3. ํ• ์ธ๋œ ๊ธˆ์•ก : ํ• ์ธ๋ฐ›์€ ๊ธˆ์•ก์„ ๋นผ๊ณ  ์‹ค์ œ ์ง€๋ถˆํ•  ๊ธˆ์•ก 4. ํ• ์ธ์œจ = (ํ• ์ธ์•ก / ์ƒํ’ˆ์•ก) * 100 = (2,000 / 10,000) * 100 = 0.2 * 100 = 20% 5. ํ• ์ธ ์ ์šฉ๋œ ๊ฐ€๊ฒฉ = ์ƒํ’ˆ์•ก * (100% - ํ• ์ธ์œจ) = 10,000 * (1.00 - 0.1) = 9,000์› 1) ๋งค๊ฐœ๋ณ€์ˆ˜์˜ ์ดํ•ด 2) ๋ฐ˜ํ™˜์˜ ์ดํ•ด ''' #๋‹ค์Œ๊ณผ ๊ฐ™์ด import๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. #import m...
13,496
804b6acbf9057afd432c20bb08e02cfbe0390509
''' 6. ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R P I N A L S I G Y A H R P I And then read line by line: "PAHNAPLSII...
13,497
75caa344cd346acbbd07b413133d6c4306576ad3
s=input() s = s[::-1] print(s)
13,498
a3dfcbcafaaa634f396f1d7320a67293b2d952b1
from django.test import TestCase from django.test.client import Client from model_mommy import mommy from .models import Vehicle # Create your tests here. class ReserveTestCase(TestCase): def setUp(self): self.vehicle = mommy.make( 'vehicle.Vehicle', reservation_code='1', _quantity=10 ...
13,499
b65c5d2453428a07ddefe880529a53e4340f8c4d
import sqlite3 import glob from sklearn.feature_extraction.text import CountVectorizer import numpy as np import scipy.spatial.distance as distance def insert_similarity_name(cur, sim_name): cur.execute("INSERT INTO similarity (name) VALUES (?)", (sim_name,) ) sim_id = cur.execute("SELECT * FRO...