text
stringlengths
2
999k
import sys import os import subprocess inputArgs = sys.argv # set filenames bimName = sys.argv[2] samName = sys.argv[4] evtName = sys.argv[6] edpName = sys.argv[8] simName = sys.argv[10] scriptDir = os.path.dirname(os.path.realpath(__file__)) #If requesting random variables run getUncertainty #Otherwise, Run Opense...
from sklearn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("MLPClassifier" , "BinaryClass_10" , "oracle")
import hashlib # 生成 api 签名 class ApiSign: def __init__(self, app_key: str = '', app_secret: str = ''): self.app_key = app_key self.app_secret = app_secret def get_sign(self, user_token = "", **params): # user_token: 用户 token 参数 (可选) # params: request dict # 删除 sign ...
from dile import Dile from pprint import pprint from numpy import array, floor ''' could be useful | | | V V V ''' # Returns the sub-tree of a given dile up to "sublevels" level # as a vector of dile objects def fromSubTree(d, sublevels, vec): ''' dile splitted in 4 regions: *--------* |no | ne |...
''' main issue here was to global patforrec. youll probs forget. ''' import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as mticker import matplotlib.dates as mdates import numpy as np from numpy import loadtxt import time totalStart = time.time() date,bid,ask = np.loadtxt('GBPUSD1d.txt', u...
########################################################################## # MediPy - Copyright (C) Universite de Strasbourg # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for de...
#!/usr/bin/python # -*- coding: utf8 -*- # import mymodule # ^^^^^^^^^^^^^^^ <- no need to import module # # for more info, please see the references - this is just an ugly demo def bar(d): usleep(500000) # there isn't function by this name in std Python print d print type(d) return int(d['a'] + d['b'...
import torch.nn as nn import torch.nn.functional as F from base import BaseModel import pdb import torch import math class AttentionPDEModel(nn.Module): def __init__(self,ndim,T,device_num = 0): super(AttentionPDEModel, self).__init__() # W_x = torch.randn(ndim, ndim, requires_grad=True) # ...
from sqlalchemy import engine_from_config from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import configure_mappers import zope.sqlalchemy # import or define all models here to ensure they are attached to the # Base.metadata prior to any initialization routines from ..models import model # flake8: noqa # r...
from tamarco.resources.basic.metrics.reporters.base import CarbonBaseHandler def test_base_handler_creation_no_metric_prefix(): base_handler = CarbonBaseHandler() assert base_handler.metric_prefix == "" def test_base_handler_creation_metric_prefix(): base_handler = CarbonBaseHandler("test") assert b...
from typing import List import warnings class TableField: def __init__(self, name: str, description: str = '', is_pii: bool = False) -> None: self.name = name self.description = description self.is_pii = is_pii def __str__(self): return self.name def __eq__(self, __o: obj...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # "Parsing Inputs" - a chapter of "The Fuzzing Book" # Web site: https://www.fuzzingbook.org/html/Parser.html # Last change: 2022-02-09 08:25:36+01:00 # # Copyright (c) 2021 CISPA Helmholtz Center for Information Security # Copyright (c) 2018-2020 Saarland University, aut...
""" WSGI config for uuidproject project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_S...
#!/usr/bin/env python # filter_qc 0.0.1 # Generated by dx-app-wizard. # # Basic execution pattern: Your app will run on a single machine from # beginning to end. # # See https://wiki.dnanexus.com/Developer-Portal for documentation and # tutorials on how to modify this file. # # DNAnexus Python Bindings (dxpy) documenta...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Ship() result.template = "object/ship/shared_decimator_tier3.iff" result.attribute_template_id = -1 result.stfNa...
from collections import Iterable from mathsat import msat_term, msat_env from mathsat import msat_make_true, msat_make_false from mathsat import msat_make_constant, msat_declare_function from mathsat import msat_get_rational_type from mathsat import msat_make_and as _msat_make_and from mathsat import msat_make_or as _...
n = int(input('Digite um número: ')) d = n * 2 t = n * 3 r = n ** (1/2) print(f'O número digitado é {n}. \n Seu dobro é {d}. \n Seu triplo é {t}. \n Sua raiz quadrada é {r:.2f}')
from .collections import DottedDict from .diagnostics_manager import DiagnosticsManager from .edit import apply_edits from .edit import parse_workspace_edit from .edit import TextEditTuple from .file_watcher import DEFAULT_KIND from .file_watcher import file_watcher_event_type_to_lsp_file_change_type from .file_watcher...
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Utilities to track training progress in terms of epochs, batches, samples, and tokens. Callbacks, algorithms, and schedulers can use the current training time to fire at certain points in the training process. The :class:`~.time.Time...
import pytz import six import pandas as pd from ..instruments import Instrument class LocalDataSource: DAILY = 'daily.bcolz' INSTRUMENTS = 'instruments.pk' DIVIDEND = 'dividend.bcolz' TRADING_DATES = 'trading_dates.bcolz' YIELD_CURVE = 'yield_curve.bcolz' YIELD_CURVE_TENORS = { 0: 'S...
""" View more, visit my tutorial page: https://mofanpy.com/tutorials/ My Youtube Channel: https://www.youtube.com/user/MorvanZhou Dependencies: torch: 0.4 torchvision """ import torch import torch.nn as nn import torch.utils.data as Data import torchvision # torch.manual_seed(1) EPOCH = 1 BATCH_SIZE = 50 LR = 0.001 ...
import os import random from functools import reduce from collections import namedtuple from web3 import Web3 from raiden_contracts.constants import SETTLE_TIMEOUT_MIN from raiden_contracts.utils.merkle import compute_merkle_tree, get_merkle_root from eth_abi import encode_abi MAX_UINT256 = 2 ** 256 - 1 PendingTran...
"""New standard I/O library. Based on sio.py from Guido van Rossum. - This module contains various stream classes which provide a subset of the classic Python I/O API: read(n), write(s), tell(), seek(offset, whence=0), readall(), readline(), truncate(size), flush(), close(), peek(), flushable(), try_to_find_fil...
def read_header(file_path, delimiter="\t"): hdr = {} f = open(file_path,"r") line = f.readline() if line is None: return hdr columns = line.rstrip().split(delimiter) indices = {} for i, col_name in enumerate(columns): indices[col_name] = i hdr["names"] = columns hdr["indices"] = indices f.close() return ...
import argparse import os, sys import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn import torchvision from torchvision import transforms from PIL import Image import numpy as np from tqdm import tqdm from sklearn.cluster import KMeans from scipy.stats import ortho_group ...
# Copyright The PyTorch Lightning team. # # 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 i...
import os from json import loads snyk_config = loads("""{ "OrginisationMap": [ { "Name": "FirstChecked-Org", "Matcher": "1-*" }, { "Name": "SecondChecked-Org", "Matcher": "2-*" }, { "Name": "CatchAll-Org", "Matcher": "*" } ] }""") def get_snyk_token(): return os.environ.get('SECRET...
''' Copyright 2020 Xilinx Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softw...
"""Defines forms related to rooms.""" from flask_login import current_user from sqlalchemy.exc import IntegrityError from wtforms import StringField from base.forms import ApiForm from base.forms.validators import DataRequired, DataLength from database import db_session from errors import unable_to_generate_token fro...
#!/usr/bin/env python3 """Combine logs from multiple bitcoin nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile. If no argument is provided, the most recent test directory will be used.""" import argparse from collection...
# # Copyright (C) 2019 GreenWaves Technologies # # 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 agre...
''' A wrapper over the Slack API. ''' __author__ = 'Alex Bertsch' __email__ = 'abertsch@dropbox.com' import logging from slackclient import SlackClient from securitybot.user import User from securitybot.chat.chat import Chat, ChatException from typing import Any, Dict, List class Slack(Chat): ''' A wrapper ...
import uuid from datetime import datetime from sqlalchemy.orm.scoping import scoped_session import factory import factory.fuzzy from app.extensions import db # import SQLAlchemy model GUID = factory.LazyFunction(uuid.uuid4) TODAY = factory.LazyFunction(datetime.now) FACTORY_LIST = [] class FactoryRegistry: d...
""" Example demonstrating how to add DID with the role of Trust Anchor to ledger. Uses seed to obtain Steward's DID which already exists on the ledger. Then it generates new DID/Verkey pair for Trust Anchor. Using Steward's DID, NYM transaction request is built to add Trust Anchor's DID and Verkey on the ledger with th...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 30.03.2018 16:35 :Licence MIT Part of grammpy """ from unittest import main, TestCase from grammpy import * from grammpy.parsers import cyk from grammpy.transforms import ContextFree, InverseContextFree class S(Nonterminal): pass class My: def __init_...
from default_config import basic_cfg import albumentations as A import os import pandas as pd import cv2 cfg = basic_cfg cfg.debug = True # paths cfg.name = os.path.basename(__file__).split(".")[0] cfg.data_dir = "/raid/landmark-recognition-2019/" cfg.train cfg.data_folder = cfg.data_dir + "train/" cfg.train_df = "/...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
import _plotly_utils.basevalidators class ConeValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="cone", parent_name="", **kwargs): super(ConeValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_s...
def resolve_name(name): """ Imports a specific object from a dotted path and returns just that object. From nose.utils.resolve_name (with the logging parts taken out) which in turn is from unittest.TestLoader.loadTestByName """ parts = name.split('.') parts_copy = parts[:] while parts_c...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2018-10-01 15:31 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependen...
# encoding:utf-8 import requests import redis appId = "18037773" apiKey = "opPSLkjXliSrYXfrKizsFGiC" secretKey = "tfXgvzAcGXoasQmnoRvElWBPRsleOFbg" ### {'refresh_token': '25.3cb47937a3d79c0552463462d73e9438.315360000.1891850261.282335-18037773', 'expires_in': 2592000, 'session_key': '9mzdCPA10u7tfQacqSQuqSRdb3SIkZjC...
# Ajuste de funções import numpy as np import matplotlib.pyplot as plt def aj_lin(xi, yi): ''' Realiza o ajuste linear de pontos em uma reta de ajuste no formato "y = ax + b" :param xi: coordenadas x dos pontos :param yi: coordenadas y dos pontos :return: coeficiente angular "a" e coeficiente line...
# Copyright 2012 Pinterest.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ######################################################## # ____ _ __ # # ___ __ __/ / /__ ___ ______ ______(_) /___ __ # # / _ \/ // / / (_-</ -_) __/ // / __/ / __/ // / ...
import os import codecs from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) def read(*parts): # intentionally *not* adding an encoding option to open return codecs.open(os.path.join(here, *parts), 'r').read() setup( name='backtrace', version="0.2.1", url='https://gith...
############################################################################### ## ## Copyright (c) Crossbar.io Technologies GmbH ## ## 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...
import streamlit as st import time import numpy as np import pandas as pd from aegis_datagen import build_constant_val_msg_stream @st.cache def get_data(): AWS_BUCKET_URL = "s3://h1st-tutorial-autocyber/attack-samples" df = pd.read_parquet(AWS_BUCKET_URL + "/20181114_Driver2_Trip1-0.parquet") return df d...
N = int(input()) A = list(map(int, input().split())) rev = 0 for i in range(N): rev += 1 / A[i] print(1 / rev)
# -*- coding: utf-8 -*- """ pygments.styles.pastie ~~~~~~~~~~~~~~~~~~~~~~ Style similar to the `pastie`_ default style. .. _pastie: http://pastie.caboo.se/ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style impor...
import math import operator import os import pickle import re import sys import traceback import uuid import warnings from bisect import bisect from collections.abc import Iterable, Iterator, Mapping from functools import partial, wraps, reduce from itertools import product, zip_longest from numbers import Number, Inte...
''' ********************************************************************** * Author : Ala Rmida * E-mail : ala.rmida.ingen@gmail.com * website : https://ala-rmida-ann1998.netlify.app/ ********************************************************************** ''' #!/usr/bin/env python3 import RPi.GPIO...
""" Transform functions for Tomography in Numpy, Scipy, Torch, and Skimage Estimates affine transform between measured image and predicted image https://github.com/scikit-image/scikit-image David Ren david.ren@berkeley.edu Dec 28, 2020 """ import numpy as np import torch from skimage.registration import optical...
import numpy as np import tensorflow as tf from tensorflow.contrib import rnn def _print_success_message(): print('Tests Passed') def test_create_lookup_tables(create_lookup_tables): with tf.Graph().as_default(): test_text = ''' Moe_Szyslak Moe's Tavern Where the elite meet to drink ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
#!/usr/bin/env python #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- from collections import namedtuple import codecs, sys import subprocess import os.path as path from .unit_test import unit_test class program_unit_test(unit_test): def _make_command(self, program, arg...
"""Drawing multiple plots in a single figure""" import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec def make_space_above(axes, topmargin=1): """ increase figure size to make topmargin (in inches) space for titles, without changing the axes sizes""" fig = axes.flatten()...
from django.db import models class Feedback(models.Model): name = models.CharField(max_length=30, blank=False) email = models.EmailField() message = models.TextField(max_length=1000, blank=False) def __str__(self): return '%s - %s' % (self.name, self.email) class Project(models.Model): ...
# Copyright 2011 OpenStack Foundation # 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 requ...
from Optimizador.C3D import * t = -1 e = -1 def getEncabezado(): content = "from goto import with_goto\n" content += "from Instrucciones.TablaSimbolos.Tabla import Tabla\n" content += "from Instrucciones.Sql_insert import insertTable\n" content += "from Instrucciones.TablaSimbolos.Arbol import Arbol\n...
import re def double_substring(line): matches = re.findall(r'(.+)(?=.*\1)', line) largest = '' if not matches else max(matches, key=lambda m: len(m)) return len(largest)
from pprint import pprint class Config: lr = 0.1 resume = False checkpoint = '/home/claude.cy/file/ssd/checkpoint/' data_root = '/home/claude.cy/.data/all_images' voc07_trainval = 'torchcv/datasets/voc/voc07_trainval.txt' voc12_trainval = 'torchcv/datasets/voc/voc12_trainval.txt' voc07_test...
# -*- coding: utf-8 -*- from __future__ import ( absolute_import, division, print_function, unicode_literals) import base64 import datetime import json from builtins import str import mock from allauth.socialaccount.models import SocialAccount from django.contrib.auth.models import User from django.core.urlresolv...
""" Copyright 2012 Illumina Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
# ========================================================================= # # Copyright 2018 National Technology & Engineering Solutions of Sandia, # LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, # the U.S. Government retains certain rights in this software. # # Licensed under the Apache...
# -*- coding: utf-8 -*- """CCXT: CryptoCurrency eXchange Trading Library (Async)""" # ----------------------------------------------------------------------------- __version__ = '1.19.55' # ----------------------------------------------------------------------------- from ccxt.async_support.base.exchange import Ex...
#!/usr/bin/env python3 # Copyright (c) 2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test tx status in case of reorgs while wallet being shutdown. Wallet txn status rely on block connection/d...
name = 'pizzacutter' title = 'create and update projects from project templates' version = 'v1.1.9' url = 'https://github.com/bitranox/PizzaCutter' author = 'Robert Nowotny' author_email = 'bitranox@gmail.com' shell_command = 'pizzacutter' def print_info() -> None: print("""\ Info for PizzaCutter: create an...
"""contains forms related to creating customized tests.""" from flask_wtf import FlaskForm from wtforms import (RadioField, SelectMultipleField, StringField, SubmitField, widgets) from wtforms.validators import DataRequired, url from mod_regression.models import RegressionTest from mod_test.model...
# coding: utf-8 import unittest import mock from cinepass.client.v4 import cities SERVER_RESPONSE = { "cities": [ { "id": "1", "name": "Berlin", "slug": "berlin", "lat": 52.50735, "lon": 13.42855, "country": "DE" }, {...
''' enethpath computes the elastic net (EN) regularization path (over grid of penalty parameter values). Uses pathwise CCD algorithm. INPUT: y : Numeric 1darray of size N (output, respones) X : Nnumeric 2darray of size N x p. Each row represents one observation, and each column represent...
"""Unit tests for decorators.""" import pytest from taukit.base.decorators import interface @interface({ 'x': {'type': 'string'}, 'y': {'type': 'integer'} }) def tfunc(x, y, z): return x*(y+int(z)) tfunc2 = interface({'z': {'type': 'integer'}})(tfunc) class A: @interface({ 'x': {'type': 'str...
import nibabel as nib from tqdm import tqdm from scipy.ndimage import label, generate_binary_structure from pathlib import Path import json import numpy as np from ivadomed import postprocessing as imed_postpro from typing import List def run_uncertainty(image_folder): """Compute uncertainty from model prediction...
# Time: 93 ms # Memory: 12 KB n = int(input()) flst = ["I hate", "I love"] * n clst = [" that"] * n for i in range(n): if i == n - 1: clst[i] = " it" sol = flst[i] + clst[i] print(sol, end = " ")
""" Copyright (c) <'2020'> <'Alrick Grandison'> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial appl...
# Copyright (c) 2020 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 applic...
## # Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U. # 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...
# Copyright 2020 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import textwrap import pytest from .common import ( precollected, researcher, researchers, some_other_paper, some_paper, ) def test_bibtex(some_paper): expected = textwrap.dedent( """ @inproceedings{merrienboer2018-differentiation97, author = {Bart van Merrienboer...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="knowledge-distillation", version="0.0.1", author="Aljo", author_email="aljo@novasolution.net", description="knowledge distillation", long_description=long_description, long_descrip...
import sublime_plugin import threading def toggle_table_mode(view, on=True): if on: view.settings().set("AlignTabTableMode", True) view.set_status("aligntab", "[Table Mode]") else: view.settings().erase("AlignTabTableMode") erase_table_rows(view) view.set_status("aligntab", "") def get_table_rows(view):...
from __future__ import absolute_import, division, print_function, with_statement from __future__ import unicode_literals import re from copy import deepcopy from deepstreampy.utils import Undefined, num_types SPLIT_REG_EXP = r"[\.\[\]]" def get(data, path, deep_copy): node = data tokens = _tokenize(path) ...
import uuid import urllib import urlparse from datetime import datetime from time import time import oauth2 as oauth from Crypto.PublicKey import RSA from django.db import models from oauth_provider.compat import AUTH_USER_MODEL, get_random_string from oauth_provider.managers import TokenManager from oauth_provider.co...
import numpy as np import codecs import os import random from keras import backend as K from keras.models import Model from keras.layers.embeddings import Embedding from keras.layers import Input, Dense, Lambda, Permute, Dropout from keras.layers import Conv2D, MaxPooling1D def load_data(fpath, label): data = [] ...
# -*- coding: utf-8 -*- # flake8: noqa VERSION = (0, 3, 1) # PEP 386 __version__ = ".".join([str(x) for x in VERSION]) from gmaps.geocoding import Geocoding from gmaps.directions import Directions from gmaps.timezone import Timezone from gmaps.elevation import Elevation
import math import unittest class PowTest(unittest.TestCase): def powtest(self, type): if type != float: for i in range(-1000, 1000): self.assertEqual(pow(type(i), 0), 1) self.assertEqual(pow(type(i), 1), type(i)) self.assertEqual(pow(type(0), 1)...
# ctfpwn/misc - misc routines do do misc stuff :) def get_character_set(lc=True, uc=True, nb=True, sc=True): """ returns string of characters for misc iterations lc - lowercase uc - uppercase nb - numbers sc - special characters """ lc_char_set = 'abcdefghijklmnopqrstuwvyxz' uc_cha...
s = input() list_data = list(s) check_cal = False result = 1 list_data.sort() print(list_data) for idx in range(len(list_data)): if list_data[idx] == '0': continue if check_cal == False and list_data[idx] == '1': result += 1 else: check_cal = True result *= int(list_data[i...
"""View Helper Module.""" from jinja2 import Markup def set_request_method(method_type): """Return an input string for use in a view to change the request method of a form. Arguments: method_type {string} -- Can be options like GET, POST, PUT, PATCH, DELETE Returns: string -- An input s...
# Copyright (c) 2018 Cloudify Platform Ltd. 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 ap...
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/kennethreitz/setup.py/blob/master/setup.py # Note: To use the 'upload' functionality of this file, you must: # $ pip install twine import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command # Pack...
import unittest from models import news News = news.News class NewsTest(unittest.Testcase): ''' Test Class to test the behaviour of the News class ''' def setUp(self): ''' Set up method that will run before every Test ''' self.new_news = News(1234,'Python Must Be Crazy'...
# Copyright (c) 2013 Mirantis Inc. # # 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 writ...
from __future__ import absolute_import from flytekit.common.mixins import registerable as _registerable from flytekit.common import interface as _interface, nodes as _nodes, sdk_bases as _sdk_bases import six as _six class ExampleRegisterable(_six.with_metaclass(_sdk_bases.ExtendedSdkType, _registerable.Registerable...
# python3 # Copyright 2018 DeepMind Technologies Limited. 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 re...
""" Django settings for Django project. Generated by 'django-admin startproject' using Django 2.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Bu...
# -*- coding: UTF-8 -*- # Copyright 2015-2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) # go gfktest # python manage.py test from __future__ import unicode_literals from builtins import str # from lino.utils.test import DocTest from lino.utils.djangotest import WebIndexTestCase from django.db impo...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib import os # automatically import any Python files in the models/huggingface/ directory models_dir = os.path.dirname(__file_...
# coding=utf-8 # Copyright 2021 The HuggingFace Team. 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 requir...
from runsuite import * class DriverTestMysql(DriverTestBase): def test_invalid_db(self): with self.assertRaises((AuthenticationError, IOError)): self.connect(database = self.options['_database']) def test_invalid_user(self): with self.assertRaises(AuthenticationError): self.connect(user = self.options['_...
from __future__ import absolute_import, unicode_literals import collections import functools import operator from celery import shared_task from url_shortener.models import Link @shared_task def get_daily_information(slug): data = Link.objects.get(short_slug=slug) device_dict = data.views_count_devices[0] ...