content stringlengths 5 1.05M |
|---|
import unittest
import pandas as pd
from tests.test_utils import TestUtils
from enda.ml_backends.sklearn_estimator import EndaSklearnEstimator
try:
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.ensemble import AdaBoostRegressor, RandomForestRegressor
from sklearn.svm import S... |
""" Generate new files from templates. """
import argparse
import sys
from typing import Optional
from contextlib import contextmanager
import os
import shlex
from itertools import chain
from cjrh_template import Template
import biodome
__version__ = '2017.10.3'
@contextmanager
def file_or_stdout(args, filename: Op... |
import os
import paramiko
def get_private_key():
# or choose the location and the private key file on your client
private_key_file = os.path.expanduser("/home/ubuntu/.ssh/id_rsa")
return paramiko.RSAKey.from_private_key_file(private_key_file, password='')
def get_ssh(myusername, myhostname, myport):
... |
import json
from unittest.mock import patch
from ddt import ddt
from django.test import tag
from django.urls import reverse
from requests.exceptions import HTTPError
from rest_framework import status
from .test_setup import TestSetUp
@tag('unit')
@ddt
class ViewTests(TestSetUp):
def test_get_catalogs(self):
... |
import sys
stack = []
def recursion(stack, last):
if stack:
now = stack.pop()
else:
return -1
s = 0
while now != -last:
foo = recursion(stack, now)
if foo == -1:
return -1
s += foo
if stack:
now = stack.pop()
else:
... |
from chaco.api import ArrayPlotData
from enable.component_editor import ComponentEditor
from traits.api import (
List, Instance, Either, Str, on_trait_change, Tuple, Any,
Property)
from traitsui.api import (
TabularEditor, View, UItem, VGroup, EnumEditor, HGroup, Item)
from traitsui.tabular_adapter import T... |
from .device import (ORTDeviceInfo, get_available_devices_info,
get_cpu_device_info)
from .InferenceSession import InferenceSession_with_device
|
#!/usr/bin/env python3
import sys
import numpy as np
with open(sys.argv[1]) as infile:
rows = [a.strip() for a in infile]
def do_round(cube):
x, y, z = cube.shape
new_cube = np.zeros(cube.shape, dtype=bool)
for i in range(x):
for j in range(y):
for k in range(z):
... |
"""bsw URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... |
from pandas import DataFrame
from typing import List, Tuple, Dict
from models.team_stats import TeamSkeletonStats
def get_opponents_in_given_fixture_list(team_id: int, fixtures: DataFrame) -> List[int]:
home_opponents = fixtures.loc[fixtures['team_a'] == team_id, 'team_h']
away_opps = fixtures.loc[fixtures['t... |
#!/usr/bin/env python3
# coding:utf-8
from pickle import load
with open("banner.p", "rb") as f:
print(load(f))
|
#!/usr/bin/env python
import re
from setuptools import setup
def get_version(filename):
f = open(filename).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", f).group(1)
version = get_version('flake8_assertive.py')
description = open('README.rst').read() + "\n\n" + open('CHANGELOG.rst').read()
g... |
import modules.weapon as weapon
basic_sword = weapon.Weapon("Sword", "A sword you found somewhere.", 10, 0.5, 10, "slash", 1 , "You took the sword.", "You dropped the sword.")
big_axe = weapon.Weapon("Axe", "A big axe you found somewhere.", 20, 0.5, 10, "slash", 1 , "You took the axe.", "You dropped the axe.") |
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import cache_page
from .forms import CommentForm, PostForm
from .models import Follow, Group, Post, User
from .settin... |
from numpy import random
from impl.distribution import distribution
class triangular(distribution):
def __init__(self, mini, mode, maxi):
self.mini = float(mini)
self.mode = float(mode)
self.maxi = float(maxi)
def generate(self):
return int(random.triangular(self.mini, self.m... |
from .multiagent_particle_env import RLlibMultiAgentParticleEnv as MultiAgentParticleEnv
__all__ = [
"MultiAgentParticleEnv"
]
|
from flask import abort, Flask, jsonify, request
import os
import asyncio
import pyjuicenet
import aiohttp
from prettytable import PrettyTable
from pytz import timezone
import datetime
import requests
import database_helper
import html_renderer
app = Flask(__name__)
@app.route("/")
def show_all_chargers():
datab... |
import pytest
import networkx as nx
from ..pyfastg import add_node_to_digraph
def test_basic():
def check_asdf(g):
assert "asdf" in g.nodes
assert g.nodes["asdf"]["cov"] == 5.2
assert g.nodes["asdf"]["gc"] == 4 / 6.0
assert g.nodes["asdf"]["length"] == 6
def check_ghjasdf(g):
... |
from rest_framework import serializers
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import PatientConsultation, PatientRegistration, Facility
from care.facility.models.prescription_supplier import Pre... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure_devtools.perfstress_tests import PerfStressTest
from azure.identity import ClientSecretCredential, TokenCachePersistenceOptions
from azure.identity.aio impor... |
import re, hashlib, random, json, csv, sys
from datetime import datetime, timedelta, tzinfo
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import caches
from django.core.exceptions i... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-21 08:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0005_photolikes'),
]
operations = [
migrations.RemoveField(
... |
class Record:
vdict = dict()
count = 0
record = dict()
reclen = 0
fd = None
# The constructor opens the Record Defenition File and sets
# the record defenition
def __init__(self, recName, fileName, mode="r", encoding="Latin-1"):
defstr = self.recordDef(recName)
self.vdic... |
import os
import posixpath
import sys
import docker
import json
from unittest import TestCase, skipUnless
from unittest.mock import Mock, call, patch, ANY
from pathlib import Path, WindowsPath
from parameterized import parameterized
from samcli.lib.build.build_graph import FunctionBuildDefinition, LayerBuildDefinit... |
import requests
import json
coin_market_cap = requests.get(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false",
headers = {"accept": "application/json"})
print("Enter the number of top cryptocurrencies by market capitalization: ")... |
"""
"""
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class BaseAgent:
"""
"""
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def agent_init(self, agent_info= {}):
""" """
@abstractmethod
def agent_start(self, obser... |
import torch
import gpytorch
from torch.nn.functional import softplus
from gpytorch.priors import NormalPrior, MultivariateNormalPrior
class LogRBFMean(gpytorch.means.Mean):
"""
Log of an RBF Kernel's spectral density
"""
def __init__(self, hypers = None):
super(LogRBFMean, self).__init__()
if hypers is not No... |
# python
import lx, lxifc, lxu, modo
import tagger
from os.path import basename, splitext
CMD_NAME = tagger.CMD_SET_PTAG
def material_tags_list():
res = set(tagger.scene.all_tags_by_type(lx.symbol.i_POLYTAG_MATERIAL))
for type, tag in tagger.items.get_all_masked_tags():
if type == "material":
... |
import turtle
'''this makes a circle by building many squares'''
def draw_square(tom):
for _ in range(4):
tom.forward(100)
tom.right(90)
def draw_flower():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.speed(0)
brad.color("blue")
for i in rang... |
class Solution:
def maxProfit(self, prices):
index = 0
flag = False
ans = 0
i = 1
n = len(prices)
while i < n:
if prices[i] > prices[i - 1]:
flag = True
else:
if flag:
ans += prices[i - 1] - p... |
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
from lxml import etree
import requests
import re
def get_links(who_sells=0):
# urls = []
list_view = 'http://bj.58.com/pbdn/{}/'.format(str(who_sells))
print(list_view)
wb_data = requests.get(list_view, headers=h... |
# -*- coding: utf-8 -*-
import os
import json
from logging import getLogger
from six import string_types, text_type
from collections import OrderedDict
from ckan import logic
from ckan import model
import ckan.plugins as p
from ckan.lib.plugins import DefaultDatasetForm
try:
from ckan.lib.plugins import Default... |
# coding=utf-8
# IP地址取自国内髙匿代理IP网站:http://www.xicidaili.com/nn/
# 仅仅爬取首页IP地址就足够一般使用
import telnetlib
from bs4 import BeautifulSoup
import requests
import random
URL = 'http://www.xicidaili.com/nn/'
HEADERS = {
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.... |
import struct
__all__ = ['AbstractEnumValue', 'IntValue', 'KnobModeEnum', 'PadModeEnum', 'SusModeEnum']
class AbstractEnumValue (object):
_VALUES = {}
def __init__(self, val):
if isinstance(val, int):
try:
self._value = next(k for k, v in self._VALUES.items() if v == val)... |
s = input().strip()
n = int(input().strip())
a_count = s.count('a')
whole_str_reps = n // len(s)
partial_str_length = n % len(s)
partial_str = s[:partial_str_length]
partial_str_a_count = partial_str.count('a')
print(a_count * whole_str_reps + partial_str_a_count)
|
import asyncio
import math
import networkx as nx
from ccxt import async_support as ccxt
import warnings
__all__ = [
'create_multi_exchange_graph',
'create_weighted_multi_exchange_digraph',
'multi_graph_to_log_graph',
]
def create_multi_exchange_graph(exchanges: list, digraph=False):
"""
Returns a ... |
"""Methods for creating, manipulating, and storing Teradata row objects."""
import csv
from claims_to_quality.lib.qpp_logging import logging_config
from claims_to_quality.lib.teradata_methods import deidentification
import teradata
logger = logging_config.get_logger(__name__)
def csv_to_query_output(csv_path):
... |
#!/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... |
# Copyright 2021 AIPlan4EU project
#
# 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 wri... |
preco = float(input('Qual o valor do produto ? R$ '))
porcentagem = float(input('Qual a porcentagem ? '))
calculo = preco - (preco * porcentagem / 100)
print(f'O produto que custava R${preco}, na promoção com desconto de {porcentagem}% vai custar {calculo:.2f}') |
import json
import logging
from unittest import mock
from django.test import TestCase
from djenga.logging.formatters import JsonFormatter, JsonTaskFormatter
__all__ = [ 'JsonFormatterTest', ]
log = logging.getLogger(__name__)
class JsonFormatterTest(TestCase):
def test_json_formatter(self):
formatter = ... |
#!/usr/bin/env python3
'''
booksdatasource.py
Jeff Ondich, 21 September 2021
For use in the "books" assignment at the beginning of Carleton's
CS 257 Software Design class, Fall 2021.
'''
#Revised by Thea Traw
import csv
class Author:
def __init__(self, surname='', given_name='', birth_year=None,... |
/home/wai/anaconda3/lib/python3.6/copy.py |
import pytest
from ergaster import add
data = (
(1, 2, 3),
(2, 2, 4),
(3, 2, 5),
)
@pytest.mark.parametrize("x, y, res", data)
def test_add(x, y, res):
assert add(x, y) == res
|
def grafoSimples(matriz):
result = ""
l = 0
am = 0
for linha in range(len(matriz)):
for coluna in range(len(matriz[linha])):
if(linha == coluna and matriz[linha][coluna] == 2):
result+=("Há laço no vertice %s\n" %(linha+1))
l = 1
if (linha... |
# coding=UTF-8
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from product.models import TaxClass
from l10n.models import AdminArea, Country
#from satchmo_store.shop.models import Order
#from satchmo_store.sho... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import colorcet as cc
import datashader as ds
import datashader.utils as utils
import datashader.transfer_functions as tf
sns.set(context="paper", style="white")
data_dir = os.path.abspath("./data")
data_fname = ... |
# -*- coding: utf-8 -*-
from .base_settings import *
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
FOP_EXECUTABLE = "C:/U... |
import json
from dagster import ModeDefinition, execute_solid, solid
from dagster_slack import slack_resource
from mock import patch
@patch("slack.web.base_client.BaseClient._perform_urllib_http_request")
def test_slack_resource(mock_urllib_http_request):
@solid(required_resource_keys={"slack"})
def slack_so... |
# Copyright (c) 2011-2020 Eric Froemling
#
# 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 rights
# to use, copy, modify, merge, publish,... |
#!/usr/bin/env python
from avro.io import BinaryEncoder, BinaryDecoder
from avro.io import DatumWriter, DatumReader
import avro.schema
from io import BytesIO
import argo_ams_library
from argo_ams_library import ArgoMessagingService
import argparse
import base64
import logging
import logging.handlers
import sys
import ... |
from datetime import datetime
from itertools import chain
from random import randint
from django.contrib.auth.decorators import login_required
from django.contrib.formtools.wizard.views import SessionWizardView
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.utils.decorators impo... |
'''
visualize VIL-100 datasets in points form or curves form.
datasets name:vil-100
paper link: https://arxiv.org/abs/2108.08482
reference: https://github.com/yujun0-0/MMA-Net/tree/main/dataset
datasets structure:
VIL-100
|----Annotations
|----data
|----JPEGImages
|----Json
|----trai... |
from __future__ import print_function
import os
import re
import sqlite3
import sys
import traceback
import simpy
from vcd import VCDWriter
from . import probe
from .util import partial_format
from .timescale import parse_time, scale_time
from .queue import Queue
from .pool import Pool
class Tracer(object):
na... |
from pyhafas.profile import ProfileInterface
from pyhafas.profile.interfaces.helper.parse_lid import ParseLidHelperInterface
from pyhafas.types.fptf import Station
class BaseParseLidHelper(ParseLidHelperInterface):
def parse_lid(self: ProfileInterface, lid: str) -> dict:
"""
Converts the LID given... |
from __future__ import print_function, absolute_import
import torch
from torch.optim.lr_scheduler import _LRScheduler
from bisect import bisect_right
AVAI_SCH = ['single_step', 'multi_step', 'cosine', 'multi_step_warmup']
def build_lr_scheduler(optimizer,
lr_scheduler='single_step',
... |
"""
File: rocket.py
Name:Claire Lin
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.... |
from enum import Enum
class RecipeStyle(Enum):
"""
Class for allrecipes.com style labels
"""
diabetic = 'diabetic'
dairy_free = 'dairy_free'
sugar_free = 'sugar-free'
gluten_free = 'gluten_free'
low_cholesterol = 'low_cholesterol'
mediterranean = 'mediterranean'
chinese = 'chin... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class ImplementationGuide_PageSchema:
"""
A set of rules of how FHIR is used to ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-15 01:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... |
from rallf.sdk.logger import Logger
from rallf.sdk.network import Network
from rallf.sdk.listener import Listener
class Task:
def __init__(self, manifest, robot, input, output):
self.manifest = manifest
self.robot = robot
self.finished = False
self.status = "stopped"
self.... |
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$',
views.IndexView.as_view(),
name='index'),
re_path(r'^(?P<pk>[-\w]+)/$',
views.PageDetailView.as_view(),
name='page_detail'),
]
|
import unittest
import time
from liquidtap.client import Client
class TestClient(unittest.TestCase):
def setUp(self) -> None:
self.client = Client()
self.client.pusher.connection.bind('pusher:connection_established', self._on_connect)
def _on_connect(self, data: str):
print('on_conne... |
class NopBackpressureManager:
def __init__(self):
pass
def register_pressure(self):
pass
def unregister_pressure(self):
pass
def reached(self) -> bool:
return False
class BackpressureManager:
def __init__(self, max):
self.max = max
self.pressure... |
import re
import croniter
from datetime import timedelta, datetime
from functools import partial
from airflow import DAG
from airflow.sensors.external_task import ExternalTaskSensor
from dagger import conf
from dagger.alerts.alert import airflow_task_fail_alerts
from dagger.dag_creator.airflow.operator_factory import... |
from __future__ import absolute_import
from collections import defaultdict, Sequence, OrderedDict
import operator
from string import capwords
import numpy as np
from .elements import ELEMENTS
# records
MODEL = 'MODEL '
ATOM = 'ATOM '
HETATM = 'HETATM'
TER = 'TER '
MODEL_LINE = 'MODEL ' + ' ' * 4 + '{:>4d}\n'
END... |
# Copyright 2017-2020 TensorHub, Inc.
#
# 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 writ... |
"""Module for raceplan exceptions."""
class CompetitionFormatNotSupportedException(Exception):
"""Class representing custom exception for command."""
def __init__(self, message: str) -> None:
"""Initialize the error."""
# Call the base class constructor with the parameters it needs
su... |
################ Running: F:\users\emiwar\edited_new\catAtt.py #################
COM1
Serial<id=0x52b47f0, open=True>(port='COM1', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=2.5, xonxoff=False, rtscts=False, dsrdtr=False)
492
1 False [('b', 1.378630934454577)]
1 finished.
2 desert [('b', 1.37283... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: server_admin.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... |
import tensorflow as tf
from tensorflow.keras.applications import InceptionV3
__all__ = ["inception_score"]
def inception_score(images):
r"""
Args:
images: a numpy array/tensor of images. Shape: NxHxWxC
Return:
inception score
"""
img_shape = images.shape
if img_shape[1] !=... |
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from django.core.mail import send_mail
from .models import Profile
from django.conf import settings
SUBJECT = 'WELCOME TO DEVCONNECT'
MESSAGE = """ Congratulation I have to say thank you for creating a new account
with our... |
"""
Setup file for installation of the dataduct code
"""
from setuptools import find_packages
from setuptools import setup
from dataduct import __version__ as version
setup(
name='dataduct',
version=version,
author='Coursera Inc.',
packages=find_packages(
exclude=["*.tests", "*.tests.*", "test... |
import re
f = open("regex.txt", "r")
content = f.readlines()
# s = 'A message from cs@uni.edu to is@uni.edu'
for i in range(len(content)):
if re.findall('[\w\.]+@[\w\.]+', content[i]):
print(content[i], end='') |
"""
Command-line interface implementing synthetic MDS Provider data generation:
- custom geographic area, device inventory, time periods
- generates complete "days" of service
- saves data as JSON files to container volume
All fully customizable through extensive parameterization and configuration options.
"""
... |
class Cache:
# private with __
__store = {}
# THIS BLOCK demo for PROTECTED if required - Single _
# _protected_store = {}
#
# @property
# def protected_store(self):
# return self._protected_store
def get(self, key):
if key:
try:
value_for_k... |
b = "Hello, World!"
print(b[:5])
|
#!/usr/bin/python3
import argparse
import os
import random
import logging
import tensorflow as tf
import numpy as np
from PIL import Image
from unet import UNet, Discriminator
from scripts.image_manips import resize
model_name = "matting"
logging.basicConfig(level=logging.INFO)
# Parse Arguments
def parse_args():... |
from setuptools import setup
setup(name='socialsent',
version='0.1.2',
description='Algorithms for inducing domain-specific sentiment lexicons from unlabeled corpora.',
url='https://github.com/williamleif/socialsent',
author='William Hamilton',
author_email='wleif@stanford.edu',
lic... |
########################################################################
# SwarmOps - Heuristic optimization for Python.
# Copyright (C) 2003-2016 Magnus Erik Hvass Pedersen.
# See the file README.md for instructions.
# See the file LICENSE.txt for license details.
# SwarmOps on the internet: http://www.Hvass-Labs.org/... |
# -*- coding: utf-8 -*-
"""
Created on Mar 23 11:57 2017
@author: Denis Tome'
"""
__all__ = [
'VISIBLE_PART',
'MIN_NUM_JOINTS',
'CENTER_TR',
'SIGMA',
'STRIDE',
'SIGMA_CENTER',
'INPUT_SIZE',
'OUTPUT_SIZE',
'NUM_JOINTS',
'NUM_OUTPUT',
'H36M_NUM_JOINTS',
'JOINT_DRAW_SIZE',... |
# coding: utf-8
"""
Ed-Fi Operational Data Store API
The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reas... |
# -*- coding: utf-8 -*-
__doc__="返回选择物体的类型"
import rpw
from rpw import revit, DB, UI,db,doc
from System.Collections.Generic import List
import json
import subprocess as sp
#from MyLib.Adaptor import BAT_Wall
from Adaptor import BAT_ElementMaterial
from Helper import *
#根据Accessmbly Code 筛选构件
title="根据Accessmbly筛选构件价格... |
#!/usr/bin/env python
'''
This script will generate a convenient <.csv> detailing the nucleotide composition of
sequences in fasta format. This <.csv> may be imported and merged with other <.csv>s to build
a comprehensive data sheet.
'''
#Imports
from collections import Counter
from Bio import SeqIO
from Bio.Seq im... |
#7. Desarrolle el programa que determine el área y
# el perímetro de un rectángulo sabiendo que el área = b x h, perímetro = 2x (b+h).
B=float(input("Ingresa el B: "))
H=float(input("Ingresa el H: "))
area=(B*H)
perim=2*(B+H)
print("El Area es : ",area)
print("El perimetro es : ", perim)
|
from typing import List
from webdnn.backend.code_generator.allocator import MemoryLayout
from webdnn.backend.fallback.generator import FallbackDescriptorGenerator
from webdnn.backend.fallback.kernel import Kernel
from webdnn.graph.operators.concat import Concat
source = """
concat: function(input_arrays, output_array... |
import logging
import sys
import signal
import time
import os
from networktables import NetworkTables
import csv
from Adafruit_BNO055 import BNO055
import RPi.GPIO as GPIO
NetworkTables.initialize()
nt = NetworkTables.getTable("IMU_Data")
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT)
GPI... |
#2. Sorteie 20 inteiros entre 1 e 100 numa lista. Armazene os números
#pares na lista PAR e os números ímpares na lista IMPAR. Imprima as três listas.
import random
num = 0
controle = 0
pares = []
impares = []
todos = []
a , b = 0 , 0
while(controle <=19):
num = random.randrange(1,100)
todos.in... |
from material.frontend import Module
class Sample(Module):
icon = 'mdi-image-compare'
|
# -*- coding: utf-8 -*-
"""Submit a test calculation on localhost.
Usage: verdi run submit.py
"""
from __future__ import absolute_import
from __future__ import print_function
import os
from aiida_ce import tests, helpers
from aiida.plugins import DataFactory, CalculationFactory
from aiida.engine import run
# get code... |
# pylint: disable=C0103,R0201
from typing import Tuple, Union, Callable, Optional, Any
from django.http import HttpResponse
from django.urls import re_path, path, URLPattern, URLResolver
# in case of include we get a tuple
ViewType = Optional[Union[Callable[..., HttpResponse], Tuple[Any, Any, Any]]]
class url:
... |
import paho.mqtt.client as mqtt
import sqlite3
import datetime
broker_address = "127.0.0.1"
dataToPush = {}
changed = []
bedToSub = []
bedToId = {} # lookup dict
def getBeds(db):
"""
Populate the bedToSub list from the db
"""
global bedToSub
cursorDb = db.cursor()
command = "SELECT WardNo, B... |
import copy
import time
from .core import ProgramLearningAlgorithm
from program_graph import ProgramGraph
from utils.logging import log_and_print, print_program, print_program_dict
from utils.training import execute_and_train
class ENUMERATION(ProgramLearningAlgorithm):
def __init__(self, max_num_programs=100):... |
from __future__ import division
import sys, glob
sys.path.append('/home/richard/scicore/GROUP/data/2017_Karolinska_EV-D68/SVVC/src')
sys.path.append('/scicore/home/neher/GROUP/data/2017_Karolinska_EV-D68/SVVC/src')
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
#import seaborn as... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 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 ... |
# kakao api 사용=>계정등록=>앱생성=>인증키 발급(restful key)
from urllib.request import urlopen
import xmltodict
import pandas as pd
import datetime
from sqlalchemy import create_engine
def upload_data():
GEV_API = 'STUV378914'
url= 'http://api.gevolution.co.kr/rank/xml/?aCode={GEV_API}&market=g&appType=game&rankType=1&ra... |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter, AutoMinorLocator
import matplotlib as mpl
# Make some style choices for plotting
color_wheel = ['#329932',
'#ff6961',
'b',
'#6a3d9a',
... |
customer = {
"name": "Fahad Hafeez",
"age": 30,
"is_verified": True,
}
customer["name"] = "Fahad Hafeez"
print(customer.get("birthdate", "Oct 18 2005")) |
#
# Turn off logging in extensions (too loud!)
import vb2py.extensions
import unittest
vb2py.extensions.disableLogging()
import vb2py.vbparser
vb2py.vbparser.log.setLevel(0) # Don't print all logging stuff
from vb2py.plugins.attributenames import TranslateAttributes
class TestAttributeNames(unittest.TestCase):
... |
"""
=============================================================
Bisecting K-Means and Regular K-Means Performance Comparison
=============================================================
This example shows differences between Regular K-Means algorithm and Bisecting K-Means.
While K-Means clusterings are different w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.