text stringlengths 38 1.54M |
|---|
N = int(input())
A = list(map(int, input().split()))
c1 = {}
c2 = {}
for i in range(N):
c1.setdefault(i + A[i], 0)
c1[i + A[i]] += 1
c2.setdefault(i - A[i], 0)
c2[i - A[i]] += 1
result = 0
for k in set(c1).intersection(c2):
result += c1[k] * c2[k]
print(result)
|
import numpy as np
import scipy.io as io
params = ['Lgrad','vc','h','m','rou']
for k in range(5):
theta_param = io.loadmat(params[k] +'_data.mat')
theta = theta_param[params[k]]
print(theta)
matpath1 = params[k] + '_data_c.mat'
for j in range(4):
theta[j+1,1] = np.abs(theta[j+1,0]... |
"""
api.py
All API route endpoints
:copyright: (C) 2014 by github.com/alfg.
:license: MIT, see README for more details.
"""
from datetime import timedelta
from flask import request, jsonify, json, Response
from flask.ext.classy import FlaskView, route
from app import app, meta, auth, auth_enabled, adapter
from ap... |
# Copyright (C) 2010-2016 Dzhelil S. Rufat. All Rights Reserved.
"""
>>> from spexy.grid import Grid_1D
>>> from spexy.grid.grid import hodge_star_matrix
>>> g = Grid_1D.chebnew(3)
>>> H0, H1, H0d, H1d = hodge_star_matrix(g)
>>> H0
array([[ 0.808, 0.058],
[ 0.058, 0.808]])
>>> H1d
array([[ 1.244, -0.089],
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCommerceTransportCarbonDataQueryModel(object):
def __init__(self):
self._biz_date_end = None
self._biz_date_start = None
self._biz_scene = None
self._city_co... |
import logging
# Messages
STARTUP_MSG = u"pydKeg\nStarting"
STARTUP_LOGMSG = u"pydKeg Starting"
# Display Parameters
DISPLAY_DRIVER='winstar_weg'
DISPLAY_WIDTH = 100 # the width of the display
DISPLAY_HEIGHT = 16 # the height of the display
DISPLAY_SIZE = (DISPLAY_WIDTH, DISPLAY_HEIGHT)
#DISPLAY_WIDTH = 20 # the cha... |
import requests
import json
def login(account):
url='https://api.map.baidu.com/location/ip'
form_data={
"ip": account["ip"],
"ak": account["ak"],
"coor":account["coor"]
}
# form_data = {"ip": "101.247.112.18", "ak": 'dntnIGs3ueWbi8TGkGYz0l8j1p6c9Yc1', "coor": "bd09ll"}
... |
# Generated by Django 2.1.4 on 2018-12-28 19:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('meals', '0002_remove_meals_preperation_time'),
]
operations = [
migrations.AddField(
model_name='meals',
name='prepe... |
# -*- coding: utf-8 -*-
# Copyright (C) 2008 Murphy Lab
# Carnegie Mellon University
#
# Written by Luis Pedro Coelho <lpc@cmu.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either ver... |
import os
for i in range(0, 5000):
print(str(i).zfill(4))
os.system("diff saidas/t"+str(i).zfill(4)+" minhas_saidas/r"+str(i).zfill(4)+" > diff/diff"+str(i).zfill(4))
os.system("find ./diff -empty -delete")
|
#!/usr/bin/python2
import sys
from dictcc import Dict
from dictcc import Result
if len(sys.argv) != 4:
print("Argument count is wrong")
sys.exit()
from_lang = sys.argv[1]
to_lang = sys.argv[2]
search = sys.argv[3]
r = Dict.translate(word=search, from_language=from_lang, to_language=to_lang)
if r.n_results <... |
from Helpers.misc import swap, verify
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Algoritmo de resolucion de tablero domino haciendo uso de la fuerza bruta
#
# @param pBoard = Matriz sobre el cual se ejecutara el algoritmo para la busqueda de
# soluc... |
def func(int):
factor1=str(int)
ten ={
"1":"ten",
"2":"twenty",
"3":"thirty",
"4":"forty",
"5":"fifty",
"6":"sixty",
"7":"seventy",
"8":"eighty",
"9":"ninety",
"0":""
}
hundred = {
"1":"one",
"2":"two",
"3":"three",
"4":"four",
"5":"five",
... |
from django.utils import timezone
from consents.models import Consent, Person, Term
from consents.tests.base import ConsentTestBase
class TestTermModel(ConsentTestBase):
def setUp(self) -> None:
super().setUp()
self.person1 = Person.objects.create(
personal="Harry", family="Potter", e... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import spearmanr, pearsonr
data_after = pd.read_csv('../../data/for_plotting_project/post_processing_YES_filtering_of_3_protein_for_scatterplot_density_12_vs_15.txt', sep="\t", index_col = -2)
data_before = pd.read_csv('../../d... |
"""
CHIME constants and parameters.
"""
# Sampling frequency
ADC_SAMPLE_RATE = float(800e6)
# Number of samples in the inital FFT in the F-engine.
FPGA_NSAMP_FFT = 2048
FPGA_FRAME_RATE = ADC_SAMPLE_RATE / FPGA_NSAMP_FFT
# f-engine parameters for alias sampling.
FPGA_FREQ0 = ADC_SAMPLE_RATE
FPGA_NFREQ = FPGA_NSAMP_... |
from pyspark import SparkContext, SparkConf
import os
import subprocess
import tempfile
import urllib2
import sys
JOB_NAME = "Test Spark JOB"
SOURCE_PROGRAM_PATH = "http://192.168.205.44:8000/a.out"
TEMP_PATH = "/tmp/a.out"
LOAD_COUNT = 8
SC = None
def initialize_spark(job_name="SparkJob"):
"""
Configure s... |
# Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# 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 ... |
#!/usr/bin/env python3
from grole import Grole
import ssl
# Create an SSL context from keys created through e.g. Let's Encrypt or self signing:
# Generate a self signed cert with:
# openssl genrsa -out rootCA.key 4096
# openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.crt -subj "/CN=ro... |
from collections import Counter
M,N,K,L,D = map(int, input().split())
row = []
col = []
for _ in range(D):
x,y,p,q = map(int, input().split())
if x==p: col.append(min(y,q))
if y==q: row.append(min(x,p))
c0 = Counter(row).most_common()
c1 = Counter(col).most_common()
k = [x[0] for x in c0]
l = [x[0] for... |
import write_dependencies as wd
def parse_document(sentence_dictionary, event_id, acct_type):
"""
INPUT: dictionary that is output from the Stanford Core Parser using
jsonrpclib
OUTPUT: a list of lists where each sublist represents a dependency and
contains sentence id, both words in the dependency and their p... |
'''
Created on 2013-7-27
@author: Administrator
'''
import urllib,urllib2
from thread_pool import Worker
from thread_pool import WorkerManager
import sys
import framework.tool.FileHandler as FileHandler
def test_job(id, sleep = 0.001 ):
try:
html = urllib.urlopen('http://www.cnproxy.com/p... |
l = int(input())
c = int(input())
if( l % 2 == 0 and c % 2 == 1) or ( l % 2 == 1 and c % 2 == 0) :
print(0)
else:
print(1) |
from unittest.case import TestCase
from unittest import main
from case_converter.utils import convert_to_camel_case, convert_to_underscore
class TestConvertToCamelCase(TestCase):
def test_underscore_to_camel_dict(self):
input_data = {
"9_under_score_4_days": 1,
"a_game_of_thrones":... |
import yfinance as yf
import datetime as dt
import pandas as pd
def sixMonthIndex(tickers):
start = dt.datetime.today() - dt.timedelta(180)
end = dt.datetime.today()
cl_price = pd.DataFrame()
for ticker in tickers:
cl_price[ticker]= yf.download(ticker, start, end, period = "6mo")["Adj Clos... |
class Node:
def __init__(self, value):
self.data = value
self.left = None
self.right = None
def insert(self, current, new):
if current.data < new.data:
if current.right != None:
self.insert(current.right, new)
else:
current... |
from tkinter import *
HEIGHT = 1000
WIDTH = 1000
from tkinter import ttk
window = Tk()
window.geometry("800x1000")
window.title("42 Opentrons App")
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text='Main')
tab_control.add(tab2, text... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dbus
import re
def get_bus():
bus = dbus.SessionBus()
return bus
def get_player(bus):
for service in bus.list_names():
if re.match('org.mpris.MediaPlayer2.', service):
return bus.get_object(service, '/org/mpris/MediaPlayer2')
de... |
# -*- coding: utf-8 -*-
"""Provides a ``CacheableWidgetMixin`` which allows you to construct deform
widgets whose ``values`` are populated dynamically (e.g.: from the db) to
delay actually making db calls until the form they are part of is actually
rendered, and to cache their rendered template output using `Alk... |
"""
单词接龙
给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:
每次转换只能改变一个字母。
转换过程中的中间单词必须是字典中的单词。
说明:
如果不存在这样的转换序列,返回 0。
所有单词具有相同的长度。
所有单词只由小写字母组成。
字典中不存在重复的单词。
你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
示例 1:
输入:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog... |
import pandas as pd
import pickle
from sklearn.externals import joblib
from sklearn import preprocessing
from ..config import develop as default_config
features = '''
สวัสดี
อะไร
ยังไง
เมื่อไหร่
บาย
'''
def get_feature(messages):
features_result = {}
features_count = 0
for feature in features:
... |
import urllib.request
import json
from urllib.parse import urlencode, quote_plus
serviceurl = 'http://py4e-data.dr-chuck.net/json?'
while True:
address = input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urlencode({'sensor':'false', 'address': address})
print ('Retri... |
# RecreateDistributionAreaPolygon.py
# Create DistributionArea polygon feature class
# Copy it into the production database.
# This program is run monthly on Arctic as a scheduled task
#
# This program can only run successfully when
# a connection can be created to the production database
#
# The Distributi... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
... |
__author__ = 'Jeevan'
"""
Mapper program takes input files from the hadoop job, i.e data from pos and neg
folders from both training and testing.
"""
import sys
import glob
from nltk.corpus import stopwords # Import the stop word list
import re
from bs4 import BeautifulSoup # Imported to remove html tags from the rev... |
from collections import Counter
class ValueHistogram:
def build(self, values):
c = Counter(values)
h = max(c.values()) + 1
return [
''.join(e)
for e in zip(*[(c[i]*'X') + (h-c[i])*'.' for i in xrange(10)])
][::-1]
|
#%%
from cv2 import cv2
import numpy as np
import matplotlib.pyplot as plt
import json
import os
def proccess_image(img):
width = 1200
height = 600
img = cv2.resize(img, (width, height))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.GaussianBlur(img, (3, 3), 3)
return img
orb = cv2.ORB... |
from __future__ import print_function, unicode_literals
import json
from aspen.utils import utcnow
from gratipay.testing import Harness
class Tests(Harness):
def make_participant(self, *a, **kw):
kw['claimed_time'] = utcnow()
return Harness.make_participant(self, *a, **kw)
def test_on_key_... |
import numpy
import theano.tensor as T
from theano import function
x = T.dscalar('x')
y = T.dscalar('y')
|
import json
import pytest
from girder.models.item import Item
from pytest_girder.assertions import assertStatusOk
from geometa.constants import GEOMETA_FIELD
from ..utils import uploadSampleData
@pytest.mark.plugin('geometa')
def test_geometa_create_endpoint(server, admin, fsAssetstore):
uploaded = uploadSampleDa... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from typing import List, Optional, Union
from airbyte_cdk.models import FailureType
from airbyte_cdk.utils.traced_exception import AirbyteTracedException
from .source_files_abstract.file_info import FileInfo
class S3Exception(AirbyteTracedException):
... |
from qiskit import IBMQ, Aer
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit.qasm import pi
from qiskit.extensions import U3Gate
import numpy as np
import matplotlib.pyplot as plt
import os
from rwutil import *
OUTPUT = "output"
IBMQ.load_account()
Prov = IBMQ.get_provider(group='ope... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 14:55:27 2017
@author: misakawa
"""
class Typedef:
def __init__(self, type_, error_msg = "Type of {return_or_input} {idx_or_key} should be {type}." ):
self.type_ = type_
self.error_msg = error_msg
def set_lambda(self,... |
# Multi-variable linear regression2
import tensorflow as tf
tf.set_random_seed(777)
# 데이터
# x1 x2 x3
x_data = [[73., 80., 75.], # (5,3)
[93., 88., 93.],
[89., 91., 90.],
[96., 98., 100.],
[73., 66., 70.]]
y_data = [[152.], # 5,1
[185.... |
import tensorflow as tf
import skimage.color, skimage.transform
# Hyper-parameters
# Experiment name
exp_name = 'DDQN-SpaceInvaders'
# Environment
env_name = 'SpaceInvaders-v0'
# Whether to train
train = True
# Whether to plot
plot = True
# Whether to get stats
stats = False
# Whether to render
render = False
# ... |
import numpy as np
def o2satv2a(salinity: np.ndarray, temp: np.ndarray) -> np.ndarray:
"""
Calculate O2 concentration at saturation
:param salinity:
:param temp:
:return:
"""
# Define constants, etc. for saturation calculation
# The constants used are for units of mL O2 / L.
a0 = ... |
from django.urls import path, include
from django.conf.urls import url
from .views import *
from rest_framework import routers
from .views1 import AssetsView, RecipesView, PicturesView
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='Recipes API')
router = routers.Defau... |
# Copyright 2020 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 a... |
# B. Box Fitting
from collections import Counter, OrderedDict
for _ in range(int(input())):
n, W = map(int, input().split())
inp = list(map(int, input().split()))
mp = OrderedDict(Counter(sorted(inp, reverse=True)))
ans = 0
while n > 0:
w_left = W
for w in mp:
while w... |
#!/usr/bin/env python
#coding:utf-8
#Author Fleece_Lin Mail: linuxlzy@163.com QQ: 594621466
import redis
import sys
keyindex = ['used_memory', 'used_memory_rss', 'mem_fragmentation_ratio', 'blocked_clients', 'connected_clients',
'connected_slaves',
'instantaneous_ops_per_sec', 'keyspa... |
#!/usr/bin/python
'''
Created on Sun Octoer 12, 2019
@author: 2.009 Purple
This subscribes to the data published by multiple_fsr.py and calibrates for a sepecific user
'''
import rospy
import getch
import serial
from fsr_readout.msg import forces
from std_msgs.msg import (
Bool,
String,
Int32,
Float64,
Float64Mu... |
#coding:utf-8
import os
import pickle
import amipy
import w3lib.url as urltool
class Request(object):
def __init__(self,spider,url,*,
callback=None,
headers=None,
errback=None,
excback=None,
params=None,
proxy=No... |
from yoamisafe import views
from django.conf.urls import patterns, include, url
urlpatterns = patterns("",
url(r'/temp', views.temp, name='temp'),
url(r'^/map/.*', views.map, name='map'),
)
|
from django.shortcuts import render
from weddingApp.models import RSVP
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
# Create your views here.
class HomeView(TemplateView):
template_name =... |
import requests, json, time
coursedata = []
activeList = []
course_index = 0
speed = 10
uid=0
status = 0
status2 = 0
activates = []
quantity = 0
a = 1
# 获取cookie
def get_cookie(user_id,password):
global uid
url="http://i.chaoxing.com/vlogin?passWord="+str(password)+"&userName="+str(user_id)
res=requests.get... |
import pandas as pd
def get_data_by_year(year_list):
df_list = list()
for year in year_list:
file_path = f'names\yob{year}.txt'
df = pd.read_csv(file_path, names=['Name', 'Gender', 'Qty'])
df['Year'] = year
df_list.append(df)
return pd.concat(df_list)
def count_top... |
from .fetch import db_fetch, GatherInfo, ContentInfo, Statistic
from .telephone import db_tel, CompanyInfo, StatInfo
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 5 16:10:03 2019
@author: andreascazzosi
"""
# =============================================================================
# Class
# =============================================================================
class Player:
players_li... |
#!/usr/bin/env python3
from types import SimpleNamespace
from lilaclib import *
g = SimpleNamespace()
build_prefix = 'extra-x86_64'
def pre_build():
g.oldfiles = clean_directory()
g.files = download_official_pkgbuild('firefox')
for line in edit_file('PKGBUILD'):
if line.startswith('pkgname='):
lin... |
import asyncio
from datetime import datetime
from buffered_channel import BufferedChannel
from event import Event
class Stream:
def __init__(self, update, interval=0, name=None):
self.update = update
self.sources = []
self.sink = None
self.data_chan = BufferedChannel()
... |
def diagonalDifference(arr):
dd = 0
du = 0
length = len(arr)
for i, line in enumerate(arr):
dd = dd + line[i]
du = du + line[length - 1 - i]
return abs(dd - du)
|
import departing_and_reducing_stopwords as DARS
import numpy as np
from TFIDF import TextVectorizer as TV
from BSKM import *
import os
import time
from sklearn.feature_extraction.text import TfidfVectorizer
import pickle
#from compiler.ast import flatten
def getfiles(path):
#filenames = os.listdir(r'E:\te... |
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
class EmbeddingNet(nn.Module):
"""ResNet50 except the classification layer to extract feature
"""
def __init__(self, network='cifar_resnet50', pretrained=False, embedding_len=128, gap=True, f... |
import pandas as pd
import numpy as np
import random as rd
illegal = ["Class"]
class decisionTree:
""""A class that represents a binary decision tree"""
leadingNode = None
nodeArray = []
def addNode(self, node):
self.leadingNode = node
def printTree(self):
pipelines = 0
ze... |
from itertools import combinations # 조합 모듈 이용하기
# 바로 set()을 선언하고 진행해도 되지만
# 프로그래머스 json iteralize 오류 때문에 list 위주로 풀이했다.
def solution(numbers):
answer = []
# 조합 모듈 사용
result = combinations(numbers, 2)
for combination in result:
answer.append(sum(combination))
# 리스트를 집합으로 바꿔 중복을 제거 -> 다시... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'XT'
from time import strftime
import os, sys
import random
base_dir = str(os.path.dirname(os.path.dirname(__file__)))
base_dir = base_dir.replace('\\', '/')
file_path = base_dir + "/db_fixture"
sys.path.append(file_path)
import mysql_db
from... |
from selenium.common.exceptions import NoSuchElementException
def test_add_to_cart_button_is_presence(browser):
browser.get('http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/')
try:
browser.find_element_by_css_selector('.btn.btn-lg.btn-primary.btn-add-to-basket')
except No... |
from rest_framework import serializers
from film.models import origin
class originSerializers(serializers.ModelSerializer):
class Meta:
model = origin
fields = '__all__'
class originOnSerializers(serializers.ModelSerializer):
class Meta:
model = origin
fields = ['name']
|
from copy import copy
from client_states.default.device_event_serializer import \
DefaultDeviceEventSerializerState
from timeattendance.models import DeviceEventChangeRequestForCheck, DeviceEvent
class OmcDeviceEventSerializerState(DefaultDeviceEventSerializerState):
def update(self, instance, validated_dat... |
# Поработайте с переменными, создайте несколько, выведите на экран. Запросите у пользователя некоторые числа и строки и
# сохраните в переменные, затем выведите на экран.
my_name = "Donald"
print(my_name)
my_age = 111
print(my_age)
print(float(my_age))
print(my_name, my_age)
name = input("Добрый день, введите пожалуйс... |
#!/usr/bin/env python
"choose build options for and push to Mozilla's try server"
import sys
import re
import inspect
# A node in the decision tree
class N: # Node
def __init__ (self, prompt, help, action):
self.prompt = prompt
self.help = help
self.action = action
# this deletes a character, then mov... |
# Copyright 2012 James McCauley
#
# 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 writi... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about, name='about'),
path('kids/', views.KidListView.as_view(), name='kids'),
path('kids/<int:pk>', views.KidDetailView.as_view(), name='kid-detail'),
path('kids/<int:pk>/<slug:date>', views... |
from django.contrib import admin
from .models import Expense, Expense_Type, Unit
admin.site.register(Expense)
admin.site.register(Unit)
admin.site.register(Expense_Type)
|
import itertools
import pandas as pd
import numpy as np
import sys
from collections import defaultdict
data_file = sys.argv[1]
with open(data_file, 'r') as f: # open the file
contents = f.readlines()
data_genes = []
frequent_1set = set()
# Geneartes all the combinations of given itemset
def combination_gen(item... |
from rest_framework.parsers import JSONParser
from rest_framework import viewsets
from scapi.models.shoppingcartuser import shoppingcartuser
from scapi.serializers.shoppingcartuserSerializer import shoppingcartuserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = shoppingcartuser.objects.all()
se... |
from django.urls import path
from . import views
urlpatterns = [
path('evaluate-architecture', views.EvaluateArchitecture.as_view()),
]
|
class AIController():
"""Abstract/Base controller for AI."""
def __init__ (self, mission_model, entity_id):
""" Constructor. pass in the id of the entity to control."""
self.mission_model = mission_model
self._init_entities(entity_id)
self.next_moves_by_entity_id = {}
def ... |
# -*- coding: utf-8 -*-
import time
from datetime import datetime, timedelta
from collections import defaultdict
from decimal import Decimal
from django.db import transaction
from django.db.models import Sum
from . import models
def get_token_code():
objs = models.SDBToken.objects.filter(is_disabled=False).order_... |
# coding: utf-8
import numpy as np
from .base import NeighborsBasedMethod
class NearestNeighbor(NeighborsBasedMethod):
'''最近傍のノードとの距離を計算する
最も近いノードを知っている(神)
O(ノード数x平均エッジ数)
'''
header = ['area_id', 'degree', 'labeled_degree', 'distance']
def __init__(self, network, distfunc):
super().... |
import webbrowser
# import requests
# #webbrowser.open('http://inventwithpython.com/')
#
# res = requests.get('http://www.teachinginsanity.net/APUSH/Unit%2001/Henretta%20Chapter%202.pdf')
# print(type(res))
# res.raise_for_status()
# file = open('APUSH2.txt', 'wb')
# for chunk in res.iter_content(100000):
# file.wr... |
import tkinter
main = tkinter.Tk()
myText = tkinter.Text(main)
myText.pack()
# 往文本框插入内容 \r\n是换行
myText.insert(tkinter.INSERT, '这是一段内容,会显示在文本框里\r\n')
myText.insert(tkinter.INSERT, '这是一段内容,会显示在文本框里\r\n')
myText.insert(tkinter.INSERT, '这是一段内容,会显示在文本框里\r\n')
main.mainloop() |
### Estrutura condicional -- simples quando não tem o ''else'' composta quando o tem
'''
if carro.esquerda():
bloco true
else:
bloco false
'''
### condição composta
'''
tempo = int(input('Quantos anos ntem seu carro? '))
if tempo <=3:
print('Carro novo')
else:
print('Carro velho')
print('---FIM---')
''... |
""" server.py """
from flask import Flask, request, jsonify, render_template
from pymongo import MongoClient
import json
MONGODB_HOST = 'localhost'
MONGODB_PORT = 27017
app = Flask(__name__)
app.config.from_object(__name__)
app.config['MONGO_DBNAME'] = "mainAPP"
#connection = MongoClient('localhost', 27017)
connec... |
import tensorflow as tf
import numpy as np
import optimizer as om
import dataset as ds
import matplotlib.pyplot as plt
from PIL import Image as pi
import model
import time
import os
EPOCH_NUM = 500
def main():
print('Loading MNIST dataset...')
mnist = ds.Dataset()
mnist.load(ds.MNIST, '../MNIST/')
mod... |
# https://atcoder.jp/contests/abc233/tasks/abc233_b
# # 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)
L, R = map(int, input().split())
S = inp... |
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
from data import X, y
from train import rf, xgb, gb, et, sv
kfold = StratifiedKFold(n_splits=3, random_state=17)
rf_results = cross_val_score(rf, X, y, cv=kfold, n_jobs=4)
xgb_results = cross_val_score(xgb, X, y, c... |
"""
A, B and Modulo
Problem Description
Given two integers A and B, find the greatest possible positive M, such that A % M = B % M.
Problem Constraints
1 <= A, B <= 10^9
A != B
Input Format
The first argument given is the integer, A.
The second argument given is the integer, B.
Output Format
Return an integer de... |
from messy import Base
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
class Chatroom(Base):
__tablename__ = 'chatrooms'
id = Column(Integer, primary_key=True)
title = Column(String(200))
member_limit = Column(Integer)
pri... |
import requests
from time import sleep
from igninterage import Igninterage
"""flood no tpc de imagens random"""
"""https://www.ignboards.com/threads/topico-das-imagens-randoms.455505695/"""
TOPICO = '455505695'
TEMPO = 200 # segundos
def gur():
""" Retorna img random do imgur.
"""
r = requests.get('ht... |
from django.apps import AppConfig
class EasyifscapiConfig(AppConfig):
name = 'easyifscapi'
|
'''
DESAFIO 041
Crie um programa que leia o ano de nascmento de um atleta.
e mostre sua categoria,de acordo com a idade:
- Até 9 anos: MIRIM - Até 25 anos: SÊnior
- Até 14 anos: INFANTIL - Acima: MASTER
- Até 19 anos: JUNIOR
'''
from datetime import date
ano_atual = date.today().year
nasc = int(input('Ano de nasci... |
#!/usr/bin/env python3
# Convert a coreos-assembler build into a "release.json"
# Originally from https://github.com/coreos/fedora-coreos-releng-automation/blob/main/coreos-meta-translator/trans.py
# See also https://github.com/coreos/fedora-coreos-tracker/blob/main/Design.md#release-streams
from argparse import Argu... |
#
# AUTHOR: Natchapol Srisang (UtopiaBeam)
# KEYWORD: Topological ordering
#
n, m = map(int, input().split())
edges = [tuple(map(int, input().split())) for _ in range(m)]
for _ in range(5):
ls = list(map(int, input().split()))
dc = dict(zip(ls, range(n)))
for s, e in edges:
if dc[s] > dc[e]:
... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import *
@admin.register(Food)
class FoodAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'portion', 'portion_unit', 'fats', 'protein', 'sodium', 'carbohidrates', 'cholesterol','calories', 'created_at', 'last_updated_... |
from django.db import models
from listings.models import Country, Province, City, Zone, OpertationType, PropertyType
# Create your models here.
class CountryData(models.Model):
"""
EACH DATA POINT REPRESENTS ONE MONTH
- Each time a new listing is saved the state in the
current month is updated if it al... |
import requests
from bs4 import BeautifulSoup
url = "https://www.yelp.ca/search?find_desc=Restaurants&find_loc=Sherwood+Park%2C+AB&ns=1"
yelp_r = requests.get(url)
print(yelp_r.status_code)
yelp_soup = BeautifulSoup(yelp_r.text, 'html.parser')
#print(yelp_soup.prettify())
#print(yelp_soup.findAll('a'))
# Pull Page... |
import hashlib
#Expect bytes as inputs
input_as_bytes = b"Hola soy un string!"
first_output = hashlib.sha256(input_as_bytes)
#Only H to h changed
input_as_bytes_changed = b"hola soy un string!"
second_output = hashlib.sha256(input_as_bytes_changed)
print(f"First input: {input_as_bytes}")
print(first_output.hexdigest... |
import pynput.keyboard #this library allow us to manage user keyboard and mouse
import threading
import smtplib
import optparse
log =""
def getargs():
parser = optparse.OptionParser() #command line options and arguments
parser.add_option("-e","--email",dest="email",help="your email")
parser.add_option("-p"... |
from django.shortcuts import render
from game.models import Oyunlar
from haberler.models import Haber,AddFavoriHaber, YorumHaber
from forum.models import Forum, Yorumforum, LikeYorum, LikeForum
from user.models import AddMyFriends, User
def anasayfa(request):
oyun_active=Oyunlar.objects.order_by("?").first()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.