content stringlengths 5 1.05M |
|---|
import unittest
from credentials import Credentials
class TestCredentials(unittest.TestCase):
'''
class that defines TestCredentials' test cases
Args:
unittest.TestCase: aids in creating new testcases.
'''
def setUp(self):
'''
runs before every test case
''... |
## @file
## @brief @ref avr
## @copyright Dmitry Ponyatov <dponyatov@gmail.com> CC-NC-ND
## github: https://github.com/ponyatov/metapy430
from frame import *
## @defgroup avr AVR
## @brief @ref avr
## @ingroup mcu
## @{
class AVR(ARCH): pass
class ATmega(MCU): pass
## @}
|
# Copyright 2017 by Kurt Rathjen. All Rights Reserved.
#
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
# This l... |
import tensorflow as tf
import numpy as np
from ml_utils.keras import get_states, set_states, apply_regularization
from ml_utils.model_builders import dense_stack
from .pget import create_traces, update_traces, step_weights_opt
from .pget import explore_continuous, explore_discrete, explore_multibinary
#TODO: saving... |
import json
import maya.cmds as mc
def pyToAttr(objAttr, data):
"""
Write (pickle) Python data to the given Maya obj.attr. This data can
later be read back (unpickled) via attrToPy().
Arguments:
objAttr : string : a valid object.attribute name in the scene. If the
object exists, but the ... |
from instapy_cli import client
def upload_stories(image):
username = 'clippingcatolico'
password = 'neto1234'
image = image
with client(username, password) as cli:
cli.upload(image, story=True) |
from pandas import Series
from pytest import approx
from signature_scoring.models import Profile
from helpers.mathtools import split_to_pos_and_neg
from helpers.cache import hash_series
from signature_scoring.models import Signature
from signature_scoring.scoring_functions.generic_scorers import score_spearman
import ... |
from unittest import TestCase
import numpy as np
import pandas as pd
from pyfibre.model.objects.fibre import (
Fibre
)
from pyfibre.model.tools.metrics import FIBRE_METRICS
from pyfibre.tests.probe_classes.objects import ProbeFibre
class TestFibre(TestCase):
def setUp(self):
self.fibre = ProbeFibr... |
"""
Schema validation tools
"""
import jsonschema
from . import versions
def validate(data, schema_type, version="dev"):
"""
Validates a given input for a schema input and output type.
"""
schema = versions.get_schema(schema_type, version)
jsonschema.validate(data, schema)
|
import os
import json
import jsonlines
import h5py
import networkx as nx
import math
import numpy as np
class ImageFeaturesDB(object):
def __init__(self, img_ft_file, image_feat_size):
self.image_feat_size = image_feat_size
self.img_ft_file = img_ft_file
self._feature_store = {}
def ge... |
"""Test classifier_cls_by_name."""
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
from skutil.estimators import classifier_cls_by_name
def test_base():
assert classifier_cls_by_name('LogisticRegression') == LogisticRegression
a... |
import allure
from page_objects.LoginPage import LoginPage
@allure.parent_suite("Проверка тестового магазина opencart")
@allure.suite("Тесты страницы авторизации")
@allure.epic("Проверка магазина на opencart")
@allure.feature("Проверка наличия элементов на странице логина")
@allure.title("Поиск элементов на странице... |
from twilio.twiml.voice_response import Redirect, VoiceResponse
response = VoiceResponse()
response.redirect('http://www.foo.com/nextInstructions')
print(response)
|
# -*- coding: utf-8 -*-
import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
INDEX_DEATH_ROW_INFO_URL = 1
INDEX_LAST_STATEMENT_URL = 2
base_url = "https://www.tdcj.texas.gov/death_row/"
death_row_infos = []
headers = {
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,im... |
# encoding: utf-8
"""
open booking connect
Copyright (c) 2021, binary butterfly GmbH
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
from typing import Union
from .redis import Redis
class RedisWrapper:
def __init__(self, redis: Redis, database: str):
... |
# This file is part of GridCal.
#
# GridCal 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 version 3 of the License, or
# (at your option) any later version.
#
# GridCal is distributed in the hope that... |
# -*- coding: utf-8 -*-
"""
.. module: byroapi.byroapi
:synopsis: Main module
.. moduleauthor:: "Josef Nevrly <josef.nevrly@gmail.com>"
"""
import asyncio
import io
import logging
from typing import BinaryIO, Union
from aioyagmail import AIOSMTP
from .http_handler import HttpHandler
from .template import Templat... |
##!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Две модели гипергеометрическое распределение (N=2 и N=40)
Запуск:
python ./hypergeometric_distribution.py
Пример визуализации возникновения событий в соответствии с гипергеометрическим распределением.
Гипергеометрическое распределение моделирует количество удачных ... |
from timeit import timeit
from source import adjacency_graph, edges_graph, records_graph
def timer(repeats=1):
def decorator(f):
def new_function():
full_time = timeit(f, number=repeats)
return round(full_time, 3)
return new_function
return decorator
class EGraph:
... |
# Simple hangman solver, guesses letters in order of frequency
import re
print('anttispitkanen')
words = []
temp_words = []
word = input().strip()
while word:
words.append(word)
temp_words.append(word)
word = input().strip()
letters = {letter for word in words for letter in word}
frequencies = [(lette... |
num = float(input('Digite um número real: '))
print(f'O quadrado de {num} é {num ** 2}') |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
arr = []
res = 0
for i in range(len(s)):
if s[i] in arr:
res = max(res, len(arr))
arr.append(s[i])
ind = arr.index(s[i])
arr = arr[ind+1:]
... |
import math
class Edge:
def __init__(self, lower, upper):
assert upper >= lower
self.lower = lower
self.upper = upper
@property
def width(self):
return (self.upper - self.lower)
@property
def log_ratio(self):
if self.lower <= 0:
return 1
... |
import sys
from setuptools import setup, find_packages
install_requires=[
'Pillow>=2.2.2',
'Jinja2>=2.7,<2.8',
]
tests_require=[
'cssutils>=0.9,<1.0',
]
# as of Python >= 2.7 argparse module is maintained within Python.
if sys.version_info < (2, 7):
install_requires.append('argparse>=1.1')
# as of ... |
import asyncio
from ssl import SSLContext
import pytest
from slack_sdk import WebClient
from slack_sdk.oauth.installation_store import FileInstallationStore
from slack_sdk.oauth.state_store import FileOAuthStateStore
from slack_sdk.web.async_client import AsyncWebClient
from slack_bolt.async_app import AsyncApp
from ... |
dt.filename = '//femto/C/All Projects/APS/Experiments/2018.06/Archive/PATHOS.dt.txt'
flag.filename = '//mx340hs/data/anfinrud_1805/Archive/PATHOS.flag.txt' |
import pytest
def test_rnaseq_remote_portal_init():
from genomic_data_service.rnaseq.remote.portal import Portal
portal = Portal()
assert isinstance(portal, Portal)
def test_rnaseq_remote_portal_get_gene_url():
from genomic_data_service.rnaseq.remote.portal import Portal
portal = Portal()
as... |
# ===============================================================================
# Copyright 2013 Jake Ross
#
# 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... |
# From this directory, execute
# magnetovis --script=Axis.py
import paraview.simple as pvs
import magnetovis as mvs
sourceArguments = {
"time": "2001-01-01",
"extent": [-40., 40.],
"coord_sys": "GSM",
"direction": "X"
}... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from slack_logging.formatters import LevelEmojis, SlackLoggerFormatter
from slack_logging.handlers import SlackLoggerHandler
def configure_slack_logger(logger_name):
"""
build a logger with handlers for the configured channels
:type logger_nam... |
import os
from srd import add_params_as_attr, add_schedule_as_attr
from srd.quebec import template
module_dir = os.path.dirname(os.path.dirname(__file__))
# wrapper to pick correct year
def form(year):
"""
Fonction qui permet de sélectionner le formulaire d'impôt provincial par année.
Parame... |
from .resultsmontage import results_montage
from .sortedcolormontage import create_sorted_color_montage
from .colorutils import color_histogram
from .colorutils import get_dominant_color
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the stepPerms function below.
def stepPerms(n,m=3):
tot=0
for x in rec(n,m):
n=1
i=0
l=0
while i<m:
if x[1] > 0:
l+=x[1]
n*=math.factorial(l)/(math.facto... |
import sys
import os
# import current path
projectFolder = os.path.dirname(__file__)
if projectFolder not in sys.path:
sys.path.append(projectFolder)
# attach debugger
from lib.sdk.debugger import *
pydev_path = "JetBrains/Toolbox/apps/PyCharm-P/ch-0/192.6262.63/helpers/pydev"
debug(pydev_path)
import loader
rel... |
import numpy as np
from . import charminv
class Harminv(charminv.Harminv):
threshold = {'error': 0.1,
'relative_error': np.inf,
'amplitude': 0.0,
'relative_amplitude': -1.0,
'Q': 10.0
}
def compute_threshold(self, inrange=F... |
"""Add ProjectOption
Revision ID: 1d1f467bdf3d
Revises: 105d4dd82a0a
Create Date: 2013-11-20 16:04:25.408018
"""
# revision identifiers, used by Alembic.
revision = '1d1f467bdf3d'
down_revision = '105d4dd82a0a'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'projectopti... |
"""https://leetcode.com/problems/maximum-depth-of-binary-tree/
Examples:
>>> Solution().maxDepth(None)
0
"""
from typing import Optional
from pytudes._2021.utils import binary_tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(
# self, val: int = 0, left: "TreeNodeType" ... |
# -*- coding=utf -*-
from __future__ import absolute_import
from cubes.model import Cube, create_dimension
from cubes.model import aggregate_list
from cubes.browser import *
from cubes.stores import Store
from cubes.errors import *
from cubes.providers import ModelProvider
from cubes.logging import get_logger
from .m... |
#!/usr/bin/env python3
import py_trees
blackboard = py_trees.blackboard.Client(name="Global")
parameters = py_trees.blackboard.Client(name="Parameters", namespace="parameters")
blackboard.register_key(key="foo", access=py_trees.common.Access.WRITE)
blackboard.register_key(key="/bar", access=py_trees.common.Access.WR... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Data61, CSIRO
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
from cognite.power.client import PowerClient
from cognite.power.data_classes import PowerAsset, PowerAssetList
from cognite.power.power_area import PowerArea
from cognite.power.power_corridor import PowerCorridor, PowerCorridorComponent
from cognite.power.power_graph import PowerGraph
|
# Generated by Django 3.0.7 on 2020-07-29 06:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('graphs', '0004_alabama_temperature_input'),
]
operations = [
migrations.CreateModel(
name='Temps',
fields=[
... |
import os
import pickle
import numpy as np
import PIL.Image
import dnnlib
import dnnlib.tflib as tflib
import config
import scipy
import dnnlib.tflib as tflib
import math
import moviepy.editor
from numpy import linalg
import numpy as np
import pickle
def main():
tflib.init_tf()
# Load pre-trained network.
... |
from __future__ import with_statement
import six
if six.PY3:
import unittest
else:
import unittest2 as unittest
from mock import Mock, patch
from twilio.rest.resources import AuthorizedConnectApps
from twilio.rest.resources import AuthorizedConnectApp
class AuthorizedConnectAppTest(unittest.TestCase):
d... |
#!/usr/bin/env python
import subprocess
from src.core.setcore import *
from src.core.menu.text import *
from src.core.dictionaries import *
# definepath
definepath = os.getcwd()
sys.path.append(definepath)
# grab the metasploit path
meta_path = meta_path()
# here we handle our main payload generation
def payload_ge... |
import logging
import math
import re
import time
import uuid
from datetime import datetime
from os import path
import requests
from config import Config
class Run(Config):
def __init__(self):
super(Run, self).__init__()
self.collection = self.Collection(__file__)
self.exploitUrl = 'http... |
# Python
from __future__ import unicode_literals
# Django-Site-Utils
from site_utils.utils import app_is_installed
def test_app_is_installed(settings):
assert app_is_installed('contenttypes')
assert app_is_installed('django.contrib.contenttypes')
assert app_is_installed('admin')
assert app_is_install... |
'''
To run functional tests:
python3 manage.py test functional_tests
'''
import sys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest(StaticLiveServerTestCase):
@classmethod
def setUpCla... |
from django.db.models.loading import get_model
from mptt import models as mpttmodels
from django.db import models
from django.conf import settings
from accounts.business.fields import MemberStatusField
from nodes.business.managers import NodeManager
from nodes.roles import ManageRole
from vaultier.business.db import Ti... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
import cPickle as pickle
except:
import pickle
class UserValues(object):
"""
Creating a class in which the instance attributes are based on the dictionary
'GWsky_config' by default. GWsky_config is created and pickled by the 'user_values' ***... |
# Copyright 2015-2016 FUJITSU LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
import unittest
import subprocess
class ConversionTestCase(unittest.TestCase):
conversion_cls = None
def setUp(self):
super(ConversionTestCase, self).setUp()
self.conversion = self.conversion_cls()
self.null = open('/dev/null', 'w')
def tearDown(self):
super(ConversionT... |
"""
Unit Tests for seq_prob_ratio.py
"""
import math
from nose.tools import assert_equal, assert_almost_equal, assert_less, raises
from nose.plugins.attrib import attr
from ..sprt import seq_prob_ratio
from ..sprt import bernoulli_lh
from ..sprt import bernoulli_seq_ratio
from ..sprt import normal_lh
from ..sprt imp... |
""" Melhore o jogo do desafio 028 onde computador vai "pensar" em
um numero entre 0 e 10. So que agora o jogador vai tentar adivinhar
até acertar, mostrando no final quantos palpites foram
necessarios para vencer. """
from random import randint
numero = randint(0,10)
jogador = int(input('Qual numero o computador penso... |
from django.contrib.auth import get_user_model
from rest_framework import viewsets
from django_pyjwt_example import serializers
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = get_user_model().objects.all()
serializer_class = serializers.UserSerializer
|
from django.db import models
from .validators import validate_is_pdf
class PdfFile(models.Model):
series = models.ForeignKey(
'Series',
on_delete=models.CASCADE,
related_name='pdfs',
blank=True,
null=True,
)
file = models.FileField(upload_to='pdfs/%Y/', validators=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutIteration(Koan):
def test_iterators_are_a_type(self):
it = iter(range(1,6))
total = 0
for num in it:
total += num
# >>> [x for x in range(1,6)]
# [1, 2, 3, 4, 5]
self... |
#!/usr/bin/env python
from setuptools import setup, Extension
import sys
import platform
import os
from py4a import patch_distutils
patch_distutils()
mods = []
if sys.platform == 'win32':
XP2_PSDK_PATH = os.path.join(os.getenv('ProgramFiles'), r"Microsoft Platform SDK for Windows XP SP2")
S03_PSDK_PATH = os... |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import pytest
from pluggy import PluginManager, HookimplMarker, HookspecMarker
hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
def test_parse_hookimpl_override() -> None:
class MyPluginManager(PluginManager):
def parse_hookimpl_opts(self, module_or_class, name):
opts... |
#!/usr/bin/env python
import sys
import numpy as np
from edrixs.iostream import write_emat, write_umat
def get_hopping_coulomb():
N_site = 16
norbs = 32
U, t = 4.0, -1.0
umat=np.zeros((norbs, norbs, norbs, norbs), dtype=np.complex128)
for i in range(N_site):
off = i*2
umat[off, of... |
import os
import sys
from SteamworksParser import steamworksparser
class InternalConstant:
def __init__(self, name, value, type_, precomments, comment, spacing):
self.name = name
self.value = value
self.type = type_
self.precomments = precomments
self.comment = comment
... |
x = int(input('Enter the number: \t'))
if x%2==0:
if x%3==0:
print("Number is divisible by 2 and 3")
else:
print("Number is divisible by 2 only")
print("x%3= ", x%3)
elif x%3==0:
print("Number is divisible by 3 only")
else:
print("Number is not divisible by 2 and 3")
... |
import json, time, random
def main():
# TODO: allow them to choose from multiple JSON files?
with open('spooky_mansion.json') as fp:
game = json.load(fp)
print_instructions()
print("You are about to play '{}'! Good luck!".format(game['__metadata__']['title']))
print("")
play(game)
def... |
"""Proof-of-concept for model card integration in SageMaker Pipelines"""
import logging
import tempfile
import urllib
from pathlib import Path
from datetime import datetime
import dataclasses
from typing import List, Text, Union, Optional
import json
import base64
import boto3
import jinja2
# lots of model card tutoria... |
from drawable_element import DrawableElement
from education_item import EducationItem
class Education(DrawableElement):
# constants
BASE_Y_OFFSET = 3090
MAX_WIDTH = 1660
MIN_X_SPACING = 35
CONTENT_Y_SPACING = 70
def __init__(self, data, cv):
super().__init__(cv)
self.edu_header = data["edu_header"]
self.i... |
import bottle
from os import path
STATIC_FOLDER = path.join(path.dirname(__file__), 'public')
ALLOW_TYPES = ['html', 'js', 'css', 'png', 'jpg', 'ico', 'webp']
app = bottle.Bottle()
# single page app
@app.route('/')
@app.route('/index.html')
def index():
return bottle.static_file('index.html', root = STATIC_FOLDE... |
import pygtk
pygtk.require('2.0')
import gtk
from pyshorteners.shorteners import Shortener
# get the clipboard
clipboard = gtk.clipboard_get()
#read clipboard for the text copied
url_original = clipboard.wait_for_text()
try:
shortener = Shortener('TinyurlShortener')
url = format(shortener.short(url_original))
# ... |
version https://git-lfs.github.com/spec/v1
oid sha256:5273b67e29f8efd017f0e9242282d3ec90d2b8355f528e3a195ca5d8b5cfbbbd
size 3303
|
# Celery task status
STATUS_PENDING = "PENDING"
STATUS_RUNNING = "RUNNING"
STATUS_SUCCESS = "SUCCESS"
STATUS_FAILURE = "FAILURE"
# Keys lookup status strings.
KEYS_STATUS_SUCCESS = "success"
KEYS_STATUS_FAIL = "fail"
KEYS_STATUS_NOMATCH = "nomatch"
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/010_UK.ipynb (unless otherwise specified).
__all__ = ['LAST_MODIFIED']
# Cell
from ..imports import *
from ..core import *
import openpyxl
# Cell
LAST_MODIFIED = datetime.date.today() |
import requests
import json
from flask import Blueprint, request, jsonify, render_template, Flask
from flask_cors import CORS, cross_origin
import pandas as pd
import re
import os
# *************************************************************************** #
# ML Engineers imports. Must be formated like th... |
import numpy as np
import pyrender
import trimesh
import math
from pyrender.constants import RenderFlags
import config
class Renderer:
"""
Renderer used for visualizing the SMPL model
Code adapted from https://github.com/vchoutas/smplify-x
"""
def __init__(self, faces, img_res=512):
self.r... |
from leapp.actors import Actor
from leapp.libraries.actor import reportsettargetrelease
from leapp.models import Report
from leapp.tags import IPUWorkflowTag, TargetTransactionChecksPhaseTag
class ReportSetTargetRelease(Actor):
"""
Reports information related to the release set in the subscription-manager aft... |
from datetime import datetime
import logging
from zentral.core.events.base import BaseEvent, EventMetadata, EventRequest, register_event_type
from zentral.core.queues import queues
logger = logging.getLogger('zentral.contrib.osquery.events')
ALL_EVENTS_SEARCH_DICT = {"tag": "osquery"}
class OsqueryEvent(BaseEvent)... |
import re
import sys
from abc import ABCMeta
from copy import copy as _copy, deepcopy
import logging
import typing as t
from types import MethodType
from collections import ChainMap
from collections.abc import Mapping, Callable
from threading import RLock
from laza.common.collections import fallbackdict, orderedset... |
import tensorflow as tf
import time
import numpy as np
tf.compat.v1.disable_eager_execution()
def main():
from neural_compressor.experimental import Quantization, common
quantizer = Quantization('./conf.yaml')
# Do quantization
quantizer.model = common.Model('./inception_v1.ckpt')
quantized_mod... |
# -*- coding:utf-8 -*-
import smtplib, email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header
import secret_key, constants, ra... |
from output.models.nist_data.atomic.unsigned_short.schema_instance.nistschema_sv_iv_atomic_unsigned_short_min_inclusive_2_xsd.nistschema_sv_iv_atomic_unsigned_short_min_inclusive_2 import NistschemaSvIvAtomicUnsignedShortMinInclusive2
__all__ = [
"NistschemaSvIvAtomicUnsignedShortMinInclusive2",
]
|
#!/usr/bin/python3
"""
A node to be used in a linked list
"""
class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
"""
A class to represent the linked list queue
"""
class Linked_Queue:
def __init__(self, size):
self.size = size
self.... |
import os
from datetime import datetime
A_NONE = 'None'
A_PARTIAL = 'Partial'
A_FULL = 'Full'
A_FAIL = 'Fail'
A_PASS = 'Pass'
class Scan:
'''abstract class to scan a raw data file'''
file_path = None
file_size = None
reader = None
progress = 0 # completed percentage (0 - 100)
scan_resu... |
import tornado.iostream
import tornado.ioloop
import tornado.concurrent
import tornado
import time
import socket
import functools
import collections
class UDPRequest(object):
def __init__(self, addr, port, data, src_port=0):
self.addr = addr
self.port = port
self.data = data
self... |
import json
import os
import uuid
import pickle
from Alerts.Alert import Alert
from AlertsParameters.Categories.Category import Category
class AlertsDiskIO(object):
def __init__(self):
super().__init__()
home = os.path.expanduser("~")
self.alertsDirectory = os.path.join(home, "EbayAlerto... |
import random
from typing import Tuple
from PIL import Image
def get_average_per_channel(img: Image) -> Tuple[float, float, float]:
r, g, b = 0, 0, 0
area = img.width * img.height
for y in range(img.height):
for x in range(img.width):
pixel = img.getpixel((x, y))
r += pi... |
# n is not required in this program
# to meet the requirements of STDIN of hackerrank we are using n variable
def soln(a, scores):
scores = sorted(list(dict.fromkeys(scores)))
print(scores[-2])
if __name__ == "__main__":
n = int(input())
arr = map(int, input().split())
soln(n, arr)
|
from future.standard_library import install_aliases
install_aliases()
from urllib.request import urlopen
import os
import logging
import sys
data_dir = os.path.join(os.path.abspath(__file__ + '/../../../..'), 'data/raw/weather_wunderground')
logger = logging.getLogger(__name__)
# include your weather stations here b... |
from __future__ import annotations
import pytest
pytest.register_assert_rewrite("tests.mixology.helpers")
|
# @ build_board.py
# This adds additional functions to the build_bios.py
#
# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
"""
This module serves as an additional build steps for the Mt Olympus board
"""
import os
import sys
def pre_b... |
import forumsweats.discordbot as discordbot
from ..commandparser import Member
import discord
from forumsweats import db
name = 'duelstreak'
aliases = ('duel-streak', 'duelwinstreak', 'duel-winstreak', 'duelwin-streak', 'duel-win-streak')
args = '[member]'
async def run(message, member: Member = None):
'Tells you y... |
import multiprocessing
import sys
import mido
import pretty_midi
import numpy as np
import collections
from joblib import Parallel, delayed
from mir_eval.util import hz_to_midi
from tqdm import tqdm
def parse_midi(path):
print("Parsing midi")
"""open midi file and return np.array of (onset, offset, note, vel... |
import pandas as pd
import numpy as np
import os
import random
import warnings
warnings.simplefilter('ignore')
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split, KFold, StratifiedKFold
import lightgbm as lgb
TARGET = 'Survived'
N_ESTIMATORS = 1000
... |
from deidentify.base import Annotation, Document
from deidentify.taggers import CRFTagger
from deidentify.tokenizer import TokenizerFactory
tokenizer = TokenizerFactory().tokenizer(corpus='ons')
tagger = CRFTagger(model='model_crf_ons_tuned-v0.2.0', tokenizer=tokenizer)
def test_annotate():
doc = Document(
... |
# # -*- encoding: utf-8 -*-
import shared as s
import utils as u
def AritMenu():
u.LogoType(s.LogoPath)
print("1 - Adição")
print("2 - Subtração")
print("3 - Multiplicação")
print("4 - Divisão")
print("x - Voltar")
Opt = u.getch()
if Opt == 'x': return 0
u.clear()
print("<'exit' para sair>")
if Opt == '4': ... |
import os
import itertools
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from tqdm import trange
import numpy as np
from scipy.misc import imread, imresize
from util import audio
def __load_and_save_images(category, config):
category_input_base_dir = os.path.join(config.base_d... |
def is_divisible(n):
for divisor in range(2, 21):
if n % divisor != 0:
return False
return True
number = 1
while not is_divisible(number):
number += 1
print(number)
|
# Example 5
def main():
# Create a dictionary with student IDs as the keys
# and student data stored in a list as the values.
students = {
"42-039-4736": ["Clint", "Huish", "hui20001@byui.edu", 16],
"61-315-0160": ["Michelle", "Davis", "dav21012@byui.edu", 3],
"10-450-1203": ["Jorge... |
import boto3
import mock
import pytest
import requests
import yaml
from botocore.stub import Stubber
from datetime import datetime
from dateutil.tz import tzutc
from freezegun import freeze_time
from io import StringIO
from app import (
create_hostedgraphite_base_metrics,
format_cloudwatch_metric_datapoint_fo... |
from kakaopy.client import Client
import json
class main(Client):
async def onMessage(self, chat):
print(chat.message)
if chat.message == "power":
await chat.reply("kakaopy is runnnnnnnnning~")
if chat.message == "Hello":
attachment = {'mentions': [{'user_id': chat.authorId, 'at':... |
import random
import subprocess
from pathlib import Path
from xml.dom.minidom import Childless
import time
import os
import appdirs
import socket
BASE_RAND_STR = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
BASE_RAND_STR_LEN = len(BASE_RAND_STR)
def random_str(str_len=16)->str:
result_str = '... |
#!/usr/bin/env python
import os
import numpy as np
import open3d as o3
import transforms3d as t3
import pyquaternion as pq
def invert_ht(ht):
ht = np.tile(ht, [1, 1, 1])
iht = np.tile(np.identity(4), [ht.shape[0], 1, 1])
iht[..., :3, :3] = ht[..., :3, :3].transpose(0, 2, 1)
iht[..., :3, [3]] = -np.m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.