content stringlengths 5 1.05M |
|---|
import os
from signal import pause
from pirotohomie.logging import setup_logging
import click
import yaml
def get_config_form_file(filename='config.yaml'):
if not os.path.isfile(filename):
raise ValueError('Config file %r does not exist!' % filename)
with open(filename, 'r') as f:
return yaml.... |
import json
import requests
shashlik = input("Вставь хеш\n>> ")
i = 0
while True:
r1 = requests.get("http://www.multiliker.com/service/view/?hash=" + shashlik)
middle = (json.loads(r1.text))["picture"]
print(middle)
headers = {"Content-Type": "application/x-www-form-urlencoded"}
payload = (
... |
from django import forms
from .models import Profile
class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(max_length=100,widget=forms.PasswordInput)
class Resetform(forms.Form):
password = forms.CharField(max_length=100, widget=forms.PasswordInput)
confirm... |
# Copyright 2020 Google LLC
#
# 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 writing, ... |
import pytest
from featureflags.evaluations.clause import Clause
from featureflags.evaluations.constants import (CONTAINS_OPERATOR,
ENDS_WITH_OPERATOR,
EQUAL_OPERATOR,
EQUAL_S... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import torch.nn as nn
BN_MOMENTUM = 0.1
logger = logging.getLogger(__name__)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes... |
# terrascript/data/mrcrilly/awx.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:12:44 UTC)
import terrascript
class awx_credential(terrascript.Data):
pass
class awx_credential_azure_key_vault(terrascript.Data):
pass
class awx_credentials(terrascript.Data):
pass
__all__ = [
"awx... |
# -*- coding: utf-8 -*-
# file: main.py
# author: JinTian
# time: 11/03/2017 9:53 AM
# Copyright 2017 JinTian. 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
#
# htt... |
import logging
from unittest.mock import patch
from dotenv import load_dotenv
from util.logger import init_logger, get_logger
load_dotenv()
job_id = 'job_123'
@patch.dict('os.environ', {'JOB_ID': job_id})
def test_init_logger():
assert job_id not in logging.root.manager.loggerDict, 'job id is not initialized'
... |
import requests
import json
from flask import Flask,jsonify
import os
import logging
app = Flask(__name__)
logger = logging.getLogger('Zabbix_integrator')
logger.setLevel({"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
"WARNING": logging.WARNING,
"ERROR": logging.ERR... |
import logging
import os, sys
import splunk
import splunk.entity
import splunk.Intersplunk
import json
logger = logging.getLogger(__name__)
splunkhome = os.environ['SPLUNK_HOME']
sys.path.append(os.path.join(splunkhome, 'etc', 'apps', 'trackme', 'lib'))
import rest_handler
import splunklib.client as client
class Tr... |
from typing import TYPE_CHECKING, Optional, Union, Dict, Any
from dis_snek.client.const import MISSING, Absent
from dis_snek.client.utils.attr_utils import define, field
from dis_snek.client.utils.converters import optional as optional_c
from dis_snek.client.utils.converters import timestamp_converter
from dis_snek.mo... |
from amadeus.client.decorator import Decorator
from amadeus.safety.safety_rated_locations._by_square import BySquare
class SafetyRatedLocations(Decorator, object):
def __init__(self, client):
Decorator.__init__(self, client)
self.by_square = BySquare(client)
def get(self, **params):
'... |
##########################################################################
#
# pgAdmin 4 - PostgreSQL Tools
#
# Copyright (C) 2013 - 2020, The pgAdmin Development Team
# This software is released under the PostgreSQL Licence
#
#########################################################################
from flask_wtf.csr... |
#---------------------------------------------------------------------------------------------------
#
#---------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------
"""
Class: Pa... |
arquivo = open('db.csv','r')
linhas = arquivo.readlines()
for linha in linhas:
palavras = linha.split(',')
arquivo.close()
|
from discord import Embed, Member
from discord.ext import commands
from discord.utils import get
from random import choice, randint
from requests import get as rget
class Random(commands.Cog, name='Random'):
"""
Utilisable par tout le monde et contient des "jeux" et de l'aléatoire.
"""
def __init__(se... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import cv2
import time
import ctypes
import numpy as np
import routines as myr
def fortranize(m):
return np.array(m,order='F')
def ccf(m,n_p):
(npixr,mean,var) = myr.make_standard(m,0)
m = fortra... |
# -*- coding: utf-8 -*-
"""The task-based multi-process processing engine."""
import os
import shutil
import tempfile
import redis
from plaso.lib import definitions
from plaso.multi_process import engine
from plaso.storage import factory as storage_factory
from plaso.storage import merge_reader
from plaso.storage.re... |
from west.commands import WestCommand
from west import log
from west import util
from pathlib import Path
import os
import subprocess
class Yocto(WestCommand):
def __init__(self):
super().__init__(
"yocto",
"",
None)
self.top_dir = util.west_topdir()
sel... |
import sys
from copy import deepcopy as copy
from hqca.operators import *
def InverseJordanWignerTransform(op):
'''
transforms a Pauli string into a Fermionic Operator
'''
Nq = len(op.s)
pauli = ['I'*Nq]
new = Operator()
new+= FermiString(
coeff=op.c,s='i'*Nq)
# define pauli... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 Intel Corporation
#
# 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 app... |
# (C) unresolved-external@singu-lair.com released under the MIT license (see LICENSE)
import datetime
import sys
import time
from multiprocessing import Queue # hack
import common
class cmd_log:
def log(self, message, info = False):
print(message, file = sys.stdout if info else sys.stderr)
def log_ln(self... |
from numpy.core.fromnumeric import size
from text_models import Vocabulary
from collections import Counter
import numpy as np
# Collocations
date = dict(year=2022, month=1, day=10)
voc = Vocabulary(date, lang='En')
bigrams = Counter({k: v for k, v in voc.voc.items() if k.count("~")})
co_occurrence = np.zeros((5, 5))
... |
"""
ptime.format
~~~~~~~~~~~~
:copyright: (c) 2013 by Marat Ibadinov.
:license: MIT, see LICENSE for more details.
"""
import re
class FormatError(Exception):
pass
class Format(object):
TEMPLATES = {
# day #
'd': (r'\d{2}', 'day'),
'D': (r'[a-z]{... |
# coding=utf-8
from sqlalchemy import create_engine, Column, String, DATETIME, DATE, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import redis
import pymysql
pymysql.install_as_MySQLdb()
# 初始化数据库连接:
engine = create_engine('mysql+pymysql://root:12345678@localhost... |
def splitInteger(num, parts):
""" split_integer == PEP8 (forced mixedCase by CodeWars) """
quo, rem = divmod(num, parts)
if rem == 0:
return [quo] * parts
return [quo if a > rem else quo + 1 for a in xrange(parts, 0, -1)]
|
import logging
from zentral.core.events import event_cls_from_type, register_event_type
from zentral.core.events.base import BaseEvent, EventMetadata, EventRequest
logger = logging.getLogger('zentral.contrib.inventory.events')
ALL_EVENTS_SEARCH_DICT = {"tag": "machine"}
class EnrollmentSecretVerificationEvent(Base... |
from .components import *
from .window import *
from .factory import * |
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import views
from author.models import *
from Followers.models import *
from posts.models import *
from comment.models import *
from logging import exception
from django.http import response
from django.http import request
... |
from __future__ import print_function # For printing no newline
import sympy
from sympy import Rational
from sympy import factorial
import numpy as np
def Taylor( n, dx ):
"""Compyute n terms in the Taylor expansion for a function centered 'dx'
away from where the terms will be evaluated."""
return [ (d... |
r"""
===============================================================================
Submodule -- throat_shape_factor
===============================================================================
"""
import scipy as _sp
def compactness(geometry, throat_perimeter='throat.perimeter',
throat_area='thr... |
# coding=utf-8
import unittest
from mem_dixy.tag.alphabet import logical
from mem_dixy.Unicode.U0000 import *
from enum import Enum
class enum_comparison(Enum):
lt = 0,
le = 1,
eq = 2,
ne = 3,
ge = 4,
gt = 5,
sa = 6,
sn = 7
class operator():
pass
class comparison(operator):
... |
from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator
from orchids.models import Orchid, Greenhouse
class NumberForm(forms.Form):
number = forms.IntegerField(label='Number of days to simulate', initial=1,
validators=[MinValueValidator(0),... |
import pytorch_lightning as pl
import sys
sys.path.append('./models')
import os
import optuna
from optuna.integration import PyTorchLightningPruningCallback
from pytorch_lightning import Trainer, seed_everything
from argparse import ArgumentParser
from pytorch_lightning.loggers import TensorBoardLogger, TestTubeLogger... |
import requests
from bs4 import BeautifulSoup
import re
import os
import pandas as pd
def get_useful_columns(result):
"""
Filter csv columns to make use of:
GD - goal difference, FTHG (Full time home goals), HST (Home shots on target)
B365H (Odds favouring home team in the match by Bet365),... |
import os
if os.name == 'nt':
os.environ['basedir_a'] = 'F:/Temp2/'
else:
os.environ['basedir_a'] = '/gpfs/home/cj3272/tmp/'
import luccauchon.data.C as C
import PIL
import keras
from samples.amateur.config import AmateurInference
from os import listdir
from os.path import isfile, join
from sklearn.model_selec... |
#Import modules for main GUI program
import vienna_config_windows
from vienna_config_windows import gs_path, find_gs
import os, sys, subprocess, shutil, time
import tkinter
from tkinter import *
from tkinter import messagebox
from tkinter.filedialog import askopenfile
from PIL import Image, ImageTk, EpsImagePlu... |
#coding:utf-8
import os
import requests
from PIL import Image
import math
def imagesget():
os.mkdir('images')
count=0
while True:
img=requests.get('http://wsxk.hust.edu.cn/randomImage.action').content
with open('images/%s.jpeg'%count,'wb') as imgfile:
imgfile.write(img)
... |
from dictish import Dictish
AN_EMPTY_DICTISH = Dictish()
LETTER_TO_NUMBER = Dictish([("a", 1), ("b", 2), ("c", 3)])
def test_an_empty_dictish_is_falsey():
assert bool(AN_EMPTY_DICTISH) is False
def test_a_populated_dictish_is_truthy():
assert bool(LETTER_TO_NUMBER) is True
|
# -*- coding: utf-8 -*-
"""
Created on 07 Mar 2021 14:02:18
@author: jiahuei
"""
from . import file
from . import image
from . import misc
from . import video
|
#!/usr/bin/env python3
class Solution:
def circularArrayLoop(self, nums):
l = len(nums)
for i in range(l):
print(f'i = {i}')
head = slow = fast = i
while True:
slow = (slow+nums[slow])%l
fast1 = (fast+nums[fast])%l
... |
"""
Load pp, plot and save
8km difference
"""
import os, sys
#%matplotlib inline
#%pylab inline
import matplotlib
matplotlib.use('Agg')
# Must be before importing matplotlib.pyplot or pylab!
from matplotlib import rc
from matplotlib.font_manager import FontProperties
from matplotlib import rcParams
from mpl_to... |
# Generated by Django 2.0.5 on 2018-06-07 21:43
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('graduation_design', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='dissertation... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
class LogDestinationPolicy(pulumi.CustomResource):
"""
Provides a CloudWatch Logs destinat... |
#!/usr/bin/env python
# import some utils.
import rospy
from std_msgs.msg import Float64
class InterpolateThrottle:
def __init__(self):
car_name = rospy.get_param("~car_name", "/car")
# Allow our topics to be dynamic.
self.rpm_input_topic = rospy.get_param(
"~rpm_input_topic"... |
from django import template
from django_extras.utils import humanize
register = template.Library()
@register.filter(is_safe=True)
def describe_seconds(value):
"""
Convert a seconds value into a human readable (ie week, day, hour) value.
:param value: integer value of the number of seconds.
:return: ... |
# -*- coding: utf-8 -*-
# --------------------------------------
# @Time : 2021/5/12$ 12:12$
# @Author : Qian Li
# @Email : 1844857573@qq.com
# @File : network.py
# Description : details(i.e., online network,online projector network, online predictor,classifier, target network, target projector,) for self-supe... |
from datetime import datetime
from PIL import Image
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.timezone import now
from dj... |
from __future__ import absolute_import
from tastypie.authentication import Authentication
from tastypie.authorization import Authorization
from tastypie.resources import ModelResource
from tastypie_sorl_thumbnail.fields import ThumbnailField
from .models import Photo
class PhotoResource(ModelResource):
thumbnai... |
"""
Settings,
As for the database, look for ../sql_orm/database.py
"""
#DEBUG/TEST MODE: This allows HTTP connection instead of HTTPS
TEST_MODE = True
API_PORT = 8000
# These are used only if the TEST_MODE is disabled
SSL_CERT_LOCATION = "path"
SSL_KEY_LOCATION = "path"
SSL_CA_LOCATION = "path"
# JWT access setting... |
from django.contrib import admin
from django.urls import path
from pag.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home, name='home')
]
|
import glob
import os
from mkgen.utils import flat
default_config = {
"languages": [
{"name": "python", "extensions": [".py"], "interpreter": "$(PYTHON)"},
{"name": "R", "extensions": [".R", ".r"], "interpreter": "$(R)"},
],
"src_paths": ["src"],
}
def get_interpreter(config, file):
... |
## https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
## given a list that's already sorted, find the indices that bound
## a given element (or -1, -1 if that element is not in the list).
## goal is to this in O(log(n)), i.e. to take advantage of the fact
## that the list is sorted.... |
# Mirror JNT & orient L>R
import maya.cmds as mc
def doMirrorJnt(side='L'):
sel = mc.ls(sl=1)
if side=='R':
side=['R_','L_']
else:
side=['L_','R_']
for each in sel:
right = each.replace(side[0], side[1], 1)
mc.duplicate(each, n=right)
try:
mc.parent... |
import lsst.pipe.base as pipeBase
import lsst.pipe.base.connectionTypes as cT
from lsst.ip.isr import Defects
from .eoCalibBase import EoDetRunCalibTaskConfig, EoDetRunCalibTaskConnections, EoDetRunCalibTask
__all__ = ["EoDefectsTaskConfig", "EoDefectsTask"]
class EoDefectsTaskConnections(EoDetRunCalibTaskConnect... |
import unittest
import sys
sys.path.append('./')
solutions = __import__('solutions.141_linked_list_cycle', fromlist='*')
helper = __import__('utils.helper', fromlist='*')
class Test(unittest.TestCase):
def test_hasCycle(self):
s = solutions.Solution()
head = helper.constructListNode([1, 2])
... |
import logging
from bglib.flow.decision import Decision
class PickBetweenPlayers:
UntilEmpty = 1
OneEach = 2
def __init__(self, choice_pool, pick_order, mode, remove_picked_choices=True):
if len(choice_pool) < len(pick_order):
raise ValueError('Not enough choices ({}) to make {} picks... |
import unittest
import datetime
import numpy as np
import pandas as pd
import pytz
import time
from ibis.impala.tests.common import IbisTestEnv, ImpalaE2E, connect_test
from ibis.tests.util import assert_equal
import ibis
import ibis.common as com
import ibis.config as config
import ibis.expr.datatypes as dt
import ... |
# pylint: disable=C0111,R0903
"""Displays APT package update information (<to upgrade>/<to remove >)
Requires the following packages:
* aptitude
contributed by `qba10 <https://github.com/qba10>`_ - many thanks!
"""
import re
import threading
import core.module
import core.widget
import core.decorators
import ... |
from couchbase_helper.documentgenerator import SDKDataLoader
from lib.membase.api.rest_client import RestConnection
from lib.testconstants import STANDARD_BUCKET_PORT
from pytests.eventing.eventing_constants import HANDLER_CODE
from pytests.eventing.eventing_base import EventingBaseTest, log
from membase.helper.cluster... |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# ... |
# SPDX-License-Identifier: MIT
# (c) 2019 The TJHSST Director 4.0 Development Team & Contributors
from django.contrib import admin
from .models import SiteRequest
# Register your models here.
admin.site.register(SiteRequest)
|
import os
from github import Github
import yaml
g = Github(os.getenv('GITHUB_TOKEN'))
GITHUB_USER = 'MachineUserHallicopter/'
def push_file_to_github(filename, content, repo):
repo = g.get_repo(GITHUB_USER + repo)
print(repo.create_file(path=filename, content=content, message="adds: autocommit new post", bra... |
import gym
import numpy as np
import matplotlib.pyplot as plt
def policy(state, theta):
"""
Parameters
----------
state : numpy array
contains state of cartpole environment.
theta : numpy array
contains parameters of linear features
Returns
-------
numpy array
... |
from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('page/<int:page>/', views.PostListView.as_view(), name='post_list'),
path('category/<slug:category>/', views.PostCategoryListView.as_view(), name='post_catego... |
import numpy as np
from emulator.main import Account
from agent.agent import Agent
env = Account()
state = env.reset()
print(state.shape)
agent = Agent([5, 50, 58], 3)
# state = np.transpose(state, [2, 0, 1])
# state = np.expand_dims(state, 0)
# action = agent.get_epsilon_policy(state)
# reward, next_state, done = e... |
from PySide2.QtCore import Signal, Slot, Qt
from PySide2.QtWidgets import QMessageBox, QTabWidget, QHBoxLayout
import numpy as np
from hexrd.ui.constants import OverlayType, PAN, ViewType, ZOOM
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.image_canvas import ImageCanvas
from hexrd.ui.image_series_toolb... |
# -*- coding: utf-8 -*-
import pandas as pd
import pytest
from bio_hansel.qc import QC
from bio_hansel.subtype import Subtype
from bio_hansel.subtype_stats import SubtypeCounts
from bio_hansel.subtyper import absent_downstream_subtypes, sorted_subtype_ints, empty_results, \
get_missing_internal_subtypes
from bio_... |
import os
import sys
import argparse
import time
import schedule
import json
from mailattachmentsarchiver import mailattachmentsarchiver as maa_app
def generateIMAP(file,addr,port,user,pwd):
"""Generates IMAP credentials from sensitive environmental values.
:param file: File to output.
:param addr: Email... |
import os
from PIL import Image
def alpha_to_color(image):
image = image.convert('RGBA')
image.load()
background = Image.new('RGB', image.size, (255, 255, 255))
background.paste(image, mask=image.split()[3])
return background
if __name__ == '__main__':
for dir_name in ['dark chocolate', 'white... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\complex\roommate_situation.py
# Compiled at: 2019-02-13 18:34:49
# Size of source mod 2**... |
"""
MIT License
Sugaroid Artificial Inteligence
Chatbot Core
Copyright (c) 2020-2021 Srevin Saju
Copyright (c) 2021 The Sugaroid Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without re... |
import numpy as np
def feature_normalize(X, y):
# You need to set these values correctly
x_mean = X.mean()
y_mean = y.mean()
x_std = X.std()
y_std = y.std()
X_norm = (X - x_mean) / x_std
y_norm = (y - y_mean) / y_std
mu = np.array([x_mean['Size'], x_mean['Bedrooms'], y_mean['Price']]... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
# Copyright (c) Ostap developers.
# =============================================================================
# @file test_fitting_components.py
# Test module
# - It tests various multicom... |
#!/usr/bin/env python
# encoding: utf-8
"""
test_api
----------------------------------
Tests for `dibs.api` module.
"""
from dibs.models import Item
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
# from django.core.urlresolvers import reverse
from rest_framework impo... |
#!/usr/bin/env python
# Copyright 2018 Battelle Energy Alliance, LLC
import subprocess
import getpass
import argparse
import sys
import re
import textwrap
from argparse import RawTextHelpFormatter
import os
import hashlib
from base64 import encodestring as encode
from base64 import decodestring as dec... |
""" by Luigi Acerbi, Shan Shen and Anne Urai
International Brain Laboratory, 2019
#TODO: Anne
"""
import numpy as np
class DataSet:
""" Object containing data that can be preprocessed.
Inputs: dataframe # pandas
Methods: preprocess
"""
class TrialData:
def __init__(self, data, meta_data=dict(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file makes the Supplementary Figure 5, it needs the filter_SRAG.py
results to run.
"""
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
data_init = pd.read_csv('../Data/SRAG_filtered_morb.csv')
data_init = data_init[(data_i... |
from decimal import Decimal
from tests import BaseXchangeTestCase
from xchange.models.base import (
Ticker, OrderBook
)
class TickerTestCase(BaseXchangeTestCase):
def test_ticker(self):
ticker = Ticker({
'ask': '9314.65',
'bid': '100.51',
'high': '9480',
... |
"""
turbine_costsse.py
Created by Katherine Dykes 2012.
Copyright (c) NREL. All rights reserved.
"""
from openmdao.main.api import Component, Assembly
from openmdao.main.datatypes.api import Array, Float, Bool, Int, Enum
import numpy as np
from fusedwind.plant_cost.fused_tcc import FullTurbineCostModel, FullTCCAggre... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from .managers import UserManager
class User(AbstractUser):
"""Custom User model for authentication with email as identifier."""
USERNAME_FIELD = "email"
REQUIRED_FIELD... |
import os
from typing import Any
from typing import cast
from typing import Dict
from typing import Iterable
from ...exceptions import InvalidFile
from ..plugins.util import get_plugins_from_file
def upgrade(baseline: Dict[str, Any]) -> None:
for function in [
_migrate_filters,
_rename_high_entro... |
somaidade=0
madiaidade=0
maioridadehomem=0
nomevelho=''
totmulher20=0
for p in range(1, 5):
print('------{}°pessoa------'.format(p))
nome=str(input('Nome:')).strip()
idade=int(input('Idade:'))
sexo=str(input('Sexo[M/F]:')).strip().upper()
somaidade+=idade
if p==1 and sexo in 'M':
... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import image as mpimg
img = cv2.imread('input/forest.jpeg')
cv2.imshow('foreste',img)
# Histograma da imagem em tons de cinza
plt.hist(img.ravel(),256,[0,256])
plt.xlabel('Tonalidade de Cinza')
plt.ylabel('Quantidade de Pixels')
plt.s... |
"""This is an auto-generated file. Modify at your own risk"""
from typing import Awaitable, Any, Callable, Dict, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from cripy import ConnectionType, SessionType
__all__ = ["Overlay"]
class Overlay:
"""
This domain provides various functionality relate... |
import pandas as pd
import matplotlib.pyplot as plt
from math import ceil
def event_count_plot(qa_data_path, event_name,**kwargs):
event_data_path = qa_data_path + '_' + event_name + '.csv'
qa_data_df=pd.read_csv(event_data_path)
plt.figure(figsize=(6, 4))
plt.plot('event_date', 'n_event', data=qa_data... |
"""
Author: Rayla Kurosaki
File: phase4_print_to_workbook.py
Description: This file contains the functionality to print the student's
transcript on a Microsoft Excel Workbook in a pretty and easy to
read format.
"""
from openpyxl import styles
from openpyxl.styles import Alignment, Font
fro... |
import fastapi
from app.schemas.health import HealthOutSchema
router = fastapi.APIRouter()
@router.get("/", response_model=HealthOutSchema)
def health():
return HealthOutSchema(status="OK")
|
import discord
import sys
import os
import io
import asyncio
import json
from discord.ext import commands
class Mod:
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.has_permissions(administrator = True)
async def msg(self, ctx, user: discord.Mem... |
# Copyright (c) ZenML GmbH 2021. 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:
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... |
try:
import _persistence_module
except ImportError as err:
class _persistence_module:
@staticmethod
def run_persistence_operation(persistence_op_type, protocol_buffer, save_slot_id, callback):
callback(save_slot_id, False)
return False
class PersistenceOpType:
kPer... |
from tests.compat import unittest, mock
from tests.test_search_exact import TestSearchExactBase
from tests.test_substitutions_only import TestSubstitionsOnlyBase
from tests.test_levenshtein import TestFindNearMatchesLevenshteinBase
from fuzzysearch import find_near_matches, Match
from fuzzysearch.common import FuzzySe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 6 11:34:06 2020
@author: satish
"""
import numpy as np
import os
import sys
import argparse
import random
import torch
import torch.nn as nn
from torch.autograd import Variable, gradcheck
class MSE_loss:
def __init__(self):
print("Initializing M... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from multiselectfield import MultiSelectField
from django.conf import settings
class CustomUser(AbstractUser):
# user for chat id for current
gender = models.CharField(max_length=26,choices=[('Male', 'Male'), ('Female', 'Fe... |
import json
import os, sys
sys.path.append('/opt/airflow/')
from dags.connectors.sf import _write_to_stage, sf
def _opened_vaults(manager, **setup):
q = f"""SELECT outputs[1].value::string, outputs[0].value
FROM {setup['db']}.staging.manager
WHERE function = 'open'; """
opened_vaults_list = sf.execu... |
'''
QBI Batch Crop APP: Batch cropping of high resolution microscopy images
QBI Software Team
*******************************************************************************
Copyright (C) 2018 QBI Software, The University of Queensland
This program is free software; you can redistribute it and/or... |
import os
import zipfile
path = 'horse-or-human'
local_zip = './data/horse-or-human.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('./data/horse-or-human')
local_zip = './data/validation-horse-or-human.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('./data/validation-horse-or-... |
"""Tests the appimage activity."""
from rever import vcsutils
from rever.logger import current_logger
from rever.main import env_main
from pathlib import Path
REVER_XSH = """
$ACTIVITIES = ['appimage']
"""
SETUP_FILE = """
import setuptools
setuptools.setup(
name="rever-activity-appimage-test",
version="42.1.... |
#!/usr/bin/python3
def main():
print(LatticePath(20,20))
def LatticePath(m,n, memo={}):
if m == 0 or n == 0:
return 1
if (m, n) in memo.keys():
return memo[(m, n)]
result = LatticePath(m - 1, n) + LatticePath(m, n - 1)
memo[(m , n)] = result
return result
if __name__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.