content
stringlengths
5
1.05M
# MIT License # Copyright (c) 2017 MassChallenge, Inc. from __future__ import unicode_literals import swapper from accelerator_abstract.models import BaseStartupLabel from accelerator_abstract.models.label_model import LabelModel class StartupLabel(BaseStartupLabel): class Meta(LabelModel.Meta): swappa...
import deep_ga import tensorflow as tf from tensorflow import keras import os import matplotlib.pyplot as plt class AssertWeightsFinite(keras.callbacks.Callback): def __init__(self): super(AssertWeightsFinite, self).__init__() def on_epoch_end(self, epoch, logs=None): for weight in self.model...
"""Tests for retrieving license information.""" from unittest import TestCase, mock from flask import Flask from ....domain.submission import License from .. import models, get_licenses, current_session from .util import in_memory_db class TestGetLicenses(TestCase): """Test :func:`.get_licenses`.""" def t...
import enum from pydantic import BaseModel, EmailStr from typing import Optional, List # from stripe.api_resources import payment_method class YesNoNone(enum.Enum): YES = "yes" NO = "no" NONE = "null" class ClientBase(BaseModel): class Config: orm_mode = True class ClientInfo(ClientBase):...
from fuzzywuzzy import fuzz class ActionsHandler: """ actions object function: There are 3 different cases that a text could match. 1: A text contains exactly the text specified in a exactly attribute. 2: A text matches with a text specified in a match attribute, b...
""" Given the index of an image, take this image and feed it to a trained autoencoder, then plot the original image and reconstructed image. This code is used to visually verify the correctness of the autoencoder """ import torch import argparse import numpy as np import torchvision.transforms as transforms import matp...
# ***** merge code for NPOL data ***** # Author: Stacy Brodzik, University of Washington # Date: October 24, 2016 # Description: from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import logging as log import sys # ----------------------------------...
from functools import wraps import traceback import copy import socket def catch_exception(origin_func): def wrapper(self, *args, **kwargs): try: u = origin_func(self, *args, **kwargs) return u except Exception as e: # print(origin_func.__name__ + ": " + e.__str__...
from django import forms from . import models class FileForm(forms.ModelForm): class Meta: model = models.File fields = '__all__' class ImageForm(forms.ModelForm): class Meta: model = models.Image fields = '__all__'
from ctypes import * import ctypes.util import _ctypes from os import system def generate_getter(user_fun_name): file = open("casadi_fun_ptr_getter.c", "w") file.write("int "+user_fun_name+"(const double** arg, double** res, int* iw, double* w, void* mem);\n") file.write("int "+user_fun_name+"_work(int *sz_arg...
import CaboCha class Kongming: def __init__(self, stopwords=None): self.cabocha = CaboCha.Parser() self.stopwords = stopwords def _get_modifier(self, tree, chunk): surface = '' for i in range(chunk.token_pos, chunk.token_pos + chunk.head_pos + 1): token = tree.tok...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( x , y ) : if ( x == 1 ) : return ( y == 1 ) pow = 1 while ( pow < y ) : pow = pow * x ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from dj.choices import Choices from django.contrib.auth.models import AbstractUser from django.db import models as db from django.db.models.signa...
'''------------------------------------------------------------------------------- Tool Name: UpdateDischargeMap Source Name: UpdateDischargeMap.py Version: ArcGIS 10.2 License: Apache 2.0 Author: Environmental Systems Research Institute Inc. Updated by: Environmental Systems Research Institute In...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import math import pdb # This is a PyTorch data augmentation library, that takes PyTorch Tensor as input # Functions can be applied in the __getitem__ function to do augmentation on the fly during training. # These functions can be ...
import dataclasses as dc @dc.dataclass(unsafe_hash=True) class Demand: route: str origin: str destination: str demand_per_second: float
import os from hendrix.resources import DjangoStaticResource from django.conf import settings from django.contrib.staticfiles import finders class DjangoStaticsFinder: """ finds all static resources for this django installation and creates a static resource for each's base directory """ ...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns = get_columns() proj_details = get_project_details() pr_item_map = get_purchas...
"""DNA design container classes""" import string # Global DNA nt groups group = {"A": "A", "T": "T", "C": "C", "G": "G", "W": "AT", "S": "CG", "M": "AC", "K": "GT", "B": "CGT", "V": "ACG", "D": "AGT", "H": "ACT", "N": "ACGT"} # SpuriousC group codes rev_group = dict([(v, k) for (k, v) in li...
# position/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # Diagrams here: https://docs.google.com/drawings/d/1DsPnl97GKe9f14h41RPeZDssDUztRETGkXGaolXCeyo/edit from django.db import models from election_office_measure.models import CandidateCampaign, MeasureCampaign from exception.models impor...
import streamlit as st def show(): st.markdown("The termination criterion is a preset number of generations.") max_gens = st.slider("Number of Generations", min_value=1, max_value=100, value=50)
lado = float (input ("Qual é o valor do lado do quadrado: ")) area = lado * lado area_aoquadrado = area * 2 print ("A área do quadrado é {} e o dobro do quadrado é {}".format (area,area_aoquadrado))
from django.views.generic import View from django.conf import settings from django.http import HttpResponseRedirect from . import forms class IndexView(View): def get(self, request): next = "/" if "next" in request.GET: next = request.GET.get("next") response = HttpResponseRe...
#! /usr/bin/env python """ Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Trains a simple GPT-2 based disambiguation model. Author(s): Satwik Kottur """ from __future...
from django.contrib import admin from lists.models import List @admin.register(List) class ListAdmin(admin.ModelAdmin): """Register List model at admin panel Search by: name : icontains """ list_display = ("name", "user", "count_rooms") search_fields = ("name",) filter_horizontal = (...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
import os import tensorflow as tf from config import cfg class Model(object): def __init__(self, img_channels=3, num_label=2, call_type='training'): ''' Args: img_channels: Integer, the channels of input. num_label: Integer, the category number. ''' self.bat...
class Scene(object): def enter(self): 4 pass 5 6 class Engine(object): 8 9 def __init__(self, scene_map): 10 pass 11 12 def play(self): 13 pass 14 class Death(Scene): 16 17 def enter(self): 18 pass 19 class CentralCorridor(Scene): 21 22 def enter(self): 23 pass 24 class LaserWeapon...
"""[summary] Init module [description] The init module creates Flask object, databases, and logging handler """ from flask import Flask from flask_restful import reqparse, abort, Api, Resource import sqlite3 from config import Config from flask_sqlalchemy import SQLAlchemy from sqlalchemy import event import...
# header html from libraries.string_processes import pcom_create_html_from_array from libraries import constants as ct from libraries import schematics as sch # adds footer def polimorf_add_footer(footer_data,meta_present): out_html = ct.PCOM_NO_ENTRY if meta_present: add_footer = pcom_create_html...
from math import * from sympy import * global Y,deriv,dydx,count count=0 h=5 global Vgb,Vfb,q,Es,Cox,Po,No,St,NA,ND def func( Y ): global Vgb,Vfb,q,Es,Cox,Po,No,St,NA,ND try: p=Vfb + Y - (sqrt(2*q*Es)/Cox) *(sqrt( Po*St*( e**(-Y/St )-1) +( NA-ND )*Y + No*St*( e**(Y/St )-1) ) ) -Vgb retur...
import numpy as np from numpy.testing import assert_array_equal import pytest import tensorflow as tf from .. import volume @pytest.mark.parametrize("shape", [(10, 10, 10), (10, 10, 10, 3)]) @pytest.mark.parametrize("scalar_labels", [True, False]) def test_apply_random_transform(shape, scalar_labels): x = np.one...
# -*- coding: utf-8 -*- """ Created on Mon Aug 11 16:19:39 2014 """ import os import sys import imp # Put location of sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..\\..')) + '\\modules') # add ODYM module directory to system path #NOTE: Hidden variable __file__ must be know to script ...
from common.utils import read_file from . import food def main() -> None: food_list = read_file("d21/data/input.txt", food.parse) # Part1 result1 = food.count_impossible(food_list) print(f"Result 1-> {result1} <-1") # Part2 result2 = food.get_canonical(food_list) print(f"Result 2-> {resu...
import warnings import numpy as np import pandas as pd from astropy.time import Time __all__ = [ "UNKNOWN_ID_REGEX", "preprocessObservations", ] UNKNOWN_ID_REGEX = "^u[0-9]{12}$" def preprocessObservations( observations, column_mapping, astrometric_errors=None, mjd_scale="utc"...
from evalmate import confusion from . import evaluator class EventEvaluation(evaluator.Evaluation): """ Result of an evaluation of any event-based alignment. Arguments: utt_to_label_pairs (dict) Dict containing the alignment for every utterance. Key is the utter...
# Generated by Django 3.1a1 on 2020-06-03 17:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0002_auto_20200603_1029'), ] operations = [ migrations.CreateModel( name='Programme', fields=[ ...
import json import logging import pandas as pd from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func from iotfunctions import bif from iotfunctions.metadata import EntityType, BaseCustomEntityType from iotfunctions.db import Database from iotfunctions.enginelog import EngineLogging EngineLoggi...
from .Scheduler import Scheduler from .MongoConn import MongoConn from .Catalog import Catalog, Course from .Response import Response from .SlackConn import SlackConn from .Output import output
# -*- coding: utf-8 -*- # Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. try: import pplog as logging except ImportError: import logging logger = logging.getLogger(__name__) import numpy as np ...
import os # setting for the searchable path curr_dir = os.getcwd() curr_dir = curr_dir.replace('tasks', '') """ Data dimensions of the dataset in use Assumption: all of the samples are having same size Note: data are not down or up-sampled """ DATA_DIMENSION = {'height': 256, 'width': 256, ...
#!/usr/bin/env python #Communicate with end devices via LoRa. #Communicate with server via MQTT(hbmqtt) and HTTP POST. #Save data in the sqlite database. #Parse JSON from MQTT and LoRa protocol. #Communication module: LoRa. #Communication method with device via LoRa. #Uart port drive LoRa module. #Parse JSON between d...
# Kertaus kerrasta 1 # Tulostaminen näytölle: print print("Moikka") # Laskutoimitukset print(5 + 7) # Mitä tämä tulostaa? print(9 + 9) # Mitä tämä tulostaa? print("9 + 9") # Kommentti # Tämä on kommentti
# Generated by Django 2.2.2 on 2019-07-08 19:11 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('django_import_data', '0017_auto_20190708_1504'), ] operations = [ migrations.RemoveField( model_name='modelimportattempt', n...
__all__=["Enigma","Rotor","Reflector"]
from selenium import webdriver from bs4 import BeautifulSoup from time import sleep from common.flags import GlobalState from modules.scrappers.scrapper import Scrapper class NorwegianScrapper(Scrapper): def __init__(self): super().__init__("norwegian") self.url_base = "https://www.norwegian.com/...
import pytest from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from poliastro.atmosphere import COESA76 from poliastro.atmosphere.coesa76 import p_coeff, rho_coeff coesa76 = COESA76() def test_outside_altitude_range_coesa76(): with pytest.raises(ValueError) as excinfo: ...
"""This is the entry point into the Mesh application""" import argparse import logging import sys from mesh.configuration import get_config from mesh.interactive import first_run_setup def setup_args(): """Initialize the CLI argument parser""" parser = argparse.ArgumentParser( prog='Mesh', ...
# MIT License # # Copyright (c) [2018] [Victor Manuel Cajes Gonzalez - [email protected]] # # 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 th...
from __future__ import absolute_import, division, print_function import time from mmtbx import monomer_library import mmtbx.refinement.real_space.fit_residue import iotbx.pdb from mmtbx.rotamer.rotamer_eval import RotamerEval import mmtbx.utils import sys from libtbx import easy_pickle import libtbx.load_env from six.m...
"""Setup for deniable.""" import os import codecs from setuptools import setup HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """Return multiple read calls to different readable objects as a single string.""" return codecs.open(os.path.join(HERE, *parts), 'r').read() LONG_DESCRIPTION...
import os, functools, math, sys, itertools, re, time, threading, xlwt, configparser import numpy as np import tkinter as tk from xlwt import Workbook from tkinter import ttk, filedialog, messagebox #CONSTANTS # Data from: Pyykko, P. and Atsumi, M., Chem. Eur. J. 2009, 15, 186. element_radii=[ ["None",None],['H' ...
## @ingroup Methods-Aerodynamics-Common-Fidelity_Zero-Drag # parasite_drag_wing.py # # Created: Dec 2013, SUAVE Team # Modified: Jan 2016, E. Botero # Apr 2019, T. MacDonald # Apr 2020, M. Clarke # May 2021, E. Botero # -------------------------------------------------------------...
# Copyright (C) 2007 - 2012 The MITRE Corporation. See the toplevel # file LICENSE for license terms. # SAM 6/12/12: I've moved the document pairer into its own file. # SAM 5/9/12: Added initial support for doing alignment via Kuhn-Munkres. from munkres import Munkres, make_cost_matrix import MAT.Document from MAT....
from abc import abstractmethod from copy import deepcopy from typing import Any import numpy as np import pandas as pd from aistac.handlers.abstract_handlers import HandlerFactory from aistac.intent.abstract_intent import AbstractIntentModel from ds_discovery.components.commons import Commons __author__ = 'Darryl Oatr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 28 05:21:49 2019 @author: yibo """ import matplotlib import matplotlib.pyplot as plt from matplotlib.widgets import CheckButtons import numpy as np import IPython from IPython import get_ipython from matplotlib.patches import Ellipse, Polygon font =...
# ---------------------------------------------------------------------------- # Python Wires Tests # ---------------------------------------------------------------------------- # Copyright (c) Tiago Montes. # See LICENSE for details. # ---------------------------------------------------------------------------- """ ...
# 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 by applicable law or ...
import random from typing import List from operator_generator_strategies.distinct_operator_strategies.distinct_window_strategy import \ DistinctWindowGeneratorStrategy from utils.contracts import Aggregations from operator_generator_strategies.base_generator_strategy import BaseGeneratorStrategy from operators.agg...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (c) 2014-2016 pocsuite developers (https://seebug.org) See the file 'docs/COPYING' for copying permission """ import sys from pocsuite_cli import pcsInit from .lib.core.common import banner from .lib.core.common import dataToStdout from .lib.core.settings im...
import io import pickle import socket import psutil import argparse import sys sys.path.append("..") from ...messaging import network_params from ...messaging import message from ...messaging import messageutils import getpass parser = argparse.ArgumentParser() parser.add_argument("-k", "--Kill") args = parser.parse...
import base64 import datetime import json import logging import urllib.parse import OpenSSL.crypto as crypto import aiohttp import pytz import requests import esia_client.exceptions logger = logging.getLogger(__name__) class FoundLocation(esia_client.exceptions.EsiaError): def __init__(self, location: str, *ar...
# Import the Flask Framework from flask import Flask import os import sys # This is necessary so other directories can find the lib folder sys.path.append(os.path.join(os.path.dirname(__file__), 'lib')) # Note: We don't need to call run() since our application is embedded within # the App Engine WSGI application ser...
#!/usr/bin/env python import astropy.io.fits as pyfits import numpy as np import sys,pylab if len(sys.argv)<3 : print sys.argv[0],"residuals.fits spots.list" sys.exit(0) hdulist=pyfits.open(sys.argv[1]) hdulist.info() data=hdulist[0].data model=hdulist["MODEL"].data ivar=(hdulist["PULL"].data/(hdulist["RESI...
# -*- coding: utf-8 -*- import sympy as sy from sympy import symbols, Matrix def inv_sym_3x3(m: Matrix, as_adj_det=False): P11, P12, P13, P21, P22, P23, P31, P32, P33 = \ symbols('P_{11} P_{12} P_{13} P_{21} P_{22} P_{23} P_{31} \ P_{32} P_{33}', real=True) Pij = [[P11, P12, P13], [P21...
import simplejson as json import sys import re import os # Uses a customized version of simplejson, because the dump json has entries # with the same key, and the order of the keys is important. The customized # version adds a counter to each key name, for uniqueness, and to recover # order by sorting. Then at pretty ...
import argparse import zipfile import yaml import os from .peanut import Job from .mpi_calibration import MPICalibration from .mpi_saturation import MPISaturation from .hpl import HPL from .blas_calibration import BLASCalibration from .stress_test import StressTest from .bit_flips import BitFlips from .version import _...
# Generated by Django 3.1.7 on 2021-04-12 12:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('metadata', '0009_tradeagreement'), ('interaction', '0074_update_service_questions_and_answers'), ] operations = [ migrations.AddFiel...
from django.shortcuts import render_to_response from django.template import RequestContext from models import ToBeAnnotated def index(request): tbas = ToBeAnnotated.objects.all() return render_to_response("index.html",RequestContext(request, {"tbas":tbas}))
import setuptools import os from pathlib import Path root = Path(os.path.realpath(__file__)).parent version_file = root / "src" / "sphinx_codeautolink" / "VERSION" readme_file = root / "readme_pypi.rst" setuptools.setup( name="sphinx-codeautolink", version=version_file.read_text().strip(), license="MIT", ...
import numpy as np data_a = np.fromfile('error.dat', dtype=float, count=-1, sep='') data_a1 = data_a[::2] data_a2 = data_a[1::2] import matplotlib as mpl font = {'family' : 'serif', 'size' : 16} mpl.rc('font', **font) import matplotlib.pyplot as plt fig = plt.figure() plt.plot(data_a1, data_a2, label='$\e...
# -*- coding: utf-8 -*- class PreviewGeneratorException(Exception): pass class UnavailablePreviewType(PreviewGeneratorException): """ Exception raised when a preview method is not implemented for the type of file you are processing """ pass class UnsupportedMimeType(PreviewGeneratorExcepti...
# Author: Luka Maletin from data_structures.stack import Stack OPERATORS = '&|!' def infix_to_postfix(expression): postfix = [] priority = {'(': 1, '&': 2, '|': 2, '!': 2} operators = Stack() for token in expression: if token in OPERATORS: # Operators are added to the stack, but...
import pytest from expackage import my_add def test_my_add(): # Unit test for my_add function assert my_add(3, 2) == 5 def test_my_add_first_input_raises(): # Test that my_add raises a TypeError when first input isn't a number with pytest.raises(TypeError) as excinfo: my_add('not a number',...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys from nycTaxis import core from nycTaxis import dataHandler assert len(sys.argv) == 2, "Usage: 1. Argument - target date, rolling average" targetDate = sys.argv[1] taxiDataFrame = dataHandler.loadDataFrame('/home/tobi/Projects/BlueYonder/etc/data.h...
# Copyright 2019 PerfKitBenchmarker 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...
''' Created on 22/02/2013 @author: victor ''' import pyRMSD.RMSDCalculator import numpy import math NUMBER_OF_THREADS = 4 if __name__ == '__main__': # Reading coords coordsets = numpy.load("data/tmp_amber_long.npy") number_of_atoms = coordsets.shape[1] number_of_conformations = coordsets.shape[0] ...
# coding:utf8 from kivy.uix.modalview import ModalView class AuthPopup(ModalView): def __init__(self, app, **kwargs): self.show_password_text = 'Показать пароль' self.hide_password_text = 'Скрыть пароль' self.app = app super(AuthPopup, self).__init__(**kwargs) def log_in(se...
from setuptools import setup setup( name="gpef", version="0.0.1", description="General Purpose Experiment Framework", author='zhaozhang', author_email='[email protected]', packages=['gpef.tools', 'gpef.graphic', 'gpef.stat'], #install_requires=["matplotlib"], entry_points=""" [...
from __future__ import print_function import sys from armada_command import armada_api from armada_command.scripts.compat import json def add_arguments(parser): parser.add_argument('saved_containers_path', help='Path to JSON file with saved containers. They are created in /opt/armada. ' ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2019-01-20 19:07 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_depend...
# -*- coding: utf-8 -*- from __future__ import absolute_import import numpy as np from hypothesis import given, assume from hypothesis.strategies import characters, text from eli5.lime.textutils import SplitResult, TokenizedText def test_split_result(): s = SplitResult.fromtext("") assert list(s.tokens) == ...
from typing import Optional, Dict, Tuple, List import numpy as np from konvens2020_summarization.data_classes import Corpus from konvens2020_summarization.featurizer import TfidfFeaturizer from konvens2020_summarization.preprocessor import Preprocessor def get_important_words(corpus: Corpus, ...
import time import numpy as np from sklearn.metrics.scorer import balanced_accuracy_scorer from automlToolkit.utils.logging_utils import get_logger from automlToolkit.components.evaluators.base_evaluator import _BaseEvaluator from automlToolkit.components.evaluators.evaluate_func import holdout_validation, cross_valid...
# Copyright 2013 Mark Dickinson # # 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,...
from pololu_drv8835_rpi import motors import math class MotorControl: def __init__(self): self.rightSpeed = 0 self.leftSpeed = 0 def adjustSpeed(self, rightSpeed, leftSpeed): self.rightSpeed = rightSpeed self.leftSpeed = leftSpeed 480 if rightSpeed > 480 else rightSp...
""" `%hierarchy` and `%%dot` magics for IPython =========================================== This extension provides two magics. First magic is ``%hierarchy``. This magic command draws hierarchy of given class or the class of given instance. For example, the following shows class hierarchy of currently running IPyth...
# -*- coding: utf-8 -*- import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [] operations = [ migrations.CreateModel( name='Attribute', fields=[ ( 'id', models....
# Copyright (c) 2016-2018, University of Idaho # All rights reserved. # # Roger Lew ([email protected]) # # The project described was supported by NSF award number IIA-1301792 # from the NSF Idaho EPSCoR Program and by the National Science Foundation. from os.path import join as _join from os.path import exists as _e...
from protocol import Protocol from transition import Transition def name(n): return "Flock-of-birds 2 ({})".format(n) # From https://hal.archives-ouvertes.fr/hal-00565090/document # Example 2, p. 5 def generate(n): Q = set(range(n + 1)) T = set() S = {"0", "1"} I = {"0": 0, "1": 1} O = {i: (0 ...
import boto3 def get_batch_client(access_key, secret_key, region): """ Returns the client object for AWS Batch Args: access_key (str): AWS Access Key secret_key (str): AWS Secret Key region (str): AWS Region Returns: obj: AWS Batch Client Obj """ return boto3....
class Environment: def __init__(self): self.total_timesteps = 1000 self.timesteps_occurred = 0 self.current_state = 0 self.markov_chain = [self.current_state] def get_current_state(self): return self.current_state def get_actions(self): return [-1, 1...
import json import os import random from pprint import pprint def load_data(filename): if filename is None: raise ValueError("None is not a valid file name") with open(os.path.abspath(filename)) as json_file: #raw_data = open(filename).read() return json.load(json_file) def ...
# coding: utf-8 """ Характеристики для цифрового фильтра """ # Other from pylab import * from numpy import arange from numpy import ones # App from visualisers import mfreqz from visualisers import impz from iir_models.iir_digital import calc_digital_characteristics if __name__=='__main__': mean_params = ...
""" # author: shiyipaisizuo # contact: [email protected] # file: prediction.py # time: 2018/8/24 22:18 # license: MIT """ import argparse import os import torch import torchvision from torchvision import transforms # Device configuration device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') pa...
#-*- encoding: utf-8 -*- import os import types from functools import reduce _GLOBAL_CONFIG = dict( user_agent = 'citationdetective', log_dir = os.path.join(os.path.expanduser('~'), 'cd_logs'), ) # A base configuration that all languages "inherit" from. _BASE_LANG_CONFIG = dict( articles_sampling_fracti...
# This is a temporary script that MAY be useful later. # What it does is creates origin folders based on file names import os import shutil from tqdm import tqdm WHERE_TO_COPY = r"C:\Users\Aleksei\Desktop\origin_folders".replace("\\", "/") FROM_COPY = r"F:\_ReachU-defectTypes\__new_2020_06\orthos".replace("\\", "/") ...
# From https://github.com/PyCQA/bandit/blob/master/examples/sql_statements-py36.py import sqlalchemy # bad query = "SELECT * FROM foo WHERE id = '%s'" % identifier query = "INSERT INTO foo VALUES ('a', 'b', '%s')" % value query = "DELETE FROM foo WHERE id = '%s'" % identifier query = "UPDATE foo SET value = 'b' WHERE...
# -*- coding: utf-8 -*- import os ConsumerKey = os.environ['ConsumerKey'] # * enter your Consumer Key * ConsumerSecret = os.environ['ConsumerSecret'] # * enter your Consumer Secret * AccessToken = os.environ['AccessToken'] # * enter your Access Token * AccesssTokenSecert = os.environ['AccesssTokenSecert'] # * ent...
""" A file to create confusion matrix for each classification result Example : { # For each protected group "0": { # For each ground truth, create confusion matrix "0": {"TP": 3, "FP": 2, "TN": 5, "FN": 1}, "1": {"TP": 5, "FP": 1, "TN": 3, "FN": 2} }, "1": { "0": {"TP": 5...