content stringlengths 5 1.05M |
|---|
# encoding: utf-8
'''Cache-related utilities.
'''
from types import *
import sys, os
__all__ = ['callable_cache_key', 'app_shared_key']
def callable_cache_key(node):
'''Calculate key unique enought to be used for caching callables.
'''
if not isinstance(node, (MethodType, FunctionType)):
return hash(node.__... |
import abc
import dataclasses
import logging
from datetime import timedelta
from typing import Dict, List, Optional, Union
import confluent_kafka # type: ignore
from .auth import SASLAuth
from .errors import (DeliveryCallback, ErrorCallback, log_client_errors,
log_delivery_errors)
class Produc... |
'''
Function Name : ProcessDisplay
Description : In This Application It Generate Log Files After Every 5 Minutes And Store All Log File In Running_Process Folder
Function Date : 19 July 2021
Function Author : Prasad Dangare
Input : Get The Directory Name
Output : It Create One ... |
import paramiko
import getpass
from time import sleep
username = raw_input("Enter your username: ")
#Remove below sharp sign to hard code your password
#password = "YOUR PASSWORD HERE"
#use below line to ask for password and echo it to user
#password = raw_input("Enter your password: ")
#use below line to ask for pass... |
import os, _cbstools
__dir__ = os.path.abspath(os.path.dirname(__file__))
class JavaError(Exception):
def getJavaException(self):
return self.args[0]
def __str__(self):
writer = StringWriter()
self.getJavaException().printStackTrace(PrintWriter(writer))
return u"\n".join((unicode(super(JavaError,... |
# -*- coding: utf-8 -*-
#
# setup.py
#
# Author: Michael E. Tryby
# US EPA - ORD/NRMRL
#
''' Setup up script for nrtest_swmm package. '''
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
entry_points = {
'nrtest.compare': [
'swmm allclose ... |
class LossScaler(object):
r"""Base class for implementing custom loss scaler strategies
Once the scaler is configured, no user intervention is needed to update loss scale during training.
Note:
This class should never be instantiated, but used as an abstract class for custom loss scaling strategy.... |
import numpy as np
import scipy as sp
from scipy.stats import norm
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
from scipy import sparse
# 机器... |
import unittest
from main import Sudoku
class TestSudoku(unittest.TestCase):
def setUp(self):
self.sudoku = Sudoku([
[0, 0, 0, 2, 6, 0, 7, 0, 1],
[6, 8, 0, 0, 7, 0, 0, 9, 0],
[1, 9, 0, 0, 0, 4, 5, 0, 0],
[8, 2, 0, 1, 0, 0, 0, 4, 0],
[0, 0, 4, 6, 0, 2, 9, 0, 0],
[0, 5, 0, 0, 0,... |
import argparse
from .suite import *
from .synth import *
from .real import *
def parse_arguments():
parser = argparse.ArgumentParser()
group_save_load = parser.add_mutually_exclusive_group()
group_save_load.add_argument("--save", help="File path to store the session data.")
group_save_load.add_arg... |
r"""@package motsfinder.utils
General utilities for simplifying certain tasks in Python.
"""
from __future__ import print_function
import functools
import importlib.util
from builtins import range, map
from tempfile import NamedTemporaryFile
from glob import glob
import os
import os.path as op
import re
import subpr... |
from django.db.models import F, OrderBy
class OrderableAggMixin:
def __init__(self, *expressions, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expres... |
"""
Import json data from URL to Datababse
"""
import requests
import json
import os
from ....product.models import ProductVariant
from django.core.management.base import BaseCommand
from datetime import datetime
from ....settings import PROJECT_ROOT
from prices import Money
import decimal
class Command(BaseCommand):
... |
import warnings
import torch
import torch.fx
import torch.fx.experimental.fx_acc.acc_ops as acc_ops
def trt_transposed_matmul(lhs: torch.Tensor, rhs: torch.Tensor, lhs_transposed: bool, rhs_transposed: bool):
if lhs_transposed:
lhs = lhs.transpose(-1, -2)
if rhs_transposed:
rhs = rhs.transpose... |
import numpy as np
import pybullet as p
import time
import matplotlib.pyplot as plt
from cep.envs import Tiago_LeftParallelHand_Base
from cep.cep_models import cep_tiago_base_pathplan_x
import torch
joint_limit_buffers = 0.02
joint_limits = np.array([2.5, 2.5, 3.1416, 2.75, 1.57, 3.53, 2.35, 2.09, 1.57, 2.09]) - join... |
from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription([
Node(
package='ackermann_controller',
executable='ackermann_teleop_joy',
parameters=[
{'max_speed': 1},
... |
import random
import math
import typing
from misc import module_utils
import torch
from torch import nn
from torch.nn import functional
from torch.nn import init
from torchvision import models
def default_conv(
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int=1,
... |
from brownie import ERC20Basic, config, accounts
def deployContract():
account = accounts.add(config["wallets"]["from_key"])
ERC20Basic.deploy(100000000,{'from': account})
def main():
deployContract()
|
#! /usr/bin/env python
#
# Copyright (c) 2019 Daw Lab
# https://dawlab.princeton.edu/
import os, sys
from setuptools import setup, find_packages
path = os.path.abspath(os.path.dirname(__file__))
## Metadata
DISTNAME = 'sisyphus'
MAINTAINER = 'Sam Zorowitz'
MAINTAINER_EMAIL = 'zorowitz@princeton.edu'
DESCRIPTION = 'Ev... |
"""Dummy command workers module for various test cases."""
|
"""Utility functions for MongoDB document insertion, updates and retrieval."""
from typing import (Any, List, Mapping, Optional)
from bson.objectid import ObjectId
from pymongo.collection import ReturnDocument
from pymongo import collection as Collection
def find_one_latest(collection: Collection) -> Optional[Mappi... |
# -*- coding=UTF-8 -*-
# pyright: strict
from __future__ import annotations
from collections import defaultdict
from copy import deepcopy
from typing import (
TYPE_CHECKING,
Any,
Callable,
DefaultDict,
Dict,
Iterable,
List,
Sequence,
Set,
Tuple,
TypeVar,
)
from ... import... |
import json
from datetime import datetime as dt
import requests
from django.contrib import admin
from django.conf import settings
from django import forms
from .models import History
class HistoryAdminForm(forms.ModelForm):
class Meta:
model = History
widgets = {}
fields = '__all__'
def __... |
#!/usr/bin/env python3
'''
Пример объектной организации кода
'''
from tkinter import *
from tkinter import colorchooser
class App(Frame):
'''Base framed application class'''
def __init__(self, master=None, Title="Application"):
Frame.__init__(self, master)
self.master.rowconfigure(0, weight=1)... |
#!/usr/bin/env python
import sys
def fun(gtf):
D = {}
with open(gtf) as handle:
for l in handle:
if l.startswith('#') or l.startswith('\n'):
continue
tmplist = l.split('\t')
qStart = int(tmplist[3])
qEnd = int(tmplist[4])
ite... |
# -*- coding: utf-8 -*-
"""Core Auxein mutations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from abc import ABC, abstractmethod
from auxein.population.genotype import Genotype
import numpy as np
class Mutation(ABC):
def __init__(self, exten... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from pants.bsp.spec.base import Uri
from pants.bsp.utils import freeze_json
@dataclass(frozen... |
import os
import time
from datetime import datetime as dt, timedelta
from dateutil.parser import parse as date_parse
os.chdir('..')
from RScheduler import TaskScheduler
def job(x, y): print(x, y)
def test_registry():
s = TaskScheduler()
s.every("businessday").at("10:00").do(job, x="hello", y="world")
s.on('2019-0... |
# Generated by Django 2.0.9 on 2019-03-08 03:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tracking', '0002_auto_20190111_1434'),
]
operations = [
migrations.AlterField(
model_name='device',
name='district',... |
# Copyright 2017 F5 Networks Inc.
#
# 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 writi... |
#! /usr/bin/env python3
"""pretty-print json data in a given file
saves a pretty-printed version instead of overwriting the original
"""
import sys
import os
import json
INDENT = 2
def prettify(filename):
"""input: filename
output: None
side-effect: a file containing the pretty printed json
"""
... |
#MenuTitle: Move All Paths Position to Left Bottom
# -*- coding: utf-8 -*-
__doc__="""
左下の座標が(0,ディセンダー値)になるようにパスを移動
"""
Glyphs.clearLog()
font = Glyphs.font
layer = font.selectedLayers[0]
desc = layer.descender
nodeMinX = layer.bounds.origin.x
nodeMinY = layer.bounds.origin.y
#x,y座標を移動する
for thisPath in layer.paths... |
#!/usr/bin/env python3
import datetime
import json
import os
import re
import fnmatch
from PIL import Image
import numpy as np
import sys
sys.path.append('../')
from pycococreatortools import pycococreatortools
ROOT_DIR = '/home/ccchang/disk2_1tb_ssd/robot_dataset/panel_exp_fixed/mycoco/'
###Synthetic images
IMAGE_... |
from hamilton import node
from hamilton.experimental.decorators import augment
|
import torch.nn.functional as F
from torch import nn
class CapsuleLoss(nn.Module):
def __init__(self):
super(CapsuleLoss, self).__init__()
def forward(self, classes, labels):
left = F.relu(0.9 - classes, inplace=True) ** 2
right = F.relu(classes - 0.1, inplace=True) ** 2
marg... |
import wikipedia
print(len(wikipedia.summary("Albert Einstein", sentences=15))) |
import datetime
from collections import namedtuple
from . import consts as C
from .exceptions import FileFormatError, RDBValueError
from .util import read_byte, read_int, skip_bytes, unpack, unpack_pairs
from .intset import unpack_intset
from .ziplist import unpack_ziplist
from .zipmap import unpack_zipmap
from .lzf i... |
from .assay import AssayBuilder
from .glycoassay import GlycoAssayBuilder
|
from .bbox_nms import multiclass_nms
from .bbox_nms_reid import multiclass_nms_reid
from .merge_augs import (merge_aug_bboxes, merge_aug_masks,
merge_aug_proposals, merge_aug_scores)
__all__ = [
'multiclass_nms', 'multiclass_nms_reid', 'merge_aug_proposals', 'merge_aug_bboxes',
'merge... |
class Route:
'''
route decorator
'''
def __init__(self, app):
# introduction app (framework) instance
self.app = app
def __call__(self, url, **options):
'''
implement call method
'''
# if methods parameter not define, then init just support GET met... |
from collections import defaultdict
from util import UNDEF_ADDR, CFuncGraph, GraphBuilder, hexrays_vars, get_expr_name
import idaapi
import ida_hexrays
import json
import jsonlines
import os
import re
import subprocess
import sys
try:
from CStringIO import StringIO ## for Python 2
except ImportError:
from io i... |
# coding: utf-8
# Copyright © 2014-2020 VMware, Inc. All Rights Reserved.
################################################################################
from typing import Dict
from unittest import TestCase
from cbopensource.connectors.taxii.taxii_connector_config import TaxiiConnectorConfiguration
from cbopensourc... |
# Client Payment Python SDK
# API docs at https://github.com/Space-Around/client-payment-sdk-python
# Authors:
# Viksna Max <viksnamax@mail.ru>
# ClientPaymentSDK
from .client import ClientPaymentSDK
from .sign import sign
from .exceptions import ClientPaymentSDKError, RequestError, InternalServerError, SignatureVerif... |
#!/usr/bin/env python3
import importlib.util, os.path, sys
__all__ = ("update", "reset_to_zero", "increment_revision_if_not_frozen")
VERSION_PY_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"version.py"
)
def _module_from_file(module_name, file_path):
spec = importlib.util.spec_from_fi... |
import logging
import time
from BaseHTTPServer import BaseHTTPRequestHandler
from threading import Thread, Lock, Condition
from lib.proxy import proxy_sockets
from lib.stats import EC2StatsModel
from lib.utils import ThreadedHTTPServer
logger = logging.getLogger(__name__)
class Message(object):
def __init__(s... |
"""Imprime 'Fizz' se o número digitado for divisível por 3"""
numero = int(input('Digite um número: '))
if numero % 3 == 0:
print('Fizz')
else:
print(numero)
|
from __future__ import division
from Util import *
class Solfeggio:
@staticmethod
def solfeggios ():
for seq in [
[1, 4, 7],
[5, 2, 8],
[3, 6, 9]]:
for perm in permutations (seq):
yield list_to_number (perm)
@staticmethod
def chrang (chakra, rang):
return solfeggio[rang, chakra]
ranges = ["low... |
from __future__ import division
from __future__ import print_function
import torch.nn as nn
def conv2d(channels_in, channels_out, kernel_size=3, stride=1, bias = True):
return nn.Sequential(
nn.Conv2d(channels_in, channels_out, kernel_size=kernel_size, stride=stride, padding=(kernel_size-1)//2, bia... |
"""Utility functions finding which storage type is used."""
from birgitta import context
__all__ = ['stored_in']
def stored_in(t):
"""Returns true if storage type equals t"""
storage_type = context.get("BIRGITTA_DATASET_STORAGE")
return t == storage_type
|
#!usr/bin/env python
#-*- coding:utf-8 -*-
"""
@author: nico
@file: serializers.py
@time: 2018/08/24
"""
from rest_framework import serializers
from generic_relations.relations import GenericRelatedField
from blog.api.serializers import PostListSerializer
from blog.models import Post
from oper.m... |
import os
from xml.dom import minidom
from xml.dom.minidom import parseString
from xml.etree import ElementTree
import lxml.etree as ET
from eatb.utils.fileutils import read_file_content
from eatb.xml.xmlschemanotfound import XMLSchemaNotFound
def pretty_xml_string(xml_string):
xml = parseString(xml_string)
... |
import helpers
import contextio as c
CONSUMER_KEY = "YOUR_CONTEXTIO_CONSUMER_KEY"
CONSUMER_SECRET = "YOUR_CONTEXTIO_CONSUMER_KEY"
api = c.ContextIO(
consumer_key=CONSUMER_KEY,
consumer_secret=CONSUMER_SECRET,
debug=True
) # returns v2.0 API by default
helpers.headerprint("FETCHING ACCOUNTS (v2.0 API)")
... |
#!/usr/bin/python
# this source is part of my Hackster.io project: https://www.hackster.io/mariocannistra/radio-astronomy-with-rtl-sdr-raspberrypi-and-amazon-aws-iot-45b617
# this program will determine the overall range of signal strengths received during the whole session.
# this program can be run standalone but... |
#
# Not used at the moment, but will be needed later
#
import os
def get_nova_credentials():
d = {}
d['version'] = '2'
d['username'] = os.environ['OS_USERNAME']
d['api_key'] = os.environ['OS_PASSWORD']
d['auth_url'] = os.environ['OS_AUTH_URL']
d['project_id'] = os.environ['OS_TENANT_NAME']
... |
import io
import os
import re
from dataclasses import dataclass, field
from typing import BinaryIO, Dict, Tuple, cast
from .cov_info import BBEntry, CodeBlock, CoverageInfo
from .exceptions import InvalidBBTableHeader, InvalidHeader, InvalidModuleTableHeader
from .module_table_entries import get_proper_module_table_en... |
import datetime
def votar(anonascimento=0):
anonascimento = int(anonascimento)
if anonascimento > ano:
return 'ERRO'
idade = ano - anonascimento
if idade >= 18:
return f'Com {idade} anos podes votar!'
else:
return f'Com {idade} anos não podes votar!'
ano = datetime.dateti... |
import pandas as pd
from mlp import MLP_reg
from neumannS0_mlp import Neumann_mlp
from learning_curves import run
n_iter = 20
n_jobs = 40
n_sizes = [1e5]
n_sizes = [int(i) for i in n_sizes]
n_test = int(1e4)
n_val = int(1e4)
data_type = 'MCAR'
filename = 'MCAR_depth_effect'
compute_br = True
# First fill in data_des... |
"""
Copyright 2013 Rackspace
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, software
dist... |
import numpy as np
from coptim.optimizer import Optimizer
class GradientMethodExactMinimization(Optimizer):
def __init__(self):
# TODO: More metrics: vector of x's, objective values, etc.
self.iterations = 0
def step_size(self, Q, c, x, d, func):
g = func.gradient(Q, c, x)
re... |
from keras.optimizers import Adam
class DiffusionVAEParams(object):
'''
classdocs
'''
def __init__(self,
steps=10,
truncation_radius=0.5,
var_x=1.0,
r_loss="mse",
d=2,
optimizer = Adam(),
... |
### Backend for testing
###Import packages
import sys, os, os.path, h5py, time, shutil
from os import walk
import pandas as pd
import xgboost as xgb
import numpy as np
import matplotlib.pyplot as plt
from shutil import copy
from sklearn.metrics import accuracy_score, f1_score
from scipy.optimize.minpac... |
from django.shortcuts import render
# Create your views here.
def index(request):
title = 'Dashboard'
author = 'Made with 💚 by Diaz Ardian'
content = {
'title': title,
'author': author,
'logo': 'KACANG SERVER'
}
return render(request, 'index.html', content) |
from __future__ import print_function
import logging
import numpy as np
import pandas as pd
import sys
import torch
def SaveModelResultsToCSV(MSE, MAE, r2_score, labels, predictions, name):
x_gt = []
y_gt = []
z_gt = []
phi_gt = []
x_pr = []
y_pr = []
z_pr = []
phi_pr = []
r2_sco... |
import argparse
import os
# workaround to unpickle olf model files
import sys
import time
import numpy as np
import torch
from sevn_model.envs import VecPyTorch, make_vec_envs
from sevn_model.utils import get_render_func, get_vec_normalize
sys.path.append('sevn_model')
parser = argparse.ArgumentParser(description='... |
DEBUG = True
PORT = 8080
EXAMPLE_FOO = 'foo'
EXAMPLE_BAR = 'bar'
|
import pytest
import numpy
from thinc.types import Ragged
from thinc.api import NumpyOps
from ..data_classes import WordpieceBatch
from ..truncate import _truncate_tokens, _truncate_alignment
@pytest.fixture
def sequences():
# Each sequence is a list of tokens, and each token is a number of wordpieces
return ... |
import json
from flask import Blueprint, Response
from rentomatic.repository import memrepo as mr
from rentomatic.use_cases import room_list_use_case as uc
from rentomatic.serializers import room_json_serializer as ser
blueprint = Blueprint('room', __name__)
room1 = {
'code': 'f853578c-fc0f-4e65-81b8-566c5dffa35a... |
from homeworks.aleksey_gukov.hw05 import level04
def test():
assert level04.host("test.com/a/b/c") == "test.com"
assert not level04.host("/a/b")
assert level04.host("/a/b") == ""
assert level04.host("https://github.com/tgrx/Z22/") == "github.com"
assert level04.host("git@github.com:tgrx/Z22.git")... |
import os
import sys
import time
import argparse
import subprocess as sp
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(script_dir, "modules"))
from cparser import Parser
from scanner import Scanner, SymbolTableManager
from semantic_analyser import SemanticAnalyser
from code_... |
# Copyright (c) Xavier Figueroa
# 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, sof... |
"""An example of how to use IPython1 for plotting remote parallel data
The two files plotting_frontend.ipy and plotting_backend.py go together.
To run this example, first start the IPython controller and 4
engines::
ipcluster -n 4
Then start ipython in pylab mode::
ipython -pylab
Then a simple "run pl... |
from __future__ import absolute_import
from __future__ import unicode_literals
from git_code_debt.list_metrics import color
from git_code_debt.list_metrics import CYAN
from git_code_debt.list_metrics import main
from git_code_debt.list_metrics import NORMAL
def test_list_metrics_smoke(capsys):
# This test is jus... |
# Form / Checkbox
# Use checkboxes to switch between two mutually exclusive options.
# ---
from h2o_wave import main, app, Q, ui
@app('/demo')
async def serve(q: Q):
if q.args.show_inputs:
q.page['example'].items = [
ui.text(f'checkbox_unchecked={q.args.checkbox_unchecked}'),
ui.te... |
# import pydrakeik first. This is a workaround for the issue:
# https://github.com/RobotLocomotion/director/issues/467
from director import pydrakeik
import director
from director import robotsystem
from director.consoleapp import ConsoleApp
from director import transformUtils
from director import robotstate
from dir... |
#!/usr/bin/python
import argparse, sys, re, random, os, gzip
from multiprocessing import Pool, Lock, cpu_count, Queue
from subprocess import Popen, PIPE
import SimulationBasics
from VCFBasics import VCF
from SequenceBasics import read_fasta_into_hash
from TranscriptomeBasics import Transcriptome
from GenePredBasics imp... |
from pyplan.pyplan.preference_module.models import *
from pyplan.pyplan.preference.models import *
from pyplan.pyplan.users.models import *
from pyplan.pyplan.companies.models import *
from pyplan.pyplan.usercompanies.models import *
from pyplan.pyplan.user_company_preference.models import *
from pyplan.pyplan.company... |
#!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
"""
weather.py - jenni Weather Module
Copyright 2009-2013, Michael Yanovich (yanovich.net)
Copyright 2008-2013, Sean B. Palmer (inamidst.com)
Licensed under the Eiffel Forum License 2.
More info:
* jenni: https://github.com/myano/jenni/
* Phenny: http://inamidst.... |
from datetime import datetime
def test_arg_option_doc():
with open('README.rst') as f:
content = f.read()
option_parts = content.split('Options\n-------')[1].split('Video options\n')[0].strip()
option_parts = option_parts.splitlines()[1:-1]
option_parts = [x.split(' ', 2) for x in option_parts... |
# This script executes the PySedSim runs to produce the results associated with
# Formulation I in Wild et al. (in review)
#import pysedsim
from pysedsim import PySedSim
# instantiate model
pys = PySedSim(file_name = 'formulation_1.csv')
# run a combined serial execution of multiple deterministic and stochastic sim... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.widgets import Slider, Button, RadioButtons
"""
CONIC SECTION COORDINATE VISUALISER
A small script to visualise conic sections in an x & r coordinate system
in terms of a Radius, Bluntness, and two orthogo... |
#Faça um programa que calcule a área de um triângulo, cuja
#base e altura são fornecidas pelo usuário. Esse programa
#não pode permitir a entrada de dados inválidos, ou seja,
#medidas menores ou iguais a 0.
base=float(input("Informe a base do triangulo: "))
altura=float(input("Informe a altura do triangulo: "))
are... |
import beatsaver
def test_getMapFromID():
doesNotExist = beatsaver.maps.get_map_from_id('99999') # map does not exist
assert doesNotExist == None
machinegun = beatsaver.maps.get_map_from_id('9e5c')
assert machinegun.uploader.name == 'de125'
def test_getMapFromHash():
ov = "f402008042efaca4291a... |
import speech_recognition as sr
import pyaudio
# obtain audio from the microphone
from CommandConverters import commandparser
r = sr.Recognizer()
r.energy_threshold = 450 #設定多大能量上才會持續收聽
#r.dynamic_energy_threshold = False
audio = None
with sr.Microphone() as source:
print("current energy is {}".format(r.energy_thre... |
import os
import random
import numpy as np
import cv2
voc_colormap = [
[0, 0, 0],
[128, 0, 0],
[0, 128, 0],
[128, 128, 0],
[0, 0, 128],
[128, 0, 128],
[0, 128, 128],
[128, 128, 128],
[64, 0, 0],
[192, 0, 0],
[64, 128, 0],
[192, 128, 0],
[64, 0, 128],
[192, 0, 128... |
from channels.routing import ProtocolTypeRouter
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'/websocket', consumers.VNCConsumer)
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenOperationBizfeeAftechRefundModel(object):
def __init__(self):
self._app_name = None
self._currency = None
self._fee_order_no = None
self._g... |
from ImageLibrary import utils
from ImageLibrary.image_processor import ImageProcessor, get_image_from_config
def _get_threshold(info, threshold):
if threshold is not None:
return threshold
else:
return info[1]
class Template:
@utils.add_error_info
def __init__(self, name, config):
... |
from .pylineblocks import splitIntoBlocks, reindentBlock
|
from netket import legacy as nk
import numpy as np
import jax
from jax.experimental.optimizers import adam as Adam
# 1D Lattice
L = 20
g = nk.graph.Hypercube(length=L, n_dim=1, pbc=True)
# Hilbert space of spins on the graph
hi = nk.hilbert.Spin(s=1 / 2) ** L
ha = nk.operator.Ising(hilbert=hi, graph=g, h=1.0)
ma = ... |
import logging
import time
import traceback
from datetime import datetime
from threading import Thread
from typing import Optional
from waffles.api.abstract.handler import TaskManager
from waffles.commons.boot import CreateConfigFile
from waffles.commons.html import bold
from waffles.gems.web import get_icon_path
from... |
# from __future__ import print_function
# import csv
import numpy as np
import nltk
from nltk.corpus import wordnet as wn
from nltk import word_tokenize
# from nltk import FreqDist
from nltk.stem import WordNetLemmatizer
# import pandas
from nltk.corpus import stopwords
import string
# from string import maketrans
impo... |
#!/usr/bin/env python3
import re
from collections import namedtuple
Regex = namedtuple(
"Regex",
[
"name",
"expression",
"replacement",
]
)
#: The default regex replacements used by :func:`gatenlphiltlab.normalize`
regexes = (
Regex(
name="left_single_quote",
... |
from datetime import date, timedelta
from unittest import TestCase
from BankAccount import BankAccount, InsufficientFunds
THIRTY_DAYS_AFTER_CREATION = date.today() + timedelta(days=30)
class TestBankAccount(TestCase):
def setUp(self):
self.a = self.create_default_account()
def test_creation(self):
... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: pyide.py
# Purpose:
#
# Author: wukan
#
# Created: 2019-01-10
# Copyright: (c) wukan 2019
# Licence: GPL-3.0
#---------------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
Data engine implementation based on lighting memory database
(http://symas.com/mdb/).
The Lmdb is initialized, the access needs to use its binding API, though.
Extension packages may provide higher-level APIs based on this.
"""
from __future__ import absolute_import, division, unicode_litera... |
# Copyright (c) 2014 Mirantis Inc.
#
# 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 -*-
# python std lib
import sys
# djinja package imports
from djinja import cli
class TestCLI(object):
def test_cli(self, tmpdir):
"""
Test that when passing in certain arguments from commandline they
are handled correctly by docopt and that the method creates a Core... |
#!/usr/bin/env python
from walt.server.threads.main.snmp.base import Variant, VariantsSet, VariantProxy
from walt.server.threads.main.snmp.mibs import load_mib, unload_mib, get_loaded_mibs
POE_PORT_ENABLED=1
POE_PORT_DISABLED=2
POE_PORT_SPEEDS=(10**7, 10**8, 10**9) # 10Mb/s 100Mb/s 1Gb/s
POE_PORT_MAPPING_CACHE = {}... |
# -*- coding=utf8 -*-
"""thrift server"""
import socket
from .ev import server_run
from .const import LISTEN_BACKLOG
class ThriftServer(object):
"""thrift server
Attributes:
service: thrift service
handler: thrift handler
sock (socket)
"""
def __init__(self, service, handler)... |
# -*- coding: utf-8 -*-
"""
Tests for the model.
"""
__author__ = 'Yves-Noel Weweler <y.weweler@fh-muenster.de>'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.