content
stringlengths
5
1.05M
from typing import Dict from .expressions import ( Expression, Operation, Wildcard, AssociativeOperation, CommutativeOperation, SymbolWildcard, Pattern, OneIdentityOperation ) __all__ = [ 'is_constant', 'is_syntactic', 'get_head', 'match_head', 'preorder_iter', 'preorder_iter_with_position', 'is_a...
from openzwave.network import ZWaveNode from openzwave.value import ZWaveValue from Firefly import logging from Firefly.components.zwave.zwave_device import ZwaveDevice from Firefly.const import ACTION_OFF, ACTION_ON, AUTHOR, DEVICE_TYPE_SWITCH, LEVEL, SWITCH from Firefly.helpers.device_types.switch import Switch from...
import signal import os import subprocess # Initializes a multi processing worker and prevents the interupt signal to be handled. This should be handled by the # parent process. def init_worker(): signal.signal(signal.SIGINT, signal.SIG_IGN) def minimal_ext_cmd(cmd): # construct minimal environment env ...
"""Unit test package for aioxmppd."""
#! /usr/bin/env python3 # coding: utf-8 # flow@SEA # Licensed under the MIT License. import time import hashlib import datetime from binascii import unhexlify from base58 import b58encode, b58decode class CommonTool: @staticmethod def now(): return time.time() @staticmethod def sci_to_str(s...
class Solution(object): def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: List[str] :rtype: bool """ s_len = len(s) dp = [False] * (s_len+1) dp[0] = True for i in range(s_len): for j in range(i+1, n+1): ...
import matplotlib.pyplot as plt import numpy as np from PIL import Image # input is a H*W ndarray def display(npimg): plt.imshow(npimg, cmap='gray') plt.show() if __name__ == '__main__': images_path = "./HCL2000-100/HCL2000_100_train.npz" labels_path = "./HCL2000-100/HCL2000_100_train_label.npz" ...
import socket host, port = '', 8888 listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((host, port)) listen_socket.listen(1) print("listening on port %s" % port) while True: client_connection, client_address = l...
import sys from setuptools import setup from setuptools.command.test import test as TestCommand packageName = "arthur" import re versionLine = open("{0}/_version.py".format(packageName), "rt").read() match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", versionLine, re.M) versionString = match.group(1) class Tox(...
import os from pip._vendor.colorama import Fore from ws.RLUtils.monitoring.tracing.log_mgt import log_mgt if __name__ == '__main__': cwd = os.path.curdir acwd = os.path.join(cwd, '_tests') log_dir = os.path.join(acwd, "logs") fn_log = log_mgt(log_dir, show_debug=False, fixed_log_file=False)[0] c...
real = float ( input(' Digite o valor em reais: R$')) #dola = 5.34 dola = real / 5.34 euro = real / 6.25 print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou €{:.2f}.' .format( real,dola, euro)) #print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou € {:.2f}.'.format(real,(real/dola))) ...
# -*- coding: utf-8 -*- from openprocurement.auctions.core.tests.base import snitch from openprocurement.auctions.core.tests.blanks.contract_blanks import ( # AuctionContractResourceTest create_auction_contract_invalid, get_auction_contracts, # AuctionContractDocumentResourceTest not_found, crea...
matrix = [ #0, 1, 2, 3, 4, 5, 6, 7], #0 [0, 1, 1, 0, 0, 0, 0, 0], #0 [1, 0, 1, 1, 0, 0, 0, 0], #1 [1, 1, 0, 0, 0, 0, 0, 0], #2 [0, 1, 0, 0, 1, 1, 0, 0], #3 [0, 0, 0, 1, 0, 0, 1, 0], #4 [0, 0, 0, 1, 0, 0, 1, 0], #5 [0, 0, 0, 0, 1, 1, 0, 1], #6 [0, 0, 0, 0, 0, 0, 1, 0], #7...
from code.cli import Cli if __name__ == '__main__': Cli().run()
import cv2 import shutil import os import numpy as np from pathlib import Path from tqdm import tqdm from utils import get_all_files_in_folder def create_images_for_labeling(): dirpath = Path('denred0_data/prepare_images_for_labeling/result') if dirpath.exists() and dirpath.is_dir(): shutil.rmtree(d...
import datetime import time from huey import crontab from hueyx.queues import hueyx HUEY_Q1 = hueyx('queue1') HUEY_Q2 = hueyx('queue2') @HUEY_Q1.task() def my_task1(): print('my_task1 called') return 1 @HUEY_Q1.db_task() def my_db_task1(): print('my_db_task1 called') return 1 @HUEY_Q1.db_task(he...
"""The FleetGO component."""
from typing import List from .expresion_node import ExpressionNode from .let_node import LetNode class LetInNode(ExpressionNode): def __init__(self, let_body: List[LetNode], in_body: ExpressionNode, line: int, column: int): super(LetInNode, self).__init__(line, column) self.let_body: List[LetNode]...
from pyspark import SparkContext, SparkConf from pyspark.sql import SparkSession import pyspark.sql as sql from pyspark.sql.functions import * from pyspark.sql.types import * from collections import defaultdict from pyspark.sql import functions as F NUMBER_PRECISION = 2 def addSampleLabel(ratingSamples): ratingS...
from django.shortcuts import render # Create your views here. def home(request): return render(request, 'website_component/home.html', {'ViewName': request})
""" Entradas Salidas Impares-->int-->a """ a=0 while(a<100): if(a%2!=0 and a%7!=0): print(a) a=a+1
from pyplan_core.classes.wizards.BaseWizard import BaseWizard import json class Wizard(BaseWizard): def __init__(self): self.code = "CreateIndex" def generateDefinition(self, model, params): nodeId = params["nodeId"] if model.existNode(nodeId): base_node = model.getNode(n...
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below the provided parameter value number. # multiplesOf3and5(10) should return a number. # multiplesOf3and5(49) should return 543. # multiple...
# lextab.py. This file automatically created by PLY (version 3.6). Don't edit! _tabversion = '3.5' _lextokens = set(['DO', 'REMAINDER_ASSIGN', 'RSHIFT', 'SYNCHRONIZED', 'GTEQ', 'MINUS_ASSIGN', 'OR_ASSIGN', 'VOID', 'STRING_LITERAL', 'ABSTRACT', 'CHAR', 'LSHIFT_ASSIGN', 'WHILE', 'SHORT', 'STATIC', 'PRIVATE', 'LSHIFT...
from vpv.ui.controllers import importer from pathlib import Path import pytest def test_folder_filter(): #path: str, folder_include_pattern: str assert importer.folder_filter('/mnt/bit_nfs/neil/mutants/output/jag2/20150409_JAG2_E14.5_13.3f_HOM_XX_REC_scaled_4.6823_pixel_14.0001/output/registrations/deformable_...
from django.urls import path,include from . import views from bookshop.views import index from django.contrib.auth import views as auth_views urlpatterns = [ path('account/register',views.register,name='register'), path('account/login',views.login,name='login'), path('dashboard',index,name='dashboard'), ...
import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from astropy import wcs from astropy.io import ascii # TODO set the # UC4 296-009008 # (90.140913, -30.99747) # ASASSN ID AP 18326421 V=12.79 def find_min(xobj,yobj, xlist, ylist): 'find the index of the star closest to position xobj,...
# @file globalclasses.py # @brief global classes and objects # - # MODULE_ARCH: # CLASS_ARCH: # README: # Global variables dependence: # #standard #start.py #[GAP=FastApp(), life_cycle: always exist] #used by: start.py, scli.py #init at: start.globalclasses_init() global GAP GAP=None # refer configobj.readthed...
from http.server import HTTPServer, BaseHTTPRequestHandler from logger import logger from config import change_config, get_config BADREQUEST = 400 handlers = { 'get': [], 'post': [] } class BaseServer(BaseHTTPRequestHandler): def match_and_call(self, method): url = self.path.replace('..', '') #...
'''MIT License Copyright (c) 2021 Aditya Dangwal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
from data_collection.management.commands import BaseHalaroseCsvImporter class Command(BaseHalaroseCsvImporter): council_id = "E07000107" addresses_name = ( "local.2019-05-02/Version 1/polling_station_export-2019-03-04Dart.csv" ) stations_name = ( "local.2019-05-02/Version 1/polling_sta...
import numpy as np def check_temperature(T, melting_point=3000): """ Check if an instantaneous temperature will melt the divertor. """ if T > melting_point: print("Destroyed divertor!") melted = True elif T <= 0: raise ValueError("Unphysical temperature value!") else:...
# T-SNEを用いた文章分散表現の可視化 import sys, os sys.path.append('../') from src import * import matplotlib.pyplot as plt import japanize_matplotlib import numpy as np from scipy import sparse def visualize(xs, ys, labels, dataname): plt.figure(figsize=(15, 15), dpi=300) emotion = [ "happy", "sad", "angry", "fear/surp...
"""HOBO API""" from __future__ import annotations import json import logging import time from typing import Any, List, Optional, Union import requests from ..exceptions import ResponseError # https://docs.python.org/3/howto/logging.html#logging-basic-tutorial logger = logging.getLogger('hobo_iot') # logger.setLeve...
from Lib.statistics import mean, harmonic_mean, median, mode, median_low, median_high, median_grouped, stdev, pstdev, \ pvariance, variance, StatisticsError class Statistics(object): """The library used to define statistical outputs""" def __init__(self): self.allTimers = [] self...
"""Simple test for using adafruit_motorkit with a DC motor""" import time import board from adafruit_motorkit import MotorKit kit = MotorKit(i2c=board.I2C()) kit.motor1.throttle = 1.0 time.sleep(0.5) kit.motor1.throttle = 0
#!/usr/bin/env python # #Copyright 2020 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
from django.conf.urls import url, include urlpatterns = [ url(r'^oauth2/', include('django_auth_adfs.urls')), url(r'^oauth2/', include('django_auth_adfs.drf_urls')), ]
from typing import List, Tuple from instagrapi.exceptions import ClientError, HashtagNotFound from instagrapi.extractors import ( extract_hashtag_gql, extract_hashtag_v1, extract_media_gql, extract_media_v1, ) from instagrapi.types import Hashtag, Media from instagrapi.utils import dumps class Hashta...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.response.AlipayResponse import AlipayResponse class ZhimaCreditEpDataRatingQueryResponse(AlipayResponse): def __init__(self): super(ZhimaCreditEpDataRatingQueryResponse, self).__init__() self._amount = None sel...
# Import from standard library import logging import datetime import math # Import from third-party from flask import Flask, render_template, json, request, jsonify, session import pytz # Import local files import DAO.db_connect as db_connect from config.config import ElasticConfig def nessus_overview(): try: ...
#!/usr/bin/env python import distutils.log import os import subprocess from distutils.spawn import find_executable from setuptools import Command, find_packages, setup from distutils.command.build import build class BuildCommand(build): def run(self): self.run_command('compile_webui') build.run(...
from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import QResizeEvent from PyQt5.QtWidgets import QScrollArea, QVBoxLayout, QWidget from brainframe_qt.ui.resources import stylesheet_watcher from brainframe_qt.ui.resources.mixins.style import TransientScrollbarMI from brainframe_qt.ui.resources.paths import qt_qss_pa...
# coding: utf-8 import os import logging import sys import torch import time import copy # my staff from models.modules.context_embedder_base import ContextEmbedderBase, BertContextEmbedder, \ BertSeparateContextEmbedder, NormalContextEmbedder, BertSchemaContextEmbedder, BertSchemaSeparateContextEmbedder, \ Ele...
# Copyright 2013 - Noorul Islam K M # # 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 w...
""" Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessas funções. """ import moeda from exercicios.geral import tratamento p = tratamento.leiaFloat('Digite o preço: R$', 'preço') print(f'A met...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/5/12 14:44 # @Author : PPq from __future__ import print_function import argparse import os import shutil import time from torch.nn import DataParallel import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import ...
# Copyright (c) 2018 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 app...
from __future__ import print_function import os import sys import re import json from copy import deepcopy # Build job list ########################################### def job_builder(meta, valid_meta, workflow, job_dir, out_dir, coprocess=None, other_args="", writeimg=False): """Build a list of image processing ...
from . import Plugin class CatchallPlugin(Plugin): priority = -5 """ Turns metrics that aren't matched by any other plugin in something a bit more useful (than not having them at all) Another way to look at it is.. plugin:catchall is the list of targets you can better organize ;) Note that the ass...
import sys import logging import numpy as np import sympy as sp import ANNarchy_future.api as api import ANNarchy_future.parser as parser class Symbol(sp.core.Symbol): """Subclass of sp.core.Symbol allowing to store additional attributes. """ def __new__(self, name, method='euler'): obj = sp.co...
from juriscraper.OpinionSite import OpinionSite from datetime import datetime import re class Site(OpinionSite): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.url = "http://www.courts.state.va.us/scndex.htm" def _...
from django.conf.urls import patterns, include, url from django.contrib import admin from core.views import JobList, JobDetail, JobCreate admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'emplea_do.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', J...
import RPi.GPIO as GPIO import time from pathlib import Path import os import sys relay_signal = 4 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(relay_signal, GPIO.OUT) # pulls the signal pin high signalling the relay switch to close def garage_btn_down(pin): GPIO.output(pin, GPIO.HIGH) # Close OSC # pulls ...
# Common libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # Restrict minor warnings import warnings warnings.filterwarnings('ignore') # Import test and train data df_train = pd.read_csv('../input/train.csv') df_Test = pd.read_csv('../input/test.csv') df_test = df_...
# -*- coding: utf-8 -*- """ Gromov-Wasserstein transport method =================================== """ # Author: Erwan Vautier <erwan.vautier@gmail.com> # Nicolas Courty <ncourty@irisa.fr> # # License: MIT License import numpy as np from .bregman import sinkhorn from .utils import dist ...
# coding: utf-8 """ Cloudbreak API Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud...
"""initialize the connection and wait for a message directed at it""" from irc import * from decision import * import os import random channel = "#bitswebteam" server = "irc.freenode.net" nickname = "EisBot" irc = IRC() irc.connect(server, channel, nickname) while 1: text = irc.get_text() ...
import pickle import argparse import cv2 from tqdm import tqdm from lib.config import Config def parse_args(): parser = argparse.ArgumentParser(description="Tool to generate qualitative results videos") parser.add_argument("--pred", help=".pkl file to load predictions from") parser.add_argument("--cfg",...
# Copyright (c) 2008, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of co...
#!/usr/bin/env python """ Copyright (c) 2018 Keitaro AB Use of this source code is governed by an MIT license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. """ """ Executable module for checking github version updates for repositories from repositories.txt and alerting the slack ch...
from enum import Enum class Order(Enum): ASC = "ASC" DESC = "DESC" class DatabaseType(Enum): PSYCOPG2 = "PSYCOPG2" SQLITE3 = "SQLITE3" class Fetch(Enum): ONE = "ONE" ALL = "ALL"
# -*- coding:utf-8 -*- import threading local_value = threading.local() def test_put_thread(value): local_value.value = value test_read_thread() def test_read_thread(): print(local_value.value + " in thread: %s" % threading.current_thread().name) t1 = threading.Thread(target=test_put_thread, args=("张...
from flask import (Blueprint, render_template, redirect, request, url_for, abort, flash) from itsdangerous import URLSafeTimedSerializer from app import app, models, db from app.models import Survey, SurveyOptions from app.forms import survey as survey_forms from sqlalchemy import func # Create a su...
# coding: utf-8 import os import sys from threading import Thread sys.path.append(os.path.join(os.path.dirname(__file__), '../util')) from pluginbase import PluginBase class NotifierBase(PluginBase): def __init__(self): self.modtype = 'notifier' super().__init__() def start_notification(sel...
# -*- coding: utf-8 -*- # Copyright (c) 2017, FinByz Tech Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.model.document import Document from frappe.utils import add_days class TruckPartsInventory(Docum...
import pygame import json class Spritesheet: # Takes in Spritesheet file name. Assumes a png and a json file exist def __init__(self, filename): self.filename = filename self.sprite_sheet = pygame.image.load(filename).convert() self.meta_data = self.filename.replace('png', 'js...
""" This configuration file contains common data for parametrizing various tests such as isotherms. """ PRESSURE_PARAM = [ (1, {}), # Standard return (100000, { 'pressure_unit': 'Pa' }), # Unit specified (0.128489, { 'pressure_mode': 'relative' }), # Mode relative (12.8489, { ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import platform import sys if platform.system() != 'Linux': sys.exit(-1) from .killer import Killer from .utils import load_config parser = argparse.ArgumentParser(description='ssh key killer') parser.add_argument('-c', '--config', dest='config', m...
# coding: utf-8 ''' @Date : 2021-05-05 @Author : Zekang Li @Mail : zekangli97@gmail.com @Homepage: zekangli.com ''' import torch import string import torch.nn as nn from transformers import * SPECIAL_TOKENS = ["<bos>", "<eos>", "<info>", "<speaker1>", "<speaker2>", "<empty>", "<pad>"] SPECIAL_TOKENS_...
import os import json, decimal import boto3 from boto3.dynamodb.conditions import Key, Attr tableName = os.environ.get('ACCESS_TABLE_NAME') def handler(event, context): client = boto3.resource('dynamodb') table = client.Table(tableName) print(table.table_status) print(event) username = event['requestCont...
A_0219_9 = {0: {'A': 0.2420334938061355, 'C': -0.12964532145406094, 'E': -0.30716253311729963, 'D': -0.20136070573849837, 'G': 0.09315559829464488, 'F': 0.414085377622071, 'I': -0.11091042509341746, 'H': -0.40154576951031906, 'K': -0.11190222068525454, 'M': -0.16860437072777687, 'L': 0.20901824078912526, 'N': 0.0322878...
# from typing import Dict # import os # from unittest import TestCase, main # # import json # # from monolithcaching import CacheManager # # # class TestCacheManager(TestCase): # # @staticmethod # def get_meta_data(meta_data_path: str) -> Dict: # with open(meta_data_path) as json_file: # met...
def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ traversal1 = l1 traversal2 = l2 dummy = head = ListNode(0) carry = 0 while traversal1 != None or traversal2 != None or carry != 0: i...
# coding=utf-8 import json from common import constant from common import errcode from common.mylog import logger from dao.question.question_dao import QuestionDao from dao.question.user_question_map_dao import UserQuestionMapDao from handlers.base.base_handler import BaseHandler from myutil import tools class GetQu...
import pytest from ethereum import tester from functools import ( reduce ) from fixtures import ( MAX_UINT, fake_address, token_events, owner_index, owner, wallet_address, get_bidders, fixture_decimals, contract_params, get_token_contract, token_contract, create_contr...
import progressbar def test_with(): with progressbar.ProgressBar(max_value=10) as p: for i in range(10): p.update(i) def test_with_stdout_redirection(): with progressbar.ProgressBar(max_value=10, redirect_stdout=True) as p: for i in range(10): p.update(i) def test_w...
#!/usr/bin/env python # # Copyright 2016 Steve Kyle. 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 require...
from .find_maximum_value_binary_tree import find_maximum_value, BST def test_find_maximum_value_tree_with_one_value(): one_value = BST([5]) assert find_maximum_value(one_value) == 5 def test_find_maximum_value_tree_with_two_values(): one_value = BST([10, 2]) assert find_maximum_value(one_value) == 1...
import matplotlib.pyplot as plt import networkx as nx import os import random import warnings from matplotlib.backends import backend_gtk3 from settings import OUTPUT_DIR warnings.filterwarnings('ignore', module=backend_gtk3.__name__) RESTART_PROBABILITY = 0.15 STEPS_MULTIPLIER = 100 def random_walk_sample(grap...
from collections import KeysView def find(iterable: list or KeysView, key=lambda x: x): for elem in iterable: if key(elem): return elem return None def index(iterable: list, key=lambda x: x) -> int: x = 0 for elem in iterable: if key(elem): return x x += 1 return -1
from django.apps import AppConfig class CalToolConfig(AppConfig): name = 'cal_tool'
# # # 0=================================0 # | Kernel Point Convolutions | # 0=================================0 # # # ---------------------------------------------------------------------------------------------------------------------- # # Callable script to start a training on Myhal...
#!/usr/bin/env python """Split large file into multiple pieces for upload to S3. S3 only supports 5Gb files for uploading directly, so for larger CloudBioLinux box images we need to use boto's multipart file support. This parallelizes the task over available cores using multiprocessing. Usage: s3_multipart_upload....
#!/usr/bin/env python # coding: utf-8 ################################################################################################### # # File : frame_study.py # # Auhtor : P.Antilogus # # Version : 22 Feb 2019 # # Goal : this python file read raw data image , and can be used for specific sensor diagnostic like : ...
#!/usr/bin/python # # Copyright 2012 Sonya Huang # # 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 ag...
class Solution(object): def lengthOfLongestSubstringTwoDistinct(self, s): """ :type s: str :rtype: int """ if not s: return 0 c = s[0] maxlen = 0 chars = set([c]) llen = 0 start = 0 end = 0 for i, cc in enume...
import sys from sqlalchemy import create_engine import pandas as pd import numpy as np import re from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import PorterStemmer, WordNetLemmatizer from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.mod...
#!/usr/bin/env python # -*- coding: utf-8 # Copyright 2017-2019 The FIAAS 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 # # Unle...
# -*- coding: utf-8 -*- # # michael a.g. aïvázis <michael.aivazis@para-sim.com> # (c) 1998-2022 all rights reserved # support import qed # custom properties def selectors(default={}, **kwds): """ A map from selector names to their legal values """ # build the trait descriptor and return it retur...
#!/usr/bin/env python import numpy from numpy.random import RandomState from sklearn.datasets import make_friedman1 from sklearn.model_selection import train_test_split from typing import Union from backprop.network import Network _demo_problem_num_train_samples: int = 1000 _demo_problem_num_test_samples: int = 100 ...
# Copyright 2020 Board of Trustees of the University of Illinois. # # 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 ...
import numpy as np from mrcnn import utils def build_rpn_targets(image_shape, anchors, gt_class_ids, gt_boxes, config): """Given the anchors and GT boxes, compute overlaps and identify positive anchors and deltas to refine them to match their corresponding GT boxes. anchors: [num_anchors, (y1, x1, y2, x2)...
from django import forms from django.contrib import admin from django.utils.safestring import mark_safe from .models import Episode, ShowDate from .tasks import generate_peaks class ShowsCommonModelAdminMixin: save_on_top = True list_filter = ("published", "show_code") list_display_links = ("show_code", ...
""" Events emitted by the artist model """ from dataclasses import dataclass from typing import List, Optional from OpenCast.domain.event.event import Event, ModelId @dataclass class ArtistCreated(Event): name: str ids: List[ModelId] thumbnail: Optional[str] @dataclass class ArtistThumbnailUpdated(Eve...
from unittest import TestCase from lie2me import Field class CommonTests(object): def get_instance(self): return self.Field() def test_submitting_empty_value_on_required_field_returns_error(self): field = self.get_instance() field.required = True value, error = field.submit(f...
import os import sys from RLTest import Env from redisgraph import Graph, Node, Edge sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from base import FlowTestsBase redis_graph = None male = ["Roi", "Alon", "Omri"] female = ["Hila", "Lucy"] class testGraphMixLabelsFlow(FlowTestsBase): def __init__...
import io import logging from typing import List, Union LOG = logging.getLogger(__name__) class FileHelper: """Encapsulates file related functions.""" def __init__(self, filepath, line_idx, contents): self.filepath = filepath self.line_idx = line_idx self.contents = contents @cl...
#!/usr/bin/python import sys import tarfile import json import gzip import pandas as pd import botometer from pandas.io.json import json_normalize ## VARIABLE INITIATION #system argument # arg 1 = 'rs' or 'sn' # arg 2 = hour file 6,7 or 8 ? # arg 3 = start row # arg 4 = end row # arg 5 = key selection, 1,2,3,4 # sn 7...
from analyzers.utility_functions import auth from parsers.Parser import Parser class HthParser(Parser): __url = "https://fantasy.premierleague.com/api/leagues-h2h-matches/league/{}/?page={}&event={}" __HUGE_HTH_LEAGUE = 19824 def __init__(self, team_id, leagues, current_event): super().__init__(t...