content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ (C) Guangcai Ren <rgc@bvrft.com> All rights reserved create time '2019/8/28 16:18' Module usage: 测试用例 """ import os from app import create_app # 设置配置的文件名 config_path = os.environ.get('CONFIG_NAME') or 'config_test.yml' os.environ['FLASK_CONFIG'] = os.path.dirname(os.path.dirname(__file__)...
# # Copyright 2019 The FATE 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 appli...
"""Base classes describing both classification and clustering models that can be used for training and prediction.""" from typing import Optional, Sequence import numpy as np from slub_docsa.common.document import Document class ClassificationModel: """Represents a classification model similar to a scikit-lear...
# -*- coding: utf-8 -*- """ orm types base module. """ from abc import abstractmethod from sqlalchemy import TypeDecorator from pyrin.core.exceptions import CoreNotImplementedError class CoreCustomType(TypeDecorator): """ core custom type class. all application custom types must be subclassed from thi...
def bubbleSort(l, n): for i in range(n): for j in range(n-1-i): if l[j][0] > l[j+1][0]: l[j], l[j+1] = l[j+1], l[j] return l[:] def selectionSort(l, n): for i in range(n): minj = i for j in range(i+1, n): if l[j][0] < l[minj][0]: ...
# -*- coding: utf-8 -*- ################################################################################ ## Form generated from reading UI file 'TabWater.ui' ## ## Created by: Qt User Interface Compiler version 5.14.1 ## ## WARNING! All changes made in this file will be lost when recompiling UI file! #########...
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='cryptos', version='1.36', description='Python Crypto Coin Tools', long_description=open('README.md').read(), author='Paul Martin', author_email='paulmartinforwork@gmail.com', url='http://github.com/primal1...
class TokenException(Exception): """Base class for all exceptions generated by tokenization.""" def __init__(self, *args): pass
import json import pandas as pd from cognite import _constants as constants from cognite import config from cognite._utils import InputError from cognite.v05 import timeseries class DataTransferService: """Create a Data Transfer Service object. Fetch timeseries from the api. """ # TODO: Support fi...
""" Recipes available to data with tags ['GSAOI', IMAGE']. Default is "reduce_nostack". """ recipe_tags = {'GSAOI', 'IMAGE'} from geminidr.gsaoi.recipes.sq.recipes_IMAGE import reduce_nostack _default = reduce_nostack
#!/usr/bin/env python # The MIT License (MIT) # # Copyright (c) 2015 Caian Benedicto <caian@ggaunicamp.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...
import csv import logging logger = logging.getLogger(__name__) CONSTELLATIONS = { '01': 'AND', '02': 'ANT', '03': 'APS', '04': 'AQR', '05': 'AQL', '06': 'ARA', '07': 'ARI', '08': 'AUR', '09': 'BOO', '10': 'CAE', '11': 'CAM', '12': 'CNC', '13': 'CVN', '14': 'CMA'...
from test.TestPolicy import TestPolicy __all__ = ["TestPolicy"]
# -*- coding: utf-8 -*- """ This source code file is licensed under the GNU General Public License Version 3. For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. """ from libs.AgentA...
from flask import Flask from flask_restful import Api from decouple import config as env from app.main.config import config_by_name, cache from app.main.controller.stocks import StocksController def create_app(): app = Flask(__name__) app.config.from_object(config_by_name[env('YAHOO_STOCKS_API_ENV')]) c...
# -*- coding: utf-8 -*- # from odoo import http # class OverwriteIrSequence(http.Controller): # @http.route('/overwrite_ir_sequence/overwrite_ir_sequence/', auth='public') # def index(self, **kw): # return "Hello, world" # @http.route('/overwrite_ir_sequence/overwrite_ir_sequence/objects/', auth=...
import testserver if __name__ == '__main__': app = testserver.get_from_cfg('config.py') app.run('0.0.0.0', 8080, use_reloader=False, threaded=True)
""" seed_location_table.py Seeds the location table using the geocoder function to identify the latitude and longitude for the given location. """ import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) from model import Profile, Location, db, connect_to_...
from functools import reduce lines = [] with open('input.txt', 'r') as f: for line in f: line = line.strip() lines.append(line) def everyone_yes(c, ss): for s in ss: if c not in s: return False return True counts = 0 s = set() ss = [] all_c = set() for i, line in enumerate...
# Generated by Django 2.2.10 on 2021-01-13 13:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('agents', '0014_person_meta'), ] operations = [ migrations.AddField( model_name='agent', name='radical', ...
# -------------------- # FILE NAME # -------------------- # Purpose or description # *** SOME SETUP STUFF *** # MODULES FROM PYTHON'S STANDARD LIBRARY # MODULES FROM PYPI (the Python community) # MY MODULES # SOME FUNCTIONS AND VARIABLES FOR EASY REFERENCE # *** MAIN PROGRAM STARTS HERE ***
from datetime import datetime import logging class TestStep: """Representation of a single test step. This class provides the basic block for a test. Each test can consist of multiple steps with each step being represented by instances of this class. The test step logic should be contained in the __...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html import os import sys # -- Project information ---------------------------------------...
__author__ = 'juan'
import torch import torch.nn as nn from lib.normalize import Normalize __all__ = ['Generator', 'Discriminator'] class Generator(nn.Module): """ Generator for generating hard positive samples. A three layer fully connected network. Takes (a, p, n) as input and output p'. """ d...
import logging import os import subprocess import sys import tempfile from concurrent.futures import ThreadPoolExecutor from pymongo import MongoClient from threading import Lock # Configuration for log output logger = logging.getLogger() logger.setLevel(logging.INFO) stdout_handler = logging.StreamHandler(sys.stdou...
import argparse import base64 import mimetypes import os import threading import time import webbrowser from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.parse import quote RESPONSE = "" RESPONDED = False IOMD = """ %% fetch text: fileContent={filename} %% js // You can access the file content in...
from django.contrib import admin from jobs.models import Job, WorkHistory, EducationHistory, Reference admin.site.register(Job) admin.site.register(WorkHistory) admin.site.register(EducationHistory) admin.site.register(Reference)
""" Module for random Recommender """ import numpy from overrides import overrides from lib.abstract_recommender import AbstractRecommender class RandomRecommender(AbstractRecommender): """ A class that takes in the rating matrix and oupits random predictions """ def __init__(self, initializer, evalua...
import json from typing import List from podm.podm import Box class PCOCODataset: def __init__(self): self.annotations = [] # type: List[PCOCOAnnotation] self.images = [] # type: List[PCOCOImage] self.categories = [] # type: List[PCOCOCategory] self.licenses = [] # ...
class Solution: def maxProfit(self, prices): if len(prices) < 1: return 0 min_price = prices[0] max_profit = 0 for price in prices: if price - min_price > max_profit: max_profit = price - min_price if price < min_price: ...
# ============================================================================= # HEPHAESTUS VALIDATION 7 - LINEAR ALGEBRA SOLUTION DIFFERENCES # ============================================================================= # IMPORTS: from Structures import MaterialLib, Laminate, XSect from AircraftParts import Airfoi...
#!/usr/bin/env python # -*- coding: utf-8 -*- class ErrorServiceTopLevelException(Exception): pass class ErrorValidationSmsContent(ErrorServiceTopLevelException): pass class SmsContentTypeError(ErrorValidationSmsContent): pass class SmsContentLengthError(ErrorValidationSmsContent): pass class ...
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'ImagestoreAlbumCarousel.height' db.delete_column('cmsplugin_imagestorealbumcarousel', 'h...
from copy import deepcopy import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from .attention import Self_Attn2D def normalize_imagenet(x): ''' Normalize input images according to ImageNet standards. Args: x (tensor): input image...
from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.db import models from django.db.models import functions, Q, Subquery from django.urls import reverse from django.utils import timezone from django.utils.translation import gettext_lazy as _ UNIT_SEEDS = 's'...
from flask import Flask, render_template, request, url_for, redirect, flash, session, Response from flask_cors import * app = Flask(__name__) fuck = 'what are you fucking doing' # -------------------------------------------------- # -------------------------------------------------- # ---------------------------------...
import logging import os import subprocess import glob import sys from shutil import copyfile import pdftotext import PyPDF2 from wand.image import Image as WandImage log = logging.getLogger(__name__) def convert_pdf_to_tif(source_file, output_dir): """ Create a TIF for every Page in the PDF and saves th...
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Science/NewtonsThirdLaw/newtons-third-l...
import torch.nn as nn from abc import ABC, abstractmethod class LossEvaluator(ABC): @abstractmethod def compute_batch(self, model, image_array, label_array): pass def compute_individual(self, model, image, label): return self.compute_batch( model, image.unsqueeze(0), label.un...
# import json import os from dotenv import load_dotenv from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # """ # translator.py connects to ibm_watson # language translator and converts English # to French and vice versa using functions # frenchToEnglish and eng...
import datetime import time import pytz from dateutil import relativedelta def datetime_str_to_timestamp(datetime_str, tz=None): dt = datetime.datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S') return datetime_to_timestamp(dt, tz) def datetime_to_timestamp(dt, tz=None): if tz: dt = pytz.timez...
""" Write the INTDER main and auxiliary input file """ import automol.geom import intder_io._util as intder_util def input_file(geo, zma=None): """ Write the main INTDER input file. Currently just supports a basic harmonic frequency and total energy distribution calculation. :param geo: ...
a = 5 b = 5 print(a + b) for number in [1, 2, 3, 4, 5, 6]: print(number, end=' ')
import decimal import sys #For the ratio, we want to look at the number of packs opened to percentage finished #What is the best number of packs to open to get the best dupes/(packs*itemsPerPack) completeSet=12 packs=28 itemsPerPack=1 #============================================Math Way# decimal.getcontext().prec ...
from sklearn import preprocessing from sklearn.cluster import KMeans from sklearn.decomposition import PCA import seaborn as sns import numpy as np import pandas as pd def loudness_scaled(songs): loudness = songs[['loudness']].values min_max_scaler = preprocessing.MinMaxScaler() loudness_scaled =...
import json from .GiteaUserCurrentEmails import GiteaUserCurrentEmails from .GiteaUser import GiteaUser class GiteaUserCurrent(GiteaUser): def __init__(self, client): super(GiteaUserCurrent, self).__init__(client) self.is_current = True def follow(self, username): try: s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.contrib.gis.db.models.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='CongressionalDistrict', ...
#!/usr/bin/env python # Author: veelion import time import pickle import requests from selenium import webdriver from selenium.webdriver.common.keys import Keys def save_cookies(cookies, file_to_save): with open(file_to_save, 'wb') as f: pickle.dump(cookies, f) def login_auto(login_url, username, passw...
"""DGL Distributed Training Infrastructure.""" from __future__ import absolute_import from ._ffi.function import _init_api from .nodeflow import NodeFlow from .utils import unwrap_to_ptr_list from . import utils _init_api("dgl.network") def _create_sender(): """Create a Sender communicator via C api """ ...
from enum import Enum """ OCP = open for extension, closed for modification """ class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 class Size(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 class Product: def __init__(self, name, color, size) -> None: self.name = name self.color = color...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class MassMailing(models.Model): _name = 'mail.mass_mailing' _inherit = 'mail.mass_mailing' sale_quotation_count = fields.Integer('Quotation Count', compute='_compute_...
import paho.mqtt.client as mqtt import shortid import json import conf import values def createAE(): req_message = {} req_message['m2m:rqp'] = {} req_message['m2m:rqp']['op'] = 1 # create req_message['m2m:rqp']['to'] = conf.ae.parent req_message['m2m:rqp']['fr'] = conf.ae.id req_...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # --------------------------------------------------------- import os from ._constants import USER_FACING_NAME, TRACEPARENT_ENV_VAR from ._span import Span from ._vendored import _execution_co...
import requests import semver import os from urllib.parse import urlsplit from .errors import MyError def check(config): checkUrl = urlsplit(config["publishLink"])._replace( path = "/api/version", query = None ).geturl() resp = requests.get(checkUrl) myVersionInfo = semver.parse_version_info(config["version"...
# -*- coding: utf-8 -*- """ Created on Thu Oct 25 00:16:05 2018 @author: Haider Raheem """ import random def throwUntil(x): """ input sum: x, 2<=x<=12 random input for die1 and die2 rolled counts time rolled to get sum """ count = 0 die1 = 0 die2 = 0 while die1 + ...
import audalign as ad import pytest import pickle test_file_eig = "test_audio/test_shifts/Eigen-20sec.mp3" test_file_eig2 = "test_audio/test_shifts/Eigen-song-base.mp3" test_folder_eig = "test_audio/test_shifts/" class TestAlign: ada = ad.Audalign(num_processors=4) @pytest.mark.smoke def test_align_fing...
from game import Game g = Game([]) g.flop() g.turn() g.river()
from three.core import Uniform, UniformList class Fog(object): # fog effect is applied with 0% opacity at startDistance from camera, # increasing linearly to 100% opacity at endDistance from camera def __init__(self, startDistance=1, endDistance=10, color=[0,0,0]): self.uniformList = UniformLis...
# -*- coding: utf-8 -*- import unittest from matplotlib import rcParams import matplotlib.pyplot as plt import numpy as np from pprint import pprint as print __updated__ = "2021-06-11" class TestFuncat2TestCase(unittest.TestCase): def test_rank(self): my_array = np.array([[1, 56, 55, 15], ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 27 20:39:40 2020 @author: kant # Daily Challenge #2 - String Diamond Your task is to return a string that displays a diamond shape on the screen using asterisk (“*”) characters. The shape that the print method will return should resemble a diam...
import stripe from stripe import api_requestor from stripe import util from async_stripe.api_resources.abstract import patch_custom_methods async def capture_patch(self, idempotency_key=None, **params): url = self.instance_url() + "/capture" headers = util.populate_headers(idempotency_key) self.refresh_fr...
# Copyright (c) 2018, Oracle and/or its affiliates. # Copyright (C) 1996-2017 Python Software Foundation # # Licensed under the PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 import seq_tests #import pickle from compare import CompareTest class TupleTest(seq_tests.CommonTest): type2test = tuple def test_constr...
"""Test double linked list implementation.""" import pytest @pytest.fixture def test_lists(): """Dll fixtures.""" from src.dll import DoubleLinkedList empty = DoubleLinkedList() one = DoubleLinkedList(3) multi = DoubleLinkedList([1, 2, 3, 4, 5]) return empty, one, multi def test_node_class(...
### -------------------------------------- ### Airflow scheduler ### Angel Valera Motos - P2 - CC ### -------------------------------------- ### # incluimos las bibliotecas necesarias from datetime import timedelta from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators....
# Generated by Django 3.0.3 on 2020-02-10 22:47 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('helpdesk', '0004_queuequ...
"""A parser for reading VLBI eccentricity vectors from file Description: ------------ Reads the VLBI eccentricity vector from file. """ # Standard library imports from datetime import datetime import re # Midgard imports from midgard.dev import plugins from midgard.parsers._parser_line import LineParser @plugins...
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
from django.shortcuts import render from mailer.models import Person, MailTemplate from django.http import HttpResponse from django.core.mail import send_mail import csv from google_forms_mailer import settings # Create your views here. def home(request): ''' Home page view ''' template = "index.html" return rend...
import glob import os from flask import json APP_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..') class FileHandler(object): def __init__(self, username, image_names): if not os.path.exists(APP_ROOT + '/annotations'): os.makedirs(APP_ROOT + '/annotations') if not...
#!/usr/bin/env python # # Copyright 2018 Verily Life Sciences 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 a...
#!/usr/bin/env python ############################################################################## # # diffpy.structure by DANSE Diffraction group # Simon J. L. Billinge # (c) 2008 trustees of the Michigan State University. # All rights reserved. # # File coded b...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2016 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this ...
# Generated by Django 3.0.8 on 2020-07-23 22:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20200723_1611'), ] operations = [ migrations.AlterField( model_name='projecttemplate', name='image'...
#!/usr/bin/python3 import multiprocessing import sys import random from time import sleep def progressbar(width,min,max,current,text=""): hashcount = int(current/((max-min)/width)) fmt = "[%-"+str(width)+"s]" sys.stdout.write("\r") sys.stdout.write("\033[K") sys.stdout.write(fmt % ('#'*hashcount)) sys.stdout.wr...
from pathlib import Path import collections import deepdish as dd import mne from autoreject import (get_rejection_threshold, AutoReject) def autoreject_repair_epochs(epochs, reject_plot=False): """Rejects the bad epochs with AutoReject algorithm Parameters ---------- epochs : mne epoch object ...
# Copyright (c) 2021, Roona and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document from frappe.utils import (strip) class DeliveryArea(Document): def autoname(self): self.area_name = strip(self.area_name) self.name = self.area_name
from lixian_plugins.api import command from lixian_cli_parser import parse_command_line from lixian_config import get_config from lixian_encoding import default_encoding def b_encoding(b): if 'encoding' in b: return b['encoding'] if 'codepage' in b: return 'cp' + str(b['codepage']) return 'utf-8' def b_name(...
import numpy as np np.set_printoptions(sign=' ') print(np.eye(*map(int, input().split()))) """It 'unpacks' the elements in the list returned from [ int(x) for x in input().split() ]"""
__author__ = 'saeedamen' # Saeed Amen # # Copyright 2016 Cuemacro # # 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 l...
import importlib from musicxml.tests.util import MusicXmlTestCase from musicxml.xsd.xsdindicator import XSDSequence, XSDChoice from musicxml.xsd.xsdcomplextype import * from musicxml.xsd.xsdattribute import * from musicxml.xsd.xsdcomplextype import XSDComplexType from musicxml.xsd.xsdsimpletype import * from musicxml...
# 1. if node v has not been visited, then mark it as 0. # 2. if node v is being visited, then mark it as -1. If we find a vertex marked as -1 in DFS, then their is a ring. # 3. if node v has been visited, then mark it as 1. If a vertex was marked as 1, then no ring contains v or its successors. class Solution: def...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from .. import TestUnitBase class TestPHPDeserializer(TestUnitBase): def test_reversible_property(self): data = {"42": True, "A to Z": {"0": 1, "1": 2, "2": 3}} ds = self.load() self.assertEqual(json.dumps(data) | -ds | ds | json...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from swagger_server.models.base_model_ import Model from swagger_server import util class ModelFlowChartNodeLinkedEdges(Model): """NOTE: This class is auto genera...
from django.urls import include, path from . import views app_name = 'main' urlpatterns = [ path('', views.index, name='index'), path('help', views.help, name='help'), path('details/<int:pk>/', views.details, name="details"), path('overview', views.overview, name='overview'), path('tools', views.pu...
# Databricks notebook source NRJXFYCZXPAPWUSDVWBQT YVDWRTQLOHHPYZUHJGTDMDYEZPHURUPFXD GMJLOPGLOTLZANILIDMCJSONOTNIZDYVSV HBUSZUHKJSRCMJQSJKGFSQAYLKPJUVKGUY FMJLCEHCNOQLGHLULYDPRUZUKMTWRBTLRASSIVMJ VJGQUSEDKRWDPXYLJMEEAMLNVBGMBVKRIYPGRJCKYKZX BLTCKGNOICKASIVEPWO RUJYBXAOS WGKYLEKOZP EKBYFUATSAEHQVRGCOHWHQVRMTEPOYLWLMCV...
# -*- coding: utf-8 -*- import os import shutil from functions import counter def slurp(filePath): with open(filePath) as x: data = x.read() return data # same as slurp but return Array of lines instead of string def slurpA(filePath): with open(filePath) as x: data = x.read().splitlines() return data ...
#!/usr/bin/env python # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Runs multiple commands concated with '&&'. This script exists to avoid using complex shell commands in gcc_toolchain.gni's tool("so...
from qtpy.QtWidgets import QWidget, QPushButton, QSpacerItem, QSizePolicy, QHBoxLayout, QVBoxLayout, QLabel from qthandy import vbox, clear_layout, hbox, margins, flow, FlowLayout def test_clear_layout(qtbot): widget = QWidget() qtbot.addWidget(widget) widget.show() layout = vbox(widget) layout....
import os.path as op import subprocess import sys import numpy as np import pandas as pd def test_compartment_cli(request, tmpdir): in_cool = op.join(request.fspath.dirname, 'data/sin_eigs_mat.cool') out_eig_prefix = op.join(tmpdir, 'test.eigs') try: result = subprocess.check_output( ...
import sys sys.path.append('src') from Constants import PathFinder # noqa autopep8 finder = PathFinder() class TestPathFinder(): def test_init(self): assert type(PathFinder()).__name__ == 'PathFinder' def test_get_symbols_path(self): assert finder.get_symbols_path() == 'data/s...
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the ...
import numpy as np import tensorflow as tf import ast import os from tensorflow.python import pywrap_tensorflow from matplotlib import pyplot from matplotlib.pyplot import imshow import image_utils import model import ops import argparse import sys num_styles = 32 imgWidth = 512 imgHeight = 512 channel = 3 checkpoi...
from introductoryproblems.increasing_array import * class TestIncreasingArray: def test_case_1(self): assert solve([3, 2, 5, 1, 7]) == 5
import unittest # Add the parent directory to the path for the import statement import os import sys import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) # Now do the import from translator import ...
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ This script is a template for a workbench script. """ from kagura.getlogger import logging from kagura.safetynet import safetynet from kagura.utils import start_end_log from kagura.getarg import get_args from kagura import processqueue @start_end_log def main(): ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Custom recipe for Multisheet Export to Existing Excel Template """ import logging from pathvalidate import ValidationError, validate_filename import dataiku from dataiku.customrecipe import get_input_names_for_role from dataiku.customrecipe import get_output_names_for_ro...
from django.core.exceptions import ValidationError def username_validator(username): # check if username starts with '@' if username[0] != '@': raise ValidationError('This field should start with \'@\'.')