text stringlengths 8 6.05M |
|---|
IVERSION = (2, 13, 0)
VERSION = ".".join(str(i) for i in IVERSION)
LYREBIRD = "Lyrebird " + VERSION
|
from django import forms
CHOICES_UNITS = [
('day', 'Day(s)'),
('hour', 'Hour(s)'),
('minute', 'Minute(s)')]
CHOICES_TIMEZONES = [
('US/Eastern', 'Eastern Standard'),
('US/Central', 'Central'),
('US/Mountain', 'Mountain'),
('US/Standard', 'Pacific Standard')]
class McreateForm(forms.Form):
token = for... |
from flask import Flask, render_template
app = Flask(__name__, template_folder='python-eel-framework/web')
@app.route('/')
def index():
return render_template('main.html')
|
# -*- coding:utf8 -*-
import requests
import YiMa_SMS
from time import sleep
import logging
import time
import string
import random
Token = '00397229e4479e2d92629ff4049e09a49da7af66'
Base_Url = 'http://api.fxhyd.cn/UserInterface.aspx?' + 'token=' + Token
ym = YiMa_SMS.YiMaSMS()
t = int(time.time())
logger_name = "... |
#Tkinter Color GUI Button Click & Exit
from tkinter import * #imports all of the tkinter module
window = Tk() #call tkinter function to create a tkinter window // create GUI window // window is the named given to the GUI: name is needed for attributes
window.title("Hello Python") #Title of the Message Window /... |
import django
from django.conf.urls import include, url
from django.http import HttpResponse, Http404
from django.shortcuts import redirect
from django.test import TestCase
from django.test.utils import override_settings
from .utils import (
WorkingView, BrokenView, get_results_for, PickyTestResult, mocked_pattern... |
from libs.config import alias, color
from libs.myapp import send, base64_encode
@alias(True, func_alias="c", _type="FILE")
def run(*web_file_paths):
"""
cat
Read file(s) from target system.
eg: cat {web_file_path1} {web_file_path2} ..
"""
for each_file_path in web_file_paths:
... |
aspirtes@as-c02s5076h3qf.local.69039 |
from tkinter import *
li = Tk()
li.geometry("180x164")
li.title("Lightsout")
def b1_pressed():
if b1.cget('bg') == 'blue':
b1.config(bg='yellow')
else:
b1.config(bg='blue')
if b2.cget('bg') == 'blue':
b2.config(bg='yellow')
else:
b2.config(bg='blue')
if b5.cget('bg'... |
from morepath import redirect
from onegov.core.security import Public
from onegov.org.models import Organisation
from onegov.translator_directory import TranslatorDirectoryApp
from onegov.translator_directory.collections.translator import \
TranslatorCollection
from onegov.user import Auth
@TranslatorDirectoryApp... |
class BinaryTree:
def __init__(self, value=None):
self.data = value
self.left = None
self.right = None
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
self.__data = value
def add_leftchild(self, tree):
if (tree.d... |
number = int(input('Number: '))
print('DOUBLE: {}'.format(number**2))
print('TRIPLE: {}'.format(number**3))
print('SQUARE ROOT: {}'.format(number**(1/2))) |
# D. Mery, UC, September, 2019
# http://domingomery.ing.puc.cl
# Face images are in directory 'faces', there are two faces of M. Bachelet (mb_01 and mb_02),
# two faces of S. Piñera (sp_01 and sp_02) and one face of somebody else (xx_01).
# The features are stored in npy file, one row per image using the following or... |
#!/usr/bin/env python3
from markovest import Chain
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-s', '--sentences', type=int, default=1,
help='generate a paragraph with this many sentences')
parser.add_argument('-l', '--link',... |
"""
Token recognition occurs in this file.
"""
from rest_framework_simplejwt.tokens import RefreshToken
def get_token(user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token)
}
|
import requests, json
from tkinter import *
from module2 import open_auth_page, open_calc_page
def open_auth():
open_auth_page(window)
def open_calc():
open_calc_page(window)
window = Tk()
window.geometry("1000x700")
btn1 = Button(text="auth", command=open_auth)
btn1.pack()
btn2 = Button(text="calc", comm... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
import os
import time
from mechanical_markdown.command import Command
from termcolor import colored
default_timeout_seconds = 300
VALID_MATCH_MODES = ('exact', 'substring')
class Step:
def __init__(self, parameters, shell):
... |
# Generated by Django 3.0.1 on 2020-01-14 02:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('library_app', '0009_auto_20200114_0209'),
]
operations = [
migrations.RemoveField(
model_name='image',
name='user',
... |
'''
Created on 2011-11-27
@author: binliu
'''
import os
import sys
import subprocess
class pywincmd(object):
'''
封装操作系统命令的对象
'''
def __init__(self):
'''
Constructor
'''
self.command_str = ""
def run(self):
try:
self.p = subprocess.Pope... |
import os
from moksha.common.lib.converters import asbool
blocking_mode = asbool(os.environ.get('UMB_BLOCKING_MODE', 'False'))
heartbeat = int(os.environ.get('UMB_HEARTBEAT', 0))
config = dict(
environment="dev",
zmq_enabled=False,
# 'messaging-devops-broker01.dev1.ext.devlab.redhat.com:61612,messaging-de... |
from speech.response_queue import PriorityQueue
def test_queue_waits_for_missing_response():
first_request = 1
first_message = "this is the first message"
second_request = 2
second_message = "this is the second message"
queue = PriorityQueue()
queue.push(second_request, second_message)
# ... |
import numpy as np
import os
def validate_model_on_dataset(model, X, Y, scale_factor):
channel_count = Y[0].shape[2]
error_on_all = 0
error_on_best = 0
for channel in range(channel_count):
for y_ground, y_pred in zip(Y, model.predict(X)):
error = abs((np.sum(y_ground[:, :, channel... |
from Pages.ContentPages.BasePage import Page
from selenium.webdriver.common.by import By
class MediaAddingPage(Page):
def __init__(self, driver):
self.driver = driver
self.locators = {
'cta_button': {'by': By.XPATH, 'value': 'id("block-mainpagecontent")/ul[1]/li[1]/a[1]'},
... |
# Method0 --- use nothing, every request use a socket to send and receive and
# it is sync, it is simple
# Method1 --- use async mechnism like coroutine, every request has its own
# clinet socket (can be improved?)
# if use asyncio, may use new thread to run loop event
# Method2 --- ... |
from enum import Enum
import re
from time import sleep
import requests
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from generators import gen_user_agent
PORT = 8080
S... |
from flask import render_template, redirect, url_for, flash, request
from portfolio import app, mail
from portfolio.forms import ContactForm
from flask_mail import Message
@app.route('/', methods=['GET', 'POST'])
def index():
form = ContactForm()
if form.validate_on_submit():
if request.meth... |
# -*- coding: utf-8 -*-
"""
Programa para obtener algoritmo minimo para torre de Hanoi usando recursividad
CLUB ALGORITMIA UPIITA
Aaron Merlos
"""
def Hanoi(discos, origen, destino, auxiliar):
if (discos==1):
print("Mueve el disco 1 del poste {} al poste {}".format(origen, destino))
... |
from Pages.ContentPages.BasePage import Page
import time, pytest
class PageCT(Page):
def __init__(self, driver):
self.driver = driver
super().__init__(driver)
self.locators = {
}
self.page_test_data = {
'title': 'Page CT title',
}
self.node_parag... |
def extract(infile,outfile):
resultlist=random.sample(range(1,232030377),1000)
resultdict={}
for i in range(1000):
resultdict[resultlist[i]]=""
out=open(outfile,"w")
n=0
for seq_record in SeqIO.parse(infile, "fasta"):
n+=1
if n in resultdict.keys():
out.write... |
a, b, c = 12, 12.0, "12.0"
print(a, type(a), b, type(b), c, type(c)) |
def IsDigit(a):
x = int(a) #input("Enter your number")
if (x / 1 == x):
return ("Yes")
def IsPossitive(a):
x = a
if (int(x) >= 0):
return ("Yes")
def checkBin(a):
p = set(a)
s = {'0', '1'}
if s == p or p == {'0'} or p == {'1'}:
return ("Yes")
else:
r... |
#!/usr/bin/env python3
import sys
import json
import logging
import traceback
from tqdm import tqdm
import numpy as np
global logger
def evaluate(preds, solution, uids):
true_pos = 0
false_pos = 0
false_neg = 0
for pmid in preds:
true_pos += len([pred for pred in preds[pmid] if pred in sol... |
"""
Notification queries
"""
from typing import Generator, List, Optional, Union
import warnings
from typeguard import typechecked
from ...helpers import Compatible, format_result, fragment_builder
from .queries import gql_notifications, GQL_NOTIFICATIONS_COUNT
from ...types import Notification
from ...utils import... |
import logging
import os
import pandas as pd
from autumn.core import db
from autumn.core.plots.model import plots
from autumn.core.plots.plotter import FilePlotter
from autumn.core.db.process import select_outputs_from_candidates, target_to_series
from autumn.core.plots.utils import REF_DATE
from . import plots
log... |
"""
Includes various coverage statistics, namely the binomial segmentation algorithm
"""
from __future__ import division
from skbio.stats.composition import closure
from skbio.stats import subsample_counts
import numpy as np
import matplotlib.pyplot as plt
import sympy as sy
from scipy.optimize import newton
from sc... |
import re
inp = "1, 4.00, burger"
out = re.split("\s*,\s*", inp)
print(out)
print(out[1])
print(out[2])
d = {}
d[out[0]] = {}
print(d)
d[out[0]][out[2]] = out[1]
print(d) |
def len_syl_to_len_symb(corpus):
accumulator = 0
corp_len = 0
vowels = ["у", "е", "ы", "а", "о", "э", "я", "и", "ю", "ё"]
for text in corpus.texts:
for sentence in text:
for token in [token.value for token in sentence if token.group == "word"]:
vow = 0
... |
class Solution(object):
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
# 双指针法,左边从0开始,右边从sqrt(c)开始
if c < 0:
return False
import math
sqrt_c = int(math.sqrt(c))
if sqrt_c ** 2 == c:
return True
i, ... |
# -*- coding: utf-8 -*-
import cv2
import math
def compare_by_RGB(image_1,image_2):
"""
基于通道和的差
:param image_1:
:param image_2:
:return:
"""
G_1 = 0
B_1 = 0
R_1 = 0
G_2 = 0
B_2 = 0
R_2 = 0
#第一个图像的通道和
for x in image_1:
for y in x:
G_1 += y[0]
... |
##*******************************************************************************************
## Institulo Tecnológico de Costa Rica
## Análisis de algoritmos
## Código de curso : IC - 3002
## Profesor : Mauricio Rojas Fernández
##
## PROGRAMA : Maximos_Arreglo.py
##
## Estudiante : Melissa Molina Corrales.
##
## Ca... |
# flake8: noqa
__version__ = "0.5.0"
from .benchmark import benchmark
from .utils import set_download_dir, set_log_level, setup_seed
|
# Generated by Django 3.1.3 on 2021-01-20 09:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('programmes', '0005_programme_discontinued'),
('products', '0006_product_discontinued'),
('checkout', '0008_a... |
"""
Time/Space Complexity = O(N)
"""
class Solution:
def isValid(self, s: str) -> bool:
if len(s) == 1:
return False
stack = [s[0]]
for i in s[1:]:
if i == ')' and stack and stack[-1] == '(':
stack.pop()
elif i =... |
f = open("text.txt", "a")
f1 = open("text.txt")
f.write("\n")
f.write("Hello from 10.py")
f.close() |
def change_to_minute_and_hour(n) :
hour = n / 60
minute = n - hour * 60
return hour , minute
if __name__ == '__ main__' :
n = raw_input('Enter a number of minute :')
s = int(n)
res = change_to_minute_and_hour(s)
print res
|
#!/usr/bin/env python
# coding: utf-8
# In[242]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import skew
get_ipython().run_line_magic('matplotlib', 'inline')
sns.set() # Used for styling
#plt.style.use('ggplot') # Used for styling
# In[200]:
csv_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 12:57
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
#!/usr/bin/python
""" this is a brainf*** interpreter"""
print "input path: "
filename = raw_input()
print "approxomate tape size:"
tape_size = input()
file = open(filename, 'r')
tape = [0] * tape_size
#print tape
def exicute(line):
i = 0
while (i < len(line)):
ch = line[i]
if( ch == '+' ):
tape[inde... |
from freezegun import freeze_time
from onegov.election_day.layouts import ElectionCompoundLayout
from tests.onegov.election_day.common import create_election_compound
from tests.onegov.election_day.common import login
from tests.onegov.election_day.common import upload_election_compound
from tests.onegov.election_day.... |
import abc
from ulugugu import drawings, vec2
from ulugugu.events import send_event, event_used, ACK
from ulugugu.utils import cursor_over_drawing
class Widget(metaclass=abc.ABCMeta):
@abc.abstractmethod
def value(self):
pass
@abc.abstractmethod
def get_drawing(self):
pass
def handle_event(self, e... |
#!/usr/bin/env python
"""A basic fork in action"""
import os
def my_fork():
child_pid = os.fork()
if child_pid == 0:
print "Child Process: PID# %s" % os.getpid()
else:
print "Parent Process: PID# %s" % os.getpid()
if __name__ == "__main__":
my_fork()
|
import sys
import pymysql
import json
def handler(event, context):
statusCode = 200
message = []
rds_host = "rds-mysql-demo.csnnean90nqb.us-east-2.rds.amazonaws.com"
name = "USER_NAME"
password = "USER_PASSWORD"
db_name = "DB_NAME"
newEmpID = json.loads(event["body"]).get("newEmpID", "B... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-09-21 20:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0029_auto_20160921_2123'),
('messaging', '00... |
import sys
sys.path.append('../')
from lib import spaceman
def test_load_word():
word = spaceman.load_word()
assert type(word) == str
assert len(word) >= 1
assert word.isalpha()
def test_is_word_guessed():
assert spaceman.is_word_guessed('alpha', ['a', 'l', 'p', 'h'])
assert not spaceman.is_word_guessed('beta'... |
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying {from_file} to {to_file}!")
#! open the from file and assign to in_file
in_file = open(from_file)
#! read the contents of in_file that opened the from_file
in_data = in_file.read()
print(f"The input file is {len(in_data... |
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
class Contact(models.Model):
email = models.EmailField(max_length=100)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
cla... |
from odoo import api, fields, models
class PartnerTransaction(models.Model):
_name = 'partner.transaction'
_order = 'create_date DESC'
description = fields.Text('Description')
from_partner_id = fields.Many2one(
'res.partner',
'From Partner',
required=True
)
to_partner_... |
from typing import List
from fastapi import APIRouter, HTTPException, Path, BackgroundTasks
from app.api import crud
from app.models.pydantic import (
SummaryPayloadSchema,
SummaryResponseSchema,
SummaryUpdatePayloadSchema,
)
from app.models.tortoise import SummarySchema
from app.summarizer import generat... |
import collections
class Solution(object):
def maxSlidingWindow0(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums: return []
def findnewMax(begin):
end = begin+k if begin+k<=len(nums) else len(nums)
... |
from doubly_linked_list import DoublyLinkedList
class LRUCache:
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that provides fast acce... |
import warnings
import glob
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
warnings.filterwarnings("ignore")
from fingerprinter.reader import read_single
from fingerprinter.fingerprint import Fingerprinter
from fingerprinter.fingerprint_record import determine_match
from database.fingerpr... |
# Copyright 2017 AT&T Intellectual Property. All other 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... |
#!/usr/bin/env python
# encoding: utf-8
import threading , multiprocessing
def loop() :
x = 0
while True :
x *= 1
for i in range(multiprocessing.cpu_count()) :
t = threading.Thread(target=loop)
t.start()
# 可以看到活动监视器上python的CPU占用率达到了99.8% 虽然是4核的CPU,但是CPU占用率最多也只能达到100%
# 这是因为解释器在执行python时。有一个GI... |
dependencies = ['mxnet', 'torch', 'torchvision', 'pretrainedmodels', 'efficientnet_pytorch']
from efficientnet_pytorch import EfficientNet
from gluoncv.model_zoo import mask_rcnn_fpn_resnet101_v1d_coco as mask_rcnn_fpn_resnet101_v1d_coco_mxnet
from pretrainedmodels.models import pnasnet5large
from torchvision.models i... |
# -*- coding: iso-8859-1 -*-
import serial
# Abre porta Serial com seus devidos parâmetros
ser = serial.Serial(port='/dev/ttyACM0', baudrate=9600, timeout=1)
# Lê repetidamente e imprime qualquer mensagem que vem do arduino
while True:
msg = ser.readline().decode('ascii')
print(msg)
|
# -*- coding: utf-8 -*-
import numpy as np
from src.Loss.loss import Loss
class MSE(Loss):
def forward(self, y, yhat):
'''
y et yhat de taille (batch,d)
batch : nombre d'exemples
d : nombre de classes
'''
return np.linalg.norm(y - yhat, axis=1) ** 2
def backw... |
#! /usr/bin/env python
import sys
import os
import roslib
roslib.load_manifest('non_simple_action')
import rospy
import actionlib
import non_simple_action.msg
class CountActionClient (actionlib.action_client.ActionClient):
def __init__(self, name):
rospy.loginfo('Creating CountActionClient %s' % name)
... |
import sqlite3
import json
def dict_factory(cursor, row):
return {header: data for header, data in zip([head[0] for head in cursor.description], row)}
db_connection = sqlite3.connect('league.db')
db_connection.row_factory = dict_factory
db_cursor = db_connection.cursor()
if __name__ == '__main__':
db_cursor.exe... |
class thisapp():
def inputReceived(self, args):
self.move +=1
print "input received ", self.move
if self.checkInput(args):
self.checkForFlips(args[0], args[1])
if self.pieces[2] >= self.totalGamePlaces:
self.gameOver()
self.api.writeToLCD(0,0,self.turnPrint[self.turn]) # player, line, me... |
from ED6ScenarioHelper import *
def main():
# 米尔西街道
CreateScenaFile(
FileName = 'R0200 ._SN',
MapName = 'Rolent',
Location = 'R0200.x',
MapIndex = 22,
MapDefaultBGM = "ed60020",
Flags = 0,
... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
retu... |
# -*- coding:gbk -*-
import numpy as np
class syllable():
'''音节类,f0_sequence是每一帧的f0形成的序列'''
def __init__(self, begt='', endt='', f0_sequence=[], spk=""):
if begt and endt and f0_sequence:
self.begt = begt
self.endt = endt
self.f0_sequence = f0_sequence
se... |
import nltk
import pymorphy2
from nltk.collocations import *
from nltk.corpus import stopwords
def go():
with open('test') as file:
words = nltk.tokenize.word_tokenize(file.read())
stop = stopwords.words('russian')
words = [word.lower() for word in words if word.isalpha() and word.lower() ... |
import pandas as pd
import re
import os
import datetime
from datasource_manager import DATASOURCE_MAPPING
from flask import current_app
from config import CURRENT_SOURCE_FILES_PATH
from datetime import datetime
from models import Base
def start(connection, file_path_list, should_drop_first_col=False):
result = {... |
#'''pri.nt(id(a),i )
print("",5 and 3)
|
import matplotlib.pyplot as plt
import sys
import string
import numpy
from matplotlib.backends.backend_pdf import PdfPages
from itertools import chain
from matplotlib.patches import Polygon
#maxi = lambda v: max(enumerate(v), opeator.itemgetter(1))
SSTART = 2
SEQ = "SQKLVFFAEDVGSNKGAIIGLMVGGVVIATVIVITLVMLKKK"
NSEQ =... |
import numpy as np
from googlenet import googlenet
# from googlenet import googlenet
WIDTH = 90
HEIGHT = 90
LR = 1e-3
epoch = 10
model = googlenet(WIDTH,HEIGHT,LR)
# googlenet = googlenet(width,height,1,LR)
for i in range(epoch):
train_data = np.load('car_vs_forest.npy')
train = train_data
X = np.array([i[0] f... |
def caesar_encrypt(word, n):
c = ""
for i in word:
if not i.isalpha():
c += i
elif i.isupper():
c += chr((ord(i) + n - 65) % 26 + 65)
else:
c += chr((ord(i) + n - 97) % 26 + 97)
return c
def caesar_decrypt(word, n):
c = ""
for i in word:
... |
"""
Get thermal vac calibration files
Copy grism and imaging flats from /grp/hst/wfc3e/ground_testing/opusdata/ir4
with get_files.sh
cd RAW
grep g1 wfc3_log.prt |grep flat | grep 2008 | sed "s/csii//" |sed "s/_/ /" | sed "s/ /r_/" > list
grep "f[01]" wfc3_log.prt |grep ir | grep flat | grep 2008 | grep spars10 | gre... |
import numpy as np
from tools.likelihoods import *
import tools.emcee as mc
import sys
import tools.arrays as arr
import pylab as plt
plt.style.use("y1a1")
plt.switch_backend("pdf")
sys.path.append('/home/samuroff/cosmosis/')
from cosmosis.postprocessing import plots
from cosmosis.plotting import kde
files = sys.argv... |
import bge
from bge import logic
from bge import events
from bge import render
import time
pt = [time.time()]
x0 = 0.
y0 = 0.
z0 = 0.
x1 = 1.
y1 = 1.
z1 = 1.
print("[Only printed on module load")
def update():
t = time.time()
dt = t - pt[0]
pt[0] = t
controller = logic.getCurrentController()
... |
# coding: utf-8
# import libraries
import sys,os
import networkx as nx
import geopandas as gpd
import math
import numpy as np
import time
import pandas as pd
from multiprocessing import Pool
from rasterstats import zonal_stats
import shapely
from shapely.geometry import Point
import subprocess
sys.path.append(os.path.... |
from glob import glob
import numpy as np
import wfdb
import biosppy
import matplotlib.pyplot as plt
import cv2
def get_records():
""" Get paths for data in data/mit/ directory """
# Download if doesn't exist
# There are 3 files for each record
# *.atr is one of them
paths = glob('/path/to/MIT... |
#!/usr/bin/python
#\file lambda_local.py
#\brief test lambda with local variable.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Feb.21, 2017
import time,threading
locker= threading.RLock()
def func(i, obj):
while obj['count']>0:
with locker:
print 'thread',i,obj,id(obj)
o... |
from DecisionNode import DecisionNode
from Leaf import Leaf
from Question import Question
from Node import Node
class DecisionTree:
'''
This is just the tree classifier and some objects this is just to have the infos put in a good way.
'''
def __init__ (self, data, header, maxNodes):
self.maxNodes=maxNodes
... |
a,b=input().split()
c=0
d=-1
for i in range(int(b)):
if i%2==0:
a=a[c+1:]
if i%2==1:
a=a[:d]
print(a)
|
import re
import six
from raincoat.match import Match, NotMatching
from raincoat import source
from raincoat import github_utils
def get_merge_commit_sha1(ticket, session):
# This is an adaptation of
# https://github.com/django/code.djangoproject.com/blob/
# cad96e2d980fc0453b34dd3d17ce6cb895e1aa89/tra... |
'''Write a Python function to multiply all the numbers in a list.
Sample List : (8, 2, 3, -1, 7)
Expected Output : -336
'''
def multiply(myList) :
result = 1
for x in myList:
result = result * x
return result
list1 = [8, 2, 3, -1, 7]
print(multiply(list1))
|
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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
#
# ... |
import time
import traceback
class TimeoutWaitResultError(Exception):
pass
def retry_get_result(callback, args={}, delay=1, wait=10, max_count_retry=0, is_raise=True, result_true=None):
"""
:param max_count_retry:
:param args:
:param callback: is a function that can return object o... |
import re
import random
from typing import Optional
from .accent import Accent
HICCBURPS = (
"- burp... ",
"- hic- ",
"- hic! ",
"- buuuurp... ",
)
def duplicate_char(match: re.Match) -> Optional[str]:
if random.random() > 0.8:
return
severity = random.randint(1, 6)
return matc... |
from Player import Player
from Cards import Cards
from Enemy import Enemies
import random
playerOne= Player("hassan",150,0,0,True)
#enemies beta type
enemy_one = Enemies("Dawnsoul",15,8,False)
enemy_two = Enemies("slayer",25,5,False)
enemy_three = Enemies("Mage",10,10,False)
enemy_four = Enemies("The Icy Hag",30,2,F... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Dict
import pytest
from smorest_sfs.modules.auth import ROLES
from smorest_sfs.modules.email_templates.models import EmailTemplate
from tests._utils.helpers import param_helper
from tests._utils.injection import GeneralModify
class TestEmailTemplateMo... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
# author:罗徐 time:2019/8/1
# 顶帽和黑帽操作
# 图形形态学梯度
import cv2 as cv
import numpy as np
def top_hat_demo(image):
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY)
kernel=cv.getStructuringElement(cv.MORPH_RECT,(5,5))
dst=cv.morphologyEx(gray,cv.MORPH_TOPHAT,kernel)... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2018/4/8 下午5:24
# @Author : dapengchiji!!
# @FileName: 判断是否是回文数.py
def is_palindrome(n):
return str(n)==str(n)[::-1] #str()将整数转化成字符串
output=filter(is_palindrome, range(1,1001))#利用filter()函数筛选出1~1000中的回数
print(list(output)) |
# Generated by Django 3.1.3 on 2020-11-04 15:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('social_media_posts', '00... |
s=input() #input으로 숫자를 받는다.
count=0
for i in range(len(s)-1):# 마지막 까지
if s[i]!=s[i+1]: # 앞에 숫자가 다른경우 count를 더해준다.
count+=1
print((count+1)//2)# count를 1을 더해 2로 나누어 준다. |
#!/usr/bin/env python3
#This is a simple script which walks the trees in the TCCD/data folder
#to find and list all the folders containing files that need to be
#dealt with in various ways. These lists are saved into text files
#which can be read and used by the build process.
#Author Martin Holmes. November 2016.
i... |
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.dashboard, name='dashboard'),
path('board/', views.all_board_member, name='all-board-member'),
path('board/edit/<list_id>', views.edit_board_member, name='edit-board-member'),
path('board/add/', views.add... |
#Algorithm To implement Shortest Job First
n=int(input('Enter the Number of Process : '))
process=[int(x) for x in input('Enter the Process Number : ').split()]
burst_time=[int(x) for x in input('Enter the burst time of the Process : ').split()]
total_waiting_time=0
process_burst_time=zip(process,burst_time)
pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.