content
stringlengths
5
1.05M
import sys import traceback import battlecode as bc #magic numbers unmapped = 60000 impassable = 65000 def pathPlanetMap(currentMap): mapHeight = currentMap.height mapWidth = currentMap.width #game map grows up and right, array grows down and right #so all my maps are upsidedown map = [[unmapped]...
# coding: utf-8 import os, errno import shutil import re import time from enum import Enum import pickle import string from systemtools.location import isFile, getDir, isDir, sortedGlob, decomposePath, tmpDir from systemtools.basics import getRandomStr class TIMESPENT_UNIT(Enum): DAYS = 1 HOURS = 2 MINU...
# -*- coding: utf-8 -*- from dataviva import db, lm from dataviva.apps.general.views import get_locale from dataviva.apps.user.models import User from dataviva.utils.encode import sha512 from dataviva.utils.send_mail import send_mail from datetime import datetime from dataviva.translations.dictionary import dictionary ...
#!/usr/bin/python ################################################################################ # retrieveKEGG # Access the KEGG API and retrieves all data available for each protein-coding # gene of the "n" organisms specified. Creates a file for each succesful query. # Ivan Domenzain. Last edited: 2018-04-10 ####...
from django.db import models from django.contrib.auth.models import User class Profile(models.Model): image = models.ImageField(upload_to='images/', default='images/default.jpg') bio = models.TextField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Image(models.Model): image = mode...
import re input = open('d15.in').read() lines = filter(None, input.split('\n')) regex = r'^(\w+): capacity ([-\d]+), durability ([-\d]+), flavor ([-\d]+), texture ([-\d]+), calories ([-\d]+)$' ingredients = [] capacities = [] durabilities = [] flavors = [] textures = [] calorieses = [] for i, line in enumerate(line...
import uuid from django.db import models from django_countries import fields # Annex F - Company Data Service # SQL data model class Company(models.Model): company_id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, ) name = models.TextField(db_index=True, default=None, unique=True, e...
from django.shortcuts import reverse from rest_framework.test import APITestCase from model_bakery import baker from glitchtip import test_utils # pylint: disable=unused-import class OrgTeamTestCase(APITestCase): """ Tests nested under /organizations/ """ def setUp(self): self.user = baker.make("use...
# Copyright (C) 2020-2021 by TeamSpeedo@Github, < https://github.com/TeamSpeedo >. # # This file is part of < https://github.com/TeamSpeedo/FridayUserBot > project, # and is released under the "GNU v3.0 License Agreement". # Please see < https://github.com/TeamSpeedo/blob/master/LICENSE > # # All rights reserved. impo...
ENGLISH_HELLO_PREFIX = "Hello" def hello(name: str = None) -> str: """Return a personalized greeting. Defaulting to `Hello, World` if no name and language are passed. """ if not name: name = "World" return f"{ENGLISH_HELLO_PREFIX}, {name}" print(hello("world"))
from webdiff import argparser import tempfile import os from nose.tools import * _, file1 = tempfile.mkstemp() _, file2 = tempfile.mkstemp() dir1 = tempfile.mkdtemp() dir2 = tempfile.mkdtemp() def test_file_dir_pairs(): eq_({'files': (file1, file2)}, argparser.parse([file1, file2])) eq_({'dirs': (dir1, dir2)...
import open3d as o3d import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler, StandardScaler, MaxAbsScaler import os import h5py import random def o3d_to_numpy(o3d_cloud): """ Converts open3d pointcloud to numpy array """ np_cloud_points = ...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_layer_widget.ui' # # Created by: PyQt5 UI code generator 5.7 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Layer(object): def setupUi(self, Layer): Layer.setObje...
from .type import Type, Base, JSONable, AbstractJSONable from .functions import to_json __version__ = "0.2.1"
#!/usr/bin/env python # The MIT License (MIT) # # Copyright (c) 2015 by Brian Horn, [email protected]. # # 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 w...
# # # 0=================================0 # | Kernel Point Convolutions | # 0=================================0 # # # ---------------------------------------------------------------------------------------------------------------------- # # Segmentation model # # ------------------------------...
import glob import os, sys import pickle import numpy as np from codecs import open as codecs_open import re from collections import Counter, defaultdict UNK_TOKEN = '<unk>' # unknown word PAD_TOKEN = '<pad>' # pad symbol WS_TOKEN = '<ws>' # white space (for character embeddings) RANDOM_SEED = 1234 THIS_DIR = os.p...
from collections import defaultdict from pandas import DataFrame from diagrams.base import * def format_time(data, column_name): data[column_name + "_f"] = (data[column_name] / 1000).round(2) return data def add_highest_scheduling_difference(data): column_names = data.columns.values scheduled_columns = lis...
from .models import User from django.utils.translation import gettext, gettext_lazy as _ from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated passwor...
#!/usr/bin/python # -*- coding: utf-8 -*- __title__ = '' __author__ = 'xuzhao' __email__ = '[email protected]' from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() LOGIN_TYPE = ( ('account', '账户密码'), ('email', '邮箱验证码') ) class UserSerializer(seri...
''' Created on Mar 12, 2019 @author: lhadhazy ''' from sklearn.base import TransformerMixin from sklearn import preprocessing class StandardScaler(TransformerMixin): def fit(self, X, y=None): return self def transform(self, X): scaler = preprocessing.StandardScaler() return scaler.f...
from django.shortcuts import get_object_or_404 from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import invalid_ipn_received from orders.models import Order from django.template.loader import render_to_string from django.core.mail import EmailMessage from django.conf import settings im...
""" """ import time import numpy as np import matplotlib.pyplot as plt import os os.chdir("/Users/wham/Dropbox/_code/python/vessel_segmentation") import vessel_sim_commands as vsm import tree_processing as tp import sklearn.decomposition as decomp data_objects = [] data_cols = [] counter = 0 num_samples = 5 nu...
"""Test for the testing module""" # Authors: Guillaume Lemaitre <[email protected]> # Christos Aridas # License: MIT from pytest import raises from imblearn.base import SamplerMixin from imblearn.utils.testing import all_estimators from imblearn.utils.testing import warns def test_all_estimators(): ...
""" Constants ~~~~~~~~~ Constants and translations used in WoT replay files and the API. """ MAP_EN_NAME_BY_ID = { "01_karelia": "Karelia", "02_malinovka": "Malinovka", "04_himmelsdorf": "Himmelsdorf", "05_prohorovka": "Prokhorovka", "07_lakeville": "Lakeville", "06_ensk": "Ensk", ...
# coding: utf-8 """ DedupeApi.py Copyright 2016 SmartBear Software 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...
# _*_ coding:utf-8 _*_ import xadmin from .models import Courses # from teacheres.models import Teacheres # class TeachersChoice(object): # model = Teacheres # extra = 0 #课程 class CoursesAdmin(object): list_display = ['name', 'coursesAbstract', 'teacherid'] search_fields = ['name'] list_filter =...
from setuptools import setup, find_packages import selfea VERSION = selfea.__version__ # with open("README.rst", "r") as fh: # long_description = fh.read() # setup( # name="selfea", # version=VERSION, # author="Jay Kim", # description="Lazy computation directed acyclic graph builder", # long_description=...
import argparse import requests import json from lxml import html import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def get_average_price(url): url_without_sort = url.replace('&_sop=15', '') url_completed_listings = url_without_sort + \ '&LH_Sold=1&LH_Complete=1&_sop=1...
# Copyright 2021 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, ...
from django.shortcuts import render from django.utils import timezone from django.views.generic.detail import DetailView from django.views.generic.list import ListView from .models import Announcement from contestsuite.settings import CACHE_TIMEOUT # Create your views here. class AnnouncementListView(ListView): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 27 21:50:08 2019 @Description : Mostly about lists @author: manish """ primes = [2, 3, 5, 7] hands = [ ['J', 'Q', 'K'], ['2', '2', '2'], ['6', 'A', 'K'], # (Comma after the last element is optional) ] print(len(hands)) print(primes,h...
graph = dict() graph['A'] = ['B', 'C'] graph['B'] = ['E','C', 'A'] graph['C'] = ['A', 'B', 'E','F'] graph['E'] = ['B', 'C'] graph['F'] = ['C'] matrix_elements = sorted(graph.keys()) cols = rows = len(matrix_elements) adjacency_matrix = [[0 for x in range(rows)] for y in range(cols)] edges_list = [] for ke...
#!/bin/python3 import math import os import random import re import sys def binary_search(left, right, n): print(left, right, n) if left == right: return left, False mid = (left+right)//2 middle = scores[mid] if middle == n: return mid, True elif middle > n: ...
#!/usr/bin/env python # Use Python 3 # Install dependencies: pip install tensorflow flask # Run server: python nsfw_server.py # Open in browser: http://localhost:8082/classify?image_path=/home/user/image.jpg import sys import argparse import tensorflow as tf from model import OpenNsfwModel,...
from setuptools import setup, find_packages install_requires = ["python-socketio==4.4.0", "Flask==1.1.1"] setup( name="pytest-visualizer", use_scm_version={"write_to": "src/visual/_version.py"}, long_description=open('README.md').read(), license="MIT", setup_requires=["setuptools_scm"], packag...
import sys, random assert sys.version_info >= (3,7), "This script requires at least Python 3.7" xfactor = random.randint(1,10) yfactor = -1 count = 0 while xfactor != yfactor: count= count+1 yfactor = input("what is the number?") yfactor = int(yfactor) if xfactor == yfactor: print("congrats")...
from typing import Tuple, Optional, Type class VSM: init_args: Tuple = () def __init__(self): self.states = [] self.current_state: 'Optional[VSM]' = None self.help_text = "" def enter(self, parent_state: 'VSM'): pass @staticmethod def _init_state(state: 'Type[VSM...
import unittest import pandas as pd import numpy as np import collections as col import copy import parser import rule_set as rs from relation import * from connection import * class TestparserMethods(unittest.TestCase): def test_parse_interval(self): #good examples inter1 = "(0.8,4.2)" #neither...
# constans CHARS = '\ !%"#&\'()*+,-./0123456789:;?AÁẢÀÃẠÂẤẨẦẪẬĂẮẲẰẴẶBCDĐEÉẺÈẼẸÊẾỂỀỄỆFGHIÍỈÌĨỊJKLMNOÓỎÒÕỌÔỐỔỒỖỘƠỚỞỜỠỢPQRSTUÚỦÙŨỤƯỨỬỪỮỰVWXYÝỶỲỸỴZaáảàãạâấẩầẫậăắẳằẵặbcdđeéẻèẽẹêếểềễệfghiíỉìĩịjklmnoóỏòõọôốổồỗộơớởờỡợpqrstuúủùũụưứửừữựvwxyýỷỳỹỵz' # noqa CHARS_ = [char for char in CHARS] PIXEL_INDEX = 127 NO_GEN_IMAGES = 2**5 ...
#!/usr/bin/python '''! Program to compute the odds for the game of Baccarat. @author <a href="email:[email protected]">George L Fulk</a> ''' def bacc_value(num1, num2): '''! Compute the baccarat value with 2 inputed integer rank values (0..12). ''' if num1 > 9: num1 = 0 if num2 > 9: ...
import ctypes import pytest c_lib = ctypes.CDLL('../solutions/0344-reverse-string/reverse-string.so') @pytest.mark.parametrize('string, ans', [(b"Hello World", b"dlroW olleH"), (b"Hannah", b"hannaH")]) def test_reverse_string(string, ans): c_lib.reverseString(strin...
from datetime import datetime from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, redirect from django.template.loader import render_to_string from .forms import jsForm, FCMForm, FCMCONCEPTForm, FiltersForm, SortMapsForm, FCMEDGEForm from .models import FCM fro...
# -*- coding: utf-8 -*- """ Created on Wed Jan 19 02:20:34 2022 @author: maout """ import torch import numpy as np from matplotlib import pyplot as plt from DeterministicParticleFlowControl import torched_DPFC #import DeterministicParticleFlowControl as dpfc from utils.utils_pytorch import set_device ###Limit cycle f...
import re from fastest.utils import count_truthy def used_as_int(statement, variable): """ example: used_as_int("a = 4", "a") -> 1 # example: used_as_int("a + 4", "a") -> 1 # example: used_as_int("a * 4", "a") -> 1 # example: used_as_int("a - 4", "a") -> 1 # :param statement: :param variab...
from typing import Optional, List from ..options import Options from ..validation_rule import ValidationRule from .content import Content from ....utils.serializer import serialized ValidationRules = List[ValidationRule] class Checkbox(Content): def __init__( self, content_id: str, ...
import os import sys sys.path.insert(0, os.path.abspath("../src/investporto")) # -- Project information ----------------------------------------------------- import investporto project = "investporto" copyright = "2020, Sebastian Fischer" author = "Sebastian Fischer" version = investporto.__version__.split(".")[0]...
#=========================================================================== # # Copyright (c) 2014, California Institute of Technology. # U.S. Government Sponsorship under NASA Contract NAS7-03001 is # acknowledged. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modific...
"""Titan orbital module.""" from datetime import datetime as dt import numpy as np # Constantes UA = 149597870.7 # 1 Astronomical unit (km) # Default orbital parameters ORBIT = { 'saturn_orbit': 15.945, # 1 Saturn orbit (days) 'sun_orbit': 10751, # 1 Sun orbit (days) 'obliqu...
import sys from server import main #from . import server if __name__ == '__main__': sys.exit(main())
from django.core.management.base import BaseCommand from products.models import Product class Command(BaseCommand): help = 'Restock all products with the given quantity' def add_arguments(self, parser): parser.add_argument( '-q', '--quantity', type=int, ...
#Convert all the words to lower case #Source https://github.com/saugatapaul1010/Amazon-Fine-Food-Reviews-Analysis import re def lower_case(x): x = str(x).lower() x = x.replace(",000,000", " m").replace(",000", " k").replace("′", "'").replace("’", "'")\ .replace("won't", " will not").r...
from ._generic import SitemapScraper class BBCFoodScraper(SitemapScraper): """ A scraper for bbc.co.uk/food """ NAME = "bbcfood" RECIPE_URL_FORMAT = "https://www.bbc.co.uk/food/recipes/{id}/" RECIPE_URL_RE = r"https://www.bbc.co.uk/food/recipes/(?P<id>[^/]+)/?$" SITEMAP_URL = "https://ww...
import math import os import random import re import sys from collections import Counter #Complete the reverseShuffleMerge function below. def reverseShuffleMerge (s): s = list (reversed (s)) remaining_dict, required_dict, added_dict = { } , { } , { } for c in s: if c ...
from PyQt4.Qt import QApplication class DummyLauncher: def __init__(self, parent): self.parent = parent def set_property(self, name, value): pass
import numpy as np import collections import math import json from argparse import Namespace from dataclasses import dataclass, field import torch import sacrebleu from fairseq import metrics, utils from fairseq.criterions import FairseqCriterion, register_criterion from fairseq.dataclass import FairseqDataclass from...
import torch from torch import nn from torch.nn import functional as F class ContrastiveEmbeddingLoss(nn.Module): """ Contrastive embedding loss paper: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf """ def __init__(self, margin=1.0, reduction="mean"): """ Cons...
from __future__ import annotations import logging from typing import TYPE_CHECKING from snecs.typedefs import EntityID from scripts.engine import library, world from scripts.engine.action import Skill, init_action from scripts.engine.component import Aesthetic, Position from scripts.engine.core.constants import Dama...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Copyright 2014, Quixey Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in self.c.mpliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless ...
#7- Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. def float_bin(number, places = 3): whole, dec = str(number).split(".") whole = int(whole) dec = int (dec) res = bin(whole)[2:] + "." ...
''' The windows_files module handles windows filesystem state, file uploads and template generation. ''' from __future__ import unicode_literals import ntpath import os from datetime import timedelta import six from pyinfra import logger from pyinfra.api import ( FileUploadCommand, operation, OperationE...
#! /usr/bin/env python '''Generate a site.attrs file to prepare for an unattended installation of a Stacki Frontend. Usage: stacki_attrs.py list [options] stacki_attrs.py [options] Options: -h --help Display usage. --debug Print various data structures duri...
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import numpy as np import tensorflow as tf from .. import variables as vs from .. import utils from .. import initializations def embedding(incoming, input_dim, output_dim, weights_init='truncated_normal', trainab...
from contract import DappMethodAdmin,DappMethodInfo,Test from privateKey import my_address, private_key from web3.auto import w3 DAPP_ID = 1 ONE_ETHER = 10 ** 18 def getInfo(): count = DappMethodInfo.functions.getStoreMethodCount(DAPP_ID).call() print("当前DAPP的方法数量为:",count) for i in range(count): ...
import requests import json from PXDetector import PXDetector motion_url = 'http://localhost:5000/detect_motion' frame_url = 'http://localhost:5000/get_still' #Detect motion for 30s: payload = {'timeout':30,} r=requests.post(motion_url,json=payload).json() print(r) #Grab still image: r=requests.post(frame_url) #Ret...
from tesi_ao import sandbox, package_data import matplotlib.pyplot as plt import numpy as np def plot_calibration_reproducibility(): ''' mcl.fits, mcl1.fits, mcl2.fits sono 3 misure di calibrazione ripetute in rapida sequenza ''' fname0 = package_data.file_name_mcl('mcl0') fname1 = package_data.f...
"""Module for custom callbacks, especially visualization(UMAP).""" import logging import pathlib from typing import Any, Dict, List, Optional, Union import anndata import numpy as np import scanpy as sc import tensorflow as tf from scipy import sparse as scsparse from tensorflow import config as tfconfig from tensorfl...
''' The worst rouge like in existance By: Owen Wattenmaker, Max Lambek background taken from: http://legend-tony980.deviantart.com/art/Alternate-Kingdom-W1-Castle-Background-382965761 character model taken from: http://piq.codeus.net/picture/33378/chibi_knight ''' #TODO ########################################...
# -*- coding: utf-8 -*- """ Display a scrollable history list of commands. """ from typing import List, Callable from PyQt5.QtWidgets import QBoxLayout, QListWidget, QListWidgetItem, QLabel from py_hanabi.commands.command import Command __author__ = "Jakrin Juangbhanich" __email__ = "[email protected]" clas...
print("data structs baby!!") # asdadadadadadad
#!/bin/bash for SUBID in 04 05 06 07 08 09 10 11 12 13 14 do sbatch submission_connectivity.sh $SUBID done
# Copyright 2018 The Oppia 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 applicable ...
from podium_api.account import make_account_get from podium_api.events import ( make_events_get, make_event_create, make_event_get, make_event_delete, make_event_update ) from podium_api.devices import ( make_device_get, make_device_create, make_device_update, make_device_delete, make_devices...
#!/usr/bin/env python try: # <= python 2.5 import simplejson as json except ImportError: # >= python 2.6 import json versions = ['2.0.0','2.0.1', '2.0.2', '2.1.0', '2.1.1', '2.3.0', 'latest'] for v in versions: print '-- testing %s/reference.json' % v reference = json.load(open('%s/reference....
import unittest import faker from aiohttp.test_utils import unittest_run_loop from ..test_case import AuthenticatedClericusTestCase fake = faker.Faker() class LoginTestCase(AuthenticatedClericusTestCase): @unittest_run_loop async def testLogin(self): resp = await self.client.request("GET", "/me/") ...
#!/usr/bin/env python from math import ceil import numpy as np from opensoundscape.spectrogram import Spectrogram import torch from torchvision import transforms def split_audio(audio_obj, seg_duration=5, seg_overlap=1): duration = audio_obj.duration() times = np.arange(0.0, duration, duration / audio_obj.sam...
from .api import * from .db import * from .utils import * from .domain import *
from sidmpy.CrossSections.cross_section import InteractionCrossSection class VelocityIndependentCrossSection(InteractionCrossSection): def __init__(self, norm): """ This class implements a velocity-independent cross section with a constant value specified by norm :param norm: the cross se...
import os import errno from io import BytesIO import time from flask import abort, current_app, jsonify, request, url_for from flask.views import MethodView from werkzeug.exceptions import NotFound, Forbidden from werkzeug.urls import url_quote from ..constants import COMPLETE, FILENAME, SIZE from ..utils.date_funcs ...
import re def check_domain(url): return re.search('(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9][/]', url).group(0)
# -*- coding: UTF-8 -*- from django.contrib import admin from .models import Article, Category, Tag, BlogComment from pagedown.widgets import AdminPagedownWidget from django import forms # from DjangoUeditor.forms import UEditorField class ArticleForm(forms.ModelForm): body = forms.CharField(widget=AdminPagedown...
from pprint import pprint import asyncio from panoramisk import Manager async def extension_status(): manager = Manager(loop=asyncio.get_event_loop(), host='127.0.0.1', port=5038, username='username', secret='mysecret') await manager.connect() action = { ...
import json, os from os.path import relpath class JSONOutput: def __init__(self, machine): self.machine = machine self.settings = machine.settings self.logger = self.settings['logger'] def export(self): img_obj = self.load_machine_image() # add machine properties to...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: fzk # @Time 10:59 import json from flask import request, render_template, flash from app.web.blueprint import web from app.forms.book import SearchForm from app.kernel.param_deal import FishBook from app.view_models.book import BookViewModel @web.route('/book/sea...
import ply.yacc as yacc import sys from Utils.Cool.ast import * from Sintax.lexer import create_lexer #-------------------------Parser----------------------------------# class CoolParsX(object): def __init__(self): self.tokens = None self.lexer = None self.parser = None self.error_...
import databases import sqlalchemy from fastapi import FastAPI from ormar import Integer, Model, ModelMeta, String from pytest import fixture from fastapi_pagination import LimitOffsetPage, Page, add_pagination from fastapi_pagination.ext.ormar import paginate from ..base import BasePaginationTestCase from ..utils im...
from tempfile import NamedTemporaryFile import consts import pytest from assisted_service_client.rest import ApiException from tests.base_test import BaseTest, random_name class TestGeneral(BaseTest): def test_create_cluster(self, api_client, cluster): c = cluster() assert c.id in map(lambda clu...
def to_html(bibs): return 'Hello'
import sys def sol(): input = sys.stdin.readline N = int(input()) k = int(input()) left = 1 right = k ans = 0 while left <= right: mid = (left + right) // 2 cnt = 0 for i in range(1, N + 1): cnt += min(mid // i, N) if cnt >= k: right ...
from django.contrib import admin from .models import (AgentTemplate, SecurityPolicyTemplate, Service, SecurityPolicy, Customer, Log, Agent, Algorithm, AlgorithmTemplate) # class SecurityPolicyInline(admin.TabularInline): # model = SecurityPolicy # extra = 3 # # class S...
import random from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from .models import CaseStudy # Create your views here. def index_view(request): """ Render index page with case study as success story """ template_name = "main.html" ...
import os import unittest import numpy as np from numpy.testing import assert_allclose from gnes.encoder.base import PipelineEncoder from gnes.encoder.numeric.pca import PCALocalEncoder from gnes.encoder.numeric.pq import PQEncoder from gnes.encoder.numeric.tf_pq import TFPQEncoder class TestPCA(unittest.TestCase):...
segment_to_number = { "abcefg": "0", "cf": "1", "acdeg": "2", "acdfg": "3", "bcdf": "4", "abdfg": "5", "abdefg": "6", "acf": "7", "abcdefg": "8", "abcdfg": "9", } def decode(key, code): one = tuple(k for k in key if len(k) == 2)[0] four = tuple(k for k in key if len(k) ...
import time def prune(args, model, sess, dataset): print('|========= START PRUNING =========|') t_start = time.time() batch = dataset.get_next_batch('train', args.batch_size) feed_dict = {} feed_dict.update({model.inputs[key]: batch[key] for key in ['input', 'label']}) feed_dict.update({model....
from typing import Dict from requests.models import Response from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import BackendApplicationClient from previsionio.utils import NpEncoder import json import time import requests from . import logger from . import config from .utils import handle_error_response...
import warnings from scraps.fitsS21 import hanger_resonator warnings.warn( DeprecationWarning( "This module has been deprecated in favor of scraps.fitsS21.hanger_resonator" ) ) def cmplxIQ_fit(paramsVec, res, residual=True, **kwargs): """Return complex S21 resonance model or, if data is specifie...
import time import asyncio joined = 0 messages = 0 async def update_stats(): await client.wait_until_ready() global messages, joined client.loop.create_task(update_stats()) @client.event async def on_message(message): global messages # ADD TO TOP OF THIS FUNCTION messages += 1 # ADD...
import os import pytest from brownie import * from integration_tests.utils import * from src.rebaser import Rebaser from src.utils import get_healthy_node os.environ["DISCORD_WEBHOOK_URL"] = os.getenv("TEST_DISCORD_WEBHOOK_URL") os.environ["ETH_USD_CHAINLINK"] = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" os.enviro...
import httplib, sys import myparser class search_google_labs: def __init__(self,list): self.results="" self.totalresults="" self.server="labs.google.com" self.hostname="labs.google.com" self.userAgent="(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6" id=0 self.set=""...
default_app_config = 'task.apps.TaskConfig'