input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
""" Functionality for analysis of single quantum dots
For more details see https://arxiv.org/abs/1603.02274
"""
# %%
import scipy
import scipy.ndimage
import numpy as np
import matplotlib.pyplot as plt
import warnings
import logging
import qcodes
from qcodes.plots.qcmatplotlib import MatPlot
from qtt.data import dat... | |
else:
bot.say("Unknown error: " + block)
def doltaBlock(bot, name, project, target):
creds = getCreds(name)
if creds is None:
bot.say(CONTACT_OP)
return
site = getWiki(project)
if site is None:
bot.say("I don't know that wiki.")
return
csrfToken = getCSRF(bot, site, creds, "csrf")
... | |
<gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
import re
from . import utilities
from . import media
from .base import loadable
class MalformedAnimePageError(media.MalformedMediaPageError):
"""Indicates that an anime-related page on MAL has irreparably broken markup in some way.
"""
pass
... | |
<filename>stitch/stitch.py
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import os
import cv2 as cv
import numpy as np
from scipy import optimize as so
import pandas as pd
from tqdm import tqdm
import hough as ld
import lineutils as ut
from lineutils import r, t, x, y
def fst(x): return x[0]
def snd(x): return x... | |
<gh_stars>0
"""
Classes and functions to deal with hexagonal grids.
This module assumes that the hexagonal grid is aligned with the x-axis.
If you need it to be aligned with the y-axis instead, you will have to
swap x and y coordinates everywhere.
"""
from collections import namedtuple
from heapq import heappush, hea... | |
kind, val in self.ivarsData:
self.ivarsDict[self.munge(key)] = g.GeneralSetting(
kind, ivar=key, val=val, tag='ivars')
for key, kind, val in self.encodingIvarsData:
self.encodingIvarsDict[self.munge(key)] = g.GeneralSetting(
kind, encoding=val, ivar=key, tag='encoding')
#@+node:ekr.20041117065611.2: *4* gcm.initI... | |
strings containing aligned sequences
Returns
-------
numpy.array
2D array containing sequence alignment
(first axis: sequences, second axis: columns)
"""
if len(sequences) == 0:
raise ValueError("Need at least one sequence")
N = len(sequences)
L = len(next(iter(sequences)))
matrix = np.empty((N, L), dtype=... | |
<reponame>PetreStegaroiu/python-esppy<filename>esppy/connectors/fs.py
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright SAS Institute
#
# 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
#
# htt... | |
<reponame>petcomputacaoufrgs/EMS
import logging
import pandas as pd
import music21
from bisect import bisect_left
SETTINGS = {
'RESOLUTION': 16,
'KEYBOARD_SIZE': 88,
'KEYBOARD_OFFSET': 21
}
def interactive_debug_serial(serialized):
"""Interactive debugger of the serialized dataframe"""
serial_instruments = list... | |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=R0915,R0912,R0913,R0914,R0902
"""
File : generator.py
Author : <NAME> <<EMAIL>>
Generator module defines various data generator for MLaaS4HEP framework.
"""
from __future__ import print_function, division, absolute_import
# system modules
import os
import j... | |
unique identifier of the cluster.
- **NodeType** *(string) --*
The node type for the nodes in the cluster.
- **ClusterStatus** *(string) --*
The current state of the cluster. Possible values are the following:
* ``available``
* ``available, prep-for-resize``
* ``available, resize-cleanup``
* ``cancelling-r... | |
CDP, Maine",1113),
("Standish CDP, Maine",255),
("Steep Falls CDP, Maine",1720),
("Thomaston CDP, Maine",2018),
("Topsham CDP, Maine",6103),
("Unity CDP, Maine",321),
("Van Buren CDP, Maine",1687),
("Waldoboro CDP, Maine",1260),
("Washburn CDP, Maine",1065),
("Waterville city, Maine",16515),
("Westbrook city, Maine",18... | |
leftFit[0]*ploty**2 + leftFit[1]*ploty + leftFit[2]
rightFitx = rightFit[0]*ploty**2 + rightFit[1]*ploty + rightFit[2]
for r in rect:
cv2.rectangle(outImg2,(r[2], r[0]),(r[3],r[1]),(0,255,0), 2)
cv2.rectangle(outImg2,(r[4], r[0]),(r[5],r[1]),(0,255,0), 2)
# Identify the x and y positions of all nonzero pixels ... | |
content of the sandbox folder copying all that are not in `provenance_exclude_list`. Note
# that directories are not created explicitly. The `node.put_object_from_filelike` call will create intermediate
# directories for nested files automatically when needed. This means though that empty folders in the sandbox or
#... | |
dict_iso={'afghanistan': 'Afghanistan',
'albania': 'Albania',
'algeria': 'Algeria',
'andorra': 'Andorra',
'angola': 'Angola',
'antigua-and-barbuda': 'Antigua and Barbuda',
'argentina': 'Argentina',
'armenia': 'Armenia',
'aruba': 'Aruba',
'australia': 'Australia',
'austria': 'Austria',
'azerbaijan': 'Azerbaij... | |
of last item in col
:param col: Passed to grid, defaults to 0
:param padx: Passed to grid
:param pady: Passed to grid
:param sticky: Passed to grid
:param rowspan: Passed to grid
:param colspan: Passed to grid
:param widgetkwargs: Passed to widget creation
:param gridkwargs: Passed to grid placement
"""
widg... | |
logic in case of partial reconfiguration building on platform logics**. The `id` of the uploaded Image can then be used to create *Instances* or *Clusters*. It **must** contain the corresponding .sig file that was produced by the build. The resulting image can be viewed and deleted like other images. # noqa: E501
This... | |
:param cluster_pt_number_list: number of points to generate for each cluster center
:param cluster_radius_list: list of size of each cluster
:return: list of sample points that belong to various clusters
"""
k = len(cluster_pt_number_list) # number of clusters to generate clusters for
if (not(k == len(cluster_ce... | |
cloud_build_options: Optional[pulumi.Input['CloudBuildOptionsArgs']] = None,
container: Optional[pulumi.Input['ContainerInfoArgs']] = None,
files: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
zip: Optional[pulumi.Input['ZipInfoArgs']] = None):
"""
Code and application artifacts used to deploy a ... | |
'like', 'history%' ),
])
histories = self.history_manager.list( filters=filters )
# for h in histories:
# print h.name
self.assertEqual( histories, [ history1, history2, history3 ])
filters = self.filter_parser.parse_filters([ ( 'name', 'like', '%2' ), ])
self.assertEqual( self.history_manager.list( filters=fil... | |
# License: BSD 3 clause
# -*- coding: utf8 -*-
import unittest
import numpy as np
from scipy.sparse import csr_matrix
from tick.array_test.build import array_test as test
class Test(unittest.TestCase):
def setUp(self):
self.correspondence_dict = {
'Double': {
'python_type': float,
'cpp_type': 'double',
},
'... | |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, s... | |
<filename>src/python/grapl_analyzerlib/tests/test_process_node.py
import time
import unittest
from typing import cast, Dict
import hypothesis
import hypothesis.strategies as st
import pytest
from hypothesis import given
from grapl_analyzerlib.prelude import *
from grapl_analyzerlib.test_utils.dgraph_utils import upse... | |
<filename>casa_imaging/casa_utils.py
"""
Utility functions for operating on CASA-exported FITS files.
"""
import astropy.io.fits as fits
from astropy.wcs import WCS
import numpy as np
import os
import shutil
import scipy.stats as stats
import traceback
import yaml
from collections import OrderedDict as odict
import dat... | |
import_config.resetSqoopStatistics() - Finished")
def saveSqoopStatistics(self, sqoopStartUTS, sqoopSize=None, sqoopRows=None, sqoopIncrMaxvaluePending=None, sqoopMappers=None):
logging.debug("Executing import_config.saveSqoopStatistics()")
logging.info("Saving sqoop statistics")
self.sqoopStartUTS = sqoopStar... | |
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>",
"<KEY>", ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version ... | |
strides_node = inputs_vals[ConvParamIdx.stride_idx].node()
strides_vals = list(strides_node.inputs())
mace_strides = [strides_vals[i].node()['value'] for i in range(2)]
strides_arg = op.arg.add()
strides_arg.name = MaceKeyword.mace_strides_str
strides_arg.ints.extend(mace_strides)
pads_node = inputs_vals[ConvPar... | |
<filename>baseline/vectorizers.py
import collections
import copy
import tempfile
import unicodedata
import re
import json
from typing import Tuple, List, Iterable, Set, Dict
import numpy as np
from functools import lru_cache
from eight_mile.downloads import open_file_or_url, get_file_or_url
from eight_mile.utils impor... | |
import sys
import unittest
from tf.fabric import Fabric
# LOAD THE TEST CORPUS
TF = Fabric('tf')
api = TF.load('sign name')
F = api.F
S = api.S
# MAKE CUSTOM SETS OF NODES
Sign = set(range(1, F.otype.maxSlot + 1))
Node = set(range(1, F.otype.maxNode + 1))
sets = dict(Sign=Sign, Node=Node)
# RUN A QUERY, OPTIONA... | |
for (nw, kv) in zip(self.nweights(), kvalues))
def aggregate_lfunction(self, r, edge_correction=None):
"""
Compute the aggregate of the empirical L-function over all patterns in
the collection
Parameters
----------
r : array-like
Array of values at which to evaluate the emprical aggregate
L-function.
edge_c... | |
[0, 1, 2]
1:α(t) = 2.00 + 1.00 t; π = [1, 2]
2:α(t) = 2.00 + 1.00 t; π = [0]
3:α(t) = 2.00 + 1.00 t; π = [2]
4:α(t) = 2.00 + 1.00 t; π = [0, 1]
Servers:
0:β(t) = 6.00 . (t - 4.00)+
1:β(t) = 6.00 . (t - 4.00)+
2:β(t) = 6.00 . (t - 4.00)+>, [0, 1, 3])
"""
flow_list = []
list_prems = []
pre = 0
for flow in se... | |
import numpy as np
import h5py
from typing import List, BinaryIO
from mlagents_envs.exception import UnityException
class BufferException(UnityException):
"""
Related to errors with the Buffer.
"""
pass
class AgentBuffer(dict):
"""
AgentBuffer contains a dictionary of AgentBufferFields. Each agent has his o... | |
<gh_stars>0
import datetime
import unittest
from il2fb.ds.events.definitions.shootdowns import AIAircraftShotdownEvent
from il2fb.ds.events.definitions.shootdowns import AIAircraftShotdownSelfEvent
from il2fb.ds.events.definitions.shootdowns import HumanAircraftShotdownEvent
from il2fb.ds.events.definitions.shootdowns... | |
<filename>samples/sample_architectures.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
© <NAME>, <NAME>, 2017
Some example architectures to be used with corresponding config files in folder configs/examples.
Overview:
---------
ArchitectureDense: Simple dense layer network (use with main_lstm.py)
ArchitectureLSTM: Most sim... | |
"""
check_is_fitted(self)
if not all([hasattr(estimator, "predict_proba")
for estimator in self.estimators_]):
raise AttributeError("The base estimator should "
"implement predict_proba method")
return self._predict_proba
def _predict_proba(self, X):
results = [estimator.predict_proba(X) for estimator... | |
(7.64882606875107 + log(0.0001 + m.x1025))*m.x1025 + (3.17102601538367 + log(0.0001 +
m.x1026))*m.x1026 + (5.18893371623782 + log(0.0001 + m.x1027))*m.x1027 + (3.92481308582461 + log(
0.0001 + m.x1028))*m.x1028 + (3.5163958265858 + log(0.0001 + m.x1029))*m.x1029 + (
3.58276300677207 + log(0.0001 + m.x1030))*m.x1030... | |
<filename>gen/calc.py
""" This module contains the logic for specifying and validating the top-level
DC/OS configuration from user arguments
The data structure called 'entry' is what defines which validation checks
should be run, how arguments should be calculated, which arguments should have
set defaults, which argum... | |
<reponame>RI-imaging/ODTbrain
"""2D Fourier mapping"""
import numpy as np
import scipy.interpolate as intp
def fourier_map_2d(uSin, angles, res, nm, lD=0, semi_coverage=False,
coords=None, count=None, max_count=None, verbose=0):
r"""2D Fourier mapping with the Fourier diffraction theorem
Two-dimensional diffracti... | |
residue_1.resname in AMINO_ACIDS and residue_1.id[0] == " ":
resnum_1 = str(residue_1.id[1]) + residue_1.id[2].strip()
resaa_1 = convert_aa(residue_1.get_resname(), quiet=True)
interacting_residues = set()
for atom_1 in residue_1:
interacting_residues.update(ns.search(atom_1.get_coord(), r_cutoff, "R"))
interacti... | |
################################################################################
# Copyright (c) 2006-2017 Franz Inc.
# All rights reserved. This program and the accompanying materials are
# made available under the terms of the MIT License which accompanies
# this distribution, and is available at http://opensource.o... | |
def kfold_column(self, n_folds=3, seed=-1):
"""
Build a fold assignments column for cross-validation. This call will produce a column
having the same data layout as the calling object.
:param n_folds: Number of folds.
:param seed:Seed for random numbers (affects sampling when balance_classes=T)
:return: A column... | |
%(class_name)s could not be found: %(exception)s")
class NotAllowed(RackException):
msg_fmt = _("Action not allowed.")
class ImageRotationNotAllowed(RackException):
msg_fmt = _("Rotation is not allowed for snapshots")
class RotationRequiredForBackup(RackException):
msg_fmt = _("Rotation param is required for b... | |
import warnings
import torch
from torch.autograd import gradcheck, gradgradcheck
from xitorch.interpolate.interp1 import Interp1D
from xitorch._tests.utils import device_dtype_float_test
@device_dtype_float_test(only64=True, additional_kwargs={
"bc_type": ["clamped", "natural", "not-a-knot", "periodic", None],... | |
<reponame>Grim-es/udon-pie-auto-completion
from typing import overload
from UdonPie import System
from UdonPie import UnityEngine
from UdonPie.Undefined import *
class AudioSource:
def __new__(cls, arg1=None):
'''
:returns: AudioSource
:rtype: UnityEngine.AudioSource
'''
pass
@staticmethod
def op_Implicit(a... | |
<reponame>guillaume-thiry/OECD-Chatbot
# @ Copyright Inria, Ecole Polytechnique
# Shared under the MIT license https://opensource.org/licenses/mit-license.php
# This file contains all the functions that are used in the area detection
# The main part of the code is the function find_areas, that will be used elsewhere i... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 10:31:31 2020
@author: grat05
"""
import numpy as np
from numpy import exp
import pandas as pd
from functools import wraps
class ObjDict():
def __repr__(self):
return str(self.__dict__)
def isList(thing):
return isinstance(thing, (list, tup... | |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.or... | |
: list
ordered sql entries.
"""
reordered_entries = []
other_entries = []
for sql_entry in sql_entries:
if 'CREATE' in sql_entry:
reordered_entries.append(sql_entry)
else:
other_entries.append(sql_entry)
reordered_entries.extend(other_entries)
return reordered_entries
def _transform_sql(self, sql_entries, ... | |
= 'LOB2?' # Seems to have been removed. May have been on LOB2, though.
# pipe_rf260['exit_position']['direction'] = 180. # degrees, giving dir of pipe leading towards injector, up is 90
i += 1
# CPMID
pipe_cpmid = ods['gas_injection']['pipe'][i]
pipe_cpmid['name'] = 'CPMID'
pipe_cpmid['exit_position']['r'] = 0.9... | |
# Call the MoE
moe_out_2d, importance, load, _, _ = moe.Eval(
dp.devices, xs_2d, train, identifiers=None, summaries=True)
# Reshape the output to the original shape.
moe_out = dp(tf.reshape, moe_out_2d, dp(tf.shape, xs))
# These losses encourage equal load on the different experts.
loss = loss_coef * (eu.CVSquare... | |
<reponame>JiazeWang/PAConv
"""
@Author: <NAME>
@Contact: <EMAIL>
@Time: 2020/03/06
@Document: Basic operation/blocks of 3D-GCN
"""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
def get_neighbor_index(vertices: "(bs, vertice_num, 3)", neighbor_num: int):
"""
Return: (bs,... | |
+ m.b45 - m.b156 <= 0)
m.c2389 = Constraint(expr= - m.b15 + m.b17 - m.b157 <= 0)
m.c2390 = Constraint(expr= - m.b15 + m.b19 - m.b158 <= 0)
m.c2391 = Constraint(expr= - m.b15 + m.b21 - m.b159 <= 0)
m.c2392 = Constraint(expr= - m.b15 + m.b23 - m.b160 <= 0)
m.c2393 = Constraint(expr= - m.b15 + m.b25 - m.b161 <= 0)
m... | |
None:
instanceElement.attrib['stylemapfamilyname'] = instanceObject.styleMapFamilyName
if instanceObject.styleMapStyleName is not None:
instanceElement.attrib['stylemapstylename'] = instanceObject.styleMapStyleName
if self.effectiveFormatTuple < (5, 0):
# Deprecated members as of version 5.0
if instanceObject.gly... | |
import json
import sys
import threading as th
import time
from base64 import b64encode
from io import open
from os import path
from serial.serialutil import SerialException
from modi2_firmware_updater.util.message_util import decode_message, parse_message, unpack_data
from modi2_firmware_updater.util.modi_winusb.modi... | |
<filename>ansible_collection/hpe/nimble/plugins/modules/hpe_nimble_network.py
#!/usr/bin/python
# # Copyright 2020 Hewlett Packard Enterprise Development LP
#
# 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 th... | |
expected to take responsibility for this
entry."""),
'lino_xl.lib.cal.Event.event_type' : _("""The type of this entry. Every calendar entry should have this
field pointing to a given EventType, which holds
extended configurable information about this entry."""),
'lino_xl.lib.cal.Event.state' : _("""The state of this ... | |
<reponame>CiscoSystems/fabric_enabler
import os
import urllib
import json
import requests
import socket
import netaddr
import pexpect
import logging
import time
import sys
REQUEST_TIMEOUT = 30
PING_MONITOR_TYPE = 'PING'
HTTP_MONITOR_TYPE = 'HTTP'
HTTPS_MONITOR_TYPE = 'HTTPS'
TCP_MONITOR_TYPE = 'TCP'
SHARED_CONFIG_DE... | |
single hour of a day with its 12 5-minute intervals which specify the temperature adjustment . The
thermostat will apply this temperature adjustment on top of the user's program.
:param selection: The selection criteria for update
:param demand_managements: A list of demand management objects
:param timeout: Numbe... | |
from functools import reduce
# from keras import layers
# from keras import initializers
# from keras import models
# from keras_ import EfficientNetB0, EfficientNetB1, EfficientNetB2
# from keras_ import EfficientNetB3, EfficientNetB4, EfficientNetB5, EfficientNetB6
import tensorflow as tf
from tensorflow.keras impo... | |
<reponame>MArtinherz/sportsipy
import pandas as pd
import re
from functools import wraps
from lxml.etree import ParserError, XMLSyntaxError
from pyquery import PyQuery as pq
from urllib.error import HTTPError
from .. import utils
from .constants import PLAYER_SCHEME, PLAYER_URL, ROSTER_URL, DETAILED_STATS
from .player ... | |
1) for _ in range(3) // _를 하면 변수없이 반복문이 3번 돈다.
a=[[0]*3 for _ in range(3)] # [0]*3 가 3번 반복됨.
print(a)
=>[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
열
행 0 1 2
0 [0, 0, 0]
1 [0, 0, 0]
2 [0, 0, 0]
열
행 0 1 2
0 [0, 1, 0]
1 [0, 2, 0]
2 [0, 0, 0]
a=[[0]*3 for _ in range(3)] # [0]*3 가 3번 반복됨.
a[0][1]=1
a[1][1]=2
... | |
<gh_stars>1-10
#-----------------------------------------------------#
#
# Copyright (c) 2020-2021 <NAME> <<EMAIL>>
#
# See the LICENSE file for your full rights.
#
#-----------------------------------------------------#
# Imports
#-----------------------------------------------------#
import bpy
import ... | |
<reponame>royukira/MyAI
import numpy as np
import random
# ========= Node ===========
class TimeNode(object):
"""
For store the transitions generated at ith time step (i.e. self.time = i )
"""
def __init__(self, time):
self.previous = None
self.time = time
self.transitions = []
self.nextTime = None
def ge... | |
<reponame>khoak20hcmut/Penalty_BF<gh_stars>1-10
from typing import Optional, Sequence
from procset import ProcSet
import pytest
import batsim_py
from batsim_py.events import SimulatorEvent
from batsim_py.events import JobEvent
from batsim_py.events import HostEvent
from batsim_py.jobs import DelayJobProfile
from bats... | |
block_adapters,
task,
)
else:
layer_outputs = encoder_layer(hidden_states, attention_mask, past_key_value, block_adapters, task=task, output_attentions=output_attentions)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
enc... | |
<gh_stars>0
#!/usr/bin/env python
import roslib
import rospy
import smach
import smach_ros
import sys
import time
from geometry_msgs.msg import Pose
from hlpr_speech_recognition.speech_listener import SpeechListener
from hlpr_speech_msgs.srv import SpeechService
#from hlpr_speech_synthesis import speech_synthesizer... | |
from __main__ import vtk, qt, ctk, slicer
#
# LabelStatistics
#
class BenderLabelStatistics:
def __init__(self, parent):
import string
parent.title = "Bender Label Statistics"
parent.categories = ["Quantification"]
parent.contributors = ["<NAME> (Isomics), <NAME> (Kitware)"]
parent.dependencies = ["CropVolume"]... | |
"""The WaveBlocks Project
IOM plugin providing functions for handling
homogeneous Hagedorn wavepacket data.
@author: <NAME>
@copyright: Copyright (C) 2010, 2011, 2012, 2013, 2016 <NAME>
@license: Modified BSD License
"""
import numpy as np
def add_inhomogwavepacket(self, parameters, timeslots=None, blockid=0, key=... | |
# Copyright 2002-2011 <NAME>. See LICENSE for licensing information.
"""mixminion.server.PacketHandler: Code to process mixminion packets"""
import binascii
import threading
import types
from mixminion.Common import encodeBase64, formatBase64, LOG
import mixminion.Crypto as Crypto
import mixminion.Packet as Packet
i... | |
"""
Test JADN Schema transformations
Transformation -> Reduce Complexity
"""
from unittest import main, TestCase
import jadn
from jadn.definitions import EXTENSIONS
class Resolve(TestCase):
schema = {} # TODO: test Merge imported definitions
# def test_resolve(self):
class StripComments(TestCase):
schema = {
... | |
+= err
y_prob_test[idx] = pred
test_batches += 1
pred_y_test = np.argmax(y_prob_test, axis=1)
acc_test = accuracy_score(pred_y_test, y_test)
roc_auc_test = ROC_AUC(y_test, pred_y_test)
# Then we print the results for this epoch:
print(
"Epoch {} of {}\ttraining loss:\t{:.6f}\tvalidation accuracy:\t{:.2f}... | |
if d[s0][None] is not False:
populate_selection(
d[s0], selection[1:], os.path.join(root, s0)
)
if d[s0][None] is False:
# At best, the root is not all true
d[None] = None
def split_all(x):
head, tail = os.path.split(x)
if (len(head) == 0) or (len(tail) == 0):
return [x]
else:
return split_all(head) + [tai... | |
the data. This profile has an radius unit of {r} and a value unit of "
"{v}".format(r=self.radii_unit.to_string(), v=self.values_unit.to_string()))
# I don't think I'm going to allow any fits without value uncertainties - just seems daft
if self._values_err is None:
raise XGAFitError("You cannot fit to a profile t... | |
db_procedure_not_implemented.restype = None
break
# /Users/cmbarton/grass_source/grass-7.8.3/dist.x86_64-apple-darwin18.7.0/include/grass/defs/dbmi.h: 244
for _lib in six.itervalues(_libs):
if not hasattr(_lib, 'db_protocol_error'):
continue
db_protocol_error = _lib.db_protocol_error
db_protocol_error.argtypes = ... | |
not None:
if self.tools.is_clang:
with open(self.export_map_file, 'wt') as fh:
for export_entry in actual_export_list:
print('_{}'.format(export_entry), file=fh)
argv += [ '-Wl,-exported_symbols_list,{}'.format(self.export_map_file) ]
else:
with open(self.export_map_file, 'wt') as fh:
print("{", file=fh)
print... | |
# get the model as DPC-RNN
import sys
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
sys.path.append('../backbone')
# to extract the features
from select_backbone import select_resnet
# to aggregate the features in one
from convrnn import ConvGRU
# to calculate loss
from uncertainty ... | |
from dataclasses import dataclass
from . import B
class Keyboard:
WRAP_TOP = "wrap_top"
WRAP_BOTTOM = "wrap_bottom"
WRAP_LEFT = "wrap_left"
WRAP_RIGHT = "wrap_right"
EXIT_TOP = "exit_top"
EXIT_BOTTOM = "exit_bottom"
EXIT_LEFT = "exit_left"
EXIT_RIGHT = "exit_right"
EXIT_DIRECTIONS = [EXIT_TOP, EXIT_BOTTOM... | |
5-6 of the Microscan MS3 manual for reference
"""
Disabled = b'0'
Enabled = b'1'
class EAN128Status(Enum):
"""Enables/disables/requires the EAN-128 subset of the Code 128 symbology
EAN-128 is commonly used in shipping applications, defining a wide variaty
of application specific extensions while using a subset... | |
From here on, modules need certain
# libraries, are platform-specific, albo present other surprises.
#
# Multimedia modules
# These don't work dla 64-bit platforms!!!
# These represent audio samples albo images jako strings:
# Operations on audio samples
# According to #993173, this one should actually work fi... | |
import boto3
import botocore
import configparser
import json
import logging
import os
import re
import uuid
try:
from collections.abc import namedtuple
except ImportError:
from collections import namedtuple
from ..config import get_config_file, rlock
__all__ = [
"clients",
"get_tags",
"get_ecr_repo",
"set_ecr_... | |
<gh_stars>0
# Copyright The PyTorch Lightning team.
#
# 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 agr... | |
<reponame>Sotilrac/shared_playlist
# -*- coding:utf-8 -*-
#
# Copyright (C) 2012, <NAME> <<EMAIL>>
#
# 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 you... | |
stopping")
return
self._send_queue.put((priority, (message, callback)))
def _start_greenlets(self):
"""Start standard greenlets that should always run, and put them in a dict indexed by their name,
to allow special operations to refer to them specifically."""
self._named_greenlets = {
name: self._group.... | |
'y': 1104, 'width': 542, 'height': 108}, # Left bank top-right button
'Joy_8': {'Type': 'Digital', 'x': 1124, 'y': 1220, 'width': 542, 'height': 108}, # Left bank bottom-right button
'Joy_9': {'Type': 'Digital', 'x': 574, 'y': 1220, 'width': 542, 'height': 108}, # Left bank bottom-middle button
'Joy_10': {'Type': 'D... | |
if k == 0:
return []
map_fit_ind = defaultdict(list)
for ind in individuals:
map_fit_ind[ind.fitness].append(ind)
fits = list(map_fit_ind)
current_front = []
next_front = []
dominating_fits = defaultdict(int)
dominated_fits = defaultdict(list)
# Rank first Pareto front
for i, fit_i in enumer... | |
radius, in the deflected configuration); please note that this clearance is only approximate because the calculation assumes that the blade is a line with no volume (however, the calculation does use the local tower radius); when B2N2 is above the tower top (or below the tower base), the absolute distance to the tower ... | |
dictionary."""
args = {}
if 'id' in _dict:
args['id'] = _dict.get('id')
else:
raise ValueError('Required property \'id\' not present in FirewallRuleUpdateInputFilter JSON')
return cls(**args)
@classmethod
def _from_dict(cls, _dict):
"""Initialize a FirewallRuleUpdateInputFilter object from a json dictionary."... | |
then its path_id will be a/b/abc/temp_file.py.
path_id: str = models.TextField(db_index=True, unique=True)
owner: UserProfile = models.ForeignKey(UserProfile, on_delete=CASCADE)
realm: Optional[Realm] = models.ForeignKey(Realm, blank=True, null=True, on_delete=CASCADE)
create_time: datetime.datetime = models.DateT... | |
"""
Run to generate figures for presentation.
Requires TeX; may need to install texlive-extra-utils on linux
Requires xppy and Py_XPPCall
the main() function at the end calls the preceding individual figure functions.
figures are saved as both png and pdf.
Copyright (c) 2016, <NAME>, <NAME>
All rights rese... | |
from enum import Enum, unique
@unique
class WordType(Enum):
UNKNOWN = 0
SYMBOL = 1
TOGGLE = 2
VALUE = 3
FLAG = 4
DESTINATION = 5
words = {
"'": WordType.SYMBOL,
"-": WordType.SYMBOL,
"*": WordType.SYMBOL,
":": WordType.SYMBOL,
"\\": WordType.SYMBOL,
"_": WordType.SYMBOL,
"{": WordType.SYMBOL,
"|": Wor... | |
As the tree is being populated lazily we create a
# dummy that will be removed when the node is expanded for the
# first time.
cnid._dummy = TreeItem( cnid )
# Return the newly created node:
return cnid
#---------------------------------------------------------------------------
# Deletes a specified tree node... | |
<reponame>py-sdl/py-sdl2<filename>sdl2/test/render_test.py
import sys
import copy
import pytest
import ctypes
from ctypes import byref, POINTER, c_int, c_float, sizeof
import sdl2
from sdl2 import SDL_Init, SDL_Quit, SDL_INIT_EVERYTHING, SDL_GetError
import itertools
from sdl2.stdinc import Uint8, Uint32, SDL_TRUE, SDL... | |
<gh_stars>1-10
"""
Weighted mini-bucket elimination for graphical models
Computes upper or lower bounds on the partition function or MAP/MPE configurations, depending on weights
Supports incremental construction
Supports TRW-based importance sampling
class WMB:
# attributes:
# elimOrder[i]
# priority[Xj] = i if eli... | |
import json
from datetime import datetime
import asyncio
import gspread_asyncio
from oauth2client.service_account import ServiceAccountCredentials
class Handlers:
"""
A collection of multiple handlers
"""
class JSON:
"""
Simple JSON handler for reading and dumping JSON data into files
"""
@staticmethod
def ... | |
<reponame>ollimacp/spacial-boxcounting-cpu-gpu<filename>BoxcountFeatureExtr.py
import numpy as np
from numba import jit #Numba translates Python functions to optemized machine code at runtime and results in significant speedups
import time
#for debugging
import linecache
import sys
def PrintException():
exc_type, exc... | |
<gh_stars>10-100
import numpy as np
import pytest
import psyneulink as pnl
import psyneulink.core.llvm as pnlvm
from psyneulink.core.compositions.composition import Composition
from psyneulink.core.components.functions.nonstateful.combinationfunctions import Reduce
from psyneulink.core.components.functions.nonstatefu... | |
<filename>tests/transformers/test_model_wrapper.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 11:46:59 2018
@author: <NAME>
"""
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.base import Transf... | |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... | |
int
:param EndTime: 结束时间(Unix 时间戳,秒级), 为0 表示当前时间
:type EndTime: int
:param Context: 搜索上下文, 用作查询游标
:type Context: str
:param Size: 单次获取的历史数据项目的最大数量, 缺省10
:type Size: int
:param EventId: 事件标识符,可以用来指定查询特定的事件,如果不指定,则查询所有事件。
:type EventId: str
"""
self.ProductId = None
self.DeviceName = None
self.Type = None
se... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.