content stringlengths 5 1.05M |
|---|
notas = (100, 50, 20, 10, 5, 2, 1)
valor = int(input("Digite o valor: "))
for i in range(len(notas)):
numDeNotas = valor / notas[i]
valor %= notas[i]
print("Quantidade de notas %d: %d" % (notas[i], numDeNotas))
|
#!/usr/bin/python
from . import * |
#!/usr/bin/env python
from __future__ import unicode_literals
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
import threading
import random
import time
import json
# D... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class Fftw(Package):
"""Used to test that a few problematic concretization
cases with the old concretizer have been... |
import asyncio
import discord
from discord.ext import commands
class AutoRoles(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = self.bot.get_cog("Database")
self.stop_loops = False
self.bot.loop.create_task(self.premium_sweep())
def cog_unload(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from struct import unpack
from .uuid import Uuid
class ValueState:
def __init__(self, payload):
"""
typedef struct {
PUUID uuid; // 128-Bit uuid
double dVal; // 64-Bit Float (little endian) value
} PACK... |
import math
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
plt.show()
def run():
V = 7.4
kV = np.array([[3600, 2850, 2170, 1800]])
Pmax = np.array([[240, 180, 125, 95]])
Ipmax = np.array([[62, 50, 35, 28]])
R0 = np.array([[0.0183, 0.0289, 0.0488, 0.0747]])
I0 = np.array([[2.8, 2.4, 1.6, 1.3]])
... |
DOMAIN_ICONS = {
"youtube.com": "fa:fab fa-youtube",
"youtu.be": "fa:fab fa-youtube",
"reddit.com": "fa:fab fa-reddit-alien",
"github.com": "fa:fab fa-github",
}
|
#!/usr/bin/env python3
"""
Merges several csv files (the first file serves as base)
Assumes that they have the same set of columns,
but the columns do not have to be in the same order
"""
import csv
import sys
def main():
if len(sys.argv) < 3:
print("Wrong number of arguments: specify at least two files ... |
from django.db.models import ManyToOneRel, Model
FIELD_PERMISSION_TYPES = ["view", "change"]
class FieldPermissionsModelRegistry(object):
def __init__(self):
self._registry = {}
def register(self, cls, include_fields=None, exclude_fields=None):
if not issubclass(cls, Model):
rais... |
# -*- coding: utf-8 -*-
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file'
)
|
import json
import random
from os import environ
def lambda_handler(event, context):
request = event['Records'][0]['cf']['request']
redirect_url = ${redirect_path == null ? "request['uri']": "${redirect_path}"}
protocol = request['headers']['cloudfront-forwarded-proto'][0]['value']
response =... |
#!/usr/bin/env python
import sys, os
import datetime
# Get path of script
scriptpath = os.path.dirname(os.path.realpath(__file__))
# take schedule name as input, e.g. b21096
exp = sys.argv[1]
# Check if we should download schedule, or assume it already exists locally
dl=False
if (len(sys.argv)==3) and (sys.argv[2]==... |
# Crear un archivo
f = open("flag.txt", "w")
f.write("quiero salir de fiesta pero estoy haciendo programación :) ")
f.close
f = open("flag.txt", "r")
print(f.read())
|
# -*- coding: utf-8 -*-
import pydicom
import pytest
from pynetdicom2 import asceprovider
from pydicom import uid
from pynetdicom2 import dsutils
from tiny_pacs import ae
from tiny_pacs import db
from tiny_pacs import event_bus
from tiny_pacs import storage
@pytest.fixture
def memory_storage():
bus = event_bus.... |
from abc import ABC, abstractmethod
from deluca.lung.devices.pins import Pin, PWMOutput
import os
import numpy as np
class SolenoidBase(ABC):
"""An abstract baseclass that defines methods using valve terminology.
Also allows configuring both normally _open and normally closed valves (called the "for... |
# Program to lowercase first n characters in a string
temp=str(input("Enter a string in upper case :"))
n=int(input("How many first characters do you want to in lower case:"))
new_string=temp[:n].lower()+temp[n:]
print(new_string)
|
# Generated by Django 3.1.4 on 2021-01-24 20:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finance', '0014_auto_20210121_0152'),
]
operations = [
migrations.AddField(
model_name='transaction',
name='entry_am... |
import json
import os
import sys
from datetime import datetime
# Layer code, like parsing_lib, is added to the path by AWS.
# To test locally (e.g. via pytest), we have to modify sys.path.
# pylint: disable=import-error
try:
import parsing_lib
except ImportError:
sys.path.append(
os.path.join(
... |
import itertools
from stevedore import extension
Recipe = str
Dish = str
def get_inventory():
return {}
def get_all_recipes() -> list[Recipe]:
mgr = extension.ExtensionManager(
namespace='ultimate_kitchen_assistant.recipe_maker',
invoke_on_load=True,
)
def get_recipes(ex... |
#Autor: Olavo M
from flask import Flask, render_template, request, redirect
#import somente do necessario para a interface web
app = Flask(__name__)
class Noh: #clase do no, contendo seu valor e o ponteiro para o proximo
def __init__(self, valor):
self.valor = valor #o valor pode ser de qualquer tipo, m... |
import logging
import os
import time
import pytest
import sdk_cmd
import sdk_plan
import sdk_tasks
import sdk_upgrade
import sdk_utils
from tests import config
log = logging.getLogger(__name__)
FRAMEWORK_NAME = "secrets/hello-world"
NUM_HELLO = 2
NUM_WORLD = 3
# check environment first...
if "FRAMEWORK_NAME" in os... |
#!/usr/bin/env python
__author__ = 'Michael Meisinger'
from pyon.core.governance import ANONYMOUS_ACTOR
from pyon.public import log, CFG, BadRequest, EventPublisher, Conflict, Unauthorized, NotFound, PRED, OT, RT
from interface.services.scion.iscion_management import BaseScionManagement
class ScionManagementServic... |
# Package: Python
# License: Released under MIT License
# Notice: Copyright (c) 2020 TytusDB Team
# Developer: Maynor Piló Tuy
import os
import time
from storageManager.ArbolBmas import ArbolBmas
# CLASE PARA INSTANCIAR CADA UNA DE LAS FUNCIONES :
class CrudTuplas:
def __init__(self, columas)... |
from unittest import TestCase
import unittest
import pygem.openfhandler as ofh
import numpy as np
import filecmp
import os
class TestOpenFoamHandler(TestCase):
def test_open_foam_instantiation(self):
open_foam_handler = ofh.OpenFoamHandler()
def test_open_foam_default_infile_member(self):
ope... |
__________________________________________________________________________________________________
sample 192 ms submission
class Solution:
def findCircleNum(self, M: List[List[int]]) -> int:
seen = set()
def visit_all_friends(i: int):
for friend_idx,is_friend in enumerate(M[i]):
... |
default_app_config = 'tenant_resource.apps.TenantResourceConfig'
|
# SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: Apache-2.0
import logging
import pytest
from _pytest.fixtures import FixtureRequest
from _pytest.monkeypatch import MonkeyPatch
from pytest_embedded_idf.serial import IdfSerial
# This is a custom Serial Class to add the er... |
import uuid
from django.db import models
from django.utils.text import Truncator
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
from django.conf import settings
UPLOAD_DIRECTORY_PROFILEPHOTO = 'images_profilephoto'
class CustomUserManager(BaseUserManager):
"""
Cu... |
# Python script to pre-process Duke data:
# o reorganizes the directory structire into LabCAS archive format
# o creates the dataset metadata file
import os
import sys
from glob import glob
from shutil import copyfile
import dicom
# process data from $LABCAS_ARCHIVE/Duke --> $LABCAS_ARCHIVE/Sample_Mammography_Referen... |
""" Tests for vol_rms_diff function in diagnostics module
Run with:
nosetests test_vol_rms_diff.py
"""
import numpy as np
from .. import diagnostics
from numpy.testing import assert_almost_equal, assert_array_equal
def test_vol_rms_diff():
# We make a fake 4D image
shape_3d = (2, 3, 4)
V = np.prod(s... |
# Copyright (c) 2005-2007 ActiveState Software Ltd.
"""Configuration support for Makefile.py's."""
import sys
import os
from os.path import isfile, basename, splitext, join, dirname, normpath, \
exists, abspath
from pprint import pprint
import imp
import types
from mklib.common import *
class C... |
import json
import sys
import os
import time
from lbcapi import api
# Apiauth-Nonce
# A nonce is an integer number, that needs to increase with every API request.
def getNonce():
return str(round(time.time() * 1000))
# /bitcoinaverage/ticker-all-currencies/
def getBitCoinAverage():
pass
# Ofertas de los ... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
# Check if camera opened successfully
if (cap.isOpened()== False):
print("Error opening video stream or file")
frameNum = 0
# Read until video is completed
while(cap.isOpened()):
# Capture frame-by-frame
ret, frame = cap.read()
frameNum += 1
if r... |
from django.db import models
from manage_tools.models import Tool
from user.models import User
class Request(models.Model):
PENDING_APPROVAL = 'PA'
APPROVED = 'AP'
REJECTED = 'RE'
RETURNED = 'RT'
status_choices = (
(PENDING_APPROVAL, 'Pending Approval'),
(APPROVED, 'Approved'),
... |
from flourish.generators.atom import AtomGenerator
PATHS = [
AtomGenerator(
path = '/index.atom',
name = 'atom-feed',
),
]
|
##########################################################################
#################### This class is for plotting specefic data and not par
##########################################################################
# import libraries
import numpy as np
import pandas as pd
import os
from utils.plot_data impor... |
hens, goats = map(int, input().split())
print(2 * hens + 4 * goats, 2 * (hens + goats))
|
glfuncnames = """
GlmfBeginGlsBlock
GlmfCloseMetaFile
GlmfEndGlsBlock
GlmfEndPlayback
GlmfInitPlayback
GlmfPlayGlsRecord
glAccum
glAlphaFunc
glAreTexturesResident
glArrayElement
glBegin
glBindTexture
glBitmap
glBlendFunc
glCallList
glCallLists
glClear
glClearAccum
glClearColor
glClearDepth
glClearIndex
glClearStencil
g... |
# -*- coding: utf-8 -*-
"""Padding operations for cylindrical data.
@@wrap_pad
@@wrap
"""
from __future__ import division
import tensorflow as tf
from math import floor, ceil
def wrap_pad(tensor, wrap_padding, axis=(1, 2)):
"""Apply cylindrical wrapping to one axis and zero padding to another.
... |
import uuid
import os
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
from django.conf import settings
def recipe_image_file_path(instance, filename):
"""Generate file path for new recipe image"""
ext = filename.split('.')[-1]
... |
import re
import aviation_weather
from aviation_weather import exceptions
from aviation_weather.components import Component
class _ChangeGroup(Component):
def __init__(self, raw):
try:
self.wind = aviation_weather.Wind(raw)
raw = raw.replace(self.wind.raw, "")
except exce... |
envs = [
'dm.acrobot.swingup',
'dm.cheetah.run',
'dm.finger.turn_hard',
'dm.walker.run',
'dm.quadruped.run',
'dm.quadruped.walk',
'dm.hopper.hop',
]
times = [
1e6, 1e6, 1e6, 1e6, 2e6, 2e6, 1e6
]
sigma = 0.001
f_dims = [1024, 512, 256, 128, 64]
lr = '1e-4'
count = 0
for i, env in enume... |
int(input())
nums = set([int(x) for x in input().split()])
int(input())
print(len(nums.union(set([int(x) for x in input().split()])))) |
#!python2.7
# -*- coding: utf-8 -*-
import maya.cmds as cmds
import maya.utils
import sys
sys.dont_write_bytecode = True
def setPref():
cmds.evaluationManager(mode = "off")
cmds.optionVar(intValue = ["gpuOverride",0])
cmds.savePrefs(general =True)
maya.utils.executeDeferred(setPref) |
#SQuADのデータ処理
#必要条件:CoreNLP
#Tools/core...で
#java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -port 9000 -timeout 15000
import os
import sys
sys.path.append("../")
import json
import gzip
import pandas as pd
import numpy as np
from tqdm import tqdm
from nltk.tokenize import word_tokenize,sent_tokenize... |
import time
import numpy as np
from random import randint
import tensorflow as tf
import datetime
import random
import os
class Seed(object):
"""Class representing a single element of a corpus."""
def __init__(self, cl, coverage, root_seed, parent, metadata, ground_truth, l0_ref=0, linf_ref=0):
"""Ini... |
from django.contrib import admin
from .models import Newsletter, Recruitment
# Register your models here.
@admin.register(Newsletter)
class NewsletterAdmin(admin.ModelAdmin):
display = ('full_name', 'full_name', 'time_stamp')
@admin.register(Recruitment)
class RecruitmentAdmin(admin.ModelAdmin):
display = ('u... |
import tkinter as tk
import numpy
from PIL import Image, ImageTk
class ImageLabel(tk.Label):
"""A label with an updatable image."""
def update_image(self, image: numpy.ndarray) -> None:
"""Update the label with the given image."""
display_image = Image.fromarray(image)
display_image =... |
from flask import request, current_app
from flask_restful import Resource
from app import models
from app.api.schemas import CountdownResultSchema, CountdownResultsWithAdditionalDataSchema, CountdownResultsQuerySchema
from app.auth.views import current_user, authorized_or_403
from app.models import CountdownResult, db... |
import pymr
import time
class IndexInverter(pymr.Solver):
def reader(self):
with open('testcases/index.txt', 'r') as f:
return f.read().strip().split('\n')
def mapper(self, value):
time.sleep(0.1)
value = value.split()
for i in value[1:]:
yield i, value[... |
# Modules
import os
import sys
import tifffile
import numpy as np
import opt_functions as opt
import matplotlib.pyplot as plt
from pathlib import Path
# Data paths
proj_folder = Path(r'D:\OPTReconstructionData\M3_523_17wNIF_ASMA_Projections')
recon_folder = Path(r'C:\Users\david\Desktop\M3_523_17wNIF_ASMA_Reconstructi... |
import gym
from stable_baselines.common import make_vec_env
from stable_baselines.common.policies import MlpPolicy
from stable_baselines import PPO2
import tutorenvs
from tutorenvs.multicolumn import MultiColumnAdditionDigitsEnv
from tutorenvs.multicolumn import MultiColumnAdditionSymbolic
import numpy as np
from pprin... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-23 11:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('todo', '0004_auto_20161023_1133'),
]
operations = [
migrations.AddField(
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import F
from django.dispatch import receiver
from machina.apps.forum.signals import forum_viewed
@receiver(forum_viewed)
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs):
"""
Receiver ... |
from .base_feature import BaseFeature
class POSFeature(BaseFeature):
def word2features(self, s, i):
word = s[i][0]
features = {
'bias' : 1.0,
'[0]' : word,
'[0].lower' : word.lower(),
'[0].istitle': all(w.istitle() for w in word.split('... |
from unittest import TestCase
from similarityPy.algorithms.standart_deviation import StandartDeviation
from tests import test_logger
__author__ = 'cenk'
class StandartDeviationTest(TestCase):
def setUp(self):
pass
def test_algorithm_with_list(self):
test_logger.debug("StandartDeviationTest... |
#!/usr/bin/env python
import os, sys, re
import shutil
from aos_parse_components import get_comp_name
# Global definitions
top_config_in = "build/Config.in"
board_config_in = "board/Config.in"
example_config_in = "app/example/Config.in"
profile_config_in = "app/profile/Config.in"
autogen_start = "--- Generated Auto... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com)
@description:
"""
import addressparser
if __name__ == '__main__':
location_str = ["徐汇区虹漕路461号58号楼5楼",
"泉州市洛江区万安塘西工业区",
"朝阳区北苑华贸城",
"上海浦东新区城区昌邑路1669弄7号602(苗圃路口)",
"湖北天门市渔薪镇湖... |
c = 0
chk = 1
for _ in ' '*int(input()):
if input() == 'A':
c += 1
else:
if c > 0:
c -=1
else:
chk = 0
print("YES" if chk and c == 0 else "NO") |
# Imports
import numpy as np
from stablab.profile_solve_guess import profile_solve_guess
"""get_profile gets the profile of a """
def get_profile(p, s, tol=1e-8, sL=-10, sR=10, num_inf=2, timeout = 10):
# Set up the passed arguments into s.
s.update({'L': sL, 'R': sR})
max_err = 1+tol
# Begin solvi... |
# -*- coding: utf-8 -*-
import unittest
import tempfile
from os.path import join
from os.path import pardir
from os.path import sep
from collections import namedtuple
from calmjs.parse import utils
class UtilsTestCase(unittest.TestCase):
def setUp(self):
self.old_dist = utils.ply_dist
self.py_ma... |
# -*- coding: utf-8 -*-
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from Ranking.models import *
from ShopData.models import *
from users.models import UserData
from users.models impor... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
"""Resource Name CloudFormation Custom Resource"""
from . import lambda_function
__all__ = ["lambda_function"]
|
# GOAL: Handle exceptions for SmtApi.
# Take a HTTP response object and translate it into an Exception
# instance.
def handle_error_response(resp):
# Mapping of API response codes to exception classes
codes = {
-1: SmtApiError,
'400': BadRequest,
'401': AuthFail,
'403': HeaderMi... |
from tkinter import filedialog
from tkinter import *
from PIL import Image
import os
s_path = 'C:\\Users\\BRUNO\\Desktop\\CNN\\UST\\van_gogh.png'
c_path = 'C:\\Users\\BRUNO\\Desktop\\CNN\\UST\\tiger.png'
output_path = 'C:\\Users\\BRUNO\\Desktop\\CNN\\UST\\outputs'
def run():
alpha = str(alpha_scale.get()/100)
... |
import os
from easydict import EasyDict as edict
cfg1 = edict()
cfg1.PATH = edict()
cfg1.PATH.DATA = ['/home/liuhaiyang/dataset/CUB_200_2011/images.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/train_test_split.txt',
'/home/liuhaiyang/dataset/CUB_200_2011/images/']
cfg1.PATH.LABEL = '/home/liuhaiyang/da... |
# -*- coding: utf-8 -*-
"""
Created on 20170704 21:15:19
@author: Thawann Malfatti
Loads info from the settings.xml file.
Examples:
File = '/Path/To/Experiment/settings.xml
# To get all info the xml file can provide:
AllInfo = SettingsXML.XML2Dict(File)
# AllInfo will be a dictionary follow... |
from .src.models import * |
import random
import numpy as np
import cv2
import lmdb
import torch
import torch.utils.data as data
import data.util as util
class CrossnetDataset(data.Dataset):
"""
Read LQ (Low Quality, e.g. LR (Low Resolution), blurry, etc) and GT image pairs.
If only GT images are provided, generate LQ images on-the-... |
#!/usr/bin/env python3
'''
# ppe-cli.py
# interactive search of playerprofiler
'''
import logging
import click
from nfl.ppe import PlayerProfilerExplorer
@click.command()
@click.option('-h', '--path', type=str, default='/tmp',
help='Save path')
@click.option('-f', '--file_name', type=str,
... |
# Copyright 2014-2015 Canonical 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 ... |
"""Template exceptions."""
class MalformedTemplate(Exception):
"""Malformed template."""
def __init__(self, cause):
"""Init."""
message = f"Malformed template: {cause}"
super(MalformedTemplate, self).__init__(message)
class MissingTemplate(Exception):
"""Missing template."""
... |
from django.shortcuts import render_to_response
from django.shortcuts import render
from .models import *
from django.http import HttpResponse
import json
from datetime import datetime
from datetime import date, timedelta
from datetime import time
from django.http import HttpResponseRedirect
import cgi
from isoweek im... |
#*******************************************************************************
# Copyright 2014-2018 Intel Corporation
# All Rights Reserved.
#
# This software is licensed under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the Li... |
# -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Author: ryanss <ryanssdev@icl... |
from faker import Faker
from faker.providers import BaseProvider, internet
fake = Faker('pt_BR')
data = {
'login': fake.user_name(),
'name': fake.name(),
'user_type': fake.random_elements(elements=('I', 'E'))[0],
'main_email': fake.email(),
'alternative_email': fake.email(),
'usp_email': fake... |
import logging
import os
def setup_logger():
# create logger
logger = logging.getLogger("")
level = logging.INFO if os.getenv("ENV") == "prod" else logging.DEBUG
logger.setLevel(level)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(level)
# c... |
from urllib import request
import json
import os
import glob
def template(name, key, definition):
s = ""
s += f"# -*- mode: snippet -*-\n"
s += f"# name: {name}\n"
s += f"# key: {key}\n"
s += f"# --\n"
s += f"{definition}"
return s
def main():
file_url = "https://raw.githubusercontent... |
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from random import shuffle
from unittest import TestCase
from mock import Mock, PropertyMock, patch
from tests.misc.helper import get_alice_xmss, get_slave_xmss, get_r... |
import ldap
from awx.sso.backends import LDAPSettings
from awx.sso.validators import validate_ldap_filter
def test_ldap_default_settings(mocker):
from_db = mocker.Mock(**{'order_by.return_value': []})
with mocker.patch('awx.conf.models.Setting.objects.filter', return_value=from_db):
settings = LDAPSe... |
#!/usr/bin/env python
__author__ = "Kharim Mchatta"
#To connect to it upload the script on the victim server
#On your attack machine run the command below:
#nc target-ip target-port
#############################################
# Simple Reverse Listener #
# by Kharim Mchatta ... |
from IPython.core.magic import magics_class, line_cell_magic, Magics
from IPython.core.magic import needs_local_scope
from IPython.display import display, Markdown
@magics_class
class fstringMagic(Magics):
def __init__(self, shell, cache_display_data=False):
super(fstringMagic, self).__init__(shell)
@... |
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from transformer import Embedding
import re
def GraphEmbedding(vocab, embedding_dim, pretrained_file=None, amr=False, dump_file=None):
if pretrained_file is None:
return Embedding(vocab.size, embedding_dim, vocab.padding_... |
"""Unit tests for `OMMBV.vector`."""
import numpy as np
import pytest
import OMMBV
from OMMBV import sources
from OMMBV.tests.test_core import gen_data_fixed_alt
class TestVector(object):
"""Unit tests for `OMMBV.vector`."""
def setup(self):
"""Setup test environment before each function."""
... |
"""Lion Optimization Algorithm.
"""
import copy
import itertools
import numpy as np
import opytimizer.math.distribution as d
import opytimizer.math.general as g
import opytimizer.math.random as r
import opytimizer.utils.constant as c
import opytimizer.utils.exception as e
import opytimizer.utils.logging as l
from op... |
#!/usr/bin/env python2
from pwn import *
import sys
import string
MSG = """Agent,
Greetings. My situation report is as follows:
My agent identifying code is: .
Down with the Soviets,
006
"""
context.log_level = 'error'
def encrypt(payload):
r = remote("2018shell.picoctf.com",37131)
r.recvuntil('Please enter your sit... |
import attr
from clime import clime
@attr.s(auto_attribs=True)
class Dude:
likes_ice_cream: bool = False
def declare_ice_cream_status(self):
negate = " do not" if not self.likes_ice_cream else ""
print(f"hi! i{negate} like ice cream")
def main():
clime(Dude).declare_ice_cream_status()
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.tools.translate import _
class MailingList(models.Model):
_inherit = 'mailing.list'
def _default_toast_content(self):
return _('<p>Thanks for subscribing!</p>'... |
from queue import deque
import numpy as np
class Snake():
"""
The Snake class holds all pertinent information regarding the Snake's movement and boday.
The position of the snake is tracked using a queue that stores the positions of the body.
Note:
A potentially more space efficient implementation... |
from django.conf.urls import url, include
from App import views
urlpatterns = [
url(r'^index/',views.index,name='index')
] |
from django.http import HttpResponse
def homepage(request):
html = """
<html>
<body>
<h1>Zacni ucit</h1>
<ul>
<li><a href="/admin/">Administrace</a></li>
<li><a href="/" onclick="window.location.port=7474; return false;">Neo4j konzole</a></li>
<li><a href="/... |
import time
from castero.player import Player, PlayerDependencyError
class MPVPlayer(Player):
"""The MPVPlayer class.
"""
NAME = "mpv"
def __init__(self, title, path, episode) -> None:
"""Initializes the object.
Overrides method from Player; see documentation in that class.
... |
# coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# 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 applicab... |
import retrieve
import validation
from time_functions import time_delay
from selenium.webdriver import ActionChains
def like_pic(browser):
heart = retrieve.like_button(browser)
time_delay()
if validation.already_liked(heart):
heart.click()
def like_pic_in_feed(browser, number = 1):
loop = 1
wh... |
import pytest
from prometheus_ecs_discoverer import toolbox
def test_chunk_list_with_even_size():
big_list = list(range(100))
chunks = toolbox.chunk_list(big_list, 10)
assert len(chunks) == 10
for chunk in chunks:
assert len(chunk) <= 10
def test_chunk_list_with_uneven_size():
big_list ... |
import csv
import os
import shutil
import sys
import tempfile
import unittest
from pyspark import StorageLevel
from pyspark.sql import Row
from sourced.ml.utils import create_engine, SparkDefault
from sourced.ml.transformers import ParquetSaver, ParquetLoader, Collector, First, \
Identity, FieldsSelector, Reparti... |
# Licensed under an MIT open source license - see LICENSE
"""
SCOUSE - Semi-automated multi-COmponent Universal Spectral-line fitting Engine
Copyright (c) 2016-2018 Jonathan D. Henshaw
CONTACT: henshaw@mpia.de
"""
import numpy as np
import itertools
import matplotlib.pyplot as plt
import sys
from matplotlib import ... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.md')).read()
CHANGES = open(os.path.join(here, 'CHANGES.md')).read()
requires = [
'paste',
'pyramid>=1.0.2',
'pyramid_jinja2==2.5',
'pyramid_debugtoolbar==2... |
"""
ctr
~~~
This module provides an implementation for the Counter (CTR)
block cipher mode of operation.
Author: Kinshuk Vasisht
Dated : 12/03/2022
"""
import typing
import secrets
from .core import ModeOfOperation
from .padding import PaddingMode
from .utils import xor
class CounterMode(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.