content
stringlengths
5
1.05M
#!/usr/bin/python3 def multiply_by_2(a_dictionary): a = {} for x, y in a_dictionary.items(): a.update({x: y*2}) return a
# Copyright 2017 Predict & Truly Systems 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 applic...
import os import logging import requests from django.conf import settings from django.http import HttpResponseBadRequest, HttpResponseNotFound from django.views import View from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import ...
# -*- coding: utf-8 -*- """ Test functions in network_selection.py. """ """License: Copyright 2020-2022 The Cytoscape Consortium 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 witho...
print("\tWelcome to the Factor Generator App") #Creamos la variable c = True para utilizar en un bucle sin fin c = True #Creamos el bucle while c : num = int(input("\nEnter a number to determine all factors of that number: ")) fact = [] #Añadimos los factores del número for i in range(1,num+1): ...
#!/usr/bin/env python import os class FindDir(): _base_dir = os.path.dirname(os.path.realpath(__file__)) conf_dir = '' log_dir = '' found_dir = '' # for special cases def __init__(self, dirname=None): if dirname is None: # maybe these should 'always' be the case self.conf_dir...
import json from .util import UserTestCase from django.test import Client, RequestFactory from django.test.utils import override_settings from django.db import models from django.contrib.auth.models import AnonymousUser from django_grainy.models import ( UserPermission, GroupPermission, GrainyHandler, ...
# Copyright (c) 2018-2021, Texas Instruments # 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 condition...
import pkg_resources from .bert import Bert __version__ = pkg_resources.resource_string("easybert", "VERSION.txt").decode("UTF-8").strip() __all__ = [__version__, Bert]
from ..util import enum class DataSource(object): CANDLE_VALUES = ['high', 'low', 'open', 'close'] CANDLE_SIZE = len(CANDLE_VALUES) CANDLE = enum(CANDLE_VALUES) def __init__(self, start_time=None, tick_size=None): if start_time is None or tick_size is None: self.start_time = start_...
""" Copyright (c) 2016-2019 Keith Sterling http://www.keithsterling.com 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, m...
#! /usr/bin/env python3.8 """ AUTHOR : MOHAN KUMAR PALURU Description : Audio Server Starter App Run this file with python3.8 to start the service """ import uvicorn from decouple import config if __name__ == "__main__": AUDIO_SERVER_PORT = int(config("AUDIO_SERVER_PORT")) uvicorn.run("app:ap...
import os import json import sys from pathlib import Path if __name__ == "__main__": which_matrix = sys.argv[1] testcase_json = "e2etest/testcases.json" ec2_matrix = {"testcase": [], "testing_ami": ["amazonlinux2", "ubuntu16", "windows2019"]} ecs_matrix = {"testcase": [], "launch_type": ["EC2", "FARGA...
from django.conf.urls import url from . import api urlpatterns = [ url(r'^api/redshiftdb/(?P<pk>\d+)/$', api.RedShiftDbUpdate.as_view()), url(r'^api/RedshiftSchema/', api.RedShiftSchemaList.as_view()), url(r'^(?i)api/redshiftdb/', api.RedShiftDbList.as_view()), # url(r'^(?i)api/CopyDataToRedShift/', api....
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
from __future__ import with_statement import copy import pytest from whoosh import fields, qparser, query from whoosh.compat import b, u from whoosh.filedb.filestore import RamStorage from whoosh.qparser import QueryParser from whoosh.query import And from whoosh.query import AndMaybe from whoosh.query import Constan...
"""Module containing tests for the data utility functions""" from unittest import TestCase, main from judah.utils.data import remove_empty_string_values, replace_keys_with_aliases, replace_substrings class TestDataUtilities(TestCase): """Tests for the data utility functions""" def test_remove_empty_string_v...
#================================================================ # # File name : detect_mnist.py # Author : PyLessons # Created date: 2020-08-12 # Website : https://pylessons.com/ # GitHub : https://github.com/pythonlessons/TensorFlow-2.x-YOLOv3 # Description : mnist object detection exampl...
# Copyright 2012 OpenStack Foundation # # 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 ...
""" This module represents the Jupyter server extension for flexxlab. It is responsible for adding the Flexx handlers to the Tornado application that underlies the Jupyter server. """ from flexx import app def _jupyter_server_extension_paths(): return [{ "module": "flexxlab" }] def load_jupyter_ser...
import gettext from i18n import catalog, translate import os import shutil def test_translation(): """Tests if the translation function returns a Translation instance. The translation object returned can be both a GNUTranslations or a NullTranslations depending if there's a locale directory with ...
class Field: def __init__(self, type_, default, value=None): self.type_ = type_ self.default = default self._value = value @property def value(self): if self._value is None: return self.default else: return self._value
#!/usr/bin/python3 import os import environ from utils.singleton_class import SingletonMetaClass class EnvInjecter(metaclass=SingletonMetaClass): def __init__(self, env_var_name="DOT_ENV_PATH"): self.env = environ.Env() DOT_ENV_PATH = self.env.str(env_var_name, default=None) if DOT_ENV_PA...
from __future__ import annotations import requests as rq import os from .retrieval import DataRetrievalStrategy # . needed because modules not packaged from typing import Optional from app.spoonderful.config import settings class SpoonacularResponse: """ Class to make requests to Spoonacular's API and store ...
# Copyright 2022 @ReneFreingruber # # 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 agreed to in...
assert 1 assert 1, foo
from pyproj import Transformer from genet import Stop, Route from genet.modify import schedule from tests.fixtures import assert_semantically_equal def test_reproj_stops(): stops = {'26997928P': {'routes': ['10314_0'], 'id': '26997928P', 'x': 528464.1342843144, 'y': 182179.7435136598, '...
import math import random import gym import numpy as np from . import agent as a from . import terrain as t from . import config as c from . import gui as gui class RocketballEnv(gym.Env): def __init__( self, maxthrust=1.0, leftborder=-1.5, rightborder=1.5, topborder=2.0, delta_time=1. /...
from functools import partial from graphene import Node, Field, ID from graphene.types.utils import get_type from graphene_django.utils import is_valid_django_model from graphene_django_extras.rest_framework import GraphqlPermissionMixin from graphene_django_extras.utils import queryset_builder class BaseNodeField(Gr...
import matplotlib from matplotlib import * import matplotlib.pyplot as plt def getValues (): l = [] #labels x = [] #pontos_hanan y = [] #pontos_gerados z = [] #custo f = [] fi = open("result.log") n = 0 t = [] for i in fi: t.append(i) n += 1 if n % 5 == 0: ...
# /dust/src/utils/lang.py # Package import __init__ from dust.src.errors import UnexpectedOptionError def check_opts(opts, expected_keys): """Check that no options are supplied that are not in the expected key list, throws Error on unexpected""" _ = tuple(filter(lambda key: key not in expected_keys,...
import unittest import warnings from lib import * class TestAddTaxos(unittest.TestCase): courses = [] taxos = [] def setUp(self): # make "unclosed socket" warnings stop, see this for instance # https://github.com/boto/boto3/issues/454 warnings.filterwarnings( "ignore...
from django.apps import AppConfig class MesfactoryConfig(AppConfig): name = 'mesfactory'
from pyramid.view import view_config from ..models import Todos @view_config(route_name='todo_list', renderer='../templates/todos_list.jinja2') def todo_list(request): todos = request.dbsession.query(Todos).all() return {'todos': todos} @view_config(route_name='todo_view', renderer='../templates/todo_view....
#!/usr/bin/python3 import calendardb from nlp.universal_dependencies import ParsedUniversalDependencies from user_interface.user_interaction_service_base import UserInteractionServiceBase from .skill import SkillInput, Skill class TellTimeSkill(Skill): """Lets the assistant tell the user the current time.""" ...
import torch from torch import nn import pandas as pd import os from tqdm import tqdm import torchaudio import librosa import numpy as np import gc def sample2melspectrogram(samples,sample_rate): melspectrogram = librosa.feature.melspectrogram(samples,sample_rate,center=False) melspectrogram = libr...
# -*- coding: utf-8 -*- from typing import Optional, List from wechatpy.client.api.base import BaseWeChatAPI class WeChatTag(BaseWeChatAPI): """ 标签管理 https://work.weixin.qq.com/api/doc#90000/90135/90209 """ @staticmethod def _validate_tag_id(tag_id): if tag_id < 0: rais...
import tensorflow as tf import tensorflow.contrib as tfcontrib from tensorflow.python.keras import layers from tensorflow.python.keras import models from tensorflow.python.keras import backend as K def conv_block(input_tensor, num_filters): encoder = layers.Conv2D(num_filters, (3, 3), padding='same')(input_tensor) ...
import numpy as np from numba import njit as jit, prange from numpy import cos, cross, sin, sqrt import sys from .utils import E_to_nu, F_to_nu, norm """ Converting from Keplerian to Cartesian -------------------------------------- Helpful links: https://downloads.rene-schwarz.com/download/M001-Keplerian_Orbit_E...
import setup_path import airsim client = airsim.MultirotorClient("",4001,36000) client.confirmConnection() client.enableApiControl(True) client.armDisarm(True) landed = client.getMultirotorState().landed_state if landed == airsim.LandedState.Landed: print("taking off...") client.takeoffAsync().join() else: ...
""" @brief test log(time=1s) """ import os import unittest from pyquickhelper.loghelper import fLOG class TestLabel(unittest.TestCase): def test_label_bom(self): fLOG( __file__, self._testMethodName, OutputPrint=__name__ == "__main__") fold = os.path.abspa...
#!/usr/bin/env python3 import socketserver import sys import threading import pymongo from console.utils import wait_key from server import Server def cleanup(): client = pymongo.MongoClient(serverSelectionTimeoutMS=1) try: client['NP']['user'].drop() except pymongo.errors.ServerSelectionTimeout...
"""pessoas = {'nome': 'Carlos', 'sexo': 'M', 'idade': 18} print(f'O {pessoas["nome"]} tem {pessoas["idade"]} anos.') print(pessoas.items()) pessoas['peso'] = 60 del pessoas['sexo'] for k, v in pessoas.items(): print(f'{k} = {v}') Brasil = [] estado1 = {'uf': 'Maranhão', 'sigla': 'MA'} estado2 = {'uf': 'Ceará', 'si...
""" This script process .hdr/.exr/.tif environment map files into a specular cubemap and a irradiance cubemap. The images are then processed by the "compress_images" script and then (FINALLY), the generated .ktx files are processed by "ktxmerge.py" to create two ktx cubemap. TODO: just send one list of commands to doc...
import os,sys,platform import pygit2 import os_encoding import urllib2 from bs4 import BeautifulSoup class GitUpdator(object): osList = {"darwin":"mac","windows":"win"} def __init__(self, repo_path,origin_uri,progress_callback=None,mkdir=True): assert repo_path != None and isinstance(repo_path,basestring) if m...
# 1. Reverse the order of the items in an array. # Example: a1 = [1, 2, 3, 4, 5] a1 = a1[::-1] print(a1) # 2. Get the number of occurrences of var b in array a. a2 = [1, 1, 2, 2, 2, 2, 3, 3, 3] b2 = 2 print(a2.count(b2)) # 3. Given a sentence as string, count the number of words in it. a3 = 'ana are mere si nu are p...
import socket #import socket module #import time import threading import cv2 import base64 import numpy as np def receiveData(client): while(True): data = client.recv(1024).decode() #print(data) try: frame = data img = base64.b64decode(frame) npimg = np.fromstring(img, dtype=np.uint8) source = ...
import pandas as pd import re from datetime import timedelta from pyquery import PyQuery as pq from urllib.error import HTTPError from .. import utils from ..constants import AWAY, HOME from ..decorators import float_property_decorator, int_property_decorator from .constants import (BOXSCORE_ELEMENT_INDEX, ...
from typing import Tuple, Optional import torch from skorch.helper import SliceDict from strong_glm.glm.survival.censoring import unpack_cens_y from strong_glm.log_prob_criterion import NegLogProbLoss, _reductions class CensNegLogProbLoss(NegLogProbLoss): """ Negative-log-prob when y_true is a right-censore...
from algebreb.listas.listas_factorizacion import ListaDiferenciaCuadrados from sympy.abc import a, b, c, x, y , z import json caracteristicas = {} caracteristicas['cantidad'] = 10 caracteristicas['variables'] = [a] caracteristicas['gmin'] = 1 caracteristicas['gmax'] = 3 caracteristicas['cmin'] = 1 caracteristicas['cma...
# coding=utf-8 ''' IB Message Callback Functions Created on 10/18/2016 @author: Jin Xu @contact: jin_xu1@qq.com ''' from __future__ import absolute_import, print_function, division import pytz from datetime import datetime from copy import copy from ib.ext.EWrapper import EWrapper from ib.ext.EClientErrors import EC...
#!/usr/bin/env python2.7 import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) TAG = """ <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-40344111-29"></script> <script> window.dataLayer = window.dataLayer || []; functi...
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import os import re import sys import six from six.moves.urllib.parse import quote, urljoin from .command import Command, BadCommand from paste.deploy...
from abc import ABC, abstractmethod from devices.callbacks import handle, validate class ConnectPattern(ABC): def __init__(self): self._on_connect = None if '_is_connected' not in self.__dict__: self._is_connected = False @property def is_connected(self): """ ...
from pp.client.plone.browser.compatible import InitializeClass from Products.Five.browser import BrowserView from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile from plone import api from medialog.invoice.interfaces import IInvoiceSettings class InvoiceView(BrowserView): """ PDF view for invo...
import os from typing import List from setuptools import find_packages, setup class PackageInfo: @staticmethod def get_readme() -> str: """Returns README text if it is exists in given path""" if "README.md" in os.listdir(os.path.abspath("./")): with open(os.path.abspath("./README.md"), "r") as read...
from cloudmesh.transfer.provider.awss3.Provider import Provider as AwsProvider from cloudmesh.transfer.provider.azureblob.Provider import \ Provider as AzureblobProvider from cloudmesh.transfer.provider.local.Provider import Provider as LocalProvider from cloudmesh.storage.StorageNewABC import StorageABC from cloud...
# -*- coding: utf-8 -*- # Utility for objects management. import inspect import logging from gcommon.utils import grand class ObjectWithLogger(object): logger = None _logger_name = "" @classmethod def set_class_logger(cls, logger=None): """为类设置 logger""" if not logger: ...
""" - NIS -> Nextcloud. Export a case study to a Nextcloud folder: - Link a Nextcloud folder to a NIS case study. - Dublin Core. "convert_generator_to_dublin_core" - MSM JSON. The NIS format for the representation of sequences of commands. "convert_generator_to_json_generator" - Nextcloud -> NIS. --- *...
from django.contrib.auth import get_user_model from django.test import TestCase from posts.models import Group, Post User = get_user_model() class PostModelTest(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create_user(username='auth') cls....
import hashlib import logging import os import requests from langmodels.repository.convert import convert_file_version logger = logging.getLogger(__name__) def _download_file(url: str, path: str) -> None: response = requests.get(url, stream=True) with open(path, "wb") as f: for chunk in response.it...
import pytest import windows import windows.generated_def as gdef from windows.pycompat import basestring from .pfwtest import * ## This comment was in test_system.py: still revelant ? # Well, pytest initialize COM with its own parameters # It might make our own com.init() in WMI fail and therefore not call # CoInit...
def get_required_error(attribute): return {"required": {"message": attribute + " is required"}}
import mysqlbuilder import urllib import json recent = 10 url = 'http://codeforces.com/api/contest.list'; if __name__ == '__main__': db = mysqlbuilder.database(debug = True) html = urllib.urlopen(url).read() j = json.loads(html) if j['status'] == 'OK': for contest in j['result'][: recent]: ...
""" ---------------------------------------------------------------------------- ovf2vtk: convert OOMMF vector-field file into vtk-vector field file SYNTAX: ovf2vtk [OPTIONS] infile outfile OPTIONS: [--add xy ] adding a scalar component to the outfile showing the inplane angle of th...
from .ca_scraper import CaScraper from .example_scraper import ExampleScraper from .hema_scraper import HemaScraper from .hm_scraper import HmScraper from .primark_scraper import PrimarkScraper from .quotes_scraper import QuotesScraper from .zalando_scraper import ZalandoScraper __all__ = [ CaScraper, ExampleS...
from base64 import urlsafe_b64encode from functools import partial import hashlib import os from pathlib import Path import re import yaml def get_configuration(cfg_path): cfg_path = Path(cfg_path) return ReloadWrapper(Configuration, cfg_path) class ReloadWrapper: def __init__(self, factory, file_path)...
#-*-coding: utf-8 -*- from multiprocessing import Process, Queue from threading import Thread from time import sleep import random import logging import json from tqdm import tqdm LOG_FILE_NAME = 'log.log' def _without_processes(URLList, OnePageHandlerClass): ''' Обработка списка URL-ов в простом цикле. ''' ...
import numpy as np import cv2 from matplotlib import pyplot as plt image = cv2.imread('filtering/man.jpg') mask = np.zeros(image.shape[:2], np.uint8) bgdModel = np.zeros((1,65), np.float64) fgdModel = np.zeros((1,65), np.float64) rect = (120,79,150,150) cv2.grabCut(image, mask, rect, bgdModel, fgdModel, 5, cv2.GC_I...
import torch from fairseq.data.data_utils import collate_tokens import os from scipy import stats import numpy as np from fairseq.models.roberta import RobertaModel modelroot = '/private/home/chuntinz/work/fairseq-hallucination/container' model = 'roberta.large.mnli' roberta = RobertaModel.from_pretrained( '{}/{}...
import numpy as np import math M_w_p = np.array([[0, 0, -1, 0.035], [0, 1, 0, 0.105], [1, 0, 0, 0.041], [0, 0, 0, 1]]) def forwardKinematics(theta1, theta2, theta3): """ Function to Perform Forward Kineamtics Parameters ---------- theta1 : Angle 1 input to the Hubert Robot theta2 : Angle 2 i...
#!/usr/bin/env python3 from telegram import InlineQueryResultArticle,InputTextMessageContent from telegram.ext import Updater from telegram.ext import CommandHandler, MessageHandler, Filters, InlineQueryHandler from uuid import uuid4 import logging import exchanges import requests import math logging.basicConfig(form...
# coding: utf-8 __author__ = 'Miso' from flask_redis import FlaskRedis redis_store = FlaskRedis()
# inspired by and VU visualization based on Jeff Epler's JEplayer: # https://learn.adafruit.com/pygamer-mp3-player-with-circuitpython?view=all import gc import os import random import time import adafruit_bitmap_font.bitmap_font import adafruit_display_text.label from adafruit_progressbar import ProgressBar import ada...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import py...
from tkinter import * from ies import * from .layers import * from util import * import math class LayersPanel(ScrollFrame): def __init__(self, parent): ScrollFrame.__init__(self, parent) self.parent = parent self.columnconfigure(0, weight=1) self.layers = [] self.rowCounter = 3 self.selection = Str...
""" evaluation ~~~~~~~~~~ Contains routines and classes to help with evaluation of predictions. """ import numpy as _np import scipy.special as _special import collections as _collections import datetime as datetime import logging as _logging from . import naive as _naive from . import predictors as _predictors from ...
#!/usr/bin/env python3 # coding: utf-8 # Copyright 2016 Abram Hindle, https://github.com/tywtyw2002, and https://github.com/treedust # # 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 # ...
# # For this is how God loved the world:<br/> # he gave his only Son, so that everyone<br/> # who believes in him may not perish<br/> # but may have eternal life. # # John 3:16 # import numpy as np from aRibeiro.math import * from aRibeiro.opengl import * #from multiprocessing import RLock from threading import RLock ...
# -*- coding: utf-8 -*- import random from google.appengine.ext import db from model import Lecture from model import LectOrder import logging SITE_URL = "http://www.geocities.jp/timeway/" KOUGI_NUM = 106 def getMsg(): lecture_no = lectorder_get() query = db.GqlQuery("SELECT * FROM Lecture WHERE lecture_no =...
#!/usr/bin/env python # This script will run the mdig simulations without using GRASS-GIS. # Audrey Lustig # Bio-Protection Research Centre, Lincoln University, NZ # March 2016 import random import math import numpy import glob, os import shutil import multiprocessing from time import time as now import numba import...
"""Unit tests for neural_net.py""" import math import random import string import unittest import numpy as np import xarray as xr from littlenet import neural_net as nn from littlenet import utility LAYER_SIZES = [10, 5, 2] NUM_LAYERS = len(LAYER_SIZES)-1 NUM_CASES = 3 NUM_LABELS = 2 INPUT_SIZE = LAYER_SIZES[0] SIGMO...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
#hits = 0 #misses = 0 #ejects = 0 class CompositedCacheMixin(object): def __init__(self, *args, **kwargs): super(CompositedCacheMixin, self).__init__(*args, **kwargs) self._merged_solvers = { } def _blank_copy(self, c): super(CompositedCacheMixin, self)._blank_copy(c) c._merged...
""" Integration tests for the login handling. TODO: Clean up the tests in this module. """ from datetime import timedelta from importlib import import_module from time import sleep from django.contrib.auth import get_user_model, login, logout from django.http import HttpRequest from django.test import override_settin...
import numpy as np import opt_einsum from typing import Any, Sequence, FrozenSet, Optional, Tuple, Union, cast import collections import itertools from jax import core from jax import lax from jax._src.numpy.lax_numpy import ( _promote_dtypes, shape, reshape, _all, _removechars, _polymorphic_ei...
from config_parser import parseConfig import os import sqlite3 # Use expanduser to expand ~ to the user's home directory DB_FILENAME = os.path.expanduser(parseConfig()['db_filename']) def main(): # Start the database fresh if os.path.exists(DB_FILENAME): os.remove(DB_FILENAME) # Connect to d...
import datetime import json class ComplexEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d') else: return ...
# Copyright (C) 2020 Ghifari Pradana # # SPDX-License-Identifier: MIT from floodsystem.station import inconsistent_typical_range_stations from floodsystem.stationdata import build_station_list def run(): stations = build_station_list() print(inconsistent_typical_range_stations(stations)) if __name__ == "__...
#! /usr/bin/env python import unittest import os.path import sys import logging logging.root.setLevel(logging.DEBUG) import Path from Vispa.Main.Directories import * from Vispa.Main.Application import Application from Vispa.Plugins.EventBrowser.EventBrowserPlugin import EventBrowserPlugin from Vispa.Plugins.Browser....
import jax import jax.numpy as jnp import optax from .nn import Model __all__ = ["apply_model", "update_model"] @jax.jit def apply_model(state, images, labels): """Computes gradients, loss and accuracy for a single batch.""" def loss_fn(params): logits = Model().apply({"params": params}, images) ...
import subprocess import os # print(os.getcwd()) # os.chdir("build/") commandList = [] commandList.append("./ZMQEchoer --SubEP ipc:///tmp/pingTopic1 --PubEP ipc:///tmp/pongTopic1") msgLen = '10000' commandList.append("./ZMQInitiator --PubEP ipc:///tmp/pingTopic1 --SubEP ipc:///tmp/pongTopic1 --msgLength " + msgLen) c...
#!/usr/bin/env python import argparse import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import warnings warnings.filterwarnings('ignore') # ----- Kaggle Submission --------------------------------------------- def submit_to_kaggle(model, X_test, sample_submission, submissi...
# -*- coding: UTF-8 -*- import unittest from ytcc.storage import Storage from unittest.mock import patch class TestRemoveFile(unittest.TestCase): @patch('os.remove') def test_remove_file(self, mock): video_id = 'v2309jfGew' file_path = 'subtitle_v2309jfGew.en.vtt' storage = Storage(v...
from django.apps import AppConfig class SaraswatiConfig(AppConfig): name = 'saraswati'
"""Solr query""" import unittest def default_reporter(percent): print("\rProgress: {percent:3.0f}%".format(percent=percent)) class SolrServer(object): server = None port = None def __init__(self, protocol, server, port): """ Constructor to initialise solr client API URL @t...
import imageProcess import numpy from skimage.measure import label, regionprops def areaFilter(bImg): labelImg = label(bImg) numLabel = labelImg.max() props = regionprops(labelImg) bImg[:] = False areaList = [] for i in range(numLabel): areaList.append(props[i].area) areaList =...
import datetime from sqlalchemy import ( Column, Datetime ) from sqlalchemy.ext.declarative import declarative_base class Base(object): created_at = Column( Datetime, default=datetime.datetime.utcnow, nullable=False ) updated_at = Column( Datetime, default=date...
#!/usr/bin/env python2 """Context for all tests.""" from __future__ import absolute_import import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)) + "../lcovparse")) import lcovparse # pylint: disable=wrong-import-position,unused-import
def finder(data): return finder_rec(data, len(data)-1) def finder_rec(data, x): if x == 0: return data[x] v1 = data[x] v2 = finder_rec(data, x-1) if v1 > v2: return v1 else: return v2 print(finder([0, -247, 341, 1001, 741, 22]))