content
stringlengths
5
1.05M
import tempfile import asyncio import typing import time from statistics import mean from mitmproxy import ctx from mitmproxy.io import db from mitmproxy.test import tflow class StreamTester: """ Generates a constant stream of flows and measure protobuf dumping throughput. """ def __init__(sel...
""" Week 1, Day 3, Lab 3 Maria Liu """ #3.1 str_list = ['a', 'd', 'e', 'b', 'c'] print(str_list) str_list.sort() #sorts it alphabetically print(str_list) #3.2 str_list.append('f') #adds 'f' to str_list print(str_list) #3.3 str_list.remove('d') #removes 'd' from str_list print(str_list) #3.4 print(str_list...
import sys from datetime import datetime from bs4 import BeautifulSoup import requests from tabulate import tabulate from dataclasses import astuple, dataclass STAR_COST_TABLE = { 'Master Agent': 25, 'Superior Agent': 10, 'Exceptional Agent': 7, 'Distinguished Agent': 5 } @dataclass class CSGOStashIte...
"""Plotting functions for AnnData. """ import os import numpy as np import pandas as pd from pandas.api.types import is_categorical_dtype from matplotlib import pyplot as pl from matplotlib import rcParams from matplotlib.colors import is_color_like import seaborn as sns from .. import settings from .. import logging...
# regressionLine.pyw # Program graphically plots a regressions line after a user has put in all # points via mouse clicks. """Redo the regression problem from Chapter 8 (Programming Exercise 13) using a Regression class. Your new class will beep track of the various quantities that are needed to compute a line of regr...
# -*- coding: utf-8 -*- from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import unittest from asciimatics.parsers import AsciimaticsParser, AnsiTerminalParser, ControlCodeParser, Parser import asciimatics.constants as co...
#!/usr/bin/env python import os import sys import platform curwd = os.path.dirname(__file__) root = os.path.normpath(os.path.join(curwd, os.pardir)) build = os.path.join(os.path.abspath(root), 'build') gyplib = os.path.join(root, 'tools', 'gyp', 'pylib') sys.path.insert(0, gyplib) import gyp def run_gyp(args): r...
from kloppy.infra.serializers.tracking.metrica_epts.models import Sensor import logging from typing import Tuple, Dict, List from dataclasses import replace from kloppy.domain import ( TrackingDataset, Frame, Point, Point3D, Transformer, build_coordinate_system, Provider, PlayerData, ) ...
""" Test-only Django settings for the dh@mit computational history project. DO NOT run with this file in production """ from .settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'localhost', 'PORT': '5432', 'NAME': ...
""" Detect arrow key for speaker keys and raise similar events """ import atexit import logging import os import select import sys import threading import time import sys, select, tty, termios from event import EventEnum, Event, EVENT_KEY_UP, EVENT_KEY_DOWN, EVENT_KEY_LEFT, EVENT_KEY_RIGHT, EVENT_KEY_Q import ctypes ...
# coding=utf-8 import types import node_clean import node_locate class NodeUpdate(node_locate.NodeLocate): ''' #节点修改: 修改ndb中的数据 #查询条件使用ndb路径查询, 并更新查询路径上的数据 ''' def __init__(self): self.update_value = None def update(self, node, path, value, action): if type(value) == ...
""" Utilities functions """ import joblib import os import errno import numpy as np import pandas as pd import logging import types from copy import deepcopy logger = logging.getLogger(name=__name__) # Handling Doc-string inheritance def fix_docs(cls): """ This will copy missing documentation from parent c...
# -*- coding: utf-8 -*- """ 模型结构插件 """ from . import torch from . import tensorflow
def f1(a, c): print(a) print(c) f1(1, 3)
SURVEY_MANAGING_GET = { 'tags': ['설문지 관리'], 'description': '설문지 리스트 불러오기', 'parameters': [ { 'name': 'Authorization', 'description': 'JWT Token', 'in': 'header', 'type': 'str', 'required': True } ], 'responses': { '2...
from django.dispatch import Signal pre_download = Signal(providing_args=["instance", "field_name", "request"])
# import torch # import torch.nn as nn # import torch.nn.functional as F # import torchvision.transforms as transforms # import torchvision # from torch.autograd import Variable from PIL import Image # from tensorflow import keras from keras_segmentation.pretrained import pspnet_101_voc12 from pytorch_fid.inception i...
from . import * from .room import Room from .files import Files from .plugin_instance import AsyncPluginInstance, PluginInstance, _DefaultPlugin from .plugin import Plugin from . import streams from . import ui from . import structure from . import shapes from . import macro from . import user
from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.utils.sample_test import sample_user, sample_super_group, \ sample_category PRODUCT_CREATE_URL = reverse('product:product-create') class PublicProductCreateApiT...
import re import string from typing import Optional from core.utils import load_json_resource, ILogger, StringUtils class BaseOracle(object): def __init__(self, entity: str, resource_id: str, thorough: bool, logger: ILogger, name_character_set: str): self.__entity = entity self.__thorough = thoro...
from .linear_regression import LinearRegression
""" author: Gonzalo date started: 06/11/18 This script generates a table of correlations for the selected features. """ import pandas as pd import numpy as np def feature_correlation(wave): cols = ['type', 'tenure', 'beds', 'rooms', 'size'] df = pd.read_csv(wave + '_hhresp.tab', sep = '\t') feature_df...
import torch import configparser import numpy as np from utils.mysqlTools import MySqlHold conf = configparser.ConfigParser() conf.read('config/config.cfg') mysql = MySqlHold(host=conf.get('mysql', 'host'), user=conf.get('mysql', 'user'), password=conf.get('mysql', 'pass...
# # Autogenerated by Thrift Compiler (0.11.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException from thrift.TRecursive impo...
import pytest from eight_bit_computer.operations import copy_op from eight_bit_computer.data_structures import get_machine_code_byte_template from eight_bit_computer.exceptions import OperationParsingError def generate_parse_line_test_data(): ret = [] test_input = "" expected = [] ret.append((test_i...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Written by feymanpriv import init_path import sys, os import numpy as np import cv2 import pickle from scipy.io impo...
from .navigation import * from .pretty_help import * __version__ = "1.2.1"
# vim:ts=4:sts=4:sw=4:expandtab import logging from satori.core.models import PrivilegeTimes PageInfo = Struct('PageInfo', [ ('contest', DjangoStruct('Contest'), False), ('contestant', DjangoStruct('Contestant'), False), ('role', DjangoStruct('Role'), False), ('user', DjangoStruct('User'), False), ...
import os import cv2 import sys import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt from torch.utils.data import DataLoader, Dataset, TensorDataset from torch import optim from torch import Tensor from torchvision import transforms from u_net_model impor...
# Copyright 2017,2018,2019,2020,2021 Sony Corporation. # Copyright 2021 Sony Group 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-...
import pytest from aleph.services.utils import ( is_valid_ip4, get_ip4_from_service, get_ip4_from_socket, get_IP, ) def test_is_valid_ip4(): assert is_valid_ip4("1.2.3.4") assert is_valid_ip4("123.456.789.123") assert not is_valid_ip4("") assert not is_valid_ip4("Hello !") assert ...
#!/usr/bin/python import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/home/ubuntu/Sites/php-proxy-app/gpu_attack.github.io/CollectData") from CollectData import app as application application.secret_key = 'Add your secret key'
from pathlib import Path from qtpy import QtCore from qtpy import QtWidgets class ExtractFrameDialog(QtWidgets.QDialog): def __init__(self, video_file=None, *args, **kwargs): super(ExtractFrameDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Extract Frames from a video") self.r...
# Copyright 2018 The TensorFlow Probability Authors. # # 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...
# Copyright 2010 OpenStack Foundation # 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 requ...
# coding: utf-8 from unittest import main, TestCase from django.template import Context from django.template.loader import render_to_string, get_template_from_string from mock import patch, MagicMock from static_precompiler.compilers.coffeescript import CoffeeScript from static_precompiler.exceptions import StaticCompi...
import sqlite3 from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, open_sqlite_db_readonly def get_installedappsGass(files_found, report_folder, seeker, wrap_text): for file_found in files_found: file_found = str(file_found) if file_found.endswith('.d...
"""Matplotlib mcseplot.""" import matplotlib.pyplot as plt import numpy as np from scipy.stats import rankdata from . import backend_show from ....stats.stats_utils import quantile as _quantile from ...plot_utils import ( make_label, _create_axes_grid, ) def plot_mcse( ax, plotters, length_plotte...
"""SDO Map subclass definitions""" #pylint: disable=W0221,W0222,E1101,E1121 __author__ = "Keith Hughitt" __email__ = "keith.hughitt@nasa.gov" from sunpy.map import Map from sunpy.cm import cm from matplotlib import colors import numpy as np class AIAMap(Map): """AIA Image Map definition References -...
import torch from torch import nn # 搭建神经网络 class Tudui(nn.Module): def __init__(self): super(Tudui, self).__init__() self.model = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=1, padding=2), nn.MaxPool2d(kernel_size=2), nn.Conv2d...
# Copyright 2021 The Flax Authors. # # 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 wri...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from unittest import mock import numpy as np import pandas as pd from ax.core.arm import Arm from ax.core.data import Data from ax.core.experiment import Experiment from ax.core.metric import Metric from ax.core.objective i...
from setuptools import setup, find_packages setup( name="hgdb", packages=find_packages(), package_data={ 'backup': ['static/*', 'static/*/*', 'static/*/*/*'] } )
import obspython as S class Example: def crete_text_source(self): current_scene = S.obs_frontend_get_current_scene() scene = S.obs_scene_from_source(current_scene) settings = S.obs_data_create() S.obs_data_set_string( settings, "text", "The quick brown fox ju...
#!/usr/bin/python # -*- coding: utf-8 -*- import pandas as pd import os.path as osp import numpy as np import re from bs4 import BeautifulSoup as bs from nltk.tokenize import word_tokenize, sent_tokenize from nltk import FreqDist import cPickle as pkl def combine(train_dict, test_dict): """Combine a list of csv fi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals try: from collections import Counter except ImportError: from backport_collections import Counter import datetime from operator import attrgetter from django.db import models from django.utils.timezone import now from aldryn_app...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals import pytest from six.moves import zip from efc.rpn_builder.lexer import Lexer from efc.rpn_builder.parser import operands, operations, Parser @pytest.fixture(scope='module') def parse(): lexer = Lexer() ...
from ._version import version __version__ = version class PhotoManagerBaseException(Exception): pass class PhotoManagerException(PhotoManagerBaseException): pass
from .tailer import Tailer __VERSION__ = '0.4.8' __DATE__ = '2021-02-01'
# Generated by Django 2.2.1 on 2019-05-27 04:14 import ckeditor_uploader.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('post', '0002_post_text'), ] operations = [ migrations.AlterField( model_name='post', name='t...
# Generated by Django 3.2.3 on 2021-05-24 10:38 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
num = (int(input('Digite um valor: ')), int(input('Digite outro valor: ')), int(input('Digite outro valor: ')), int(input('Digite outro valor: '))) print('O número 9 apareceu {} vezes'.format(num.count(9))) if 3 in num: print('O valor 3 apareceu na posição {}'.format(num.index(3) + 1)) else: ...
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: steammessages_clientserver_userstats.proto # plugin: python-betterproto # Last updated 09/09/2021 from dataclasses import dataclass from typing import List import betterproto @dataclass(eq=False, repr=False) class CMsgClientGetUserStats(betterpro...
import sys from typing import List, Optional from PySide2.QtGui import QColor from Engine.EngineManga.manga import Volume, Manga, Chapter from core import Core from PySide2.QtWidgets import * from gui.myWindow import Ui_MainWindow # import engines: better create a proper core class and deal with it outside from Eng...
class Link: empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest def __repr__(self): if self.rest: rest_str = ", " + repr(self.rest) else: rest_str = "" ...
# -*- coding: utf-8 -*- from input_definition import InputDefinition class Input(object): interactive = True def __init__(self, definition=None): if definition is None: self.arguments = {} self.options = {} self.definition = InputDefinition() else: ...
import csv import cv2 import sys import numpy as np # loads image from filepath using opencv def get_image(basepath, filepath): # read in images from center, left and right cameras source_path = filepath # extract filename from filepath using split and check platform if sys.platform == 'win32': ...
from django.contrib import admin # Register your models here. # Importamos cada unas de las clases creadas en el archivo models.py from .models import Etnia from .models import tipoDoc from .models import EstaCivil from .models import TipoEstu from .models import TipoLogr admin.site.register(Etnia) admin.site.registe...
""" .. module:: django_core_utils.tests.test_fields :synopsis: django_core_utils fields unit test module. *django_core_utils* fields unit test module. """ from __future__ import absolute_import, print_function from inspect import getargspec, getmembers, isfunction from django.core.exceptions import ValidationEr...
import time from threading import Thread from queue import Queue from collections import deque # ========= # Constants # ========= # Directions UP = 1 DOWN = -1 NONE = 0 # Priorities INSIDE = 1 OUTSIDE = 0 # ========== # Exceptions # ========== class WrongActionError(Exception): """ Исключение, поднимающее...
from os import getenv from os.path import abspath, dirname basedir = abspath(dirname(__file__)) class Config(object): SECRET_KEY = getenv('SECRET_KEY') or 'secret_key' MONGODB_DB = getenv('MONGODB_DB') or 'Cerebro' MONGODB_HOST = getenv('MONGODB_HOST') or 'localhost' MONGODB_PORT = getenv('MONGODB_P...
from flask import current_app from flask_login import current_user from app.api.services import (audit_service, audit_types, team_member_service, team_service, users) from .util import escape_markdown, render_email_template, send_or_handle_error def send_removed_team_member_notificatio...
from ..factory import Type class messageChatDeletePhoto(Type): pass
# http://pythontesting.net/framework/unittest/unittest-introduction/ import unittest from unnecessary_math import multiply class TestUM(unittest.TestCase): def setUp(self): pass def test_numbers_3_4(self): self.assertEqual( multiply(3,4), 12) def test_strings_a_3(self): sel...
import mmcv import numpy as np from pycocotools.coco import COCO from evaluate import compute_JI, compute_APMR import json from utils import misc_utils anno_path = './data/crowdhuman/annotations/annotation_val.json' pred_path = './work_dirs/results.pkl' anno_data = COCO(anno_path) pred_data = mmcv.load(pred_path) im...
""" Helpers to run things on multiple repos and collect errors """ import abc import sys from typing import Any, Generic, List, Tuple, TypeVar # noqa import cli_ui as ui import tsrc T = TypeVar('T') class ExecutorFailed(tsrc.Error): pass class Task(Generic[T], metaclass=abc.ABCMeta): def on_start(self...
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Conv1D, Dense import rinokeras as rk from rinokeras.layers import PaddedConv, Stack from .layers import BidirectionalCudnnLSTM class NetsurfModel(Model): def __init__(self, input_name: str = 'encoder_output'): ...
from DataStructures.PrimeCurves import NistPrimeCurve from ECDSA.Message import FormatMessage from util import inv from FastArithmetic.joint_multiplication import FastJointMultiplier from FastArithmetic.scalar_multiplication import FastScalarMultiplier from random import SystemRandom class GenerateKeyPair: def __...
from .eLABJournalObject import * class Study(eLABJournalObject): def __init__(self, api, data): """ Internal use only: initialize study object """ if ((data is not None) & (type(data) == dict) & ("name" in data) ): super().__init__(api, data, "st...
n = int(input()) strength = list(map(int,input().split())) money=0 for i in range(n-1): for j in range(i+1,n): money+=abs(strength[i]-strength[j]) print(money)
from __future__ import unicode_literals, division, print_function # built in modules import os import sys import time import codecs import shutil import argparse from six.moves import input # project modules from toolbox import countlines, CuiSemTypesDB, SimstringDBWriter, mkdir from constants import HEADERS_MRCONSO,...
TYPE_CHECKING = False class Any: pass class _GetAttr(type): def __getitem__(self, x): return self class Generic(metaclass=_GetAttr): pass class Generator(Generic): pass class Callable(Generic): pass class List(Generic): pass class Optional(Generic): pass class Tuple(Generic): ...
#!/usr/bin/python3 import collections import datetime import os import shlex import time # dictionaries will get better performance... # see: http://stackoverflow.com/questions/2646157/what-is-the-fastest-to-access-struct-like-object-in-python Aggregation = collections.namedtuple( "aggregation", ["aggregatio...
""" Autore : andreabisello at 20/08/2020 testsuite """ import pytest import logging foo = logging.getLogger('foo') bar = logging.getLogger('bar') baz = logging.getLogger('baz') @pytest.yield_fixture(scope='session') def session_thing(): foo.debug('constructing session thing') yield foo.debug('destroyin...
from arjuna.tpi import Arjuna from arjuna.tpi.markup import * from .wp import WPLoginLogout @test_function def test(my): automator = Arjuna.create_gui_automator() WPLoginLogout.login(automator) main_win = automator.MainWindow() main_win.maximize() print(main_win.get_title()) automator.exec...
from django.conf.urls import url from django.views.generic import TemplateView from django.views.decorators.cache import cache_page from .. import views urlpatterns = [ url(r"^$", views.index), url(r"^simple/$", views.BasicView.as_view()), url(r"^users/$", views.UserList.as_view(), name="users-list"), ...
from abc import ABC from code_transformer.experiments.experiment import ex, ExperimentSetup from code_transformer.modeling.constants import NUM_SUB_TOKENS_METHOD_NAME, NUM_SUB_TOKENS from code_transformer.preprocessing.datamanager.preprocessed import CTBufferedDataManager from code_transformer.preprocessing.dataset.ab...
from datetime import datetime, timedelta from flask.sessions import SessionInterface, SessionMixin from werkzeug.datastructures import CallbackDict import sqlalchemy import json import uuid from blog.models import DBSession from sqlalchemy.orm.exc import NoResultFound # http://flask.pocoo.org/snippets/110/ class Sql...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ TODO """ from numpy.random import permutation class MassPrior(object): """ TODO """ def __init__(self, prior): self.prior = prior def sample(self, size=1): #TODO: revisit size return permutation(self.prior) # class Distribution(o...
import torch as ch import numpy as np from lime.lime_text import LimeTextExplainer from tqdm import tqdm from wordcloud import WordCloud import matplotlib import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') import os from collections import defaultdict def make_lime_fn(model...
import game import collections import random import pickle import time import numpy as np class QLearning(game.Game): def __init__(self, cards, strategy="random", player_card_num=2, num_players=3): self.num_players = num_players self.starting_player = 0 self.last_player = 0 self.ga...
#!/usr/bin/env python3 """Exception classes specific to pushdown automata.""" from automata.shared.exceptions import AutomatonError class PDAError(AutomatonError): """The base class for all PDA-related errors.""" pass class NondeterminismError(PDAError): """A DPDA is exhibiting nondeterminism.""" ...
# !/usr/bin/env python # Created by "Thieu" at 16:44, 18/03/2020 ----------% # Email: nguyenthieu2102@gmail.com % # Github: https://github.com/thieu1995 % # --------------------------------------------------% import numpy as np from copy import deepcopy from mealpy.optimizer import Optimi...
""" Error Classes """ class APIError(Exception): """ API Error Base Class """ def __init__(self, description, *args, **kwargs): super(APIError, self).__init__(*args, **kwargs) self.description = description
import math import pymongo from datetime import datetime, timezone, timedelta from bson.objectid import ObjectId class Models(): __tablename__ = None __columns__ = [] def __init__(self, Connection, tableName, columns, unique = None, seed = False): if seed is True: self.connection = Co...
import argparse import os import sys import warnings import fitlog import torch import torch.nn.functional as F from torch import nn, optim from tqdm import tqdm warnings.filterwarnings("ignore") from fastNLP import (AccuracyMetric, BucketSampler, ClassifyFPreRecMetric, ConstantTokenNumSampler, Cr...
import pandas as pd import torchvision.transforms as transforms from PIL import Image from torch.utils.data import Dataset class CIFAR10Dataloader(Dataset): def __init__(self, src_path, sample_paths, class_labels): self.image_transformer = transforms.Compose([transforms.RandomHorizontalFlip(), tr...
from dotenv import load_dotenv from pandas import DataFrame import pandas as pd import numpy as np import tweepy import time import json import csv import os load_dotenv() consumer_key = os.getenv("CONSUMER_KEY") consumer_secret = os.getenv("CONSUMER_SECRET") access_token = os.getenv("ACCESS_TOKEN") access_token_secr...
import os import sys from collections import * from copy import deepcopy from itertools import * # change to dir of script os.chdir(os.path.dirname(os.path.abspath(__file__))) input_file = "input.txt" if "s" in sys.argv: input_file = "input_small.txt" try: with open(input_file) as f: data = f.read() #...
from dnslib import * try: from scapy.all import * except: print "You should install Scapy if you run the server.." app_exfiltrate = None config = None buf = {} def handle_dns_packet(x): global buf try: qname = x.payload.payload.payload.qd.qname if (config['key'] in qname): ...
import torch import torch.nn as nn from torch.nn.parallel import data_parallel from torch.autograd import Variable from torch.nn.functional import log_softmax from seq2seq.tools import batch_sequences from .modules.state import State class Seq2Seq(nn.Module): def __init__(self, encoder=None, decoder=None, bridge...
import json from .dtometa import DTOMeta class DTO(metaclass=DTOMeta): def __new__(cls, *args, **kwargs): obj = super(DTO, cls).__new__(cls) obj._initialized_dto_descriptors = dict() obj._dto_descriptors_values = dict() for attr in obj._dto_descriptors: obj._initialize...
""" Helper functions. """ from random import random, randint from time import sleep import uasyncio as asyncio from lib.constants import UINT_16 from lib.europi import DigitalOut, digital_outputs def random_chance(percentage: float) -> bool: return random() < percentage def randint16() -> int: return ran...
import os import platform import re from Tkinter import * root = Tk() RX_Bytes = 0 TX_Bytes = 0 def update(): global RX_Bytes global TX_Bytes f = os.popen('netstat -e') result = f.readlines() #print result[4] match = re.findall('[0-9]+', result[4]) #print match rx, tx = int(match[0]), int...
import pandas as pd import numpy as np import math from scipy.signal import argrelextrema def score(data): ## Calification rules max_border = 360 # Max threshold for valid point min_border = 0 # Min threshold for valid point base_ang = 180 # Objective angle threshold_ang ...
from django.db import migrations def _forward_func_deduplication_feed_entries(apps, schema_editor): FeedEntry = apps.get_model('api', 'FeedEntry') unique_set = set() delete_list = [] for feed_entry in FeedEntry.objects.all(): unique_desc = (feed_entry.feed_id, feed_entry.url, ...
__author__ = 'Giacomo Tanganelli' __version__ = "3.0"
import torch import torch.nn as nn from torch.autograd import Function from torch.nn import functional as F def quantization(x, k): n = 2 ** k - 1 return RoundFunction.apply(x, n) def normalization_on_weights(x): x = torch.tanh(x) x = x / torch.max(torch.abs(x)) * 0.5 + 0.5 return ...
# Copyright 2020 Samsung Electronics Co., Ltd. # # 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...
""" 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 distri...