id int64 0 10k | text stringlengths 186 4k | length int64 128 1.02k |
|---|---|---|
200 | import numpy as np
import cv2 as cv
def get_rgb(img):
shape = np.shape(img)
size = shape[0] * shape[1]
rgb = [0, 0, 0]
for row in img:
for cell in row:
for color in range(3):
rgb[color] = rgb[color] + (cell[color]/255)
rgb = [color/size for color in rgb]
return rgb
def get_hsv(img):
shape = np.shape(i... | 265 |
201 | """Package for parsing and compiling Python source code
There are several functions defined at the top level that are imported
from modules contained in the package.
parse(buf, mode="exec") -> AST
Converts a string containing Python source code to an abstract
syntax tree (AST). The AST is defined in compiler... | 243 |
202 |
import torch.nn as nn
import abc
class ADType(abc.ABC): ...
class AdversarialDefensiveModel(ADType, nn.Module):
"""
Define some basic properties.
"""
def __init__(self):
super(AdversarialDefensiveModel, self).__init__()
self.adv_training = False
self.attacking = False
... | 850 |
203 | from setuptools import setup, find_packages
with open("requirements.txt") as f:
install_requires = f.read().strip().split("\n")
# get version from __version__ variable in custom_app/__init__.py
from custom_app import __version__ as version
setup(
name="custom_app",
version=version,
description="desc",
author="m... | 159 |
204 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | 228 |
205 | import os
import typing as t
from ._internal.models.base import MODEL_NAMESPACE, PICKLE_EXTENSION, Model
from ._internal.types import MetadataType, PathType
from .exceptions import MissingDependencyException
try:
import evalml
import evalml.pipelines
except ImportError:
raise MissingDependencyException("e... | 621 |
206 | # A step by step example on using SVM with sklearn
# Authors: Wahab Hamou-Lhadj, Fatima AitMahammed, Mohammed Shehab
# SRT Lab
import pandas as pd
from sklearn import svm
from sklearn import metrics
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics... | 750 |
207 | import requests
from pprint import pprint
import time
i = 0
url = "https://deckofcardsapi.com/api/deck/new/shuffle/"
querystring = {"deck_count":"6"}
headers = {
'Cache-Control': "no-cache",
'Postman-Token': "2f173ba1-10b3-4750-b499-dbf083901e7f"
}
response = requests.request("GET", url, headers=header... | 347 |
208 | from rest_framework import serializers, viewsets
from brambling.api.v1.permissions import IsAdminUserOrReadOnly
from brambling.models import EnvironmentalFactor
class EnvironmentalFactorSerializer(serializers.ModelSerializer):
link = serializers.HyperlinkedIdentityField(view_name='environmentalfactor-detail')
... | 177 |
209 | from __future__ import division
from pyproj import Proj
from resippy.photogrammetry.dem.abstract_dem import AbstractDem
import numpy as np
import resippy.photogrammetry.crs_defs as crs_defs
class ConstantElevationDem(AbstractDem):
def __init__(self, elevation=0):
self.elevation = elevation
def get_e... | 543 |
210 | """
Slixmpp: The Slick XMPP Library
Copyright (C) 2020 Mathieu Pasquet
This file is part of Slixmpp.
See the file LICENSE for copying permission.
"""
from slixmpp.plugins.base import register_plugin
from slixmpp.plugins.xep_0377.stanza import Report, Text
from slixmpp.plugins.xep_0377.spam_reporting ... | 134 |
211 | # Copyright 2019 ducandu GmbH, 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 applicable law or ... | 644 |
212 | from vae import VAE
from latents import DiagonalGaussianLatent
from priors import IsoGaussianPrior
from likelihoods import DiagonalGaussianLikelihood
from keras.layers import Input, Dense
from data.my_mnist import img_pixels as mnist_pixels
import os
def fit_vae(vae, x_train, x_test=None, epochs=100, batch=100, weigh... | 800 |
213 | """
Helper to get packages list and removing comments
"""
from os.path import isfile, isdir
from os import listdir
from lib.colorp import printc
def get_packages_list(usepath):
"""
Read a file / a dir and get package.use directives
"""
lines = []
if isfile(usepath):
try:
with op... | 508 |
214 | #!/usr/bin/python
import RPi.GPIO as G
import time
import os
import signal
import sys
import threading
import subprocess
print "switchhello started."
COUNT = 5
# PIN_LED = 17
PIN_LED = 21
SWITCH_SOUND = 13
# SWITCH_MAP = {
# 18:1,
# 27:2,
# 22:3,
# 23:4
# }
# SWITCH_MAP = {
# 24:5,
# 10:6,
# 9:7,
# 25:8
#... | 887 |
215 | #!/usr/bin/env python
"""
lgc/main.py
"""
import json
import numpy as np
from scipy.stats import spearmanr
PNIB_THRESH = 0.999
ISTA_THRESH = 0.999
# --
# Helpers
def compute_score(targets, scores):
assert targets.shape == scores.shape
n = scores.shape[1]
return min([spearmanr(scores[:,i], targets[:... | 594 |
216 | _base_ = './yolov3_d53_mstrain-608_273e_coco.py'
# dataset settings
#改个resize需要把train_pipeline所有配置申明一遍吗?
img_norm_cfg = dict(mean=[0, 0, 0], std=[255., 255., 255.], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(
type='Expand',
... | 754 |
217 | # -*- coding: utf-8 -*-
from aiida.engine import ToContext, WorkChain, run
from child import ChildWorkChain
class SimpleParentWorkChain(WorkChain):
@classmethod
def define(cls, spec):
super(SimpleParentWorkChain, cls).define(spec)
spec.expose_inputs(ChildWorkChain)
spec.expose_outputs... | 275 |
218 | import os.path as op
from cognigraph.nodes import sources, outputs
from cognigraph.pipeline import Pipeline
import logging
import time
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s:%(name)-17s:%(levelname)s:%(message)s')
cur_dir = '/home/dmalt/Code/python/cogni_submodules' # < --... | 372 |
219 | # Задача 3. Вариант 6.
# Напишите программу, которая выводит имя "Самюэл Ленгхорн Клеменс", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире.
# Velyan A. S.
# 27.05.2016
print("Герой нашей сегодняшней программы - Сэмюэл Ленгхор... | 504 |
220 | # autos.py
class Auto():
def __init__(self, make, model, year, color, num_wheels):
self.make = make
self.model = model
self.year = year
self.color = color
self.num_wheels = num_wheels
def drive(self):
print("WE ARE DRIVING", self.model)
def advertise(self):... | 485 |
221 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-10-12 00:06
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('billing', '0005_card_default'),
]
operations = [
... | 543 |
222 | import sys
from .commands import commands_list
def print_help () :
print("spyware_server_scripts [command] [cmd-arg]")
print("[*] Commands : ")
for command in commands_list :
print(f"\t {command.name} - {command.description}")
def run_command (name, *args) :
for command in commands_list :
... | 290 |
223 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 343 |
224 | """
Plot terminal states
--------------------
This example shows how to compute and plot the terminal states of the cell-state transition.
CellRank can be applied to any cell-state transition, be it differentiation, regeneration, reprogramming or other.
"""
import cellrank as cr
adata = cr.datasets.pancreas_preproc... | 534 |
225 | # -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
import numpy as np
import matpl... | 775 |
226 | # Generated by Django 3.2.6 on 2021-08-19 18:58
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('receitas', '0004_auto_20210819_1448'),
]
operations = [
migrations.AddField(
model_name='receita',
n... | 314 |
227 | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectSettings.productionSetting')
try:
from django.core.management import execute_from_command_lin... | 247 |
228 | import threading
from dataflowfx.common import *
class DataProcessingGroup:
def __init__(self) -> None:
self.dpMap = dict()
pass
def getProcessorMapCounts(self):
procCounts = { k : len(v) for k, v in self.dpMap.items() }
return procCounts
def addDataProcessor(self, dataPro... | 699 |
229 | from envirophat import weather
from envirophat import light
import datetime
import json
d = datetime.datetime.now().isoformat()
#d = datetime.now(timezone.utc).astimezone().isoformat()
#print(d)
#print(weather.temperature())
#print(weather.pressure(unit='hPa'))
#print("tmp=" + str(weather.temperature()))
#print("pre... | 411 |
230 | from torch import nn
from mmdet.utils import build_from_cfg
from .registry import (BACKBONES, NECKS, ROI_EXTRACTORS, SHARED_HEADS, HEADS,
LOSSES, DETECTORS)
def build(cfg, registry, default_args=None):
if isinstance(cfg, list):
modules = [
build_from_cfg(cfg_, registry,... | 436 |
231 | from tensorboard_logger import configure, log_value
import os
class FileLogger:
"Log text in file."
def __init__(self, path):
self.path = path
def log_string(self, file_name, string):
"""Stores log string in specified file."""
text_file = open(os.path.join(self.path, file_name+".lo... | 605 |
232 | import pytest
from pinpointtwitter import app
@pytest.fixture()
def pinpoint_event():
""" Generates A Pinpoint Event"""
return {
"Message": {},
"ApplicationId": "71b0f21869ac444eb0185d43539b97ea",
"CampaignId": "54115c33de414441b604a71f59a2ccc3",
"TreatmentId": "0",
"ActivityId... | 650 |
233 | # © Cyril C Thomas
# https://t.me/cyril_c_10
import os
class Config(object):
BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "")
API_ID = int(os.environ.get("APP_ID", ))
API_HASH = os.environ.get("API_HASH", "")
LOG_CHANNEL = int(os.environ.get("LOG_CHANNEL", -100))
MONGODB_URI = os.environ.g... | 219 |
234 | # Copyright (c) 2020 PaddlePaddle 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 applic... | 863 |
235 | from math import radians, sin, cos, tan
angulo = float(input('Digite o ângulo que você deseja: '))
seno = sin(radians(angulo))
cosseno = cos(radians(angulo))
tangente = tan(radians(angulo))
print('O ângulo de {} tem o SENO de {:.2f}'.format(angulo, seno))
print('O ângulo de {} tem o COSSENO de {:.2f}'.format(angulo,... | 169 |
236 | # Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.front.common.partial_infer.concat import concat_infer
def concat_ext(attrs):
node_attrs = {
'type': 'Concat',
'axis': attrs.int("dim", 1),
'infer': concat_infer
}
return node_a... | 142 |
237 | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist, Point, PoseStamped
from nav_msgs.msg import Path
from std_msgs.msg import Float32MultiArray
import sys
import numpy as np
from pid_control.msg import points
rospy.init_node('pub_point', anonymous = True)
class Publish():
def __init__(self):
... | 870 |
238 | from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(
name='spaghetti-graph',
version='1.0.1',
description='Graph function level Python dependencies to understand and fix spaghetti code',
long_description=readme(),
classifiers=[
'Licen... | 433 |
239 | # Generated by Django 3.1.3 on 2020-11-29 04:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("secateur", "0037_auto_20200927_1531"),
]
operations = [
migrations.AddField(
model_name="user",
name="screen_name",
... | 186 |
240 | import numpy as np
def fold(f, l, a):
return a if (len(l) == 0) else fold(f, l[1:], f(a, l[0]))
def f_and(x, y):
return x and y
def f_or(x, y):
return x or y
def parameters_allocation_check(module):
parameters = list(module.parameters())
return fold(f_and, parameters, True) or not fold(f_or, ... | 444 |
241 | import operator
import math
def squared_distance(p, q):
'''Returns the squared distance between points p and q'''
(px, py), (qx, qy) = p, q
return (px - qx)**2 + (py - qy)**2
def closest_pair(points):
'''
Input: points | tuple of at least 2 points of the form (x, y)
Output: smallest squared d... | 608 |
242 | from xml.etree.ElementTree import Element, SubElement, Comment
from ElementTree_pretty import prettify
top = Element('top')
comment = Comment('Generated for PyMOTW')
top.append(comment)
child = SubElement(top, 'child')
child.text = 'This child contains text.'
child_with_tail = SubElement(top, 'child_with_tail')
chi... | 178 |
243 | # CONSTANTS
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
't', 'u', 'v', 'w', 'x', 'y', 'z']
capital_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y... | 627 |
244 | from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name='redfishtool',
version='1.1.0',
description='Redfishtool package and command-line clie... | 432 |
245 | import sentry_sdk
from fastapi import FastAPI
# from sentry_sdk import set_tag
# from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from app.api.api import api_router
from app.core.config impo... | 582 |
246 | # -*- coding: utf-8 -*-
import django
if django.VERSION < (2, 0):
from django.conf.urls import include, url as re_path
else:
from django.urls import include, re_path
from django.http import HttpResponse
from .views import (
force_maintenance_mode_off_view, ForceMaintenanceModeOffView,
force_maintena... | 576 |
247 | # Copyright 2020- Robot Framework Foundation
#
# 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 ag... | 440 |
248 | #!/usr/bin/env python
# Copyright (c) 2019 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
import sys
import pprint
import steelscript
from steelscr... | 459 |
249 | #!/usr/bin/env python3
import bitcoincash
from bitcoincash.electrum import Electrum
from bitcoincash.electrum.svr_info import ServerInfo
from bitcoincash.core import CBlockHeader, x
from bitcoincash.wallet import CBitcoinAddress
import asyncio
bitcoincash.SelectParams("testnet")
scripthash = CBitcoinAddress("bchtest:... | 261 |
250 | from datetime import datetime
from sqlalchemy import DateTime
from sqlalchemy.ext.hybrid import hybrid_property
from microhttp_restful import Field
class ActivationMixin:
activated_at = Field(DateTime, nullable=True, readonly=True, protected=True)
@hybrid_property
def is_active(self):
return se... | 457 |
251 | from behave import then, given
from behave_django.decorators import fixtures
from test_app.models import BehaveTestModel
@fixtures('behave-fixtures.json')
@given(u'a step with a fixture decorator')
def check_decorator_fixtures(context):
pass
@fixtures('behave-second-fixture.json')
@given(u'a step with a second... | 414 |
252 | # -*- coding: utf-8 -*-
#* Copyright (c) 2020 Intel Corporation
import os,sys,copy,json
import subprocess
import datetime
import time
os.system('sudo -E apt-get install iasl')
if os.path.exists('iasl_build'):
os.system('rm -rf iasl_build')
os.system('mkdir -p iasl_build')
cmd = "cd iasl_build" + "&&" +"wget https:/... | 337 |
253 | from flask import Flask, jsonify
from flask_restful import Resource, Api
from flask_accept import accept, accept_fallback
app = Flask(__name__)
app.debug = True
api = Api(app)
class IndexResourceWithoutFallback(Resource):
@accept('application/vnd.vendor.v1+json')
def get(self):
return jsonify(versio... | 437 |
254 |
from django.contrib import admin
from models import *
from forms import *
class PlaceAdmin(admin.ModelAdmin):
"""
ModelAdmin for Place.
"""
list_display = (
'name',
'code',
'woeid',
)
search_fields = (
'name',
'code',
'woeid',
)
list_fi... | 663 |
255 | import sys
def main():
input = sys.stdin.readline
N, K = map(int, input().split())
S = [int(input()) for _ in range(N)]
if 0 in S:
return N
if K == 0:
return 0
l, r = 0, 0
ans = 0
m = 1
while r < N:
while r < N and m <= K:
ans = max(ans, r-l)
... | 291 |
256 | import sys
import os
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from app import flask_app, db
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
app = flask_app
MIGRATION_DIR = os.path.joi... | 195 |
257 | #!/usr/bin/env python
import setuptools
try:
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
except (IOError, OSError):
long_description = ''
setuptools.setup(
name='xontrib-up',
version='1.0.1',
license='MIT',
author='mattmc3',
author_email='ohmyx... | 588 |
258 | import os
from time import sleep
from dronekit import connect, Vehicle
from app.helper import create_directory
from app.gpslogger import GPSLogger
from app.multiheadcamera import MultiHeadCamera
class CameraVehicle(Vehicle):
def __init__(self, *args):
super(CameraVehicle, self).__init__(*args)
ou... | 634 |
259 | '''
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
'''
import os
import pickle
import numpy as np
repetition_options = list(range(5))
model_options = ["xrv", "densenet", "covidnet"]
mask_options = ["unmasked", "masked"]
disentangle_options = ["no-disentangle", "disentangle"]
... | 843 |
260 | from unittest import TestCase
import jsons
from jsons import DeserializationError
class TestComplexNumber(TestCase):
def test_dump_complex_number(self):
a = 5 + 3j
dumped = jsons.dump(a)
self.assertDictEqual({'real': 5.0, 'imag': 3.0}, dumped)
def test_dump_complex_number_property(se... | 438 |
261 | """
The PyTorch2Keras converter interface
"""
from onnx2keras import onnx_to_keras
import torch
import onnx
import io
import logging
def pytorch_to_keras(
model, args, input_shapes=None,
change_ordering=False, verbose=False, name_policy=None,
):
"""
By given PyTorch model convert layers with ONNX.
... | 837 |
262 | from gitlabform.gitlab import GitLab
from gitlabform.processors.defining_keys import Key, And
from gitlabform.processors.multiple_entities_processor import MultipleEntitiesProcessor
class BadgesProcessor(MultipleEntitiesProcessor):
def __init__(self, gitlab: GitLab):
super().__init__(
"badges"... | 321 |
263 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Utilities common to all administration panels.
"""
from django.contrib import admin
class BaseAdmin(admin.ModelAdmin):
"""
Parent class with attributes common to all CAL-ACCESS data models.
"""
save_on_top = True
def get_readonly_fields(self, *arg... | 335 |
264 | from setuptools import setup
setup(
name="python-velbus",
version="2.0.42",
url="https://github.com/thomasdelaet/python-velbus",
license="MIT",
author="Thomas Delaet",
install_requires=["pyserial==3.3"],
author_email="thomas@delaet.org",
packages=["velbus", "velbus.connections", "velbus... | 154 |
265 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 503 |
266 | # В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны
# каждому из чисел в диапазоне от 2 до 9. Примечание: 8 разных ответов.
a = [0] * 8
for i in range(2, 100):
for j in range(2, 10):
if i % j == 0:
a[j - 2] += 1
for i, item in enumerate(a, start=2):
print(f'Числу ... | 277 |
267 | # Usage:
#
# -- Build the project for distribution:
# python3 setup.py sdist bdist_wheel
#
# -- Run unit tests:
# python3 setup.py test
#
# -- Run inside venv:
# python setup.py develop
# venv/bin/netbot
from netbot import __version__
import setuptools
setuptools.setup(
name='netbot',
version=__... | 525 |
268 | import sys
import os
import io
import re
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
from misc import printdbg
class PapelConfig():
@classmethod
def slurp_config_file(self, filename):
# read papel.conf config but... | 772 |
269 | ##############################################################################
# Copyright (c) 2016 ZTE Corp and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at... | 336 |
270 | from torch.autograd import Function, Variable
from .._ext import channelnorm
class ChannelNormFunction(Function):
@staticmethod
def forward(ctx, input1, norm_deg=2):
assert input1.is_contiguous()
b, _, h, w = input1.size()
output = input1.new(b, 1, h, w).zero_()
channelnorm.C... | 355 |
271 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 823 |
272 | import tensorflow as tf
from alt_model_checkpoint.tensorflow import AltModelCheckpoint
from alt_model_checkpoint.test__init__ import CommonAltModelCheckpointTests
class TfKerasAltModelCheckpointTest(CommonAltModelCheckpointTests):
def setUp(self):
self.cls = AltModelCheckpoint
self.model_cls = tf... | 166 |
273 | #
# Created on Sun Dec 05 2021
#
# The MIT License (MIT)
# Copyright (c) 2021 Maatuq
#
# 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 restriction,
# including without limitation the ri... | 482 |
274 | '''
Pattern:
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
'''
print('Number of patterns: ')
number_rows=int(input('Enter number of rows: '))
#upper part of the pattern
for row in range(1,number_rows+1):
for column in range(number_rows-1,row-1,-... | 284 |
275 | import abc
from enum import Enum
class AuthType(Enum):
SOURCE = 0
DESTINATION = 1
class BaseAuthHandler(metaclass=abc.ABCMeta):
@abc.abstractmethod
async def fetch(self, request, bundle):
pass
@abc.abstractmethod
async def get(self, resource, provider, request, action=None, auth_ty... | 159 |
276 | from setuptools import setup, find_packages
setup(
name = 'comake',
packages=find_packages(), # this must be the same as the name above
version = 'v0.1.6',
description = 'A c++ build tool',
author = 'liaosiwei',
author_email = 'liaosiwei@163.com',
url = 'https://github.com/boully/comake',
... | 387 |
277 | from buffalo import utils
utils.init()
from chunk import Chunk
from pluginManager import PluginManager
PluginManager.loadPlugins()
class TestChunk:
def test_init(self):
assert Chunk(0,0) is not None
def test_data(self):
chunk = Chunk(100,100)
assert chunk.data is not None
assert len(chunk.data) is 32 and ... | 179 |
278 | #!/usr/bin/env python
# Copyright 2020 Google Inc. 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 require... | 532 |
279 | from os import popen
def determine_provider():
result = popen('/usr/sbin/dmidecode -t system').read()
output = result.lower()
if 'amazon' in output:
provider = 'ec2'
elif 'microsoft' in output:
provider = 'azure'
elif 'google' in output:
provider = 'gce'
else:
r... | 153 |
280 | DEFAULT_CONFIG = {
# Protector server address
'host': 'localhost',
'port': 8888,
# Connection to the time series database API
'backend_host': 'localhost',
'backend_port': 8086,
'rules': [
'prevent_delete',
'prevent_drop',
'series_endswith_dot',
'short_series_n... | 420 |
281 | # Created by MechAviv
# ID :: [927000080]
# Hidden Street : Scene Change 1
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.setStandAloneMode(True)
sm.forcedInput(1)
sm.sendDelay(30)
sm.forcedInput(0)
sm.showFieldEffect("demonSlayer/text8", 0)
sm.sendDelay(50... | 224 |
282 | import pulumi
import pulumi.runtime
from ... import tables
class StorageClassList(pulumi.CustomResource):
"""
StorageClassList is a collection of storage classes.
"""
def __init__(self, __name__, __opts__=None, items=None, metadata=None):
if not __name__:
raise TypeError('Missing r... | 557 |
283 | print('\033[1mINFORME 3 VALORES PARA DESCOBRIR QUAL O MAIOR!\033[m')
n1 = int(input('>> 1º VALOR: '))
n2 = int(input('>> 2º VALOR: '))
n3 = int(input('>> 3º VALOR: '))
print('\033[1mRESULTADO...\033[m')
if n1 > n2 and n1 > n3:
print(f'MAIOR VALOR: {n1}.')
elif n2 > n1 and n2 > n3:
print(f'MAIOR VALOR: {... | 238 |
284 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License,... | 313 |
285 | #!/usr/bin/env python
#coding=utf-8
import os
from setuptools import setup, find_packages
try:
from jupyterpip import cmdclass
except:
import pip
import importlib
pip.main(['install', 'jupyter-pip'])
cmdclass = importlib.import_module('jupyterpip').cmdclass
__title__ = 'pyecharts'
__description... | 851 |
286 | # coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.custom_data import CustomData
from bitmovin_api_sdk.models.response_envelope import ResponseEnvelope
from ... | 742 |
287 | import pytest
from requests import Session
from requests.adapters import BaseAdapter
from requests.models import PreparedRequest
from requtests import fake_response, FakeAdapter
from .test_utils import assert_prepared_request, build_request
TEST_DATA = "some data"
TEST_URL = "https://api.example.com/some/url"
def te... | 954 |
288 | # SPDX-FileCopyrightText: Copyright (C) 2021 Ryan Finnie
# SPDX-License-Identifier: MIT
import hashlib
from unittest import TestCase
from rf_pymods.smwrand import SMWRand
class TestSMWRand(TestCase):
def test_first_run(self):
"""Check first result"""
with SMWRand() as smwrand:
self.a... | 762 |
289 | import sys
if __name__ == "__main__":
file_name = "input.txt"
if len(sys.argv) >= 2:
file_name = sys.argv[1]
with open(file_name, "rU") as f:
lines = f.read().strip().split("\n")
changes = (int(val) for val in lines)
result = sum(changes)
print(result)
| 135 |
290 | import cPickle as pickle
from vendor.HoeffdingTree.hoeffdingtree import *
from vendor.HoeffdingTree.ht.weightmass import WeightMass
def __loadModel(name):
with open(name+".pickle") as pickle_handle:
return pickle.load(pickle_handle);
# zapisywanie modelu do pliku
def __storeModel( clf,name):
with open... | 306 |
291 | import numpy as np
def BatchGenerator(X, y, batch_size, shuffle=True):
if shuffle:
indices = np.random.permutation(X.shape[0])
X = X[indices]
if y is not None:
y = y[indices]
for i in range(X.shape[0] // batch_size):
batch = {}
batch['x'] = X[i * batch_siz... | 225 |
292 | # -*- coding: utf-8 -*-
from drf_link_header_pagination import LinkHeaderPagination
from rest_framework.response import Response
class CountPaginationHeaders(LinkHeaderPagination):
def get_paginated_response(self, data):
next_url = self.get_next_link()
previous_url = self.get_previous_link()
... | 504 |
293 | ENTITY_POSITION_TOP_INCREASE = 100
ENTITY_POSITION_LEFT_INCREASE = 300
TYPES_INTEGER = "integer"
TYPES_STRING = "string"
TYPES_BOOLEAN = "boolean"
TYPES_DATETIME = "datetime"
TYPES_DATE = "date"
TYPES_TIME = "time"
TYPES_CURRENCY = "currency"
TYPES_TEXT = "text"
TYPES_DOUBLE = "double"
FIELD_TYPES = (
(TYPES_INTE... | 437 |
294 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open('requirements.txt', 'r') as f:
install_reqs = [
s for s in [
line.strip(' \n') for line in f
] if not s.startswith('#') and s != ''
]
setuptools.setup(
name="tsfel",
version="0... | 360 |
295 | def to_role_name(feature_name):
return feature_name.replace("-", "_")
def to_feature_name(role_name):
return role_name.replace("_", "-")
def resource_name(prefix, cluster_name, resource_type, component=None):
name = ''
if (not prefix) or (prefix == 'default'):
if component is None:
... | 698 |
296 | import graphene
from gql_types import Matchup
import models
class AssignMatchupNotes(graphene.Mutation):
class Arguments:
tournament = graphene.ID(required=True)
matchup = graphene.ID(required=True)
notes = graphene.String(required=True)
matchup = graphene.Field(Matchup, required=Tru... | 198 |
297 | import redlab as rl
from time import sleep
import numpy as np
import matplotlib.pyplot as plt
print("-------einzelneWerte-------------------------")
print("16BitValue:" + str(rl.cbAIn(0, 0, 1)))
print("VoltageValue:" + str(rl.cbVIn(0, 0, 1)))
print("-------Messreihe-------------------------")
print("Messreihe:" + str... | 304 |
298 | import random
from ...mock.mock_abstract_device import MockAbstractDevice
from ..tc335 import TC335
"""
Mock Lakeshore 335 Temperature Controller
"""
class MockTC335(MockAbstractDevice, TC335):
"""
Mock interface for Lakeshore 335 Temperature Controller.
"""
def __init__(self, *args, **kwargs):
self.mocking =... | 355 |
299 | import sys
import os
import mock
sys.path.insert(0, os.path.dirname(__file__))
from sublime_hg import find_repo_root
def test_ThatHgRootIsFoundCorrectly():
paths = (
r'C:\No\Luck\Here',
r'C:\Sometimes\You\Find\What\You\Are\Looking\For',
r'C:\Come\Get\Some\If\You\Dare',
)
old_ex... | 240 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.