content
stringlengths
5
1.05M
#!/usr/bin/env python3 # # Copyright (c) 2020 Roberto Riggio # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
import numpy import sys from scipy import interpolate from PyQt5.QtGui import QPalette, QColor, QFont from PyQt5.QtWidgets import QMessageBox from orangewidget import gui from orangewidget.settings import Setting from oasys.widgets import gui as oasysgui from oasys.widgets import congruence from oasys.util.oasys_ut...
import os import torch import torch.utils.data as data import torch.utils.data.distributed import torchvision.transforms as transforms import torchvision.datasets as datasets from PIL import Image import sys #sys.path.append('/home/choi574/cocoapi/PythonAPI') sys.path.append('/mnt/lls/local_export/3/home/choi574/cocoa...
from os import getenv from webapp import create_app from argparse import ArgumentParser app = create_app(getenv('FLASK_CONFIG') or 'development') def main(): parser = ArgumentParser() parser.add_argument("-p", "--port", help="port number") args = parser.parse_args() port = int(args.port or 5000) ...
import UMLS_Api_search_example.GUI import UMLS_Api_search_example.UMLSAPI def runExample(api_key): umls_api_object = UMLS_Api_search_example.UMLSAPI.UMLSAPI(api_key=api_key) UMLS_Api_search_example.GUI.GUI(umls_api_object) # search_term = input('Insert search term: ') # umls_api_object.search(search_t...
import json, os, pandas as pd, numpy as np, csv from datasets import load_dataset from collections import Counter import requests, zipfile, tarfile import utils_scorer, utils_misc # SummaC Benchmark class SummaCBenchmark: def __init__(self, benchmark_folder="/home/phillab/data/summac_benchmark/", dataset_names=["...
import numpy as np import tensorflow as tf from tf_stft import Spectrogram, Logmel def ConvBlock(out_channels, pool_size): return tf.keras.Sequential([ tf.keras.layers.Conv2D(filters=out_channels, kernel_size=(3, 3), strides=(1, 1), padding='same', data_format='channels_first', activation='linea...
FACEBOOK_BASE_API = "https://graph.facebook.com" FACEBOOK_VERSION_API = "v7.0" REPORT_ENDPOINT_PATTERN = { 'FACEBOOK_ACCOUNT_REPORT': "{network_id}/insights" }
def test_data_asset_citations(pandas_dataset): citation_date = "2020-02-27T12:34:56.1234Z" pandas_dataset.add_citation("test citation", citation_date=citation_date) suite = pandas_dataset.get_expectation_suite() assert suite.meta["citations"][0] == { "comment": "test citation", "batch_kw...
from __future__ import division from __future__ import print_function import os import hashlib import paddle import paddle.nn as nn def make_divisible(v, divisor, min_val=None): if min_val is None: min_val = divisor new_v = max(min_val, int(v + divisor / 2) // divisor * divisor) # Make sure that ...
from collections import OrderedDict from operator import itemgetter from matplotlib import pyplot from tqdm import tqdm from utils.argument_parser import * from utils.file_utils import * from utils.regex_utils import replace_all_redundant_characters def main(): input_dir, judgement_year, dict_path, number_of_wo...
# -*- coding: utf-8 -*- # # Copyright (C) 2018 CERN. # # Invenio-Record-Editor is free software; you can redistribute it and/or modify # it under the terms of the MIT License; see LICENSE file for more details. """Configuration for the invenio-record-editor module.""" from .permissions import allow_all RECORD_EDITOR...
import matplotlib.pyplot as plt from matplotlib.animation import PillowWriter import numpy as np import torch import seaborn as sns class Figure: def __init__(self, save_animation=False, save_name="animation"): self.figure, (self.ax1, self.ax2) = plt.subplots(ncols=2, nrows=1, figsize=(8, 4)) sn...
import cytest # from ./lib; must be first import curry class ICurryTestCase(cytest.TestCase): '''Tests for the API found in module ``curry``.''' def test_reload(self): curry.reload() curry.path.insert(0, 'data/curry/kiel') self.assertIn('data/curry/kiel', curry.path) curry.import_('rev') self....
import json import tensorflow as tf import tensorflow.compat.v1 as tf1 from tensorflow.keras import initializers import numpy as np from mpi4py import MPI from gpt2_keras.builder.gpt2parallelize import GPT2, MultiLayerPerceptron from gpt2_keras.builder import original_gpt2 from gpt2_keras.builder.builderParallel import...
from xicam.core.execution.workflow import Workflow from xicam.core.execution.daskexecutor import DaskExecutor from xicam.plugins import Input, Output, ProcessingPlugin from pyFAI.detectors import Pilatus2M import numpy as np from pyFAI import AzimuthalIntegrator, units from scipy.ndimage import morphology import fabi...
# $Id$ # # Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ #DOC """ class B...
# # # # import my stuff from common_batch import delete_file from common_batch import delete_directory_content # delete created folders and files delete_directory_content("batch/") delete_directory_content("batch_out/") delete_directory_content("results/") delete_directory_content("log/") delete_directory_content("sh...
import pickle import numpy as np from matplotlib import pyplot as plt def plot_stat_mean(stat_key='mean', methods=('scalarization', 'nsga2_2'), enemy=(1, 2, 5), seeds=None, prefix=None, fancy=False, savepath=''): runs = [] if seeds is None: seeds = [111, 222, 333, 444, 555, 666, 777, 888, 999, 1010] ...
import core.decorators from core.utility.strings import str_request_function @core.decorators.delete.init def init(update, context): bot = context.bot message = update.message.text[9:] if message != "": bot.send_message(605363037,str_request_function.HELP_MESSAGE .f...
""" inference script for both batch transform and endpoint Implements four call-backs, see https://sagemaker.readthedocs.io/en/stable/using_sklearn.html # The SageMaker Scikit-learn model server loads your model by # invoking a model_fn function that you must provide in your script. model = model_fn(model_dir) ...
from pydoautomator import Automator import inspect import responses import requests from tests.unit_tdd.api_mocks import shutdown_droplet_success_response, error_404_response from unittest.mock import MagicMock import pytest from pydoautomator.errors import TurnoffDropletError def test_turnoff_droplet_should_exist():...
from numpy import exp, gcd, real, imag from numpy import array, dot, matrix from numpy import pi as _pi from numpy.linalg import det from sympy.ntheory.factor_ import totient from itertools import chain from typing import Union, List # returns the nth primitive root of the unit def _nth_roots_of_unity(num...
# Copyright 2018 The TensorFlow 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 applica...
# -*- coding: utf-8 -*- from webframework import TESTDATA from selenium.webdriver.common.by import By from webframework.extension.util.common_utils import * from time import sleep from common_lib import Common_lib from pagemodel.cs_initial_configuration import Cs_initial_configuration from pagemodel.cs_system_settings_...
#!/usr/bin/env python3 """Analyze optical systems This is vaguely like a ray tracer, but: - Elements are encountered in a prescribed order. - We track phase information (and maybe more stuff later). - We trace from origin to a detector. For consistency, distances are measured in meters throughout -- even wavelengths....
class Astronaut: def __init__(self, name): self.name = name jose = Astronaut(name='José Jiménez') str(jose) # <__main__.Astronaut object at 0x01E3FDF0> print(jose) # <__main__.Astronaut object at 0x01E3FDF0>
# Generated by Django 2.1.2 on 2019-05-10 03:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='profile', name='goods', ...
print('Exercício Python #024 - Verificando as primeiras letras de um texto') cid = str(input('Em qual cidade você nasceu? ')).strip().title() print(cid[0:3] == 'São')
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.ome_children import ome_children def test_ome_children(): """Test module ome_children.py by downloading ome_children.csv and testing shape of...
# Function to check if generated sequence is valid or not def isValid(board,rn,cn): #Column for i in range(rn): if board[i][cn]=='Q': return False #Diagonal \ r=rn c=cn while r>=0 and c>=0: if board[r][c]=='Q': return False r-=1 c-=1 ...
# Copyright (c) 2021 - present / Neuralmagic, 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 b...
def problem464(): """ The Möbius function, denoted μ(n), is defined as: • μ(n) = (-1)^ω(n) if n is squarefree (where ω(n) is the number of distinct prime factors of n) • μ(n) = 0 if n is not squarefree. Let P(a,b) be the number of integers n in the interval [a,b] such tha...
from ..base_test import BaseTestCase class BaseApiTestCase(BaseTestCase): def setUp(self): super(BaseApiTestCase, self).setUp() with self.client.session_transaction() as session: session['token'] = { 'token_type': 'Bearer', 'expires_in': '3600', ...
#Contents of conftest.py import pytest #Command line options: def pytest_addoption(parser): parser.addoption("-U","--url", dest="base_url", default="http://localhost:6464/", help="Base url for the application under test") #Test arguments: @pytest...
import json import hashlib import os from shutil import copyfile data = json.load(open('midis.json')) orig_path = "full/" midis = [] for midi in data: orig_filename = hashlib.sha1(midi['file_urls'][0].encode('utf-8')).hexdigest()+".mid" target_path = 'midis/' + midi['file_path'] target_filename = midi[...
#!/usr/bin/python class Prefix: def __init__(self, address=None, length=None, ip_version=None): self.address = address self.length = length self.ip_version = ip_version def __str__(self): return 'Prefix <%s/%d>, IP version %d' % (self.address, self.length, self.ip_version)
# Python的第2期作业: # 写或仿写一个供大家可以import 的类库 要求: # 1、至少有一个方法和__init__ # 2、完整易懂的使用方法或注释 # 3、实现的功能和场景不限(比如手机号码检查,但不能仅限于长度、开头、数字,要丰富更多其他内容,例如归属地等 # 使用方法 from hongWeiSecondPhaseTask import * if __name__ == '__main__': image = Image.open('图片名') image = image.convert('RGB') print(get_dominant_color(image))
# -*- coding: utf-8 -*- from __future__ import print_function, division import unittest import datetime import pytest from ircelsos.query_ircelsos import query_ircelsos from ircelsos.parser import get_observations, parse_observation class TestQuery(unittest.TestCase): @pytest.mark.network def test_query_a...
import sqlite3 import os from pydub import AudioSegment from tempfile import mktemp import numpy as np import os import pylab import librosa import librosa.display import sklearn import matplotlib.pyplot as plt from PIL import Image import imagehash from classes import SongRecord conn = sqlite3.connect('../shazam_dem...
# Generated by Django 3.2.5 on 2022-03-15 19:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainApp', '0002_auto_20220315_1722'), ] operations = [ migrations.CreateModel( name='Teams', fields=[ ...
#!/usr/bin/env python3 import os import unittest from textwrap import dedent from python_utils import import_vars, set_env_var, print_input_args, \ print_info_msg, print_err_msg_exit, cfg_to_yaml_str from fill_jinja_template import fill_jinja_template def create_diag_table_file(run_dir): ...
import os import pytest import pickle from tokenizers import SentencePieceUnigramTokenizer from ..utils import data_dir, train_files class TestUnigram: def test_train(self, train_files): tokenizer = SentencePieceUnigramTokenizer() tokenizer.train(train_files["small"], show_progress=False) ...
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' Automate SSH logins when you're force to authenticate with a password. ''' import getpass import optparse import os import sys import keyring import pexpect import hmac, base64, struct, hashlib, time def calGoogleCode(secretKey): ''' google autho code''' input ...
# -*- coding: UTF-8 -*- import tensorflow as tf import numpy as np from tensorflow.contrib.seq2seq import * from tensorflow.python.layers.core import Dense from datetime import datetime,timedelta from pyspark.sql import SparkSession, DataFrame, Row, Window from pyspark.sql import functions as F from pyspark.sql.types i...
from pathlib import Path import numpy as np from blockmatrix import blockmatrix def get_resource_dir(): p = Path(blockmatrix.__file__).parent.parent return p / "res" def get_example_raw(): saved = np.load(get_resource_dir() / "example_dat.npz") return saved["raw"], saved["nch"], saved["ntim"]
# start of answer def reverse_num(number): return None # added so that this script will run. feel free to modify it # end of answer print("Test 1: Test that the return value is an int value") print("Expected:True") print("Actual :" + str(isinstance(reverse_num(123), int))) print() print("Test 2") print("Expect...
import csv import glob import sys import re def natural_sort(l): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(l, key=alphanum_key) def merge_csv(pattern, outf): print(pattern) with ope...
import os import numpy as np import pandas as pd from itertools import product from itertools import permutations import warnings from typing import List class SourceHook: def __init__(self, sourcedata=None, metadata=None): """Base Class for CAST data queries. Attributes: source (Sour...
from django.core.management.base import BaseCommand from ...auth import kill_sessions class Command(BaseCommand): help = "Log out all users" def handle(self, **options): kill_sessions()
#!/bin/python3 import math import os import random import re import sys # Complete the findDigits function below. def findDigits(n): w=str(n) count=0 for i in range(w.__len__()): q=int(w[i]) if(q==0): continue else: if(n%q==0): count=cou...
import sys import logging import argparse from PyQt5 import QtCore, QtGui, QtWidgets from psdaq.cas.pvedit import Pv logger = logging.getLogger(__name__) NReadoutChannels = 14 NTriggerChannels = 12 accSel = ['LCLS-I','LCLS-II'] linkStates = ['Down','Up'] rxpols = ['Normal','Inverted'] RowHdrLen = 110 modes ...
"""Itemizations class module for Squaredown. """ from aracnid_logger import Logger from squaredown.connector import Connector # initialize logging logger = Logger(__name__).get_logger() class Itemizations(Connector): """Contains the code to process Square Order Itemizations. Attributes: collection:...
from .base import SetupPyRecipe class PyFtpdLibRecipe(SetupPyRecipe): def __init__(self, *args, **kwargs): super(PyFtpdLibRecipe, self).__init__(*args, **kwargs) self.sha256 = '88c1dc3daa8de9ff5b25fd57ae8cc439' \ '0b5d034f87f2396ebd93eeb8f6879972' self.description = '...
from django.urls import path from django.views.decorators.csrf import csrf_exempt from . import views urlpatterns = [ path('step1', csrf_exempt(views.step1), name='step1'), path('step2', csrf_exempt(views.step2), name='step2'), path('check', csrf_exempt(views.check), name='check'), ]
"""Thermal conductivity base class.""" # Copyright (C) 2020 Atsushi Togo # All rights reserved. # # This file is part of phono3py. # # 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 m...
import numpy as np import xarray as xr from . import Tidegauge, general_utils import matplotlib.dates as mdates import utide as ut import scipy.signal as signal from coast import stats_util, crps_util class TidegaugeAnalysis: """ This contains analysis methods suitable for use with the dataset structure o...
import os import sys DIR_TASK = os.path.basename(os.getcwd()) DIR_LIB = os.path.abspath(os.path.join(os.path.dirname(__file__),"../")) DIR_TASK = os.path.dirname(os.path.abspath(__file__)) + '\\' import gc import json, csv, time, string, itertools, copy, yaml, re import pyodbc import numpy as np import pandas as pd i...
# included from snippets/main.py def debug(*x, msg=""): import sys print(msg, *x, file=sys.stderr) def solve(R1, C1, R2, C2, phase=0): # debug(R1, C1, msg=":R1, C1") if R1 == R2 and C1 == C2: return 0 if R1 + C1 == R2 + C2: return 1 if R1 - C1 == R2 - C2: return 1 ...
import re import transports import static from errors import * # Route Tables # ============ class RegexRouter(object): """ A hybrid hash table, regex matching table. Tries to do O(1) hash lookup falls back on worst case O(n) regex matching. """ _re = [] _dct = {} def __init__(self,...
from user import User from credentials import Credentials import random def create_user(name,password): ''' Function to create a new user account ''' new_user = User(name,password) return new_user def create_credentials(account, email, password): ''' method credentials details ''' ...
#!/usr/bin/env python import rospy import sys import numpy as np import actionlib from geometry_msgs.msg import Vector3 from pioneer_mrs.msg import * # include msg for action from pioneer_mrs.srv import * class Algorithm: def __init__(self): # robot parameters self._hostname = rospy.get_param('...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
import unittest import subprocess import os class MainTest(unittest.TestCase): def test_cpp(self): print("\n\nTesting C++ code...") subprocess.check_call(os.path.join(os.path.dirname( os.path.relpath(__file__)), 'bin', 'python_cpp_example_test')) print("\nResuming Python tests....
from ..game import Mode from ..game import SwitchContinue import logging class Trough(Mode): """Manages trough by providing the following functionality: - Keeps track of the number of balls in play - Keeps track of the number of balls in the trough - Launches one or more balls on request a...
#!/usr/bin/env python # coding: utf-8 # # Property Price Guide Fetcher # This script allows you to find the price range for a given property listed on [Domain.com.au](https://www.domain.com.au/) where there is no price provided by the agent. # It does this by retrieving a property's details then performing a series of...
# # Copyright 2018-2022 Elyra 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 applicable law or agreed to in writ...
# Copyright 2017 gRPC 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 applicable law or agreed to in writing...
import time from flask.ext.restful import Resource, reqparse, abort from flask import jsonify from ..model.auth import Auth as Model from restful_mys.controller.secure_resource import SecureResource class Auth(Resource): def __init__(self): """ Sets up request parser and model for authentication...
# coding=utf-8 # Copyright 2019 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...
"""Test str reducer module.""" import hashlib import unittest from bootstrap4c4d.classes.description import Description from bootstrap4c4d.reducers.str import reduce_strings class TestStringsReducer(unittest.TestCase): def test_reduce_strings(self): description = Description({ "id": "MY_DES...
#!/usr/bin/env python # Copyright 2016 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 ...
import os import gc from datetime import datetime import logging import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedKFold import optuna as optuna import lightgbm as lgb import common.com_util as common import modeling.train_util as tra...
"""Support for mill wifi-enabled home heaters.""" import voluptuous as vol from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, FAN_ON, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_T...
"""Remove old imported buyer accounts Revision ID: 470 Revises: 460 Create Date: 2016-01-22 16:20:29.793439 """ # revision identifiers, used by Alembic. revision = '470' down_revision = '460' from alembic import op def upgrade(): op.execute(""" DELETE FROM users WHERE users.role = 'buyer'; ...
from storage import Storage from tools import markdown, html2text __all__ = ['Storage', 'markdown', 'html2text']
#!/usr/bin/env python # # Copyright 2015-2021 Flavio Garcia # # 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...
def optimal_summands(n): summands = [] i = 1 while n!=0: if i <= n: summands.append(i) n, i = n-i, i+1 else: n += summands.pop() return summands if __name__ == '__main__': n = int(input()) summands = optimal_summands(n) print(len(summands)) for x in summands:...
from django.test import SimpleTestCase from analytics.metrics.duration import get_duration from core.models import Run, Track class DistanceMetricTestCase(SimpleTestCase): def test_placeholder(self): run = Run() tracks = [Track() for _ in range(10)] actual = get_duration(run, tracks) ...
from django.urls import include, path from django.conf.urls import url from django.contrib.auth import views as auth_views from .views import charities, users, volunteers urlpatterns = [ path('', users.home, name='home'), path('reset-password/', auth_views.PasswordResetView.as_view(template_name='user...
#!/usr/bin/env python # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. import StringIO from operator import truth try: from Bio import trie except ImportError: import os from Bio import ...
""" Created on Sun Feb 10 11:21:31 2019, Last update on Sun Mar 15 00:01:05 2020 @author: Amir Reza Sadri """ import os import numpy as np import argparse import datetime import QCF import time from medpy.io import load # for .mha, .nii, or .nii.gz files import matplotlib.pyplot as plt import matplot...
#!/usr/bin/env python import json import subprocess from datetime import datetime calendar = subprocess.check_output( "cal -3 -m --color=always", shell=True, universal_newlines=True) events = subprocess.check_output( "calcurse -Q --output-datefmt %d/%m/%Y", shell=True, universal_newlines=True)...
#!/usr/bin/env python # -*- coding:utf-8 -*- import socket import traceback class Sock(object): def __init__(self, family, stype, proto=0, bufsize=1024 * 1024): self.family = family self.type = stype self.proto = proto self.buf = bufsize self._create() def _create(s...
n = int(input('Digite um número: ')) print('O antecessor do número {} é {}, e o sucessor é {}.'.format(n, n - 1, n + 2))
from setuptools import setup, find_packages long_desc = 'Task Tool is a bottle app which implements an extended TODO list.' long_desc += 'It logs the time spent on each task and generates' long_desc += 'graphs with statistics.' setup( name = 'task_tool', version = '1.0.0.dev1', description = 'Extended TO...
# King Pirate medal = 1142013 if sm.canHold(medal): sm.chatScript("You have earned a new medal.") sm.startQuest(parentID) sm.completeQuest(parentID)
# -*- coding: utf-8 -*- from datetime import datetime from flask import Flask, jsonify from flask_restful import Resource, Api from flask_apispec import marshal_with, doc, use_kwargs from flask_apispec.views import MethodResource from apispec import APISpec from apispec.ext.marshmallow import MarshmallowPlugin from fla...
import sys import click from census_similarity.io import read_csv_write_header, read_rows @click.command() @click.argument('input_file', required=False, type=click.File('rt'), default=sys.stdin) @click.argument('output_file', required=False, type=click.File('rt'), default=sys.stdout)...
import pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.ticker import AutoMinorLocator from matplotlib.backends.backend_pdf import PdfPages import sys import os sys.path.append( os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) ) ...
import numpy as np import tensorflow as tf if int(tf.__version__[0]) > 1: from tensorflow.keras.utils import Sequence else: from tensorflow.python.keras.utils import Sequence class DefaultGenerator(Sequence): """ Create the default generator class using Keras sequence as the parent """ def _...
from enum import Enum, EnumMeta class _ValueEnumMeta(EnumMeta): """ EnumMeta that returns `value`. """ def __getattribute__(cls, name): obj = super().__getattribute__(name) if isinstance(obj, Enum) and hasattr(obj, 'value'): obj = obj.value return obj def __get...
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) import re import datetime import mock from distutils.version import StrictVersion from redis import Redis from tests import RQTestCase, fixtures from rq.utils import backend_class, ens...
import logging import os import traceback from xia2.Schema.Sweep import SweepFactory # this must be defined in a separate file from xia2setup.py to be # compatible with easy_mp.parallel_map with method="sge" when # xia2setup.py is run as the __main__ program. def get_sweep(args): assert len(args) == 1 directo...
#!/usr/bin/env python3 # 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 bisect import copy import enum import numbers import operator import optparse import os import re import strin...
from cfd_trading.core.broker import Broker from cfd_trading.core.monitor import BasicMonitor from cfd_trading.core.account import Account, Accounts from cfd_trading.core.order import Order from trading_ig import IGService import pandas as pd import numpy as np class IG(Broker): """ A class for IG Trading B...
class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) keys added (2) keys removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): self.current_dict, self.past_d...
from typing import Dict from src.python.review.inspectors.issue import IssueType ISSUE_CLASS_TO_ISSUE_TYPE: Dict[str, IssueType] = { # Kotlin | Java interop issues 'Call of Java mutator method on immutable Kotlin collection': IssueType.ERROR_PRONE, 'Function or property has platform type': ...
import FWCore.ParameterSet.Config as cms process = cms.Process("EwkDQM") process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.GlobalTag.globaltag = 'START52_V5::All' process.load("DQM.Physics.ewkDQM_cfi") process.load("DQMServices.Core.DQM_cfg") process.load("DQMServices.Components...
#!/usr/bin/env python2 # vim: expandtab:tabstop=4:shiftwidth=4 ''' Report time to execute 'docker info' ''' # Adding the ignore because it does not like the naming of the script # to be different than the class name # pylint: disable=invalid-name,import-error from docker import APIClient as DockerClient from do...