content
stringlengths
5
1.05M
import os import collections import json class MainConfig: fileName = "main.config" settings = collections.OrderedDict() # Saves the cfg file @staticmethod def saveConfig(fileName): print("ConfigFile - Save Config") jsn = json.dumps(MainConfig.settings) fp...
import sys (*I,) = map(int, sys.stdin.read().split()) n, m = I[:2] aby = I[2 : 2 + m * 3] a = aby[::3] b = aby[1::3] y = aby[2::3] yab = list(zip(y, a, b)) q = I[2 + m * 3] vw = I[(m + 1) * 3 :] wv = list(zip(vw[1::2], vw[::2])) yab.sort(reverse=True) jwv = sorted(list(enumerate(wv)), reverse=True, key=...
# -*- coding: utf-8 -*- import json from pathlib import Path from typing import List, Dict, Any, Tuple, Set from tabulate import tabulate def get_duplicate_elements(file: str) -> None: print("Searching for duplicate elements in multi-opinion sentences") file_path = Path.home().joinpath(Path(file)) with...
#------------------------------------------------------------------------------ # # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # Written by: David C. Morrill # # Date: 12/06/2005 # #------------------------------------------------------------------------------ """ Pseudo-package for ...
""" Implementation of AbstractMQTTClient using asyncio-mqtt client. """ import asyncio import logging from asyncio.queues import QueueFull from typing import Any, List, Optional, Tuple from paho.mqtt import client as paho # type: ignore from asyncio_mqtt.client import Client, Will # type: ignore from . import ( ...
from contextlib import contextmanager import os @contextmanager def cd(newdir): prevdir = os.getcwd() os.chdir(os.path.expanduser(newdir)) try: yield finally: os.chdir(prevdir)
def load_parameters(): """ Loads the defined parameters """ # Input data params TASK_NAME = 'padchest' DATA_ROOT_PATH = '/home/lvapeab/DATASETS/' + TASK_NAME + '/' # Image and features files (the chars {} will be replaced by each type of features) IMG_FILES = {'train': 'Annotations/...
from django.shortcuts import render,redirect from django.contrib import messages # for message from django.urls import reverse from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from actualite.mo...
import os import numpy as np import glob name_array = ["single_select", "multi_select", "build_queue", "cargo", "cargo_slots_available", "screen", "minimap", "game_loop", "score_cumulative", "p...
import os import numpy as np import cv2 camera_matrix = np.load("camera_matrix.npy") dist_coeffs = np.load("dist_coeffs.npy")
"""Module to make the folder as python package."""
import pytest from tests.context import fables @pytest.mark.parametrize( "name,expected_extension", [ ("basic.csv", "csv"), ("basic.csv.xlsx", "xlsx"), ("basic", None), (".gitignore", None), ("basic.xlsb", "xlsb"), ], ) def test_extension_from_name(name, expected_e...
# coding=utf-8 import numpy as np from PySide import QtGui,QtCore import matplotlib matplotlib.use('Qt4Agg') matplotlib.rcParams['backend.qt4']='PySide' from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.collections import PatchCollectio...
from ...utils import Command from ..utils import DrivePlatformManager class UpdateCommand(Command): """Update an existing DriveApp.""" def setup(self, subparsers): parser = super(UpdateCommand, self).setup(subparsers) parser.add_argument('-i', '--drive_app_id', required=True, type=str, help="...
""" tests ~~~~~ Test suite for the synthrunner package. """
from collections import namedtuple from sklearn.ensemble import GradientBoostingRegressor from uq360.algorithms.builtinuq import BuiltinUQ class QuantileRegression(BuiltinUQ): """Quantile Regression uses quantile loss and learns two separate models for the upper and lower quantile to obtain the prediction i...
from torch.nn import * from collections import OrderedDict class DANet(Module): def __init__(self, num_classes=21, resnet_based_type=101): super(DANet, self).__init__() if resnet_based_type == 18: self.conv1 = _building_block_layer(2, 2, 2, 2) elif resnet_based_type == 34: ...
import face_recognition from os import path class Face: def __init__(self, app): self.storage = app.config["storage"] self.db = app.db self.faces = [] # storage all faces in caches array of face object self.known_encoding_faces = [] # faces data for recognition self.face_...
import math from django.conf import settings from django.core.mail import send_mail from django.http import HttpResponsePermanentRedirect from django.template.loader import render_to_string from django.utils.html import strip_tags from django.contrib.auth import password_validation, get_user_model from rest_framework ...
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import dace.library @dace.library.environment class cuBLAS: cmake_minimum_version = None cmake_packages = [] cmake_variables = {} cmake_includes = [] cmake_libraries = ["cublas"] cmake_compile_flags = [] cmake_lin...
from flask import render_template,request,redirect,url_for,abort from flask_login import login_required,current_user from . import main from .. import db,photos from ..request import get_quote from ..models import User,Role,Blog,Comment from .forms import UpdateProfile,BlogForm,CommentForm # View function for the land...
# coding: utf-8 from __future__ import unicode_literals from mock import patch import dns.resolver from django.core.files.base import ContentFile from django.core.urlresolvers import reverse from modoboa.core import factories as core_factories from modoboa.core.models import User from modoboa.lib.tests import ModoT...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- _author_ = 'ThomasHuke[thomashuke@icloud.com]' def file(n): t = [] while n < 99: t.append(n) n = n + 2 print( t ) file(1) #[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, #43, 45, 47, 49, 51, 53, 55, 57, 59, 6...
#!/usr/bin/env python from database import Database from dmidecode import system from random import randint from socket import getfqdn from sys import exit,stderr from time import sleep class SystemInfo(object): def __init__(self): if '0x0100' in system(): key='0x0100' else: key='0x0001' self.SKU=system...
import datetime from typing import Any, Dict, List, Optional from uuid import uuid4 from beanie import Document, Indexed from bson.objectid import ObjectId from pydantic import AnyHttpUrl, BaseModel, EmailStr, Field from ..general_use_models import PydanticObjectId class CompanyLetterModel(BaseModel): """Company...
#!/usr/bin/env python # -*- coding: utf-8 -*- from pathlib import Path import warnings import covsirphy as cs def main(): warnings.simplefilter("error") # Create output directory in example directory code_path = Path(__file__) input_dir = code_path.parent.with_name("input") output_dir = code_path...
import time from pathlib import Path from vae_model import * from datetime import datetime from utils import vae_create_dirs import logging from dataloader import * import argparse from tqdm import tqdm from vrae_model import VRAEEncoder, VRAEDecoder """ Specify datatset name (mnist, fashion-mnist, cifar1...
import re import time import logging import logging.handlers from datetime import datetime, timedelta from res.stations import stations from res.pinyin import PinYin import requests logger = logging.getLogger(__name__) def get_arg(arguments): # 当没有传入附加参数时 将默认参数均设置为True argkeys = ['-C', '-D', '-G', '-K', '-O'...
import configparser import os import random import unittest from TM1py.Objects import AnonymousSubset, Subset, Cube, Dimension, Element, Hierarchy, MDXView, NativeView from TM1py.Services import TM1Service config = configparser.ConfigParser() config.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'confi...
distancia = float(input('Digite a distancia da viagem: ')) if distancia <= 200: print('Sua viagem irá custar R${}'.format(distancia * 0.50)) if distancia > 200: print('Sua viagem irá custar R${}'.format(distancia * 0.45))
import pandas as pd import numpy as np import requests # class name,必須跟檔案名一致,例如 class SHORTSALE_MARGINPURCHASE_RATIO,檔名也是 SHORTSALE_MARGINPURCHASE_RATIO.py class SHORTSALE_MARGINPURCHASE_RATIO: def __init__(self, stock_price, ShortSaleMarginPurchaseTodayRatioThreshold=0.3, ...
import numpy as np import cv2 import pathlib from lane_lines_finder.process_step import ProcessStep from lane_lines_finder.camera import Camera from lane_lines_finder.perspective_transform import PerspectiveTransform from lane_lines_finder.lane_lines_detector import FindLines class DrawText(ProcessStep): def __in...
from django.contrib import admin # Register your models here. from adminapi.models import Admin admin.site.register(Admin)
# -*- coding: utf-8 -*- from odoo import api, fields, models class AccountAnalyticAccount(models.Model): _inherit = 'account.analytic.account' @api.multi @api.depends('prepared_hours_ids.purchased_hours') def compute_total_purchase_hours(self): total_purchased_hours = 0.0 for rec...
from . import python_aio, python_aio_asyncio from .abstract import AbstractContext, AbstractOperation from .version import __author__, __version__ try: from . import linux_aio from . import linux_aio_asyncio except ImportError: linux_aio = None # type: ignore linux_aio_asyncio = None # t...
# Copyright (c) 2021 kamyu. All rights reserved. # # Google Kick Start 2021 Round F - Problem B. Festival # https://codingcompetitions.withgoogle.com/kickstart/round/0000000000435bae/0000000000887dba # # Time: O(NlogN) # Space: O(N) # # Template: # https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/des...
from rest_framework import serializers from authors.apps.social_auth import twitter_auth, google_auth, facebook_auth from authors.apps.social_auth.register import register_user class AuthSerializer(serializers.Serializer): '''Class to register a user if decoded token information is valid''' def validate_token...
from crud.roles.r10_vistor import visitor from crud.roles.r11_banned_user import banned_user from crud.roles.r20_inactive_user import inactive_user from crud.roles.r30_normal_user import normal_user from crud.roles.r31_wiki_editor import wiki_editor from crud.roles.r40_super_user import super_user from crud.roles.r50_a...
''' Created on Jun 17, 2014 '''
# -*- encoding: utf-8 -*- """ Copyright(C) 2018-2019 TEST All rights reserved File : items.py Time : 2020/07/27 14:32:51 Author : mazhiyong Version : 1.0 """ from fastapi import APIRouter, HTTPException router = APIRouter() @router.get("/") async def read_items(): return [{"name": "Item...
import argparse import json import os from random import random, randrange, shuffle, choice import numpy as np import torch from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from tqdm import tqdm from config import is_mac_or_pycharm, Config from vocab import load_voca...
from enum import Enum class MouseEvents(Enum): RIGHT = 0 LEFT = 1 MIDDLE = 2 def mouse_click_identifier(event): """ event also has x & y attributes """ if event.num == 1: return MouseEvents.LEFT elif event.num == 2: return MouseEvents.RIGHT else: return MouseE...
#!/usr/bin/env python """ Use of this file is governed by the COPYING file in this distribution """ from distutils.core import setup setup(name = "KamaeliaContributionPackage", version = "0.1", description = "Sample Kamaelia Community Contribution package", author = "Michael", author_email = "m...
from __future__ import annotations from container.base import ClosedBase from graph.node import Node class ClosedList(ClosedBase): def __init__( self: ClosedList, ) -> None: super().__init__() self.elements_set = set() self.elements_list = list() def __...
#!/usr/bin/env python # --coding:utf-8-- # Copyright (c) 2020 vesoft inc. All rights reserved. # # This source code is licensed under Apache 2.0 License, # attached with Common Clause Condition 1.0, found in the LICENSES directory. import random import sys import os import time import logging import pytest current...
from typing import Dict, Optional import torch from torch import Tensor, nn from .. import properties as p # from ..md.md import (AdjEvl, EvalEnergies, EvalEnergiesForces, Reset, # BMEAdjEvl, BMEShk) from ..md.unified import UpdtMom, UpdtPos, UpdtTim from ..forcefield import EvlAdjEngFrc from ..f...
""" file: models/alista.py author: Xiaohan Chen last modified: 2021.04.05 Implementation ALISTA with support selection. """ import math import torch import numpy as np import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from .utils import shrink, shrink_...
from collections import OrderedDict, defaultdict from statistics import mean from tanakinator.common import( GameState, TextMessageForm, QuickMessageForm, ) from tanakinator.models import ( UserStatus, Question, Answer, Solution, Feature, Progress, PreparedSolution ) from tanakinator import db def ge...
class Solution: def maxIncreaseKeepingSkyline(self, grid: List[List[int]]) -> int: orig = sum([sum(l) for l in grid]) for i in range(len(grid)): for j in range(len(grid[i])): grid[i][j] = min(max(grid[i]), max([h[j] for h in grid])) return sum([sum(l) for l in gri...
#// Remon Hasan, 19th sep '19 s = input() n = len(s) m = n - 1; while m > 0: find = False for i in range(0, n - m): for j in range(i + 1, n - m + 1): match = True for k in range(0, m): if s[i+k] != s[j+k]: match = False brea...
# coding:utf-8 from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * import sys import qtawesome from random import randint from time import sleep, ctime import cv2 import os import numpy as np from net.mtcnn import mtcnn import utils.utils as ut...
import torch from rc_class.leaky_echo_cell import Leaky_echo_cell from rc_class.base_model_rc_ridge import Base_model_rc_ridge class Model_esn_ridge(Base_model_rc_ridge): def __init__(self, input_dim, hidden_dim, output_dim, w_generator, win_generator, wbias_generator, h0_Generator, h0_p...
""" INF100 Oblig oppgaver Av Daniel Liland """ # %% """ Oppgave 1 """ print('Gi tre heltall.') tall1 = int(input('Tall #1: ')) tall2 = int(input('Tall #2: ')) tall3 = int(input('Tall #3: ')) if tall1 < tall2 < tall3: print('Tallene er strengt stigende') elif tall1 > tall2 > tall3: print('Ta...
## Making the code corpus ## This involves ## Hit every directory and read every supported files ## Form a corpus of words without special symbols ## Tokenize Camel case and Hungarian to split out new words ## Any word below 3 letter is not Allowed import os import pandas as pd import sys import pickle import configpa...
#!/bin/python """Skript um Training des Modells durchzuführen. Das Model wird nach `model/model.pkl` persistiert. dvc Pipeline anlegen: ``` dvc run -d data\\interim\\model_dev_data.pkl -d nuedigex\\train.py -M score.json -o models/model.pkl python -m nuedigex.train ``` Ausführen mit ``` python -m neud...
# coding: utf8 """email_collection.py: EmailCollection is a container for Email class """ __author__ = "Sacha Schutz - Hugo Mayer" __copyright__ = "Copyright 2015, labsquare" __license__ = "GPL3" __email__ = "sacha@labsquare.org" import re import glob from unsec import Email, tools import logging c...
# Generated by Django 3.2.5 on 2021-08-08 13:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0003_event_resolution'), ] operations = [ migrations.AlterField( model_name='event', name='confidence', ...
from python_graphql_client import GraphqlClient import asyncio import socket UDP_IP = "192.168.10.113" UDP_PORT = 52522 def print_handle(data): print(str(data["data"]["liveMeasurement"]["power"])) MESSAGE = str(data["data"]["liveMeasurement"]["power"]).encode('UTF-8') sock = socket.socket(socket...
import numpy as np import pytest from dnnv.properties.expressions import * from dnnv.properties.transformers import PropagateConstants def test_Or_symbols(): transformer = PropagateConstants() a, b, c = Symbol("a"), Symbol("b"), Symbol("c") expr = Or(a, b, c) new_expr = transformer.visit(expr) a...
from http import HTTPStatus from backend.models import Participant from backend.serializers.participant_serializer import ParticipantSchema def test_get_participants_when_logged_in(auth_client, add_participants): """Test get participants list for logged in user.""" rv = auth_client.get("/participants/") ...
import os, sys, itertools from subprocess import call from multiprocessing import Pool from multiprocessing import Process from ScoreSet import ScoreSet from create_folds import CreateFolds from score_files import ScoreFile from milp import ComputeMILP from compact_folder import CompactFolder def Search(scoreFile, t...
import uvicorn from fastapi import FastAPI tags_metadata = [ { "name": "users", "description": "Operations with users. The **login** logic is also here.", }, { "name": "items", "description": "Manage items. So _fancy_ they have their own docs.", "externalDocs": { ...
#! /usr/bin/env python # Generates ISP connectivity log until stopped by user. # Version 0.2 from datetime import datetime import time import os import sys hostname = 'someIPaddress' logfile = open('pinglog.csv', 'w') logfile.write('Test of: ' + os.uname()[1]) logfile.close() if len(sys.argv) == 1: interval = 60 e...
from __future__ import annotations from spark_auto_mapper_fhir.fhir_types.uri import FhirUri from spark_auto_mapper_fhir.value_sets.generic_type import GenericTypeCode from spark_auto_mapper.type_definitions.defined_types import AutoMapperTextInputType # This file is auto-generated by generate_classes so do not edi...
""" Tests for numba.utils. """ from __future__ import print_function, absolute_import from numba import utils from numba import unittest_support as unittest class C(object): def __init__(self, value): self.value = value def __eq__(self, o): return self.value == o.value def __ne__(self,...
import pytest import mock from glabra import analyze from glabra import text class TestTextGenerator(object): @classmethod def setup_class(cls): cls.sa = analyze.SequenceAnalyzer( [("ab", 1), ("bc", 1), ("cd", 1), ("de", 1), ("xxxx", 1)]) cls.sa2 = analyze.SequenceAnalyzer( [("ab", 1), ("...
import types from huey.decorators import queue_command as _queue_command, periodic_command as _periodic_command, crontab from huey.djhuey import invoker def queue_command(retries=0, retry_delay=0): if type(retries) == types.FunctionType: return _queue_command(invoker)(retries) def inner(fn): ...
""" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> check_redis_qps.py >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> The function of this module is to roughly calculate the QPS of Redis. """ from os import popen from time import sleep import datetime import sys import argparse def InquireRedis(ip, port, answer): reqproccess...
#!/usr/bin/env python from __future__ import print_function """ c_module_toc.py """ import glob import re import sys PURE_C_RE = re.compile(r'.*/(.*)module\.c$') HELPER_C_RE = re.compile(r'.*/(.*)\.c$') def main(argv): # module name -> list of paths to include c_module_srcs = {} for c_path in glob.glob('Mod...
import re import time from typing import Optional, Any, Callable from slack_sdk.errors import SlackApiError def wrap_rate_limit(func: Callable, *args, **kwargs) -> Any: try: return func(*args, **kwargs) except SlackApiError as e: if e.response["error"] != "ratelimited": raise e ...
from homeworks.nikita_marchenkov.lesson11 import level02 def test(): obj = level02.User("Nikita", "erastfandorin228@mail.ru") assert isinstance(obj, level02.User) assert obj.name assert obj.email
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-08-01 07:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('quotas', '0001_initial'), ] operations = [ migrations.AddField( ...
from allauth.account import app_settings from allauth.account.utils import send_email_confirmation from django.contrib.auth import authenticate from django.contrib.auth.forms import PasswordResetForm from phonenumber_field.serializerfields import PhoneNumberField from rest_auth.serializers import ( PasswordResetSer...
"""Module to remove the noise from Project Gutenberg texts.""" import os from .text import TEXT_END_MARKERS, TEXT_START_MARKERS, LEGALESE_END_MARKERS, LEGALESE_START_MARKERS def strip_headers(text): """Remove lines that are part of the Project Gutenberg header or footer. Note: this function is a port of the...
n = int(input()) matrix = [row for lists in range(n) for index, row in enumerate(input())] last_pos_possible = [] pos = "" last_count_mov = 0 for i in range(len(matrix)): row = matrix[i] if "k" in row: k_row_i = row.index("k") pos = f"{i}:{k_row_i}" break def check_for_ops(): globa...
# -*- coding: utf-8 -*- import json import logging from django.test.client import Client from networkapi.test.test_case import NetworkApiTestCase log = logging.getLogger(__name__) class TestCIDRPostTestCase(NetworkApiTestCase): fixtures = [ 'networkapi/system/fixtures/initial_variables.json', ...
class Search: def __init__(self, problem, parameters): self.problem = problem self.parameters = parameters def run(self): if self.parameters['method'] == 'ambs': self.parameters.pop('method') from ytopt.search.ambs import AMBS search = AMBS(problem=se...
import os import time from psychopy import core, visual, gui, data, event from psychopy.tools.filetools import fromFile, toFile from random import randint, shuffle from psychopy.iohub import launchHubServer, EventConstants # By default, ioHub will create Keyboard and Mouse devices and # start monitoring for any events...
''' **Reverse a String** - Enter a string and the program will reverse it and print it out. ''' def main(): s = raw_input('Enter string to be reversed: ') print s[::-1] if __name__ == '__main__': main()
# $Id$ # # Copyright (C) 2001-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ unit testing code f...
# # @lc app=leetcode id=855 lang=python3 # # [855] Exam Room # # @lc code=start import bisect class ExamRoom(object): def __init__(self, N): self.N, self.L = N, [] def seat(self): N, L = self.N, self.L if not L: res = 0 else: d, res = L[0], 0 for a...
cores = {'vermelho':'\033[1;31m', 'verde':'\033[1;32m', 'azul':'\033[1;34m','limpar':'\033[m','amarelo':'\033[1;33m','ciano':'\033[1;36m'} número = int(input('Digite um número inteiro: ')) print('''Escolha uma das bases para conversão: [1] BINÁRIO [2] OCTAL [3] HEXADECIMAL''') base = int(input('Qual é a sua opção: '))...
from setuptools import setup from python_avatars import __version__ with open('README.md') as readme_file: README = readme_file.read() setup_args = dict( name='python_avatars', version=__version__, description='SVG avatar library for Python', long_description_content_type="text/markdown", lon...
#!/usr/bin/python import datetime, openpyxl as xl, os from argparse import Namespace import code import operator, collections, re, argparse from django.conf import settings from django.core.management.base import BaseCommand, CommandError import utils.sms_utils as sms import mwbase.models as mwbase import swapper Auto...
# -*- coding: utf-8 -*- import pickle import torch from torch.autograd import Variable # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. from dataset_gen import DatasetGenerator file = 'train' with open(file, mode='rb') as f: pos, neg = pickle.load(f) train = []...
""" @author: Timothy Brathwaite @name: Bootstrap Sampler @summary: This module provides functions that will perform the stratified resampling needed for the bootstrapping procedure. """ from collections import OrderedDict import numpy as np import pandas as pd def relate_obs_ids_to_chosen_alts(...
#!/usr/bin/env python # Script to combine the various output FITS files from 'find_events.py'. # Input argument is a directory path in which there are sets of files of # the following form: # # geant_events_all_[0-9]+_frames.fits # geant_events_all_[0-9]+_pix.fits # geant_events_all_[0-9]+_evt.fits # geant_eve...
# Generated by Django 3.2.12 on 2022-04-12 13:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("product", "0166_update_publication_date_and_available_for_purchase"), ] operations = [ migrations.AddField( model_name="digital...
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import os import psycopg2 import pytest from app_settings import AppSettings from os import listdir from coop_evolve.simulation_run import SimulationRun from coop_evolve.db_setup import DB_Setup class TestSimulationRunCreation: def test_defaults(sel...
import RPi.GPIO as GPIO import time POWER_PIN = 15 class Power: @classmethod def init(cls): # Set power pin to output GPIO.setup(POWER_PIN, GPIO.OUT) # Set default power state to off GPIO.output(POWER_PIN, GPIO.LOW) @classmethod def toggle(cls): GPIO.output(POWER_PIN, GPIO.HIGH) time...
from typing import Any from .HSDCommands import HSDCmd class OtherDevHSDCmd(HSDCmd): @staticmethod def from_dict(self, obj: Any): pass def to_dict(self): pass class OtherDevHSDGetCmd(OtherDevHSDCmd): pass class OtherDevHSDSetCmd(OtherDevHSDCmd): pass cla...
import re from os.path import join import glob import os import pandas as pd from datetime import date import pygal from pygal.style import BlueStyle from pygal.style import DarkGreenBlueStyle from pygal.style import TurquoiseStyle from pygal.style import CleanStyle from collections import Counter from pygal.style impo...
import argparse import smtplib from datetime import datetime from email.mime.text import MIMEText GOOGLE_SMTP_SERVER = 'smtp.gmail.com' TLS_PORT = 587 def smtp_login(username, password, server=GOOGLE_SMTP_SERVER, port=TLS_PORT): server = smtplib.SMTP(server, port) server.starttls() server.login(username...
import argparse import logging import torch import torchvision import torchvision.transforms as transforms import torch.optim as optim import torch.nn as nn from models import SupCEResNet PATH = './saved_models/cifar_resnet_' INIT_LR = 0.1 EPOCHS = 70 DECREASING_LR = [20, 40] DROP_LR = .1 # set device settings devi...
from rest_framework.generics import ListAPIView from rest_framework import permissions from .models import Hero from .serializers import HeroSerializer class HeroListView(ListAPIView): permission_classes = (permissions.AllowAny, ) queryset = Hero.objects.all() serializer_class = HeroSerializer pagina...
import re, subprocess, unittest from mock import MagicMock, Mock, patch from click.testing import CliRunner from .context import hlcloud from hlcloud import cli_buckets_list class CliBucketsListTest(unittest.TestCase): @patch("google.cloud.storage.Client") def test_buckets_list(self, client_patch): e...
from magma import wire, compile, EndCircuit from loam.boards.icestick import IceStick, Decoder icestick = IceStick() for i in range(2): icestick.J1[i].input().on() for i in range(4): icestick.J3[i].output().on() main = icestick.main() decoder = Decoder(2) wire( decoder(main.J1), main.J3 ) EndCircuit()
from typing import Tuple from Toggl.togglApi import getTogglReport, obtainBase64Pdf from Utils.systemUtils import getWorkspaceId, getTogglToken from Wire.proxy import sendMessage def processMessage(message): if message["type"] == "conversation.new_text": processTextMessage(message) def processTextMessa...
from distutils.extension import Extension from Cython.Build import build_ext, cythonize def build(setup_kwargs): """Build extension modules.""" setup_kwargs.update( { "ext_modules": cythonize( [ Extension("credis.base", ["credis/base.pyx"]), ...
# Directory and File locations DATASETDIR = "driving_dataset/" MODELDIR = "save" MODELFILE = MODELDIR + "/model.ckpt" LOGDIR = "logs"