text stringlengths 38 1.54M |
|---|
### Version 0.1.0: Initial version
__version_info__ = (0, 4, 5)
__version__ = '.'.join(str(v) for v in __version_info__)
|
import subprocess
def execute_cmd_with_output(cmd, working_dir=None):
try:
# if working_dir is None:
# res = subprocess.check_output(cmd, shell=True)
# else:
# res = subprocess.check_output(cmd, shell=True, cwd=working_dir)
# debug
# javac_res=subprocess.Pop... |
from flask import Flask, render_template, flash, request,Markup
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField
from Anthem_POC import data_parsing
from Anthem_POC import clean_up_sentence
from Anthem_POC import bow
from Anthem_POC import question_from_class
from keras.mod... |
import pygame
from pygame.locals import *
from EventManager import *
from SpriteSheet import *
from Entity import *
# - - - - - - - - - - - - - - - - - - - SpriteState
# - - - - - - - - - - - - - - - - - - - Sector Sprite
class SectorSprite(ViewEntity):
def __init__(self, sector, group=None):
pygame.sprite.Sprite.... |
from h5py import File
from math import pi, cos, sin, atan2, ceil
from numpy import sin as npsin, cos as npcos, \
minimum, maximum, ravel_multi_index, \
arange, empty, zeros, \
hstack, fliplr, rot90
from scipy.integrate import quad
from scipy.sparse import csr_matrix
from quadrant import foldQuadrant, ... |
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from models.employee import Employee
class EmployeeSchema(SQLAlchemyAutoSchema):
'''
AutoSchema for EmployeeAPI request validation
'''
class Meta:
model = Employee
exclude = ['id']
load_instance = True
|
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
n = int(input('请输入模拟次数:'))
distance = np.zeros(n)
step = np.random.randint(2,size=n)
z = np.zeros(n)
for i in range(1, n):
if step[i] == 1:
distance[i] = distance[i-1] + step[i]
else:
distance[i] = distance[i-1] - 1
z[i] = np.sqrt(i)
dis... |
"""
Dados n e n seqüências de números inteiros não-nulos,
cada qual seguida por um 0,
calcular a soma dos números pares de cada seqüência.
"""
n = int(input("Digite o número de sequências: "))
for cont in range(n):
n2 = int(input("Digite o tamanho desa sequência "))
soma = 0
soma_aux = soma
... |
import subprocess
import numpy as np
import torch
import torch.distributed as torch_distrib
from pytorch_lightning.utilities.model_utils import is_overridden
from pytorch_lightning.trainer.supporters import Accumulator
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.core.step_result impor... |
INPUT_PATH = "./input.txt"
MAX_ROW = 127
MAX_COLUMN = 7
def find_pos(data, lower_half_code, upper_half_code, max_range):
current_interval = (0, max_range)
for e in data:
sum_interval = current_interval[1] - current_interval[0] + 1
if e == lower_half_code:
current_interval = (curre... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from blog import views
router = DefaultRouter()
router.register('all', views.ReadOnlyBlogViewSet, 'all')
router.register('mine', views.ManageBlogViewSet, 'mine')
app_name = 'blog'
urlpatterns = [
path('', include(router.urls)... |
import time
from kafka import KafkaProducer
import json
import requests
producer = KafkaProducer(bootstrap_servers=['localhost:9092'],
value_serializer=lambda x: json.dumps(x).encode('utf-8'))
print("\tProducing random quotes and storing in topic Quotes.\n")
while True:
resp = requests.ge... |
import gym
from gym import spaces
from gym.utils import seeding
import numpy as np
from matplotlib import pyplot as plt
class MultiGoalEnv(gym.Env):
def __init__(self, nr_goal = 4, goal_reward=100.):
radius = 2.
self.min_x = -radius*1.1
self.max_x = radius*1.1
self.min_y = -rad... |
import time
import numpy as np
# Tic toc constants
TICTOC_START = 0
TICTOC_COUNT = 0
TICTOC_MEAN = 0
TICTOC_MAX = -float('inf')
TICTOC_MIN = float('inf')
def convertHEXtoDEC(hexString, N):
"""
Return 2's compliment of hexString
"""
for hexChar in hexString:
asciiNum = ord(hexChar)
if ... |
# 145.
list = [1, 2, 3]
for i in list:
print("3 *", i)
# 146.
# 146-1.
list = ['가', '나', '다', '라']
list_a = list[1:]
for i in list_a:
print(i)
# 146-2.
list = ['가', '나', '다', '라']
for i in list[1:]:
print(i)
# 147.
list = ['가', '나', '다', '라']
for i in list[::2]:
print(i)
... |
import os
import csv
#create a .csv file from the bbc/ folder that can be found here:
#http://mlg.ucd.ie/datasets/bbc.html
def prepare_data(dir):
with open('classes.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(('classes', 'text'))
subdirs = [subdir for subdir in os.list... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-11-26 03:52
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations... |
#!/usr/bin/python3
import sqlite3
import datetime
import random
import string
import os
from typing import List
from pandas.core.series import Series #class
import pandas as pd
from history.aHistory import AHistory #class
from userBehaviourDescription.userBehaviourDescription import UserBehaviourDescription #class
... |
# -*- coding: utf-8 -*-
from . import payroll_ci
#from . import hr_cnps_monthly
from . import hr_disa
from .import cotisation_mensuelle_report
|
import json as js
import pandas as pd
class Addressbook:
def __init__(self):
self.first = 0
self.last = 0
self.phone = 0
self.telephone = 0
self.addie = 0
self.email = 0
self.data = {}
self.data['Information'] = []
self.namedata = {}
... |
"""
语法
条件成立执行的表达式 if 条件 else 条件不成立执行的表达式
"""
a = 1
b = 2
c = a if a > b else b
print(c)
# 需求: 有两个变量,比较大小 如果变量1 大于 变量2 执行 变量 1 - 变量2; 否则 变量2 - 变量1
aa = 10
bb = 6
cc = aa - bb if aa > bb else bb - aa
print(cc)
|
from . import db
from flask_login import UserMixin
from . import login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy.sql import func
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Colum... |
# Copyright 2019 SAP SE
#
# 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, software
... |
#! /usr/bin/env python
import unittest
import Exchange
class TestOrder(unittest.TestCase):
def test_create(self):
o = Exchange.Order("A:AUDUSD:100:1.47\n")
self.assertEqual(o.qty, 100)
self.assertEqual(o.instrument, "AUDUSD")
self.assertEqual(o.id, "A")
self.assertEqual(o.p... |
__author__ = "legendtkl"
def mul_return(a,b):
return a+1,b+1
if __name__ == "__main__":
print mul_return(1,2)
|
from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from .models import Question, Essay
from .forms import AnswerForm
from .utils.model import *
from .utils.helpers import *
import os
current_path = os.path.abspa... |
#########################################################################################
# TED Metric Calculator
#
#########################################################################################
from apted.helpers import Tree
from apted.apted import APTED
import sys
from tree_utils i... |
# -*- coding: utf-8 -*-
from datetime import date
from datetime import timedelta
from vatsystem.model import *
b = lambda v:" " if not v else v
na = lambda v: 'N/A' if not v else v
pd = lambda v:" " if not v else str(v)[0:10]
pt = lambda v:" " if not v else str(v)[0:19]
pi = lambda v:0 if not v else int(v)... |
import unittest
import numpy as np
from dezero import Variable
import chainer
import dezero.functions as F
from dezero.utils import gradient_check, array_allclose
class TestLinear(unittest.TestCase):
def test_forward1(self):
x = Variable(np.array([[1, 2, 3], [4, 5, 6]]))
w = Variable(x.data.T)
... |
# ----------------------------------------------------
# Dateiname: queue_.py
# Implementierung das Abstrakten Datentyps Schlange (Queue)
#
# Objektorientierte Programmierung mit Python
# Kapitel 27
# Michael Weigend 19. 11. 2009
# ----------------------------------------------------
class Queue:
def __init__(se... |
from django.conf import settings
SHOW_N_EVENTS = 5
DEFAULT_DATETIME_INPUT_FORMAT = getattr(
settings, 'DEFAULT_DATETIME_INPUT_FORMAT', '%d/%m/%Y %H:%M')
DEFAULT_DATE_INPUT_FORMAT = getattr(
settings, 'DEFAULT_DATE_INPUT_FORMAT', '%d/%m/%Y') |
from luma.core.render import canvas
class Screen:
positions = {
"1": (5, 5),
"2": (5, 15),
"3": (5, 25),
"4": (5, 35),
"5": (5, 45),
}
def __init__(self, device, fps=25):
self.device = device
self.fps = fps
self.data = {
"1": "--... |
# -*- coding: utf-8 -*-
import clipboard
import random
import string
import time
while True:
size = random.randint(5, 20)
txt = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(size))
clipboard.copy(txt)
time.sleep(.5)
|
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, jsonify, send_from_directory
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from app import app, db
from app.forms import LoginForm, RegistrationForm, Ed... |
# Generated by Django 2.2.7 on 2020-08-19 08:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0015_auto_20200819_0711'),
]
operations = [
migrations.CreateModel(
name='FirstVsSecond'... |
class Solution(object):
def removeDuplicateLetters(self, s):
"""
:type s: str
:rtype: str
"""
counter=collections.Counter(s)
resultset=set()
stack=[]
for c in s:
counter[c]-=1
if c in resultset:
continue
... |
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--data_root", type=str, default="data/")
parser.add_argument("--checkpoints", type=str, default="./checkpoints")
parser.add_argument("--temps", type=str, default="./temps")
parser.add_argument("--device",... |
import subprocess
class Compose:
"""
Manages an instance of compose.
"""
def __init__(self, composefile):
self.base_command = [
"docker-compose",
"--log-level",
"ERROR",
"-f",
composefile
]
def cmd(self, arg):
l ... |
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
if __name__ == '__main__':
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class_dict = {'background': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4, 'bottle': 5, 'bus': 6, 'car'... |
#coding:utf-8
import unittest
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import *
from sqlalchemy.orm import *
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:keen@localhost/logsss'
db = SQLAlchemy(app)
class M_Logsss(db.Model):
__tablename__ =... |
import os
import cv2
def fixEdge_H(p_val, img_h):
if p_val <= 0:
p_val = 1
if p_val >= img_h:
p_val = img_h - 1
return p_val
def fixEdge_W(p_val, img_w):
if p_val <= 0:
p_val = 1
if p_val >= img_w:
p_val = img_w - 1
return p_val
def save_xml(image, filename, b... |
from django.core.management.base import BaseCommand, CommandError
from django.core import management
from prices.models import Product, Brand, Competitor, Result, Archive
from scrapers import TemcoScraper, SqoneScraper, GlobalindustrialScraper, WalkeremdScraper, ElectricmotorwholesaleScraper, MotoragentsScraper
fro... |
# utility functions for pgmpy library
# authors: murphyk@, Drishttii@
#!pip install pgmpy
#!pip install graphviz
import superimport
import pgmpy
import numpy as np
import itertools
from graphviz import Digraph
def get_state_names(model, name):
state_names = dict()
cpd = model.get_cpds(name)
state_names = cpd.... |
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import tensorflow as tf
# seed 값 생성
seed = 0
np.random.seed(seed)
tf.set_random_seed(seed)
# 데이터 로드
dataset = np.loadtxt("./data/pima-indians-diabetes.csv", delimiter=",") # 경로의 './' 은 현재 경로(study)
... |
import requests
bestsellers_url = 'https://www.nytimes.com/books/best-sellers/'
# requests will go to the bestsellers website, and then download it as a response object
response = requests.get(bestsellers_url)
'''
To check if requests actually worked
print(response.status_code)
Status code 200 is good (codes between... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 13:51:34 2019
@author: Narahari B M
"""
import numpy as np
import cv2
def get_custom_augmentations(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255,
random_crop_size=(32, 32), padding_for_crop=4,pixel... |
# -*- coding: utf-8 -*-
"""
A wrap of H
>>>DOCTEST COMMANDS
(THE TEST ANSWER)
@author: Yi Zhang. Created on Tue Aug 29 17:02:33 2017
Department of Aerodynamics
Faculty of Aerospace Engineering
TU Delft
"""
import meshes_chooser
import numpy as np
from forms import form
f... |
n = int(input());
# this range starts from 2 and end by n + 1, because in python range include first border , but not include last one
for i in range(2,n + 1):
if(n % i == 0):
print(i)
break
|
from django.db import models
from common.models.abstract import *
from common.models.general import ArrangementCategory, ArrangementClass
class ArrangementType(DescribeableModel, HostableModel, TimeStampedModel, InsertableModel, UpdateableModel,
StatusRecordableModel, MakeableModel, CheckableMod... |
import json
class Principal(object):
def __init__(self):
estrutura = input("Entre com a estrutura JSON: ")
dict_estrutura = self.de_json(estrutura)
print(dict_estrutura)
print('\n')
print(type(dict_estrutura))
def de_json(self, estrutura):
try:
... |
#! python3
# -*- coding: utf-8 -*-
from enum import Enum, unique
@unique
class BeverageType(Enum):
Coke = "Coca-Cola"
Fanta = "Fanta"
def __str__(self):
return self.value |
from django.contrib import admin
from .models import Note, Category
admin.site.register(Note)
admin.site.register(Category)
|
def main():
n = int(input('Digite o valor de N: '))
maior_valor = 0
count = 1
while count <= n:
valor = int(input())
if(valor > maior_valor):
maior_valor = valor
count += 1
print('O maior valor é',maior_valor)
main()
|
from django import forms
class DateTimePickerInput(forms.TextInput):
template_name = 'stark/forms/widgets/datetime_picker.html'
|
# %%
import numpy as np
import scipy.io as io
import os
import sys
def npz2mat(data='full_path'):
"""
Usage
----------
convert .npz data file to .mat data file
Parameters
----------
data: full path of data
Example:
----------
import npz2mat
npz2mat('/Users/linxiaomin/D... |
import os
from datetime import timedelta
import redis
from flask import Flask, request, jsonify, make_response, abort
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, current_user, get_jwt
from src.models import User, db, db_setup, Group
ACCESS_EXPIRES = timedelta(hours=1)
app = Flask(__... |
#!/usr/bin/python3
from sys import argv
import os, subprocess
with open(argv[1], 'rb') as f:
f.seek(int(argv[2], base=16), 0)
data = f.read(512)
for i in range(0, 16):
filename = os.sep.join([argv[3], format(i, '02')])
with open(filename + '.gbapal', 'wb+') as f:
f.write(data[i * 32:i * 32 + ... |
from __future__ import absolute_import
import argparse
def arg_parse():
parser = argparse.ArgumentParser(description='DLCV TA\'s tutorial in image classification using pytorch')
# Datasets parameters
parser.add_argument('--train_dir', type=str, default='../data/train_data_waterloo',
... |
import unittest
from pydatacoll.protocols.iec104.frame import *
soe_bin = b"\x68\x15\x1a\x00\x06\x00\x1e\x01\x03\x00\x01\x00\x08\x00\x00\x00\xad\x39\x1c\x10\xda\x0b\x05"
i_bin = b"\x68\x0e\xe8\x00\x06\x00\x65\x01\x0a\x00\x01\x00\x00\x00\x00\x05"
s_bin = b"\x68\x04\x01\x00\x94\x00"
u_bin = b"\x68\x04\x07\x00\x00\x00"
... |
import numpy as np
import pandas as pd
def load_data():
feature = [];
label = []
with open('/Users/hanzhao/PycharmProjects/MLstudy/file/lrdataset.txt') as fr:
for line in fr.readlines():
line_arr = line.strip().split()
feature.append([1.0, float(line_arr[0]), float(line_arr... |
#-*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from .models import Dialog, Node
from .luis_cognition import cognizer
from .papago_translate import translator
import json
# Create your views here.
translator = translator()
cognizer = c... |
from flask import Flask, request, jsonify, Response
from flask_restful import Api, Resource
import shelve
from random import random
# curl command to test POST
# curl -i -H "Content-Type: application/json" -X POST -d "{\"no\": \"way\"}" http://127.0.0.1:5000/
def get_db():
return shelve.open("data")
def get_new... |
# coding=utf-8
# Copyright (C) 2020 NumS Development Team.
#
# 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... |
from bs4 import BeautifulSoup
import urllib.request as req
import urllib.parse as par
def show_me_the_graph(df):
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
g = nx.Graph()
g.add_edges_from(df)
pr = nx.pagerank(g)
fm._reb... |
# %load q02_get_unique_values/build.py
from greyatomlib.pandas_project.q01_read_csv_data_to_df.build import read_csv_data_to_df
import pandas as pd
import numpy as np
# You have been given the dataset already in 'ipl_df'.
ipl_df = read_csv_data_to_df('data/ipl_dataset.csv')
def get_unique_venues():
return ipl_df... |
from slyguy.language import BaseLanguage
class Language(BaseLanguage):
ASK_USERNAME = 30001
ASK_PASSWORD = 30002
LOGIN_ERROR = 30003
IP_ADDRESS_ERROR = 30005
TV = 30009
MOVIES = 30010
KIDS = 30011
FEAT... |
from django.db import models
from django.core.urlresolvers import reverse
# Create your models here.
class Article(models.Model):
STATUS_CHOICES = (
('d', 'Draft'),
('p', 'Published'),
)
title = models.CharField('标题', max_length=70)
body = models.TextField('正文')
created_time = mod... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Life's pathetic, have fun ("▔□▔)/hi~♡ Nasy.
Excited without bugs::
| * *
| . .
| .
| * ,
| .
|
| *
|... |
import random
class Person():
def __init__(self, name, hp=100, mp=100, atk = 70, magiclist = [], *args):
self.name = name
self.hp = hp
self.mp = mp
self.maxhp = hp
self.maxmp = mp
self.atk_high = atk + 10
self.atk_low = atk - 10
self.action = ["Physic... |
import json
import requests
from src.api.factory.exceptions.service_exceptions.google_exceptions.calendar_exceptions import CalendarParamsException, \
CalendarIdentifierException
from . import MaintainEventExecutor
class UpdateEventExecutor(MaintainEventExecutor):
def _create_action_endpoint(self) -> str:
... |
__author__ = 'aurel'
from .app import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_oauthlib.provider import OAuth2Provider
app = Flask(__name__)
db = SQLAlchemy()
oauth = OAuth2Provider()
def init_app(settings='aag_oauth_service.config.DevelopmentConfig'):
app.config.from_object(settings)
db.ini... |
# -*- coding: utf-8 -*-
# author: Ethosa
import sqlite3
import regex
from configparser import ConfigParser
from collections import OrderedDict
from random import randint
from os import remove
from saya import Vk, Uploader
from wakatime.wakatime import Wakatime
# Read and parse config file.
# [VK]
# USER_TOKEN, GROUP_... |
#!/usr/bin/python
### Required packages
# python-novaclient
from novaclient import client
import sys
import getopt
def main(argv):
global _debug, _instance, _username, _password, _tenant, _authurl, _action
_debug = 0
_action = "reboot-force" # reboot, reboot-force, stop
try:
opts, ar... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
i... |
import numpy as np
from numpy import random
from matplotlib.pyplot import *
import matplotlib.collections as collections
from matplotlib.colors import ColorConverter
import cv2
# We represent a center surrond haar feature
# as an array of 4 points and a color selector
# [x1,y1,x2,y2,x3,y3,x4,y4]
# First 2 points repr... |
#!/usr/bin/env python
# These are file types we do not want to send to DocumentCloud.
file_excludes = (
'accdb',
'aiff',
'au',
'db',
'ds_store',
'exe',
'flac',
'mid',
'midi',
'mdb',
'mov',
'mp3',
'mpa',
'ogg',
'pst',
'py',
'wav',
'wma',
'zip'
... |
# Copyright (c) 2021. by Roman N. Krivov a.k.a. Eochaid Bres Drow
import os
from typing import Dict, Any, Optional
from common.app_logger import get_logger
from common.convertors import remove_start_path_sep, append_end_path_sep
from common.utils import get_parameter
from s3._base._base import S3Base, INFO_OLD, INFO_... |
from flask import Flask
import os
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World! Running Flask inside Docker!!'
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True, port=5000)
|
"""
Created on 2018/9/3
@author: yby
@desc : 2018-09-3
contact author:ybychem@gmail.com
"""
import pandas as pd
import logging
from tasks.backend.orm import build_primary_key
from datetime import date, datetime, timedelta
from tasks.utils.fh_utils import try_2_date, STR_FORMAT_DATE, datetime_2_str, split_chunk, try_... |
import os
import requests
def download_image(image_name, image_url):
''' This function downloads images as binary-data files
to "images" folder.
'''
filename = os.path.join(images_dir_path, image_name)
response = requests.get(image_url)
with open(filename, "bw") as file:
file.write(re... |
"""Write a Python program to access and print a URL's content to the console."""
import urllib.request
def my_url_content(path):
return print((urllib.request.urlopen(path).read()))
path = 'https://stackoverflow.com/questions/15138614/how-can-i-read-the-contents-of-an-url-with-python'
my_url_content(path) |
from datetime import datetime
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User,Group,Permission
from django.contrib.contenttypes.models import ContentType
from annotatetext.models import Annotation
from actstream.m... |
def main():
bebida = 10.50
frete = 0.86
custoFixo = 1.50
qtdBebidas = eval(input("Quantas bebidas"))
result = ((bebida + frete) * qtdBebidas) + custoFixo
print("O valor total e: ", result)
main() |
# -*- coding: utf-8 -*-
{
'name': "independent_product_profit_margin",
'summary': """
Set the Price List based on Profit Margin.
One per Company
""",
'description': """
Set the Price List based on Profit Margin.
One per Company
""",
'author': "Juan Carlos Ferná... |
#!/usr/bin/env python
## Let's write some functions to log in, enable, and get all
## text on one page on a switch.
def login(telnet_conn):
# log in
pass
def enable(telnet_conn):
# enable mode on switch
pass
def disabling_paging(telnet_conn):
# all text on one page, no paging
pass
## This ... |
#!/usr/bin/env python
"""
Averages all unwrapped igrams, making images of the averge phase per date
"""
import glob
import itertools
import subprocess
import datetime
# import multiprocessing
import os
import h5py
import numpy as np
import argparse
import rasterio as rio
from pathlib import Path
from apertools import... |
from botmanlib.menus import OneListMenu
from telegram.ext import CallbackQueryHandler
from src.models import DBSession, Game
class UserTeamGamesMenu(OneListMenu):
menu_name = 'team_games_menu'
model = Game
def entry(self, update, context):
return super(UserTeamGamesMenu, self).entry(update, cont... |
#11.4.5.draw_length_tree.py
from Bio import Phylo
tree = Phylo.read("sample_tree4.nwk","newick")
Phylo.draw(tree)
|
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
Pre-condition: dna consists of characters 'A', 'T', 'C', 'G'
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return... |
# Ex040 - Understanding function arguments
def add_txt(t1, t2='Python'):
print(t1+':'+t2)
add_txt('Best') # 'Best:Python' is printed out.
add_txt(t2='Korea', t1='1st') # '1st:Korea' is printed out.
def func1(*args):
print(args)
def func2(width, height, **kwargs):
print(kwargs)
func1()... |
import threading
import time
def thead1():
print("子线程名字为{0:s}".format(threading.current_thread().name))
time.sleep(1)
print("{0:s}线程程结束".format(threading.current_thread().name))
if __name__ == '__main__':
#任何进程默认启动一个线程。称为主线程。
#主线程可以启动新的子线程。
#和父进程与子进程的原理雷同。
#current_theaad().返回当前线程的实例.
... |
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right= None
def sum_of_tree( trav):
if not trav:
return 0
return (trav.data + sum_of_tree(trav.left) + sum_of_tree(trav.right))
def isSumTree( node_t):
#ls , rs = 0,0
#check for empty tree... |
# Copyright (c) 2013 Rackspace, 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 wr... |
#!/usr/bin/env python
# Python script created by Lucas Hale
# Standard Python libraries
from __future__ import (absolute_import, print_function,
division, unicode_literals)
from collections import OrderedDict
import os
import sys
import uuid
# http://www.numpy.org/
import numpy as np
# http:... |
# test_geom.py
'''
Simple geometry description to test nfc workflow
'''
import FluidChannel as fc
testChannel = fc.FluidChannel(Lx_p = 2.,Ly_p = 3., Lz_p = 14.,N_divs = 50,
obst = fc.EmptyChannel(3.))
testChannel.write_bc_vtk()
|
import cv2
"""
OpenCV file download
!wget https://sourceforge.net/projects/opencvlibrary/files/opencv-unix/3.4.1/opencv-3.4.1.zip
"""
class Face_crop:
def __init__(self , image):
self.image = image
def Face_crop_haar(self , address):
print("* Attempting to crop out a face using Haar Cascades")
fc = cv2.Casc... |
a = [23, 14, 56, 12, 19, 9, 15, 25, 31, 42, 43]
i=0
count=0
sum=0
while i<len(a):
if a[i]%2==0:
print("even")
elif a[i]%2!=0:
print("odd")
count=count+(a[i])
sum=sum+(a[i])
i=i+1
print(count)
print(sum)
print(sum//i)
|
from typing import Any, Optional, Union
from tartiflette.coercers.common import CoercionResult, coercion_error
from tartiflette.coercers.inputs.null_coercer import null_coercer_wrapper
from tartiflette.utils.values import is_invalid_value
__all__ = ("scalar_coercer",)
@null_coercer_wrapper
async def scalar_coercer(... |
from unittest.mock import Mock
import pytest
from django.http import QueryDict
from rest_framework import serializers
from rest_framework.test import APIRequestFactory
from locations.models import Location
from locations.serializers import LocationSerializer
from trucks.models import Truck, TruckImage
from trucks.ser... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 21:01:23 2021
@author: aitor
"""
#Import the Body class to make Celestial Bodies!
from Final_Project_Code import Body
#Import the Simulate class to run the Simulation!!!!!
from Final_Project_Code import Simulate
def main():
#Gathers data from Body_Data folder... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.