content
stringlengths
5
1.05M
from django.shortcuts import render from django.views.generic import View from .models import Story, Gallery, Comment from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect, HttpResponse from django.db.models import Q from utils.email_send import send_register_email from django...
import hashlib try: from urllib.parse import urlencode except ImportError: from urllib import urlencode from django.apps import apps from django.contrib.contenttypes.models import ContentType from django.contrib.sites.shortcuts import get_current_site from django.utils import formats from django.utils.html im...
""" Plotting convenience functions. """ from math import ceil import ipywidgets as widgets import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from model_base import get_ext_input # define basics prop_cycle = plt.rcParams["axes.prop_cycle"] colors = prop_cycle.by_key()["color"]...
# -*- coding: utf-8 -*- """ Created on Sat Oct 23 08:58:37 2021 @author: michp-ai """ # This script is web automation for the Capstone project on ML rapid text labeling # Before running this script in a different console start the web server by running main.py for the web app # This is a simple demo script to illustr...
#!/Users/robertpoenaru/.pyenv/shims/python import numpy as np import matplotlib.pyplot as plt from numpy import random as rd CHARGE_E = 1 # return the radius of a nuclei with respect to the total number of nucleus (assuming a constant density) class Charge_Distribution: def __init__(self, A, Z, diffuseness, ...
import producer_ipc import consumer_ipc
#!/usr/bin/env python3 import sys if sys.version_info[0] != 3 or sys.version_info[1] < 5: print("Holo requires Python version 3.5 or greater") sys.exit(1) # Metadata name = "Holo" description = "episode discussion bot" version = "0.1.1" # Ensure proper files can be access if running with cron import os from pathlib...
import mtfl from mtfl.hypothesis import MetricTemporalLogicStrategy from hypothesis import given @given(MetricTemporalLogicStrategy) def test_identities(phi): assert mtfl.TOP == mtfl.TOP | phi assert mtfl.BOT == mtfl.BOT & phi assert mtfl.TOP == phi | mtfl.TOP assert mtfl.BOT == phi & mtfl.BOT as...
import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from fastapi_for_firebase.cache_control import middleware @pytest.mark.parametrize( "max_age,s_maxage,header_value", [(30, 60, "public, max-age=30, s-maxage=60"), (30, None, "public, max-age=30")], ) def test_cache_control__g...
import django.forms.widgets as widgets class AbilityListBoxSelect(widgets.SelectMultiple): template_name = 'dnd5e/widgets/ability_list_box.html' option_template_name = 'dnd5e/widgets/ability_list_box_option.html' class Media: css = {'all': ('css/ability_listbox.css',)} js = ('js/ability_l...
""" Common utilities between parsing and retrieval lambdas. TODO: Considering structuring this as a class (if that's workable with AWS Lambda layers). Many methods accept similar parameters, in order to accomplish API calls, and it's information that could be easily encoded as state in an object. """ import os import...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
import csv import argparse import sys def get_args(argv): """ Parse arguments from command line """ args = argparse.ArgumentParser() args.add_argument('-u', required = True, metavar = '<bed>', help = 'Patcher output') args.add_argument('-r1', require...
from costf import calculate_cost def schedule_permutation(num_phar): for i in range(1, num_phar - 4 + 1): for j in range(1, num_phar - i - 3 + 1): for k in range(1, num_phar - i - j - 2 + 1): for l in range(1, num_phar - i - j - k - 1 + 1): m = num_phar - i ...
import torch def compute_pairwise_cosine_distances(minibatch_embeddings, full_matrix=False): # cosine_distance = 1 - cosine_similarity # cosine similarity (A,B)= cos(theta) = (A . B ) / (||A||*||B||) , # constrainining embeddings into a hypersphere (unit-sphere) so all norms are 1 reduces this to a matr...
genetic_code = { 'ttt': 'F', 'tct': 'S', 'tat': 'Y', 'tgt': 'C', 'ttc': 'F', 'tcc': 'S', 'tac': 'Y', 'tgc': 'C', 'tta': 'L', 'tca': 'S', 'taa': '*', 'tga': '*', 'ttg': 'L', 'tcg': 'S', 'tag': '*', 'tgg': 'W', 'ctt': 'L', 'cct': 'P', 'cat': 'H', 'cgt': 'R', 'ctc': ...
from typing import Any, Callable, List, Dict, Union, Optional, Sequence, Tuple from numpy import ndarray from collections import OrderedDict from scipy import sparse import os import sklearn import numpy import typing # Custom import commands if any from sklearn.preprocessing import StandardScaler from d3m.container....
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT import time import board import busio import neopixel from adafruit_seesaw.seesaw import Seesaw from digitalio import DigitalInOut import adafruit_requests as requests import adafruit_esp32spi.adafruit_esp32spi_socket as socke...
""" This file is part of python-tdbus. Python-tdbus is free software available under the terms of the MIT license. See the file "LICENSE" that was provided together with this source file for the licensing terms. Copyright (c) 2012 the python-tdbus authors. See the file "AUTHORS" for a complete list. """ import unittes...
''' Выполнить задание уровня pro Написать программу “Угадай число”. Программа должна с помощью наводящих вопросов отгадать число. ''' # https://github.com/vv31415926/python_lesson_02_Pro # Угадай число import random num = random.randint( 1,1000000 ) print('Игрок это не замечает: задумано '+str(num) ) print( 'Отгада...
import threading import os from boottest import local_dict from datetime import datetime, timedelta from functools import wraps import traceback import json import hashlib from django.conf import settings __all__ = [ 'STATE_DEBUG', 'STATE_INFO', 'STATE_WARNING', 'STATE_ERROR', 'operation_writer', 'except...
import network import ujson import exception def connect_to_access_point(wifi_config_filename='wifi_config.json'): try: with open(wifi_config_filename) as f: json = f.read() except OSError: raise exception.FileNotFoundError(wifi_config_filename) config = ujson.loads(json) ...
# Generated by Django 3.2.7 on 2021-10-19 04:33 from django.db import migrations, models import uuid class Migration(migrations.Migration): dependencies = [ ('authors', '0017_alter_author_user'), ] operations = [ migrations.AlterField( model_name='author', name='...
from setuptools import find_packages from setuptools import setup setup( name="estimagic", version="0.1.2", description="Tools for the estimation of (structural) econometric models.", long_description=""" Estimagic is a Python package that helps to build high-quality and user friendly i...
import re import string with open("data/input_4.txt", "r") as f: data = list() one_pass = list() for line in f.readlines(): if line == "\n": data.append({i.split(":")[0]: i.split(":")[1] for i in one_pass}) one_pass = [] continue op = line.replace("\n", "...
import ntpath import os import pickle from functools import partial from pathlib import Path from time import sleep import peewee from kivy.app import App from kivy.clock import Clock from kivy.event import EventDispatcher from kivy.logger import Logger from kivy.metrics import dp from kivy.properties import ( Bool...
import copy import numpy as np from utils.utils import getdtype from Ottergrad.autograd import Tensor, Func, checkTensor from Ottergrad.utils import * def ndot(a, b): res = np.dot(a, b) return res class _dot(Func): def __init__(self): super().__init__() def __call__(self, x, y): t...
import sys import requests_html from requests.sessions import session from t.log import error def check_platform() -> dict: return { "darwin": {"audio": "afplay {}"}, "linux": {"audio": ""}, "win32": {"audio": ""}, }[sys.platform] def check_langs() -> list: session, langs = req...
class RegressionPredictor(): def __init__(self, model): self.model = model def predict(self, X, decimals=2): """ Performs one Prediction. Parameters: - X: Input array compatible with model interface for inference. - decimals (int): Number of decimals required ...
# Copyright 2020 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, ...
#/************************************************************************************************************************ # Copyright (c) 2016, Imagination Technologies Limited and/or its affiliated group companies. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modificat...
from __future__ import division import cv2 import numpy as np import scipy.io import scipy.ndimage def padding(img, shape_r=240, shape_c=320, channels=3): img_padded = np.zeros((shape_r, shape_c, channels), dtype=np.uint8) if channels == 1: img_padded = np.zeros((shape_r, shape_c), dtype=np....
# Generated by Django 3.0.2 on 2020-01-08 18:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projectm', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='completed', ...
''' Inference engine for sparse image pair correspondences ''' import time import random import numpy as np import torch from COTR.inference.inference_helper import THRESHOLD_SPARSE, THRESHOLD_AREA, cotr_flow, cotr_corr_base from COTR.inference.refinement_task import RefinementTask from COTR.utils import debug_utils...
#!/usr/bin/python3 # run this on bsd to create keys in dconf import os from gi.repository import Gio schema_source = Gio.SettingsSchemaSource.new_from_directory( # get default schema os.path.expanduser("../data"), Gio.SettingsSchemaSource.get_default(), False, ) schema = schema_source.lookup('com.githu...
"""Tests for module state accessors in the protocol engine state store.""" import pytest from pytest_lazyfixture import lazy_fixture # type: ignore[import] from decoy import Decoy from contextlib import nullcontext from typing import ContextManager, Dict, NamedTuple, Optional, Type, TypeVar, Union from opentrons.har...
import asyncio import pytest import zmq from zmq.utils import z85 from zope.interface.verify import verifyClass def test_noop_auth_backend_client(): from pseud.auth import NoOpAuthenticationBackendForClient from pseud.interfaces import IAuthenticationBackend assert verifyClass(IAuthenticationBackend, No...
# -*- coding: utf-8 -*- """ Provide functions and classes: Model = Class for loading and using trained models from tensorflow create_cell = function for creatting RNN cells with wrappers """ import tensorflow as tf from tensorflow.python.ops.rnn_cell_impl import LSTMCell, ResidualWrapper, DropoutWrapper, MultiRNN...
import os from typing import Dict, List from . import config from .err import PinterestException from .util import pinterest_request class Pin: def __init__(self, token: str, pin_id: str = None): self.token = token self.pin_id = pin_id def create(self, board: str, note: str, link: str = Non...
""" HTML renderer for mistletoe. """ import re import sys from itertools import chain from urllib.parse import quote from mistletoe.block_token import HTMLBlock from mistletoe.span_token import HTMLSpan from mistletoe.base_renderer import BaseRenderer import html class HTMLRenderer(BaseRenderer): ...
import scipy.misc import numpy as np def fractal_dimension(Z): # Only for 2d image assert(len(Z.shape) == 2) def boxcount(Z, k): S = np.add.reduceat( np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), np.arange(0, Z.shape[1], k), axis=1) ...
import matplotlib.pyplot as plt def plot_drift_score_per_dimension(df_drift_scores, plot_file_name=False, latex_font=False): """ Parameters ---------- df_drift_scores: Data frame with drift scores plot_file_name: Name of plot file latex_font: Whether latex font should be used Returns ...
# -*- coding: utf-8 -*- # Problem Set 5: Experimental Analysis # Name: Brighton Ancelin # Collaborators (discussion): # Time: # SEARCH FOR "MY_CODE" COMMENT TO FIND MY CONTRIBUTIONS import pylab import numpy as np import re # cities in our weather data CITIES = [ 'BOSTON', 'SEATTLE', 'SAN DIEGO', 'PHI...
from robot.exceptions import RobotError class InvalidJointAngleError(RobotError): def __init__(self, msg): super().__init__(msg) class InvalidJointDictError(RobotError): def __init__(self, msg): super().__init__(msg) class InvalidSerialDictError(RobotError): def __init__(self, msg): super().__init_...
# Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import dj_database_url from project_runpy import env BASE_DIR = os.path.dirname(__file__) SECRET_KEY = env.get("SECRET_KEY", "Rotom") DEBUG = env.get("DEBUG", False) ALLOWED_HOSTS = ["*"] INSTALLED_APPS = ( "bandc.apps.agenda.ap...
import io import pytest from cptv.bitstream import BitStream def test_single_bytes(): b = BitStream(io.BytesIO(b'\xff\xee\xdd')) assert b.bytes(1) == b'\xff' assert b.bytes(1) == b'\xee' assert b.bytes(1) == b'\xdd' def test_multi_bytes(): b = BitStream(io.BytesIO(b'\xff\xee\xdd')) assert b....
coordinates_01EE00 = ((123, 121), (123, 123), (124, 119), (124, 124), (124, 125), (124, 126), (124, 127), (124, 129), (125, 115), (125, 117), (125, 118), (125, 121), (125, 122), (125, 123), (125, 130), (125, 135), (126, 115), (126, 119), (126, 120), (126, 121), (126, 122), (126, 123), (126, 124), (126, 125), (126, 12...
class PrintSetup(APIObject, IDisposable): """ Represents the Print Setup (Application Menu->Print->Print Setup) within Autodesk Revit. """ def Delete(self): """ Delete(self: PrintSetup) -> bool Delete the current print setting,and make the In-Session setting as the current on...
import pygame.sprite class Soldier(pygame.sprite.Sprite): def __init__(self, surface, char_type: str, x: int, y: int, scale: int, speed: int): pygame.sprite.Sprite.__init__(self) self.surface = surface self.char_type = char_type self.speed = speed self.direction = 1 # Fac...
import os from barbarika.helpers import logger from barbarika.aws import send_response, get_subnet_address, get_subnet_gateway from barbarika.citrixadc import CitrixADC current_aws_region = os.environ['AWS_DEFAULT_REGION'] def lambda_handler(event, context): fail_reason = None logger.info("event: {}".format...
import torch from torch.utils.data import Dataset from torchvision import transforms, datasets from torch.utils.data import ( DataLoader, RandomSampler, DistributedSampler, SequentialSampler, ) import scipy.io as sio from PIL import Image import numpy as np import heapq class load_prc...
# Autoencoder from .SSIM_loss import SSIM_loss from .Mutil_SSIM_loss import Multi_SSIM_loss from .VAE_loss import VAE_loss # GAN from .SRGAN_loss import GeneratorLoss as SRGAN_Gloss from .SRGAN_loss import DiscriminatorLoss as SRGAN_Dloss
#!/usr/bin/python # # Copyright 2015 Microsoft 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...
"""Lefthook installer """ from ._core import run __version__ = '0.1.2' __all__ = ['run']
import logging import time class Heartbeat: @classmethod def init(cls, job_metadata): cls.iterations_count = 0 cls.previous_beat_at = time.time() cls.min_seconds_between_beats = 10 cls.job_metadata = job_metadata @classmethod def increase_iterations(cls, n_iter): ...
import datetime from django.test import TestCase from pytz import UTC from beers.models import ( Beer, Manufacturer, BeerAlternateName, ManufacturerAlternateName, BeerPrice, ServingSize, ) from taps.test.factories import TapFactory from venues.test.factories import VenueFactory from .factories import BeerFac...
from unittest import TestCase import tempfile import os from jinjawalk import JinjaWalk from typing import Callable, Dict import shutil def path_joiner(base: str) -> Callable[[str], str]: return lambda s: os.path.join(base, s) def dump_string(file_path: str, s: str): with open(file_path, "w") as of: ...
# Author: a101269 # Date : 2020/3/4 import os from glob import glob import torch from argparse import ArgumentParser from config.config import configs from pre_process.vocab import load_vocab from pre_process.conll_processor import ConllProcessor from pre_process.dataloader import Dataloader from utils.utils ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' #============================================================================= # FileName: addtask # Desc: # Author: ge.jin # Email: ge.jin@woqutech.com # HomePage: wwww.woqutech.com # Version: 0.0.1 # LastChange: 5/3/16 9:33 AM # ...
# Third order Newton's method max_steps = 50 ## max number of iterations to use x0 = 2. def f(x): return x**3 - 2. def fp(x): return 3*x**2 def fpp(x): return 6*x def third_order(): global x x = [] x.append(x0) for i in range(max_steps): x.append(x[i] - f(x[i])/fp(x[i]) - (fpp(x...
""" This contains the unit tests for the cross_validate module. """ from __future__ import print_function import unittest from Analytics import cross_validate as cv from Parser import build_training as bt from Train import train_model as tm from copy import deepcopy import numpy as np from sklearn.preprocessing imp...
# Generated by Django 3.1.3 on 2021-03-19 11:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ...
from .platform_factory import get_platform
# -*- coding: utf-8 -*- """Provides the AppConfig class, that is required by Django.""" # Django imports from django.apps import AppConfig from django.conf import settings from django.core.checks import register from django.db.models.signals import post_save from django.utils import six # app imports from auth_enhanc...
# Copyright 2018 Changan Wang # 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, so...
#! /usr/bin/python3 #-*- coding: utf-8 -*- from __future__ import print_function import sys import re import os import shutil from contextlib import closing import requests import urllib.request from urllib.error import HTTPError, URLError import socket import ftplib def url_split(target): return target[0:target....
from dbt.adapters.bigquery.connections import BigQueryConnectionManager # noqa from dbt.adapters.bigquery.connections import BigQueryCredentials from dbt.adapters.bigquery.relation import BigQueryRelation # noqa from dbt.adapters.bigquery.relation import BigQueryColumn # noqa from dbt.adapters.bigquery.impl import B...
import typing IntegerType = typing.NewType("IntegerType", int) TextType = typing.NewType("TextType", str) VarcharType = typing.NewType("VarcharType", str)
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from collections import defaultdict from io import StringIO from os.path import basename, dirname, splitext from typing import DefaultDict, Set from google.protobuf.compiler.plu...
from django.contrib import admin from .models import Contact # Register your models here. @admin.register(Contact) class AdminContact(admin.ModelAdmin): pass
from django.apps import AppConfig class TplansConfig(AppConfig): name = 'tplans'
''' Problem 2: Even Fibonacci numbers Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find th...
from django.shortcuts import render from .models import UserPost, UserProfile # Create your views here. class FollowUserPosts(object): """ PO文列表 """ def __init__(self, user_name=None, page_size=10): self.user_name = user_name self.user_post_list = [] self.total_num = 0 ...
from ssher.core.ports.outgoing import OS import pexpect class CmdRunner(OS): def spawn_child(*args, **kwargs): kwargs.setdefault("encoding", "utf-8") return pexpect.spawn(*args, **kwargs).interact()
import unittest from caravan.tables import Tables from caravan.parameter_set import ParameterSet from caravan.simulator import Simulator class ParameterSetTest(unittest.TestCase): def setUp(self): self.t = Tables.get() self.t.clear() self.sim = Simulator.create("echo") def test_ps(sel...
import os import requests import pymysql import pytest from flask import url_for from solarforecastarbiter.datamodel import QualityFlagFilter as QFF from sfa_dash import create_app BASE_URL = 'http://localhost' resample_threshold = QFF.resample_threshold_percentage @pytest.fixture(scope='session') def auth_toke...
# --------------------------------------------------------------------- # Alarm Rule # --------------------------------------------------------------------- # Copyright (C) 2007-2021 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # Python modules impor...
#!/bin/env python from sys import argv import os REPEAT = 865 RULES = [(18,19,20,21,22,23,24,25),(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18),(26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,1)] + \ [tuple(range(i,i+17)+[i-17]) for i in range(43,825,17)] + \ [(825,826,827,828,829,830,831,832,833,834,835,...
''' Author: Eric P. Nichols Date: Feb 8, 2008. Board class. Board data: 1=white, -1=black, 0=empty first dim is column , 2nd is row: pieces[1][7] is the square in column 2, at the opposite end of the board in row 8. Squares are stored and manipulated as (x,y) tuples. x is the column, y is the row. ''' imp...
from distutils.core import setup from os import path from glob import glob def get_modules(): objdir = path.join(path.dirname(__file__),'bbots/*.py') mods=[] for file in glob(objdir): name = path.splitext(path.basename(file))[0] if name == '__init__': continue mods.appe...
import random from datetime import datetime, timedelta import config from classes.command import command from classes.module import Module class Adventure(Module): """ Always be adventurous! """ def __init__(self, handler): self.handler = handler @command(description="Ge...
from common.celeryapp import get_celery_app from common.measurement import Measure app = get_celery_app() @app.task @Measure.timer(__name__, function_name_as_metric=True) @Measure.counter(__name__, function_name_as_metric=True, count_once=True) def echo(message='This is default queue'): print(message)
name = "S - Big City Scroll" description = "Draws stacked rectangles scaled to audio amplitude, scrolls across screen with history fade" knob1 = "Scroll Direction" knob2 = "Y Position" knob3 = "History Opacity" knob4 = "Color" released = "September 7 2017"
# -*- coding: iso-8859-1 -*- """ MoinMoin - MoinMoin.packages tests @copyright: 2005 MoinMoin:AlexanderSchremmer, 2007 Federico Lorenzi, 2010 MoinMoin:ReimarBauer @license: GNU GPL, see COPYING for details. """ import os import py import tempfile import zipfile from dateti...
import os # first cd to a place that has lots (at least 200 GB) of space! for year in range(2009, 2016): for month in range(1, 13): for color in 'yellow', 'green': if color == 'green': # green taxis only show up starting from 08/2013 if year <= 2012: ...
# coding=utf-8 ############################################################################### # # This file is part of pyglfw project which is subject to zlib license. # See the LICENSE file for details. # # Copyright (c) 2013 Roman Valov <roman.valov@gmail.com> # #########################################...
import numpy from numpy.random import normal import matplotlib.pyplot as plt def matlab_hist(v): plt.hist(v, bins=50, normed=False) plt.show() def numpy_hist(v): (n,bins) = numpy.histogram(v, bins=50, normed=False) plt.plot(.5*(bins[1:]+bins[:-1]), n) plt.show() if __name__ == "__main__": mu,...
"""" Copyright © Krypton 2021 - https://github.com/kkrypt0nn Description: This is a template to create your own discord bot in python. Version: 2.8 """ import json import os import platform import random import sys import asyncio import sqlite3 from pytz import timezone import discord from discord.ext import command...
#!/usr/bin/python3 print("Content-type: text/html\r\n\r\n") from bs4 import BeautifulSoup import requests page = requests.get('http://scores.sify.com/?ref=deskcric') soup = BeautifulSoup(page.content,'html.parser') match_name=soup.find_all('a',{'class':'scroll'})[0].string print("<h1>Current match running is:"+matc...
from django.urls import path, include from rest_framework.routers import DefaultRouter from .viewsets import ComediansViewSet, JokesViewSet router = DefaultRouter() router.register("comedians", ComediansViewSet) router.register("jokes", JokesViewSet) urlpatterns = [ path("", include(router.urls)), ]
from setuptools.dist import Distribution class BinaryDistribution(Distribution): def has_ext_modules(foo): return True def wheel_name(**kwargs): # create a fake distribution from arguments dist = BinaryDistribution(attrs=kwargs) # finalize bdist_wheel command bdist_wheel_cmd = dist.get_c...
Python Program To Check Combo Sum N integers are passed as input to the program. The program must print the count of the combination of the integers (1 or more integers) which add up to a given sum S. Boundary Condition(s): 1 <= N <= 25 -10^5 <= S <= 10^5 Input Format: The first line contains N. The second line contai...
import numpy as np #import matplotlib.pyplot as plt def interpret_many(x_raw, relu, pool, all_wi_ai, best_trigrams = {}, n=5): pool = pool.squeeze() #should be len(x_raw) x num_filters (128) relu = relu.squeeze() if len(x_raw)==1: pool=np.expand_dims(pool, axis=0) relu=np.expand_dims(relu, axis=0) text_lists =...
def compute_pay(hours, rate): if hours <= 40: pay = rate * 40 else: pay = ((hours - 40) * (1.5 * rate)) + (40 * rate) return pay try: hrs = float(input('Enter Hours:\n')) rate = float(input('Enter Rate:\n')) print(compute_pay(hrs, rate)) except: print("Please enter numeric ...
#! python3 # maillist and mail merge for CBD + Theos customer lists # data is from CSV files downloaded from Theos and CBD web # copy the files into the mailist directory on D:\ # Chad Cropley 2016-06-23 a RAD design solution # # import modules import os import csv import shutil # make sure we're in the rig...
""" Validate a configuration value by converting it to a specific type. These functions are used by :mod:`staticconf.readers` and :mod:`staticconf.schema` to coerce config values to a type. """ import datetime import logging import re import time import six from staticconf.errors import ValidationError def validat...
from .dataset import MemoryMapDataset
import requests import sys import random import os import os.path as op from mastodon import Mastodon from datetime import datetime # -------------------------------------------------- DIR_SFW = 'sfw/' DIR_NSFW = 'nsfw/' def main(): mastodon = Mastodon( access_token = 'token.dat', api_base_ur...
# test for+range, mostly to check optimisation of this pair # apply args using * for x in range(*(1, 3)): print(x) for x in range(1, *(6, 2)): print(x) # zero step try: for x in range(1, 2, 0): pass except ValueError: print('ValueError') # apply args using ** try: for x in range(**{'end':...
# -*- encoding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///test.db', convert_unicode=True) db = scoped_session(sessionmaker(autocommit=False, ...