content stringlengths 5 1.05M |
|---|
# -*- test-case-name: mimic.test.test_dns -*-
"""
Defines get for reverse dns
"""
import json
from uuid import uuid4
from six import text_type
from zope.interface import implementer
from twisted.plugin import IPlugin
from mimic.rest.mimicapp import MimicApp
from mimic.catalog import Entry
from mimic.catalog import End... |
from .. import arr
import numpy as np
import math
cfg = {
'name': 'PVI - Plethysmographic Variability Index',
'group': 'Medical algorithms',
'desc': 'Calculate pulse pressure variation',
'reference': 'Aboy et al, An Enhanced Automatic Algorithm for Estimation of Respiratory Variations in Arterial Pulse... |
#!/usr/bin/env python3
import argparse
import logging
from shared import common_utils
from operations import operations
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format="%(levelname)s : %(message)s")
parser = argparse.ArgumentParser(prog='ALU UCE Auto Builder')
sub_parsers = par... |
from typing import Optional, Union, Tuple, List, Dict
from torch import nn
def init_weights(module: nn.Module):
"""
Initialize one module. It uses xavier_norm to initialize nn.Embedding
and xavier_uniform to initialize nn.Linear's weight.
Parameters
----------
module
A Pytorch nn.Modu... |
import sys
import time
import ipdb
import numpy as np
import os
path = os.path.realpath('../')
if not path in sys.path:
sys.path.insert(0, path)
from pyDecorators import InOut, ChangeState, Catch
class <YourLaserName>(object):
def __init__(self, **kwargs):
super(<YourLaserName>, self).__init__()
... |
class Planet():
"""
This object represents a planet
_________________________________________________
Attributes:
name, mass, aphelion, perihelion, semi_major_axis,
eccentricity, orbital_period, synodic_peroid
_________________________________________________
"""
def __init__(self,
... |
"""Test migration
Revision ID: 5df4b399aae2
Revises: 486c860564a2
Create Date: 2022-03-17 11:41:30.500797
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '5df4b399aae2'
down_revision = '486c860564a2'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gener... |
from consolemenu import *
from consolemenu.items import *
import modules
class Modules:
def __init__(self):
self.modules = {}
self.menu = ConsoleMenu("Modules", "Run code on the db data.")
def register_module(self, module_name, module_func):
self.modules[module_name] = module_func
... |
""" Generate disconnected testrespiratory network """
import graph_tool.all as gt
import pickle
f = open('param_files/param_dashevskiy.pkl')
p = pickle.load(f)
f.close()
# setup "enum" types
CS = 0
CI = 1
TS = 2
Sil = 3
gCaN_array = (p['gCaNS'], p['gCaNI'], p['gCaNTS'], p['gCaNSil']);
gP_array = (p['gPS'], p['gPI... |
supported_vector_sizes = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
result = ""
for i in range(len(supported_vector_sizes)):
vsize = supported_vector_sizes[i]
if i == 0:
result += "#if"
else:
result += "#elif"
result += " STANDARD_VECTOR_SIZE == " + str(vsize) + "\n"
result += "const sel_t FlatVec... |
def read_source_json(source):
from sheetsite.json_spreadsheet import JsonSpreadsheet
wb = JsonSpreadsheet(source['filename'])
return wb
|
"""Functions for making test data JSON-serializable.
"""
from collections import Counter
import json
def serializable(obj):
"""Return whether `obj` is JSON-serializable."""
try:
json.dumps(obj)
except (TypeError, OverflowError):
return False
return True
def make_collector(report, re... |
#!/usr/bin/env python3
from __future__ import division
from builtins import str
import os, sys, time, json, requests, logging
import re, traceback, argparse, copy, bisect
from xml.etree import ElementTree
from UrlUtils import UrlUtils
import util
import gtUtil
from util import ACQ, InvalidOrbitException
import datetim... |
# -*- coding: utf-8 -*-
from scrapy.selector import Selector
from scrapy import Request
import re
import execjs
from gorden_crawler.spiders.shiji_base import BaseSpider
from gorden_crawler.items import BaseItem, ImageItem, SkuItem, Color
import copy
import json
import logging
import difflib
import requests
import datet... |
import json
import logging
import msgpack
log = logging.getLogger(__name__)
class QuacGeneralProcessor:
def __init__(self, args):
self.train_file = args.train_file
self.dev_file = args.dev_file
self.save_train_file = args.save_train_file
self.save_dev_file = args.save_dev_file
... |
from collections import defaultdict
import gzip
import re
# Code snipped from:
# https://gist.github.com/slowkow/8101481
GTF_HEADER = ['seqname', 'source', 'feature', 'start', 'end', 'score', 'strand', 'frame']
R_SEMICOLON = re.compile(r'\s*;\s*')
R_COMMA = re.compile(r'\s*,\s*')
R_KEYVALUE = re.compile(r'(\s+|... |
import numpy as np
from typing import List, Tuple
def hard_disk(x, y, r=1.0, center=(0, 0), scale=100):
"""
A circular barrier
"""
xc, yc = center
v_grid = np.zeros((len(y), len(x)))
barrier_cond = np.add.outer((y - yc) ** 2, (x - xc) ** 2) <= r ** 2
v_grid[barrier_cond] = scale
retur... |
from javax.swing import *
from java.awt import *
from java.awt.event import *
from variables import *
from javax.swing.table import DefaultTableModel
import sys
from importFiles import *
from JMRIlistAll import *
class ListAllJmriLocations(JDialog):
def __init__(self):
JDialog.__init__(self, None, 'All ... |
import visa
rm = visa.ResourceManager()
print(rm.list_resources())
inst = rm.open_resource('GPIB0::23::INSTR')
print(inst.query("*IDN?")) |
import requests
from bs4 import BeautifulSoup
import random
import os
import click
l=[] #For storing random numbers
choice=input("How many random images you want to download?? \n")
def download_img(data,filename): #Function to download images
if (os.path.isdir('XKCD')): #Asserts for existence
pass
e... |
import pyspark.sql.types as t
from datalakebundle.table.schema.TableSchemaGenerator import TableSchemaGenerator
schema = t.StructType(
[
t.StructField("FIELD1", t.IntegerType()),
t.StructField("FIELD2", t.DoubleType()),
t.StructField("FIELD3", t.DoubleType()),
t.StructField(
... |
from abc import ABC, abstractmethod
from typing import Union
import numpy as np
class ForwardCurve(ABC):
"""
Abstract base class for deterministic forward curves.
Examples:
Equity: F(T) = S_0 * Div(T) / Disc(T) (more generally includes dividends, borrow cost, etc.)
FX: F(T) = F... |
from collections import OrderedDict
import blueice.exceptions
import pytest
import numpy as np
from blueice import pdf_morphers
def test_morpher_api():
conf = dict(hypercube_shuffle_steps=2,
r_sample_points=2)
for name, morph_class in pdf_morphers.MORPHERS.items():
print("Testing %s"... |
# coding: utf-8
from __future__ import unicode_literals
import pytest
# fmt: off
TEXTS = ("作为语言而言,为世界使用人数最多的语言,目前世界有五分之一人口做为母语。",)
JIEBA_TOKENIZER_TESTS = [
(TEXTS[0],
['作为', '语言', '而言', ',', '为', '世界', '使用', '人', '数最多',
'的', '语言', ',', '目前', '世界', '有', '五分之一', '人口', '做',
'为', '母语', '。'... |
# Copyright 2016 Eotvos Lorand University, Budapest, Hungary
#
# 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... |
import zen
import numpy
import unicodedata
import sys
sys.path.append('../zend3js/')
import d3js
import csv
import progressbar
import numpy.linalg as la
import matplotlib.pyplot as plt
plt.ioff()
from scipy.linalg import solve
from numpy import *
from time import sleep
import random
G_1=zen.io.gml.read... |
#print("Hello"+ " " + "World")
#print('Enter Your name')
#val=input('Enter your name : ')
#print("The length of your name is - " +str(len(val)))
a=input("Enter value of a ")
b=input("Enter value of b ")
print("Swapping varibales ==" )
c=b
b=a
a=c
print(a)
print(b)
|
import os
import time
import boto3
from sklearn.model_selection import train_test_split
import pickle
import cv2
import pytesseract
import spacy
#Comment out the next line if you are using a CPU to train your model
spacy.prefer_gpu()
from utils import evaluate_model()
from utils import save_model()
import... |
from django.test import TestCase, client
class SmokeTest(TestCase):
"""I.e., does it run?"""
def SetUp(self):
self.client = client.Client()
def fetch(self, path, status):
"""See if the specified page produces the expected HTTP status"""
response = self.client.get(path)... |
from core.terraform.resources import TerraformResource
from core.config import Settings
from core.providers.aws.boto3 import batch
class BatchComputeEnvironmentResource(TerraformResource):
"""
Base resource class for Terraform AWS Batch compute environment resource
Attributes:
resource_instance_n... |
import pathlib
from ftplib import FTP
ftp = FTP(
"10.10.10.5",
"anonymous",
passwd=""
)
fnames = open("filename.list","r")
fn = fnames.readlines()
plist = open("password.list","r")
pwd = plist.readlines()
for i in range(12):
pf = pathlib.Path(fn[i].rstrip('\n') +".txt")
pf.touch()
w... |
#
# Copyright (c) 2021, NVIDIA 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.0
#
# Unless required by applicable law or agreed ... |
# Quick tests for the markup templatetags (django_markwhat)
import re
import unittest
from django.template import Template, Context
from django.utils.html import escape
try:
import textile
except ImportError:
textile = None
try:
import markdown
markdown_version = getattr(markdown, "version_info", 0)... |
# -*- coding: utf-8 -*-
import os
import json
from flask import current_app, request, Response
from flask.ext.restful import abort, fields, marshal_with, marshal
from sqlalchemy.orm.exc import NoResultFound
from export_report import ExportOgranisationsResource
from domain.models import Address, Organisation, Person, ... |
"""
A Pillow loader for .ftc and .ftu files (FTEX)
Jerome Leclanche <jerome@leclan.ch>
The contents of this file are hereby released in the public domain (CC0)
Full text of the CC0 license:
https://creativecommons.org/publicdomain/zero/1.0/
Independence War 2: Edge Of Chaos - Texture File Format - 16 Octobe... |
import contextlib
import os
@contextlib.contextmanager
def modified_environ(*remove, **update):
"""Temporarily updates the os.environ dictionary in-place."""
env = os.environ
update = update or {}
remove = remove or []
# List of environment variables being updated or removed.
stomped = (set(u... |
""" PUBLIC CONSTANTS """
DOMAIN = "script_engine"
CLASS_NAME_PATTERN = '_Script_*'
FILE_NAME_PATTERN = 'script_*.py'
FUNCTION_NAME_PATTERN = '_script_*'
SCRIPT_FOLDER = "/config/script_engine/"
|
from glob import glob
import os
import os.path
import shutil
import subprocess
import sys
from argparse import ArgumentParser
def pad_number(num):
length = len(str(num))
return ((3 - length) * '0') + str(num)
ddpost_par = """
'{e_file}' = name of file with E stored
'{outfile}' = p... |
# -*- coding: utf-8 -*-
import turtle
def main():
window = turtle.Screen()
tortuga = turtle.Turtle()
make_square(tortuga)
turtle.mainloop()
def make_square(turtle):
lenght = int(raw_input('Digite el largo del lado: '))
for i in range(4):
make_line_and_turn(turtle, lenght)
def make_line_and_turn(turtle, le... |
import json
import os
import re
import psutil
import time
import redis
from flask import Flask
from flask import render_template
from flask import jsonify
app = Flask(__name__)
r = redis.StrictRedis(host='localhost', port=6379, db=0)
log_path = '/opt/doorbell/logs'
@app.route("/", methods=['GET'])
def hello():
... |
from __future__ import division
import collections
from typing import Any, Dict, List, Optional, Union
import astropy.units as u
import numba as nb
import numpy
import scipy.integrate
from past.utils import old_div
from astromodels.core.memoization import use_astromodels_memoization
from astromodels.core.parameter i... |
import pygame
from engine import *
from eventManager import *
class Label(Engine.GUI.Widget):
def __init__(self, text, textColor = None, backgroundColor = None, fontSize = None, padding = None, width = None, height = None, transparentBackground = True):
super().__init__()
self.textColor = textColo... |
"""
백준 10162번 : 전자레인지
"""
a = 300
b = 60
c = 10
n = int(input())
i = n // a
n -= a * i
j = n // b
n -= b * j
k = n // c
n -= c * k
if n != 0:
print(-1)
else:
print(i, j, k) |
# coding=UTF-8
from .attributes import Mutation as M
from .attributes import VerbTense as VT
from .attributes import VerbDependency as VD
from .attributes import VerbPerson as VPN
class VerbTenseRule:
def __init__(self,
particle: str = "",
mutation: M = M.NoMut,
... |
/home/runner/.cache/pip/pool/fe/ca/59/86e292e614eb58e873ac46f32bb19e13a24808e2adf28dec6abb5ce99f |
import os
import re
import struct
import sys
import textwrap
sys.path.insert(0, os.path.dirname(__file__))
import ufunc_docstrings as docstrings
sys.path.pop(0)
Zero = "PyInt_FromLong(0)"
One = "PyInt_FromLong(1)"
True_ = "(Py_INCREF(Py_True), Py_True)"
False_ = "(Py_INCREF(Py_False), Py_False)"
None_ = object()
AllO... |
# reference ==>
import taichi as ti
import handy_shader_functions as hsf
import argparse
ti.init(arch = ti.cuda)
res_x = 512
res_y = 512
pixels = ti.Vector.field(3, ti.f32, shape=(res_x, res_y))
@ti.kernel
def render(t:ti.f32):
# draw something on your canvas
for i,j in pixels:
# Set const
... |
# -*- coding: utf-8 -*-
from cms.admin.dialog.forms import PermissionAndModeratorForm, PermissionForm, ModeratorForm
from cms.models import Page
from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required
from django.http import Http404, HttpResponse
from django.shortcuts im... |
'''
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that node. If such a node does not exist, return null.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self,... |
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from api.models.ec.organization import Organization
from api.models.ec.store import Store
from django.core.cache import caches
from django.contrib.sites.models import Site
class SubDomain(models.Model):
class Meta:... |
import unittest
# O(1). Bit manipulation.
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
prev = n & 1
n >>= 1
while n:
if n & 1 ^ prev:
prev ^= 1
n >>= 1
else:
... |
#
# MIT License
#
# (C) Copyright 2020-2022 Hewlett Packard Enterprise Development LP
#
# 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
# the... |
#!/usr/bin/env python
oracle_home = '/usr/local/ohs'
domain_name = 'base_domain'
domain_home = oracle_home + '/user_projects/domains/' + domain_name
node_manager_name = 'localmachine'
node_manager_listen_address = 'localhost'
node_manager_listen_port = '5556'
node_manager_username = 'ohs'
node_manager_password = 'welc... |
(lambda N:(lambda N,A:print(("Average: %.2f\n"%A)+str([n for n in N if len(n)>A])))(N,sum([len(n)for n in N])/len(N)))([n.strip()for n in __import__("sys").stdin])
|
#!/usr/bin/env python
import random
import numpy as np
from cs224d.data_utils import *
import matplotlib.pyplot as plt
from c5_word2vec import *
from c6_sgd import *
random.seed(314)
dataSet = StanfordSentiment()
tokens = dataSet.tokens()
nWords = len(tokens)
# We are going to train 10-dimensional vectors for this ... |
"""Implementation of treadmill admin aws role.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import io
import json
import logging
import click
from treadmill import cli
from treadmill import exc
from treadmil... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
# Django
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponse
# tools
from comic_app.tools.extract_comic_titles import extract_image_comics
from comic_app.tools.extract_comic_titles import extract_marvel_comics
from comic_app.tools.extract_comic_titles import extract_dc_comics
fr... |
## @ingroup Components-Energy-Networks
# Battery_Ducted_Fan.py
#
# Created: Sep 2014, M. Vegh
# Modified: Jan 2016, T. MacDonald
# Apr 2019, C. McMillan
# Apr 2021, M. Clarke
# ----------------------------------------------------------------------
# Imports
# -------------------------------------... |
class WindowError(Exception):
"""
Base exception for errors thrown by the window framework.
Idealy, this could be used to catch every error raised by this library.
This does not include errors raised by the underlying graphics backend.
"""
pass |
import numpy as np
from matplotlib import pyplot as plt
def plot_diagrams(
diagrams,
plot_only=None,
title=None,
xy_range=None,
labels=None,
colormap="default",
size=20,
ax_color=np.array([0.0, 0.0, 0.0]),
diagonal=True,
lifetime=False,
legend=True,
show=False,
ax=N... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
# Generated by Django 3.2.3 on 2021-06-10 01:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('rosters', '0040_roster_settings'),
]
operations = [
migrations.AlterModelOptions(
name='rostersettings',
options={'permissio... |
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
l, res = 0, 0
for r in range(len(s)):
if s[r] in dic:
l = max(dic[s[r]], l)
dic[s[r]] = r + 1
res = max(res, r - l + 1)
return res
s = Solution()
print(s.... |
import argparse
import json
import os
import pickle
import sys
import time
from typing import Iterable, List, Dict
from rlo import config_utils
from rlo.cost_normalizers import available_cost_normalizers
from rlo.dataset_refiner import get_available_dataset_refiners
from rlo import factory
from rlo.extra_plots import ... |
from django import forms
from django.core.exceptions import ValidationError
from pyparsing import ParseException
from .grammar import parse
class SearchField(forms.CharField):
def clean(self, *args, **kwargs):
value = super().clean(*args, **kwargs)
if not value:
return ""
try:... |
# -*- coding: utf-8 -*-
"""
@author : Wang Meng
@github : https://github.com/tianpangji
@software : PyCharm
@file : permissions.py
@create : 2021/2/14 17:11
"""
import json
from system.models import Permissions
def redis_storage_permissions(redis_conn):
permissions = Permissions.objects.filter(menu=Fal... |
import os
import matplotlib.pyplot as plt
import imageio
def visualize_ground_truth(mat, size=4.0):
"""
`mat`: (d, d)
"""
plt.rcParams['figure.figsize'] = [size, size]
fig, ax = plt.subplots(1, 1)
ax.matshow(mat, vmin=0, vmax=1)
plt.setp(ax.get_xticklabels(), visible=False)
plt.se... |
#!/usr/bin/env python3
import sys
import unittest
sys.path.append('.')
from logger.transforms.prefix_transform import PrefixTransform
class TestPrefixTransform(unittest.TestCase):
def test_default(self):
transform = PrefixTransform('prefix')
self.assertIsNone(transform.transform(None))
self.assertEqu... |
import json
import re
from datetime import time, date, datetime
from enum import Enum
from typing import Any, Type, Union, List, Dict, Set, Optional, TypeVar, Sized, overload, Callable, cast
from .base import Field, Cleaned
from .errors import ValidationError, ErrorCode
T1 = TypeVar('T1')
T2 = TypeVar('T2')
VT = Typ... |
from django.contrib import admin
from products.models import *
# Register your models here.
admin.site.register(Product)
admin.site.register(MainProductsCategorie)
admin.site.register(ProductsSubCategorie)
|
# Copyright 2019 Julie Jung <moonyouj889@gmail.com>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by ap... |
from tqdm import tqdm
from rdkit import Chem
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
from pathlib import Path
def normalize_inchi(inchi):
try:
mol = Chem.MolFromInchi(inchi)
return inchi if (mol is None) else Chem.MolToInchi(mol)
except: return inchi
# Segfault in rdkit take... |
class Pessoa:
olhos =2
def __init__(self,*filhos,nome= None,idade=35):
self.idade = idade
self.nome=nome
self.filhos =list(filhos)
def cumprimentar(self):
return f'Olá, meu nome é {self.nome}'
@staticmethod
def metodo_estatico():
return 42
@classmethod
... |
# NLP written by GAMS Convert at 04/21/18 13:54:05
#
# Equation counts
# Total E G L N X C B
# 253 253 0 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... |
'''
Created on Feb 15, 2016
@author: jason
'''
from .sklearntools import MultipleResponseEstimator, BackwardEliminationEstimatorCV, \
QuantileRegressor, ResponseTransformingEstimator
from pyearth import Earth
from sklearn.pipeline import Pipeline
from sklearn.calibration import CalibratedClassifierCV
outcomes = ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import waflib.TaskGen
import waflib.Task as Task
from waflib import Utils
import waflib
import os.path as osp
import os
def uniqify(lst):
rlst = []
for v in lst:
#print v, rlst
if v in rlst:
#... |
"""
Tests for dit.example_dists.numeric.
"""
import pytest
import numpy as np
from dit.shannon import entropy
from dit.example_dists import bernoulli, binomial, hypergeometric, uniform
def test_bernoulli1():
""" Test bernoulli distribution """
d = bernoulli(1 / 2)
assert d.outcomes == (0, 1)
assert... |
import os
import logging
import asyncio
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
class OutputWorker(object):
def __init__(self, **kwargs):
self.type = kwargs.get("type", None)
self.logger = logging.getLogger(__name__)
output_dir = kwargs.get("output_dir", No... |
from triangle import Triangle
def saccade_model_mle(gazepoints, src_xy, tgt_xy, init_t_start, init_t_end):
'''
Parameter
gazepoints
src_xy, 2D list, best quess for saccade start location
tgt_xy, 2D list, best guess for saccade end location
init_t_start, best guess for saccade start time
init_t_end, best... |
import linkr # flake8: noqa: F401
import time
import mock
from models import Link
from test.backend.test_case import LinkrTestCase
with mock.patch.object(time, 'time', return_value=5):
link = Link(
alias='alias',
outgoing_url='outgoing url',
)
link.link_id = 1
class TestLink(LinkrTes... |
import pandas as pd
import sqlite3
path = "C:/Users/Grace Sun/physics_hackathon/"
db_path = path+'/Databases/'
strings = ["Attacks", "Characters", "Cleric", "Conditions", "Damage Types", "Fighter", "Items", "Monsters", "Rogue", "Save Types", "Spells", "Weapons", "Wizard"]
for string in strings:
conn = sqlite3.conne... |
import os
import math
import json
import random
import numpy as np
import networkx as nx
from abc import ABC, abstractmethod
from barl_simpleoptions.state import State
class Option(ABC) :
"""
Interface for a reinforcement learning option.
"""
def __init__(self) :
pass
@abstractmethod
... |
from skimage import io
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from tifffile import imsave
def threshold(imgarray, darkparticles, sigma, thresholdvalue, usesigma):
newarray = imgarray
if (imgarray.ndim) > 1:
newarray = imgarray.flatten
mean = np.average(imgarra... |
import tvm
import math
import numpy as np
from functools import reduce
import utils
assert_print = utils.assert_print
gen_enum = utils.gen_enum
any_factor_split = utils.any_factor_split
get_factor_lst = utils.get_factor_lst
gen_group = utils.gen_group
is_power_of_x = utils.is_power_of_x
def able_inline(op, down_grap... |
# lambdas are single expressions used in declaring
a = lambda x, y, d: x * 6 - d + y*d -x
ans = a(3,5,8)
print(ans) # --> 47
print((lambda x, y, d: x * 6 - d + y*d - x)(3, 5, 8)) # --> 47
# Lambdas can be used as lexical closures in other functions
def adder(n):
return lambda x: x + n # uses n from outer s... |
from django.contrib import admin
from .models import Post
# Register your models here.
admin.site.register(Post) |
from ..vector3 import Vector3
gravity = Vector3(0, -9.81, 0)
"""Gravitational constant (9.81 m/s^2)"""
|
import pytest
from pytest_bdd import given, scenario, then, when, parsers
import os
import subprocess
import time
from common.mayastor import container_mod, mayastor_mod
from common.volume import Volume
import grpc
import mayastor_pb2 as pb
def megabytes(n):
return n * 1024 * 1024
def find_child(nexus, uri):... |
# # from __future__ import print_function
import argparse
from tqdm import tqdm
import tensorflow as tf
import logging
logging.getLogger().setLevel(logging.INFO)
from utils.lr_scheduler import get_lr_scheduler
from model.model_builder import get_model
from generator.generator_builder import get_generator
import sys
phy... |
"""Module controlling the writing of ParticleSets to NetCDF file"""
import os
import random
import shutil
import string
from datetime import timedelta as delta
from glob import glob
import netCDF4
import numpy as np
from parcels.tools.error import ErrorCode
from parcels.tools.loggers import logger
try:
from mpi4p... |
'''初始化'''
from .mole import Mole
from .hammer import Hammer |
from collections import OrderedDict
from coreapi.compat import urlparse
from openapi_codec.utils import get_method, get_encoding, get_links_from_document
from openapi_codec import encode
class AbstractCodec:
def _generate_swagger_object(self, document):
parsed_url = urlparse.urlparse(document.url)
... |
import subprocess
import time
class LiteClient:
def __init__(self, args, config, log):
self.log = log
self.config = config
self.ls_addr = args.ls_addr
self.ls_key = args.ls_key
self.log.log(self.__class__.__name__, 3, 'liteClient binary : ' + self.config["bin"])
sel... |
import requests
with open('file.txt', 'rb') as f:
data = f.read()
response = requests.put('http://localhost:28139/file.txt', data=data)
|
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.ticker as mticker
import csv
import json
import math
import random
import bisect
import os
import argparse
import fnmatch
import sys
import statistics
from enum import Enum
from typing import *
... |
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), '..')) # append the MIALab root directory to Python path
import SimpleITK as sitk
import pymia.filtering.filter as fltr
import pymia.filtering.registration as fltr_reg
import mialab.data.structure as structure
import mialab.utilities.... |
from osiris.base.environments import env
def example():
value = env.get_property("sys.aws.region_name")
print(value)
if __name__ == '__main__':
example()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-10-27 15:45
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
d... |
import os
import numpy as np
from PIL import Image
import torch
import torchvision
import torchvision.datasets
from torchvision import transforms
from torch.utils.data import Dataset
from torch.utils.data import DataLoader, Dataset, Sampler
class LT_Dataset(Dataset):
num_classes = 365
def __init__(self, root... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.