content stringlengths 5 1.05M |
|---|
from tennisim.game import prob_deuce_occurs
from tennisim.game import prob_game
from tennisim.game import prob_game_outcome
from tennisim.game import prob_win_deuce
from tennisim.game import theory_game
class TestTheoryGame:
"""Tests for the `theory_game` function"""
def test_theory_game_zero(self) -> None:
... |
#!/usr/bin/env python
# Google Code Jam 2017. Round 1B
# Problem B. Stable Neigh-bors
#
# * Problem
# You are lucky enough to own N pet unicorns. Each of your unicorns has
# either one or two of the following kinds of hairs in its mane: red hairs,
# yellow hairs, and blue hairs. The color of a mane depends on exactly ... |
from typing import TYPE_CHECKING, Optional, List, Tuple
import urwid
from .ansi_widget import ANSIWidget
if TYPE_CHECKING:
from .controller import Controller # noqa: F401
class View(urwid.WidgetWrap):
def __init__(self, controller: 'Controller') -> None:
self.controller = controller
self.... |
#Description: Example Python __init__ method, class methods and 'self'
#simple class
class Airplane:
pass
# create 2 instances of the Airplane class
airplane1 = Airplane()
airplane2 = Airplane()
#############################################
# simple class with __init__ method
class Airplane:
def __init__(se... |
import sys
import os
import click
from .. import shared
from .. import crypt
@shared.cli.command()
@click.argument("name", required=False)
@click.option("--list_docs", "-l", is_flag=True, default=True, required=False)
@click.option(
"--open-file",
"-o",
is_flag=True,
required=False,
help="Open t... |
"""
Source link:
https://stackoverflow.com/questions/3844430/how-to-get-the-duration-of-a-video-in-python
"""
def with_opencv(filename):
import cv2
video = cv2.VideoCapture(filename)
duration = video.get(cv2.CAP_PROP_POS_MSEC)
frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT)
return duration, fra... |
import logging
from sirbot import SirBot
from slack import methods
from slack.actions import Action
from slack.exceptions import SlackAPIError
from pybot.endpoints.slack.message_templates.mentor_volunteer import MentorVolunteer
from pybot.endpoints.slack.utils import MENTOR_CHANNEL
logger = logging.getLogger(__name_... |
"Get the latest cloud prices."
import requests
import math
from tqdm import tqdm
import pandas as pd
import os, re
import datetime, time
from pathlib import Path
class DataProcessor:
"Process and store a table of data for a particular provider."
def __init__(self, table_name):
data_path = Path.home()/... |
# -*- coding: utf-8 -*-
"""
Helper functions for tasks.
"""
import os
import subprocess
from frequent import __version__
#
# Constants
#
VERSION = __version__
#
# Functions
#
def convert_rst_to_markdown(content):
"""Convert an rst file to markdown"""
ret = list()
curr = content.splitlines(keepend... |
{
"targets": [
{
"target_name": "<(module_name)",
"product_dir": "<(module_path)",
"dependencies": ["deps/binding.gyp:libopus"],
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"cflags": [
"-pthread",
... |
# -*- coding: utf8 -*-
from contextlib import closing
import json
# pip install PyMySQL
import pymysql
from pymysql.constants.CLIENT import MULTI_STATEMENTS
def connect():
return pymysql.connect(host='localhost',
user='root',
password='',
... |
from .lexer import MCPLexer
from .parser import MCPParser
from .format import MCPFormat
import os
import io
import subprocess
from subprocess import PIPE
from packaging.version import Version
import difflib
import logging
import pprint
class MCPAst:
def __init__(self):
self.logger = logging.getLogger("mc... |
# Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""
Creating table for external mappings
Create Date: 2019-11-04 07:47:19.384426
"""
# disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=invalid-name
import sq... |
# -*- coding: utf-8 -*-
def decreasingNode(node_in=1970, node_out=5, hidden_layer=3, get_allNode=True):
"""A network structure that the number of neurons in each hidden layer is decreased proportionally.
Parameters
----------
node_in : int
The number of nodes in the input layer.
node_o... |
# import pandas as pd
import random
import matplotlib.pyplot as plt
import plotly.graph_objects as go
import numpy as np
import plotly.express as px
from pandas import DataFrame
from matplotlib.backends.backend_pdf import PdfPages
res_8 = [45, 27, 15, 28, 20, 8, 19, 21, 9, 24, 3, 16, 7, 12, 6, 9, 1, 3, 17, 27, 19, 26... |
import asyncio
import zmq
from zmq.asyncio import Context
context = Context()
loop = asyncio.get_event_loop()
async def client(i):
print("Connecting to server")
socket = context.socket(zmq.REQ)
socket.connect("tcp://localhost:5555")
request = f"Hello {i}"
print(f"Sending request: {request}")
... |
from . import base
from . import ea
from . import tti
from . import voltcraft
from . import gwinstek
from . import conrad_relay
from . import agilent
open = base.Base.open
|
import datetime
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils.translation import ugettext_lazy as _
from ..cart.models import Cart
from ..pricing import Price
from ..product.models import Variant
from ..util import count... |
import copy
import datetime as dt
import itertools
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.graphics.tsaplots as tpl
import statsmodels.tsa.arima.model as arm
import statsmodels.tsa.stattools as stls
import tqdm
from bokeh.io import ex... |
from analogs_finder.analysis import analysis_dataset as an
import types
import argparse
import sys
from functools import partial
import collections
from tqdm import tqdm
import numpy as np
from rdkit import Chem
from rdkit import DataStructs
from rdkit.Chem.Fingerprints import FingerprintMols
from multiprocessing impor... |
import os
from typing import Optional
from justmltools.s3.aws_credentials import AwsCredentials
from justmltools.s3.s3_bucket_object_downloader import S3BucketObjectDownloader
from justmltools.s3.s3_bucket_object_finder import S3BucketObjectFinder
class S3Downloader:
def __init__(self, credentials: Optional[Aw... |
import unittest
from py.tests.utils import test
from py import search_insert_position as sip
class TestSearch(unittest.TestCase):
@test(sip.Solution.search_insert)
def test_search_insert_position(self):
test([1, 3, 5, 6], 5, result=2)
test([1, 3, 5, 6], 2, result=1)
test([... |
from datetime import datetime, timedelta, timezone
import unittest
import paniot
from . import mixin
class IotApiTest(mixin.Mixin, unittest.TestCase):
def test_01(self):
resp = self.api.device(pagelength=0)
self.assertEqual(resp.status_code, 400)
def test_02(self):
with self.assertRa... |
#!/usr/bin/env python3
import requests
import urllib.request
from urllib3.exceptions import InsecureRequestWarning
import json
import secrets
import string
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
class redfish_request(object):
@staticmethod
... |
from airsim.client import MultirotorClient
from gym_flock.envs.airsim.utils import send_loc_commands, send_velocity_commands, setup_drones, get_states
from gym_flock.envs.airsim.utils import parse_settings
import numpy as np
import copy
from gym_flock.envs.spatial.make_map import gen_obstacle_grid
from gym_flock.envs... |
from distutils.core import setup
from setuptools import find_namespace_packages
with open("requirements_dev.txt") as f:
requirements_dev = f.read().splitlines()
with open("requirements.txt") as f:
requirements = f.read().splitlines()
with open("README.md") as f:
long_description = f.read()
setup(
n... |
import pygame
from deleteModule import delete_module
from PygameButton import PygameButton
pygame.init()
info_object = pygame.display.Info()
width = info_object.current_w
height = info_object.current_h
game_display = pygame.display.set_mode((width, height), pygame.RESIZABLE)
pygame.display.set_caption("Main frame")
cl... |
"""Complete arguments for the program."""
import argparse
def get_args():
"""Get the arguments for the training - testing of the net."""
parser = argparse.ArgumentParser(
description='Petrography training routine')
# Dataloading-related settings
parser.add_argument('--config', default='experi... |
#----------------------------------- processing.py -------------------------------------#
"""
This file contains utility functions to process a case into useful quantities (stored
in numpy arrays). These include calculating features, Pr_t, should_use, etc.
"""
# ------------ Import statements
import tecplot
i... |
# Copyright 2013-2015 Hugo Caille
#
# 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,... |
#!/usr/bin/python3
answer = 0
guess = 0
tries = 1
def inputAnswer():
global answer
answer = input("\n\nPlease enter correct answer: ")
return answer
def inputGuess():
global guess
guess = input("\n\nPlease enter your guess: ")
return guess
def errorChecking(x):
if len(x) == 4 and x.isdig... |
# Copyright (c) 2019 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
'''
En este modelo se ha realizado Grid Search de Random Forest con SMOTE
'''
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV
import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classificatio... |
from abc import abstractmethod
from threading import Lock
class AbstractIntegerSequenceGenerator(object):
"""
Abstract base class for generating a sequence of integers.
"""
def __iter__(self) -> "AbstractIntegerSequenceGenerator":
return self
@abstractmethod
def __next__(self) -> int... |
from elasticsearch.client.utils import NamespacedClient, query_params, _make_path
class FeaturesClient(NamespacedClient):
def __init__(self, client):
NamespacedClient.__init__(self, client)
default_store_request = self.transport.perform_request('GET', _make_path('_ltr'))
if not default_st... |
r"""
Lazy Laurent Series Rings
The ring of lazy Laurent series over a ring has usual arithmetic operations,
but it is actually not a ring in the usual sense since every
arithmetic operation gives a new series.
EXAMPLES:
The definition of Laurent series rings is not initially imported into the
global namespace. You n... |
# Sample to operate file and folder
import os
# current folder
current_dir_path = os.path.abspath('.')
print(current_dir_path)
# project folder
project_dir_path = os.path.abspath('..')
print(project_dir_path)
# list all folders in project folder
all_folders = [x for x in os.listdir('..') if os.path.isdir(os.path.j... |
# -*- coding: utf-8 -*-
###################################################################################################
#
# Smoothstreams plugin for XBMC
# Copyright (C) 2016 Smoothstreams
#
###################################################################################################
import time
import ca... |
from application.models.Entry import Entry
from application.app import db
from flask import jsonify
import traceback
class EntryService:
def create_entry(self, params):
try:
pass
except Exception as ex:
return {"Message": "Something went wrong", "exception": traceback.format_exc()}, 500
def get_all_entri... |
import numpy as np
import tempfile
import logging
import pandas as pd
import rpSBML
import libsbml
import os
##TODO: this really does not need to be an object
class rpMerge:
"""Class that hosts the different functions to merge two SBML files
"""
def __init__(self):
"""Constructor of the class
... |
import os
import random
def divide_splits(classes):
train_file = open('annotations/trainlist01.txt', 'w+')
test_file = open('annotations/testlist01.txt', 'w+')
for i, clazz in enumerate(classes):
seqs = list(os.listdir('videos/' + clazz))
seqs.sort()
for seq in seqs:
te... |
from mock import Mock
class ConditionalReturn(Mock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._returns = []
def __call__(self, *args, **kwargs):
expected_key = (args, kwargs)
for key, value in self._returns:
if key == expecte... |
# Copyright 2018 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, s... |
"""Functions for cleaning and modifying the datasets
"""
|
import os
from sys import argv
def countstep(filename):
textfile=open(filename, "r")
inputString=textfile.readlines()
i = 0
for line in inputString:
line = line.split()
wanted='Step'
if wanted in line:
i+=1
print( i)
if __name__ == "__main__":
try:
filename, outputfile = argv
except... |
import os
import sys
ganimator_dir = os.path.dirname(os.path.abspath(__file__))
print("ganimator_dir", ganimator_dir)
sys.path.append(ganimator_dir)
from . import functions
from .IDriver import IDriver
from .StyleGanTfDriver import StyleGanTfDriver
from .StyleGanPyDriver import StyleGanPyDriver
from .StyleGanPyExperim... |
import argparse
import os
def parse_params(args_parser):
args_parser.add_argument(
'--job-dir',
required=True
)
args_parser.add_argument(
'--train-file',
required=True
)
args_parser.add_argument(
'--output-file',
required=True
)
args_parser... |
from flask import Flask, json, send_file, request, make_response, jsonify
from Classes.Services.Main_Service import Service
from Classes.Services.GraphGeneratorService import GraphGenerator
from Classes.Enricher import Enricher
from Classes.Services.TDService import TDService
from Classes.FileTracker import FileTracke... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
# main imports
import os, sys
import argparse
import json
import numpy as np
import shutil
# PNG images
from PIL import Image
# others import
from ipfml import utils
from scipy.signal import savgol_filter
'''
Display progress information as progress bar
'''
def write_progress(progress):
barWidth = 180
outpu... |
def solve():
n = int(input())
arr = list(map(int,input().split()))
dp = [1]*n
for i in range(n):
for j in range(i-1,-1,-1):
if arr[i] > arr[j]:
dp[i] = max(dp[i],dp[j]+1)
print(max(dp))
if __name__ == '__main__':
solve() |
#! /usr/bin/env python
from subprocess import Popen,PIPE,STDOUT
import collections
import os
import sys
import time
import math
import os
import time
from urllib2 import urlopen
from random import randint
BOOTSTRAP_URL = "" #TODO
SENTINEL_GIT_URL = "https://github.com/KeplerPay/sentinel.git"
MN_USERNAME = "MN1"
MN_PO... |
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
tokens = self.tokenize(input)
result = [tokens]
while len(result[0]) > 1:
n = []
for i in result:
for j in range(0,le... |
#!/usr/bin/python
'''
This reads DHT11 sensor data and sends it to Adafruit.io (https://adafruit.io/)
for data analysis and visualization. Requires a valid account.
'''
import sys, time
import Adafruit_DHT
from Adafruit_IO import Client
aio = Client('<Insert Adafruit AIO key here>')
# Setup sensor type and Pin connect... |
#!/usr/bin/python3
import socket
import ipaddress
from queue import Queue
import threading
import argparse
parser = argparse.ArgumentParser(description="Look for open ports on a host or range of hosts.")
parser.add_argument('--iprange', help="Provide IP or IP range (CIDR notation).")
parser.add_argument('--sport', he... |
from PIL import Image
from datetime import datetime
from tkinter import filedialog
import tkinter as tk
from threading import Thread
from os import path
def RGBtoHEX(color):
#RGB to HEX conversion (no transparency)
return '#%02x%02x%02x' % (color)
def imagePixels(image):
#returns a list with i... |
def print_stats(n, duration):
pairs = [
('Total messages', n),
('Total duration (s)', duration),
('Throughput (msg/s)', n/duration)
]
for pair in pairs:
label, value = pair
print(' * {:<25}: {:10,.2f}'.format(label, value))
|
'''
Created on Aug 4, 2015
@author: Burkhard
'''
# create dictionary to hold connection info
dbConfig = {
'user': 'Admin',
'password': 'admin',
'host': '127.0.0.1',
}
|
# coding=utf-8
# Copyright 2016 MarkLogic Corporation
#
# 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 l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
"""
:authors:
Guannan Ma @mythmgn
:create_date:
"""
# import gc
import time
# import pympler
# from pympler import summary
# from pympler import muppy
from cup import log
from cup.services import heartbeat as cuphb
from cup.services import executor
from cup import net... |
from os import path
import numpy as np
from ..io import read_mesh_file, read_material_file
from ..utils import read_image
from .mesh import MeshBase
class Material(object):
"""A struct object containing information about the material.
The supported materials have the following:
- An ambient color
... |
# BSM Python library and command line tool
#
# Copyright (C) 2020 chargeIT mobility GmbH
#
# SPDX-License-Identifier: Apache-2.0
from ..crypto.curves import SECP256r1
from hashlib import sha256
# TODO: What about making the encoding a configurable property of the SunSpec
# device?
PYSUNSPEC_STRING_ENCODING = 'iso-8... |
# encoding: UTF-8
# CTA引擎中涉及到的交易方向类型
CTAORDER_BUY = u'买开'
CTAORDER_SELL = u'卖平'
CTAORDER_SHORT = u'卖开'
CTAORDER_COVER = u'买平'
# 本地停止单状态
STOPORDER_WAITING = u'等待中'
STOPORDER_CANCELLED = u'已撤销'
STOPORDER_TRIGGERED = u'已触发'
# 本地停止单前缀
STOPORDERPREFIX = 'CtaStopOrder.' |
# Author: https://github.com/AI-Cloud-and-Edge-Implementations/Project15-G4
import logging
import pandas as pd
logger = logging.getLogger(__name__)
class MetadataProcessing:
def __init__(self, metadata_filepath):
self.metadata_filepath = metadata_filepath
def load_metadata(self):
"""Calcul... |
import pygame
import sys
import random
import time
# Defining important global variables:-
##########################################################
pygame.init()
clock = pygame.time.Clock()
best_score = 0
longest_time = 0
width = 700
height = 750
DISPLAY_SCREEN = pygame.display.set_mode((width, height))
pygame.di... |
from abc import ABC, abstractmethod
class ShellInit(ABC):
@abstractmethod
def shell_init(self):
pass
@abstractmethod
def shell_set(self, profile_name=None):
pass
|
import csv
from django.core.management.base import BaseCommand, CommandError
from api.models import Company, Transaction
class Command(BaseCommand):
help = 'Imports transactions and companies from a CSV file into the database'
def add_arguments(self, parser):
parser.add_argument('csv_path', type=st... |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Mapping, Optional, Sequence
from . import tags
@dataclass
class CommandSpec:
positional_args: Sequence[str] = ()
tags: tags.Tags = field(default_factory=tags.Tags)
test_type: Optional[str] = None
must_follo... |
"""Test functionality of mixed stand simulator."""
import unittest
import copy
import numpy as np
import matplotlib.pyplot as plt
from mixed_stand_model import mixed_stand_approx as ms_approx
from mixed_stand_model import parameters
from tests.utils import get_sis_params, sis_analytic, ZERO_PARAMS
# TODO add tests f... |
import functools
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Flatten, Input, Conv2D, LeakyReLU
from modules.resizing import imresize_np
def _regularizer(weights_decay=5e-4):
return tf.keras.regularizers.l2(weights_decay)
def _kernel_init(scale=1.0, seed=N... |
from PIL import Image, ImageFilter
img = Image.open('./testImg/DSC_2292.JPG')
filtered_img = img.convert('L')
filtered_img.save("grey.png", 'png')
#filtered_img = img.filter(ImageFilter.SMOOTH)
#grey_img = img.filter(ImageFilter.)
#filtered_img.save("test.png", 'png')
#print(img.mode)
#print(img.format)
#print(dir(img... |
# Copyright 2013-2021 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 Libidl(AutotoolsPackage):
"""libraries for Interface Definition Language files"""
ho... |
import sys
result = ""
def V(i,j):
return 'V%d_%d' % (i,j)
def domains(Vs):
return [ q + ' in 1..9' for q in Vs ]
def all_different(Qs):
return 'all_distinct([' + ', '.join(Qs) + '])'
def get_column(j):
return [V(i,j) for i in range(9)]
def get_raw(i):
return [V(i,j) f... |
import json, sys
from cmd import Cmd
from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol
class CommandInterface(Cmd):
def do_call(self, call_id):
"""call <call id>
Create a new call with id ... |
"""
This is the master object, of which there may be only one.
User should not ever really need to access this object, but it will store and track the behavior and data of all
children behind the scenes
Mainloop method belongs here.
Construction mode may be turned on during development, which will make all children pro... |
import botocore.config
import logging
import time
from cartography.util import run_cleanup_job
logger = logging.getLogger(__name__)
# TODO memoize this
def _get_botocore_config():
return botocore.config.Config(
read_timeout=360,
retries={
'max_attempts': 10,
}
)
def get... |
import os
import time
import shutil
import sys
import uuid
from os.path import join
import logging
# TODO Check if it works correctly
# TODO try to make it completly automatic, without the need of entering the camera_type
def _logpath(path, names):
logging.info('Working in %s' % path)
return [] # nothing wi... |
class Propagator:
def __init__(self, input_shape=None):
self.input_shape = input_shape
@property
def network(self):
return self._network
@network.setter
def network(self, network):
self._network = self.torch2network(network)
|
from functions import *
from time import sleep
while True:
user = Biblioteca() # O usuário pode acessar a biblioteca
while True:
interface()
resp = leiaEnt('Escolha uma opção: ')
if resp == 1:
jogo = Arquivo(str(input('Nome: ')), str(input('Data: ')), str(input('Tempo Jogad... |
# accounts/urls.py
from django.urls import path
from .views import Actions
urlpatterns = [
path('', Actions.as_view(), name='actions'),
] |
from elements import AlgebraicStructure, Monoid
from firstorder import Identity
A = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
OP = {lambda x, y: x + y, lambda x, y: x * y, lambda x, y: x - y, lambda x, y: x / y}
ID = {Identity(A, lambda x, y: OP[0](x, y) == OP[0](y, x))}
print(AlgebraicStructure(A, OP, ID))
print(Monoid({1, 2,... |
"""
Znajdz najdluzsze powtorzenie w napisie.
"""
from collections import deque
# Wersja 1
def najdluzsze_powtorzenie_v1(slowo):
lista = list(slowo)
kolejka = deque(slowo[1:])
powtorzenia = list()
wynik = list()
while kolejka:
for i, elem in enumerate(kolejka):
if lista[i] == e... |
import yagmail
def send_email(title, url, image_url, description, username, password):
yag = yagmail.SMTP(username, password)
if image_url:
image_url_text = """<p><img src="{image_url}></p>"""
content = (f"<p><b>{title}</b></p>{image_url_text}<p>{description}</p>"
f'<p><a href="{u... |
from __future__ import print_function
from six import string_types
import numpy as np
from pyNastran.dev.bdf_vectorized.bdf import BDF
from pyNastran.utils.numpy_utils import integer_types
def bdf_renumber(bdf_filename, bdf_filename_out, size=8, is_double=False,
starting_id_dict=None, round_ids=Fal... |
import sys
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pprint import pprint
from ..data import load_rows, make_output_matrix
from ..bbox import extract
X, y = load_rows(9, 1)
yvis = np.copy(y)
result = extract(y[0])
fig,ax = plt.subplots(1)
pprint(result)
ax.imshow(make_output_matrix(yvi... |
import calendar, locale
locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')
cal = calendar.Calendar()
arr = list(enumerate(cal.yeardatescalendar(2021, 1)))
arr = [(i[0], i[1][0]) for i in arr]
weeks = {"odd": [], "even": []}
c = 1
for month_numb, month in arr:
for week_numb, week in enumerate(month):
if month_numb > 1 ... |
from systems.commands.index import Command
class Generate(Command('template.generate')):
def exec(self):
self.provision_template(
self.module,
self.module_template,
self.template_fields,
display_only = self.display_only
)
|
from time import sleep
from urllib.parse import quote
from urllib3.exceptions import MaxRetryError
import requests
from models.excel_handler import ExcelHandler
from models.drivers.web import WebDriver
from models.drivers.request import RequestDriver
from models.page import (
EntepreneurPage, CompanyPage,
Ca... |
def binary_search(arr, l, r, val):
"""
# Returns index of x in arr if present, else -1
Time Complexity: O(Logn)
Space Complexity: O(1)
:param arr: List[int]
:param val: int
:return: int
"""
if r >= l:
mid = 1 + (r - l) // 2
if arr[mid] == val:
return m... |
from fastapi import APIRouter, HTTPException
from services.scheduler_services import post_webhooks
from services.settings_services import SiteSettings, SiteTheme
from utils.global_scheduler import scheduler
from utils.snackbar import SnackResponse
router = APIRouter(tags=["Settings"])
@router.get("/api/site-settings... |
from dataclasses import dataclass
@dataclass
class ApiResult:
response_body: str = ""
query: str = ""
ip_address: str = ""
user_agent: str = ""
handler_time: str = ""
runtime_time: str = ""
class SafeDict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
... |
from django.apps import AppConfig
class CoursesemesterConfig(AppConfig):
name = 'coursesemester'
|
"""This module includes the implementation of the singleton decorator."""
import functools
from typing import Any
def singleton(cls):
"""Singleton decorator.
Args:
cls: class to decorate
Returns:
Callable[([_Any_Callable], _Any_Callable)]: Decorated class implementing the S... |
from rest_framework.renderers import BrowsableAPIRenderer
from djangorestframework_camel_case.settings import api_settings
from djangorestframework_camel_case.util import camelize
class CamelCaseJSONRenderer(api_settings.RENDERER_CLASS):
def render(self, data, *args, **kwargs):
return super().render(came... |
# coding: utf-8
"""
Experimental Looker API 3.1 Preview
This API 3.1 is in active development. Breaking changes are likely to occur to some API functions in future Looker releases until API 3.1 is officially launched and upgraded to beta status. If you have time and interest to experiment with new or modifie... |
# coding: utf-8
import math
velocidade = float(raw_input())
diametro = float(raw_input())
tempo = int(raw_input())
area = math.pi * (diametro/2.0) **2
vazao = velocidade * area * 1000
litros = tempo * vazao
print "Quantidade de água =", litros, "litros."
|
import tensorflow as tf
from core.nac_cell import NacCell
class NaluCell(object):
def __init__(self, input_shape, output_shape, scope = "nalu_cell"):
"""
:param input_shape: input sample dimension
:param output_shape: output dimension
:param scope: the tensorflow scope used for v... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Email'
db.create_table(u'db_email_backend_email', (
... |
import pytest
import numpy as np
import os
from shutil import rmtree
from numpy.testing import assert_equal, assert_allclose
from xsugar import Experiment
def testDirectoryAbsence(exp_data):
"""
Tests that our test directories are properly created and destroyed
"""
data_exists = os.path.isdir(exp_data[... |
"""Biapol utilities for Python
``biapol-utilities`` (a.k.a. ``biapolutils``) is a collection of utility functions
for image processing and visualization that is maintained by the Bio-image Analysis
Technology Development Group at DFG Cluster of Excellence "Physics of Life", TU Dresden
Subpackages
-----------
label
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.