content
stringlengths
5
1.05M
from twilio.twiml.voice_response import VoiceResponse, Dial def generate_wait(): twiml_response = VoiceResponse() wait_message = ( 'Thank you for calling. Please wait in line for a few seconds.' ' An agent will be with you shortly.' ) wait_music = 'http://com.twilio.music.classical.s3....
import pandas as pd import matplotlib.pyplot as plt import numpy as np from helper import find_csv grid = plt.GridSpec(2, 2, wspace=0.4, hspace=0.3) ax1 = plt.subplot(grid[0,0]) ax2= plt.subplot(grid[0,1]) ax3= plt.subplot(grid[1,:]) for i in find_csv(): df = pd.read_csv(i,header=None) df_forward = df[:int(le...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class SetMaterialRgbParamNode(Node, ArmLogicTreeNode): '''Set material rgb param node''' bl_idname = 'LNSetMaterialRgbParamNode' bl_label = 'Set Material RGB Param' bl_icon = 'GAME' def ...
#!/usr/bin/env python # encoding: utf-8 from smisk.mvc import * from smisk.serialization import data import datetime, time # Importing the serializers causes them to be registered import my_xml_serializer import my_text_serializer # Some demo data DEMO_STRUCT = dict( string = "Doodah", items = ["A", "B", 12, 32.1...
#!/usr/bin/env python """Stp - Stock Patterns Usage: stp_mgr stp_mgr insider """ from docopt import docopt import stp print(stp.__file__) from stp import feed from stp.feed.insidertrading import data import sys def insider(): records = data.get_records() for record in records: print(record) ...
# -------------------------------------------------------- # CRPN # Written by Linjie Deng # -------------------------------------------------------- import yaml import caffe import numpy as np from fast_rcnn.config import cfg from fast_rcnn.nms_wrapper import nms from quad.quad_convert import whctrs, mkanchors, quad_2...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from yandex.cloud.access import access_pb2 as yandex_dot_cloud_dot_access_dot_access__pb2 from yandex.cloud.containerregistry.v1 import registry_pb2 as yandex_dot_cloud_dot_containerregistry_dot_v1_dot_registry__pb2 from yandex.cloud.con...
#----------------------------------------------------------------------- #Copyright 2019 Centrum Wiskunde & Informatica, Amsterdam # #Author: Daniel M. Pelt #Contact: D.M.Pelt@cwi.nl #Website: http://dmpelt.github.io/msdnet/ #License: MIT # #This file is part of MSDNet, a Python implementation of the #Mixed-Scale Dense...
import numpy as np from utils.misc import arr2grid from planner.astar import AStar from planner.dijkstra import Dijkstra from planner.bestfirst import BestFirst from planner.breadthfirst import BreadthFirst from planner.bi_astar import BiAStar from planner.bi_dijkstra import BiDijkstra from planner.bi_bestfirst import ...
#!/usr/bin/env python3 # coding: utf8 # Author: Lenz Furrer, 2017 ''' Formatter base classes. ''' import os import io from lxml import etree class Formatter: ''' Base class for all formatters. ''' ext = None binary = False # text or binary format? def __init__(self, config, fmt_name): ...
# 첫 도착지 # 짝수: 1 -> 2 # 홀수: 1 -> 3 # 두번째 도착지 # 짝수: 1 -> 3 # 홀수: 1 -> 2 # 3번째 도착지 # 작은 아이가 두번째 아이에게 얹힌다. (마지막을 제외하고 다시 뭉친다.) # 4번째 # 3번째로 큰 아이가 빈 곳으로 간다. # 5번째 # 작은 아이가 두번째 + 3번째 아이에게 얹힌다. (마지막을 제외하고 다시 뭉친다.) import sys n = int(sys.stdin.readline()) count = 0 # 매개변수 : 총 개수, 시작, 목표, other,...? def hanoi(total, sta...
from __future__ import unicode_literals from .common import InfoExtractor class YouJizzIE(InfoExtractor): _VALID_URL = r'https?://(?:\w+\.)?youjizz\.com/videos/(?:[^/#?]+)?-(?P<id>[0-9]+)\.html(?:$|[?#])' _TESTS = [{ 'url': 'http://www.youjizz.com/videos/zeichentrick-1-2189178.html', 'md5': '...
# see https://docs.python.org/3/reference/expressions.html#operator-precedence # '|' is the least binding numeric operator # '^' # OK: 1 | (2 ^ 3) = 1 | 1 = 1 # BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0 print(1 | 2 ^ 3) # '&' # OK: 3 ^ (2 & 1) = 3 ^ 0 = 3 # BAD: (3 ^ 2) & 1 = 1 & 1 = 1 print(3 ^ 2 & 1) # '<<', '>>' # OK: 2 &...
import sys import os def jeff(): print('quick attack the enemy press a to attack b to block c for super ') bob=10 alice=60 turn1=0 turn2=2 spr=5 mod1=0 mod2=0 speed=0 c1=print('bob health is ',bob) c2=print('alice health is ',alice) print(c1,c2) ...
wild = "https://image.ibb.co/dPStdz/wild.png" wild_plus_four = "https://image.ibb.co/jKctdz/wild_4.png" red = { '0': 'https://image.ibb.co/gnmtB8/red_0.png', '1': 'https://image.ibb.co/hvRFPT/red_1.png', '2': 'https://image.ibb.co/f9xN4T/red_2.png', '3': 'https://image.ibb.co/hDB4Jo/red_3.png', '4'...
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). # Copyright 2020 Tecnativa - Pedro M. Baeza from odoo import api, fields, models class SaleOrder(models.Model): _inherit = "sale.order" type_id = fields.Many2one( comodel_name="sale.order.type", string="Type", compute="_...
import importlib from functools import partial from multiprocessing import Process, Queue from flask import Flask, request app = Flask("serverfull") bees = ["a", "b"] # TODO: get this from somewhere workers = {} def bee_loop(handler, inq, outq): request = inq.get() print("Got request") outq.put(handl...
import numpy as np import cv2 cap = cv2.VideoCapture(0) facedetection = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') while True: ret, frame = cap.read() gry = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) face = facedetection.detectMultiScale(gry,1.3,5) fo...
# Copyright 2017 VMware Inc. All rights reserved. # 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 # # ...
# -*- coding: UTF-8 -*- """ Automatized configuration and execution of Inspect peptide identification for a list of spectrum files and a list of reference proteomes. Specifications of posttranslational modifications can either be directly passed by the user or assigned to the dataset by its filename (if dataset group i...
from django.db import models # Create your models here. class TipoElectrodomestico(models.Model): nombre = models.CharField(max_length=200) foto = models.ImageField(null =True, blank=True) def __str__(self): #Identificar un objeto return self.nombre def numProductos(self): ...
# Copyright 2021 Lucas Fidon and Suprosanna Shit """ Data loader for a single case. This is typically used for inference. """ import torch from monai.data import Dataset, DataLoader def single_case_dataloader(inference_transform, input_path_dict): """ :param inference_transform :param input_path_dict: di...
import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions import threading import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) class WriteToCallback(beam.PTransform): def __init__(self, callback, lock): self._callback = callback self._lock...
from sys import path path.append('/home/joerojas/Desarrollo/Curso-Basico-Python/101_misModulos/modules') import modulo2 zeroes = [0 for i in range(5)] ones = [1 for i in range(5)] print(modulo2.suma(zeroes)) print(modulo2.producto(ones))
''' Classes from the 'LinkPresentation' framework. ''' try: from rubicon.objc import ObjCClass except ValueError: def ObjCClass(name): return None def _Class(name): try: return ObjCClass(name) except NameError: return None LPMultipleMetadataPresentationTransformer = _Cla...
### Worker threads and payloads for sending web requests from enum import Enum from threading import Thread import requests from requests.adapters import HTTPAdapter from bs4 import BeautifulSoup as bs from urllib.parse import urljoin # The Worker class is reused for both stages of execution, so it needs to be able to...
import os from datetime import datetime from flask import Flask, request, flash, url_for, redirect, \ render_template, abort, send_from_directory from doctor_api.app import doctor_api_bp from patient_api.app import patient_api_bp app = Flask(__name__) app.config.from_pyfile('flaskapp.cfg') app.register_blueprint...
# -*- coding: utf-8 -*- # trump-net (c) Ian Dennis Miller from flask_security import ConfirmRegisterForm from flask_wtf.recaptcha import RecaptchaField class ExtendedRegisterForm(ConfirmRegisterForm): recaptcha = RecaptchaField() def validate(self): rv = ConfirmRegisterForm.validate(self) if...
from crestdsl.model import * # bad practice, but used for the evaluation of commands from .simulator import Simulator import logging logger = logging.getLogger(__name__) import io try: import colored from colored import stylize color_enabled = True except ImportError: color_enabled = False except io....
# # Constant Price Market Making Simulator # # simulate different liquidity provision and trading strategies # from typing import Tuple import csv import numpy as np import pandas as pd from numpy.random import binomial, default_rng # TODO: switch to decimal type and control quantization. numeric errors will kill us...
load("@bazel_gazelle//:deps.bzl", "go_repository") def load_external_go_repositories(): ########## Server request handling ############### go_repository( name = "com_github_andybalholm_brotli", importpath = "github.com/andybalholm/brotli", commit = "1d750214c25205863625bb3eb8190a51b2cef...
from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING from nli_z3950.load_marc_data import get_marc_records_schema, parse_record from pymarc.marcxml import parse_xml_to_array import datetime, json def get_resource(parameters, stats): stats['sea...
import os import sqlite3 class DatabaseRepository: def __init__(self, database_file, schema_file): db_is_new = not os.path.exists(database_file) self.connection = sqlite3.connect(database_file, check_same_thread=False) if db_is_new: with open(schema_file, 'rt') as f: ...
"""Utility methods for interacting with Kubernetes API server. This module is merged into the `metalk8s_kubernetes` execution module, by virtue of its `__virtualname__`. """ from __future__ import absolute_import from salt.exceptions import CommandExecutionError import salt.utils.files import salt.utils.templates imp...
import logging.config import configparser import metrics from datetime import datetime import urllib.request from unittest import mock from requests import request from aiohttp.web import Response from jiracollector import JiraCollector import pytest config = configparser.ConfigParser() config.read('metrics.ini') lo...
""" MIT License mift - Copyright (c) 2021 Control-F Author: Mike Bangham (Control-F) Permission is hereby granted, free of charge, to any person obtaining a copy of this software, 'mift', and associated documentation files (the "Software"), to deal in the Software without restriction, including without limita...
from constant_sum import * if __name__ == "__main__": t = 56 n = 510 s = 510 for i in range(500): l = (T_len(t,n-i,s)) if l>0: print(log(l,2),t, n-i, s, t*n - s+i, t*n ) #for b in range(t, 1, -1): # p = 0 # k = min(n*(t - b + 1), s) # #k = s #...
from .statement_base import Statement import sasoptpy class DropStatement(Statement): @sasoptpy.class_containable def __init__(self, *elements): super().__init__() for i in elements: self.elements.append(i) self.keyword = 'drop' def append(self, element): pas...
R = int(input()) print(2*3.141592653589793*R)
import numpy as np import pandas as pd import sys from typing import Literal from arch import arch_model import warnings from sklearn.exceptions import ConvergenceWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", category=ConvergenceWarning) def get_rolling_vol_forecasts(return_series, ...
from django.templatetags.static import static as get_static_url from django.shortcuts import redirect from .exceptions import UnknownMessageTypeError from .models import Dispatch from .signals import sig_unsubscribe_failed, sig_mark_read_failed def _generic_view(message_method, fail_signal, request, message_id, disp...
""" Modules for prediciting topological properties """
""" Class of water block """ import os from .block import Block import math class CurrentWaterRight(Block): """ Represents the block of water """ def __init__( self, settings: any, path: str = 'advancing_hero/images/blocks/water3.png', ): super().__init__(os.path.ab...
# Importar las dependencias de flask from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for # Importar clave/ayudantes de encriptacion from werkzeug import check_password_hash, generate_password_hash # Importar FireBase from firebase import firebase # Importar el objeto de base d...
def ErrorHandler(function): def wrapper(*args, **kwargs): try: return function(*args, **kwargs) except Exception as e: # pragma: no cover pass return wrapper
import pandas as pd import numpy as np import tensorflow as tf from math import floor from dataset.date_format import START_CODE, INPUT_FNS, OUTPUT_VOCAB, encodeInputDateStrings, encodeOutputDateStrings, dateTupleToYYYYDashMMDashDD def generateOrderedDates(minYear: str, maxYear: str) -> list: daterange = pd.date...
from __future__ import division, print_function, absolute_import # LIBTBX_SET_DISPATCHER_NAME iota.single_image # LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1 # LIBTBX_PRE_DISPATCHER_INCLUDE_SH export BOOST_ADAPTBX_FPE_DEFAULT=1 ''' Author : Lyubimov, A.Y. Created : 05/31/2018 Last Change...
import requests from bs4 import BeautifulSoup import urllib.request import pytesseract from PIL import Image from PIL import ImageEnhance def shibie(filepath): # 打开图片 img = Image.open(filepath) img = img.convert('RGB') enhancer = ImageEnhance.Color(img) enhancer = enhancer.enhance(0) enhancer =...
import random import uuid from datetime import timedelta import re from discord import AllowedMentions, ButtonStyle, Embed from squid.bot import CommandContext, SquidPlugin, command from squid.bot.errors import CommandFailed from squid.utils import now, parse_time, s from .views import GiveawayView class Giveaways(S...
# Copyright 2016, FBPIC contributors # Authors: Remi Lehe, Manuel Kirchen # License: 3-Clause-BSD-LBNL """ This file is part of the Fourier-Bessel Particle-In-Cell code (FB-PIC) It defines the structure necessary to implement the moving window. """ from fbpic.utils.threading import njit_parallel, prange # Check if CUDA...
from django.shortcuts import render from swpp.models import Profile from swpp.serializers import ProfileSerializer from rest_framework import generics, mixins, permissions from swpp.permissions import IsOwnerOrReadOnly class ProfileList(generics.ListAPIView): queryset = Profile.objects.all() serializer_class =...
KIND = { 'JOB': 'job', 'DEPLOYMENT': 'deployment' } COMMAND = { 'DELETE': 'delete', 'CREATE': 'create' }
# Copied from http://www.djangosnippets.org/snippets/369/ import re import unicodedata from htmlentitydefs import name2codepoint from django.utils.encoding import smart_unicode, force_unicode from slughifi import slughifi def slugify(s, entities=True, decimal=True, hexadecimal=True, model=None, slug_field='slug', p...
from typing import Optional from typing import Tuple import attr @attr.s(auto_attribs=True) class SlotAttentionParams: # model configs resolution: Tuple[int, int] = (128, 128) # since we not using ViT # Slot Attention module params num_slots: int = 7 # at most 6 obj per image/video # dim of sl...
from verifai.simulators.car_simulator.examples.control_utils.LQR_computation import * from verifai.simulators.car_simulator.simulator import * from verifai.simulators.car_simulator.lane import * from verifai.simulators.car_simulator.car_object import * from verifai.simulators.car_simulator.client_car_sim import * impor...
import numpy as np from mesostat.metric.impl.mar import unstack_factor, rel_err def predict(x, alpha, u, beta): # return np.einsum('ai,ijk', alpha, x) + np.einsum('ai,ijk', beta, u) return x.dot(alpha.T) + u.dot(beta.T) def fit_mle(x, y, u): # # Construct linear system for transition matrices # M11 ...
''' The MIT License (MIT) Copyright © 2021 Opentensor.ai 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,...
from srf.io.listmode import save_h5 import numpy as np data = np.fromfile("normal_scan_true.txt", dtype=np.float32).reshape(-1,7) result = {'fst': data[:, :3], 'snd': data[:, 3:6], 'weight': np.ones_like(data[:,0])} save_h5('input.h5', result)
from flask import Flask from . import api, web app = Flask( __name__, static_url_path='/assets', static_folder='static', template_folder='templates') app.config['SECRET_KEY'] = 'secret' # this is fine if running locally app.register_blueprint(api.bp) app.register_blueprint(web.bp)
default_app_config = 'user_deletion.apps.UserDeletionConfig'
#!/usr/bin/python # -*- coding: utf-8 -*- """ Copyright 2012-2021 Smartling, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this work except in compliance with the License. * You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/l...
# =============================================================================== # NAME: SerialHVisitor.py # # DESCRIPTION: A visitor responsible for the generation of header file # for each serializable class. # # AUTHOR: reder # EMAIL: reder@jpl.nasa.gov # DATE CREATED : June 4, 2007 # # Copyright 201...
import time import os import binascii import re from datetime import datetime from bson.json_util import dumps, loads from flask.helpers import get_template_attribute from flask import render_template from init import app, rdb from utils.jsontools import * from utils.dbtools import makeUserMeta from db i...
import socket import threading class Server: def __init__(self, ip, port): self.sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sck.bind((ip, port)) self.sck.listen() self.conCallback = None self.clientThrCallback = None self.disconCallback = None self.clients = { } self.nextClID = 0 def...
from math import pi, cos, log, floor from torch.optim.lr_scheduler import _LRScheduler class CosineWarmupLR(_LRScheduler): ''' Cosine lr decay function with warmup. Ref: https://github.com/PistonY/torch-toolbox/blob/master/torchtoolbox/optimizer/lr_scheduler.py https://github.com/Randl/MobileNetV...
from construct import * from construct.lib import * switch_integers__opcode = Struct( 'code' / Int8ub, 'body' / Switch(this.code, {1: Int8ub, 2: Int16ul, 4: Int32ul, 8: Int64ul, }), ) switch_integers = Struct( 'opcodes' / GreedyRange(LazyBound(lambda: switch_integers__opcode)), ) _schema = switch_integers
# -*- coding: utf-8 -*- # bricks.py: utility collections. # # Copyright (C) 2009, 2010 Raymond Hettinger <python@rcn.com> # Copyright (C) 2010 Lukáš Lalinský <lalinsky@gmail.com> # Copyright (C) 2010 Yesudeep Mangalapilly <yesudeep@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a c...
# -*- coding: utf-8 -*- """ PyEVO reCAPTCHA API module =============================================== .. module:: pyevo.api.recaptcha :platform: Unix, Windows :synopsis: PyEVO reCAPTCHA API module .. moduleauthor:: (C) 2012 Oliver Gutiérrez TODO: Check recaptcha API module for incomplete class method get_ch...
from ._container import AadModelContainer from onnxconverter_common.topology import Topology from onnxconverter_common.data_types import FloatTensorType from ad_examples.aad.forest_aad_detector import AadForest def _get_aad_operator_name(model): # FIXME: not all possible AAD models are currently supported if not is...
#import matplotlib.pyplot as plt from flask import Flask, render_template, jsonify import requests import json import numpy as np import time app = Flask(__name__) @app.route('/') def index(): r = requests.get("http://127.0.0.1:5000/chain").text r = json.loads(r) # Fetch the chain length chain_leng...
import numpy as np import lsst.afw.table as afwTable import lsst.pex.config as pexConfig import lsst.pipe.base as pipeBase import lsst.geom as geom import lsst.sphgeom as sphgeom from lsst.meas.base.forcedPhotCcd import ForcedPhotCcdTask, ForcedPhotCcdConfig from .forcedPhotDia import DiaSrcReferencesTask __all__ = ...
# Generated by Django 2.1 on 2018-09-08 14:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('api', '0003_market'), ] operations = [ migrations.AlterUniqueTogether( name='market', unique_together={('name', 'exchange')}, ...
import serial import struct import time def init_Serial(): print("Opening Serial Port COM 10") ser = serial.Serial( port='COM10', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS ) return ser def wait_for_Pi(se...
from .Updater import Converters class _DataManager: def unpack(self, data): return self.unpackItems(data.items()) def unpackItems(self, items): return {key: self.itemsToDict(value) for key, value in items} def itemsToDict(self, data): if hasattr(data, "__dict__"): ret...
#!/usr/bin/env python from __future__ import print_function import roslib roslib.load_manifest('mct_watchdog') import rospy import threading import functools import numpy import mct_introspection import yaml import cv import Image as PILImage import ImageDraw as PILImageDraw import ImageFont as PILImageFont from cv_b...
#!/usr/bin/python # # Example of complex # Graph representing a network # import gvgen # Creates the new graph instance graph = gvgen.GvGen(None, "overlap=\"scale\";\nlabelfloat=\"true\";\nsplines=\"true\";") # We define different styles graph.styleAppend("router", "shapefile", "router.png") graph.styleAppend("router...
""" Functions related to calculating the rotational energy of asymmetric molecules. Townes and Schawlow, Ch. 4 """ from pylab import poly1d def asymmetry (A,B,C): """ Ray's asymmetry parameter for molecular rotation. For a prolate symmetric top (B = C), kappa = -1. For an oblate symmetric top (B = A), kappa =...
import matplotlib.pyplot as plt import numpy as np import torch # from scipy.special import softmax # from mpl_toolkits.axes_grid1 import make_axes_locatable def compare_distogram(outputs, targets): plt.figure(num=1, figsize=[15, 10]) plt.clf() # names = ['Distance','Omega','Phi','Theta'] names = ['dN...
import functools import requests import suds.transport as transport import traceback try: import cStringIO as StringIO except ImportError: import StringIO __all__ = ['RequestsTransport'] def handle_errors(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args,...
''' @author: Frank ''' import zstacklib.utils.http as http import zstacklib.utils.log as log import zstacklib.utils.plugin as plugin import zstacklib.utils.jsonobject as jsonobject import zstacklib.utils.daemon as daemon import zstacklib.utils.iptables as iptables import os.path import functools import t...
#a POC of queue manager with two button to increment and decrement the current value and broadcast it by wifi import machine from machine import I2C, Pin import time import network #set to True to enable a display, False to disable it use_display=True if use_display: #display setup, i have a 128x32 oled on this...
import sys import PyNexusZipCrawler # GET NEXUS MODS MOD ID FROM USER INPUT f_id = raw_input("Enter the Nexus Mods File ID you want to crawl: ") # CRAWL IT PyNexusZipCrawler.crawl_zip_content(f_id, "110")
import logging import os import pyaudio, wave, pylab import numpy as np import librosa, librosa.display import matplotlib.pyplot as plt from scipy.io.wavfile import write from setup_logging import setup_logging INPUT_DEVICE = 0 MAX_INPUT_CHANNELS = 1 # Max input channels DEFAULT_SAMPLE_RATE = 44100 # Default sample...
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you unde...
from flask import Flask, jsonify import json from flask import Flask, render_template import numpy as np from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an ...
class User(): def __init__(self, first_name, last_name, gender, email): self.first_name = first_name self.last_name = last_name self.gender = gender self.email = email self.login_attempts = 0 def describe_user(self): print(self.first_name) print...
#!/usr/bin/env python import pod import sys, binascii from StringIO import StringIO def ConvertMac(dotted): if dotted.find(":") == -1: str = binascii.unhexlify(dotted) else: str = "".join([chr(eval("0x"+i)) for i in dotted.split(":")]) if len(str) != 6: raise ValueError("Not a MAC address") ret...
from typing import List from ..codes import * from dataclasses import dataclass @dataclass(repr=True, eq=True) class OppoCommand: """Represents a command to an OppoDevice""" code: OppoCodeType _parameters: List[str] _response_codes: List[str] def __init__(self, code: OppoCodeType, parameters: List[str] = No...
from django.urls import path from rest_framework import routers from .views import * router = routers.DefaultRouter() router.register('notes', NoteViewSet, basename='notes') router.register('projects', ProjectViewSet, basename='projects') router.register('habits', HabitViewSet, basename='habits') urlpatterns = router...
import torch.nn as nn import torch from Postional import PositionalEncoding class TransAm(nn.Module): def __init__(self, feature_size=200, num_layers=1, dropout=0.1): super(TransAm, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalE...
# just a package
class Solution: def isPalindrome(self, x: int) -> bool: temp = str(x) length = len(temp) flag = 0 for i in range(0,length): if temp[i:i+1] != temp[length-1-i:length-i]: flag = 1 if flag == 1: return False else: retur...
from django.contrib import admin from .models import Pokemon admin.site.register(Pokemon)
#!/usr/local/bin/python3 #-*- encoding: utf-8 -*- from flask import Flask from flask_restx import Api from setting import config from app.api.client import worker_client def run(): app = Flask(__name__) api = Api( app, version='dev_0.1', title='Integrated Worker Server API', de...
# ==============================CS-199================================== # FILE: MyAI.py # # AUTHOR: Vaibhav Yengul # # DESCRIPTION: This file contains the MyAI class. You will implement your # agent in this file. You will write the 'getAction' function, # the constructor, and...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import getopt import os.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))) from datetime import datetime from TwitterEngine import instances, BackendChooser def parseargs(name, argv): date = datetime.now() execut...
from django.contrib import admin from django.contrib.auth.decorators import login_required, permission_required from django.urls import path from . import views from .api import views as api_views app_name = 'main_app' urlpatterns = [ path('api/sites/', api_views.SitesListCreateAPIView.as_view(), name='sites_rest_...
import numpy as np from features.DetectorDescriptorTemplate import DetectorDescriptorBundle from features.cv_sift import cv_sift class SiftDetectorDescriptorBundle(DetectorDescriptorBundle): def __init__(self, descriptor): sift = cv_sift() super(SiftDetectorDescriptorBundle, self).__init__(sift, d...
import torch import torch.nn.functional as F import torch.nn as nn from transformers import BertModel # Convlution,MaxPooling層からの出力次元の算出用関数 def out_size(sequence_length, filter_size, padding = 0, dilation = 1, stride = 1): length = sequence_length + 2 * padding - dilation * (filter_size - 1) - 1 length...
from pi import KafkaProducerClient class LogProducer(object): # TODO: Implement parallel processing producer = KafkaProducerClient() for idx in range(1000): data = { "res": { "body": { "success": False, "code": "INTERNAL_SERVER_ER...