text stringlengths 8 6.05M |
|---|
from util import _get_hash, lcm
from math import gcd
class GodelHashSet:
def __init__(self, iter_vals = []):
if not isinstance(iter_vals, (str, list)):
raise ValueError("value must be string or list")
self.hash = 1
for val in iter_vals:
val_hash = _get_hash(... |
import os,sys
import numpy as np
import ROOT
from root_numpy import root2array, root2rec, tree2rec, array2root
import pandas as pd
from badchtable import get_badchtable
from pulsed_list import get_pulsed_channel_list
def import_data( ptree_filename ):
"""Imports pulse tree and outputs list of numpy arrays"""
a... |
from django import forms
from .models import Comment, Post
from django import forms
from django.contrib.auth.models import User
from .models import Profile
from django.forms.models import inlineformset_factory
class NewComment(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
cla... |
# Escalonamento de tarefas
import ordenador
from random import randint
# A função escalonar, que colocará somente as tarefas compatíveis.
def escalonar(lista):
# Passamos a lista como parâmetro para a função ordenador, que ficará responsável por organizar
# em ordem não-decrescente todas as tarefas, em função ... |
# Курс Python: основы и применение
# Задача 1, блок 2.2. Работа с кодом: модули и импорт
'''
В первой строке дано три числа, соответствующие некоторой дате date -- год, месяц и день.
Во второй строке дано одно число days -- число дней.
Вычислите и выведите год, месяц и день даты, которая наступит, когда с момента ис... |
from operator import and_ as AND
from operator import or_ as OR
from dataclasses import dataclass
@dataclass
class Rule():
conditions: list
actions: list
@dataclass
class RuleCondition():
pass
@dataclass
class RuleAction():
pass
@dataclass
class MatchCondition(RuleCondition):
fieldname: str... |
# input=input("Enter answer")
#
# def if_yes_fun(input):
#
# if input.lower() == 'yes':
# print("correct")
#
# else:
# print("Wrong")
#
# if_yes_fun(input)
# firstNo=int(input("Enter a number"))
# secNo=int(input("Enter a second number"))
# thirdNo=int(input("Enter a third number"))
#
# def... |
from urllib.request import urlretrieve
src = "https://movie-phinf.pstatic.net/20190116_187/15476220698637Uv7t_JPEG/movie_image.jpg?type=m203_290_2"
urlretrieve(src,"poster.png")
|
import unittest
from min_max_diff import *
class TestMinMaxDiff(unittest.TestCase):
def test_min_max_diff(self):
numbers = [1, 2, 3, 4, 5]
self.assertEqual(min_max_diff(numbers), 4)
def test_min_max_diff_empty_list(self):
numbers = []
self.assertEqual(min_max_diff(numbers), Non... |
# -*- coding: utf-8 -*-
import xmlrpclib
import base64
from pprint import pprint as pp
url = "http://shoprrt.com/xmlrpc/object"
db = "rimreadytires"
uid = 1
password = "Antonio230"
sock = xmlrpclib.ServerProxy(url)
model = "product.template"
real_list = []
count = 0
products_ids = sock.execute(db, uid, password,... |
import unittest
from katas.beta.small_enough_beginner import small_enough
class SmallEnoughTestCase(unittest.TestCase):
def test_true_1(self):
self.assertTrue(small_enough([66, 101], 200))
def test_true_2(self):
self.assertTrue(small_enough([101, 45, 75, 105, 99, 107], 107))
def test_tr... |
from .vol_data import VolSurfaceData, VolSmileData
import numpy as np
from datetime import timedelta
def augment_vol_data(data, n_rows, spot_perturb, time_perturb, vol_perturb):
exis_len = len(data)
augmented_data = []
for i in range(0, n_rows, exis_len):
for vol_data in data:
perturbed... |
#!/usr/bin/env python
# gscholar - Get bibtex entries from Goolge Scholar
# Copyright (C) 2011 Bastian Venthur <venthur at debian org>
#
# 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 ... |
import sys
import time
import socket
import struct
from types import LongType, FloatType
import libweb100
import Web100 as PyWeb100
from pathlib import *
################################################################
# report generation
# stdout and/or a .txt file
stdouttype="T"
tfile=None
def runlog(lvl, msg):
... |
class Vector2:
def __init__(self, _x=0, _y=0):
self.x = _x
self.y = _y
@staticmethod
def zero():
v = Vector2(0,0)
return v
@staticmethod
def one():
v = Vector2(1,1)
return v
def __str__(self):
return '({0},{1})'.format(self.x,sel... |
p="I am praveen"
if(p=="I am praveen"):
print "it works"
else:
print 'not working'
for let in p:
print "Current letter ",let
print let.tell()
st=p[5:12]
print st
|
import random
board=[[1,2,3],[4,5,6],[7,8,9]]
RandomNumberList=random.sample(range(1, 10), 9)
FreeSquareList=[]
tempcomparion=0
global StatusGame
PlayAgain=""
def DisplayBoard(board):
#
# the function accepts one parameter containing the board's current status
# and prints it out to the console
#
... |
y=int(input())
while y>0 :
print("Hello")
y=y-1
|
#python 3.8
#WebQA Json解析程序
import json
import pymysql
conn = pymysql.connect(
host='localhost', # mysql服务器地址
port=3306, # 端口号
user='root', # 用户名
passwd='root', # 密码
db='faq', # 数据库名称
charset='utf8', # 连接编码,根据需要填写
)
cur = conn.cursor() # 创建并返回游标
questionList = open(r"E:\gongzhonghao\robo... |
'''
Canetti-Halevi-Katz Public Key Encryption, IBE-to-PKE transform (generic composition of IBE+signature -> PKE)
| From: "R. Canneti, S. Halevi, J. Katz: Chosen-Ciphertext Security from Identity-Based Encryption"
| Published in: CRYPTO 2004
| Available from: http://eprint.iacr.org/2003/182
| Notes:
* type: ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
import os
import re
from dataclasses import dataclass
from pathlib import PurePath
from typing import Iterable
from pants.backend.python... |
# Módulo que contém todas as funções necessárias para criação e avaliação do K-Means
import numpy as np
import matplotlib.pyplot as plt
# Método K-Means
class KMeans():
def __init__(self, n_clusters=2, max_iter=50):
self.n_clusters = n_clusters
self.max_iter = max_iter
def euclidean_di... |
from django.urls import path
from . import views
app_name = "poll"
urlpatterns = [
path('',views.PollListView.as_view(),name="poll_list"),
path('<int:pk>/',views.PollDetailView.as_view(),name="poll_detail"),
path('vote/<int:question_id>/',views.vote,name="vote"),
path('result/<int:pk>/',views.PollResu... |
def search(nums, target):
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) // 2
if nums[mid] == target:
return nums[mid]
if nums[mid] > target:
end = mid - 1
else:
start = mid + 1
if abs(nums[start] - target) < abs(... |
#1548 Fila do recreio´
T = int(input())
while (T > 0):
alunos = int(input())
notas = input().split()
for id, i in enumerate(notas):
notas[id] = int(notas[id])
tot = 0
notas_ord = sorted(notas) # ordenar as notas
notas_ord.reverse()
for id, i in enumerate(notas):
if (notas[id... |
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, flash, request, redirect, url_for, logging, session
from wtforms import Form, StringField, TextAreaField, PasswordField, IntegerField, validators
from passlib.hash import sha256_crypt
from functools import wraps
# Config Application
app ... |
from __future__ import division, print_function
import random
import unittest
import numpy
# noinspection PyUnresolvedReferences
from six.moves import range
from smqtk.utils import bit_utils
class TestBitUtils (unittest.TestCase):
def test_int_to_bit_vector_large_0(self):
# Need at least one bit to rep... |
"""Unit test for GravitySpy
"""
__author__ = 'Scott Coughlin <scott.coughlin@ligo.org>'
import os
import unittest2
class GravitySpyTests(unittest2.TestCase):
"""`TestCase` for the GravitySpy
"""
def test_api(self):
self.assertEqual(1,1)
|
from clang.cindex import TranslationUnit, Cursor, CursorKind
from ipc_parser import parse_file
# --------------------------------------------------------------------------- #
class message:
def __init__(self, facade, method):
self.facade = facade
self.method = method
def args(method):
ret... |
from random import randint
import pyperclip
import sys
path = 'C:\\Users\Martin\Documents\\bombpartycheat\\top10000'
wordlistone = open(path)
stringone = wordlistone.read()
def complexity(word):
points = 0
letters = ['w','k','j','q','b','g']
for letter in letters:
if letter in word:
poin... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\QC\Desktop\IonTrap-WIPM-master\IonTrap-WIPM-master\GUI_Material\QC2_0TEST.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidg... |
from urllib.parse import urlencode
url = "http://in-stjoseph-assessor.governmax.com/propertymax/search_property.asp?l_nm=owner&user=guest_in-stjoseph-assessor&pass=manatron&sid={}"
query = {
'l_nm': 'owner',
'user': 'guest_in-stjoseph-assessor',
'pass': 'manatron',
'sid': 'F83D36C5F0094B86B4BE9307649D... |
def maximum_number(*args):
max_num = args[0]
for i in args:
if i > max_num:
max_num = i
return max_num
print(maximum_number(-10,-4,-7,-10,-30)) |
from src.Model import Model
class DefaultInput(object):
def __init__(self, model):
if not isinstance(model, Model):
raise TypeError("Passed wrong object to DefaultInput")
self.model = model
def up(self):
self.model.stepUp()
def down(self):
self.model.stepDown(... |
import matplotlib.pyplot as plt
import numpy as np
import uncertainties.unumpy as unp
import scipy.constants as con
from scipy.optimize import curve_fit
from scipy import stats
from uncertainties import ufloat
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLo... |
from django.conf.urls import patterns, url
from bank import views
from helper_functions import PionerAutocomplete
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^logout/$', 'django.contrib.auth.views.logout_then_login', name='logout'),
... |
from django.shortcuts import render, redirect
def index(request):
if 'nr_submits' not in request.session:
request.session['nr_submits'] = 0
return render( request, "survey_form/index.html" )
def submit(request):
if request.method == "POST":
print request.POST
request.session['nr_su... |
import sys
sys.path.append('../../python')
import caffe
from caffe import surgery, score
import numpy as np
import os
weights = sys.argv[1]
caffe.set_phase_train()
caffe.set_mode_gpu()
caffe.set_device(1)
solver = caffe.SGDSolver('solver.prototxt')
solver.net.copy_from(weights)
score.boundary_eval(solver, ('bsds'... |
def max_product(lst, n_largest_elements):
output = 1
lst.sort()
lst.reverse()
nums = []
for i in range(0, n_largest_elements):
nums.append(lst[i])
for i in nums:
output *= i
return output
print(max_product([4, 3, 5], 2))
|
import time
# DEVELOPER: https://github.com/undefinedvalue0103/nullcore-1.0/
vk = None
utils = None
config = None
logging = None
root = None
def handle(message):
act = message['action']
return ''
|
class GameStats():
"""Track statistics for Cha vs. Krtek"""
def __init__(self, ai_settings):
"""Initialize statistics."""
self.ai_settings = ai_settings
self.reset_stats()
# Start Cha vs. Krtek in an inactive state.
self.game_active = False
def reset_stats(self):
... |
import os
NEBULOUSLABS_GIT_BASEURL = 'https://gitlab.com/NebulousLabs/'
SIACOINCLASSIC_GIT_BASEURL = 'git@github.com:SiacoinClassic/'
REPOSITORYS_DIR = os.path.join(os.getcwd(), 'repositorys')
DEPENDENCIES = {
'demotemutex',
'fastrand',
'merkletree',
'bolt',
'entropy-mnemonics',
'errors',
... |
import numpy as np
value = np.random.randint(0,100, 10)
print(value)
condition = value %2 == 0
print(condition)
print(value[condition]) |
from flask import Flask, render_template, url_for, request, redirect
from flask_table import Table, Col
from flask_mysqldb import MySQL
import mysql.connector
import functools
import datetime
# import yaml
app = Flask(__name__)
#Configuring DB
# db = yaml.load(open('db.yaml'), Loader=yaml.FullLoader )
app.config['MY... |
import os
from player import Player
from actions import Actions
from data import Data
class Game:
def __init__(self, players_turn, feature_length, label_length):
self.players_turn = players_turn
self.game_over = False
self.user = Player('user')
self.opponent = Player('opponent')
... |
from config.VarConfig import iePath, chromePath
from util.DirAndTime import DirAndTime
from util.ObjectMap import get_element
from util.WaitUntil import WaitUnit
from selenium import webdriver
driver = None
waitUtil = None
# 打开浏览器
def open_browser(browser):
global driver, waitUtil
try:
if browser.l... |
"""
Time Complexity: O(logN)
"""
"""
Recursive Binary Search
"""
def recursiveBinarySearch(inputArray, low, high, toSearch):
if high >= low:
mid = (high + low) // 2
if inputArray[mid] == toSearch:
return mid
elif arr[mid] > toSearch:
return recursiveBinarySearch(inputArray, low, mid - 1... |
from pdfminer.pdfdocument import PDFDocument, PDFTextExtractionNotAllowed
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams, LTTextLineHorizontal, LTFig... |
from __future__ import absolute_import
import apache_beam as beam
import os, datetime
from apache_beam import pvalue
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToTe... |
age = 17
if age==0:
print("zero")
elif age==1:
print("one")
else:
print("old") |
import numpy as np
import cv2
# from keras.preprocessing.image import ImageDataGenerator
from keras.utils.data_utils import Sequence
from imgaug import augmenters as iaa
import random
import utils
import glob
class OneShotTrainingSequence(Sequence):
def __init__(self, image_dir, mask_dir, da=False, batch_size=1, i... |
#! /usr/local/bin/python
import json
import netCDF4 as nc
import os
files_dir = '/Users/michaesm/Downloads/test/'
def read_json(open_file, var_name):
qp = nc.chartostring((open_file.variables[var_name][:]))
try:
parsed_json = json.loads(qp[0])
return parsed_json
except:
parsed_js... |
from queries import DELETE_USER, READ_USER, UPDATE_USER
from queries import INSERT_INTO_DATABASE
from flask import Flask,render_template,request,redirect
from queries import *
from decouple import config
from flask_mysqldb import MySQL
from dotenv import load_dotenv
load_dotenv()
import MySQLdb
import os
... |
import json
import os
import sys
import pandas as pd
from PyQt5.QtCore import (QAbstractTableModel, QRegExp, QSortFilterProxyModel,
Qt)
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (QApplication, QComboBox, QFrame, QGroupBox,
QHBoxLayout, QLabel, QL... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
from collections import defaultdict
from dataclasses import dataclass
from pants.backend.python.subsystems.setup import PythonSetup
from pan... |
from django.conf.urls import include
from django.conf.urls import url
from blog.views import *
from rest_framework.urlpatterns import format_suffix_patterns
from blog.myviews import *
from rest_framework.routers import DefaultRouter
from django.conf import settings
from blog.upload import upload_image
urlpatterns = [
... |
import requests
import json
import csv
from time import sleep
url = "https://www.mcdonalds.com.cn/ajaxs/search_by_point"
headers = {
'Connection': 'Keep-Alive',
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like ... |
# Generated by Django 2.1.4 on 2018-12-13 01:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('UserProfile', '0002_auto_20181212_1731'),
]
operations = [
migrations.AlterModelTable(
name='profile',
table='UserProfile',
... |
class ResourceNotFound(Exception):
description: str = "Occurs when a customer with a specific Id does not exist"
def __str__(self):
return "The requested resource not found" |
import torch
import logging
import os
import io
import array
import six
from tqdm import tqdm
from torchtext.vocab import Vectors
logger = logging.getLogger("data")
class Crosslingual(Vectors):
def __init__(self, name, language='en', **kwargs):
self.name = name
self.language = language
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 24 15:58:02 2017
@author: dgratz
"""
import numpy as np
from glob import glob
from readFile import readFile
import re
from ParameterSensitivity import ParamSensetivity
import matplotlib.pyplot as plt
from calcSync import calcTimeSync, calcSyncVarLen... |
from itertools import permutations
skup = set()
for it in permutations('123456789', 9):
for i in xrange(1, 4):
for j in xrange(3,5):
a, b, c = int(''.join(it[0:i])), int(''.join(it[i:i+j])), int(''.join(it[i+j:]))
if a*b == c: skup.add(a*b)
print sum(skup)
|
from .BaseEditor import BaseEditor
from .ScrubSpinBox import IntScrubSpinBox, MinVal, MaxVal
from PyQt5 import QtCore
class IntegerEditor(BaseEditor):
def __init__(self, parent, item, model):
BaseEditor.__init__(self, parent, item, model)
self.spinBox = IntScrubSpinBox(self)
self.spinBox... |
import grpc
from grpcService import data_pb2, data_pb2_grpc
def run():
with grpc.insecure_channel('127.0.0.1:5000') as channel:
stub = data_pb2_grpc.LearnBoarStub(channel)
response_agent = stub.CreateAgent(data_pb2.AgentData(
env_shape = int(4),
num_actions = int(5)
... |
# Generated by Django 2.1.3 on 2019-02-25 19:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0010_variation_barcode'),
]
operations = [
migrations.AlterField(
model_name='variation',
name='image',
... |
#coding:utf8
import pylab as P
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def carrega_dados(file_name):
with open(file_name) as f:
nomes = f.readline().strip().split(',')
dados = np.genfromtxt(file_name, delimiter=',', skip_header=1)
print nomes, dados.size
if __name_... |
from flask import Flask, render_template,request,abort
app = Flask(__name__)
@app.route('/',methods=["GET"])
def inicio():
datos=[
{"valor":1,"texto":"Windows"},
{"valor":2,"texto":"Linux"},
{"valor":3,"texto":"MacOs"}
]
seleccionado="Linux"
return render_template("inicio.html",datos=da... |
from math import ceil
print('Loja de tintas\n')
area_a_ser_pintada = float(input('Informe o tamanho em metros quadrados da área a ser pintada: '))
um_litro_pinta = 3
quantidade_de_uma_lata = 18
preco_de_cada_lata = 80.00
litros_necessarios = area_a_ser_pintada / um_litro_pinta
latas_necessarias = int(ceil(litros_n... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 4 15:40:18 2017
@author: zx621293
"""
########################using t-SNE##################################
def myTSNE(X,label_refine,label,perplexity):
n = X.shape[0]
if len(label_refine) != n:
label_refine = [0]*n
label = ['no gro... |
# -*- coding: utf-8 -*-
"""
ytelapi
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class AudioDirectionEnum(object):
"""Implementation of the 'AudioDirection' enum.
The direction the audio effect should be placed on. If IN, the effects
will occu... |
import sys
import numpy as np
a=[]
with open(sys.argv[1], 'r') as f:
for line in f:
cols = line.split()
if len(cols) == 4 or len(cols) == 3:
a.append(float(cols[2]))
a=np.asarray(a)
a*=1e-3 # convert to milliseconds
print(f'avg={np.average(a):.4f} max={np.max(a):.4f} min={np.min(a):.4f}... |
from resource import getrusage,RUSAGE_SELF
def array_test():
test = {}
test['1'] = ['A']
#test['1'] = 'A'
test['2'] = 'B'
test['1'].append('C')
print (test)
print (getrusage(RUSAGE_SELF).ru_maxrss)
if __name__ == "__main__":
import sys
array_test()
|
from router_solver import *
import compilador.objects.symbol
from compilador.objects.symbol import *
# CLASE MEMORY SEGMENT
# Objeto que objetos en un segmento de memoria unico
class MemorySegment(object):
####################### INITS #######################
def __init__(self, name, size, initial_position)... |
import xgboost as xgb
import sys
import os
import numpy as np
svmFile = sys.argv[1]
pairGenesFile = sys.argv[2]
modelNam = sys.argv[3]
treesCount = int(sys.argv[4])
pairsOfGenesArr = []
f = open(pairGenesFile,"r")
for line in f:
line = line.strip('\n')
pairsOfGenesArr.append(line)
dval = xgb.DMatrix(svmF... |
import json
import logging
from threading import Thread
def flatten(api_dictionary, separator='.'):
"""
Flatten nested API dictionary. If merge keys of each nested level with given
separator - default is '.'
:param api_dictionary: nested api dictionary object with handlers
:param separator: strin... |
"""
"""
import logging
import pickle
import numpy as np
import quantities as pq
try:
import h5py
except ImportError as err:
HAVE_H5PY = False
else:
HAVE_H5PY = True
from neo.core import (objectlist, Block, Segment, AnalogSignal, SpikeTrain,
Epoch, Event, IrregularlySampledSignal,... |
import requests
from flask import *
from flask_bcrypt import Bcrypt
from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user, login_required
from flask_bootstrap import Bootstrap
from forms import RegistrationForm, LoginForm, ContactForm, HelpForm
import psycopg2
from passwords2 import psq... |
#!/usr/bin/env python3
import sys
import re
#the allele frequency used in the map file is from the ExAC
#different population are all considered here
#currently only limited to one population, if the cases is mixed,
#I will use the overall freqency in the population
def get_af(info, population_in):
if population_in... |
import os
import json
import matplotlib.pyplot as plt
with open('policy.json', 'r') as f:
file = json.load(f)
x1 = file['pg']['x']
y1 = file['pg']['y']
x2 = file['pg_baseline']['x']
y2 = file['pg_baseline']['y']
title = 'policy gradient'
plt.plot(x1, y1, linewidth=3, label='w/o baseline')
plt.plot(x2, y2, linewi... |
"""
Finding patters in Data: multi-domain graphs
"""
import argparse
from forensics.patterns import run_analysis
from forensics import seed
# step 1: seed random data
# step 2: seed POI's data
# step 3: cypher queries to seed
# step 4: cypher queries to run forensics analysis
if __name__ == '__main__':
pars... |
#!/usr/bin/env python3
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import argparse
import logging
from dataclasses import dataclass
import github
from packaging.version import Version
from pants_... |
import torch
import torch.nn
import os
import numpy as np
import matplotlib.pyplot as plt
import glob
from sklearn.svm import SVC
from sklearn.metrics import plot_confusion_matrix
from sklearn import preprocessing
from torchvision.transforms import ToTensor
from PIL import Image
from joblib import dump
# import pretra... |
# -*- coding: utf-8 -*-
"""Tests for Windows Restore Point rp.log files."""
import unittest
from dtformats import rp_log
from tests import test_lib
class RestorePointLogFileTest(test_lib.BaseTestCase):
"""Windows Restore Point rp.log file tests."""
# pylint: disable=protected-access
def testDebugPrintFileF... |
"""
Heber Cooke 10/24/2019
Chapter 5 Exercise 6
This program takes a number and converts it to base 10
"""
conversion = {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, \
"8":8, "9":9, "A":10, "B":11, "C":12, "D":13, "E":14, "F":15}
def decimalToRep(num,base):
s = 0
ex = len(num) -1
for ... |
from os import error
from flask import Flask, flash
from flask import render_template, redirect, url_for, request, abort, jsonify
from models.Modelos import *
from flask_sqlalchemy import SQLAlchemy
from pathlib import Path
from werkzeug.utils import secure_filename
import os.path
import sys
import shutil
import smtpli... |
import sys
class Tree(object):
def __init__(self,a,b,c):
self.a = None
self.b = None
self.c = None
self.level = 0
self.parent = None
self.data = [a,b,c]
def get_stream():
a,b,c = sys.stdin.readline().split()
return[int(a),int(b),int(c)]
def generate_node(ro... |
class configs:
HEADER = '\033[95m'
MD5HASH = 'd44cb8546e7e57c21caa064ee5007c8a'
PASSWD = 'your_pass_here'
PATH = 'your_path_here' |
import subprocess
def validate_connect(address):
p = subprocess.Popen(['iwgetid', '-a'], stdout=subprocess.PIPE)
output, err = p.communicate()
rc = p.returncode
mac_address = str(output).split()[3]
mac_address = mac_address[0:17]
if address == mac_address:
print(mac_address)
... |
# quotient 몫
# remainder 나머지
import sys
N = int(sys.stdin.readline())
Q5 = N // 5
R5 = N % 5
if R5 % 3 == 0: # 5로 나눈 나머지가 3의 배수로 나누어떨어지면 5a + 3b로 a+b를 출력
print(Q5 + (R5 // 3))
else: # 나누어 떨어지지 않는다면, 5로 나눈 나머지를 3으로 나누면 0, 1, 2 중 하나만 나올 수 있음
if R5 % 3 == 1 and Q5 >= 1: # 5로 나눈 나머지를 3으로 나눈 나머지가 1이면
... |
import random
from math import log, sqrt, pow
from statistics import stdev
from python_charts import draw_histogram
def get_random():
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
while sqrt(get_exp((x, y))) >= 1 or x + y == 0.0:
x = random.uniform(-1, 1)
y = random.uniform(-1, 1)
... |
"""
The flask application package.
"""
from flask import Flask, render_template
app = Flask(__name__)
app.secret_key = 'mytravelapp'
# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app
# Configurations
app.config.from_object('settings')
# Define the database object ... |
from flask import Blueprint, jsonify, render_template, Flask, url_for
import procesos.bancolombia_castigada as bancolombia_castigada
import os
# my_resourses = os.path.join('static','images')
sercice_uis_api = Blueprint('sercice_uis_api', __name__, static_folder='static',template_folder='templates')
myApp = Flask(_... |
from __future__ import with_statement
import os
from fabric.api import *
from fabric.contrib.console import confirm
# PROJECT_PATH = '/var/www/freesprache'
env.passwords = {
'Yoomsoft@yoomsoft.oicp.net:22': 'pinux@911', # Yoomsoft_Office
}
env.hosts = [
'Yoomsoft@yoomsoft.oicp.net', # Yoomsoft_Offic... |
# -*- coding: utf-8 -*-
from collections import deque
class Solution:
def validateStackSequences(self, pushed, popped):
i, j, stack = 0, 0, deque()
while i < len(pushed) or j < len(popped):
if j < len(popped) and stack and stack[-1] == popped[j]:
stack.pop()
... |
from django.contrib import admin
from django.urls import path,include
from .views import *
from django.views.generic.base import RedirectView
urlpatterns = [
#including path of questionbank
path('',include('questionbank.urls')),
path('',indexPage.as_view(),name="indexPage"),
#redirecting to admin usi... |
from django.db import models
# Create your models here.
class Med(models.Model):
Medicine_batch_no = models.IntegerField()
Medicine_name = models.CharField(null=True,max_length=50)
Medicine_Company = models.CharField(null=True,max_length=50)
Medical_quantity = models.IntegerField()
med_purchase_dat... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
def filter_list(list,minLengthSize):
"""Una funcion para filtrar las palabras de una lista que no tengan mas de 'n' caracteres"""
result=[]
for att in list[:]:
if len(att)>minLengthSize:
result.append(att)
return result
def parse_listOfObjects_to_listOfStrings(li... |
import dump
import gevent
from itm import ITM, UCWrapper
from collections import defaultdict
from numpy.polynomial.polynomial import Polynomial
import logging
log = logging.getLogger(__name__)
class Async_FWrapper(UCWrapper):
def __init__(self, channels, pump, poly, importargs):
self.curr_round = 1
... |
# PART ONE
number_steps = 0
def step_with_offset(i):
step = step_list[i]
next_i = i + step
step_list[i] = step + 1
return next_i
with open('input.txt') as input_file:
step_list = map(int, input_file.read().split())
i = 0
while i < len(step_list):
i = step_with_offset(i)
number_steps += 1
print('Part One:... |
import sys
import click
from os.path import dirname, abspath, isdir
from utils.functions import (
create_readme,
create_output_directory,
get_files,
get_optional_props,
get_props_dict,
get_props_list,
get_props_match,
get_required_props,
read_tsx_file
)
def create_tsx_file_readme... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.