text
stringlengths
2
999k
""" Functions for explaining classifiers that use tabular data (matrices). """ import collections import json import copy import numpy as np import sklearn import sklearn.preprocessing from . import lime_base from . import explanation class TableDomainMapper(explanation.DomainMapper): """Maps feature ids to names...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
import datetime import os from sqlalchemy import Column from sqlalchemy import DateTime from sqlalchemy import event from sqlalchemy import Float from sqlalchemy import ForeignKey from sqlalchemy import inspect from sqlalchemy import Integer from sqlalchemy import MetaData from sqlalchemy import sql from sqlalchemy im...
import inspect import io import os import platform import sys import threading from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime from functools import wraps from getpass import getpass from html import escape from inspect import isclass from itertools import isli...
import nnabla as nn import numpy as np from .identity import IdentityConverter from .helpers import GraphInfo class BatchNormalizationLinearConverter(IdentityConverter): """ The parameters of the batch normalization replaced simple scale and bias. Args: black_list (list): Black list of the funct...
from components.base.ecu.software.abst_comm_layers import AbstractCommModule from components.base.ecu.software.impl_physical_layers import StdPhysicalLayer from components.base.ecu.software.impl_datalink_layers import StdDatalinkLayer from components.base.ecu.software.impl_transport_layers import SegmentTransportLayer ...
AppOgl(OpenGLFrame): def initgl(self): """Initalize gl states when the frame is created""" GL.glViewport(0, 0, self.width, self.height) GL.glClearColor(0.0, 1.0, 0.0, 0.0) self.start = time.time() self.nframes = 0 def redraw(self): """Render a single frame""...
from .direct import * from . import direct from . import sparse from . import tridiagonal
#!/usr/bin/env python3 # SPDX-FileCopyrightText: © 2022 Decompollaborate # SPDX-License-Identifier: MIT from __future__ import annotations import dataclasses import struct @dataclasses.dataclass class Elf32RelEntry: offset: int # address # 0x00 info: int # word # 0x04 #...
import os import glob import json import torch import torchvision.transforms as transforms import torch.nn as nn import matplotlib.pyplot as plt import numpy as np from scipy.signal import resample, find_peaks from pulse_sampler import PulseSampler from pulse_dataset import PulseDataset from NegPearsonLoss import NegPe...
import psycopg2 usuario = "INSERT HERE" senha = "INSERT HERE" ip = "INSERT HERE" porta = "INSERT HERE" db_name = "INSERT HERE" ################################################################### # ALTERAR SOMENTE AS VARIAVEIS ACIMA !!!! # #############################################...
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from test/display_draw_lineRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class display_draw_lineRequest(genpy.Message): _md5sum = "01b404007f6687249fa0f27eea3...
import os from pathlib import Path from pprint import pprint from datetime import datetime from xml.dom import minidom import xml.etree.ElementTree as ET import re def get_all_txt_file_path(): txt_files_paths = list() for root, dirs, files in os.walk(os.getcwd()): for file in files: if fil...
""" Example Programme to for a Spot Digram using high level SpotAnalysis class """ from poptics.lens import DataBaseLens from poptics.vector import Angle,Unit3d from poptics.wavelength import getDefaultWavelength from poptics.analysis import SpotAnalysis from poptics.tio import getFloat import matplotlib.pyplot a...
# coding: utf-8 __author__ = 'Antonis' ''' Python script for Kaggle Competition This script focuses on reading the train dataset and getting information for non-numerical values. To run the script you need to have the "train.csv" file inside the /dataset folder in the project root. ''' import pandas as pd import num...
#! /usr/bin/env python from enum import IntEnum from aoc.intcode import IntCodeCPU, InterruptCode from aoc.utils import load_input class Color(IntEnum): BLACK = 0 WHITE = 1 class Direction(IntEnum): UP = 0 DOWN = 1 LEFT = 2 RIGHT = 3 class TurnDirection(IntEnum): LEFT = 0 RIGHT = ...
"""Unit tests for django_evolution.evolve.Evolver and related classes.""" from __future__ import unicode_literals from django.db import connections, models from django.dispatch import receiver from django_evolution.compat.apps import get_app, get_apps from django_evolution.errors import (EvolutionBaselineMissingErro...
from sys import float_info from sys import stdout as sysout import numpy as np import numpy.random as random import torch from IIC.code.utils.segmentation.baselines.general import pol2cart def isola_loss(adjacent_pred, centre, other, adjacent_gt, mask, verbose=False, EPS=float_info.epsilon): bn = a...
# Warning: This module must be imported before any imports of the requests module. from __future__ import unicode_literals from contextlib import contextmanager import functools import logging import os import random import time try: from warcio.capture_http import capture_http warcio_failed = False except Im...
from ryu.services.protocols.bgp.operator.views.base import \ create_dict_view_class from ryu.services.protocols.bgp.operator.views.base import \ create_list_view_class from ryu.services.protocols.bgp.operator.views.base import OperatorDetailView from ryu.services.protocols.bgp.operator.views import fields from...
"""Test date/time type. See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases """ from test.support import is_resource_enabled import itertools import bisect import copy import decimal import sys import os import pickle import random import struct import unittest from array import array from operator impor...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
import json from operator import itemgetter from contextlib import ExitStack from textwrap import dedent class TestAddPallet: def test_no_pallet(self, host): # Call add pallet with nothing mounted and no pallets passed in result = host.run('stack add pallet') assert result.rc == 255 assert result.stderr == 'e...
from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtGui import * from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtCore import QTimer import qdarkstyle import sys import time from utils import detector_utils as detector_utils import tensorflow as tf import datetime import argparse import numpy...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import traceback import warnings from ..extern.six.moves import xmlrpc_client as xmlrpc from ..extern.six.moves import socketserver f...
#!/usr/bin/env python3 # 2nd-party imports. import CommonModule def Metadata(signedBody, num_of_keys=1): '''https://github.com/uptane/asn1/blob/master/MetadataModule.asn1''' signatures = CommonModule.Signatures(num_of_keys) numberOfSignatures = CommonModule.LENGTH_SIZE_IN_BYTES type = CommonModule.TAG_SIZE_...
# for i in range(0, 5): for j in range(0, 5): print("*", end=" ") print('')# # for row in range(6): for coloumn in range(5): if ((coloumn==0 or coloumn==4) and row!=0) or ((row==0 or row==3) and (coloumn>0 and coloumn<5)): print("") ###################### for i in range(0,6): for j i...
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) import numpy as np # TODO: add formal tests import pandas as pd from sklearn.utils import check_array, check_consistent_length from sktime.datatypes import check_is_scitype, convert from sktime.p...
""" Helpers for accessing C++ STL containers in GDB. """ # @lint-avoid-python-3-compatibility-imports # @lint-avoid-pyflakes3 # @lint-avoid-pyflakes2 import gdb import re from gdbutils import * from hashes import hash_of #------------------------------------------------------------------------------ # STL accessors....
#!/usr/bin/env python3 ''' Return a list of items without any elements with the same value next to each other and preserve the original order of elements. ''' def unique_in_order(a): newlist = [] for i in a: if len(newlist) < 1 or not i == newlist[len(newlist) -1]: newlist.append(i) retu...
import pyaf.Bench.TS_datasets as tsds import pyaf.tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "None", sigma = 0.0, exog_count = 0, ar_order = 0);
{ "targets": [ { "target_name": "addon", "sources": [ "addon.cpp" ], "cflags!": [ "-fno-exceptions" ], "cflags_cc!": [ "-fno-exceptions" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], 'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ], } ] }
# # 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, software # ...
# Configuration file for jupyter-notebook. #------------------------------------------------------------------------------ # Application(SingletonConfigurable) configuration #------------------------------------------------------------------------------ ## This is an application. ## The date format used by logging f...
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli...
# Pyrogram - Telegram MTProto API Client Library for Python # Copyright (C) 2017-2018 Dan Tès <https://github.com/delivrance> # # This file is part of Pyrogram. # # Pyrogram is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published # by the Free S...
"""Contains functions for installing FFmpeg. Follows the instructions here (https://trac.ffmpeg.org/wiki/CompilationGuide) for compiling FFmpeg. """ from absl import flags FLAGS = flags.FLAGS _APT_DEPS = [ 'autoconf', 'automake', 'build-essential', 'cmake', 'git-core', 'libass-dev', 'libfreetype6-dev', 'libg...
import os import pdfkit import requests import requests_html def GetPosterNumber(base_url): photos_url = base_url + 'all_photos' r = session.get(photos_url) try: poster_num = int(r.html.xpath("/html/body/div[3]/div[1]/div/div[1]/div[2]/div[1]/h2/span/a")[0].text[1:-1]) except: poster_n...
#!/usr/bin/env python ''' parse a MAVLink protocol XML file and generate a C implementation Copyright Andrew Tridgell 2011 Released under GNU GPL version 3 or later ''' from __future__ import print_function from future.utils import iteritems from builtins import range from builtins import object import os from . imp...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import pymysql.cursors class NovelPipeline(object): def __init__(self): self.file = open('items.jl', ...
import socket import threading from queue import Queue target = "127.0.0.1" queue = Queue() open_ports = [] def portscan(port): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((target, port)) return True except: return False def fill...
from collections import Counter from dataclasses import dataclass, field from typing import Optional, List @dataclass class Paper: title: str abstract: Optional[str] = None keywords: Optional[str] = None _text: Optional[str] = None text_attr = ('title', 'abstract', 'keywords') @property d...
import json from ..utils import verify_str _default_icon = "icon.gif" class ServiceArgError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class ServiceArg(tuple): """ServiceArg(name_str, type_str) -> ServiceArg This class is us...
import logging from typing import List from uuid import UUID from fastapi import APIRouter, Depends from sqlalchemy.ext.asyncio import AsyncSession from starlette import status from api.db.models.sandbox import SandboxCreate from api.db.models.related import SandboxReadPopulated, OutOfBandReadPopulated from api.db.re...
import os, pytest from pathlib import Path from ..copygeom import CopyGeom @pytest.mark.parametrize("inputs, outputs", []) def test_CopyGeom(test_data, inputs, outputs): in_file = Path(test_data) / "test.nii.gz" if inputs is None: inputs = {} for key, val in inputs.items(): try: ...
## # Copyright (c) 2018, Microsoft Corporation # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions a...
# -*- coding: utf-8 -*- # Copyright 2022 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 o...
########################################### ##### Otterifies Notebooks from Gofer ##### ########################################### import json import sys import nbformat import re import os GOFER_IMPORT_REGEX = r"from gofer\.ok import check" GOFER_REGEX = r"check\([\"'](.+)\.py[\"']\)" for notebook in sys.argv[1:]:...
#! /usr/bin/env python # # Delete a list of existing users from the running configuration using # edit-config and the candidate datastore protected by a lock. # # $ ./nc07.py broccoli bob alice import sys, os, warnings warnings.simplefilter("ignore", DeprecationWarning) from ncclient import manager template = """<nc:...
import requests import getpass import shutil import os import sys METADATA_URL = "http://a1.phobos.apple.com/us/r1000/000/Features/atv/AutumnResources/videos/entries.json" CACHE_DIR = "/Users/:uname/Library/Caches/Aerial/" def cachePhotos(): """ Caches all of the photos that the Aerial screen saver uses ...
import nibabel as nb import numpy as np # TODO: compare with Nilearn functions and possibly extend def load_mesh(surf_mesh): ''' Load a mesh into a dictionary with entries "points", "faces" and "data" Parameters ---------- surf_mesh: Mesh to be loaded, can be a path to a file ...
from pathlib import Path import os if os.environ.get('XDG_CONFIG_HOME'): config_home = Path(os.environ.get('XDG_CONFIG_HOME')) else: config_home = Path.home() / '.config' if os.environ.get('XDG_CONFIG_DIRS'): config_global = [Path(dir) for dir in os.environ.get('XDG_CONFIG_DIRS').split(':')] else: con...
from ._certificate import Certificate
import argparse import errno import json import logging import os import re from collections import defaultdict from find_apps import find_apps from find_build_apps import BUILD_SYSTEMS, BUILD_SYSTEM_CMAKE from ttfw_idf.CIAssignExampleTest import CIExampleAssignTest, TestAppsGroup, ExampleGroup VALID_TARGETS = [ ...
import xml.etree.ElementTree as ET import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.svm import SVC from sklearn.linear_model import SGDClassifier from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt from ...
from battles.models import Invite from pokebattle import celery_app @celery_app.task def remove_used_invite(invite_id): invite = Invite.objects.get(id=invite_id) invite.delete()
from card_live_dashboard.model.GeographicSummaries import GeographicSummaries from card_live_dashboard.service import region_codes world = region_codes.get_un_m49_regions_naturalearth() geographic_summaries = GeographicSummaries(region_codes)
""" Datadogpy is a collection of Datadog Python tools. It contains: * datadog.api: a Python client for Datadog REST API. * datadog.dogstatsd: a DogStatsd Python client. * datadog.threadstats: an alternative tool to DogStatsd client for collecting application metrics without hindering performance. * datadog.dogshell: a ...
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Factory method for easily getting imdbs by name.""" __sets = {} fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: Ampel-core/ampel/cli/AbsLoadCommand.py # License: BSD-3-Clause # Author: valery brinnel <firstname.lastname@gmail.com> # Date: 25.03.2021 # Last Modified Date: 29.03.2021 # Last Modified By: valery brinnel <...
from business.concrete.concrete_strategy import ConcreteStrategy from business.factories.abstract_strategy_factory import AbstractFactory class ConcreteFactory(AbstractFactory): def create_calc_strategy(self) -> ConcreteStrategy: return ConcreteStrategy()
# (c) [Muhammed] @PR0FESS0R-99 # (s) @Mo_Tech_YT , @Mo_Tech_Group, @MT_Botz # Copyright permission under MIT License # All rights reserved by PR0FESS0R-99 # License -> https://github.com/PR0FESS0R-99/DonLee-Robot-V2/blob/Professor-99/LICENSE import re import time from typing import List from pyrogram.types import Mess...
# -*- coding: utf-8 -*- """ Test the Rescale class. """ import numpy as np import pytest from unittest.mock import create_autospec from nessai.livepoint import numpy_array_to_live_points from nessai.reparameterisations import Rescale @pytest.fixture() def reparam(): return create_autospec(Rescale) @pytest.mark...
# Copyright (c) 2021 PaddlePaddle Authors. 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 appli...
class ListNode(object): def __init__(self, x): self.val = x self.next = None ''' 回溯法 ''' class Solution1(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head ...
#!/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 ...
"""Support for Lutron switches.""" from homeassistant.components.switch import SwitchEntity from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron switches.""" devs = [] # Add Lutron Switches for (area_n...
from huobi import RequestClient from huobi.constant.test import * from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) print("\n==============test case 1===============\n") result = request_client.get_open_orders(symbol="btcus...
#!/usr/bin/env python3 import os import subprocess from os.path import join as p def main() -> int: files = [] root = "MoMMI" for dirpath, dirnames, filenames in os.walk(root): if "__pycache__" in dirnames: dirnames.remove("__pycache__") if ".mypy_cache" in dirnames: ...
# %% import git import pandas as pd import numpy as np # Find home directory for repo repo = git.Repo("./", search_parent_directories=True) homedir = repo.working_dir #Import plotting features import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib.colors import BoundaryN...
""" Module: 'urandom' on esp32_LoBo 3.2.24 """ # MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32') # Stubber: 1.2.0 def choice(): pass def getrandbits(): pass def randint(): pass def random(): pass def r...
from models.agent import Agent from models.staging_message import StagingMessage from backend.database import db from backend.rabbitmq import rabbit_producer from logger import log def agent_json(agent): log("agent_json", "Working on %s" % agent) agentType = dict({ "Id": agent.AgentType.Id, "...
from pathlib import Path from alphafold.Data.Tools import utils from typing import Optional, Callable, Any, Mapping, Sequence import subprocess class Jackhammer: def __init__(self, binary_path:Path, database_path:Path, n_cpu:int=8, n_iter:int=1, e_value:float=1e-4, z_value:Optional[float]=None, filter_f1...
import unittest from tweetfeels import TweetData from tweetfeels import Tweet from datetime import datetime, timedelta import json import os import pandas as pd import numpy as np class Test_Data(unittest.TestCase): def setUp(self): self.tweets_data_path = 'test/sample.json' self.db = './test.sqli...
# coding=utf-8 # pynput # Copyright (C) 2015-2021 Moses Palmér # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later ve...
#!/usr/bin/env python import requests import json import logging logger = logging.getLogger(__name__) class TuLing(): def __init__(self): self.__key__ = '2f1446eb0321804291b0a1e217c25bb5' self.__appid__ = 137762 def __build_req_url(self, content): return 'http://www.tuling123.com/op...
from django.db import models import time import datetime from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.http import HttpResponse, JsonResponse from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserMan...
import gym from metarl.envs import MetaRLEnv, normalize class TestNormalizedGym: def setup_method(self): self.env = MetaRLEnv( normalize(gym.make('Pendulum-v0'), normalize_reward=True, normalize_obs=True, flatten_obs=True)) ...
import pytest from mock import MagicMock, PropertyMock, patch from django import forms from pontoon.base.models import Resource from pontoon.tags.admin.forms import LinkTagResourcesAdminForm @pytest.mark.django_db def test_form_project_tag_resources(client, project0, tag0): # tests instantiation of TagResourc...
# For this basic implementation, we only need these modules from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier # Load the well-known Breast Cancer dataset # Split into train ...
# Падение волн вертикальной поляризации под углом Брюстера from rwp.sspade import * from rwp.vis import * from rwp.environment import * #from rwp.petool import PETOOLPropagationTask logging.basicConfig(level=logging.DEBUG) environment = Troposphere(flat=True) environment.z_max = 80 environment.ground_material = Custo...
# Advent of Code 2015 - Day 7 - Some Assembly Required # http://adventofcode.com/2015/day/7 import sys GATE_INPUT = 0 GATE_NOT = 1 GATE_AND = 2 GATE_OR = 3 GATE_RSHIFT = 4 GATE_LSHIFT = 5 GATE_CONNECT = 6 # Parse the input and return a map def parse_input(s): circuit = {} for line in s: gate, output ...
# Copyright 2015 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 a...
from allauth.socialaccount.providers.oauth_provider.urls import default_urlpatterns from .provider import BoxOAuth2Provider urlpatterns = default_urlpatterns(BoxOAuth2Provider)
# -*- coding: utf-8 -*- from classytags.arguments import Argument, MultiValueArgument from classytags.core import Options, Tag from classytags.helpers import InclusionTag, AsTag from classytags.parser import Parser from cms.models import Page, Placeholder as PlaceholderModel from cms.plugin_rendering import render_plac...
from datetime import datetime, timezone from typing import Union, List, Dict, Tuple from .covidstatistics import * from .exceptions import NotFound, BadSortParameter, BadYesterdayParameter, BadTwoDaysAgoParameter, BadAllowNoneParameter from .covidendpoints import * class Covid: """ Handles interactions with t...
from dataclasses import dataclass, field from parlai.agents.programr.config.base import BaseConfigurationData @dataclass class BrainTokenizerConfiguration(BaseConfigurationData): libname: None = field(default=None) split_chars: str = field(default=" ")
import numpy as np from astropy import units from pyburst.grids import grid_analyser from pyburst.physics import gravity def add_alpha(kgrid): """Adds alpha column to given Kgrid parameters ---------- kgrid : grid_analyser.Kgrid grid object containing model data """ add_redshift(kgri...
# Generated by Django 3.1 on 2020-08-11 04:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('davematthews', '0004_auto_20200811_0431'), ] operations = [ migrations.AddField( model_name='submission', name='conten...
from django.urls import path from .views import VersionUpdateView, DownloadView def get_api_urls(slug=None): """ get_api_urls returns proper urls to be included :param slug: if given, we generate urls only for single application :return: """ if slug is not None: return [ ...
from typing import Iterable, Tuple from .protocol import Protocol __all__ = [ 'Plain', ] # noinspection PyAbstractClass class Plain(Protocol): def _encode(self, dataset: Iterable[Tuple[str, int, int]]) -> bytes: return ''.join('{} {} {}\n'.format(*tpl) for tpl in dataset).encode('ascii')
# SPDX-License-Identifier: Apache-2.0 """Unit Tests for gru.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import tensorflow as tf from tensorflow.python.ops import init_ops from tensorflow....
from flask import Flask, request import json import requests as req from config import config from services.fb import FbApp app = Flask(__name__) Fb = None def configure_fb_app(): global Fb Fb = FbApp(config['fb_page_access_token'], config['fb_graph_url']) @app.route('/webhook', methods = ['POST']) def ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from fastai.vision import models,cnn_learner,error_rate,accuracy from fastai.basic_train import LearnerCallback,dataclass,nn from rx.subjects import Subject @dataclass class ProgressCallback(LearnerCallback): batch_end_subject:Subject def on_batch_end(self, **kwargs): print("batch end") self.bat...
#!/usr/bin/env python """ FattreeTopology: creates a simple fattree topology with N edge switches connected to N-1 core switches. Each edge switch connects to 2 hosts. """ from mininet.topo import Topo class FattreeTopology(Topo): def build(self, numEdgeSwitches=2, bw=20, hostsPerEdge=2): linkopts =...
import os from sanic import Sanic, response as res from sanic.exceptions import NotFound from sanic.websocket import ConnectionClosed import json from database import get_messages, post_message # initiate the sanic app app = Sanic('app') # list of connected clients clients = set() # function that sends a websocket m...
import django_filters from django.contrib.auth.decorators import permission_required from django.urls import reverse from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from coti...
"""String utilities. """ # Author Info __author__ = 'Vishwajeet Ghatage' __date__ = '17/07/21' __email__ = 'cloudmail.vishwajeet@gmail.com' # Library Imports import random import string from datetime import datetime # Own Imports from src import settings def verification_code() -> str: """Generate verification...
import datetime import time dt = datetime.datetime.now() print(dt) print(dt.day, dt.month, dt.year, dt.hour, dt.minute, dt.second) ds = datetime.datetime.fromtimestamp(time.time()) print(ds) td = datetime.timedelta(days=11, hours=5, minutes=12, seconds=8) print(td) ma = st.strftime('%Y/%m/%d %H:%M:%S %p') print(ma...