content
stringlengths
5
1.05M
#! /usr/bin/python # -*- coding: iso-8859-1 -*- # Copyright (C) 2010 Dr. Ralf Schlatterbeck Open Source Consulting. # Reichergasse 131, A-3411 Weidling. # Web: http://www.runtux.com Email: office@runtux.com # All rights reserved # **************************************************************************** # # This pr...
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from collections import namedtuple VersionInfo = namedtuple('VersionInfo', [ 'major', 'minor', 'micro', 'releaselevel', 'serial' ]) version_info = VersionInfo(4, 7, 0, 'final', 0) _specifier_ = {...
"""This file provides the unittest for the YAML parser.""" import os import yaml import rdflib import unittest2 as unittest import logging from rdflib.compare import isomorphic from osp.core.ontology.cuba import rdflib_cuba from osp.core.ontology.ontology import Ontology from osp.core.ontology.parser.owl.parser import ...
#!/usr/bin/env python """ hostlists plugin to recursively query plugins based on type. This makes it possible to obtain lists of hosts by recursively querying multiple backends. For example: * Query dns for www.foo.com * Get a list of two hostnames back haproxy1.ny.foo.com and haproxy1.lax.foo.com. * Qu...
import itertools arrList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def Solution(): # 0~9 10๊ฐœ์˜ ์ˆซ์ž๋กœ 6์ž๋ฆฌ๋ฅผ ๋ฝ‘์•„์„œ ์•ž์— 3์ž๋ฆฌ๊ฐ€ RUN/TRIPLETE ํ™•์ธ ๋’ค์— 3์ž๋ฆฌ๊ฐ€ RUN/TRIPLETE ํ™•์ธ # 10๊ฐœ์˜ ์ˆซ์ž๋กœ 6๊ฐœ์˜ ์ž๋ฆฌ๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ• > Permutation (10P6) # 10x9x8x7x6x5 ๋งŒํผ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ ๋‚˜์˜ค๊ณ  ์—ฌ๊ธฐ์„œ ์•ž์— 3์ž๋ฆฌ ๋’ค์— 3์ž๋ฆฌ ๋‚˜๋ˆ ์„œ RUN, Triplete ์กฐ๊ฑด ํ™•์ธ์„ ์ง„ํ–‰ํ•  ๊ฒƒ # ใ„ฑ. ์•ž์˜ 3...
#!/usr/bin/env python """ Executes postfix `qshape` on every queue and ships it's output to StatsD. Supported enviroment variables and their respective defaults: STATSD_HOST=localhost STATSD_PORT=8125 STATSD_PREFIX=None STATSD_MAXUDPSIZE=512 STATSD_DELAY=10 """ import os import time import schedule import subprocess i...
# # gdb helper commands and functions for Linux kernel debugging # # loader module # # Copyright (c) Siemens AG, 2012, 2013 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import os sys.path.insert(0, os.path.dirname(__file__) + "/scripts/gdb"...
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: reco.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import...
from rest_framework import serializers from ..models.issue import Issue class IssueSerializer(serializers.ModelSerializer): class Meta: model = Issue fields = ["id", "pid", "name", "description", "creation_date", "publication_date", "status", "data"]
import mysql.connector from geopy.geocoders import Nominatim from instagram.client import InstagramAPI import json import urllib2 import flickr INSTAGRAM_CLIENT_ID = '5d56eb1e594c420997c394d1dca7fcea' INSTAGRAM_CLIENT_SECRET = 'd0d78baa1e4e4f4b8af9fd9588379968' api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID,client_...
liste = [-1, -2, -3] max = liste[0] for number in liste[1:]: if number > max: max = number print("Maximum:", max)
from .. import entities from .. import PlatformException from enum import Enum import os import mimetypes class LinkTypeEnum(str, Enum): """ State enum """ ID = "id" URL = "url" class Link: # noinspection PyShadowingBuiltins def __init__(self, name, type: LinkTypeEnum, ref, mimetype=Non...
""" Work in progress.. """ import neuroml import numpy as np class NetworkContainer(neuroml.Network): pass # def __getattr__(self,name): # print('Requesting in NC: %s'%name) class OptimizedList(object): array = None cursor = 0 def __init__(self, array=None, indices={}): self....
"""empty message Revision ID: a7a8db8ea2a7 Revises: 48cfa793003b Create Date: 2019-12-13 02:35:06.445420 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = 'a7a8db8ea2a7' down_revision = '48cfa793003b' branch_labels = None depends_on = None def upgrade(): # #...
# -*- coding: utf-8 -*- ############################################################################### # # ListAllTriggers # Returns all triggers for the authenticated account. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you m...
""" UserTest - tests whether a user is able to fetch his own user record, and modify fields. All users should be able to set their phone number. Only admins should be able to set their is_admin bit """ import json import os import requests import sys from urllib im...
# (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2021 from instana.propagators.http_propagator import HTTPPropagator from instana.w3c_trace_context.traceparent import Traceparent from instana.span_context import SpanContext from mock import patch import unittest class TestHTTPPropagatorTC(unittest.TestCas...
import subprocess import sys from pathlib import Path from typing import List import colorama from SCons.Script import Dir, File def get_godot_project_files(dir: Dir, ignore_directories: List[str] = []) -> list[Path]: """Return a list of all folders containing a project.godot file""" directory: Path = Path(s...
#!/usr/bin/env python from influxdb import InfluxDBClient import json class Transaction: TIME_PERIOD = '5m' def __init__(self): self.db_client = InfluxDBClient(host='localhost', port=8086, database='system_stats') self.db_client.create_database('system_stats') async def query_info_from...
from Assignment1 import * def test_case(): outlook = 'overcast,overcast,overcast,overcast,rainy,rainy,rainy,rainy,rainy,sunny,sunny,sunny,sunny,sunny'.split(',') temp = 'hot,cool,mild,hot,mild,cool,cool,mild,mild,hot,hot,mild,cool,mild'.split(',') humidity = 'high,normal,high,normal,high,normal,normal,n...
from django.test import SimpleTestCase from core import models class ModelTests(SimpleTestCase): def test_recipe_str(self): """Test the recipe string representation""" recipe = models.Recipe( name='Pizza', description='Put in the oven' ) self.assertEquals...
import json import re from django.http import HttpResponse, JsonResponse from django.views.generic import View from .forms import UserSerializer from .models import User allowed_filters = re.compile(r'^(username|email|gender|title|first_name|' r'last_name|street|city|state|phone|cell|pp...
# -*- coding: utf-8 -*- """ Created on Thu Apr 25 05:28:51 2019 @author: KCLIANG Helper functions for biophotobot. """ from sklearn.feature_extraction.text import HashingVectorizer from sklearn.externals import joblib import pandas as pd import numpy as np from unidecode import unidecode import string import json from...
import numpy import math def test(n): count = 0 for i in range (0, math.log(n)): i = i * 2 for j in range (0, i): count += 1 x = 10000000000000000000000000000000000000000000000000000000000000000000000000000000 print(math.log(x)) print(test(x))
from gcn.layers import * from gcn.metrics import * flags = tf.app.flags FLAGS = flags.FLAGS class Model(object): def __init__(self, **kwargs): allowed_kwargs = {'name', 'logging'} for kwarg in kwargs.keys(): assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg ...
import pandas as pd import numpy as np import geopandas as gpd import shared import sys args = sys.argv[1:] sectors = [ 'ag', 'natres', 'util', 'constr', 'man_lgt', 'man_hvy', 'man_bio', 'man_tech', 'logis', 'ret_reg', 'ret_loc', 'transp', 'info', 'fire', 'serv_pers', 'lease', 'prof', 'serv_bus', 'ed_k12', 'ed_h...
import numpy as np import tensorflow as tf from neuralmonkey.dataset import Dataset from neuralmonkey.encoders.recurrent import RecurrentEncoder from neuralmonkey.decoders.decoder import Decoder from neuralmonkey.logging import warn from neuralmonkey.model.model_part import ModelPart, FeedDict from neuralmonkey.decora...
{ "variables": { "root_dir%": "<!(cd)" }, "targets": [ { "target_name": "cursor", "sources": [ "<(root_dir)/lib/main.cpp", "<(root_dir)/lib/cursor.cpp" ] }, { "target_name": "window", "sources": [ "<(root_dir)/lib/main.cpp", "<(root_dir...
from project.animal import Animal class Reptile(Animal): def __init__(self, name): Animal.__init__(self, name)
""" Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected o...
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() def requirements(fname): for line in open(os.path.join(os.path.dirname(__file__), fname)): yield line.strip() setup( name="hipy", version='1.1', author="Mark Watso...
# coding: utf-8 import itertools temp = """ ":{trait}" "-{trait}" "={trait}" "~{trait}" "<{trait}>" "_{trait}" "/{trait}" "{trait}i" "\\{trait}" "\\{trait}" "[{trait}]" ".{trait}" "({trait})" """ def grouperElements(liste, function=len): return [list(g) for k,g in itertools.groupby(sorted(liste, key=function),...
import math import torch import torch.optim as optim import horovod.torch as hvd import numpy as np from horovod.torch.mpi_ops import allgather_async from legacy.utils import (ComputeA, ComputeG) from legacy.utils import update_running_avg from legacy.utils import try_contiguous from legacy.utils import cycle from leg...
from __future__ import unicode_literals import hashlib import io import os import sys import tempfile from django.core.management import call_command from django.test import TestCase from django_jsx.management.commands.compilejsx import compile_templates, END_JS, START_JS class CompileJSXTest(TestCase): """ ...
from invoke import task def status(s): """Prints things in bold.""" print("๐Ÿท๏ธ \033[1m{0}\033[0m".format(s)) @task def lint(ctx): """ Lint code using flake8 tools. """ status("linting code ...") ctx.run("flake8 --show-source --statistics --count") @task(lint) def install(ctx): """ ...
__all__ = [ 'ESMetricsClause', 'ESBucketClause', ] class ESMetricsClause(dict): def __init__(self): pass class ESBucketClause(dict): def __init__(self): pass
"""Binary Array Search implementation""" def binary_array_search(A, target): """ Use Binary Array Search to search for target in ordered list A. If target is found, a non-negative value is returned marking the location in A; if a negative number, x, is found then -x-1 is the location where target w...
#!/usr/bin/env python2.6 from time import time from gmpy import gcd # much faster than homecoded or fractions.gcd() start = time() # Section 1: preliminary definitions p = 1009; pm1 = p - 1 q = 3643; qm1 = q - 1 n = p * q phi = pm1 * qm1 # Section 2: building our list of usable e values, as an iterator object es =...
# -*- coding: UTF-8 -*- """ Raspberry Echo - Alexa Voice Command """ # # GPIO Settings # # GPIO Pin with button connected BUTTON = 26 # Name of your microphone/soundcard in arecord -L DEVICE = "plughw:1" # Setup PATH = "/home/pi/RaspberryEcho/" AUDIBLE_PATH = PATH + "audible/"
import os import sys import networkx as nx import re import json import numpy as np import math from datetime import datetime from queue import Queue from sklearn.preprocessing import MultiLabelBinarizer class DataHandler(object): @staticmethod def dict_add(d, key, add): if key in d: d[key]...
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from Tree import Tree class Topic: def __init__(self, id: int, text: str): self.id: int = id self.text = text def add_parent(self, parent: Tree): self.parent = parent
from comondata.models import * from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields="__all__" class QuizSerializer(serializers.ModelSerializer): class Meta: model=Quiz fields="__all__" class CameraSerializer(serializers.ModelSerializer): ...
import pandas as pd import numpy as np from qualang_tools.bakery.bakery import baking from qm.qua import * import importlib.resources as pkg_resources import qualang_tools.bakery as bakery_resources c1_ops = [ # Clifford operations ("I",), ("X",), ("Y",), ("Y", "X"), ("X/2", "Y/2"), ("X/2", "-...
# # PySNMP MIB module ATM-TRACE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-TRACE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:15:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
import numpy as np import hycpy as hy import hy fft = hy.fft out_size = 64 undersample_target = False # make target undersample (match with NN input)? # ----- Resize reconstructed ----- # load and get clean object and center it target = np.load('reconstruct/reconstructed.npy') l = target.shape target = hy.select_...
""" Problem 99 Comparing two numbers written in index form like 2^11 and 3^7 is not difficult, as any calculator would confirm that 2^11 = 2048 < 3^7 = 2187. However, confirming that 632382^518061 > 519432^525806 would be much more difficult, as both numbers contain over three million digits. Using base_exp.txt (righ...
#!/usr/bin/python # # Copyright 2018-2022 Polyaxon, 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 ...
class ModelWriteVisitor: @staticmethod def visit(instance, body): return instance.accept_write_visitor(body) class ModelReadVisitor: @staticmethod def visit_model(instance): return instance.accept_read_visitor(instance.crud_metadata)
import re import sys import uuid import copy import datetime from six import iteritems from . import RefinerUtils from pandajedi.jedicore import Interaction from pandajedi.jedicore import JediException from pandajedi.jedicore.JediTaskSpec import JediTaskSpec from pandajedi.jedicore.JediDatasetSpec import JediDatasetS...
def makeArrayConsecutive2(statues): statues.sort() return (statues[len(statues) - 1] - statues[0] + 1) - len(statues) def almostIncreasingSequence(sequence): sub_sequence = [] if sequence[0] < sequence[1]: sub_sequence.append(sequence[0]) else: sub_sequence.append(sequence[1]) ...
from src.Kernel import Kernel if __name__ == '__main__': kernel = Kernel() kernel.run()
import asyncio # noinspection PyCompatibility import contextvars import functools async def py36_asyncio_to_thread(func, *args, **kwargs): """Asynchronously run function *func* in a separate thread. Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current :class:...
import numpy as np import torch import torch.utils.data import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch import optim from sklearn.metrics import roc_auc_score class SequentialDataset(torch.utils.data.Dataset): def __init__(self, seqs, targets): self.seqs...
import os from base64 import b64encode from unittest import mock from app.auth.email import send_password_reset_email from app.models import User from flask import current_app @mock.patch("app.auth.email.send_email") def test_password_reset(mocked_email, test_client, init_database): user = User.query.filter_by(e...
# -*- coding: UTF-8 -*- import sys sys = reload(sys) sys.setdefaultencoding('utf8') sys.path.append("D:/Project/Dev/Develop/PyHelp/") sys.path.append("D:/Project/Dev/Develop/PyCode/") class Debug(object): def __init__(self): sys.stdout = self sys.stderr = self def write(self, s): from System import Console ...
import pytest from aioresponses import aioresponses from yarl import URL from async_web_scraper.fetch import ( download_web_page, write_to_file, scrape_all ) @pytest.mark.asyncio @pytest.mark.parametrize("status,body,expected", [ (200, "test", b"test"), ]) async def test_download_web_page(status, body, expe...
# coding: utf-8 from .base import BaseAPI, APISET @APISET.register('target') class TargetAPI(BaseAPI): def create(self, name, hosts, comment='', allow_simultaneous_ips=True, exclude_hosts=None, reverse_lookup_only=False, reverse_lookup_unify=False, port_list_id=None, ...
# Restarting nm (via systemctl): Warning: Unit file of created job changed on disk, 'systemctl --system daemon-reload' recommended. import os, os.path import tools import logger class Initscript: def __init__ (self, name): self.name=name self.initscript = '' def configure (self, rec): # ...
import autodisc as ad import importlib class FunctionRepresentation(ad.core.Representation): @staticmethod def default_config(): default_config = ad.core.Representation.default_config() default_config.function = None #default_config.config : if defined then this is given to the functi...
import inspect from django.contrib.contenttypes.models import ContentType from django.apps import apps from django.core import serializers from django.core.management import BaseCommand from field_history.models import FieldHistory from field_history.tracker import FieldHistoryTracker, get_serializer_name class Com...
from scraper import Scraper from bs4.element import Tag from typing import List PAGE_URL_PREFIX = "https://www.billboard.com/charts/hot-100" SONG_TITLE_SELECTORS = ".o-chart-results-list__item #title-of-a-story" ARTIST_SELECTORS = ".o-chart-results-list__item c-label" class ScraperBillboardChart(Scraper): def ...
import json import datetime import ApplicationObjects as Ao # Allows to specify how object of our custom classes should be represented as json class CustomJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Ao.TimeStamp): return{ # split to remove the micr...
import numpy as np import os import warnings import xml.etree.ElementTree as ET from chainercv.chainer_experimental.datasets.sliceable import GetterDataset from chainercv.datasets.voc import voc_utils from chainercv.utils import read_image class VOCBboxDataset(GetterDataset): """Bounding box dataset for PASCAL ...
# coding: utf-8 """ Django settings for zabbix_dashboard project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.p...
# -*- coding: utf-8 -*- import unittest import numpy as np from .. import xray from ...utils import units from ...patch import jsonpickle from ...materials import compoundfromname from ...testutils.subtest import TestCase class test_xray(TestCase): def test_interpolate(self): o1 = xray.KB(kind="linear")...
#/ <reference path="./testBlocks/mb.ts" /> class Foo: def __init__(self): self.x = 0 y = Foo() basic.showNumber(y.x)
#!/usr/bin/python # https://practice.geeksforgeeks.org/problems/four-elements/0 def validPair(pair1, pair2): """ Validates that the sets have nothing in common or the pair is unique """ for p1 in pair1: for p2 in pair2: if not p1 & p2: return True return False ...
#!/usr/bin/env python # encoding: utf-8 import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print 'begin %s %s():' % (text, func.__name__) fun = func(*args, **kw) print 'end %s %s():' % (text, func.__name__) ...
# ***************************************************************************** # # 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 # # ...
#!/usr/bin/env python3 # The MIT License (MIT) # # Copyright (c) 2018-2021 Frank Klaassen # # 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 ...
from factory import DjangoModelFactory from django.contrib.auth import get_user_model class UserFactory(DjangoModelFactory): class META: django_get_or_create = ('username',) FACTORY_FOR = get_user_model()
# Copyright 2021 Rafaล‚ Safin (rafsaf). 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 applicabl...
import pandas as pd import numpy as np import json from face_alignment_keras.image_depth_generator import image_depth_generator from face_alignment_keras.models import depths_network import tensorflow as tf class LossHistory(tf.keras.callbacks.Callback): def on_train_begin(self, logs={}): self.metrics = [...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pandas as pd from pandas.api.types import is_scalar from pandas.util._validators import validate_bool_kwarg from pandas.core.index import _ensure_index_from_sequences from pandas._libs import lib from pa...
from pytest import fixture, mark from textwrap import dedent from status_monitor.configuration import get_configuration from status_monitor.model.projects import Projects from status_monitor.model.checks import Checks @fixture def conf(temp_dir): cfg_path = temp_dir / 'conf.yaml' cfg_path.write_text(dedent('...
# -*- coding: utf-8 -*- """ Created on Tue Jul 20 15:23:41 2021 @author: user24 """ # Pg290 # Inheritance from datetime import datetime class Datalog: def __init__(self): self.loglist = [] def log(self, data): now = datetime.now() item = (now, data) self...
import numpy as np import matplotlib.pyplot as plt import sys_id_utils t0 = 0.0 t1 = 20.0 num_pts = 10000 save_data = True filename = 'example_data.txt' model_param = { 'inertia' : 3.0, 'damping' : 1.0, 'pro_gain' : 50.0, 'int_gain' : 50.0, 'int_leak' : 0.0, 'noise'...
import os from pathlib import Path import cv2 import logging logger = logging.getLogger(__name__) def convert_videos_to_frames(videos_path: str, frames_path: str) -> None: video_paths = extract_file_names(videos_path) for video_path in video_paths: extract_frames(video_path, frames_path) def extrac...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Setup file for the PyDoDo distribution.""" import sys from os.path import exists, join from setuptools import setup from distutils.dist import DistributionMetadata SRC_DIR = "src" # Add custom distribution meta-data, avoids warning when running setup DistributionMet...
output_dir = ""
import numpy as np from PIL import Image from mlchain.client import Client model = Client(api_address='http://localhost:5000').model() img1 = r"/home/pdd/Desktop/sandbox/reid-strong-baseline/f1/MicrosoftTeams-image.png" img2 = r"/home/pdd/Desktop/sandbox/reid-strong-baseline/f2/MicrosoftTeams-image (11).png" result = ...
""" ferrovial_servicios_a_bordo ------------------------------- - Eugenio Marinetto - nenetto@gmail.com ------------------------------- Created 12-05-2018 """ from pymake.utils.sql.mssql import MsSQL from pymake.utils.vpn.forticlient import FortiClient # Install packages def preinstall(): MsSQL.install() ...
def getNames(): names = ['Christopher', 'Susan', 'Danny'] newName = input('Enter last guest: ') names.append(newName) return names def printNames(names): for name in names: print(name) return
#import sys #sys.path.append('../pycoind') # These are known correct values generated using vanitygen (https://github.com/samr7/vanitygen) Tests = [ ('1testbXQ43Kpdnxnn3M2pPGb25K3hctMD', '5J9YULLVqfJvcSfGKX2ACas48YgH34BhrQFBpidVbrvVoTp6NbH'), ('1test2DuCNdPEhkyxa27Y9jZjNcETHYFL', '5JpyLYVkANv94ufoUw...
#!/usr/bin/env python # Copyright(C) 2012 thomasv@gitorious # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # ...
#!/usr/bin/python3 # https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation # https://realpython.com/documenting-python-code/ # https://www.python.org/dev/peps/pep-0008/ import os import sys from gtts import gTTS # type: ignore from Inputs import read_inputs # type: ignore def main(argv=sys.argv[1...
from collections import OrderedDict from rest_framework import viewsets, mixins, permissions, response from rest_framework.authtoken.models import Token from rest_framework.settings import api_settings as rest_settings from rest_framework_jwt.settings import api_settings as jwt_settings from rest_framework_jwt.authent...
""" Copyright (c) Microsoft Corporation. Licensed under the MIT license. """ import pytest import enum from common.statuseventhandler import StatusEventsHandler, EventHandler, StatusEvent def test__add_event_and_wait__1_event__handler_receives_it(): test_handler = TestEventHandler() status_handler = StatusEve...
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker # SQLALCHEMY_DATABASE_URL = "sqlite:///api/api_database.db" SQLALCHEMY_DATABASE_URL = "postgresql://postgres:catAcat34@data.cvr52zmcftji.eu-west-2.rds.amazonaws.com:5432/Users" engine =...
#!/usr/bin/env python3 import ctypes class Array(object): """ array implementation class """ def __init__(self): self.item_count = 0 self.array_capacity = 1 self.primary_array = self._create_array(self.array_capacity) def _create_array(self, array_capacity): """ ...
import requests def get_text_file(filename): api_key = 'e18f7b258888957' post_api = 'https://api.ocr.space/parse/image' OCREngine = 2 payload = {'apikey': api_key, 'ocrengine': OCREngine} with open(filename, 'rb') as file: req = requests.post(post_api, ...
from rctk.tests.base import BaseTest, build_task_queue class ClickCounter(object): def __init__(self): self.count = 0 self.lastcontrol = None def __call__(self, event): self.lastcontrol = event.control self.count += 1 from rctk.event import Clickable class BaseClickableTest(B...
import os import random RES_DIR = os.path.dirname(os.path.abspath("R5-G4.py")) + "/res/" #sound resources channelSounds = ['vc1.mp3', 'vc2.mp3', 'vc3.mp3'] randomSounds = ['r1.mp3', 'r2.mp3', 'r3.mp3', 'r4.mp3', 'r5.mp3', 'r6.mp3', 'r7.mp3', 'r8.mp3'] err = 'err.mp3' def returnChannelSound(): return RES_DIR + '...
""" Copyright 2019 Commtech, Inc. 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 use, copy, modify, merge, publish, distri...
import time import json import flask import logging from flask_login import LoginManager, login_user, logout_user, current_user, login_required from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, validators, DateTimeField from . import db from .user import User log_filename = ...
import urllib import urllib.request import sys from concurrent.futures import ThreadPoolExecutor # globals if len(sys.argv) < 2: link = 'https://jamescampbell.us' else: link = sys.argv[1] headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686)" p = 1 def getyou(linked=link): global p f =...
from pydantic import BaseModel from enum import Enum from typing import List, Optional, Set class Stringency(str, Enum): low = 'low' medium = 'medium' high = 'high' class Sequence(BaseModel): id: str seq: str description: Optional[str] = None class Species(BaseModel): id: int name:...
# 6-6. Polling: Use the code in favorite_languages.py (page 104). # โ€ข Make a list of people who should take the favorite languages poll. # Include some names that are already in the dictionary and some that are not. # โ€ข Loop through the list of people who should take the poll. If they have already taken the poll, # pr...
#!/usr/bin/micropython from popen import popen from count_forwards import count import sys import ure date_pattern = ure.compile('exp=([0-9][0-9][0-9][0-9])-([0-1]?[0-9])-([0-9][0-9])') import time today = time.localtime()[:3] idx=count() for i in reversed(range(idx)): r = popen('uci get firewall.@redirect[%i]...
from .camera import Camera from .lighting import Light, PointLight, SpotLight from .renderer import Renderer, RenderingContext from .vector import GridShape, Vector2, Int2, Float2, Vector3, Int3, Float3, Vector4, Int4, Float4 from .transform import MatrixTransform, Transform, GridTransform from .data_structures ...