text stringlengths 8 6.05M |
|---|
__author__ = "Komal Atul Sorte"
"""
Given a sorted array arr, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
E... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
# Grid
gridArea = [] # 82 positions, first (zeroth) not used
pgridArea = 1 # For a better debugger view of the grid area (starts at index 1). Pointer in the gridarea
prev_gridArea = []
pprev_gridArea = 1 # For a better debugger view of the grid area (starts at index 1)
numsDone = [0, 0, 0, 0, 0, ... |
import os
import model
import argparse
import numpy as np
import tensorflow as tf
import pandas as pd
import os
import h5py
from datetime import datetime
from tensorflow.python.lib.io import file_io
from io import BytesIO
from keras.callbacks import (ModelCheckpoint, TensorBoard, CSVLogger, History, EarlyStopping, Lam... |
"""
#------------------------------------------------------------------------------
# Create ZV-IC Shaper
#
# This script will take a generalized input from an undamped second order system subject
# to nonzero initial conditions and solve the minimum-time ZV shaper using optimization
#
# Created: 6/20/17 - Daniel Newm... |
#Example code from Bayesian Machine Learning - AB Testing course. The aim is to find the most profitable bandit with the least possible plays.
#To achieve this, the code uses Thompson Sampling; updating the probability to selecting each bandit with each iteration until the optimal bandit is found.
import numpy as n... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-21 05:54
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dep... |
from __future__ import unicode_literals
from django.http import HttpResponseRedirect
from django.views.generic import View
from ..forms import CMSLogoutForm
class LogoutView(View):
def post(self, request, *args, **kwargs):
form = CMSLogoutForm(request, data=request.POST)
if form.is_valid():
... |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random
import queue
import figure2 as F
def plot_implicit(fn, bbox=(-2.5,2.5), AABB_size=2):
''' 陰関数のグラフ描画
fn ...fn(x, y, z) = 0の左辺
bbox ..x, y, zの範囲'''
xmin, xmax, ymin, ymax, zmin, zmax = bbox*3
""... |
class WhineBottle:
#Instance methods are functions you can apply on an instance of the class. Always requires the self argument (passed automaticly)
def __init__(self, UID, name = None, main_grape = None, year = None, type = None, properties = None):
self.UID = UID
self.name = name
self.... |
import numpy as np
import threading
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
class Tree:
def __init__(self):
self.depth = 0
self.feature_ind = 0
self.threshold_ind = 0
self.threshold = 0.0
self.prediction = None
self.left = None
... |
import pygame.mixer, pygame.sndarray
import samplerate
import time
pygame.mixer.init(44100,-16,8,4096)
snd_blue = pygame.mixer.Sound("BLUE.wav")
snd_red = pygame.mixer.Sound("RED.wav")
snd_cyan = pygame.mixer.Sound("CYAN.wav")
snd_yellow = pygame.mixer.Sound("YELLOW.wav")
#snd_blue.play()
#snd_red.play()
#snd_cyan.p... |
class Reverselter:
def __init__(self,l):
for i in reversed(range(len(l))):
print(l[i])
l=[1,2,3,4,5]
Reverselter(l)
|
import math
d=[]
a=list(map(int,input().split()))
for i in a :
d.append(math.factorial(i))
print((*d),sep=',')
|
class ColumnProxy:
def __init__(self, a, column):
self.a = a
self.column = column
def __getitem__(self, row):
return self.a[row][self.column]
def __len__(self):
return len(self.a)
class RowProxy:
def __init__(self, a, row):
self.a = a
self.row = row
... |
"""
The contents of the JSON in the docs/section-schemas files should match the
contents of the fields.contents property in the fixture files.
"""
import json
from operator import attrgetter
from pathlib import Path
from typing import Any
def main() -> None:
here = Path(__file__).parent.resolve()
django_root ... |
from django.conf.urls import url
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^behave/(?P<victimID>\d+)$', views.behave, name='behave'),
url(r'^start_the_fun/$', views.start_the_fun, name='start_the_fun'),
url(r'^end_the_fun/$', views.end_the_... |
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
# from youtubetomp3 import views
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
#... |
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import time
def tsne_transform_fit(x_w2v):
print('doing tsne')
tic = time.time()
tsne = TSNE(n_components=2)
x_tsne = tsne.fit_transform(x_w2v)
print('Time taken:', time.time() - tic)
return x_tsne
def tsne_plot(x_w2v):
p... |
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.9.5
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode \n')
from tkinter import *
from tkinter import ttk
from tkinter.scrolledtext import *
class GuiWindow():
def __init__(self):
... |
{
PDBConst.Name: "paymentmode",
PDBConst.Columns: [
{
PDBConst.Name: "ID",
PDBConst.Attributes: ["tinyint", "not null", "primary key"]
},
{
PDBConst.Name: "Name",
PDBConst.Attributes: ["varchar(128)", "not null"]
},
{
PDBConst.Name: "SID",
PDBC... |
class Toddler:
""" Modeling a toddler """
def __init__(self,name,age):
""" Initializing the toddler """
self.name = name
self.age = age
def talk(self):
""" make the toddler talk sentences """
print(f"{self.name} is now taking.")
def walk(self):
... |
# http://stackoverflow.com/questions/22397289/finding-the-values-of-the-arrow-keys-in-python-why-are-they-triples
import sys, tty, termios
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(3)
finally:
... |
#!/usr/bin/python
import sys
#For each line of the imported data set...
for l in sys.stdin:
#Break each line into items, spltting on each tab and removing blank space
items = l.strip().split('\t')
#For each item from the list of items...
fields = ('Message-ID', 'From', 'To', 'Cc', 'Bcc') #Look for these feild... |
from flask_sqlalchemy import SQLAlchemy
sql_db = SQLAlchemy()
class Address(sql_db.Model):
"""
Simple address class for a sql database
"""
__tablename__ = "addresses"
name = sql_db.Column(sql_db.String(100), primary_key=True)
address = sql_db.Column(sql_db.String(4096))
longitude = sq... |
class Arbol:
def __init__ (self, J1, J2, Meta):
self.siguiente = None
self.anterior = None
self.raiz = [J1,J2,Meta]
def Raiz(self):
return self.raiz
def crearArbol(self):
J1= self.raiz[0]
J2= self.raiz[1]
Meta= self.raiz[2]
NA=NodoAr... |
# -*- coding:utf-8 -*-
"""
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例
如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,
2,1,5,3,8,6},则重建二叉树并返回
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def re... |
from django.shortcuts import render
from .models import Post
from django.contrib.auth.decorators import login_required
@login_required(login_url="/account/signin/")
def index(request):
posts = Post.objects.filter(author=request.user)
return render(request, "showcase/index.html", {"posts": posts})
def post_det... |
def initialize_empty_grid():
squares = {}
for i in range(8):
for j in range(8):
square_info = {'piece': None, 'coord':(i, j), 'selected':None, 'gamerule':None}
squares[(i,j)] = square_info
return squares
def fix_sprite_dir(piece):
previous_dir = piece.sprite_dir
pie... |
def one_away(s1, s2):
diff = abs(len(s1) - len(s2))
if diff >= 2:
return False
elif diff == 0:
return sum(s1[i] != s2[i] for i in range(len(s1))) <= 1
else:
if len(s1) > len(s2):
temp = s1;
s1 = s2;
s2 = temp;
for idx in range(len(s1... |
import torch.nn as nn
import torchvision.models as backbone_
import torch.nn.functional as F
import torch
from torchvision.ops import MultiScaleRoIAlign
from collections import OrderedDict
import torch
from torch.nn.utils.rnn import pad_sequence
import torchvision
device = torch.device("cuda" if torch.cuda.is_available... |
import glob, os, argparse
import fitsio as fi
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--meds', type=str, action='store')
parser.add_argument('--truth', type=str, action='store')
args = parser.parse_args()
truth_dir=args.truth
meds_dir=args.meds
files=glob.glob(meds_dir+"/DES*.fits.fz")
... |
import sys
from itertools import accumulate
input = sys.stdin.readline
def main():
N, K = map( int ,input().split())
TK = K*2
B = [[0]*(K*2) for _ in range(TK)]
for _ in range(N):
x, y, c = input().split()
x, y = int(x), int(y)
if c == "B":
B[x%TK][y%TK] += 1
... |
from django.contrib.auth.models import User
from .models import StoredImage
from rest_framework import serializers
class StoredImageSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
image = serializers.ImageField()
class Meta:
model = StoredImage
... |
import sys
import os
import re
import argparse
from ics import Calendar, Event
parser = argparse.ArgumentParser()
parser.add_argument("input_file", type=str,
help="input text calendar")
parser.add_argument("output_dir", type=str,
help="output directory to store ICSs")
args = par... |
import cv2
import numpy as np
from cv2 import aruco
from src.domain.objects.robot import Robot
from src.vision.camera_parameters import CameraParameters
from src.vision.coordinate_converter import CoordinateConverter
from src.vision.transform import Transform
class RobotDetector(object):
def detect(self, img) ->... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2020-8-9 23:11:00
# version: 1.0
# __author__: zhilong
import requests
import requests
proxies = {
"http": "47.106.162.218:80" # 代理ip
}
headers = {
"User_Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.... |
from django.conf.urls import url
from shelf.views import *
app_name = "shelf"
urlpatterns = [
url(r'^authors/$', AuthorListView.as_view(), name='my_author_list'),
url(r'^authors/(?P<author_id>\d+)/$', AuthorDetailView.as_view(), name='author_detail'),
url(r'^books/$', BookListView.as_view(), name="boo... |
import Tkinter as tk
import ChordMappingParser
import ChordDecoder
import Fingers
KEYS_MAPPING = {
"7" : Fingers.INDEX,
"8" : Fingers.MIDDLE,
"9" : Fingers.RING,
"0" : Fingers.PINKY,
"b" : Fingers.THUMB1,
"n" : Fingers.THUMB2,
}
chord_mapping = ChordMappingParser.parse_mapping_CSV("mapping.cs... |
L=int(input("Quel Longueur?"))
l=int(input("Quel largeur?"))
from turtle import *
def Rectangle(L,l):
rectangle= Turtle()
rectangle.forward(L)
rectangle.right(90)
rectangle.forward(l)
rectangle.right(90)
rectangle.forward(L)
rectangle.right(90)
rectangle.forward(l)
Rectangle(L,l) |
__author__ = 'Крымов Иван'
# Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на
# экран. Например, если введено число 3486, надо вывести 6843
num = int(input("Введите целое число больше девяти: "))
m = 0
while num > 0:
m = m * 10 + num % 10
num = num // 10
print("Вывод э... |
import torch
from torch import nn
import torch.nn.functional as F
import torch.optim
from collections import OrderedDict
import logging
import numpy as np
# strip_keys is needed because if DataParallel was used during saving, the keys
# of model_state_dict are prepended with 'module.'
def load_model(model, saved_mode... |
# tUtils.py - Utils written by TDL9
# Import this module as t
# import numpy as np
import functools as fn
import itertools as itt
import hy
# eval Hy expression
# see hy document for more details
hyc = hy.eval(hy.read_str("(comp hy.eval hy.read_str)"))
# functools.reduce(function, iterable[, initializer])
reduce = ... |
a=int(input())
b=input()
c=''
for i in b:
if i in c and i!=" ":
print(int(i))
break
else:
c+=i
if c==b:
print("unique")
|
import sys
import torch
from copy import copy as copy
import numpy as np
import utils
import torch.nn.functional as F
from torch.autograd import Variable
import utils
class Plastic_Conv_Layer(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, ... |
"""
Firebase provides a set of services for Firebase provider.
"""
from diagrams import Node
class _Firebase(Node):
_provider = "firebase"
_icon_dir = "resources/firebase"
fontcolor = "#ffffff"
|
# -*- coding: utf-8 -*-
from Tkinter import *
import re,time,json,requests,brotli,os
requests.packages.urllib3.disable_warnings()
url={
"boerse":"https://www.boerse-online.de/rss",
"alpha":"https://seekingalpha.com/news/top-news/feed",
"planspiel":"https://www.planspiel-boerse.de/skherford/_js_DS/0/content_extern/... |
I = None
TARGET = None
SUM = None
def recurse(count, depth, max_depth):
global I
global TARGET
global SUM
if I >= TARGET or depth >= max_depth:
return
SUM += count
I += 1
# Recurse left
recurse(count, depth + 1, max_depth)
# Recurse right
recurse(count + 1, depth + ... |
"""
An XML Foreign Data Wrapper.
"""
from . import ForeignDataWrapper
from xml.sax import ContentHandler, make_parser
import os
from StringIO import StringIO
import pycurl
import re
class MulticornXMLHandler(ContentHandler):
def __init__(self, elem_tag, columns):
self.elem_tag = elem_tag
self.colu... |
import sys
print("Import ctypes")
from ctypes import *
print("CDLL")
lib = CDLL("/home/appuser/lib/libta_lib.so.0.0.0")
print(str(lib))
print("Importing talib")
sys.stdout.flush()
# import library
import talib
|
class Mots:
def __init__(self, mot, posinit, posactu):
self.mot=mot
self.posint = [posinit]
self.posactu=posactu
def PosInt(self,j,i):
self.posint.append((j,i))
def checkPosInt(self,j,i):
if (self.posactu[0]+j,self.posactu[1]+i)in self.posint :
return False
else :
return True
def ch... |
from api.app import create_app
from api.conf import ProductionConfig
app = create_app(ProductionConfig())
|
import json
from powerManager import Manager
def launchHTTPServer(manager):
from BaseHTTPServer import BaseHTTPRequestHandler
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if '/restart' in self.path:
try:
path = self.path.split('&')
... |
#!/usr/bin/env python
"""
_LoadForSubmitter_
Oracle function to load jobs for submission
"""
__all__ = []
from WMCore.WMBS.MySQL.Jobs.LoadForSubmitter import LoadForSubmitter as MySQLLoadForSubmitter
class LoadForSubmitter(MySQLLoadForSubmitter):
"""
_LoadForSubmitter_
Oracle implementation of JobSub... |
# webio整合flask需要
from pywebio.platform.flask import webio_view
from pywebio import STATIC_PATH
from flask import Flask, send_from_directory
# 脚本需要
from pywebio.input import *
from pywebio.output import *
from pywebio.session import set_env
# 自己程序
def cap_namer(value_str):
value_str = value_str.lower()
if 'u' i... |
import unittest
from validator import Validator
validator = Validator()
class TestCarModel(unittest.TestCase):
def test_CarModelNameValidation(self):
carModel = 'Sedan'
result = validator.nameValidate(carModel)
self.assertTrue(result)
def test_CarModelTypeValidation(self):
m... |
"""Create the model settings voor the sequential models."""
from typing import Tuple, List
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout, BatchNormalization
def build_models(input_shape: Tuple[int, int, int] = (48, 48, 1), num_classes: int = 7) -> List[dict]:
"""
Build the ... |
# -*- coding: utf-8 -*-
__author__ = 'Augusto Almeida'
__email__ = 'acba@cin.ufpe.br'
__version__ = '0.1.1'
from .elmk import ELMKernel
from .elmr import ELMRandom
from .mltools import * |
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db import models
from django.urls import reverse
from authapp.models import MyUser
from mainapp.models import Service_type
from django.template.defaultfilters import slugify
from dj... |
import os
class Config(object):
REMOTE_DEBUG = False
POSTGRES_HOSTNAME = os.environ.get('DATABASE_HOST', 'localhost')
POSTGRES_PASSWORD = os.environ.get('POSTGRES_PASSWORD', 'volumetric')
POSTGRES_USER = os.environ.get('POSTGRES_USER', 'volumetric')
POSTGRES_DB = os.environ.get('POSTGRES_DB', POST... |
__author__ = 'cloudbeer'
|
from typing import List
def Min(numbers: List, length: int) -> int:
if length <=0:
raise ValueError("Invalid parameters")
index1 = 0
index2 = length - 1
mid = index1
result = numbers[index1]
while numbers[index1] >= numbers[index2]:
if index2 - index1 == 1:
mid = in... |
# Generated by Django 2.2.5 on 2020-06-19 07:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='bio',
... |
from mxnet import ndarray as nd
def cross_entropy(yhat, y):
return - nd.pick(nd.log(yhat), y)
def SGD(params, lr):
for param in params:
param[:] = param - lr*param.grad
|
"""
Student ID: 2594 4800
Name: JiaHui (Jeffrey) Lu
Aug-2017
"""
import numpy as np
def taylor_expo(x):
"""
Implements the taylor expansion of the exponential function.
Prints out approximate relative error as the computation proceeds.
:param x: the input value for expo(x)
:return: the value for e... |
#!/usr/bin/env python
from training import Trainer
from Classifiers import SimpleNaiveBayes,HashTagNaiveBayes,SimpleCluster,UserLanguageModel,ConcensusModel,BigLanguageModel,TopFeaturesNaiveBayes,NearestNeighborsNaiveBayes,ChronologicalRanker
import experiments
import argparse
import os
parser = argparse.ArgumentPar... |
# Generated by Django 3.1.8 on 2021-07-20 00:47
import dictators.dictators_game.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dictators_game', '0005_game'),
]
operations = [
migrations.AlterField(
model_name='game',... |
n=int(input())
f=[1,1,2]
if n<3: print(f[n])
else:
for i in range(3,n+1):
f.append((f[-1]+f[-2])%10007)
print(f[n]%10007) |
from flask import redirect, render_template
from app.errors import bp
@bp.app_errorhandler(404)
def not_found_error(error):
return render_template('errors/404.html'), 404
|
#import sys
#input = sys.stdin.readline
import numpy as np
def main():
N = int( input())
P = list( map( int, input().split()))
N = 100**2+1
dp = np.zeros(N)
dp[0] = 1
for p in P:
dp[p:] += dp[:N-p]
# print(dp[:11])
ans = sum([1 if t > 0 else 0 for t in dp])
print(ans)
if... |
import torch
import numpy as np
from typing import Any, Dict, Optional, Tuple, List, Iterable
def cal_metrics(y_score, y_true):
with torch.no_grad():
metrics = {}
#print(y_score)
#print(y_true)
#y_score_softmax = nn.functional.softmax(y_score, dim=-1)
#print(y_score_softmax)... |
tc = int(raw_input())
for i in xrange(tc):
n, m = map(int, raw_input().split())
if n <= m:
if n % 2 == 0:
print "L"
else:
print "R"
else:
if m % 2 == 0:
print "U"
else:
print "D" |
import matplotlib.pyplot as plt
import numpy as np
T = 20
n = np.arange(21)
x = np.sin(2.0 * np.pi / T * n)
fig = plt.figure(figsize=(13, 5))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = ax1.twinx()
ax1.stem(n, x)
ax1.set_title("8bit")
ax1.set_xlabel("Time[sample]")
ax1.set_ylabel("Amplitude")
ax1.set_xticks(n)
ax1.hlines(... |
from pwn import *
import sys
#import kmpwn
sys.path.append('/home/vagrant/kmpwn')
from kmpwn import *
#fsb(width, offset, data, padding, roop)
#config
context(os='linux', arch='i386')
context.log_level = 'debug'
FILE_NAME = "./canary"
HOST = "shell.actf.co"
PORT = 20701
if len(sys.argv) > 1 and sys.argv[1] == 'r':... |
__author__ = 'brian'
from django.conf.urls import url
from . import views
from datetime import datetime
from My_bots.forms import BootstrapAuthenticationForm
urlpatterns=[
# /index/
url(r'^$',views.index,name='index'),
url(r'^contact/', views.contact, name='contact'),
url(r'^about/', views.about, nam... |
import time
class Timer:
def __init__(self):
self.start_time = time.clock()
def elapsed(self):
return prettify(time.clock() - self.start_time)
def prettify(elapsed):
hours, remainder = divmod(elapsed, 3600)
minutes, seconds = divmod(remainder, 60)
strings = []
_append_if_po... |
import requests,base64
from bs4 import BeautifulSoup
from cveMysqlPress import cveMysqlPress
from sendEmail import sendCveEmail
# 获取最新到CVE列表,返回包含cve的url列表
def getCVES():
try:
url = 'https://cassandra.cerias.purdue.edu/CVE_changes/today.html'
res = requests.get(url)#, headers=headers, timeo... |
from simphony.core.cuba import CUBA
from simphony.core.keywords import KEYWORDS
from ..common.atom_style_description import ATOM_STYLE_DESCRIPTIONS
class LammpsDataLineInterpreter(object):
""" Class interprets lines in LAMMPS data files using atom-style
Lines should be interpreted differently based upon th... |
def create_map(target, size):
M = {}
sum = 0
while sum <= target:
M[sum] = sum // size
sum += size
return M
if __name__ == "__main__":
target, large, small = map(int, input().split())
LARGE_MAP = create_map(target, large)
SMALL_MAP = create_map(target, small)
for vol... |
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.api import VAR, DynamicVAR
from svars_cv import SVAR_CV
# data contains quartlery observations from 1965Q1 to 2008Q2
# assumed structural break in 1979Q3
# x = output gap
# pi = inflation
# # i = interest rates
# set.seed(23211)... |
from TimeParser import TimeFraction
from GenericParser import GenericParser
from db import ConfUtil
from threading import Thread
class GridDataHolder:
"""data aggregator for the log file, separates data from render context"""
class AddIf:
def __init__(self):
pass
def __call__(sel... |
"""
十进制转换为八进制/十六进制
"""
from pythonds.basic.stack import Stack
def change_digits(num,mode):
s=Stack()
all_nums="0123456789ABCDEF"
while num>0:
a=num%mode
s.push(a)
num=num//mode
stringg=""
while not s.isEmpty():
stringg=stringg+all_nums[s.pop()]
... |
# instance/config.py
import os
SECRET_KEY = 'p3i_information_systems'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.getcwd() + '/p3i.db'
|
'''
Número perfeito: é um número onde a soma dos seus divisores positivos (exceto o próprio número) é igual a esse número
Exemplo: 6
6 = 1 + 2 + 3 = 6
'''
def numPerfeito(n):
soma = 0
for i in range(1, n):
if n % i == 0:
soma = soma + i
if(soma == n):
return 'Número perfeito'
return 'Número imperfeito'
... |
'''
kwargs = key value arguments
'''
def m1(*args, **kwargs):
print("the type of args is: ", type(args))
print("the type of kwargs is: ", type(kwargs))
# dic_lei = {"name": "lei", "age": 23, "height": 182}
def someone(**kwargs):
for k, v in kwargs.items():
print(k, ":", v)
someone(name="xiao... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from behavioral_patterns.strategy.hand_signal import get_hand, HandSignal
from behavioral_patterns.strategy.strategy import Strategy
# ˄
# Mirror Strategy: showing a hand signal from the previous opponent's hand signal.
class MirrorStrategy(Strategy):
# ˅
... |
def main():
opcodeProgrammInput = open("inputDay5.txt", "r")
for line in opcodeProgrammInput:
opcodeProgramm = [int(code) for code in line.split(",")]
opcodeProgrammInput.close()
runOpcodeProgramm(opcodeProgramm)
print(opcodeProgramm)
def runOpcodeProgramm(opcodeProgramm):
position = 0
while(position <= le... |
from django.contrib import admin
from django.utils.safestring import mark_safe
from .common import slugify
from django.forms import SelectMultiple
# Register your models here.
from .models import (
Product,
Marka,
Category,
Product_details,
Product_colors,
Product_images,
Tag,
Produ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 26 06:56:05 2019
@author: Freakky7781_VRikk
"""
from nltk import flatten
import copy
b='_'
final= [[1,2,3],[4,5,6],[7,8,b]]
def getupos(matrix):
for i in matrix:
if b in i:
return [matrix.index(i),i.index(b)]
def c... |
import mysql.connector
import hashlib
import math
import smtplib
from socket import gaierror
from smtplib import SMTPException
mydb = mysql.connector.connect(
host="127.0.0.1",
user="root",
passwd="22051998",
database = "icapitstop"
)
mycursor = mydb.cursor()
def login(username, password):
sql = "select *... |
from django.contrib import admin
from .models import SocialMedia, Member
class SocialMediaInLine(admin.TabularInline):
model = SocialMedia
extra = 1
class MemberAdmin(admin.ModelAdmin):
inlines = [
SocialMediaInLine,
]
list_display = ['name', 'email', 'role_description']
admin.site.reg... |
nEvents = 10000
xDistance = 100
yRange = [-200, 200]
typicalScatteringDistance = 10
angleConstant = 40
speedDecreaseConstant = .95
magneticField = .2
massOverCharge = 1.0
pi = 3.1415
verbose = 1
xBound = [0, 100]
yBound = [-1000, 1000]
|
from django.contrib import admin
# Register your models here.
from .models import Attraction
admin.site.register(Attraction)
|
from bisect import bisect_left
A, B, Q = map( int, input().split())
S = [ int( input()) for _ in range(A)]
T = [ int( input()) for _ in range(B)]
X = [ int( input()) for _ in range(Q)]
for i in range(Q):
q = X[i]
ANS = []
# jinja kara
JP = []
s = bisect_left(S, q)
if s == 0:
JP.append(S[... |
class A:
def do_smth(self):
print("INSIDE OF A")
class B(A):
def do_smth(self):
print("INSIDE OF B")
class C(A):
def do_smth(self):
print("INSIDE OF C")
class D(B, C):
pass
# def do_smth(self):
# print("INSIDE OF D")
obj = D()
obj.do_smth()
print(D.mro())
# ... |
from datetime import date
from freezegun import freeze_time
from onegov.ballot import ElectionCompound
from onegov.ballot import ElectionCompoundRelationship
from onegov.ballot import ElectionResult
from onegov.ballot import PartyPanachageResult
from onegov.ballot import PartyResult
from onegov.ballot import ProporzEle... |
#Divisible Sum Pairs
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
l = [(i , j) for i in range(len(a)) for j in range(i + 1 , len(a)) if (a[i] + a[j]) % k == 0]
#d = [(i , j) for i in a for j in a[1 : ]]
#print(d)
#print(l)
pri... |
import sys
import json
import requests
URL_ALL = "https://restcountries.eu/rest/v2/all"
URL_NAME = "https://restcountries.eu/rest/v2/name"
def requisiscao(url):
try:
resposta = requests.get(url)
if resposta.status_code == 200:
return resposta.text
except:
p... |
from random import seed
from random import random
import random
def generateRandomData(df, numberOfRowsToGenerate):
seed()
d = {}
#df_random = pd.DataFrame()
#GET ALL THE VALUES IN THE DATAFRAME, SAVE THEM TO A DICTIONARY. e.g., "Housing" (column name) -> [on campus, off campus] (possible values)
fo... |
from ED6ScenarioHelper import *
def main():
# 蔡斯
CreateScenaFile(
FileName = 'C3116 ._SN',
MapName = 'Zeiss',
Location = 'C3116.x',
MapIndex = 1,
MapDefaultBGM = "ed60034",
Flags = 0,
En... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.