content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ riko.modules.typecast ~~~~~~~~~~~~~~~~~~~~~ Provides functions for casting fields into specific types. Examples: basic usage:: >>> from riko.modules.typecast import pipe >>> >>> conf = {'type': 'date'} >>> next(pipe({'content':...
import os import sys import json import time import signal import psutil import filelock import webbrowser from fable import config from fable.back.http_server import run def status(): try: with open(config.INFO) as f: info = json.loads(f.read()) if info['pid'] >= 0 and psutil.pid_exist...
#!/usr/bin/python from numpy import * from math import sqrt # Input: expects 3xN matrix of points # Returns R,t # R = 3x3 rotation matrix # t = 3x1 column vector def rigid_transform_3D(A, B): assert len(A) == len(B) num_rows, num_cols = A.shape; if num_rows != 3: raise Exception("matrix A is no...
# Lint as: python2, python3 # Copyright 2020 Google LLC. 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 req...
import os from django.test import TestCase from rest_framework.test import APIRequestFactory from .mvc_model.Error import DuplicationMouseError from .mvc_model.databaseAdapter import GenericSqliteConnector from .mvc_model.mouseFilter import MouseFilter, FilterOption from .views import harvested_mouse_list, harvested_mo...
import datetime import os from pathlib import Path from shutil import copyfile from typing import Dict, Any import pandas as pd import pytz import unicodedata import re def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII...
from establishment.errors.errors import ErrorList from establishment.errors.models import get_error class SocialAccountError(ErrorList): GENERIC_INVALID_PROCESS = get_error(message="Invalid login process") INVALID_SOCIAL_TOKEN = get_error(message="Invalid social token") INVALID_SOCIAL_ACCOUNT = get_error...
#reticulate::use_virtualenv("venv") #reticulate::repl_python() import gym import gym_fishing from stable_baselines3 import SAC env = gym.make("fishing-v4") model = SAC("MlpPolicy", env, verbose=0) model.learn(total_timesteps=10000) model.save("fishing-v4-SAC-Michael")
# -*- coding: utf-8 -*- """Test views.""" #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import numpy as np from numpy.testing import assert_allclose as ac from vispy.util import keys from phy....
from jsonschema import Draft4Validator, Draft3Validator from jsonschema.validators import validator_for from .http.response import JsonResponseBadRequest class JsonFormMixin(object): def get_form_kwargs(self): kwargs = super().get_form_kwargs() if self.request.method in ('POST', 'PUT', 'PATCH') a...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- """Test lvmmodel.install. """ from os.path import abspath, dirname import unittest from .. import __version__ as lvmmodel_version from ..install import default_install_dir, svn_export, install class TestInstall(unittest.TestCase):...
""" Helpers for evaluating models. """ from .reptile import ReptileForFederatedData from mlmi.reptile.reptile_original.variables import weight_decay # pylint: disable=R0913,R0914 def evaluate(sess, model, train_dataloaders, test_dataloaders, num_classes=5, ...
""" Given positive integers {x_1, ..., x_n}, is there a subset that sums to k NP complete problem Links: https://en.wikipedia.org/wiki/Subset_sum_problem https://stackoverflow.com/a/45427013/9518712 https://cs.stackexchange.com/a/49632 https://github.com/saltycrane/subset-sum https://stackoverflow...
from __future__ import division import numpy as np import pandas as pd import netCDF4 as nc from datetime import datetime, timedelta import cPickle as pickle import sys sys.path.append('/home/wesley/github/UTide/') from utide import ut_solv import scipy.io as sio from stationClass import station def mjd2num(x): y...
# -*- coding: utf-8 -*- """ Created on Thu Nov 18 11:49:00 2021 @author: tmlab """ #%% 01. package and data load if __name__ == '__main__': import pickle import spacy import re from nltk.corpus import stopwords import pandas as pd import numpy as np from gensim.models import Coh...
import setuptools # with open("README.md", "r") as fh: # long_description = fh.read() def find_packages_with_dir(src_base, exclude): """Find packages under the given base directory and append their paths. """ pkgs = setuptools.find_packages(src_base, exclude) return {pkg: src_base + '/' + pkg.rep...
from django.conf.urls import url, include from rest_framework_nested import routers from core.views import PhotoViewSet, UserViewSet router = routers.DefaultRouter() router.register(r'photos', PhotoViewSet) router.register(r'users', UserViewSet) users_router = routers.NestedSimpleRouter(router, r'users', lookup='u...
rnl = [ { '4' : 'MMMM', '3' : 'MMM', '2' : 'MM', '1' : 'M', '0' : '' }, { '9' : 'CM', '8' : 'DCCC', '7' : 'DCC', '6' : 'DC', '5' : 'D', '4' : 'CD', '3' : 'CCC', '2' : 'CC', '1' : 'C', '0' : '' }, { '9' : 'XC', '8' : 'LXXX', '7' : 'LXX', '6' : 'LX', '5' : 'L', '4' : 'XL', '3' : 'XXX', '2' : 'XX', '1'...
# -*- coding: utf-8 -*- """ Created on Mon Feb 18 22:27:05 2019 @author: Rolikasi """ import numpy as np import matplotlib.pyplot as plt import pandas as pd from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint, TensorBoard #activate gpu import tensorflow as tf sess = tf.Session...
#!/usr/bin/env python import io import os import sys from setuptools import find_packages, setup from setuptools.command.test import test as TestCommand # Dependencies for this Python library. REQUIRES = [ "botocore>=1.4.31,!=1.4.45", 'contextlib2; python_version < "3.3"', "docker", 'mock; python_vers...
# -*- coding: utf-8 -*- """ Created on Sun Oct 12 22:40:05 2014 @author: Themos Tsikas, Jack Richmond """ import sys import time class RequestError(Exception): ''' An exception that happens when talking to the plate solver ''' pass def json2python(json): ''' translates JSON to python ...
from matplotlib import pyplot as plt def get_losses(log_file, filter_text): with open(log_file) as f: lines = f.readlines() f.close() begin_line, end_line = None, len(lines) for line, _ in enumerate(lines): if _.startswith(filter_text): begin_line = line break ...
# index.py # Scott Metoyer, 2013 # Retrieves a list of new NZB's from the newsgroups specified in a config file from nntplib import * from pymongo import MongoClient import string import datetime import time try: from config_local import config as config except ImportError: from config_default import config a...
import os def run_sgd_trained_experiment(gpu_id, cpu_list): os.system("mkdir -p ./results/sgd8") command = f"CUDA_VISIBLE_DEVICES={gpu_id} taskset -c {cpu_list} " \ f"python tools/cifar_bound_comparison.py " \ f"./networks/cifar_sgd_8px.pth 0.01960784313 ./results/sgd8 --from_inter...
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import defaultdict def loop_up_occurence_index( word_index_dict:defaultdict, word:str)->None: loop_up_result = word_index_dict[word] if len(loop_up_result) != 0 : print(' '.join( map(str, loop_up_result) ) ) ...
from pyradioconfig.parts.ocelot.calculators.calc_fec import CALC_FEC_Ocelot class Calc_FEC_Bobcat(CALC_FEC_Ocelot): pass
import logging from archinfo.arch_soot import (SootAddressDescriptor, SootAddressTerminator, SootClassDescriptor) from ..engines.soot.method_dispatcher import resolve_method from ..engines import UberEngine from ..sim_state import SimState from .plugin import SimStatePlugin l = loggin...
from django.db import models from django.conf import settings from django.utils import timezone # Create your models here. class PaytmHistory(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='rel_payment_paytm', on_delete=models.CASCADE) ORDERID = models.CharField('ORDER ID', max...
#!/usr/bin/env python3 import unittest import time import math from dataclasses import dataclass from selfdrive.hardware import HARDWARE, TICI from selfdrive.hardware.tici.power_monitor import get_power from selfdrive.manager.process_config import managed_processes from selfdrive.manager.manager import manager_cleanup...
# Maps environment variables to variables accessible within Bazel Build files def _impl(repository_ctx): env_vars = repository_ctx.attr.env_vars bzl_vars = "" for env_var in env_vars: bzl_var = repository_ctx.execute(["printenv", env_var]).stdout.rstrip() bzl_vars = bzl_vars + "\n{} = \"{}\"".format(env_...
from framework.latentmodule import LatentModule import random import time class Main(LatentModule): def __init__(self): LatentModule.__init__(self) # set defaults for some configurable parameters: self.trials = 5 def run(self): self.write('We are now testing yo...
""" -*- test-case-name: PyHouse.src.Modules.families.UPB.test.test_Device_UPB -*- @name: PyHouse/src/Modules/families/UPB/UPB_xml.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2014-2015 by D. Brian Kimmel @license: MIT License @note: Created on Aug 6, 2014 @summary: T...
import logging import optuna import optuna.integration.lightgbm as lgb import pandas as pd from catboost import CatBoostClassifier from lightgbm import LGBMClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score from s...
import numpy as np from rosenbrock_helper import f from rosenbrock_helper import f_prime_x0 from rosenbrock_helper import f_prime_x1 from rosenbrock_helper import plot_rosenbrock np.random.seed(0) def main(): x0=np.random.uniform(-2.0,2.0) x1=np.random.uniform(-2.0,2.0) x_start = (x0,x1) ...
'''Autogenerated by get_gl_extensions script, do not edit!''' from OpenGL import platform as _p, constants as _cs, arrays from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_VERSION_GL_1_5' def _f( function ): return _p.createFunction( function,_p.GL,'GL_VERSION_GL_1_5',False) _p.unpack_constants( """GL_...
r""" Gradient Accumulator ==================== Change gradient accumulation factor according to scheduling. Trainer also calls ``optimizer.step()`` for the last indivisible step number. """ from pytorch_lightning.callbacks.base import Callback class GradientAccumulationScheduler(Callback): r""" Change grad...
# Implementacion generica de Arboles de Decisiones. from math import log, inf, sqrt from B_GenericDecisionTree import DecisionTree from random import randint class RandomForest: def __init__(self, X, Y, atr_types, atr_names, num_trees): self.X = X self.Y = Y self.atr_types = atr_types self.atr_names...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from collections import namedtuple from contextlib import contextmanager import functools import logging import re from pyramid.interfaces import IRoutesMapper import jsonschema.exceptions import simplejson from pyramid_swagger.exceptions import RequestV...
# encoding: utf-8 from __future__ import unicode_literals import pytest from emails.backend.factory import ObjectFactory def test_object_factory(): class A: """ Sample class for testing """ def __init__(self, a, b=None): self.a = a self.b = b factory = ObjectFactory(c...
import smart_imports smart_imports.all() class Client(client.Client): __slots__ = () def message_to_protobuf(self, message): raise NotImplementedError def protobuf_to_message(self, pb_message): raise NotImplementedError def cmd_push_message(self, account_id, message, size): ...
import os from pathlib import Path from unittest import TestCase from metabase_manager.exceptions import InvalidConfigError from metabase_manager.parser import Group, MetabaseParser, User class MetabaseParserTests(TestCase): def test_from_paths(self): """ Ensure MetabaseParser.from_paths() return...
import os import errno import json import re import hashlib import time import webbrowser from functools import wraps from urllib.parse import urlparse from .. import editor from . import shared as G from .exc_fmt import str_e from . import msg from .lib import DMP class JOIN_ACTION(object): PROMPT = 1 UPLOA...
import os from monaco_racing import RaceReport from monaco_racing_flask.model.driver import Driver from monaco_racing_flask.app import db_wrapper PROJECT_DIR = os.path.dirname(__file__) leaderboard = RaceReport(os.path.join(PROJECT_DIR, 'data')) def create_test_db(): db_wrapper.database.create_tables([Driver]) ...
""" ----------------------------------------------------------------------------- MIT License Copyright (c) 2020 Abhilash PS 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 w...
from pathlib import Path import json import random import os import numpy as np import torch import torch.multiprocessing as mp import torch.distributed as dist from torch.backends import cudnn import torchvision import csv import matplotlib.pyplot as plt import cv2 ACTION_NAMES = ["sneezeCough", "staggering", "falli...
import pytest from unittest.mock import ( Mock, ) from webu.middleware import ( gas_price_strategy_middleware, ) @pytest.fixture def the_gas_price_strategy_middleware(webu): make_request, webu = Mock(), Mock() initialized = gas_price_strategy_middleware(make_request, webu) initialized.webu = webu...
import numpy as np import glob import pandas as pd import os from netCDF4 import Dataset import socket atlas_name = "meanstate" # or "eape" hostname = socket.gethostname() if (hostname[:8] == "datarmor") or (hostname[::2][:3] == "rin"): # login node is datarmor3 # computational nodes are rXiYnZ gdac = "/...
# coding: utf-8 from aiohttp.test_utils import TestClient import logging import pytest import serpyco import unittest import unittest.mock from rolling.exception import NoCarriedResource from rolling.kernel import Kernel from rolling.model.measure import Unit from rolling.server.document.affinity import AffinityDocume...
# Python test set -- part 2, opcodes from test_support import * print '2. Opcodes' print 'XXX Not yet fully implemented' print '2.1 try inside for loop' n = 0 for i in range(10): n = n+i try: 1/0 except NameError: pass except ZeroDivisionError: pass except TypeError: pass try: pass excep...
#!/usr/bin/env python# life.py simulates John Conway's Game of Life with random initial states # ----------------------------------------------------------------------------- import sys, random, pygame from pygame.locals import * # ----------------------------------------------------------------------------- # GLOBALS ...
# Copyright 2014 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. { 'includes': [ 'modules_generated.gypi', '../bindings/scripts/scripts.gypi', '../build/features.gypi', '../build/scripts/scripts.gypi', ]...
# -*- coding: utf-8 -*- from src.lib.SinaBlog_parser.tools.parser_tools import ParserTools from src.tools.match import Match from src.tools.debug import Debug class SinaBlogArticle(ParserTools): def __init__(self, dom=None): if dom: # Debug.logger.debug(u"SinaBlogArticle中,YESSSSSSSSSSSSSSSSSS"...
from wiki import * from traverse import * def test_create_pages(): root_page = WikiPage(title="FrontPage", text="some text on the root page", tags={"foo", "bar"}) child_page = WikiPage(title="Child1", text="a child page", tags={"foo"}) root_page.add_child(child_page) assert root_page.title == "FrontPa...
# Global constants # Dataset locations IMDB_OSCD = "~/Datasets/OSCDDataset/" IMDB_AIRCHANGE = "~/Datasets/SZTAKI_AirChange_Benchmark/" # Template strings CKP_LATEST = "checkpoint_latest.pth" CKP_BEST = "model_best.pth" CKP_COUNTED = "checkpoint_{e:03d}.pth"
# Copyright 2017 The Bazel 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 applicable la...
from loguru import logger from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer from src.preprocessing_pipeline.transforms import ( set_df_index, convert_to_str, create_title_cat, impute_age, create_family_size, drop_columns, impute_missing_values, s...
''' 1. Do the login 2. If the login is successful, use the working class 3. Else, no access allowed. ''' import sqlite3 from .setup import fileName from .Encryption import * class Working: def __init__(self, primaryPassword: str): self.conn = sqlite3.connect(fileName) self.cur = self.conn.cursor(...
import torchvision.models as models import torch model = models.resnet50(pretrained=True) model.eval() batch = torch.randn((1, 3, 224, 224)) traced_model = torch.jit.trace(model, batch) torch.jit.save(traced_model, 'resnet50.pt')
from django.contrib import admin from django.urls import path, include from django.conf.urls import url from .views import api_root app_name = 'core' urlpatterns = [ url('api-root/',api_root,name='api_root'), ]
#!/usr/bin/env python """ Collection of numerically evaluated optical parameters """ def edlen(P,T,k,f): """ Index of refraction of air, using the Edlen formula Input parameters: P - air pressure in Pa T - the temperature in C k - the vacuum wave number kL/(2*Pi) in um^-1 f - partial pressure ...
# Copyright © 2019 Arm Ltd. All rights reserved. # SPDX-License-Identifier: MIT import numpy as np from .._generated.pyarmnn import Tensor as annTensor, TensorInfo, DataType_QuantisedAsymm8, \ DataType_Float32, DataType_QuantisedSymm16, DataType_Signed32, DataType_Float16 class Tensor(annTensor): ""...
"""Utility functions for RL training.""" import torch import numpy as np def discount(rewards, gamma): """ Discount the reward trajectory. Parameters ---------- rewards : list of float Reward trajectory. gamma : float Discount factor. Returns ------- discounted_re...
#!/usr/bin/env python # -*- coding: utf-8 -*- from .mnist_classifier import MNISTClassifier __all__ = ('MNISTClassifier')
import argparse import github import requests from classroom_tools import github_utils parser = argparse.ArgumentParser() parser.add_argument( '--token', required=True, help='GitHub personal access token with repo permissions' ) parser.add_argument( '--repo_fullname', required=True, help='Rep...
"""A Morse code encoder and decoder. Morse code consists of "dits", "dahs" and spaces. A dit or dah is a signal, whereas a space is an absensce of signal. A dit is one unit of Morse time (or beat) a dah is three. Each dit or dah is followed by a space of one dit. Each character is followed by a space of three dits, an...
############################################################################## # # Copyright (c) 2003-2020 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development unt...
"""Context parser that returns a dict-like from a toml file.""" import logging import pypyr.toml as toml logger = logging.getLogger(__name__) def get_parsed_context(args): """Parse input as path to a toml file, returns dict of toml contents.""" logger.debug("starting") if not args: logger.debug(...
# Generated by Django 3.0.4 on 2020-03-16 02:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('OfficeApp', '0005_auto_20200315_1919'), ] operations = [ migrations.AlterField( model_name='episode', name='air_date...
#!/usr/bin/env python # # Copyright 2017, Data61 # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # ABN 41 687 119 230. # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE_BSD2.txt" for details. #...
from sqlalchemy import ( MetaData, Table, Column, NVARCHAR, ) meta = MetaData() def upgrade(migrate_engine): meta.bind = migrate_engine t = Table("role", meta, autoload=True) description = Column("description", NVARCHAR(255)) description.create(t) def downgrade(migrate_engine): ...
# SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2022 Scipp contributors (https://github.com/scipp) # @author Simon Heybrock from skbuild import setup from setuptools import find_packages def get_version(): import subprocess return subprocess.run(['git', 'describe', '--tags', '--abbrev=0'], ...
#!/usr/bin/env python # # This file is part of libigl, a simple c++ geometry processing library. # # Copyright (C) 2017 Sebastian Koch <s.koch@tu-berlin.de> and Daniele Panozzo <daniele.panozzo@gmail.com> # # This Source Code Form is subject to the terms of the Mozilla Public License # v. 2.0. If a copy of the MPL was ...
#!/usr/bin/python # Sample program or step 5 in becoming a DFIR Wizard! # No license as this code is simple and free! import sys import pytsk3 import datetime import pyewf class ewf_Img_Info(pytsk3.Img_Info): def __init__(self, ewf_handle): self._ewf_handle = ewf_handle super(ewf_Img_Info, self).__in...
import os from django.conf import settings from django.core.exceptions import PermissionDenied from annotation.models import ManualVariantEntryType from annotation.models.models import ManualVariantEntryCollection, ManualVariantEntry from annotation.tasks.process_manual_variants_task import ManualVariantsPostInsertTa...
from ..i18n import i18n class EasyBackupException(Exception): def __init__(self, code, **kwargs): self.code = code self.message = i18n.t(code, **kwargs) self.kwargs = kwargs def __str__(self): return self.message class BackupParseNameError(EasyBackupException): pass c...
# # OtterTune - urls.py # # Copyright (c) 2017-18, Carnegie Mellon University Database Group # import debug_toolbar from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.views import serve from django.views.decorators.cache import never_cache from website import set...
""" :codeauthor: Jayesh Kariya <jayeshk@saltstack.com> """ import sys import salt.modules.pam as pam from tests.support.mock import mock_open, patch from tests.support.unit import TestCase, skipIf MOCK_FILE = "ok ok ignore " @skipIf(sys.platform.startswith("openbsd"), "OpenBSD does not use PAM") class PamTest...
import datetime as dt def get_query(type=0, **kwargs): query = False if type == 0: query = [ { '$sort': { 'datetime': -1 } }, { '$limit': 1 } ] elif type == 1: dnow = dt.datetim...
from os import listdir from os.path import join, isfile import random from scipy import io as sio import numpy as np import copy from ipdb import set_trace as st from math import ceil class BRATS(): def __init__(self,opt,phase): super(BRATS, self).__init__() random.seed(0) self.dataroot = ...
from web3 import Web3, HTTPProvider from threading import Thread from queue import Queue import binascii from scraper.scraper import Scraper class Messenger(Thread): def __init__(self, report_q, private_key, testnet): Thread.__init__(self) self.report_q = report_q self.private_key = priva...
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.utils import timezone from django.core import serializers from .models import * from user.models import * from urllib.parse import quote, unquote from project.config import APIConfig...
def fibonacci(n): if n == 0: return 0 if n == 1: return 1 num1 = fibonacci(n - 1) num2 = fibonacci(n- 2) return num1 + num2 fib_list = [] for i in range(0, 11): fib_list.append(fibonacci(i)) print(fib_list)
from flask import Blueprint, request, stream_with_context from aleph.model import Match, Audit from aleph.logic.audit import record_audit from aleph.views.util import get_db_collection, jsonify, stream_csv from aleph.search import QueryParser, DatabaseQueryResult from aleph.serializers import MatchSchema, MatchCollect...
""" byceps.services.user.dbmodels.user ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from typing import Optional from sqlalchemy.ext.associationproxy import association_proxy from ....database im...
from socket import * import RPi.GPIO as GPIO print "Self-Driving Car Motor Module" GPIO.setmode(GPIO.BCM) #Signal pin defination GPIO.setmode(GPIO.BCM) #LED port defination LED0 = 10 LED1 = 9 LED2 = 25 #Morot drive port defination ENA = 13 #//L298 Enalbe A ENB = 20 #//L298 Enable B IN1 = 19 #//Motor port 1 IN2 = ...
"""ViT Classification model.""" from scenic.model_lib.base_models.classification_model import ClassificationModel from scenic.projects.baselines import vit class ViTClassificationModel(ClassificationModel): """ViT model for classification task.""" def build_flax_model(self): return vit.ViT( num_cla...
from neuronalnetwork import * import matplotlib.pyplot as plt from os.path import isdir import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description='Mountain Car with a neuronal network') parser.add_argument(dest='dirname', default="./") args = parser.parse_args() print("ar...
from socket import * import ssl import threading import time import re import httplib import struct import string import os import sys import socket as Socket import select class handler(threading.Thread): def __init__(self,socket, port) : threading.Thread.__init__(self) self.socket=socket ...
class AutoPrep: def __init__(self, docs): self.docs = self._format(docs) self.docs = self._clean() def _format(self, docs): # input is a single string if isinstance(docs, str): pass # input is list with strings if isinstance(docs[0], str): ...
import collections import warnings # Our numerical workhorses import numpy as np import pandas as pd import scipy.optimize import scipy.stats as st # Numba to make things faster import numba # The MCMC Hammer import emcee # Numerical differentiation package import numdifftools as ndt # Import plotting tools import...
from web_temp import web from server.proxy import server_proxy import os import sys from multiprocessing import Process,Lock import time def work1(): # lock.acquire() time.sleep(1) print(1111) web.app.run(host='0.0.0.0',port=5000,debug=False) # lock.release() def work2(): time.sleep(2) pri...
"""This module contains the general information for EquipmentTpm ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class EquipmentTpmConsts: ACTIVE_STATUS_NA = "NA" ACTIVE_STATUS_ACTIVATED = "activated" ACTIVE_STATUS_...
# Copyright (c) 2017 Hitachi, Ltd. # # 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 ...
# -*- coding: utf-8 -*- # # Copyright (c) 2021 VMware, Inc. All Rights Reserved. # SPDX-License-Identifier: BSD-2-Clause """ SPDX JSON document generator """ import json import logging from tern.formats.spdx.spdx import SPDX from tern.formats.spdx import spdx_common from tern.utils.general import get_git_rev_or_vers...
from django.utils.functional import cached_property from orders.models import Order from users.models import User from users.services import UserCreator class OrderEmailChanger: def __init__(self, order: Order, email: str): self.order = order self.email = email def __call__(self): if...
def pytest_addoption(parser): """ add `--show-viewer` as a valid command line flag """ parser.addoption( "--show-viewer", action="store_true", default=False, help="don't show viewer during tests", )
# -*- coding: utf-8 -*- import phyre, importlib, os importlib.reload(phyre) # 1 or 2 ffx=1 # pc, npc, mon, obj, skl, sum, or wep tp = 'pc' # model number (no leading zeros) num = 106 ffxBaseDir=r'C:\SteamLibrary\steamapps\common\FINAL FANTASY FFX&FFX-2 HD Remaster\data\FFX_Data_VBF\ffx_data\gamedata\...
from django.conf import settings as django_settings class LazySettings(object): @property def DJANGO_LIVE_TEST_SERVER_ADDRESS(self): """Address at which to run the test server""" return getattr(django_settings, 'DJANGO_LIVE_TEST_SERVER_ADDRESS', 'localhost:9001') @...
import re import logging from rdkit import DataStructs from rdkit.ML.Cluster import Butina from luna.util.exceptions import IllegalArgumentError logger = logging.getLogger() def available_similarity_functions(): """Return a list of all similarity metrics available at RDKit.""" regex = re.compile("Bulk([a-z...
from flask import Blueprint assets = Blueprint('assets', __name__) from . import api