content
stringlengths
5
1.05M
from talon import Module mod = Module() @mod.capture(rule="matching") def cursorless_matching_pair_symbol(m) -> str: return {"modifier": {"type": "matchingPairSymbol"}}
# Generated by Django 3.2.5 on 2021-07-20 17:30 from django.db import migrations def secrets_to_nbsecrets(apps, schema_editor): try: ObjectChange = apps.get_model('extras', 'ObjectChange') ContentType = apps.get_model('contenttypes', 'ContentType') ctsecret = ContentType.objects.get(app_...
# Data Parallel Control (dpctl) # # Copyright 2020-2021 Intel Corporation # # 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....
import subprocess import traceback # for python 3.x def runtime_exec(command): msg = {} try: result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) if int(result.returncode) != 0: print('script output: {0}'.format(result.stdout)) ...
#!/usr/bin/env python """Django DDP Presentation Project.""" import os.path from setuptools import setup, find_packages setup( name='dddppp', version='0.0.1', description=__doc__, long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='https://...
# Generated by Django 2.2.2 on 2019-08-31 20:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('source_optics', '0020_statistic_days_before_joined'), ] operations = [ migrations.AddField( model_name='statistic', ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------------------------------------...
import pandas as pd import numpy as np import re import pickle as pk np.random.seed(seed=7) data_path = './data-toxic-kaggle/train.csv' pkl_path = './data-toxic-kaggle/toxic_comments_100.pkl' perturbed_path = './data-toxic-kaggle/toxic_comments_100_perturbed.pkl' # perturbed by Edwin's script perturbed_path = './dat...
#!/usr/bin/env python3 from typing import Optional class CircularQueue: def __init__(self, capacity: int = 10): self._capacity = capacity + 1 self._items = [None] * self._capacity self._head = 0 self._tail = 0 @property def capacity(self) -> int: return self._capa...
from flask import Flask from flask_migrate import Migrate from .config import Config from .models import db from .handlers import routes def create_app(): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) db.app = app migrate = Migrate(app, db) for route in routes: ...
# -*- coding: utf-8 -*- """Workchain to run Quantum ESPRESSO calculations that generate DoS and PDoS for a structure. This requires four computations: - SCF (pw.x), to generate the initial wavefunction. - NSCF (pw.x), to generate eigenvalues, generally with a denser k-point mesh and tetrahedra occupations. - Total Do...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' ground.py File containing functions used on ground Distributed under the 3-Clause BSD License (below) Copyright 2019 Rensselaer Polytechnic Institute (Dr. John Christian, Devin Renshaw, Grace Quintero) Redistribution and use in source and binary forms, with or without...
#!/usr/bin/env python3.8 # Copyright 2020 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import textwrap import unittest from unittest import mock from typing import AbstractSet, Iterable import action_tracer ...
import matplotlib.pyplot as plt import numpy as np from numba import jit from timeit import default_timer as timer import random start = timer() # PARAMETERS TO CHANGE THE FRACTAL GENERATED seq = "AB" # sequence to alternate r values probability = 75 # probability that a given value i...
from mythx_models.response import AuthLogoutResponse def test_auth_login_response_from_valid_json(): resp = AuthLogoutResponse() assert resp.dict() == {}
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib import admin from publication_backbone.models import Publication from .models import PromoPluginModel from salmonella.widgets import SalmonellaIdWidget from fluent_contents.forms import ContentIt...
from .anchor import * from .constraints import * from .edge import * from .graph import * from .multi_edge import * from .node import * from .tools import * del anchor del constraints del edge del graph del multi_edge del node del tools
import os import pytest from iotedgedev.envvars import EnvVars from iotedgedev.output import Output from iotedgedev.utility import Utility from .utility import assert_list_equal, assert_file_equal, assert_json_file_equal pytestmark = pytest.mark.unit tests_dir = os.path.join(os.getcwd(), "tests") test_assets_dir =...
from nwck_class_3 import Newick_Tree import numpy as np f=open('data/data.dat') junk=f.readline() s1=f.readline().strip() s2=f.readline().strip() f.close() n=Newick_Tree(s1) m=Newick_Tree(s2) X=np.zeros((3,3,max(n.tree.keys())+2,len(m.tree.keys())+2)) #Z=np.zeros((3,3,max(n.tree.keys())+2,len(m.tree.keys())+2)) def x...
import csv import numpy as np import os import pandas as pd import sys import sklearn.model_selection #path = sys.argv[1] def read_patients(path='C:/Users/nealm/Dropbox (Brown)/MIMIC DATA/mimic-iii-clinical-database-1.4/mimic-iii-clinical-database-1.4'): patients = pd.read_csv(os.path.join(path, 'PATIENTS.csv.gz')...
from copy import deepcopy import torch import os, sys import_path = os.path.abspath('.') sys.path.insert(1, import_path) from vg_neural_network import NeuralNetwork from vg_game_state import GameState from vg_logger import Logger import logger import coach initial_state = GameState.initial(8, 8) logger_ = Logger()...
from scheme_runner import SchemeTestCase, Query, out cases = [ SchemeTestCase( [ Query(code=['(define (f (variadic x)) (cons 10 x))'], expected=out("f")), Query(code="f", expected=out("(f (variadic x)) [parent = Global]")), Query(code=['(f 2 3)'], expected=out("(10 2 3)"...
letters="ABCDEFGHIJKLMNOPQRSTUVWXYZ" numbers="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26" pos=numbers.find (input("WRITE STUFF? ")) print(pos)
import numpy as np import warnings from pycompss.api.api import compss_delete_object from pycompss.api.constraint import constraint from pycompss.api.task import task from dislib.data.array import Array, full, eye from dislib.data.util import compute_bottom_right_shape, \ pad_last_blocks_with_zeros from dislib.da...
#!/usr/bin/env python3 import math def solution(A, B, K): """ Returns the number of integers within the range [A..B] that are divisible by K """ first = math.ceil(A / K) * K if first > B: return 0 last = math.floor(B / K) * K return ((last - first) // K) + 1
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name="ogsolar", # The python module name. version="4.6", # The version of the module. author="Paul Austen", ...
class SettingsDict(dict): def __getattr__(self, name): if name not in self: raise AttributeError return self[name] def __setitem__(self, key, value): raise AttributeError('SettingsDict properties are immutable') def _hash_key(self): keys_and_values = [] ...
''' Created on Apr 12, 2011 @author: Yuri Corilo ''' class Constants(): atomic_exact_masses = {'H': 1.007825032239, 'D': 2.0141017778, 'T': 3.0160492777, 'He': 4.00260325415, '6Li': 6.015122795, '7Li': 7....
import configparser # CONFIG config = configparser.ConfigParser() config.read('dwh.cfg') # DROP TABLES staging_events_table_drop = "DROP TABLE IF EXISTS staging_events;" staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs;" songplay_table_drop = "DROP TABLE IF EXISTS songplays;" user_table_drop = "DROP T...
from datetime import timedelta from ebedke.utils.date import days_lower, on_workdays from ebedke.utils.text import pattern_slice from ebedke.utils.http import get_dom from ebedke.pluginmanager import EbedkePlugin URL_ROOT = "http://stexhaz.hu/index.php/hu/etl/deli-ajanlat" @on_workdays def get_menu(today): dom ...
# Copyright 2020 MONAI Consortium # 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, s...
import os from dateutil.parser import parse from glob import glob import shutil from django.core.management import BaseCommand from django.utils import timezone from presqt.utilities import read_file class Command(BaseCommand): def handle(self, *args, **kwargs): """ Delete all mediafiles that h...
from typing import Dict, List, cast import logging import copy from overrides import overrides from allennlp.data.instance import Instance from allennlp.data.tokenizers.tokenizer import Tokenizer from allennlp.data.tokenizers import Token from allennlp.data.tokenizers.whitespace_tokenizer import WhitespaceTokenizer f...
# -*- coding: utf-8 -*- """HackerNewsV4.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1dtIIRFFq81O97i6azALZbqBYgoVsUKvD """ from warnings import filterwarnings filterwarnings("ignore") import pandas as pd import json import urllib import reque...
import faulthandler faulthandler.enable() import numpy as np import tensorflow as tf from tensorflow import keras as ks import os from models import build_model from csbdeep.utils.tf import limit_gpu_memory from datawrapper import make_sequence limit_gpu_memory(fraction=0.75, allow_growth=False) # run_opts = tf.Ru...
# coding: utf-8 ''' .. versionadded:: 0.21 ''' from __future__ import absolute_import, print_function, unicode_literals from functools import wraps import logging import platform import sys import threading if sys.version_info <= (3, 4): import trollius as asyncio from ._async_py27 import run_command else: ...
import numpy as np from pychemia.utils.periodic import atomic_number, covalent_radius, cpk_colors class StructurePovray: def __init__(self, structure): self.structure = structure self.distance = 10 def create_pov(self): ret = """ #version 3.7; #include "colors.inc" // The include...
# -*- coding: utf-8 -*- """ Copyright (c) 2021, Ontario Institute for Cancer Research (OICR). 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...
"""This modules allows for convenient error functions imports""" from .http_error import http_error_handler from .validation_error import http422_error_handler from .creation_error import creation_error_handler __all__ = ["http_error_handler", "http422_error_handler", "creation_error_handler"]
"""Sensitivity analysis funcs for sensitivity analysis clinic at CSDMS 2019. Written by Nathan Lyons, May 2019 """ from csv import DictWriter from os import listdir from os.path import isfile, join import numpy as np from pandas import concat, read_csv def get_problem_dict(): # Get the path of the file with the...
from git import Repo def clone(url, destiny): return Repo.clone_from(url, destiny)
import argparse import json import os import sys from io import StringIO import pytest import yaml from bootstrap.lib.options import Options from bootstrap.lib.options import OptionsDict from bootstrap.lib.utils import merge_dictionaries def reset_options_instance(): Options._Options__instance = None sys.ar...
import pylast import configparser import logging import time import argparse from pathlib import Path logger = logging.getLogger() temps_debut = time.time() def lastfmconnect(): config = configparser.ConfigParser() config.read("config.ini") api_key = config["lastfm"]["api_key"] api_secret = config["l...
print("consume")
# -*- coding: UTF-8 -*- #import math from math import sqrt # a = input ("Valor A") # b = input ("Valor B") a = float (input("Valor A:")) b = float (input("Valor B:")) c = float (input("Valor C:")) b2 = b**2 delta = b2 - (4*a*c) try: raizquadrada = sqrt(delta) x1 = (-b-raizquadrada)/(2*a) x2 = (-b + ra...
from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize try: from Cython.Distutils import build_ext except: from distutils.command import build_ext try: import numpy as np except: raise ImportError('NumPy must be installed.') def get_extensions()...
import streamlit as st import pandas as pd import numpy as np from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics impor...
import numpy as np import argparse from depth_evaluation_utils import compute_error_3d parser = argparse.ArgumentParser() parser.add_argument("--pred_file", type=str, help="Path to the prediction file") parser.add_argument("--gt_file", type=str, help="Path to the Ground truth file") parser.add_argument('--min_limit'...
import logging import os import sys import itertools import json import torch from misc import util from .executor import ExecutorTrainer class IliadTrainer(ExecutorTrainer): def _remove_loops_in_paths(self, paths): new_paths = [] for path in paths: new_path = [] visited...
#프로그램을 구성하는 독립적인 단위를 #각각 정의하고 관리하는 방법 #자주 사용하는 일반적인 기능은 모듈로 한번 만들어 두면 #필요할때 마다 도입해서 활용 할 수 있다. #모듈 : 관련성 있는 데이터들, 함수,클래스 #모듈을 사용하려면 import 명령으로 인터프리터에게 #사용여부를 알려야 한다 #import random # 인터프리에게 사용여부를 알림 (import) #import random #import random as r #별칭으로줄여쓰기 #from random import randint #모듈명 줄여쓰기 #from math import pi #from ...
from django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserCreationForm from .models import User class MyUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ['username'] class UserCreate(generic.edit.Create...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ZhimaCreditEpSceneRatingInitializeModel(object): def __init__(self): self._apply_amount = None self._biz_ext_param = None self._credit_category = None self._ep_cer...
import unittest import xr class TestSuccessResult(unittest.TestCase): def setUp(self): self.exc = xr.Success() def test_docstring(self): self.assertEqual("Function successfully completed.", self.exc.__doc__) def test_construct(self): self.assertEqual("Function successfully compl...
from __future__ import with_statement import codecs import os from django.conf import settings from django.test import TestCase, RequestFactory from django.utils.encoding import smart_str from django_gears.finders import AppFinder from django_gears.views import serve TESTS_DIR = os.path.dirname(__file__) FIXTURES_...
import cv2 import numpy as np def findSpaces(line, thres_space): # making vertical projections verProj = cv2.reduce(line, 0, cv2.REDUCE_AVG) # make hist - same dimension as horProj - if 0 (space), then True, else False th = 0; # black pixels threshold value. this represents the space lines hist = ...
import math import os from pathlib import Path from utils.cacti_config import cacti_config ################################################################################ # MEMORY CLASS # # This class stores the infromation about a specific memory that is being # generated. This class takes in a process object, the i...
import rasterio def test_band(): with rasterio.open('tests/data/RGB.byte.tif') as src: b = rasterio.band(src, 1) assert b.ds == src assert b.bidx == 1 assert b.dtype in src.dtypes assert b.shape == src.shape
from django.shortcuts import render, redirect from django.views import View from lisibilite.Lisibilite import Lisibilite class HomePageView(View): def get(self, request): """ The function to handle the HTTP GET request for home page. :param request: The django HTTP request object :return The render object ...
import os import subprocess def test_db_import(): import fiftyone.db assert os.path.isfile( os.path.join(fiftyone.db.FIFTYONE_DB_BIN_DIR, "mongod") ) def test_db_exec(): import fiftyone.db subprocess.check_call( [os.path.join(fiftyone.db.FIFTYONE_DB_BIN_DIR, "mongod"), "--versi...
import requests import json import geojson import csv try: import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() except ImportError: pass url = "http://localhost:8080/routing/api/v1/isochrone" class Point(object): def __init__(self, lon, lat): self.lon = lon ...
import os import click import dotenv CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) cli = click.Group(name='vuejs-doc-pdf', help="Build pdf of vue.js guides", context_settings=CONTEXT_SETTINGS) def project_relative_path(*args): return os.path.join(os.path.dirname(os.path.realpath(__file__)), *args)...
import pulsar as psr def load_ref_system(): """ Returns triphenylene as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 1.23839 0.71468 -0.00000 C 1.23839 -0.71468 -0.00000 ...
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 10:24:51 2019 @author: if715029 """ import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import datasets import sklearn.metrics as skm import scipy.spatial.distance as sc #%% digits = datasets.load_digits() #%% ndig = 100 for k in np...
import matplotlib.pyplot as plt import numpy as np """ def imgmul(y): z3=np.zeros(2,dtype=int) z3[0,0]=y[0,0]*y[0,0]+y[1,1]*y[1,1] z3[0,1]=y[0,0]*y[0,1]+z1[0,1]*z2[0,0] return z3 def E(x): return x*x def DE_Dx(x): return 2*x x=10 Er=[E(x)] num...
# Copyright 2017-2021 Lawrence Livermore National Security, LLC and other # Hatchet Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: MIT import pstats import sys import pandas as pd import hatchet.graphframe from hatchet.node import Node from hatchet.graph import Graph fro...
from selenium import webdriver from time import sleep from PIL import Image from requests import get from io import BytesIO from itertools import count from sys import argv from bs4 import BeautifulSoup if len(argv) == 1: print('No arguments, aborting...') exit() elif not argv[1].startswith('https://www.scribd...
from shserver.shserver import ShortingServer if __name__ == "__main__": server = ShortingServer("0.0.0.0", 8000) server.run()
# percol configuration # https://github.com/mooz/percol # percol.view.PROMPT = ur"<bold><yellow>X / _ / X</yellow></bold> %q" # percol.view.PROMPT = ur"<cyan>Input:</cyan> %q" # Change prompt in response to the status of case sensitivity percol.view.__class__.PROMPT = property( lambda self: ur"<bold><yellow>X...
from .base import ObjectList, Object __all__ = ['UserList', 'User'] class UserList(ObjectList): get_instance_cls = lambda self: User class User(Object): @property def name(self): return self.fullname
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """gpx2geojson: GPX to GeoJSON / KML converter. GUI application for merging kashmir3d-generated multiple GPX files into a single file, decimating track points, and converting into a GeoJSON or KML file, both of which are specified in https://maps.gsi.g...
import statsmodels.api as sm import statsmodels.tsa as tsa import scipy.stats as stats import numpy as np from datetime import datetime, timedelta import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from statsmodels.stats.outliers_influence import variance_inflation_factor fr...
# -*- coding: utf-8 -*- import torch def minibatch_stddev_layer(x, group_size=4): """Appends a feature map containing the standard deviation of the minibatch. Note: Implemented as described in `this paper <https://arxiv.org/pdf/1710.10196.pdf>`_. `Reference <https://github.com/tkarras/progres...
import sys sys.path.append('') from src.parser.queryExecutor import Executor import json class Interface(): def __init__(self): self._executor = Executor() def add_index(self, query): return self._executor.execute_indexing(query) def add_figures(self, data): queries = [] ...
"""Define an object to deal with trash/recycling data.""" import asyncio from collections import OrderedDict from datetime import datetime from enum import Enum from typing import Awaitable, Callable, Dict from urllib.parse import quote_plus from aiocache import cached import pytz as tz from ics import Calendar from ...
import argparse import json import logging import sys import time from datetime import datetime import paho.mqtt.client as client import paho.mqtt.publish as publish from Sensors import Sensors from getmac import get_mac_address from pytz import timezone # Author: Gary A. Stafford # Date: 10/11/2020 # Usage: python3 ...
import time import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @pytest.fixture def driver(request): # Chrome: wd = webdriver.Chrome() print(wd.ca...
from typing import Dict from aenum import Enum from aerisweather.requests.ParameterType import ParameterType from aerisweather.requests.RequestAction import RequestAction from aerisweather.requests.RequestFilter import RequestFilter from aerisweather.requests.RequestLocation import RequestLocation from aerisweather.r...
# Python import os import sys import traceback # Pycompss from pycompss.api.task import task from pycompss.api.parameter import FILE_IN, FILE_OUT # Adapters commons pycompss from biobb_adapters.pycompss.biobb_commons import task_config # Wrapped Biobb from biobb_analysis.gromacs.gmx_rgyr import GMXRgyr # Importing cla...
import requests import os import random import string import json chars = string.ascii_letters + string.digits + '!@#$%^&*()' # This is an array of email extensions; you can add whatever in here # todo: put this in a json file instead emails = ["outlook.com", "gmail.com", "yahoo.com", "hotmail.com", "aol.com", "iclou...
"""Base with abstract classes for all parsers.""" from abc import ABC, abstractmethod from typing import Dict, List, Union from pydantic import BaseModel class BaseParser(ABC): """Base structure for parsers.""" model = BaseModel # Pydantic model to describe the response def __init__(self, content_resp...
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ import asyncio import json import os import time from unittest.mock import Mock, patch import pytest from azure.core.credentials import AccessToken from azure.core.exce...
# Copyright (c) 2019-2020 by Rocky Bernstein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is...
from spira.yevon.io.input_gdsii import * from spira.yevon.io.output_gdsii import *
from django.shortcuts import render from django.template import Context from . import forms, models from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import CreateView #beautiful soup is just an awesome name for a python package #urllib not so much, a bit basic iff i'm honest impo...
from multiprocessing import Pool from typing import Union, Tuple, List import SimpleITK as sitk import numpy as np from batchgenerators.utilities.file_and_folder_operations import join, subfolders, subfiles, save_json, isfile, \ load_json, isdir from surface_distance import compute_surface_distances from kits21.c...
from main.view import View from main.controller import Controller import subprocess class RebootView(View): def __init__(self, controller: Controller): super().__init__(controller) def update_display(self, canvas, bounding_box): canvas.text((40, 20), "Reboot?", fill="white") canvas.tex...
#!/usr/bin/env python3 import urllib.request, urllib.error, json, sys from os.path import join, expanduser, isfile, exists from os import makedirs # Configurations # Location to save downloaded wallpapers # Leave the IMAGE_DIR empty to use default directory /Users/USERNAME/Pictures/BingWallpaper # Or you can set you...
# Generated by Django 3.2.2 on 2021-05-18 21:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('images', '0003_auto_20210517_1022'), ] operations = [ migrations.AlterModelOptions( name='location', options={'order...
# # Copyright (c) nexB Inc. and others. All rights reserved. # ScanCode is a trademark of nexB Inc. # SPDX-License-Identifier: Apache-2.0 # See http://www.apache.org/licenses/LICENSE-2.0 for the license text. # See https://github.com/nexB/scancode-toolkit for support or download. # See https://aboutcode.org for more in...
import unittest from sequence_generation import topological_sort, intersect, State_Space_Error, \ Topology, State_Search_Flags, Node, Stateful_Node, Input, Output, PowerState, \ state_difference, Wire, Constraint from enzian_descriptions import enzian_nodes, enzian_wires, ISPPAC imp...
# zhoudoao@foxmail.com # 2020.5.12 """ Bayesian LeNet-5 and LeNet-5 model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf import tensorflow_probability as tfp tf.enable_v2_behavior() tfd = tfp.distributions def ba...
"""Each ListNode holds a reference to its previous node as well as its next node in the List.""" class ListNode: def __init__(self, value, prev=None, next=None): self.value = value self.prev = prev self.next = next """Wrap the given value in a ListNode and insert it after this node....
from option import option import pytest from typing import Optional, Callable def test_some(): opt = option.some(5) assert opt == 5 assert isinstance(opt, int) def test_some_exception(): with pytest.raises(option.InvalidArgument): option.some(None) def test_none(): assert option.none()...
def get_action_value(mdp, state_values, state, action, gamma): """ Computes Q(s,a) as in formula above """ return sum( prob * (mdp.get_reward(state, action, state_dash) + gamma * state_values[state_dash]) for state_dash, prob in mdp.get_next_states(state, action).items() )
import torch from torch import tensor import torch.nn as nn import sys,os import math import sys sys.path.append(os.getcwd()) from lib.utils import initialize_weights # from lib.models.common2 import DepthSeperabelConv2d as Conv # from lib.models.common2 import SPP, Bottleneck, BottleneckCSP, Focus, Concat, Detect from...
# -*- coding: utf-8 -*- from wakatime.main import execute from wakatime.packages import requests import logging import os import time import shutil import sys import uuid from testfixtures import log_capture from wakatime.arguments import parse_arguments from wakatime.compat import u, is_py3 from wakatime.constants ...
# -------------- # Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) #Code starts here census=np.concatenate((new_record,data)) ...
#!/usr/bin/env python from ..exrpc.rpclib import * from ..exrpc.server import * from ..mllib.model_util import ModelID class df_to_sparse_info: '''A python container for holding information related to dataframe to sparse conversion''' def __init__(cls,info_id): cls.__uid = info_id def load(cls,dirname): ...
#!/usr/bin/env python from math import radians import rospy from sensor_msgs.msg import LaserScan from geometry_msgs.msg import Twist class Obstacle(): def __init__(self): rospy.init_node('obstacle') self.LIDAR_ERR = 0.05 self._cmd_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1) ...
import os import sys import logging import logging.handlers from logging_gelf.handlers import GELFUDPSocketHandler from collections import defaultdict LOG_LEVELS = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL } cl...