text stringlengths 1 927k |
|---|
# -*- coding: utf-8 -*-
from pyfr.integrators import get_integrator
from pyfr.solvers.base import BaseSystem
from pyfr.solvers.euler import EulerSystem
from pyfr.solvers.navstokes import NavierStokesSystem
from pyfr.util import subclass_where
def get_solver(backend, rallocs, mesh, initsoln, cfg):
systemcls = sub... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 The TARTRL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
# Copyright 2017 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 required by applicable law or a... |
#coding:utf-8
#
# id: functional.arno.optimizer.opt_inner_join_merge_01
# title: INNER JOIN join merge
# decription: X JOIN Y ON (X.Field = Y.Field)
# When no index can be used on a INNER JOIN and there's a relation setup between X and Y then a MERGE should be performed.
# tracker_id: ... |
# 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... |
import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup as bs
from presscontrol.utils import tprint, read_cookies
from presscontrol.config import config
import pandas as pd
import random
import urllib
import newspaper
from urllib.parse import urlparse
import datetime
from googlesearch import sea... |
#NASA MPLNET functions
import numpy as np
import os
os.chdir('..')
os.chdir('..')
import PyKeller.signal_processing.pycuda_wavelets as py_wv
import PyKeller.signal_processing.wavelets as wv
import PyKeller.signal_processing.signal_analysis as sa
import PyKeller.atmos_sci.met_analysis as ma
import matplotlib.pyplot as ... |
import codecs
import os
from os import path
from setuptools import setup
def read(fname):
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
description = (
"Django package that provides Cloudinary storages for both media and "
"static files as well as management commands for rem... |
# Copyright 2021 BlobCity, 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 writing,... |
import time
import platform
class Timer:
def __init__(self):
self.time = []
self.name = []
self.history = {}
def initialize(self):
for i in range(1, len(self.time)):
name = self.name[i]
interval = self.time[i] - self.time[i - 1]
try:
... |
# Django settings for cvapp project.
try:
from localsettings import *
except ImportError:
pass
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
WWW_ROOT = '/var/www/'
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_nam... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-05 08:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('frontend', '0001_initial'),
]
operations = [
migrations.DeleteModel(
na... |
# Generated by Django 2.2.2 on 2019-07-18 09:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(... |
from sklearn import tree
from sklearn import ensemble
from sklearn import neighbors
from sklearn import neural_network
#X = [height, weight, shoe size]
X = [[190,80,10],[132,45,6],[189,67,9],[202,100,13],[145,67,6],[154,45,8],[148,89,9],[159,90,7],[188,78,12],[163,80,8]]
Y =['Female','Male','Male','Male','Female','F... |
class StringWriter(object):
def __init__(self):
self.contents = ''
def write(self,text):
self.contents += text
def getContents(self):
return self.contents
class XmlWriter(object):
class Node(object):
def __init__(self):
pass
class TextNode(Node):
... |
###########################################
# General Trapi Handler Exceptions
###########################################
class UnidentifiedQueryType(Exception):
def __str__(self):
return 'Unidentified query type. Please see https://github.com/di2ag/chp_client for details on our query types.'
class Unid... |
import streamlit as st
from pathlib import Path
import base64
from modules.toc import *
# Initial page config
page_title ='Postgres Cheatsheet for Python'
# st.set_page_config(
# page_title='Postgres Cheatsheet for Python',
# layout="wide",
# # initial_sidebar_state="expanded",
# )
def img_to_bytes(img_p... |
from django.http import Http404
from django.shortcuts import render, get_object_or_404, redirect
from .models import Product
from .forms import ProductForm, RawProductForm
def product_create_view(request):
form = ProductForm(request.POST or None)
if form.is_valid():
form.save()
form = ProductForm()
obj ... |
import time
import tools
import config
import random
import setting
from request import http
class honkai3rd:
def __init__(self) -> None:
self.headers = {
'Accept': 'application/json, text/plain, */*',
'DS': tools.Get_ds(web=True, web_old=True),
'Origin': 'ht... |
"""Implementation of the cache provider."""
# This plugin was not named "cache" to avoid conflicts with the external
# pytest-cache version.
import json
import os
from pathlib import Path
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Optional... |
# Copyright 2019 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 pwd
import subprocess
from jadi import component
from aj.api.http import url, HttpPlugin
from aj.api.endpoint import endpoint
@component(HttpPlugin)
class Handler(HttpPlugin):
def __init__(self, context):
self.context = context
@url(r'/api/passwd/list')
@endpoint(api=True)
def handle... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xrandr(AutotoolsPackage):
"""xrandr - primitive command line interface to X11 Resize, Rota... |
import asyncio
from ..pool import ConnectionPool, ClosedPool, EmptyPool
from .aioconnection import AIOLDAPConnection
MYPY = False
if MYPY:
from ..ldapclient import LDAPClient
class AIOPoolContextManager:
def __init__(self, pool, *args, **kwargs):
self.pool = pool
self.__conn = None
as... |
import json
import os
import urllib.request
import zipfile
from dataclasses import asdict
from pathlib import Path
from typing import Dict
import yaml
def safe_download(target_path: str, source_url: str, source_url2=None, min_bytes=1e0, error_msg="") -> None:
"""Attempts to download file from source_url or sourc... |
"""
saltfactories.utils.cli_scripts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code to generate Salt CLI scripts for test runs
"""
import logging
import pathlib
import stat
import textwrap
log = logging.getLogger(__name__)
SCRIPT_TEMPLATES = {
"salt": textwrap.dedent(
"""
import atexit
from salt.scr... |
#!/bin/python
import fnmatch
import os
import shutil
import subprocess
import sys
line_nb = False
for arg in sys.argv[1:]:
if (arg == "--with-line-nb"):
print("Enabling line numbers in the context locations.")
line_nb = True
else:
os.sys.exit("Non supported argument '" + arg + "'. Ab... |
from pathlib import Path
from typing import Any, Mapping
from aioworkers.core.config import ValueExtractor
from aioworkers.storage.http import Storage
BASE = Path(__file__).parent
configs = (BASE / "config.ini",)
class Client(Storage):
_service: Mapping[str, Any]
def set_config(self, config: ValueExtracto... |
# coding=utf8
import base64
import sys
import os
def f2b(file_path):
try:
os.remove(file_path + "__base64")
except Exception as e:
pass
base64_str_file = open(file_path + "__base64", "wb")
print "Processing..."
try:
with open(file_path, "rb") as f:
while True:... |
import sys
import re
if __name__ == "__main__":
file_name = sys.argv[1]
acc = []
punc = re.compile('([\.,\?!])')
with open(file_name, 'r', encoding="utf-8") as f:
while True:
sentence = f.readline().replace('\n', '')
if sentence:
sentence = punc.sub(r' \... |
"""
dj-stripe Invoice Model Tests.
"""
from copy import deepcopy
from decimal import Decimal
from unittest.mock import ANY, patch
import pytest
import stripe
from django.contrib.auth import get_user_model
from django.test.testcases import TestCase
from stripe.error import InvalidRequestError
from djstripe.enums impor... |
import math
speedofLight = 2.9979*pow(10,8)
def spaceShipSpeed():
firstLength = float(input('Input First Distance: '))
secondLength = float(input('Input Second Distance: '))
gamma = secondLength / firstLength
partone = (1-pow((1/gamma),2)) * pow(speedofLight, 2)
answer = math.sqrt(partone... |
"""
Provides basic formatting utilities.
"""
import datetime
import json
import shlex
import pipes
NONE_PLACEHOLDER = '<none>'
def contents_str(input_string, verbose=False):
"""
:param input_string: any string (may be None)
:param bool verbose: should use human-readable placeholders instead of empty
... |
"""
termcolors.py
"""
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = {color_names[x]: '3%s' % x for x in range(8)}
background = {color_names[x]: '4%s' % x for x in range(8)}
RESET = '0'
opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conce... |
# Generated by Django 3.2 on 2021-05-05 10:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('library_api', '0020_alter_meminjam_status_peminjaman'),
]
operations = [
migrations.AlterField(
model_name='meminjam',
... |
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information.
import unittest
from iptest import IronPythonTestCase, run_test, skipUnlessIronPython
@skipUnlessIronPython()
... |
# Copyright 2012 OpenStack Foundation.
# Copyright 2014 Intel Corporation
# 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/lic... |
# -*- coding: utf-8 -*-
import copy
from functools import partial
import numpy as np
from .base import Smoother
from ..base import Property
from ..types.multihypothesis import MultipleHypothesis
from ..types.prediction import Prediction, GaussianStatePrediction
from ..types.update import Update, GaussianStateUpdate
f... |
from trajectory import Trajectory, create_trajectory_list, filter, create_all_patient_trajectories
from hivevo.patients import Patient
import filenames
import matplotlib.pyplot as plt
import numpy as np
def get_activity(patient, region, normalize=False, remove_one_point_traj=False, min_freq=0.2):
time_bins = np.l... |
import csv
with open('movies.dat','w') as out:
with open('movies.csv') as csvfile:
movie = csv.reader(csvfile)
for row in movie:
out.write("::".join(row) + '\n')
with open('ratings.dat','w') as out:
with open('ratings.csv') as csvfile:
ratings = csv.reader(csvfile)
for row in ratings:
if row[0] != 'user... |
#!/usr/local/bin/ python3
# -*- coding: utf-8 -*-
# @Time : 2022-03-01 17:17
# @Author : Leo
# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
AES_SECRET_KEY = 'a' * 32 # 此处16|24|32个字符
IV = "1234567890123456"
# padding算法
BS = len(AES_SECRET_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - l... |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import unittest
import time... |
from bankapp.bank_funcs import withdraw
from sqlalchemy import select
from bankapp.models import Account
import pytest
@pytest.mark.parametrize(
"acc,amount,expected",
[
(1_000_002, 400, 600_00),
],
)
def test_withdraw(dbsession, acc, amount, expected):
withdraw(account=acc, amount=amount)
... |
#!/usr/bin/env python3
import argparse
import serial
from time import sleep
parser = argparse.ArgumentParser()
parser.add_argument('--port', default='COM4')
args = parser.parse_args()
ser = serial.Serial(args.port, 9600)
def send(msg, duration=0):
global ser
try:
ser.write(f'{msg}\r\n'.encode('utf-8')... |
from dataclasses import dataclass
import os
@dataclass
class Track:
title: str
artist: str
album: str
length: str
artwork: str
artworkFilePath: str
artworkBaseURL: str
uniqueId: str
ignore: bool
def getArtworkPath(self):
unglobbed = os.path.expanduser(self.artworkFile... |
from _operator import itemgetter
from dynafile import Dynafile
def test_scan_all_items(tmp_path):
db = Dynafile(tmp_path / "db")
aa = {
"PK": "1",
"SK": "aa",
}
ab = {
"PK": "1",
"SK": "ab",
}
ac = {
"PK": "1",
"SK": "ac",
}
ba = {
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def michelson(path):
"""Michelson's Determinations of the Velocity of Lig... |
# 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
# distr... |
#hex(x)
print(hex(255))
print(hex(-255)) |
# -*- coding: utf-8 -*-
import platform
from . import __version__
_sys_info = '{0}: {1}'.format(platform.system(), platform.machine())
_python_ver = platform.python_version()
USER_AGENT = 'UCloud UFile Python SDK {0} ({1} : Python/{2})'.format(__version__, _sys_info, _python_ver)
UCLOUD_PROXY_SUFFIX = '.cn-bj.ufile... |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 us... |
from __future__ import unicode_literals
import re
import sys
import subprocess
import os
infile, outfile = sys.argv[1:]
# usage: python3 devscripts/readme_for_cdn.py ../README.md to_be_converted.md
# git rev-parse --short master
git_commit = ''
for cwd in [
os.path.join(os.getcwd(), os.path.abspath(__file__), '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from conans import ConanFile, CMake, tools
import os
import shutil
class SPDLogSetupConan(ConanFile):
name = "spdlog_setup"
version = "master"
url = "https://github.com/bincrafters/conan-spdlog_setup"
description = "spdlog setup initialization via file co... |
# Generated by Django 3.1.7 on 2021-02-24 22:41
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Message',
fields=[
... |
r"""
Inline class
"""
from .block import Block
class InlineList(Block):
"""
InlineList class of PandocAST Element handler.
"""
def __init__(self, pan_elem, elem_type, type_def, create_element):
""" Constructor
@param pan_elem(Dict)
PandocAST Element
@param elem_typ... |
from pydantic import BaseModel, constr
from common_schemas import Response
from typing import List
from apps.climsoft.schemas import station_schema
class CreateStationQualifier(BaseModel):
qualifier: constr(max_length=255)
qualifierBeginDate: constr(max_length=50)
qualifierEndDate: constr(max_length=50)
... |
# Copyright (c) 2016, The Bifrost Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions an... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mail_editor', '0004_auto_20170406_1814'),
]
operations = [
migrations.AlterField(
model_name='mailtemplate',
... |
import numpy as np
import matplotlib.pyplot as plt
# W = J/sample
## Filtering
def sinc_kernel(cutoff, halflength): # cutoff should be between 0 and 1, TODO window function, low-pass/highpass
n = np.arange(-halflength, halflength + 1)
# get the sinc function:
out = np.sinc(cutoff*n)
# return the norm... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =============================================================================
## @file ostap/frames/frames.py
# Module with decoration of TDataFrame objects for efficient use in python
# @author Vanya BELYAEV Ivan.Belyaev@itep.ru
# @date 2018-06-16
# ================... |
#!/usr/bin/env python
import asyncio
import json
import logging
import sys
from functools import wraps
from typing import Optional, TextIO
import click
import uvloop
from rich.console import Console
from mtsync.connection import Connection
from mtsync.settings import Settings
from mtsync.synchronizer import Synchroni... |
# Copyright 2018, 2019. IBM All Rights Reserved.
# Copyright 2016 The TensorFlow 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/li... |
'''
Eventually we're going to support TF as well
'''
# import torch
# PT = {
# 'MODULE':nn.Module
# }
# TF = {
# } |
from torchvision import transforms
DICT = {
"mnist": transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
),
"cifar10_train": transforms.Compose(
[
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
... |
"""
ASGI config for PyTealChecker project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO... |
import logging
import datetime
from calendar import month_name
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.mail import get_connection
from gluu_ecommerce.utils import send_mail, generate_sha1
from account.connectors.idp_interface import email_exists
from account.mo... |
import os
import subprocess
from pathlib import Path
from warnings import warn
from .logging import get_logger
JULIA_PROJECT = str(Path(__file__).parent / "julia")
os.environ["JULIA_PROJECT"] = JULIA_PROJECT
log = get_logger("diffeqtorch_install")
def install_and_test(pyjulia=True, julia_deps=True, julia_sysimage=... |
r"""
Labelled permutations
A labelled (generalized) permutation is better suited to study the
dynamic of a translation surface than a reduced one (see the module
:mod:`sage.dynamics.interval_exchanges.reduced`). The latter is more
adapted to the study of strata. This kind of permutation was
introduced by Yoccoz [Yoc05... |
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and
# is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012)
from reversion.admin import VersionAdmin
from django.contrib.gis import admin
from .models import *
class Objec... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:owefsad
# datetime:2021/1/14 下午7:17
# software: PyCharm
# project: lingzhi-agent-server
import json
import os, re
import uuid, logging
from django.http import FileResponse
from dongtai.endpoint import OpenApiEndPoint, R
from drf_spectacular.utils import extend_sche... |
import requests # Importando biblioteca
API_KEY = "6e401fdf2b11f18db16cd6c71a777534" # Minha chave da API
cidade = input('Digite o nome da cidade : ' ) # Input para pesquisar a temperatura na cidade
link = f"https://api.openweathermap.org/data/2.5/weather?q={cidade}&appid={API_KEY}&lang=pt_br" #Link da API
req = requ... |
"""Arquivo a ser enviado ao sistema"""
def desafio1(number):
"""Função que retorna o valor entrado"""
return 0 |
import logging
import disnake
import pandas as pd
from bots import imps
from openbb_terminal.decorators import log_start_end
from openbb_terminal.stocks.government import quiverquant_model
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def lastcontracts_command(past_transactions_days: int = 2, num... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView,CreateView,UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from .models import Site
# Create your views here.
def welcome(request):
context = {
'sites': Site.object... |
"""
Module for OpenSCAP Management
"""
import os.path
import shlex
import shutil
import tempfile
from subprocess import PIPE, Popen
ArgumentParser = object
try:
import argparse # pylint: disable=minimum-python-version
ArgumentParser = argparse.ArgumentParser
HAS_ARGPARSE = True
except ImportError: #... |
#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitnamicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
parser = argparse.ArgumentParser(description='Remove the coverage data from a tracef... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import os
import pickle
from mmpt.utils import ShardedTensor
class Shard(object):
def __init__(
self,
... |
# -*- coding: utf-8 -*-
#BEGIN_HEADER
# The header block is where all import statments should live
import os
from Bio import SeqIO
from pprint import pprint, pformat
from AssemblyUtil.AssemblyUtilClient import AssemblyUtil
from KBaseReport.KBaseReportClient import KBaseReport
#END_HEADER
class psu_example:
'''
... |
# Implementation of Randomised Selection
"""
Naive Approach
---------
Parameters
---------
An arry with n distinct numbers
---------
Returns
---------
i(th) order statistic, i.e: i(th) smallest element of the input array
---------
Time Complexity
---------
O(n.log... |
import datetime
from wagtail.core import hooks
from wagtail.admin.site_summary import SummaryItem
from longclaw.orders.models import Order
from longclaw.stats import stats
from longclaw.configuration.models import Configuration
from longclaw.utils import ProductVariant, maybe_get_product_model
#from longclaw.utils impo... |
# Copyright (c) 2010-2012 OpenStack 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 agree... |
def print_hello():
print "Hello" |
# Generated by Django 2.2.10 on 2020-02-22 21:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', m... |
# 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 (t... |
# File containing exercises for chapter 8 of the Automate The Borring Stuff book - https://automatetheboringstuff.com/2e/chapter8/
# Uses library PyInputPlus -> pip install pyinputplus
import pyinputplus as pyip
def addsUpToTen(numbers):
numbersList = list(numbers)
for i, digit in enumerate(numbersList):
... |
import os
import shutil
import stat
def copy(src, dst, symlinks = False, ignore = None):
ign = shutil.ignore_patterns(ignore)
copytree(src,dst,symlinks,ign)
def copytree(src, dst, symlinks = False, ignore = None):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir... |
import os
CLSIDs = {
'3D Objects (folder)':'{0DB7E03F-FC29-4DC6-9020-FF41B59E513A}',
'Add Network Location':'{D4480A50-BA28-11d1-8E75-00C04FA31A86}',
'Administrative Tools':'{D20EA4E1-3957-11d2-A40B-0C5020524153}',
'Applications':'{4234d49b-0245-4df3-b780-3893943456e1}',
'AutoPlay':'{9C60DE1E-E5FC-40f4-A487-460851A8D9... |
gpd.read_file('../data/EUgrid10.geojson').head(1) |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""Test desidatamodel.stub functions
"""
import os
import unittest
from unittest.mock import patch
from pkg_resources import resource_filename
from astropy.io import fits
from collections import OrderedDict
from .datamodeltestcase ... |
from .payments import payment_keyboard
from .send_question import question_keyboard |
import json
class KeyboardButton:
def __init__(self, button_type: str, payload: dict):
self.type = button_type
self.payload = payload
def get_vk_repr(self):
kb_d = self.__dict__
kb_d['payload'] = json.dumps(self.payload)
color = kb_d.pop('color', None)
vk_dic... |
import arcade
from abbot.ui.gameplay_window import GameplayWindow
def main():
""" Main method """
window = GameplayWindow()
window.setup()
arcade.run()
if __name__ == "__main__":
main() |
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class SgeItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
pass |
num1 = float(input('Digite um número: '))
num2 = float(input('Digite um número: '))
if num1 > num2:
print('O número {:.2f} é maior que o número {:.2f}'.format(num1,num2))
elif num1 < num2:
print('O número {:.2f} é maior que o número {:.2f}'.format(num2,num1))
else:
print('O número {:.2f} é igual ao número {... |
from ..kernel import core
from ..character import characterKernel as ck
from functools import partial
from ..status.ability import Ability_tool
from ..execution.rules import ReservationRule, RuleSet
from . import globalSkill
from .jobbranch import warriors
from .jobclass import flora
from . import jobutils
from math im... |
# pyDFTD3 -- Python implementation of Grimme's D3 dispersion correction.
# Copyright (C) 2020 Rob Paton and contributors.
#
# This file is part of pyDFTD3.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import logging
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, reverse
from django.contri... |
# -*- coding: utf-8 -*-
"""This module provides functions related to plot or to plot data.
"""
from typhon.plots import cm # noqa
from typhon.plots.colors import * # noqa
from typhon.plots.common import * # noqa
from typhon.plots.formatter import * # noqa
from typhon.plots.plots import * # noqa
from typhon.plots... |
# Copyright 2018 Mycroft AI 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 writin... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas_rhino.geometry import RhinoPoint
class RhinoPoint(RhinoPoint):
@property
def xyz(self):
return self.geometry.X, self.geometry.Y, self.geometry.Z
def closest_point(self, *args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.