content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """Tests for `wcmatch`.""" import unittest import os import wcmatch.wcmatch as wcmatch import shutil from wcmatch import _wcparse # Below is general helper stuff that Python uses in `unittests`. As these # not meant for users, and could change without notice, include them # ourselves so we ar...
import pytest from mock import Mock from sigopt.orchestrate.job_runner.service import JobRunnerService from sigopt.orchestrate.resource.service import ResourceService class TestJobRunnerService(object): @pytest.fixture def services(self): services = Mock( sigopt_service=Mock(api_token="sigopt_api_token...
#!/usr/bin/env python3 # Author: Tyson Andre import re import sys # assumes file names don't have spaces. # Could rewrite all of this to use JSON. REDEFINE_REGEX=re.compile(r'^\S+:\d+ PhanRedefine\w+ .*defined at (\S*):\d+.*at (\S+):\d+$') assert(REDEFINE_REGEX.match(r'aaXX/fy.php:571 PhanRedefineFunction Function err...
#! /usr/bin/env python3 import os, subprocess, sys sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))) import script.common as common import script.revision as revision def main(): common.pushd(os.path.join(os.path.dirname(__file__), os.pardir)) rev = revision.revision() print...
from distconfig.backends.base import BaseBackend from distconfig.backends.execution_context import ThreadingExecutionContext class ConsulBackend(BaseBackend): """Consul backend implementation. :param client: Instance of :class:`consul.Consul`. :param execution_context: Instance of :class:`distconfig.back...
x = int(input()) if x < 1434.59: print("isento") elif x >= 1434.60 and x <= 2150: print(7.8) elif x >= 2150.01 and x <= 2866.7: print(15.0) elif x >= 2866.71 and x <= 3582: print(22.5) else: print(27.5)
class Solution: def merge(self, lhs, rhs): r_value = [] while lhs and rhs: if lhs[0] < rhs[0]: r_value.append(lhs[0]) del lhs[0] else: r_value.append(rhs[0]) del rhs[0] if lhs: r_...
from layers.dynamic_rnn import DynamicLSTM from layers.squeeze_embedding import SqueezeEmbedding from layers.attention import Attention, NoQueryAttention from layers.point_wise_feed_forward import PositionwiseFeedForward import torch import torch.nn as nn import torch.nn.functional as F # CrossEntropyLoss for Label Sm...
from tuw_nlp.text.pipeline import CustomStanzaPipeline def test_stanza_pipeline(): nlp = CustomStanzaPipeline(processors='tokenize,pos,lemma,depparse') doc = nlp('Dachgeschosse sind nicht zulässig.') assert 'head' in doc.sentences[0].to_dict()[0]
import requests from flask import Blueprint, request, jsonify, g from sqlalchemy import desc from api.utils import requires_authentication from api.models import db_session, OptimizationRun, User, Semester, Course, CourseDependency, InstructorPool, InstructorAssignment, StudentDemand, StudentRecord, StudentAssignment ...
#!/usr/bin/env python #-*- coding:utf-8 -*- import hashlib class DotWriter: """ Formats a collection of Link objects as a Graphviz (Dot) graph. Mostly, this means creating a node for each URL with a name which Graphviz will accept, and declaring links between those nodes. """ def __init__ (s...
class InfeasibleProblemError(Exception): def __init__(self, status, message): super().__init__(message) self.status = status self.message = message
from typing import Any, List, NamedTuple from pandemic_simulator.simulator import PandemicSimulationState class Results(NamedTuple): number_recovered: int number_susceptible: int number_infected: int def print(self): print("Number Recovered:", self.number_recovered) print("Number Sus...
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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...
from ._version import get_versions __version__ = get_versions()['version'] del get_versions from .__main__ import ( litereval, merge, args_kwargs, get_args, LiterEvalError, tuple_, validated, get )
SECRET_KEY='2024'
#!/usr/bin/env python import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import matplotlib.pyplot as plt import math import time import sys if sys.version_info[0] < 3: from Tkinter import * import Tkinter as Tk else: from tkinter import * import tki...
# Generated by Django 2.2.5 on 2019-12-23 15:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('groups', '0001_initial'), ] operations = [ migrations.AddField( model_name='group', name='slug', field=m...
#About print the triangle by python """ * ** *** **** ***** """ # # 定义一个变量 记录行数 # i = 1 # while i <= 5: # print("*") # i += 1 # 定义一个变量 记录列数 # j = 1 # while j <= 5: # print("*", end="") # j += 1 # 定义一个变量记录行数 i = 1 while i <= 5: # 定义一个变量 记录列数 j = 1 while j <= i: print("*", end="") ...
from collections import defaultdict, Counter, deque N, Q = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(N - 1): a, b = map(int, input().split()) G[a - 1].append(b - 1) G[b - 1].append(a - 1) A = [0 for _ in range(N)] st = 0 for i in range(N): if len(G[i]) == 1: st = i ...
from typing import Any, Callable, Dict, Optional import pytest from tartiflette import Directive, Resolver, create_engine from tests.functional.utils import is_expected _SDL = """ directive @testdire( if: Boolean! = false ifs: [Boolean!] conditions: [Boolean!]! list: [Boolean]! ) on FIELD type Cat { name:...
def checkio(first, second): first_words = first.split(","); second_words = second.split(","); first_set = set(first_words); second_set = set(second_words); intersec = ",".join(sorted(second_set.intersection(first_set))); return intersec #These "asserts" using only for self-checking and not nece...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: python/sawtooth_block_info/protobuf/client_event.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from go...
class Solution: def solve(self, n): binary = ["0"]+list(bin(n)[2:]) zero_i, one_i = -1, -1 for i in range(len(binary)-1,-1,-1): if binary[i] == "1": one_i = i if one_i != -1 and binary[i] == "0": zero_i = i break binar...
from typing import Dict, List from django.db.models.functions import Length from django.http import HttpRequest, HttpResponse from django.shortcuts import render from app.models import Person # Module-specific configurable constants. TARGET_NICK = "kevr" # The Person's nick we're focused on. def get_person(nick: ...
#!/usr/bin/env python """ reference implementation of polarization integrals by Liu Xiao """ import numpy as np from numpy import sqrt, exp, pi from scipy.special import gamma, gammainc, comb, dawsn, erf from functools import reduce import operator def factor_double(n): if n<0 or n==0 or type(n) != int : return 1 ...
from altairexpress import fourier_transform as ft import pandas as pd import numpy as np # import altair as alt def test_fourier(): """ Tests the fourier function fourier_transform to make sure the outputs are correctly rendering. Returns: -------- None The test should pass and no asse...
#!/usr/bin/env python3 import http.client import json import socket import ssl ctx = ssl.create_default_context(cafile='server.pem') ctx.check_hostname = False ctx.verify_mode = ssl.CERT_REQUIRED conn = http.client.HTTPSConnection(host='127.0.0.1', port=8000, context=ctx) try: conn.request('GET', '/') except so...
import os import logging log = logging.getLogger(__name__) try: import testing.postgresql except ImportError as e: log.info("testing.postgresql not installed") db = None def setupDB(): # Generate Postgresql class which shares the generated database global db db = testing.postgresql.PostgresqlFac...
""" pyBPL - Python-based Bayesian Program Learning. Python implementation of Bayesian Program Learning (BPL), using PyTorch. The BPL framework has been generalized to work with various types of concepts. Character learning with Omniglot is one manifestation of the BPL framework, and it is included here as the prelimin...
import pandas as pd import pickle from os import listdir from torch.utils.data import Dataset from PIL import Image from transformers import LayoutLMv2Processor from torch.utils.data import DataLoader from transformers import LayoutLMv2ForTokenClassification import torch from tqdm import tqdm import numpy as np i...
import pymongo client = pymongo.MongoClient('mongodb://localhost:27017') client.drop_database('defmon')
import pandas as pd, numpy as np from sklearn.preprocessing import OneHotEncoder author_int_dict = {'EAP':0,'HPL':1,'MWS':2} def load_train_test_data (num_samples=None): train_data = pd.read_csv('../data/train.csv') train_data['author'] = [author_int_dict[a] for a in train_data['author'].tolist()] ...
# Copyright 2018 AT&T Intellectual Property. All other 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...
from py4web import action from py4web import response #index is used without html as I dont need html code @action("index") def index(): return "Hello World" @action("mpl_barchart") def mpl_barchart(): # from py4web import response from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanva...
#!/usr/bin/env python # coding=utf-8 import urllib import requests def thinkphp_debug_index_ids_sqli_verify(url): pocdict = { "vulnname":"thinkphp_debug_index_ids_sqli", "isvul": False, "vulnurl":"", "payload":"", "proof":"", "response":"", "exception":"", ...
P, Q, R = map(int, input().split()) print(min(P + Q, Q + R, P + R))
# CPU: 0.05 s from math import log2 def factorial(num): precomputed = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600] if num > 12: return float("inf") # TLE, don't compute else: return precomputed[num] m, n, t = map(int, input().split()) if t == 1: n = fa...
# Created app. This is the BackEnd Products python code that allows you to add # Products to the DB though form. This dictates how the forms behave on a POST request. from django import forms from .models import Product # This is pure Django form of setting up how the webpage's form checking logic. Do NOT do it the ...
from django.urls import path, include from user import views #from knox import views as knox_views app_name='user' urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name="token"), path('me/', views.ManageUserView.as_view(), name='me'), ...
""" Input/Output Operation For File System """ import random from pathlib import Path from typing import List, Union import orjson __all__ = ("IO",) class IO: """Input Output.""" @classmethod def dir_create(cls, dir_name: Union[str, Path]) -> bool: """create directory""" path = Pa...
import os import logging import sys import json def read_configuration_file(file_path): if not os.path.isfile(file_path): logging.critical("Could not find configuration file '%s'", file_path) sys.exit(1) else: logging.info("Reading configuration file") with open(file_path, "r") as f: return json.loads(""...
"""Emoji Available Commands: .emoji shrug .emoji apple .emoji :/ .emoji -_-""" from telethon import events import asyncio @borg.on(events.NewMessage(pattern=r"\.(.*)", outgoing=True)) async def _(event): if event.fwd_from: return animation_interval = 0.5 animation_ttl = range(0, 11)...
import sys import png BANK_SIZE = 0x4000 COLOR_SIZE = 2 PALETTE_COLORS = 32 PALETTE_SIZE = PALETTE_COLORS * COLOR_SIZE # It is not allowed to switch banks during a frame header or a data row. This # defines the size of the zone at the bank's end where new data can't start. RED_ZONE = PALETTE_SIZE + 1 # Frame with a di...
from splinter import Browser from bs4 import BeautifulSoup as bs import pandas as pd import requests import time def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {"executable_path": "chromedriver"} return Browser("chrome", **executable_pat...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from tensorflow import keras supported_layers = { keras.layers.Conv1D: ('Conv1D', 0), keras.layers.Conv2D: ('Conv2D', 0), keras.layers.Conv2DTranspose: ('Conv2DTranspose', 0), keras.layers.Conv3D: ('Conv3D', 0), keras.layers....
import pickle import numpy as np import os import lasagne from PIL import Image def unpickle(file): with open(file, 'rb') as fo: dict = pickle.load(fo) return dict def load_databatch(data_folder, idx, img_size=32): d = unpickle(data_folder) x = d['data'] y = d['labels'] # Labels ar...
from redis import StrictRedis from hortiradar.database import get_db redis = StrictRedis() db = get_db() groups = [g["name"] for g in db.groups.find({}, projection={"name": True, "_id": False})] for group in groups: k = "s:{gr}".format(gr=group) redis.delete(k)
# -*- coding: utf-8 -*- import numpy as np from sklearn.utils import check_array from sklearn.preprocessing import LabelEncoder from sklearn.decomposition import PCA from lpproj import LocalityPreservingProjection class SubspaceClassifier(): """A subspace method classifier. Parameters ---------- ...
from django.db import models ############################## class Logger(models.Model): """Note that name may not be unique in the database - multiple cruises may have loggers named 'gyr1'. To distinguish conflicts, we use the implicit logger id.""" name = models.CharField(max_length=255, blank=True) ...
''' Version 5 of the manufacturer's TFLuna Product Manual'''
# Copyright 2021 NVIDIA Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
from swsscommon import swsscommon import os import re import time import json def test_RouteAdd(dvs): dvs.runcmd("ifconfig Ethernet0 10.0.0.0/31 up") dvs.runcmd("ifconfig Ethernet4 10.0.0.2/31 up") dvs.servers[0].runcmd("ifconfig eth0 10.0.0.1/31") dvs.servers[0].runcmd("ip route add default via 10.0...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
assert __name__ != "__main__" import os nodeVersion = os.environ['LIBNODE_NODE_VERSION'] configFlags = [] if ('LIBNODE_CONFIG_FLAGS' not in os.environ) else os.environ['LIBNODE_CONFIG_FLAGS'].split() x86 = os.environ.get('LIBNODE_X86') == '1' zipBasenameSuffix = os.environ.get('LIBNODE_ZIP_SUFFIX', '')
# -*- coding: utf-8 -*- """ """ import logging from .store import search_messages logger = logging.getLogger(__name__) def get_command_data(command_uuid): query_body = { 'query': { 'bool': { 'must': [ { 'term': { ...
"""ttLib.macUtils.py -- Various Mac-specific stuff.""" from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import sys import os if sys.platform not in ("mac", "darwin"): raise ImportError("This module is Mac-only!") try: from Carbon import Res except ImportError: impor...
#!/usr/bin/env python3 # coding:utf-8 # 这里不偷懒,一个个自己输入 num_lst = [ int(i) for i in input("Please enter a set of numbers separated by spaces: ").split(' ')] print("\nThe original order:", num_lst) # 最值的“绕远路”求法 2 max_idx, min_idx = 0, 0 max_tmp, min_tmp = num_lst[0], num_lst[0] for i in range(len(num_lst)): if max_t...
import ast from svgutils.compose import SVG def get_true_width_height(svg): if "transform" in svg.root.attrib: transform = svg.root.attrib["transform"] ind = transform.rfind("scale") transform_scale = transform[ind:].strip("scale").strip(" ").replace(" ", ",") transform_tup = ast.l...
from unittest import TestCase from taguri.validator import ( authority_name_validator, date_validator, specific_validator, ) class AuthorityNameValidatorTestCase(TestCase): def test_accepts_domain_names(self): test_cases = ( 'unqualified-domain-name', 'fully-qualified-do...
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # Kornia components: # Copyright (C) 2017-2019, Arraiy, Inc., all rights reserved. # Copyright (C) 2019- , Open Source Vision Foundation, all rights reserved. # Copyright (C) 2019- , Kornia authors, all rights reserved. # # Licensed under the Apache L...
#----------------------------------------------------------------------------- # Name: TouchstoneModels # Purpose: To store and manipulate touchstone files # Author: Aric Sanders # Created: 3/7/2016 # License: MIT License #-------------------------------------------------------------------------...
import sys import neat import numpy as np from bombots.environment import Bombots import pygame as pg from templates.NOP import NopAgent from templates.agent_that_does_not_suicide import BeatNopAgent from templates.NEAT.NEAT import NeatAgent # For Travis if '--novid' in sys.argv: import os os.environ["SDL_V...
import json from khl import TextMsg, Bot, Cert # load config from config/config.json, replace `path` points to your own config file # config template: `./config/config.json.example` with open('./config/config.json', 'r', encoding='utf-8') as f: config = json.load(f) # init Cert for Bot OAuth cert = Cert(client_i...
from torch.utils.data import DataLoader #prend un set de data le distribue en différent batch from torchvision.datasets.mnist import MNIST from typing import NamedTuple #Tuple = liste d'objets non modifiables import torchvision.transforms as T class MNISTDataset (NamedTuple): train = MNIST( root="./data"...
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('membership', '0010_remove_membershiporganizationmeta_membership_fee'), ] operations = [ migrations.AlterField( model_name='membership', name='organization', ...
import argparse import csv import logging from .consts import DEVICE_SUBPLOTS from .consts import PLOT_TYPES, PLOT_TYPE_PLOTTER, PLOT_TYPE_SCATTER from .consts import SUB_COMMAND_CSV, SUB_COMMAND_MONITOR, SUB_COMMAND_PLOT from .csv import write_csv from .parser import Parser from .utils import get_logger from .utils i...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2019 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """REST API serializers.""" import json from time import sleep from flask import cu...
from __future__ import print_function from scipy.io import readsav import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import glob import sys def get_lc_files(visit): period = 2.694047 tc=0 if visit == '83': tc = 58000.69582 elif visit == '84': ...
''' Race_Detection_Functions.py This module contains the race detection function find_single_lvl_races() It is called in Race_Detection_and_Statistics.py to detect races. ''' import numpy as np import pandas as pd from .Race_Msg_Outcome import get_msg_outcome ############################### ## Main Functions ## ###...
import logging log = logging.getLogger(__name__) def output_response(output): log.debug("Selected output: return") return output def parse_config(config): pass def get_template(): return "$speech"
from dockyard.var import GLOBAL from dockyard.utils.mongo import Mongo class Log(Mongo): """ _id level msg origin """ LEVEL = "level" MSG = "msg" ORIGIN = "origin" def _warn(self, msgs, origin): self.__save(msgs, GLOBAL.LOG_WARN, origin) def _fatal(self, msgs,...
"""this is to check in new users""" from discord.ext.commands import Bot, Cog, command, Context, CommandError from discord import Embed, Reaction, Role, Member, User, DMChannel from discord.utils import get from contributor import AlbertUnruh from re import compile from database import DbUser as DbUser from colorama im...
#!/usr/bin/env python import datetime import json import os from bson.objectid import ObjectId from flask import Flask, render_template, request from mongoengine import connect from models import LiveBlog, LiveBlogUpdate app = Flask(__name__) connect('apps', username=os.environ['APPS_USER'], password=os.environ['A...
import math import itertools import operator from typing import List def is_prime(n): '''Check for a prime.''' if not isinstance(n, int): raise TypeError('Argument should be a positive integer.') if n < 2 or (n > 2 and n % 2 == 0): return False start = 3 stop = int(math.sqrt(n))...
#!/usr/bin/env python # coding: utf-8 # # Unitary Learning without qgrad # # **Disclaimer:** This tutorial does **not** use `qgrad`. # The intention is to show follow this tutorial with # another one _using_ `qgrad` to show to how easier # things are with qgrad. # # In this tutorial, we aim to learn unitary matri...
# Copyright (c) 2019 Sony 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 applicabl...
# coding: utf-8 """ Mailchimp Marketing API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: 3.0.74 Contact: apihelp@mailchimp.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import...
"""Converts a collection of notebooks to HTML files.""" import argparse import logging from pathlib import Path import re import os import nbformat from nbconvert.exporters import HTMLExporter from nbconvert.writers import FilesWriter from nbconvert.filters.markdown_mistune import MarkdownWithMath, IPythonRenderer fro...
# -*- coding: utf-8 -*- """aves.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1B0dqujGig62wioC2lIlRG8tiUCoWRnCy """ # Install Java, Spark, and Findspark !apt-get update !apt-get install openjdk-8-jdk-headless -qq > /dev/null !wget -q http://www...
# Link - https://codeforces.com/problemset/problem/339/A string = input() string = string.split('+') string.sort() print('+'.join(string))
""" Preprocess data for document classification. """ import torch from typing import Tuple, Dict from collections import Counter from nltk.tokenize import PunktSentenceTokenizer, TreebankWordTokenizer from tqdm import tqdm import pandas as pd import os import json from .utils import get_clean_text # tokenizers sent_...
from django.db import models class Category(models.Model): name = models.CharField(max_length =30) def __str__(self): return self.name @classmethod def search_by_category(cls,name): category = cls.objects.filter(name__icontains=name).first() images=Image.objects.filter(categ...
from . import sprite, window, label, util, mouse, map_loader, surface, clock, keyboard, shapes
import syft as sy import syfertext import torch from syft.generic.string import String from syfertext.doc import Doc from syfertext.pipeline import SubPipeline hook = sy.TorchHook(torch) me = hook.local_worker nlp = syfertext.load("en_core_web_lg", owner=me) def test_subpipeline_is_not_recreated_in_remote_workers(...
from collections import deque def inOrderUsingStack(root): s=deque() curr=root while True: if curr: while curr: s.append(curr) curr=curr.left elif s: curr=s.pop() print(curr.data,end=" ") curr=curr.right ...
import json import io from os import path import logging from ipwhois.exceptions import NetError from ipwhois.tests import TestCommon from ipwhois.net import Net from ipwhois.nir import (NIR_WHOIS, NIRWhois) LOG_FORMAT = ('[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)s] ' '[%(funcName)s()] %(mess...
#!/usr/bin/env python import requests import json import sys if __name__ == "__main__": # check args length if (len(sys.argv) != 3): print "usage %s ODL_IP_address Next_Hop_address" % sys.argv[0] sys.exit(1) url = "http://admin:admin@" + sys.argv[1] + ":8181/restconf/operational/network-to...
from our_classes import * from recipes import RECIPES def ingredient_input(): ingredients = [] ingredients_mentioned = [] ingredient = input('Ingredient: ') while ingredient != '': ingredient = ingredient.lower() ingredient = ingredient.strip() if ingredient not...
from pathlib import Path import shutil from ddpg_classes.simulator_arm import SimulationArm from simulation.dm_control_cur.utility_classes.simulator import Simulation from ddpg_classes.simulator_residual import ResidualSimulation import json import logging logging.basicConfig(filename='unit_tests.log', level=logging....
from django.db import models from django.utils.module_loading import import_string from django.template.loader import get_template from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.utils.translation import gettext_lazy as _ from django.conf import settings from phonenumber_field.modelfi...
""" This module implements the training routine for the specified model. Examples: $ python -m kg.ner.train \ --config configs/baseline.yaml Current supervised results (token level evaluation): Macro average precision: 0.83 Macro average recall: 0.67 Macro F1: 0.74 """ import argparse import os import tim...
# -*- coding: utf-8 -*- """FacialKeypointsDetection.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1m2uaffjRBIC3WlkaK7hVEW6vw3EgRTN1 """ import sys import cv2 import numpy as np from tensorflow.keras.models import load_model def detectFacialPo...
from pymtl import * from tests.context import lizard from lizard.util.rtl.interface import Interface from lizard.util.rtl.method import MethodSpec from lizard.core.rtl.frontend.fetch import FetchInterface from lizard.core.rtl.messages import FetchMsg from lizard.model.hardware_model import HardwareModel, Result from li...
# -*- coding: utf-8 -*- """ Created on Wed Jul 16 16:08:42 2014 @author: crousse """ from collections import OrderedDict from board import BoardConf from traceSet import TracesSet class Protocol(object): """ An ephys protocol (I/V, ramp, gratings ....) """ def __init__(self, data, reco...
import unittest from data_structures.array_queue import ArrayQueue class ArrayQueueTest(unittest.TestCase): def test_enqueue(self): array_queue = ArrayQueue() array_queue.enqueue(1) array_queue.enqueue(2) array_queue.enqueue(3) self.assertEquals(3, array_queue.size) ...
import requests from bs4 import BeautifulSoup import time import re class Instructables: def __init__(self, config, permutations_list): # 1000 ms self.delay = config['plateform']['instructables']['rate_limit'] / 1000 # https://www.instructables.com/members/{username} self.format = ...
import os import isodate import requests from helperFunctions import human_readable_time # ------------------------------------------------------------------------------------------------------------------ # Function Name : CalculateDuration # Description : Calculate duration # ----------------------------------------...
class Account: _successor = None _balance = None def set_NextMethod(self, account): self._successor = account def pay(self, amount_to_pay): instance_class_name = self.__class__.__name__ if self.can_pay(amount_to_pay): print('Paid $' + str(amount_to_pay) + ' using ' +...
# # PySNMP MIB module ATM-RMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-RMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:15:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...