content
stringlengths
5
1.05M
#!/bin/python #comando para ver temp /opt/vc/bin/vcgencmd measure_temp # Simple script for shutting down the raspberry Pi at the press of a button. #**Adding it to startup #sudo gedit /etc/rc.local #** Add the following line before the #fi at the end of the file. #sudo python /home/pi/Scripts/shutdown_pi.py & im...
# -*- coding: utf-8 -*- # Copyright (c) 2019, ElasticRun and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document # from latte.latte_core.naming.autoname import lockless_autoname from latte.utils.indexing import ...
import json from threading import Thread import ibm_watson from ibm_watson.websocket import RecognizeCallback, AudioSource from StreamSpeechService import * from TextSpeechService import * from NLUService import * from LanguageTranslatorService import * from PersonalityInsightsService import * from TwitterService imp...
import os from .version import __version__ APP_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) default_app_config = 'irekua_rest_api.apps.IrekuaRestApiConfig'
import mock import unittest import requests import slumber class ResourceTestCase(unittest.TestCase): def setUp(self): self.base_resource = slumber.Resource(base_url="http://example/api/v1/test", format="json", append_slash=False) def test_get_serializer(self): self.assertTrue(isinstance(sel...
import pytest import pandas as pd from src.utils.preprocessing import parse_filters @pytest.fixture def df(): df = pd.DataFrame({ 'A': list('abcd'), 'B': range(4) }) return df def test_get_filter1(df): filters = { 'A': {'equals': list('abc')}, 'B': {'greater-or-equa...
#!/usr/bin/env python3 # # Required keycloak roles: realm:panadmin, client:realm-management:query-users, client:realm-management:view-users # import logging import os import redis import requests if os.environ.get('VERBOSE', False): logging.basicConfig(level=logging.DEBUG) webrecorder_home = os.environ.get('WEBRE...
from setuptools import setup, find_packages setup( name='bloomfilter', version = '0.0.1', description='low level functional bloomfilter', url='https://github.com/tommyvn/bloomfilter', author='Tom van Neerijnen', author_email='tom@tomvn.com', packages=find_packages(exclude=['contrib', 'docs'...
from twython import TwythonStreamer from datetime import datetime ''' a much simpler interface for searching the twitter stream based on a query (labeled as track = ) note here that a comma represents OR if I were to use a space to seperate hashtags it would be considerd and AND ''' class TweetStreamer(TwythonStreamer...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from datetime import datetime import os USER_ID = 1 app = Flask(__name__, instance_relative_config=True) app.config.from_object('config') # load default app.config.from_pyfile('config.py') #load instance/config.py db = SQLAlchemy(app) from dispensibilit...
from __future__ import division import os, time, cv2 import scipy.io as sio import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np from numpy import * import scipy.linalg from copy import copy, deepcopy def lrelu(x): return tf.maximum(x * 0.2, x) def identity_initializer(): def _i...
#!/usr/bin/python3 from vote import vote class Elections: def __init__(self): self.elections = {} def add_election(self, name): self.elections[name] = vote.Vote(name) def close_election(self, name): self.elections[name].close_voting() def vote(self, name, points, voter_id): ...
import typing from datetime import datetime, timedelta from .abc import BaseObject, BaseUser if typing.TYPE_CHECKING: from .state import ConnectionState __all__ = ( "ClashOfCode", "Player", ) class ClashOfCode(BaseObject): """Represents a Clash of Code. Attributes ----------- publi...
from .nuget_package import NugetPackages class Artifactory(object): def __init__(self): self.nuget_package_obj = NugetPackages() def create_all_packages(self): self.nuget_package_obj.create_all()
#exec(open('.\\templates\\plot_boxplot.py').read()) import subprocess as sp import matplotlib.pyplot as plt import pandas as pd import os import numpy as np if __name__ == '__main__': sp.call('cls', shell = True) # close all figures plt.close('all') with open('.\\data\\iris\\iris.data', 'rt') as fl: ...
# pylint: disable = C0330 ''' Utilities to download a corpus ''' import os import sys import subprocess def download_corpus(corpus_path, repo_user='QuantitativeCriticismLab'): ''' Download a corpus from Github with a sparse checkout and shallow clone. https://stackoverflow.com/a/28039894/7102572 If the directory...
facing = "E" directions = ["E", "S" ,"W", "N"] lines = [] with open("test.txt") as f: for line in f: line = line.strip() lines.append((line[0], int(line[1:]))) x = y = 0 for direction, move in lines: if direction == "F": direction = facing if direction == "N": y += move ...
# Copyright (C) 2019-2020 Intel Corporation # # SPDX-License-Identifier: MIT from . import project, source, model, item
def makeMask(n): "return a mask of n bits as a long integer" return (2 << n - 1) - 1 def dottedQuadToNum(ip): "convert decimal dotted quad string to long integer" parts = ip.split(".") return int(parts[0]) | (int(parts[1]) << 8) | (int(parts[2]) << 16) | (int(parts[3]) << 24) def networkMask(ip,...
from pandas import DataFrame import pandas as pd def enlarge(n): return n * 100 def check_nulls(df): ''' Check a dataframe for nulls, print/report them in a nice "pretty" format ''' total = df.isna().sum() total = total.sum() string = f"There are {total} null values in your dataframe" ...
# -*- coding: utf-8 -*- #/* # * Copyright (c) 2022 Renwei # * # * This is a free software; you can redistribute it and/or modify # * it under the terms of the MIT license. See LICENSE for details. # */ import re import traceback from .find_file_list import find_file_list from autocode_tools import * def _find_struct_...
# pylint: disable=too-few-public-methods from mongoengine import ( signals, EmbeddedDocumentListField, IntField, StringField ) from app_name.extensions import db from app_name.models.base import BaseModel class BookAuthor(db.EmbeddedDocument): """ Book Author model: Embedded Document """ ...
from rest_framework import serializers from .models import ( Question, Choice, Quiz, Response, ) class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = ("choice_id", "choice") class QuestionSerializer(serializers.ModelSerializer): choices ...
__author__ = 'jbbrokaw'
from django.contrib.auth.decorators import login_required from .models import Post,Profile,Rating from django.shortcuts import render,redirect from .forms import SignupForm,uploadForm,rateProject from django.contrib.auth import login, authenticate from django.http import HttpResponseRedirect from django.contrib.auth im...
# Copyright 2019 Google Inc. All Rights Reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ trace/generated-tracers.dtrace (DTrace only). """ __author__ = "Lluís Vilanova <vilanova@ac.upc.edu>" __copyright__ = "Copyright 2012-2014, Lluís Vilanova <vilanova@ac.upc.edu>" __license__ = "GPL version 2 or (at your option) any later version" __maintainer_...
from django.core.management.base import BaseCommand, CommandError from browsing.models import BrowsConf class Command(BaseCommand): help = "Delete all BrowsConf objects" def handle(self, *args, **options): brc_objs = BrowsConf.objects.all() self.stdout.write("{} objects will be deleted".for...
import time import os import redis #os.system("rm /var/run/ProcLevel.pid") f= open("/var/run/ProcLevel.pid","w+") f.write("0") f.close() r = redis.StrictRedis(host='localhost', port=6370, db=0, charset="utf-8", decode_responses=True) r.mset({"blink-green":"0|0|0|0|0"}) r.mset({"blink-blue":"0|0|0|0|0"}) class LedBlink:...
from django.urls import path from django.contrib.auth.decorators import login_required from django.contrib.auth.views import LogoutView from . import views app_name = 'accounts' urlpatterns = [ path("register/", views.UserCreateView.as_view(), name="register"), path("setup/", login_r...
#!/usr/bin/env python3 import os from render import get_tagged_content, write_output if __name__ == "__main__": for input_filename in os.listdir(path="content"): with open(input_filename.replace(".content", ""), mode="w", encoding="utf8") as output_file: def file_writer(line): ...
import json import logging import math import os import random import sys import pygame as pg from peepo.playground.wandering.vision import end_line from peepo.playground.wandering.wandering_obstacle_avoidance_model import WanderingPeepo vec = pg.math.Vector2 CAPTION = "Peepo 's World" SCREEN_SIZE = (1600, 1000) SC...
""" 105 medium construct binary tree from preorder and inorder traversal """ from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def buildTree...
import discord client = discord.Client from discord.ext import commands bot = commands.Bot(command_prefix='_') import io import aiohttp import os TOKEN = os.environ['DISCORD_TOKEN'] image = 'px-Rainbow_trout_transparent.png' self = 812453966025719808 @bot.event async def on_ready(): print(f'Bot connected as {bot.user...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\Dropbox\Dropbox\pw_prefs\RnD\tools\pw_scriptEditor\widgets\scriptEditor.ui' # # Created: Mon Mar 16 11:15:50 2015 # by: PyQt4 UI code generator 4.11.3 # # WARNING! All changes made in this file will be lost! from Qt import QtCore, Q...
# 2.Given an integer n, return the largest number that contains exactly n digits. # For n = 2, the output should be # largestNumber(n) = 99. def largestNumber(n): x = pow(10, n)-1 return x print(largestNumber(4))
# -*- coding: utf-8 -*- """ Profile: http://hl7.org/fhir/StructureDefinition/AllergyIntolerance Release: DSTU2 Version: 1.0.2 Revision: 7202 """ from typing import List as ListType from pydantic import Field from . import fhirtypes from .backboneelement import BackboneElement from .domainresource import DomainResourc...
from datetime import datetime import sqlite3 from pprint import pprint import re import pytest from bot.db import get_db def data_generator( message, user_id: int = 1, time: datetime.isoformat = '2019-01-01 00:08:00', role: str = 'member', card: str = 'test_card', nic...
pkgname = "man-pages" pkgver = "5.13" pkgrel = 0 make_cmd = "gmake" hostmakedepends = ["gmake"] pkgdesc = "Linux Documentation Project manual pages" maintainer = "q66 <q66@chimera-linux.org>" license = "GPL-2.0-or-later" url = "https://man7.org/linux/man-pages/index.html" source = f"$(KERNEL_SITE)/docs/man-pages/{pkgna...
"""Widgets that visualise volume images in .nii files.""" import nibabel as nib import matplotlib.pyplot as plt import numpy as np from ipywidgets import interact, fixed, IntSlider import inspect import scipy.ndimage # import pathlib & backwards compatibility try: # on >3 this ships by default from pathlib imp...
from __future__ import print_function #kompatibilita s Python 2.7 import sys # Implementacni test IB002 2016 - LTree (max 50 bodu) # # Vasi ulohou je implementovat ctyri funkce pro datovou strukturou "LTree". # Muzete si samozrejme pridat vlastni pomocne funkce. # # LTree je datova struktura, ktera slouzi k uklad...
from abc import ABC, abstractclassmethod from model.response import ResponseModel class CacheInterface(ABC): @abstractclassmethod async def get(cls, url: str) -> ResponseModel: pass @abstractclassmethod async def set(cls, url: str, value: ResponseModel, ttl=0): pass
from netmiko import ConnectHandler class Asa: def __init__(self, mgmt, pub, pubNet, pri, priNet): self.mgmt = mgmt self.pub = pub self.pubNet = pubNet self.pri = pri self.priNet = priNet asa_dict = {} #Gather user input and create ASA objects for configuration....
# org.onap.dcae # ================================================================================ # Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # ...
from tkinter import * rootWidget = Tk() rootWidget.title("Frame") frameWidget = LabelFrame(rootWidget, text="Frame 1 ", padx=50, pady=50) frameWidget.grid(row = 0, column = 0) frameWidget1 = LabelFrame(rootWidget, text="Frame 2 ", padx=50, pady=50) frameWidget1.grid(row = 1, column = 0) buttonWidget = Bu...
import multiprocessing from argparse import ArgumentParser from re import match import msvcrt from parsing import Parser def main(): arg_parser = ArgumentParser( prog="osu! beatmaps downloader", description="App to download beatmaps from osu! site") arg_parser.add_argument( ...
from __future__ import absolute_import from unittest import TestCase from mock import MagicMock, patch, call from datadelivery.argparser import ArgParser class ArgParserTestCase(TestCase): def test_parser_description_contains_version(self): version_str = '1.0' target_object = MagicMock() a...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for alternative extrapolation""" import solvency2_data import numpy as np import pandas as pd import unittest from collections import OrderedDict from datetime import datetime class TestAltExtra(unittest.TestCase): def test_1(self): assert solvency2_data.Dis...
from random import random, randint import numpy as np import cost_function as cf def random_tree(k): k=randint(1,k) cut_num = k leaf_num = k+1 cuts = [('H' if random()<0.5 else 'V', randint(1,999)/1000) for _ in range(cut_num)] leaves = [" (L color)" for _ in range(leaf_num)] ...
import numpy as np import scipy.sparse from .modeling.associations import HasParameterContext, NamedParameters, ParameterAliasMixin from .utils.partitioning import partitioned_polynomial_model from .utils import piecewise_polynomial as ppol from .thimblesdb import Base, ThimblesTable from .modeling import Model, Para...
#****************************************************************************** # Image pre-processing functions. * # @author Jorge Ciprián. * # Last updated: 11-01-2020. * ...
"""This module manages ssh key files for bcfg2""" import binascii import re import os import socket import shutil import sys import tempfile from subprocess import Popen, PIPE import Bcfg2.Server.Plugin from Bcfg2.Bcfg2Py3k import u_str if sys.hexversion >= 0x03000000: from functools import reduce import logging...
# -*- coding: UTF-8 -*- import config import time import requests import traceback import nonebot import json import logging import sys import os import re from nonebot import CommandSession """ 帮助函数 """ file_base_path = "cache" config_file_base_path = 'config' log_file_base_path = 'log' #每天一个日志文件 bindCQID = config.def...
# -*- coding: utf-8 -*- """Typing declrations.""" import os import re import sys from typing_extensions import Literal, TypedDict #: Flag if running from ``sphinx-build``. SPHINX_BUILD = bool( re.fullmatch(r'(?ai)sphinx-build(?:\.exe)?', os.path.basename(sys.argv[0])) ) # type: Literal[False] #...
import json from typing import Dict from skaio.core.base.message import TaskSerializer, Message class JSONSerializer(TaskSerializer): def serialize(self, message: Message) -> Dict: return json.dumps(message) def deserialize(self, data: Dict) -> Message: return json.loads(data)
""" This module written by David Keeney, 2009, 2010 Released under the LGPL for use with the SQLObject ORM library. """ import re from sqlobject import col from sqlobject import sqlbuilder from sqlobject.converters import registerConverter from sqlobject.dbconnection import DBAPI from sqlobject.postgres.pgconnection ...
import haiku as hk from haiku.initializers import Constant, RandomNormal import jax from jax import numpy as jnp class DCGenerator(hk.Module): def __init__(self, channels, ker_shapes, strides, padding, name=None): super().__init__(name=name) self.name = name self.channels = channels ...
import os import unittest import tempfile import json import numpy as np import pandas as pd import shutil from supervised import AutoML from numpy.testing import assert_almost_equal from sklearn import datasets from supervised.exceptions import AutoMLException class AutoMLTimeConstraintsTest(unittest.TestCase): ...
# Prints the kotekan version using versioneer # The script is called from make_version.cmake.in from _version import get_versions print get_versions()["version"]
import matplotlib.pyplot as plt import pandas as pd import numpy as np data = pd.read_csv('file/Salary_Data.csv') list1=list(data['YearsExperience']) list2 = list(data['Salary']) n = len(list1) sx = 0 sx2 = 0 sx3 = 0 sx4 = 0 sy = 0 sxy = 0 sx2y = 0 for i in range(n): sx = sx + list1[i] sx2 = sx2 + (list1[i]...
choise = input('digite alguma coisa: ') print('eu não entendi poderia escolher uma das opções: ') escolha = input()
def leiaInt(num): while True: try: numero = int(input(num)) except (TypeError, ValueError): print('\033[0;31mERRO! digite um número inteiro válido!\033[m') continue except (KeyboardInterrupt): print('o usuario preferiu não informar os dados') ...
import json import boto3 sqs = boto3.client('sqs') queue_url = 'https://sqs.us-east-1.amazonaws.com/494413724691/SQS_FP' def lambda_handler(event, context): # TODO implement print(event) sendToSQS(event) return { "status":"Sucessfully Send Request!" } def getname(event...
#!/usr/bin/env python3 import click def click_option(*args, **kwargs): if not 'show_default' in kwargs: kwargs.update({'show_default': True}) return click.option(*args, **kwargs)
import dis def sum(): vara = 10 varb = 10 sum = vara + varb print "vara + varb = %d" % sum print sum()
n = int(input()) a = [int(tmp) for tmp in input().split()] maxi = max(0, a[0]) s = a[0] for item in a[1:]: s += item maxi = max(maxi, s) print(maxi)
import unittest from os.path import dirname, join from seaqube.nlp.context2vec.context2vec import Context2Vec from seaqube.tools.math import cosine corpus = [['till', 'this', 'moment', 'i', 'never', 'knew', 'myself', '.'], ['seldom', ',', 'very', 'seldom', ',', 'does', 'complete', 'truth', 'belong', 't...
from google.cloud import bigquery client = bigquery.Client() dataset_id = "{}.embasy_pipeline".format(client.project) dataset = bigquery.Dataset(dataset_id) dataset.location = "US" # Send the dataset to the API for creation. # Raises google.api_core.exceptions.Conflict if the Dataset already # exists within the p...
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) setup( name='coinzdense', version='0.0.4', description='Simple Post-Quantum Signature library', long_description="""Library for hash-based signatures. The CoinZdense...
from collections import defaultdict import re import os import queue _INCLUDE_FILE_REG = re.compile(r'^\s*#include\s*(?:"|<)\s*(.*?)\s*(?:"|>)\s*') _C_EXTENSIONS = ['.cpp', '.c', '.cu'] def _is_c_file(fname): return os.path.splitext(fname)[-1] in _C_EXTENSIONS def get_include_file(fname): '''return a list...
# This file is a part of Arjuna # Copyright 2015-2020 Rahul Verma # Website: www.RahulVerma.net # 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...
from trame import start from trame.layouts import SinglePage # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout = SinglePage("Hello Trame") layout.title.content = "Hello Trame" # ----------------...
#!/usr/bin/python3.4 # -*- coding: utf-8 -*- import telebot import cherrypy import config WEBHOOK_HOST = 'preftimebot.xyz' WEBHOOK_PORT = 443 # 443, 80, 88 или 8443 (порт должен быть открыт!) WEBHOOK_LISTEN = '0.0.0.0' # На некоторых серверах придется указывать такой же IP, что и выше WEBHOOK_SSL_CERT = './webhoo...
""" WSGI config for library project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from django.conf import settings o...
# Libs import os # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # # The GPU id to use, "0" to "7" # os.environ["CUDA_VISIBLE_DEVICES"] = "0" import sys sys.path.append(os.path.join(os.getcwd(), "pytorch-lib/")) import time import torch from torch import nn import torchvision import numpy as np from collections i...
#!/usr/bin/env python2 import os import sys import glob import struct import optparse import math import utils import shutil import build import config_engine as conf def generate_index(opts): def run(args): utils.run(opts.print_only, "time", *args) # make sure proper config is loaded run(["sudo...
"""Test cases for the stick button environment.""" import matplotlib import matplotlib.pyplot as plt import numpy as np import pytest from predicators.src import utils from predicators.src.envs.stick_button import StickButtonEnv from predicators.src.structs import Action, GroundAtom, Task def test_stick_button(): ...
"""Summary table of ovary and testis counts. Table has the following columns: - FBgn - sample_ID - Count - stage = 'L3' - tissue - rep - chrom - data_source = 'RNA-Seq' """ import os import pandas as pd def main(): fbgn2chrom = get_fbgn2chrom() counts = get_counts() df = counts.join(fbgn2chrom, how="inn...
from django.db import models from django.utils.text import slugify from .prodotto import Prodotto from .variante import Variante, VarianteValore class ProdottoVariante(Prodotto): prodotto = models.ForeignKey( Prodotto, on_delete=models.CASCADE, related_name="varianti" ) variante = models.Foreign...
#!/usr/bin/env python3 import sympy as sp import numpy as np import matplotlib.pyplot as plt w = 5 w1 = 0.9 * w w2 = 1.1 * w x = sp.Symbol('x') func1 = 1/2 * (2 + sp.cos(2*w1*x) + sp.cos(2*w2*x) + 2*sp.cos((w1+w2)*x) + 2*sp.cos((w1-w2)*x)) func2 = 1/2 * (sp.cos(2*w1*x)) func3 = 1/2 * (sp.cos(2*w2*x)) func4 = 1/2 * ...
# from django.db import models # class Author(models.Model): # name = models.CharField(max_length=100) # class Meta: # ordering = ['name'] # def __unicode__(self): # return self.name
#coding:utf-8 ############################################## # SpCoSLAM online learning program (無駄なコメントアウトコードを省いたバージョン+bugfix) # かつ、SpCoAのオンライン版(SpCoSLAMから言語モデル更新と画像特徴を除けるバージョン) # Akira Taniguchi 2017/01/18-2017/02/02-2017/02/15-2017/02/21 ############################################## ##########---処理の流れ(gma...
import os, sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'radiate_sdk/')) import json import numpy as np import radiate root_path = './data/' sequence_names = os.listdir(root_path) for sequence_name in sequence_names: seq = radiate.Sequence(f"{root_path}/{sequence_name}", '...
""" Main distributed analysis module to use pyEPR. Contains code to conenct to Ansys and to analyze HFSS files using the EPR method. This module handles the micowave part of the analysis and conenction to Further contains code to be able to do autogenerated reports, Copyright Zlatko Minev, Zaki Leghtas, and the pyE...
from django.contrib import admin from galaxy_api.api import models as api_models @admin.register(api_models.Namespace) class NamespaceAdmin(admin.ModelAdmin): fields = ('name', 'company', 'email', 'avatar_url', 'description', 'groups') autocomplete_fields = ['groups'] @admin.register(api_models.NamespaceLin...
from typing import Callable, Optional import torch from torecsys.inputs.base import BaseInput class ValueInput(BaseInput): """ Base Input class for value to be passed directly. """ def __init__(self, num_fields: int, transforms: Optional[Callable] = None): """ Initialize ValueInput ...
from PIL import Image, ImageFilter, ImageEnhance import sys color = 10 contrast = 1.2 brightness = 10 sharpness = 10 blur = True contour = True smooth = True detail = True edge_enhance = True try: img = Image.open("Image.png") except IOError: print("Unable to load image") sys.exit(1) img.show() img = I...
import time import board import neopixel from rainbowio import colorwheel from digitalio import DigitalInOut, Direction pixpin = board.D1 numpix = 8 led = DigitalInOut(board.D13) led.direction = Direction.OUTPUT strip = neopixel.NeoPixel(pixpin, numpix, brightness=1, auto_write=True) def rainbow_cycle(wait): ...
""" *********************************************************** Reader Class Create Date: 09/01/2018 By: L.VOIRIN *********************************************************** 0.0.1 Adaptation module Reader LV 09/01/2018 0.0.2 Package creation LV 06/03/2022 0...
import re import threading import requests def validate_currency(currency_str): return len(currency_str) == 3 def validate_amount(amount_str): try: return float(amount_str) except ValueError: return False def validate_phone(phone_str): try: return re.match('^\+\d{1,3}\d{3,}$'...
from django.shortcuts import render, redirect from django.contrib import messages from .form import FormMhs from .models import Mahasiswa def home(request): context = { 'judul' : 'Halaman Utama', 'contributor': 'Yekk Seggaf', } return render(request, 'main/home.html', context) def aboutm...
import logging import unittest from sqlalchemy import text import time from c2cwsgiutils.sqlalchemylogger.handlers import SQLAlchemyHandler import glob import os class SqlAlchemyLoggerTests(unittest.TestCase): dummy_db_name = "dummy.db" def setUp(self): pass def tearDown(self): if glob.g...
# Copyright The PyTorch Lightning team. # # 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 i...
#!/usr/bin/python import logging logging.basicConfig(level = logging.DEBUG) from gi.repository import Vips Vips.cache_set_trace(True) try: a = Vips.Image.new_from_file("/home/john/pics/babe.poop") except Vips.Error, e: print e a = Vips.Image.new_from_file("/home/john/pics/babe.jpg") b = Vips.Image.new_from_...
import itertools import json import re import math import numpy import matplotlib.pyplot as plt from palettable.cartocolors.qualitative import Bold_3 plt.rcParams["svg.fonttype"] = "none" # plt.xkcd(scale=0.5) with open("benchmark.hmmsearch.json") as f: data = json.load(f) CPU_RX = re.compile(r"(?:--cpu|--jobs)...
from dotenv import load_dotenv import uvicorn from app import app original_callback = uvicorn.main.callback def callback(**kwargs): from celery.contrib.testing.worker import start_worker import tasks with start_worker(tasks.task, perform_ping_check=False, loglevel="info"): original_callback(**k...
import datetime import unittest import bson from nose.tools import assert_raises from hamcrest import assert_that, is_, contains_string from jsonschema import ValidationError from backdrop.core.validation import value_is_valid_id,\ value_is_valid, key_is_valid, value_is_valid_datetime_string,\ key_is_reserve...
from kutana.controller_vk.converter import convert_to_attachment import aiohttp import json async def upload_file_to_vk(ctrl, upload_url, data): upload_result_resp = await ctrl.session.post( upload_url, data=data ) if not upload_result_resp: return None upload_result_text = await upl...
# -*- coding:utf-8 -*- # @Time : 2019/8/25 18:31 # @Author : Thanlon # @Email : thanlon@sina.com # @File : md5.py # @Project : code_count import hashlib from settings import Config def md5(password): hash = hashlib.md5(Config.SALT) # hash.update(b'thanlon') hash.update(bytes(password, encoding='utf-8')) ...
"""Top-level package for ascii-art.""" __author__ = """Zero to Mastery""" __version__ = '0.1.0'