text
stringlengths
1
927k
import logging import os import uuid import threading import sys import traceback log = logging.getLogger(__name__) log_i = log.info log_d = log.debug log_w = log.warning log_e = log.error log_c = log.critical class Plugins: "" _connections = set() _plugins = {} hooks = {} def register(self, plu...
''' Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua area e a quantidade de tinta necessária para pinta-la, sabendo que cada litro de tinta, pinta uma area de 2m^2 ''' #Recebendo informações: largura = float(input('Digite a largura da parede: ')) altura = float(input('Digite a altu...
import os,json # linux data_path = os.getcwd()+"/data/data.json" # 本地调试 # data_path = os.getcwd()+""+"/data/data.json" # windows # data_path = os.getcwd() + "\data\data.json" class RunBetData: def _get_json_data(self): '''读取json文件''' tmp_json = {} with open(data_path, 'r') as f: ...
from girder_worker import entrypoint from girder_worker.__main__ import main from girder_worker.entrypoint import discover_tasks import mock import pytest def setup_function(func): if hasattr(func, 'pytestmark'): for m in func.pytestmark: if m.name == 'namespace': namespace = ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # auth: Ruben López Vázquez import requests from bs4 import BeautifulSoup from IPython.core.display import clear_output from random import randint import pandas as pd import csv import time as t import sqlite3 import sys import os def is_digit(check_input): """ func...
from datetime import datetime, date from marqeta.response_models import datetime_object import json import re class CommandoModeNestedTransition(object): def __init__(self, json_response): self.json_response = json_response def __str__(self): return json.dumps(self.json_response, default=self...
import copy import logging import lib.const as C import lib.visit as v from .. import util from ..meta import class_nonce, register_class, class_lookup from ..meta.program import Program from ..meta.clazz import Clazz from ..meta.method import Method from ..meta.field import Field from ..meta.statement import Stateme...
#start 5 objectSwarmModelBugs.py from Tools import * from ModelSwarm import * nBugs = input("How many bugs? ") worldXSize= input("X Size of the world? ") worldYSize= input("Y Size of the world? ") nCycles = input("How many cycles? (0 = exit) ") modelSwarm = ModelSwarm(nBugs, nCycles, worldXSize, worldYSize) # create...
""" py3status """ from setuptools import find_packages, setup import fastentrypoints # noqa f401 import os import sys module_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "py3status") sys.path.insert(0, module_path) from version import version # noqa e402 sys.path.remove(module_path) # Utility...
# Copyright © 2019 Province of British Columbia # # 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 agr...
#!/usr/bin/env python3 """Create IGV session for archive.""" import argparse import os from lxml import etree parser = argparse.ArgumentParser(description="Create igv session.") parser.add_argument( "-f", "--input_file", required=True, help="File with paths to files for IGV." ) args = parser.parse_args() def...
import pygame, random pygame.init() pygame.mixer.init() # loading music pygame.mixer.music.load("batman_theme.mp3") try: batmanAttackSound = pygame.mixer.Sound("batman.wav") JokerattackSound = pygame.mixer.Sound("bullet.mp3") batmanLost = pygame.mixer.Sound("pushups.mp3") jokerHealthSound = pygame.mix...
import uuid import multiprocessing def my_function(): print 'My Unique Id: {0}'.format(uuid.uuid1()) if __name__ == '__main__': for x in range(16): process = multiprocessing.Process(target=my_function) process.start()
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
from django.views.generic import View from django.shortcuts import render, render_to_response from django.template import Template, Context from django.http import HttpResponse, HttpResponseRedirect from aboutrape.models import Category, Comment, UserProfile import json def about(request): users = UserProfile.obje...
__all__ = ('Emoji',) from scarletio import export, include from ..bases import DiscordEntity, id_sort_key from ..bases import instance_or_id_to_instance, instance_or_id_to_snowflake, iterable_of_instance_or_id_to_snowflakes from ..core import BUILTIN_EMOJIS, EMOJIS, GUILDS, UNICODE_TO_EMOJI from ..http import urls a...
from selenium import webdriver import threading from queue import Queue from tqdm import tqdm import warnings import time warnings.filterwarnings('ignore') span = '/html/body/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/div[2]/div[3]/div[1]/div[2]/div/span[1]/span' base_url = 'https://translate.google.com/#' class Tra...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/AllergyIntolerance) on 2020-02-03. # 2020, SMART Health IT. import sys from dataclasses import dataclass, field from typing import ClassVar, Optional, List from .age import Age from .annota...
# -*- coding: utf-8 -*- # Copyright (c) 2021, Subscription and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestLicenseSubscriptionSettings(unittest.TestCase): pass
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
""" .. module:: index :platform: Unix :synopsis: This module implements a set of useful indexing operations useful for analyses with multiple statistical descriptors .. moduleauthor:: Andrea Petri <apetri@phys.columbia.edu> """ from abc import ABCMeta from abc import abstractproperty #########################...
# Generated by Django 2.2.24 on 2022-01-03 07:50 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('hoodapp', '0006_auto_20220103_1050'), ] operations = [ migrations.RenameField( model_name='business', old_name='created_at'...
'''from math import factorial n = int(input('Digite um número ´para calcular seu fatorial: ')) f = factorial(n) print('O fatorial de {} é {}'.format(n, f))''' n = int(input('Digite um número ´para calcular seu fatorial: ')) c = n f = 1 print('Calculando {}! = '.format(n), end='') while c > 0: print('{} '.format(c)...
#! /usr/bin/env python # -*- coding: utf-8 -*- # update by guohongze@126.com from django.shortcuts import render, HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import auth from accounts.forms import LoginUserForm, EditUserForm, ChangePasswordForm, ChangeLdapPasswordF...
# ********************************************************************************** # # # # Project: FastClassAI workbecnch # # ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import torch.nn as nn from collections import OrderedDict from functools import partial from lib.models.tools.module_helper import ModuleHelper class GlobalAvgPool2d(nn.Module): def __init_...
from glove_tf_21.utils.file_utils import save_labels import numpy as np import os def test_cooc_count(preprocessing_glove, ix_sequences_full, cooc_dict): output_cooc = dict() for ix_seq in ix_sequences_full: output_cooc = preprocessing_glove.cooc_count(output_cooc, ix_seq) assert len(output_cooc...
''' Created on 8 Apr 2015 @author: edwin ''' import unittest import ibcc import logging import numpy as np from dynibcc import DynIBCC from ibcc_balanced import BalancedIBCC def check_accuracy(pT, target_acc, goldfile='./data/gold_verify.csv'): # check values are in tolerance range gold = np.genfromtxt(goldfi...
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2021 Rapptz Copyright (c) 2021-present Disnake Development 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 restrictio...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Mar 16 09:27:55 2017 @author: bell """ import pandas as pd import xarray as xa import matplotlib.pyplot as plt import seawater as sw import datetime from io_utils import ConfigParserLocal def cond2salinity(conductivity=None, temperature=None, pressur...
#_*_ coding:utf-8 _*_ import socket import mimetypes from urllib import parse class Request(object): def __init__(self, respServerSocket, client_addr, static_path, server_version): self.respServerSocket = respServerSocket self.requestByte = respServerSocket.recv(1024) self.static_path = ...
#!/usr/bin/env python3 ''' Shell ====== Shell interface for calling ROS2 actions. ''' import rclpy from cmd2 import Cmd2ArgumentParser, with_argparser from ros2_utils.cli import complete_action_call, ClientShell from .commander_client import CommanderClient from argparse import ArgumentParser class CommanderShell(Cli...
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Nobilitas Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from argparse import ArgumentParser from base64 import urlsafe_b64encode from binascii import hexlify f...
# -*- coding: utf-8 -*- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code from ccxt.base.exchange import Exchange # ----------------------------------------------------------------------------- try: basestri...
from glob import glob import numpy as np import scipy.sparse as sparse import matplotlib.pyplot as plt import networkx as nx import operator from spatialpower.tissue_generation import assign_labels from spatialpower.tissue_generation import visualization results_dir = './results/motif_detection/' adj_mat_list = np.sor...
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'Click>=6.0', 'pyota>=2.0', ...
from office365.directory.identities.userflows.language_page import UserFlowLanguagePage from office365.entity import Entity from office365.entity_collection import EntityCollection from office365.runtime.paths.resource_path import ResourcePath class UserFlowLanguageConfiguration(Entity): """Allows a user flow to ...
import math import RPi.GPIO as GPIO import time class max31865(object): """Reading Temperature from the MAX31865 with GPIO using the Raspberry Pi. Any pins can be used. Numpy can be used to completely solve the Callendar-Van Dusen equation but it slows the temp reading down. I commented it o...
# -*- coding: utf-8 -*- from django.views.generic import ListView from django.shortcuts import get_object_or_404, redirect import datetime from django.utils.timezone import utc from .models import Event, EventTalk from .models import Support, Sponsor class EventMixin(object): '''Add event to context of views th...
from typing import Any, Dict, Iterable, cast from openslides_backend.action.actions.meeting.shared_meeting import ( meeting_projector_default_replacements, ) from openslides_backend.permissions.management_levels import ( CommitteeManagementLevel, OrganizationManagementLevel, ) from tests.system.action.base...
from running_modes.utils.general import set_default_device_cuda from running_modes.constructors.base_running_mode import BaseRunningMode from running_modes.configurations import GeneralConfigurationEnvelope from running_modes.curriculum_learning.curriculum_runner import CurriculumRunner class CurriculumLearningModeC...
# SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries # # SPDX-License-Identifier: MIT """ `adafruit_rgb_display.hx8353` ==================================================== A simple driver for the HX8353-based displays. * Author(s): Radomir Dopieralski, Michael McWethy """ try: from micropy...
import pytest import time import test_sys.test_monitor.common @pytest.fixture def monitor_factory(tmp_path, unused_tcp_port_factory): processes = [] def run_monitor(parent_infos=[], default_algorithm='BLESS_ALL', group_algorithms={}, default_rank=1): monitor_port = unused_tcp_por...
import pygame import sys import copy from settings import * from player_class import * from enemy_class import * pygame.init() vec = pygame.math.Vector2 class App: def __init__(self): try: with open(SCORE_FILE, 'r') as file: self.highest_score = int(file.read()) excep...
QUERY_LATEST = 0 QUERY_ALL = 1 RESPONSE_BLOCKCHAIN = 2
from tests import BaseAppTestCase from werkzeug.exceptions import NotFound class FlaskOmMongoPaginationTestCase(BaseAppTestCase): "Flask-OmMongo Pagination class" def setup(self): super(FlaskOmMongoPaginationTestCase, self).setup() # saving 30 Todo's for i in range(4, 34): ...
import json import torch from tqdm import tqdm from .consts import ARGS, DEVICE, TOKENIZER def read_data(path): data = [] with open(path, encoding='utf8') as f: for line in f: line = json.loads(line) data.append(line) return data def batchify(sentence_dict, phrase_list_sampled, batch_size=32): batches ...
from Str2D.src.str2d import Str2D class TestStr2D(object): def test_constuction_one(self): s0_0 = 'a\nbc\ndef' s0_l = 'a \nbc \ndef' s0_c = ' a \nbc \ndef' s0_r = ' a\n bc\ndef' s0_w0 = s0_l s0_w4 = 'a \nbc \ndef ' s0_h0 = s0_l s0_h6_t = 'a \nb...
# coding: utf-8 # Distributed under the terms of the MIT License. """ This submodule implements the base PhaseDiagram creator that interfaces with QueryConvexHull and EnsembleHull. """ from traceback import print_exc import bisect import scipy.spatial import numpy as np from matador.utils.hull_utils import ( ...
print(42 if (input_int() - 2) <= (input_int() + 2) else 0)
# coding: utf-8 """ YNAB API Endpoints Our API uses a REST based design, leverages the JSON data format, and relies upon HTTPS for transport. We respond with meaningful HTTP response codes and if an error occurs, we include error details in the response body. API Documentation is at https://api.youneedabudge...
# Copyright 2015 IBM Corp. # # 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 a...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: wushuiyong # @Created Time : 日 1/ 1 23:43:12 2017 # @Description: import time from datetime import datetime import os import re from flask import current_app from flask_socketio import emit from walle.model.project import ProjectModel from walle.model.record ...
# Importing the Kratos Library import KratosMultiphysics as KM def Create(*args): raise Exception('"CoSimulationIO" is a baseclass and cannot be used directly!') class CoSimulationIO: """Baseclass defining the interface for the input and output methods for the communication with external solvers """ ...
import subprocess import sys import argparse parser = argparse.ArgumentParser(description='Deal with download errors.') parser.add_argument('object_dir', type=str, help='Ojective directory for detection') parser.add_argument('--del', action='store_true', default=False, help='If ...
""" Callbacks for printing, logging and log information.""" import sys import time import tempfile from contextlib import suppress from numbers import Number from itertools import cycle from pathlib import Path import numpy as np import tqdm from tabulate import tabulate from skorch.utils import Ansi from skorch.dat...
import numpy as np import os import sys import glob import uproot as ur import matplotlib.pyplot as plt import time import seaborn as sns import tensorflow as tf from graph_nets import utils_np from graph_nets import utils_tf from graph_nets.graphs import GraphsTuple import sonnet as snt import argparse import yaml imp...
from __future__ import absolute_import from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path, re_path from django.urls import reverse_lazy from django.http import HttpResponse from django.views.decorators.cache import cache_pag...
# # Timer.py -- GUI independent timers. # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import time from ginga.misc import Bunch, Callback from ginga.util.heaptimer import Timer as HeapTimer, TimerHeap class TimerError(Exception): pass class Time...
# coding: utf-8 from __future__ import unicode_literals import json import os from six import text_type from boxsdk.config import API from boxsdk.object.group import Group from boxsdk.object.item import Item from boxsdk.object.user import User from boxsdk.util.api_call_decorator import api_call from boxsdk.util.text_...
r"""A simple, fast, extensible JSON encoder and decoder JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. simplejson exposes an API familiar to uses of the standard library marshal and pickle modules. Encoding ba...
# Checkoff task def completetask(inputid: int): try: import sqlite3 import datetime import time from datetime import datetime, timedelta sqliteConnection = sqlite3.connect('habit_db.sqlite3') conn = sqliteConnection.cursor() records = conn.fetchall() ...
# -*- coding: utf-8 -*- # File generated according to DMatSetup.ui # WARNING! All changes made in this file will be lost! ## WARNING! All changes made in this file will be lost when recompiling UI file! ################################################################################ from PySide2.QtCore import * from ...
""" A Printer which converts an expression into its LaTeX equivalent. """ from typing import Any, Dict as tDict import itertools from sympy.core import Add, Float, Mod, Mul, Number, S, Symbol from sympy.core.alphabets import greeks from sympy.core.containers import Tuple from sympy.core.function import AppliedUndef,...
import os import sqlite3 import traceback class GeneralDB: ''' basic sqlite3 db which can be used for many purposes this isnt very safe probably but i dont really care''' def __init__(self, sessionName): self.connection = None self.cursor = None self.sessionName = sessionName ...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Common tools for unit-testing writers.''' import os import tempfile import unittest import StringIO from grit import grd_read...
from src.actions.action import Action from src.mapfeatures.intersection import Intersection from src.playerprofile import PlayerProfile from typing import Dict class BuildRoad(Action): def __init__(self, destination_id: int): self.destination_id = destination_id def __repr__(self): return f'b...
from rx.observable import Observable from rx.anonymousobservable import AnonymousObservable from rx.disposables import CompositeDisposable, \ SingleAssignmentDisposable, SerialDisposable from rx.internal import extensionmethod @extensionmethod(Observable) def delay_with_selector(self, subscription_delay=None, ...
import boto3 import datetime import numpy as np csv_headers = { 'ec2': [ 'name', 'instance', 'type', 'hypervisor', 'virtualization_type', 'architecture', 'ebs_optimized', 'image_id', 'key_name', 'metric', 'low', 'high',...
def load_from_backup(): """ """ # TODO pass def save_to_backup(): """ """ # TODO pass if __name__ == "__main__": pass
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # Recommend to initialize NUMA status at the most program begining (before any other imports) from tutel import system_init system_init.init_affinity_at_program_beginning() import os import time import torch import torch....
frase = str(input("\033[1;32mFrase\033[m: ")).upper().lower().strip() #A função .count(), conta quantas letras dentro do parâmetro aplicado existem dentro do valor da variável. print("A letra aparece:", frase.count("a")) #A função .find() busca a primeira letra dentro do parâmetro aplicado no valor da váriavel. print...
#!/usr/bin/env python # encoding: utf-8 r""" Routines for reading and writing a HDF5 output file This module reads and writes hdf5 files via either of the following modules: h5py - http://code.google.com/p/h5py/ PyTables - http://www.pytables.org/moin It will first try h5py and then PyTables and use the corre...
from layer import EchoLayer from yowsup.layers import YowParallelLayer from yowsup.layers.auth import YowAuthenticationProtocolLayer from yowsup.layers.protocol_messages import YowMessagesProtocolLayer from yowsup.layers.protocol_receipts import Yow...
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://www.apache.org/licenses/LICENSE-2.0. # # Unless...
import pyhf import pyhf.cli import pyhf.contrib.utils import pyhf.contrib.viz.brazil import pyhf.readxml import pyhf.writexml def test_top_level_public_api(): assert dir(pyhf) == [ "Model", "PatchSet", "Workspace", "__version__", "compat", "exceptions", "get...
from driver_actions import mass_login from twitter_promote import start_promoting from find_tweets import find_tweets if __name__ == "__main__": usernames = mass_login() start_promoting(usernames) # find_tweets(15)
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
""" Created on Okt 04 12:03 2018 @author: nishit """ import configparser import json import time from IO.redisDB import RedisDB from config.configUpdater import ConfigUpdater from prediction.loadPrediction import LoadPrediction from utils_intern.messageLogger import MessageLogger redisDB = RedisDB() training_thre...
#!/usr/bin/env python -O """ Script to test database capabilities and the DB-API interface for functionality and memory leaks. Adapted from a script by M-A Lemburg. """ from time import time import array import unittest class DatabaseTest(unittest.TestCase): db_module = None connect_args = () ...
import argparse import os if __name__ == "__main__": # ---------------------------------------- # Initialize the parameters # ---------------------------------------- parser = argparse.ArgumentParser() # pre-train, saving, and loading parameters parser.add_argument('--pre_train', type = ...
from urllib.request import urlretrieve import ssl from subprocess import call import os import zipfile print("Downloading sample data, please wait") filename = 'sample.zip' urlretrieve('https://tsx.org.au/sample.zip', filename) print("Extracting") zip_ref = zipfile.ZipFile(filename, 'r') zip_ref.extractall('.') zip_r...
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
import unittest from robot.libraries.BuiltIn import RobotNotRunningError from cumulusci.robotframework.Salesforce import Salesforce from unittest import mock # FIXME: we shouldn't have to tweak these tests for every # version. The tests should be smarter. class TestLocators(unittest.TestCase): @mock.patch("cumulu...
import numpy as np import pcl import pcl.pcl_visualization def main(): cloud = pcl.load_XYZRGB("../data/teacup.pcd") viewer = pcl.pcl_visualization.CloudViewing() viewer.ShowColorCloud(cloud, b'cloud') v = True while v: v = not(viewer.WasStopped()) if __name__ == "__main__": main()
# 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 ...
from typing import FrozenSet from collections import Iterable from math import log, ceil from mathsat import msat_term, msat_env from mathsat import msat_make_constant, msat_declare_function from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type from mathsat import msat_make_and, msa...
from __future__ import print_function import glob import json import logging import sys import threading import time import os import yaml import sh from sh import ErrorReturnCode log = logging.getLogger(__name__) # Resource types and their cli shortcuts # Mostly listed here: https://docs.openshift.com/online/cli...
# qubit number=2 # total number=13 import cirq import qiskit from qiskit import IBMQ from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2,floor, sqrt, pi import numpy a...
import pytest try: from bots.stocks.due_diligence.supplier import supplier_command except ImportError: pytest.skip(allow_module_level=True) @pytest.fixture(scope="module") def vcr_config(): return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ ("perio...
""" Copyright 2015 Smart Studio. 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 d...
#!/usr/bin/python3 # ---------------------------------------------------------------------- # Librairie Outils # ---------------------------------------------------------------------- """ Fast tools for programming Usage: >>> from mblibs.fast import FastSettings >>> settings = FastSettings("/path/to/yaml_or_json"...
import sys from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import twitter_credentials """Tweepy module is used to stream live tweets directly from Twitter in real-time. The tweets are visualized and then the TextBlob module is used to do sentiment analysis on the ...
########################################### # This is the ai_module class # This class handles the "clever stuff" such as working out best move(s) to play ########################################### # achieves 10% win rate in 50 games (more thorough testing may be warranted) import numpy as np from numpy import ran...
import sys from weasyprint import HTML def get_file_names(): if len(sys.argv) < 2: print('HTML file name not provided') exit HTML_file_name = sys.argv[1] pdf_file_name = HTML_file_name + '.pdf' if len(sys.argv) >= 3: pdf_file_name = sys.argv[2] return (HTML_file_name, pdf_file_name) def generat...
""" 백준 11948번 : 과목선택 """ score = [] for _ in range(6): score.append(int(input())) print(sum(score) - min(score[:4]) - min(score[4:]))
def test(): assert ( doc.text == "I like tree kangaroos and narwhals." ), "¿Procesaste el texto correctamente?" assert ( tree_kangaroos == doc[2:4] ), "¿Seleccionaste el span correcto para 'tree_kangaroos'?" assert ( tree_kangaroos_and_narwhals == doc[2:6] ), "¿Selecciona...
from gratipay.wireup import db, env from gratipay.models.team import Team, AlreadyMigrated db = db(env()) slugs = db.all(""" SELECT slug FROM teams WHERE is_approved IS TRUE """) for slug in slugs: team = Team.from_slug(slug) try: team.migrate_tips() print("Migrated tips for '%...
from django.db.utils import OperationalError from django.core.management import BaseCommand from django.db import connections import time class Command(BaseCommand): def handle(self, *args, **options): """Command to check for database connections""" self.stdout.write("Waiting for database conne...
''' Some helpful utlity functions and classes. ''' import random class RandomMac(object): def __init__(self): self.used_macs = set() def get_mac(self): temp = self._random_mac() while True: if temp not in self.used_macs: self.used_macs.add(temp) ...