text stringlengths 8 6.05M |
|---|
import random
import yaml
from Character import Character
from Equipment import Equipment
def createCharacter(name, str=0, dex=0, con=0):
c = Character()
c.setStats(str, dex, con, name)
characters.append(c)
def createEquipment(cat, name):
if cat == 1:
stream = file('Data/equipment/weapons/' + name + '.yaml', '... |
import dash_bootstrap_components as dbc
from dash import html
buttons = html.Div(
[
dbc.Button("Regular", color="primary", className="me-1"),
dbc.Button("Active", color="primary", active=True, className="me-1"),
dbc.Button("Disabled", color="primary", disabled=True),
]
)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def rever... |
print ("Extração de Raizes")
a= float(input("Qual o valor do quoficiente a?: "))
b= float(input("Qual o valor de quoficiente b?: "))
c= float(input("Qual o valor de quoficiente c?: "))
delta = b**2-4*a*c
if delta > 0:
x = (-b+(delta**0.5))/(2*a)
x2= (-b-(delta**0.5))/(2*a)
if x2<x:
print("as raízes ... |
"""
///////////////////////////////////////////////////////
│
│ Filename: automate_1_verify_gz.py
│ Description:
│ To verify the integrity of .gz files in directory
│ and print the corrupted ones' file names.
│ ==================================================
│ Authorship: @cgneo
│ Copyright: Modified BSD License.
│... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
minimum,maxglobal = prices[0],0
for i in range(1,len(prices)):
minimum = min(minimum,prices[i])
if prices[i]>minimum:
maxglobal = max(m... |
from django.contrib import admin
from django.contrib.auth.models import Group, User
from django.contrib.auth.admin import GroupAdmin, UserAdmin
from piston.models import Consumer
from basketauth.admin import ConsumerAdmin
from subscriptions.admin import SubscriptionAdmin
from subscriptions.models import Subscription
... |
"""
*********************************************************************
This file is part of:
The Acorn Project
https://wwww.twistedfields.com/research
*********************************************************************
Copyright (c) 2019-2021 Taylor Alexande... |
"""Statistical tests for multidimensional data in :class:`NDVar` objects"""
__test__ = False
from ._stats.testnd import (t_contrast_rel, corr, ttest_1samp, ttest_ind,
ttest_rel, anova)
|
from django.conf.urls import url
from . import views
from product.views import ProductDetailView
app_name = 'product'
urlpatterns = [
url(r'$', views.index, name='index'),
url(r'^(?P<product_id>[0-9]+)/$', ProductDetailView.as_view(), name='detail')
] |
import os
from moviesnotifier import (
MoviesNotifier, SqlLiteMovieRepository, UrlLibHtmlRetriever,
PrintNotificationListener, IFNotifier, NotificationListenerList,
CorsaroneroWebpageFactory, TntvillageWebpageFactory,
MinSeedPolicy, KeywordPolicy
)
def absolutePathFromRelative(relative):
currentDirectory = ... |
"""
Functions to read from files
TODO: move the functions that read label from Dataset into here
"""
import numpy as np
def get_calibration_cam_to_image(cab_f):
for line in open(cab_f):
if 'P2:' in line:
cam_to_img = line.strip().split(' ')
cam_to_img = np.asarray([float(number) fo... |
print("New Pytthon File")
|
import numpy as np
import wfdb
from wfdb import processing
class test_processing:
"""
Test processing functions
"""
def test_resample_single(self):
sig, fields = wfdb.rdsamp("sample-data/100")
ann = wfdb.rdann("sample-data/100", "atr")
fs = fields["fs"]
fs_target = 5... |
from fractions import Fraction
def sum_fracts(lst):
answer = sum(Fraction(*a) for a in lst)
numerator = answer.numerator
denominator = answer.denominator
if numerator == 0:
return None
elif denominator == 1:
return numerator
return [numerator, denominator]
|
"""
Task 2
Construction and Reasoning with Inheritance Networks
"""
import sys
import copy
import itertools
"""
Class Sub-Concept
"""
class concept(object):
#Constructor
def __init__(self, name):
self.name = name
self.outgoingEdges = []
def __str__(self):
return self.name
... |
dadosAluno = dict()
dadosAluno['nome'] = str(input('Digite o nome: '))
dadosAluno['média'] = float(input(f'Digite a média do Aluno {dadosAluno["nome"]}: '))
if dadosAluno['média'] >= 7:
dadosAluno['situação'] = 'Aprovado'
elif 5 <= dadosAluno['média'] < 7:
dadosAluno['situação'] = 'Recuperação'
else:
dadosA... |
import pyglet
import resource, player, i_sprite
win = pyglet.window.Window(fullscreen=True)
# Our batch for holding all objects to be drawn.
b_obj = pyglet.graphics.Batch()
# Write info strings to the bottom of the screen.
help_msg = "Controls: WASD"
help_lbl = pyglet.text.Label(text=help_msg, x=10, y=30, batch=b_ob... |
from time import sleep
from tqdm import tqdm
for i in tqdm(range(1,500)):
sleep(0.01) |
import sys
from common import *
import adcdac # ADC, DAC
import bunch_select # BUN
import ddr # DDR
import detector # DET, BUF
import fir # FIR
import sensors # SE
import sequencer # SEQ
import triggers # TRG
import tune # TUNE
import tune_peaks # PEAK
import tune_fol... |
from .models import (
Architecture,
GadgetSnap,
Release,
ScreenshotURL,
)
from django.contrib import admin
@admin.register(Architecture)
class ArchitectureAdmin(admin.ModelAdmin):
pass
@admin.register(GadgetSnap)
class GadgetSnapAdmin(admin.ModelAdmin):
pass
@admin.register(Release)
class ... |
#!/usr/bin/python3
from alpha_vantage.timeseries import TimeSeries
from datetime import datetime, date, timedelta
from pytz import timezone
import subprocess
from time import sleep
import sys
THRESHOLD = 0.5 # In percentage
TIMEZONE = timezone('Europe/Madrid')
# Only execute between 8:00 and 18:00
now_utc = da... |
a,b=4,3
if True:
print('{0}'.format(a or b)) # or中, 至少有一个非0时,返回第一个非0;C语言中,a,b只要有一个数大于0,a||b为1
print('{0}'.format(a and b)) #and中含0,返回0; 均为非0时,返回后一个值;C语言中,a,b全大于0,a&&b为1
print('{0}'.format(a | b)) #按位或;C语言中,a|b为7
print('{0}'.format(a & b)) #按位与;C语言中,a&b为7
|
from __future__ import division
import datetime
from math import ceil
import six
from flask_potion.exceptions import ItemNotFound
from flask_potion import fields
class Manager(object):
"""
.. attribute:: supported_comparators
A tuple of names filter comparators supported by this manager.
:para... |
from qiskit import Aer, ClassicalRegister, execute, QuantumCircuit, QuantumRegister
q = QuantumRegister(4) # initialize 4 quantum registers (qubits)
c = ClassicalRegister(4) # initialize 4 classical registers to measure the 4 qubits
qc = QuantumCircuit(q, c) # initialize the circuit
backend = Aer.get_backend('qasm_sim... |
import mei
import time
import yaml
import scan
import skill
import julius_test
def say_something():
julius_test.listen()
if text == 'ラーメンタイマー' or text == '砂時計':
skill.ramen()
elif text == '癒やして':
skill.care()
elif text == '計算' or text == '電卓':
skill.calculation()
else:
... |
import requests
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0"}
url = "http://127.0.0.1:80/"
password_list = open("wordlist.txt", "r")
for line in password_list:
password = line.strip()
users = ["Admin", "admin"]
for user in users:
r = requests.post(url, data={"in... |
from direct.distributed.DistributedObjectGlobalUD import DistributedObjectGlobalUD
from direct.directnotify import DirectNotifyGlobal
class SpeedchatRelayUD(DistributedObjectGlobalUD):
notify = DirectNotifyGlobal.directNotify.newCategory('SpeedchatRelayUD')
def __init__(self, air):
DistributedObjectGl... |
def len():
y=input("Enter: ")
count=0
for x in y:
count=count+1
print(count)
return 0
a=len()
print(a)
|
import sys
import numpy as np
from scipy.special import erf
sys.path.append(".")
from Random import Gaussian
# main function for our coin toss Python code
if __name__ == "__main__":
# default number of samples (per experiment)
N = 10
a = -1
b = 1
if '-h' in sys.argv or '--help' in sys.argv:
... |
'''
Monitors file usage and stores last opened files
Possible to search recently used files
Check for existing index file, if none exist, create one, else open it and store in memory
Create event watching for launch file events, run in separate thread
When event found, write name:path of file to index dict, then write... |
import re
from collections import defaultdict
from dataclasses import dataclass
from typing import Optional, Union
import common.input_data as input_data
@dataclass
class MaskInstruction:
value: str
@dataclass
class MemorySetInstruction:
address: int
value: int
Instruction = Union[MaskInstruction, Memo... |
# Generated by Django 2.1.3 on 2019-03-28 03:57
import datetime
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='... |
import unittest
import os
import sys
lib_path = os.path.abspath('../src/')
sys.path.append(lib_path)
try:
from Comodo.SOM import * # @UnusedWildImport
except ImportError:
from trunk.Comodo.SOM import * # @UnusedWildImport
class TesteSOM(unittest.TestCase):
def setUp(self):
self.som1 = SOM()
... |
import glob
import os
import pathlib
import re
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
# include the path here to a folder full of rasters that QGIS can load
path_to_rasters = "."
# folder for output sections as PNGs
path_for_outputs = "."
def parse_raster_layer_depths(rfi... |
from .account_saver import RedisClient
class CookieGenator(object):
def __init__(self,website):
self.website = website
self.accounts = RedisClient('accounts', website)
self.cookies = RedisClient('cookies', website)
self.init_browser()
def init_browser(self):
def __del__(se... |
from flask import Flask
from flask_restful import Api
from models import Main, sendMail
app = Flask(__name__)
api = Api(app)
api.add_resource(Main, '/')
api.add_resource(sendMail, '/mail')
if __name__ == '__main__':
app.run(debug = True) |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 30 06:19:44 2019
@author: ethan
"""
import os
import numpy as np
import pandas as pd
from datetime import datetime as dt
from datetime import timedelta, timezone
import praw
import numpy as np
import pandas as pd
import json as js
import urllib, json
from bokeh.io impor... |
# -*- coding: utf-8 -*-
# -*- mode: python -*-
#"""Functions for file IO"""
#from __future__ import print_function, division, absolute_import
import numpy
import tables
fullFile = tables.open_file(r'C:\Users\lasya\crcns-vim1-lp3wv\data\EstimatedResponses.mat')
print(fullFile.list_nodes) # Show all variables availabl... |
def result(target, candidates):
rt = 0
for candidate in candidates:
diff = len(target) - len(candidate)
for t in target:
if t in candidate:
candidate.remove(t)
rest = len(candidate)
if (diff == 0 and (rest == 0 or rest == 1)) or (diff == 1 and rest == ... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, verbose_name=u'用户名', on_delete=models.CASCADE, related_name="userprofile")
nickname = models.CharField(max_length=32, verbose_name=u'昵称')
a... |
a=0
b=1
c=1
x=int(input("enter your number"))
for i in range(x):
print(b)
b=a+c
a=c
c=b
|
from webservice.ticketing.autotask.autotask import *
from webservice.ticketing.autotask.autotask_fields import * |
import math
print(math.asinh(300)) |
# coding=UTF-8
# POST请求接收
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import socket
import data
from hashlib import sha256
from tornado.options import define, options
from os import path, mkdir
from shutil import copyfile
# 绑定地址
define('port', default=3000, type=int, hel... |
# -*- coding: utf-8 -*-
"""
This is the main module containing the implementation of the SS3 classifier.
(Please, visit https://github.com/sergioburdisso/pyss3 for more info)
"""
from __future__ import print_function
import os
import re
import json
import errno
import numbers
import numpy as np
from io import open
fr... |
# Generated by Django 3.1.7 on 2021-03-11 14:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spotify', '0002_vote'),
]
operations = [
migrations.AlterField(
model_name='spotifytoken',
name='access_token',
... |
#!/usr/bin/env python
__author__ = "Master Computer Vision. Team 02"
__license__ = "M6 Video Analysis. Task 2"
# Import libraries
import os
from train import *
from adaptive import *
from util import *
# Highway sequences configuration, range 1050 - 1350
highway_path_in = "./highway/input/"
highway_path_gt = "./high... |
"""
Crie um programa que receba um vetor de strings e após isso receba uma outra
string e a insira no inicio de cada item da lista.
Exemplo
Entrada Saída
["a", "b", "c"] "al" ["ala", "alb", "alc"]
"""
list = []
index = 3
for i in range(index):
item = str(input("Digite o valor a ser adicionad... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import sys
import time
import logging
import json
_LOGGER = logging.getLogger(__name__)
def db_create():
from ... |
import concurrent.futures
import multiprocessing
import pickle
from typing import Any, Callable, List
import pandas as pd
import torch
import torch.distributed as dist
import tqdm
# ===== util fucntions ===== #
def item(tensor):
if hasattr(tensor, 'item'):
return tensor.item()
if hasattr(tensor, '__g... |
import unittest
from katas.kyu_7.factorial import factorial
class FactorialTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(factorial(0), 1)
def test_equal_2(self):
self.assertEqual(factorial(1), 1)
def test_equal_3(self):
self.assertEqual(factorial(2), 2)
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 21 17:01:38 2017
@author: XuL
"""
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import os
import sys
#sys.setdefaultencoding("utf-8")
import nltk
from nltk.tree import *
import nltk.data
import nltk.draw
from nltk import tokenize
from ... |
import shelve
s = shelve.open('test_shelf')
try:
s['key1'] = {'int':10, 'float':3.4, 'string':'sample data'}
finally:
s.close()
|
# NINJA BONUS: Use modules to separate out the classes into different files.
from ninja_class import Ninja
# Make an instance of a Ninja and assign them an instance of a pet to the pet attribute.
ninja1 = Ninja('joe','shmoe','salmon snacks','Victor')
ninja1.adopt_a_pet('winnie','golden','shake','bark')
# Implement w... |
import sys
s = sys.argv
for i in range(len(s)):
if i != 0:
print(s[i], end=" ") |
# -*- coding: utf-8 -*-
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url('^admin/', admin.site.urls),
url('^cl/', include('chloroform.urls')),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
import json
from frappe.utils import now, cint
from functools import partial
from toolz import compose
@frappe.whitelist()
def deliver_result(lab_test, revert=0, delivery_time=None):
doc = frappe.get_doc("Lab Test", lab_test)
if doc... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
dataset = pd.read_csv('parkinsons.data')
#dataset_updrs = pd.read_csv('parkinsons_updrs.data')
#Get the features and labels
... |
# -*- 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
class SimpleracedayItem(scrapy.Item):
### to rd_race
racedate = scrapy.Field()
racecoursecode = scrapy.Field()
raceclass = scrapy.Field... |
import json
import feedparser
"""
Story format:
{
"index": (index),
"title": (title),
"description": (description),
"channels": [(channel)],
"published": (channel),
"guid": (guid),
"link": (link)
}
"""
def extract_stories(feed):
parsed = feedparser.parse(feed["feedUrl"])
index = 0
... |
import requests
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
sess = requests.Session()
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
}
url = "https://neue-pressemitteilungen.de/post_part1.xml"
r ... |
# Multiples of 3 and 5
# 15/11/20, Robert McLeod (rbbi)
def SumMultiples(lim):
sum=0
for val in range(lim):
if val % 3 == 0 or val % 5 == 0:
sum+=val
return sum
if __name__ == "__main__":
print(SumMultiples(1000)) |
# Generated by Django 2.2.2 on 2019-08-27 00:23
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('admin01', '0005_goods'),
]
operations = [
migrations.DeleteModel(
name='Connect',
),
]
|
# LEVEL 31
# http://www.pythonchallenge.com/pc/ring/grandpa.html
# where am I?
# a google goggles search tells me this is Koh Samui, Thailand
# http://www.pythonchallenge.com/pc/rock/grandpa.html
# u: kohsamui
# p: thailand
# That was too easy. You are still on 31...
# <img src="mandelbrot.gif" border="0">
# <window... |
# coding:utf-8
import random
# 应用实例:文本文件的操作
# 示例1:先生成1~122的随机数,再产生字符对应的ASCII码,然后将满足大写字母、小写字母、数字和一些特殊符号(例如:'\n', '\r', '*', '&', '^', '$')
# 条件的字符逐一写进test.txt中,当光标到达10001时停止写入。
with open('test.txt', 'w') as f:
while 1:
# 在python中的random.randint(a,b)用于生成一个copy指定范围内的整数。其中参数a是下限,参数b是上限,生成度的随机数n: a <= ... |
print("Hello World")
print("Me")
print(2+3)
print("hi")
|
#
# @lc app=leetcode.cn id=86 lang=python3
#
# [86] 分隔链表
#
# @lc code=start
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
... |
import random
suits=('Hearts','Diamonds','Spades','Clubs')
ranks=('Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack','Queen','King','Ace')
values={'Two':2,'Three':3,'Four':4,'Five':5,'Six':6,'Seven':7,'Eight':8,'Nine':9,'Ten':10,'Jack':10,'Queen':10,'King':10,'Ace':11}
playing=True
class Card:
... |
# Osciloscopio Tektronix TBS 1052B-EDU
#
# Adquiere los datos de los canales 1 y/o 2.
# Haciendo uso de un puerto USB de la PC y el protocolo denominado:
# VISA (Virtual Instrument Software Architecture).
#
#
# Laboratorio 3, 2do Cuatrimestre 2018, DF, FCEN, UBA.
# Cesar Moreno
import numpy as np
import visa
import ... |
import random
def getMünzVerteilung():
coinNbr = []
coinNbr.append(random.choice(range(4)))
coinNbr.append(random.choice(range(4, 9)))
coinNbr.append(random.choice(range(9, 16)))
return coinNbr
def getFremdmünzen(wurf):
if wurf < 17: region = 'Bornland'
elif wurf < 19: region = 'Vallusa... |
# Hangman Game by Jake Sanders
print("Hangman Game by JSanders | November 16, 2018\n")
# Open wordlist.txt so that we can access the words to choose from
word_list_file = open("wordlist.txt", "r")
# Create a local list of all of the words in wordlist.txt
word_list = word_list_file.readlines()
# Import r... |
__all__ = [
'SearchReferenceCommitForEvent',
]
from limpyd import fields
from limpyd_jobs import STATUSES
from limpyd_jobs.utils import compute_delayed_until
from gim.core.models import IssueEvent, Commit
from .base import DjangoModelJob
class EventJob(DjangoModelJob):
"""
Abstract job model for jobs b... |
import requests
import xmltodict
from basexml import buscaCliente, DisponibilidaDeServico, ConsultaCEP, getStatusCartaoPostagem, SolicitaEtiquetas,\
GeraDigitoVerificadorEtiquetas
# cliente = buscaCliente()
# x = cliente.contrato('9912208555', '0057018901', 'sigep', 'n5f9t8')
# # z = cliente.xmlData()
# y = client... |
import speech_recognition as sr
import pyttsx3
r = sr.Recognizer()
sample_rate = 48000
chunk_size = 2048
reply = {
"hi" : "Hi",
"hello" : "hello",
"hey" : "hey",
"your name" : "pybot",
"who" : "pybot"
} #anytopic
with sr.Microphone(sample_rate= sample_rate, chunk_size= chunk_size) as source:
... |
import time
def run_time(func):
def tmp(*args):
start = time.time()
func(*args)
end = time.time()
print(round(end - start,6))
return tmp
|
from . import models
from rest_framework import serializers
import json
import isodate
class PlayerNameSerializer(serializers.ModelSerializer):
class Meta:
model = models.PlayerName
fields = ['name']
class SessionSerializer(serializers.ModelSerializer):
class Meta:
model = models.Ses... |
t = int(input())
while t > 0:
w,h,n = map(int,input().split())
d = 1
while w % 2 == 0:
w = w//2
d = d*2
while h % 2 == 0:
h = h//2
d = d*2
if d >= n:
print("YES")
else:
print("NO")
t =t-1 |
from django.contrib import admin
# Register your models here.
# Register your models here.
from Rebbit.models import *
admin.site.register(Person)
admin.site.register(Sub_rebb)
admin.site.register(Post) |
s,v,u=map(int,input().split())
print(s*v//u)
|
"""
Dada una lista de enteros y strings, devolver dos listas una con los enteros y otra con las strings
"""
lista=["jajjaj", 3,4,5,"payaso"]
enteros=[]
strings=[]
for item in lista:
tipo=type(item)
if tipo==type("a"):
strings.append(item)
else:
enteros.append(item)
print("Los enteros son:... |
from typing import Tuple
import mysql.connector
def create_connection(host: str = 'localhost', port: str = '3306',
user: str = 'root', password: str = '1104',
database: str = 'pbz2') -> Tuple:
connection = mysql.connector.connect(
host=host,
port=port,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step04_rerun_preliminary_regression_for_presidential_countries
# @Date: 2020/3/20
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
"""
python -m ConstructRegressionFile.Stata.step04_rerun_preliminary_regression_for_presidential_countries
"""
import os
fro... |
first_max = int(input())
curent_num = int(input())
if curent_num == 0:
second_max = first_max
else:
second_max = curent_num
while curent_num != 0:
if first_max <= curent_num:
(first_max, second_max) = (curent_num, first_max)
elif second_max < curent_num:
second_max = curent_num
cure... |
import sys
sys.path.append('../../python')
import caffe
from caffe import surgery, score
import numpy as np
import os
import cPickle as pickle
save_format = os.getcwd() + '/out_{}'
# base net
base = 'base.prototxt'
weights = 'vgg16fc.caffemodel'
base_net = caffe.Net(base, weights, caffe.TEST)
# init
caffe.set_mode... |
from django.db import models
from partners.models import Partner
from datetime import date
from localflavor.us.models import USStateField
from django_countries.fields import CountryField
from filebrowser.fields import FileBrowseField
# Create your models here.
class Event(models.Model):
event_name = models.CharField... |
from ibtd.graph import Graph
|
from django.urls import path
from architect.monitor import views
app_name = 'monitor'
urlpatterns = [
path('v1', views.MonitorListView.as_view(),
name='monitor_list'),
path('v1/monitor-check',
views.MonitorCheckView.as_view(),
name='monitor_check'),
path('v1/<monitor_name>', vie... |
def getArray():
line = input()
n = int(line)
lines = []
for i in range(n):
line = input().strip().split(' ')
line = [float(line[0]), float(line[1])]
lines.append(line)
return lines
#Convert input lines into points in dual plane
def dual(lines):
points = []
for line in lines:
points.append([line[0], -... |
"""
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
"""
class Solution:
def removeVowels(self, S: str) -> str:
required_string=""
for letter in S:
if letter in "aeiou":... |
from django import forms
from eshop_products_attrebute.models import ProductAttribute
from eshop_products.models import Product
colors = [('قرمز', 'قرمز'), ('آبی', 'آبی'), ('زرد', 'زرذ'), ('صورتی', 'صورتی'), ('سیاه', 'سیاه')]
sizes = [("X", "X"), ("XL", "XL"), ("XXL", "XXL"), ("XXXL", "XXXL"), ("L", "L")]
class User... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from typing import Any, Iterable
from pants.backend.helm.resolve.remotes import HelmRemotes
from pants.backend.helm.target_types import HelmC... |
import copy
import itertools
import operator
from typing import Literal
Decks = tuple[list[int], list[int]]
def get_player_decks() -> Decks:
with open("input/input22.txt") as input_file:
player_1, player_2 = input_file.read().strip().split("\n\n")
return [int(n) for n in player_1.split('\n')[1:]], [in... |
from CallBackOperator import CallBackOperator
from SignalGenerationPackage.Sinus.SinusUIParameters import SinusUIParameters
from sys import exc_info
class SinusPointsNumberCallBackOperator(CallBackOperator):
def __init__(self, model):
super().__init__(model)
def ConnectCallBack(self, window):
... |
import numpy as np
import mglearn
X, y = mglearn.datasets.make_wave(n_samples=100)
bins = np.linspace(start=-3, stop=3, num=11)
print("bins: {}".format(bins))
which_bin = np.digitize(X, bins=bins)
print("\ndata:\n", X[:5])
print("\nwhich_bin:\n", which_bin[:5]) |
import seaborn as sns
from data_paths import paths
import pandas as pd
import glob as glob
import matplotlib.pyplot as plt
from numpy import median
# TODO Have a look at something similar to a facet plot (in R)
# https://stackoverflow.com/questions/25830588/r-lattice-like-plots-with-python-pandas-and-matplotlib
# Let... |
nota1 = float(input('Digite sua primeira nota:'))
nota2 = float(input('Digite sua segunda nota:'))
print('Sua média é {}'.format((nota1+nota2)/2))
|
from django.contrib import admin
from .models import Voting, Choice
class ChoiceInline(admin.TabularInline):
model = Choice
class VotingAdmin(admin.ModelAdmin):
inlines = [
ChoiceInline,
]
admin.site.register(Voting, VotingAdmin)
|
#!/usr/bin/python3
import os # for opening and closing files
from pymongo import MongoClient # using mongoDB
client = MongoClient() # this gets us a client to the mongodatabase
# make sure to start mongod somewhere, aim at
# some custom folder
import numpy as np
import mat... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
from io import BytesIO
from mock import Mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.