input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
= 0
v_mag_log = la.spectral_crossfade(v_zeros, v_mag_log[None,:], cut_off, bw, fs, freq_scale='hz')[0]
# Phase:
#v_ph = np.hstack((m_ph_deter[i,:], m_noise_ph[i,mvf_bin:]))
v_ph = la.spectral_crossfade(m_ph_deter[None, i,:], m_noise_ph[None,i,:], cut_off, bw, fs, freq_scale='hz')[0]
elif v_voi_mask[i] == 0: ... | |
sname - symbol name
skind - symbol kind
stype - symbol type
sattr - symbol attribute
sattr_name - symbol attribute name (used only for table display)
"""
self.name = sname
self.kind = skind
self.type = stype
self.attribute = sattr
self.attribute_name = sattr_name
self.param_types = []
def set_... | |
<reponame>FooBarWidget/mizuho
#!/usr/bin/env python
"""
asciidoc - converts an AsciiDoc text file to HTML or DocBook
Copyright (C) 2002-2010 <NAME>. Free use of this software is granted
under the terms of the GNU General Public License (GPL).
"""
import sys, os, re, time, traceback, tempfile, subprocess, codecs, loca... | |
# =========================================================================== #
# Copyright 2016 The TensorFlow 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
#... | |
<gh_stars>1-10
import numpy as np
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import scipy
import fem
import scipy as sp
import pygmsh
import time
from scipy.spatial import ConvexHull, convex_hull_plot_2d
import random
import torch as T
import torch_geom... | |
#Takes a harsh view of whether or not an event "passes" and is significant. Assumes there are three replicates
#of two cell lines(N2A and CAD). There are the three "test" comparisons (soma1 vs axon1, soma2 vs axon2, soma3 vs axon3)
#and six "ctrl" comparisons (soma 1 vs soma2, soma1 vs soma3, soma2 vs soma3, axon1 vs a... | |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import numpy as np
import types
from enterprise.signals import parameter
from enterprise.signals import selections
from enterprise.signals import white_signals
from enterprise.signals import gp_signals
from en... | |
nn.BatchNorm1d(256, affine=False)
self.dropout_classifier = nn.Dropout(0.5)
def forward(self, image, face_features, numberFaces):
features = self.global_model.forward(image)
out = F.relu(features, inplace=True)
global_features_initial = F.avg_pool2d(out, kernel_size=7, stride=1).view(features.size(0), -1)
glo... | |
import sqlite3
from aselite import Atoms
from aselite import FixAtoms
from aselite import write_vasp
import local_update
import numpy
import sys
import copy
class LocalDB():
def __init__(self, db_name, nf=None, dc=None, mac=None):
self.db_name = db_name
self.nf = nf
self.dc = dc
self.mac = mac
# check if db_name... | |
"""
:param theRank:
:type theRank: int
:param Uinf:
:type Uinf: float
:param Usup:
:type Usup: float
:rtype: None
"""
return _Extrema.Extrema_ExtCC_SetRange(self, *args)
def SetTolerance(self, *args):
"""
:param theRank:
:type theRank: int
:param Tol:
:type Tol: float
:rtype: None
"""
return _Extre... | |
import copy
from functools import wraps, reduce
import socket
import os
from operator import mul
import sys
from statistics import mean
import time
import numpy as np
from rdkit.Chem import AllChem, RWMol
from rdkit import Chem
from rdkit.Chem.rdChemReactions import ChemicalReaction
from kgcn.data_util import dense_t... | |
datetime.date(2009, 11, 3)),
"TSH": pnp.Vendor("ELAN MICROELECTRONICS CORPORATION", "TSH", datetime.date(2014, 11, 14)),
"ESA": pnp.Vendor("Elbit Systems of America", "ESA", datetime.date(2009, 6, 15)),
"ESG": pnp.Vendor("ELCON Systemtechnik GmbH", "ESG", datetime.date(1999, 7, 16)),
"LXS": pnp.Vendor("ELEA CardWar... | |
times 21 or the answer to the meaning of life, continue to next state
button_status.hit = True
button_status.stand = True
button_status.double_down = can_double_bet(common_vars.player_bets, common_vars.player_cash)
self.next_state(PlayerHitState)
else:
# WOW!!! The player got two two-card hands with 21, what's th... | |
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """
from sympy.polys.algebratools import (
ZZ, QQ, RR, PolynomialRing, FractionField, EX
)
from sympy.polys.polyerrors import (
UnificationFailed,
GeneratorsNeeded,
DomainError,
)
from sympy import S, sqrt, sin, oo, raises
from s... | |
NS['mdui'])]
def _match(qq, elt):
for q in qq:
q = q.strip()
if ':' in q or '.' in q:
try:
nets = _ip_networks(elt)
for net in nets:
if ':' in q and ipaddr.IPv6Address(q) in net:
return net
if '.' in q and ipaddr.IPv4Address(q) in net:
return net
except ValueError:
pass
if q is not None and len(q) > 0:
... | |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平台:
-------------------------------------------... | |
# movies.py
# KMB 11/06/2008
import chunk
import multiprocessing
import os
import struct
import sys
import traceback
import cv2
import numpy as num
import wx
from params import params
from ellipsesk import annotate_bmp
# version of sbfmf for writing
__version__ = "0.3b"
#import static_background_fmf as sbfmf
#impo... | |
#!/usr/bin/env python3
import argparse, io, logging, os, re, subprocess, shutil, sys, tempfile
from tqdm import tqdm
from shlex import quote
import pysam
import vcf
from npsv.npsv_options import *
from npsv.variant import Variant, variant_descriptor, write_record_to_indexed_vcf
from npsv.feature_extraction import (
ex... | |
- phase_guess[i] for i in cmps]
else:
flows_guess_basis = flows_guess
global min_G, iterations
jac, hess = False, False
real_min = False
min_G = 1e100
iterations = 0
info = []
last = []
def G(flows):
global min_G, iterations
try:
flows = flows.tolist()
except:
flows = list(flows)
iterations += 1
iter_... | |
# -*- coding: UTF-8 -*-
# Version 3.1; <NAME>, <NAME>; Polar Geospatial Center, University of Minnesota; 2019
# Translated from MATLAB code written by <NAME>, Ohio State University, 2018
from __future__ import division
import math
import os
import re
import sys
import traceback
from warnings import warn
if sys.versi... | |
client = mod.BmvpcClient(cred, g_param[OptionsDefine.Region], profile)
client._sdkVersion += ("_CLI_" + __version__)
models = MODELS_MAP[g_param[OptionsDefine.Version]]
model = models.ModifySubnetAttributeRequest()
model.from_json_string(json.dumps(param))
rsp = client.ModifySubnetAttribute(model)
result = rsp.to... | |
<reponame>imran-salim/scikit-multiflow
import copy as cp
from skmultiflow.core import BaseSKMObject, ClassifierMixin, MetaEstimatorMixin
from skmultiflow.drift_detection import ADWIN
from skmultiflow.lazy import KNNADWINClassifier
from skmultiflow.utils import check_random_state
from skmultiflow.utils.utils import *
... | |
resp['errors']['name'] == u'Enter a value not more than 255 characters long'
# Attempt to create another subinterval-referencing audio file; fail
# because the contributor is not authorized to access the restricted parent_file.
params = self.file_create_params_sub_ref.copy()
params.update({
'parent_file': a_wav_f... | |
<reponame>taozenforce/cogswelladvancedrigging
"""
@author: <NAME> - Cogswell Polytechnical College 2014
Example code for a modular rigging system. This code was tested in the creation of goldie and daniel
"""
import pymel.core as pmc
from advutils import getAttribute, alignObjects, makeControlNode, ROO_XZY, ROO_YXZ
... | |
#!/usr/bin/env python3
"""Tokenizes, verbalizes, and phonemizes text and SSML"""
import itertools
import logging
import re
import typing
import xml.etree.ElementTree as etree
from decimal import Decimal
from pathlib import Path
import babel
import babel.numbers
import dateparser
import networkx as nx
from gruut_ipa im... | |
<reponame>electronicvisions/brick
from timingsignal import TimingSignal
from brick_characterizer.CharBase import CharBase
class CellRiseFall_Char(CharBase):
def __init__(self,toplevel,output_filename,temperature,use_spectre=False):
self.toplevel = toplevel
self.output_filename = output_filename
self.load_capac... | |
"attachment_payloads")
for the_file in os.listdir(attach_folder_path):
file_path = os.path.join(attach_folder_path, the_file)
try:
os.unlink(file_path)
except Exception, e:
raise e
def test_unknown_more_id_url(self):
moreURLGet = self.client.get(reverse('lrs:statements_more', kwargs={'more_id': 'aaaaaaaaaaaaaa... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Provides the Network class.
:copyright:
<NAME> (<EMAIL>), 2013
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.bui... | |
of dimension 1 over
a number field.
INPUT:
- ``n`` - a positive integer, the period.
- ``formal`` - a Boolean. True specifies to find the values of the elementary symmetric polynomials
corresponding to the formal ``n`` multiplier spectra of this map. False specifies to instead find
the values corresponding to ... | |
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Badlands surface processes modelling application. ##
## ##
## For full license and copyright information, please refer to the LICENSE.md file ##
## located at the project root, or contact the aut... | |
# 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
# distributed under the Li... | |
<gh_stars>1-10
from unittest import TestCase
from collections import Counter
from dark.intervals import OffsetAdjuster, ReadIntervals
from dark.hsp import HSP
class TestReadIntervals(TestCase):
"""
Test the ReadIntervals class
"""
EMPTY = ReadIntervals.EMPTY
FULL = ReadIntervals.FULL
def testEmpty(self):
""... | |
specified
# assign keyword args as appropriate:
for key, param_value in kwargs.items():
if key not in TimeCtrl.valid_ctrl_params.keys():
raise AttributeError('invalid keyword argument "%s"' % key)
if key == 'format':
wxdt = wx.DateTimeFromDMY(1, 0, 1970)
try:
if wxdt.Format('%p') != 'AM':
require24hr = True
... | |
KEY_ORDERED[i]
except:
numbers.remove(str_)
errors.append(str_)
else:
for str_ in names:
if i not in Name2Index:
errors.append(str_)
else:
numbers.append(Name2Index[str_])
tmp = []
for i in numbers:
if i not in tmp:
tmp.append(i)
numbers = tmp
if numbers:
start = 0
KEY_MMP_KEEP = []
min_ = min(numbers... | |
= base + (pom*rm) & e_bits.u_maxes[self.psize]
if (self.pubwl & 0x2 or not self.pubwl & 0x10): # write-back if (P==0 || W==1)
if (emu is not None) and (emu.getMeta('forrealz', False)): emu.setRegister( self.base_reg, addr)
if (self.pubwl & 0x10 == 0): # not indexed
return base
return addr
def render(self, mca... | |
coordinates_exp = np.array([[-2, -8, -7], [-9, 4, -2], [0, 2, -1], [-1, 3, -2]])
check_coordinate_system(lcs1_in_lcs0, orientation_exp, coordinates_exp, True, time)
lcs0_in_lcs1_2 = lcs1_in_lcs0.invert()
check_coordinate_system(
lcs0_in_lcs1_2, lcs0_in_lcs1.orientation, lcs0_in_lcs1.coordinates, True, time
)
... | |
<gh_stars>1000+
"""
Link Evennia to external resources (wizard plugin for evennia_launcher)
"""
import sys
from os import path
import pprint
from django.conf import settings
from evennia.utils.utils import list_to_string, mod_import
class ConnectionWizard(object):
def __init__(self):
self.data = {}
self.prev_node... | |
on creation.
if drag_name:
self.drag_group = default_drag_group()
# The current x and y coordinates of this displayable.
self.x = None
self.y = None
# The width and height of the child.
self.w = None
self.h = None
self.old_position = None
# The width and height of our parent.
self.parent_width = None
se... | |
<filename>cartctl/cartctl_test.py
#!/usr/bin/env python3
# Project: VUT FIT ATA Project - Řízení vozíku v robotické továrně
# Author: <NAME> <<EMAIL>>
# Year: 2021
# Description: Cart controller implementation testing.
import unittest
from cart import Cart, CargoReq, Status as CartStatus, CartError
from cartctl impo... | |
#!/usr/bin/env python
"""
wildthumper.py: Class definition for Wild Thumper rovers. Adafruit 16 channel PWM driver is used to control 2/3 Cytron dual channel MDD10A motor drivers.
"""
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import time
import Adafruit_PCA9685 as PD
import RPi.GPIO as GPIO
from numpy import sign
... | |
<reponame>almmello/frozen
# DO NOT EDIT THIS FILE!
#
# This file is generated from the CDP specification. If you need to make
# changes, edit the generator and regenerate all of the modules.
#
# CDP domain: Emulation
from __future__ import annotations
from .util import event_class, T_JSON_DICT
from dataclasses import d... | |
*option_spec* that correspond to the
options for the function way. See `the Docutils docs
<http://docutils.sourceforge.net/docs/howto/rst-directives.html>`_
for details.
The directive class must inherit from the class
``docutils.parsers.rst.Directive``.
For example, the (already existing) :rst:dir:`literalinclu... | |
add_max_vals_as_txt:
# Sub select data of interest
try:
ds_tmp = ds[['NOy', 'Dust', 'NOy*Dust']]
# Get extents
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# Reduce the dataset to this size.
print(xlim, ylim)
bool1 = ((ds_tmp.lon >= xlim[0]) & (ds_tmp.lon <= xlim[1])).values
bool2 = ((ds_tmp.lat >= ylim[0]) & (d... | |
from decimal import ROUND_HALF_UP, Decimal
from fractions import Fraction
from django.contrib.gis.db import models
from django.db import connection, transaction
from django.db.models import Max, Sum
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from enumfiel... | |
= QtGui.QBrush(QtGui.QColor(108, 255, 63, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Midlight, brush)
brush = QtGui.QBrush(QtGui.QColor(29, 127, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Dark, brus... | |
0.48409,
"07 14:30 Z": 0.40714,
"07 15:00 Z": 0.50504,
"07 15:30 Z": 0.39618,
"07 16:00 Z": 0.33577,
"07 16:30 Z": 0.59511,
"07 17:00 Z": 0.68796,
"07 17:30 Z": 0.98978,
"07 18:00 Z": 1.68859,
"07 18:30 Z": 4.51376,
"07 19:00 Z": 4.78925,
"07 19:30 Z": 3.90633,
"07 20:00 Z": 2.16072,
"07 20:30 Z": 1.42442,... | |
# Modifed to keep track of the greatest index in each successive parent node
# A Merkle proof is returned based on the index that is queried
# For an odd number of leaves, we need to change the merkle tree to hash
# with itself instead
# Question that remains is: Are the leaves global indices or transactions????
from... | |
"""
return self._get("canpark")
@property
def CanSetAltitude(self) -> bool:
"""The opening's altitude can be set via :py:meth:`SetAltitude()`
Raises:
NotConnectedException: If the device is not connected
DriverException: An error occurred that is not described by
one of the more specific ASCOM exceptions.
T... | |
""" Version 2.2 dated April 15th 2021 by <NAME>
This script reads sample names from a list, presents the user with
a couple of options to modify the names and arranges them on a
sheet of A4 paper so that it can be printed on Avery-Zweckform
L7871 labels
"""
from pathlib import Path # we use this for file path ope... | |
data)
# check that data after mask is not the same as source data with same offset as mask length
self.assertNotEqual(hidden_data['masked_prefix'][len(mask_pattern):], data['masked_prefix'][len(mask_pattern):])
# check that mask at correct place
self.assertEqual(hidden_data['masked_suffix'][-len(mask_pattern):], m... | |
import os
import warnings
warnings.filterwarnings("once", category=DeprecationWarning) # noqa: E402
import pytest
salem = pytest.importorskip('salem')
gpd = pytest.importorskip('geopandas')
import oggm
import xarray as xr
import numpy as np
import pandas as pd
from oggm import utils
from oggm.utils import get_demo_fi... | |
, 556 , (3, 0, None, None) , 0 , )),
(( 'Home2TelephoneNumber' , 'Home2TelephoneNumber' , ), 14895, (14895, (), [ (16392, 10, None, None) , ], 1 , 2 , 4 , 0 , 560 , (3, 0, None, None) , 0 , )),
(( 'Home2TelephoneNumber' , 'Home2TelephoneNumber' , ), 14895, (14895, (), [ (8, 1, None, None) , ], 1 , 4 , 4 , 0 , 564 , (... | |
"""
Copyright (c) 2017, 2020, Oracle Corporation and/or its affiliates. All rights reserved.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""
from javax.management import ObjectName
from org.python.modules import jarray
from wlsdeploy.aliases import alias_utils... | |
import math
import operator
from functools import reduce
import bezier
import cv2
import numpy as np
import pyclipper
from pyclipper import PyclipperOffset
from scipy.interpolate import splprep, splev
from shapely.geometry import Polygon
def compute_two_points_angle(_base_point, _another_point):
"""
以基点作x轴延长线,这根线以... | |
rate to apply.
beta1: decay rate to track the first moment.
beta2: decay rate to track the second moment.
epsilon: Small constant applied to the denominator outside of the square
root to avoid dividing by zero when rescaling.
epsilon_root: Small constant applied to the denominator inside of the square
root to avo... | |
fft_calc.calculate_levels(data)
running_stats.push(matrix)
mean = running_stats.mean()
std = running_stats.std()
matrix_buffer.appendleft(matrix)
if len(matrix_buffer) > light_delay:
matrix = matrix_buffer[light_delay]
update_lights(matrix, mean, std)
def load_custom_config(config_filename):
"""
Load custo... | |
<gh_stars>0
import bpy
import os
import math
import numpy
import loadImage
#from .config import IMAGES_DIR
#References:
# https://docs.blender.org/api/blender_python_api_2_71_release/bpy.types.Image.html
# https://blender.stackexchange.com/questions/13422/crop-image-with-python-script/13516#13516
# https://blender.sta... | |
<filename>turnipsPredictor.py<gh_stars>1-10
"""
Contains the cog for the turnip commands.
"""
from discord.ext import commands
import turnipCalculator
import datetime
import turnipSummaryImage
import discord
import errors
import timezoner
getDateAcquirer = timezoner.Timezoner("userData")
def getDate(date: str, disco... | |
<reponame>goldleaf3i/generativeCMLgraphs
#!/usr/bin/python
# COPIATO <NAME> 15/9/14
from sys import argv
import re
import sys
import math
import numpy as np
import copy
from igraph import *
from matplotlib import pyplot
import networkx as nx
from shapely.geometry import *
from descartes.patch import PolygonPatch
from... | |
check that ``xyz`` was given.
if xyz is None:
# xyz is None only at the first time cont opt is spawned, where cont_index is [0, 0,... 0].
raise InputError('xyz argument must be given for a continuous scan job')
# check whether this rotor is done
if self.species_dict[label].rotors_dict[rotor_index]['cont_indices'][... | |
'
'``packaging`` has being fully typed by adding a `py.typed` file (`#226 '
'<https://github.com/pypa/packaging/issues/226>`__)\\n\\n19.2 - '
'2019-09-18\\n~~~~~~~~~~~~~~~~~\\n\\n* Remove dependency on ``attrs`` (`#178 '
'<https://github.com/pypa/packaging/issues/178>`__, `#179 '
'<https://github.com/pypa/packagin... | |
:returns: A tuple with the following items:
0. **content** - Resource content.
1. **base64Encoded** - True, if content was served as base64.
'''
session = get_session_context('page.get_resource_content')
return await session.execute(cdp.page.get_resource_content(frame_id, url))
async def get_resource_tree() -> ... | |
A :class:`learningstudio.core.Response` object with details of status and content.
"""
relativeUrl = PATH_COURSES_MSOFFICEDOCUMENTS_ % (courseId, msOfficeDocumentId,)
return self.doGet(relativeUrl)
def getMsOfficeDocumentContent(self, courseId, msOfficeDocumentId, content_path = None):
"""Get content for... | |
df = concat(
[
DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]),
DataFrame(
np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"]
),
],
axis=1,
)
result = concat([df, df], axis=1)
tm.assert_frame_equal(result.iloc[:, :6], df)
tm.assert_frame_equal(result.iloc[:, 6:], df)
resu... | |
other
class CustomCertPack():
"""
custom certificate pack.
:attr str id: identifier.
:attr List[str] hosts: host name.
:attr str issuer: issuer.
:attr str signature: signature.
:attr str status: status.
:attr str bundle_method: bundle method.
:attr str zone_id: zone identifier.
:attr str uploaded_on: upload... | |
# coding=utf-8
# unpack.py
# Author: <NAME>
import binascii
import struct
from .message import HEADER_SIZE_BYTES, Message
from .msgtypes import *
# Creates a LIFX Message out of packed binary data
# If the message type is not one of the officially released ones above, it will create just a Message out of it
# If it... | |
{}'.format(check_result))
log_file_logger.error('#24: Check Analysis: {}'.format(check_analysis))
log_file_logger.error('#24: Unreachable Controllers: {}\n'.format(unreach_controllers))
writeFile(report_file, 'Result: WARNING - {}\n'.format(check_analysis))
writeFile(report_file, 'Action: {}\n\n'.... | |
works also for infinite iterables.
Default ``k=None`` means ``k = n``, i.e. return the tail that begins
right after the extracted items. Other values are occasionally useful,
e.g. to peek into the tail, while not permanently extracting an item.
The return value is a tuple containing the ``n`` first elements, and ... | |
<filename>salt/cloud/clouds/aliyun.py<gh_stars>1-10
# -*- coding: utf-8 -*-
'''
AliYun ECS Cloud Module
=======================
.. versionadded:: 2014.7.0
The Aliyun cloud module is used to control access to the aliyun ECS.
http://www.aliyun.com/
Use of this module requires the ``id`` and ``key`` parameter to be set... | |
<reponame>gfzriesgos/shakyground-lfs<gh_stars>1-10
# -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright (C) 2013-2018 GEM Foundation
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by t... | |
ANSIBLE_MODULES_LIST = ['a10_server',
'a10_server_axapi3',
'a10_service_group',
'a10_virtual_server',
'aci_aaa_user',
'aci_aaa_user_certificate',
'aci_access_port_block_to_access_port',
'aci_access_port_to_interface_policy_leaf_profile',
'aci_access_sub_port_block_to_access_port',
'aci_aep',
'aci_aep_to_domai... | |
db.update_segment_host_mapping(
ctx, host, {segment['segment']['id']})
hosts.add(host)
# Now they are 2 hosts with segment being mapped.
actual_hosts = db.get_hosts_mapped_with_segments(ctx)
self.assertEqual(hosts, actual_hosts)
class TestMl2HostSegmentMappingOVS(HostSegmentMappingTestCase):
_mechanism_drivers... | |
# Automatically adapted for numpy.oldnumeric Aug 02, 2007 by
import cdms2
import numpy
import copy
# from . import _regrid
import regrid2._regrid as _regrid
from .error import RegridError
class CrossSectionRegridder:
"""
PURPOSE: To perform all the tasks required to regrid the input data into the ouput data in th... | |
method == 'Telemetered':
uframe_dataset_name = 'CE07SHSM/SBD12/05-WAVSSA000/telemetered/wavss_a_dcl_non_directional'
var_list[0].name = 'time'
var_list[1].name = 'number_bands'
var_list[2].name = 'initial_frequency'
var_list[3].name = 'frequency_spacing'
var_list[4].name = 'psd_non_directional'
var_list[5... | |
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIA... | |
# NLP written by GAMS Convert at 04/21/18 13:53:08
#
# Equation counts
# Total E G L N X C B
# 2496 2496 0 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 2506 2506 0 0 0 0 0 0
# FX 5 5 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 11586 8726 2860 0
#
#... | |
<gh_stars>1-10
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | |
<gh_stars>1-10
import os
import time
import warnings
from math import isnan
import numpy as np
from ..exec_model import ExecModel, ModelObject
from .step import OptimizeStep
class OptimizeWarning(UserWarning):
pass
def _check_unknown_options(unknown_options: dict) -> None:
if unknown_options:
msg = ", ".join(m... | |
<filename>_utility.py
#############################
# Dependencies
#############################
import psycopg2
import ConfigParser
import time
import arrow
import pycrest
import pandas as pd
import json
from psycopg2.extras import RealDictCursor
from _globals import *
#############################
# Database
#####... | |
+ Origin
+ Referer
"""
def __init__(self):
"""
:param Authentication: 时间戳防盗链配置。
注意:此字段可能返回 null,表示取不到有效值。
:type Authentication: :class:`tencentcloud.cdn.v20180606.models.Authentication`
:param BandwidthAlert: 带宽封顶配置。
注意:此字段可能返回 null,表示取不到有效值。
:type BandwidthAlert: :class:`tencentcloud.cdn.v20180606.models.Ban... | |
2 . Mid HEX&DEC [yellow]*
*[/yellow] 3 . SLOW Full Display [yellow]*
**********[/yellow] DISPLAY [yellow]********[/yellow]
Enter Your Choice 1-3 ''')
print(promptdiplay)
startprint=int(input('TYPE HERE = '))
while True:
c1 = random.choice('0123456789abcdef')
c2 = random.choice('0123456789abcdef')
... | |
"""
Base functionality of meshed
"""
from collections import Counter
from dataclasses import dataclass, field
from functools import partial
from typing import Callable, MutableMapping, Iterable, Union, Sized, Sequence
from i2 import Sig, call_somewhat_forgivingly
from meshed.util import ValidationError, NameValidation... | |
using user entered target ID field."""
search_string = self.simbad_query.get()
if not len(search_string.strip()) > 0:
self.error_modal("Search query for SIMBAD must not be empty")
return
with _busy_cursor(self.root):
try:
result = query_simbad(search_string.strip())
except requests.exceptions.Timeout:
self.er... | |
<gh_stars>0
"""Include functions to validate model performance using cross-validation."""
import copy
import hashlib
import json
import numpy as np
import os
import pickle
from joblib import delayed, Parallel
from sklearn.base import clone, is_classifier
from sklearn.metrics._scorer import _check_multimetric_scoring
... | |
<filename>machine_learning/exercises/matlab/other-solutions/solution_2/DecisionTrees &Boosting/dtree1.py
#!/usr/bin/env python
"""
dtree.py -- CS181 Assignment 1: Decision Trees
Implements decision trees, decision stumps, decision tree pruning, and
adaptive boosting.
"""
import math
import random
def log2(dbl):
r... | |
+ m.x53 + m.x54 + m.x55 + m.x56 + m.x57 + m.x58 + m.x59 == 1)
m.c414 = Constraint(expr= m.x60 + m.x61 + m.x62 + m.x63 + m.x64 + m.x65 + m.x66 + m.x67 + m.x68 + m.x69 == 1)
m.c415 = Constraint(expr= m.x70 + m.x71 + m.x72 + m.x73 + m.x74 + m.x75 == 1)
m.c416 = Constraint(expr= m.x76 + m.x77 + m.x78 + m.x79 + m.x80 + m... | |
source):
L, R = {}, {}
L[source[1]] = (0, source[0]) # (d_v,a_v)
R[source[1]] = (0, source[0])
return L, R
def SFoP_source_initialisation(L, source, t0, t1):
L[source[1]] = (0, t0)
def SFoP_update(L, R, t0, t1, u, v):
du, au = L[u]
new_arrival = t0
new_distance = du + 1
if v in R:
current_best_distance, ... | |
from datetime import datetime
import os
import numpy as np
import json
from copy import deepcopy
import xarray as xr
from sklearn.model_selection import cross_validate, KFold
from sklearn.metrics import make_scorer, mean_squared_error
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils.validation... | |
map: %r" % polygon)
cur_objs.append(polygon)
self.polygons = tuple(cur_objs)
def remove_polygon(self, polygon):
"""Remove the GeoPolygon from GeoMultiPolygon.
Parameters
----------
polygon: GeoPolygon
GeoPolygon to be removed from the GeoMultiPolygon.
"""
if polygon.model_id not in self._polygons_ids:
rais... | |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
import inspect
import sys
import warnings
from contextlib import contextmanager
from func... | |
<reponame>colinRawlings/osparc-simcore
# pylint: disable=C0111, R0913
import asyncio
import json
import logging
import re
from datetime import datetime, timedelta
from distutils.version import StrictVersion
from enum import Enum
from pprint import pformat
from typing import Dict, List, Optional, Tuple
import aiodocke... | |
primenet_api.ERROR_STALE_CPU_INFO:
debug_print("STALE CPU INFO ERROR: re-send computer update")
register_instance(guid)
retry = True
elif rc == primenet_api.ERROR_UNREGISTERED_CPU:
debug_print(
"UNREGISTERED CPU ERROR: pick a new GUID and register again")
register_instance(None)
retry = True
elif rc == primene... | |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 14:00:18 2020
updated on Thu Oct 15 18:07:45 2020
@author: <NAME>
"""
#reproducability
from numpy.random import seed
seed(1)
import tensorflow as tf
tf.random.set_seed(1)
import numpy as np
from bayes_opt import BayesianOptimization
from bayes_opt.logger import JSONL... | |
import warnings
from django.db.migrations.exceptions import (
CircularDependencyError, NodeNotFoundError,
)
from django.db.migrations.graph import (
RECURSION_DEPTH_WARNING, DummyNode, MigrationGraph, Node,
)
from django.test import SimpleTestCase
class GraphTests(SimpleTestCase):
"""
Tests the digraph structure... | |
[cirq.X(b)], [b]),
(-5, 0, [cirq.CZ(a, b)], [a])]
for given_index, actual_index, op_list, qubits in op_tree_list:
c.insert(given_index, op_list, cirq.InsertStrategy.INLINE)
for i in range(len(op_list)):
assert c.operation_at(qubits[i], actual_index) == op_list[i]
def test_insert_op_tree_earliest():
a = cirq.Na... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 17 00:29:22 2021
@author: <NAME>
"""
"""
DESCRIPTION - OUTPUT PARAMETERS ANALYSIS
Script for output analysis which calculates:
ratio of metabolites, each produced by one of the two microbes in the corsortium (final product / intermediate produ... | |
`value` is not a valid value
Returns:
str: the value of `plant_equipment_operation_scheme_name` or None if not set
"""
return self["Plant Equipment Operation Scheme Name"]
@plant_equipment_operation_scheme_name.setter
def plant_equipment_operation_scheme_name(self, value=None):
"""Corresponds to IDD field `Pl... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# A tf.keras implementation of Google efficientnet,
# ported from https://github.com/keras-team/keras-applications/blob/master/keras_applications/efficientnet.py
#
"""EfficientNet models for Keras.
# Reference paper
- [EfficientNet: Rethinking Model Scaling for Convolut... | |
"""Defines various distribution models."""
import numpy as np
import numpy.random as rnd
import scipy.stats as stats
from warnings import warn
import serums.enums as enums
class BaseSingleModel:
"""Generic base class for distribution models.
This defines the required functions and provides their recommended funct... | |
from pyspark.sql import SparkSession
from pyspark.sql.functions import regexp_extract
from pyspark.sql.functions import udf
from pyspark.sql.functions import *
from pyspark.sql.types import *
from datetime import datetime,timedelta
import json
import sys
import time
import threading
'''
udf schema to return user_st_et... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.