input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
of
padding algorithm to use, or a list indicating the explicit paddings at
the start and end of each dimension. When explicit padding is used and
data_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top,
pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used
and data_format is `"NCH... | |
None
self.RequestId = None
def _deserialize(self, params):
self.TaskId = params.get("TaskId")
self.RequestId = params.get("RequestId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds ar... | |
"""
Collection of validators for rating data.
"""
from collections import defaultdict
import itertools
import attr
from registered import parser
from registered.validate import helpers
@attr.s(frozen=True)
class ValidationError: # pylint: disable=too-few-public-methods
"""
Wrapper around a single instance of a vali... | |
<filename>DINGO/along_tract.py
import gc
import re
from nipy import load_image
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cycler, transforms
from matplotlib.legend_handler import HandlerLine2D
from matplotlib.collections import LineCollection
import stats
class HandlerColorLine2D(Handle... | |
is the Abstract base class defining the methods that
must be implemented by the concrete classes.
A user should extend this class with implementations that work on
specific queue systems.
"""
Error = QueueAdapterError
# the limits for certain parameters set on the cluster.
# currently hard coded, should be re... | |
<filename>obsolete/snp2counts_test.py
##########################################################################
# Gene prediction pipeline
#
# $Id: snp2counts_test.py 2855 2010-02-10 09:59:58Z andreas $
#
# Copyright (C) 2004 <NAME>
#
# This program is free software; you can redistribute it and/or
# modify it under th... | |
<reponame>dewancse/SMT-PMR<filename>server/miscellaneous.py
import requests
from libcellml import *
import lxml.etree as ET
# pre-generated model recipe in JSON format
model_recipe = [
{
"med_fma": "http://purl.obolibrary.org/obo/FMA_84666",
"med_pr": "http://purl.obolibrary.org/obo/PR_P26433",
"med_pr_text": "sod... | |
been removed. "
# "Please call frombytes() instead.")
self.frombytes(mode, size, data, decoder_name, *args)
def convert(self, mode):
"converts an image to the given mode"
if self._mode.upper() == mode.upper():
return Image(self._instance.copy())
if not mode and self.mode == "P":
# determine default mo... | |
3),('wei', 2),('jia', 1),('ri', 4),
('gu', 4),('lei', 3),('xiao', 1),('xiao', 1),('lu', 2),('di', 2),('qiu', 1),
]),
(7,[('xie', 4),('gong', 1),('zui', 4),('xiao', 3),('pian', 1),('lian', 2),('nv', 3),
('zi', 4),('jia', 4),('qian', 2),('lou', 2),('bai', 3),('shi', 4),('guai', 1),
('gu', 4),('wo', 3),('wu', 2),('yi'... | |
# coding: tilde
from utils.helpers import COLOR_HEADER, COLOR_BLUE, COLOR_OKGREEN, COLOR_WARNING, FAIL, ENDC, COLOR_BOLD, COLOR_UNDERLINE, COLOR_GREEN, COLOR_GRAY
import logging
import core.arithmetic as arithmetic
from utils.helpers import opcode, padded_hex, pretty_bignum, all_concrete, replace_lines, replace_f
from... | |
"""Cryptocurrency Discovery Controller"""
__docformat__ = "numpy"
# pylint: disable=R0904, C0302, W0622, C0201
import argparse
from typing import List
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal.parent_classes import BaseController
from gamestonk_terminal import feature_flags as gtff
... | |
import numpy as np
import json
from os.path import join
from tqdm import tqdm
from scipy.optimize import least_squares
from pose_optimize.multiview_geo import reproject_error
DEBUG=False
def reproject_error_loss(p3d, p4, p6, cam_proj_4, cam_proj_6, num_kpt=23):
'''
Return:
kp4_e, kp6_e: error array, both (23,) sh... | |
cat[catorow,catocol] > bsid:
cat[crowcol[:,0],crowcol[:,1]] = arclakeid
# if cat[catorow,catocol] != arclakeid and cat[nrow,ncol] != arclakeid:
# print lakeid
if cat[nrow,ncol] > bsid and arcatid[j] > bsid: #### lake input cat route to another lake input catch
cat[crowcol[:,0],crowcol[:,1]] = cat[nrow,ncol]
pp = Po... | |
<reponame>lxing532/TextLinkGeo-User-Embedding
from gensim.models import doc2vec
from collections import namedtuple,Counter
import re
import string
import random
import numpy as np
from numpy import linalg as la
import tweepy
def auth_api():
key_tokens = {}
key_tokens['consumer_key'] = ''
key_tokens['consumer_secre... | |
<reponame>dtobi59/Lixur-Protocol
'''
Lixur uses a new consensus mechanism called Enchanted Consensus, which is a modified version of the Avalanche consensus but slush querying is weighted.
The weight makes it so that nodes with higher influence are more likely to be queried for their opinion.
The weight is designed in ... | |
import os
import json
import pickle
import h5py
import numpy as np
import glob
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
import seaborn as sns
from matplotlib.colors import ListedColormap
import warnings
def open_json(json_fpath):
with open(json_fpath) as js... | |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
# The implementation follows the design in PyTorch: torch.distributions.distribution.py
#
# Copyright (c) 2016- Facebook, Inc (<NAME>)
# Copyright (c) 2014- Facebook, Inc (<NAME>)
# Copyright (c) 2011-2014 Idiap Research Institute (<NA... | |
from kwmo.controllers.abstract_teambox import *
import time
from kwmo.lib.kwmo_kcd_client import KcdClient
from kwmo.lib.config import get_cached_kcd_external_conf_object
from kfs_lib import *
from kwmo.lib.base import init_session
from kwmo.lib.kwmolib import *
from kwmo.model.user import User
from kwmo.model.kfs_n... | |
@ params add mean
w = self.weights.values2d
eps -= (w * eps).sum() / w.sum()
index = self.dependent.index
fitted = DataFrame(_x @ params, index, ["fitted_values"])
idiosyncratic = DataFrame(eps, index, ["idiosyncratic"])
eps_effects = _y - fitted.values
sigma2_tot = float(eps_effects.T @ eps_effects / nobs)
si... | |
self.run = False
if event.type == pygame.MOUSEBUTTONDOWN and not self.menu_gui["main"] == 3:
self.mouse_choose()
elif self.menu_gui["main"] == 3 and event.type == pygame.MOUSEBUTTONDOWN:
self.menu_gui["main"] = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] or keys[pygame.K_UP]:
self.next_item(-1)
i... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# filename: __adapterproxymanager.py_compiler
# Tencent is pleased to support the open source community by making Tars available.
#
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License"); you... | |
+= 1
# print("passedStationCount",st1,st2,down,cnt)
return cnt
def resetStationName(self, old, new, auto_field=False):
old_dict = self.stationByDict(old)
if old_dict is not None:
old_dict["zhanming"] = new if not auto_field else new.split('::')[0]
# 更新标尺中站名
for ruler in self.line.rulers:
ruler.changeStationN... | |
Leakage': 0.00611897,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00348781,
'Renaming Unit/Peak Dynamic': 4.56169,
'Renaming Unit/Runtime Dynamic': 2.0263,
'Renaming Unit/Subthreshold Leakage': 0.070483,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0362779,
'Runtime Dy... | |
'default')
def check_edge(edge, source_name, target_name):
self.assertIsInstance(edge, dict)
source_suid = df[df.name.eq(source_name)].index[0]
target_suid = df[df.name.eq(target_name)].index[0]
self.assertEqual(edge['source'], source_suid)
self.assertEqual(edge['target'], target_suid)
self.assertIsNotNone(edge... | |
import os
import copy
import concurrent.futures
import random
import pandas as pd
import numpy as np
import xarray as xr
from joblib import dump, load
from functools import partial
from typing import List, Tuple
from sklearn.preprocessing import FunctionTransformer
from sklearn.preprocessing import StandardScaler
from... | |
"""Ice-liquid water equilibrium functions.
This module provides thermodynamic properties of ice and liquid water in
equilibrium, e.g. the enthalpy of melting.
:Examples:
>>> pressure(temp=270.)
39313338.8825
>>> densityliq(temp=270.)
1019.05568894
>>> enthalpymelt(temp=270.)
325166.686739
>>> entropymelt(temp=270.)
... | |
<reponame>GustavoSouza13/Minha_Vida_Meu_Trabalho
import os
import time
import random
def status(ListaInfo,cargoTrabalho):
ListaCampos = ["vida:","fome:","sede:","dinheiro:","exp:"]
arquivo = "arq01.txt"
ListaPosicao = procurarCampo(ListaCampos,arquivo)
divisao1 = "| |"
divisao2 = "| |"
divisao3 = "|... | |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
"""
Helpers that make development with ``structlog`` more pleasant.
See also the narrative documentation in `development`.
"""
import sys... | |
#!/usr/bin/env python
#
# Author: <NAME> (mmckerns @caltech and @uqfoundation)
# Copyright (c) 2008-2016 California Institute of Technology.
# Copyright (c) 2016-2019 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/dill/blob/... | |
<reponame>samuelkolb/polytope<filename>tests/polytope_test.py
#!/usr/bin/env python
"""Tests for the polytope subpackage."""
import logging
from nose import tools as nt
import numpy as np
from numpy.testing import assert_allclose
from numpy.testing import assert_array_equal
import scipy.optimize
import polytope as pc... | |
"""
Database table models for Water Survey of Canada National Water Data Archive Hydrometic Data
https://www.canada.ca/en/environment-climate-change/services/water-overview/quantity/monitoring/survey/data-products-services/national-archive-hydat.html
These models were autogenerated using sqlacodegen (https://pypi.org... | |
def test_subsecond_change(self):
"""Perform two ticket changes within a second."""
tkt_id = self._insert_ticket('Test', reporter='joe', component='foo')
ticket = Ticket(self.env, tkt_id)
t1 = datetime(2001, 1, 1, 1, 1, 1, 123456, utc)
ticket.save_changes('jane', 'Testing', t1)
t2 = datetime(2001, 1, 1, 1, 1, 1, 1... | |
import numpy as np
import logging
from collections import defaultdict
from Bio import motifs as BioMotifs
from itertools import product
import re
def motifs_from_file( opts ):
"""
Read through the file containing motifs to query. Should
be in the form:
ACGT-0
GATC-1
CATG-1
where the number indicates the 0-b... | |
<reponame>exizt/tistory-skin-simulator<filename>SkinParser.py
"""
skin.html을 flask의 template파일로 변환하는 부분 중 기능적인 부분들을 담당.
이를 호출하는 것은 SkinLoader
렌더링과 파서 기능을 담당한다.
"""
import re
def parse(context: str) -> str:
"""
skin.html 을 flask template 형태로 변환.
:param context: str
:return:str
"""
# 공통
context = context.repla... | |
<gh_stars>1-10
import os
import dill
import numpy as np
import copy
from math import pi, log, exp, sqrt, floor
from keras.models import Sequential
from keras.layers import LSTM, GRU, Dense
from keras import optimizers
from oscillator_snap.oscillator_auxiliaries import *
def compile_model(model, learning_rate):
"""c... | |
+ str(stars) + '\n')
else:
print 'We do not have complete QC data for this sample'
print temp[0] + '\t' + temp[1] + '\t' + temp[2] + '\t' + temp[3] + '\t' + temp[4] + '\t' + temp[5]
f.close()
g.close()
# Get the tissue type linked to each project
f = open('Supplementary_Table_2.tsv', 'r')
tissues = {}
... | |
[]
alreadyRunRandom = 0
RS_configurations_count = 0
arr = list(fast_addressing_of_data_array.values())
if len(arr) == 0:
absolute_configuration_index = 0
else:
absolute_configuration_index = np.asarray(arr, dtype=np.int).max() + 1
# See if input space is big enough otherwise it doesn't make sense to draw numb... | |
<reponame>zhangjq933/HowtoSim_Script<gh_stars>10-100
# coding=utf-8
import os, re, sys, clr, json, math, logging, random, time
from itertools import combinations
os.chdir(os.path.dirname(__file__))
logging.basicConfig(filename='gui.log', filemode='w', encoding='utf-8', level=logging.DEBUG)
clr.AddReference('System... | |
<reponame>RogerEMO/srd<filename>srd/actors.py<gh_stars>1-10
from copy import deepcopy
# INITIALIZE INDIVIDUALS AND HOUSEHOLDS #
class Person:
"""
Classe pour définir une personne.
Ceci définit une personne et son profil en termes de revenus et d'actifs.
Parameters
----------
age: int
âge de l'in... | |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import json
import requests
import dateparser
from datetime import datetime
import traceback
from typing import Any, Dict, Tuple, List, Optional, cast
from copy import copy
import hmac
import hashlib
"""Darktrace Inte... | |
* mu.cost(5.23997785185 + 9872.27408296480 * x)
B0 += 0.00000000142 * mu.cost(3.02798835989 + 3511.28529731900 * x)
B0 += 0.00000000165 * mu.cost(2.53171951288 + 16276.46394262300 * x)
B0 += 0.00000000153 * mu.cost(6.14783670557 + 13362.51701710200 * x)
B0 += 0.00000000119 * mu.cost(4.15694365082 + 3760.09707057500... | |
count_interior:
count_interior += 1
else:
count_interior=0
indice_parametros += 1
count_exterior += 1
comandos_establecidos = comandos_sin_establecer
# Si hay mas de 2 comandos de dibujado invocados...
if len(self.comandos_tikz_validados)-1 >= 0:
# Si se desea añadir los comandos invocados al "ejecutar" del c... | |
if 'n_layers' not in network_config else network_config['n_layers'] + 1
dim_hidden = network_config.get('dim_hidden', 40)
if type(dim_hidden) is int:
dim_hidden = (n_layers - 1) * [dim_hidden]
else:
dim_hidden = copy(dim_hidden)
n_layers = len(dim_hidden) + 1
boundaries = network_config['output_boundaries']
dim... | |
2),('yin', 2),('hu', 3),('xiao', 4),('yi', 4),('shi', 2),('fa', 1),
('wan', 4),('lai', 4),('bai', 3),('quan', 2),('xiang', 1),('yu', 3),('qiu', 1),
('hu', 1),('ran', 2),('geng', 4),('zuo', 4),('yu', 2),('yang', 2),('chan', 1),
('huang', 2),('yun', 2),('xiao', 1),('tiao', 2),('bai', 2),('ri', 4),('an', 4),
('bian', ... | |
<gh_stars>0
"""
This playbook processes URLs not in bogon_list and creates a task note for every indicator for review by the analyst
"""
import phantom.rules as phantom
import json
from datetime import datetime, timedelta
def on_start(container):
phantom.debug('on_start() called')
# call 'check_urls' block
check_... | |
from time import sleep, localtime
from biblio.interface.interface import *
from biblio.extras.extras import *
from os import getcwd, get_terminal_size, listdir, system
from biblio.bib import *
# /* Tamanho Terminal */
tamterm = get_terminal_size()
tamterm = tamterm[0]
if tamterm < 50:
barra = 2
elif tamterm < 75:
ba... | |
signif / 2) * repl) - 1)
lower = ma_sort[low_idx, :, :, :]
upper = ma_sort[upp_idx, :, :, :]
return lower, upper
def irf_resim(self, orth=False, repl=1000, T=10,
seed=None, burn=100, cum=False):
"""
Simulates impulse response function, returning an array of simulations.
Used for Sims-Zha error band calculation... | |
<gh_stars>10-100
from test.support import verbose, run_unittest, gc_collect, bigmemtest, _2G, cpython_only, captured_stdout
import io
import locale
import re
import sre_compile
import string
import sys
import traceback
import unittest
import warnings
from re import Scanner
from weakref import proxy
class S(str):
de... | |
<reponame>hfboyce/tableau_course
# Classification and Regression Metrics
*<NAME>, May 17th, 2021*
# Importing our libraries
import pandas as pd
import altair as alt
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.dummy import DummyClassifier, DummyRegressor
from sklearn.neighbors impor... | |
<gh_stars>0
import pytest
from summit.benchmarks import *
from summit.domain import *
from summit.utils.dataset import DataSet
from summit.utils.multiobjective import pareto_efficient, hypervolume
from summit.strategies import *
import GPy
from fastprogress.fastprogress import progress_bar
import numpy as np
import o... | |
face material
#
nodePath.setMaterial(materials[matIndex], 1) #Apply the material to this nodePath
nodePath.setTwoSided(materials[matIndex].getTwoside())
nodePath.setPythonTag('material', materials[matIndex])
nodePath.setPythonTag('pickableObjTag', 1)
#
# set polygon face textures
#
texFileMain = None
texFil... | |
<gh_stars>1-10
"""
Copyright (C) 2019 the LSNN team, <NAME>
"""
from distutils.version import LooseVersion
import datetime
from collections import OrderedDict
from collections import namedtuple
import numpy as np
import numpy.random as rd
import tensorflow as tf
from tensorflow.python.framework import function
from t... | |
import copy
import warnings
from ajenti.api import *
from ajenti.ui.element import p, UIElement
from ajenti.util import *
def is_bound_context(el):
"""
:type el: UIElement
:rtype: bool
"""
return ('{binder}context' in el.properties) and el.properties['{binder}context'] is not None
def is_bound(el):
"""
:typ... | |
datastore_pb.Query_Filter.GREATER_THAN_OR_EQUAL:
start_value = equality_value + value1
else:
raise dbconstants.AppScaleMisconfiguredQuery("Bad filter ordering")
# The second operator will be either < or <=.
if oper2 == datastore_pb.Query_Filter.LESS_THAN:
end_value = equality_value + value2
elif oper2 == datast... | |
= model.coef_
return coef
# =====================Functions used to compute the ranked features and their weights=======================
def TopGenbinary(w,feature_names):
n=len(w)
difference=np.zeros(n)
for i in range(n):
difference[i]=w[i][0]-w[i][1]
df1=pd.DataFrame(feature_names,columns=['pd'])
df1['weights'... | |
<gh_stars>100-1000
# -*- test-case-name: txweb2.test.test_server,twext.web2.test.test_resource -*-
##
# Copyright (c) 2001-2007 Twisted Matrix Laboratories.
# Copyright (c) 2010-2017 Apple Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and a... | |
# Copyright (c) 2009-2010 <NAME>. See LICENSE for details.
import sys
import traceback
from gevent import core
from gevent.hub import greenlet, getcurrent, get_hub, GreenletExit, Waiter
from gevent.timeout import Timeout
__all__ = ['Greenlet',
'joinall',
'killall']
class SpawnedLink(object):
"""A wrapper around... | |
js.start_process()
expected_calls_made = [call('1.1.1.1', 'abc', 'xyz', 'pre', ANY, ANY, ANY),
call('1.1.1.15', 'abc', 'xyz', 'pre', ANY, ANY, ANY),
call('1.1.1.16', 'abc', 'xyz', 'pre', ANY, ANY, ANY),
]
self.assertTrue(mock_connect.called)
mock_connect.assert_has_calls(expected_calls_made, any_order=True)
@... | |
def enterReturn_type121(self, ctx):
pass
# Exit a parse tree produced by CSharp4Parser#return_type121.
def exitReturn_type121(self, ctx):
pass
# Enter a parse tree produced by CSharp4Parser#member_name.
def enterMember_name(self, ctx):
pass
# Exit a parse tree produced by CSharp4Parser#member_name.
def exi... | |
<filename>ohbm/attendees.py<gh_stars>0
'''
attendees: part of the ohbm-api
'''
from ohbm.utils import get_url, ordered_to_dict, parse_item, parse_items, capitalize
class Attendees():
def __init__(self,api=None):
if api == None:
print("Please use this module from ohbm.api")
else:
self.api = api
def get_result... | |
not assigned to anyone, or if the orderHintsByAssignee '
'dictionary does not provide an order hint for the user the task is assigned to. The format is '
'defined as outlined here.')
with self.argument_context('planner planner-plan-task update-bucket-task-board-format') as c:
c.argument('planner_plan_id', type=str... | |
<filename>CodeArena/db.py
'''1. email and hash of pwd
verify email and pwd'''
from CodeArena import bcrypt
import mysql.connector as ms
from CodeArena.CodeUtilities import convert_to_file, get_countdown_time
import os
class userdbop:
def logincheck(self, email, pwd):
cnx = ms.connect(unix_socket='/Applications/MA... | |
import collections
from copy import deepcopy
import meshio
import numpy
from ._common import (
get_local_index,
get_meshio_version,
get_new_meshio_cells,
get_old_meshio_cells,
meshio_data,
)
from ._properties import (
_connections,
_face_areas,
_face_normals,
_faces,
_materials,
_volumes,
)
__all__ = [
"... | |
None:
if params.interactive:
start_color = self.status.GetBackgroundColour()
self.status.SetBackgroundColour( params.status_blue )
self.status.SetStatusText( "writing plaintext results", params.status_box )
wx.BeginBusyCursor()
wx.Yield()
self.ann_file.WriteCSV( csv_name )
if self.alive and params.interactive... | |
'The numeric ID of the file.',
},
'caption': {
'type': str,
'description': "The file's descriptive caption.",
},
'filename': {
'type': str,
'description': "The name of the file.",
},
'url': {
'type': str,
'description': "The URL of the file, for downloading purposes."
"If this is not an absolute URL, then ... | |
TBI - Generalize to go through all params, reading from each its type (from a registry),
and calling on corresponding subclass to get default values (if param not found)
(as PROJECTION_TYPE and PROJECTION_SENDER are currently handled)
"""
from psyneulink.core.components.ports.port import _parse_port_spec
from psy... | |
into the reader will be converted to the
data pack format, and being passed onto the other components for
processing.
Args:
reader: The reader to be used of the pipeline
config: The custom configuration to be passed to the reader. If
the config is not provided, the default config defined by the
reader class wil... | |
isinstance(hue_palette, dict), "`hue_palette` must be dict"
# assert drawing_order in ['sorted', 'random', 'original'],\
# "`drawing_order` must be one of ['original', 'sorted', 'random']"
# legend_order = {hue: np.unique(df[hue]) for hue in list_hue
# if (is_string_dtype(df[hue])
# or is_categorical_dtype(df[hue]))}... | |
#!/usr/bin/python
# Copyright: (c) 2020, DellEMC
# GNU General Public License v3.0+
""" Distributed virtual volume module """
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}... | |
# -*- coding: utf-8 -*-
# Copyright 2020 Google 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 ag... | |
oO0o
if 11 - 11: o0oOOo0O0Ooo . OoooooooOO - i1IIi
if 71 - 71: I1IiiI . OOooOOo . I1ii11iIi11i
if 90 - 90: i11iIiiIii + I1Ii111 % II111iiii
def lisp_clear_map_cache ( ) :
global lisp_map_cache , lisp_rloc_probe_list
global lisp_crypto_keys_by_rloc_encap , lisp_crypto_keys_by_rloc_decap
global lisp_rtr_list
if 67... | |
<reponame>toltec-astro/kidsproc<gh_stars>0
#! /usr/bin/env python
from astropy.modeling import Parameter, Model
import numpy as np
from astropy import units as u
import inspect
class _Model(Model):
"""Subclass of astropy.modeling.Model that support complex type."""
# code snippet from `astropy.modeling.Model`
de... | |
<gh_stars>0
"""
Find an approximate MMS allocation.
Based on:
<NAME> and <NAME>,
["An Improved Approximation Algorithm for Maximin Shares"](https://www.sciencedirect.com/science/article/abs/pii/S0004370221000989),
Artificial Intelligence, 2021.
Programmers: <NAME> and <NAME>
Date: 2022-05
"""
from fairpy import Allo... | |
<gh_stars>0
import json
from lxml import etree as ET
import psimi
class Mif254Builder():
"""Builds PSI-MI XML (ver 2.5.4) representation of interaction record
as a single entry <entrySet>.
"""
def __init__(self):
self.ns="http://psi.hupo.org/mi/mif"
self.nsmap = {None: self.ns }
self.mif = "{%s}" % self.ns
sel... | |
<reponame>dbeetcher/GuitarEngine
#Author-<NAME>
#Description - Generates a guitar
import adsk.core, adsk.fusion, traceback, math
from math import sqrt
from .defaultParameters import defaultParameters
# Globals
app = adsk.core.Application.cast(None)
ui = adsk.core.UserInterface.cast(None)
units = ''
#Default Inputs
de... | |
<reponame>nens/threedigrid<gh_stars>1-10
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import unittest
import tempfile
import shutil
import numpy as np
from osgeo import ogr
from threedigrid.admin.gridadm... | |
pass
def build(self, node):
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_)
return self
def buildAttributes(self, node, attrs, already_processed):
value = fi... | |
from __future__ import print_function
import os
import itertools, pkg_resources, sys
from distutils.version import LooseVersion
if LooseVersion(pkg_resources.get_distribution("chainer").version) >= LooseVersion('7.0.0') and \
sys.version_info.major == 2:
print('''Please install chainer <= 7.0.0:
sudo pip install c... | |
:param pulumi.Input[str] user_data_base64: Can be used instead of `user_data` to pass base64-encoded binary data directly. Use this instead of `user_data` whenever the value is not a valid UTF-8 string. For example, gzip-encoded user data must be base64-encoded and passed via this argument to avoid corruption.
:param ... | |
# -*- coding: utf-8 -*-
# Copyright (c) 2013, <NAME>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the foll... | |
# coding: utf-8
"""
Director API
This is the oSparc's director API # noqa: E501
OpenAPI spec version: 0.1.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from simcore_d... | |
and agg_data['percent_idle'] < 0:
return self.STATUS_BAD_NO_PINGS
if agg_data['tasks_done'] == 0 and agg_data['percent_idle'] < 1:
return self.STATUS_WARN_LONG_TASK # this case should self heal, as hard kill should be triggered
if agg_data['tasks_done'] == 0 and agg_data['percent_idle'] > 99:
return self.STATUS_OK... | |
Zserio varuint16 type from the bit stream.
:param reader: Bit stream from which to read.
:param _index: Not used.
"""
return reader.read_varuint16()
@staticmethod
def write(writer: BitStreamWriter, value: int) -> None:
"""
Writes Zserio varuint16 type to the bit stream.
:param writer: Bit stream where to w... | |
<reponame>abauville/Sunaba
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 9 16:53:49 2016
@author: abauville
"""
from math import pi, pow, exp
from InputDef import Frozen
import copy
class Material(Frozen):
_Frozen__List = ["name","material","cohesion","frictionAngle","dilationAngle","r... | |
are empirically chosen to approximately lead to unit variance targets
__C.MODEL.BBOX_REG_WEIGHTS = (10., 10., 5., 5.)
__C.MODEL.VIDEO_ON = False
## Batch normalization
# If true, use the SpatialBN layer instead of AffineChannel layer
__C.MODEL.USE_BN = False
# If true, use the BN layer in test mode (i.e. should be s... | |
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capture - uses pysafe names
return_timestamps:
which subset of 'timesteps' should be values be returned?
Returns
-------
outputs: list of dictionaries
"""
outputs = pd.DataFrame(columns=cap... | |
<reponame>reddigari/Eelbrain
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>
from functools import partial
from itertools import product
from numbers import Number
import mne
from nibabel.freesurfer import read_annot
import numpy as np
from .._data_obj import NDVar, SourceSpace, UTS
from .._utils import deprecated... | |
= 'GEOS-CF'
dfs_mod = {'GEOS-CF': df_mod_CF}
print(('!'*30, mod_label_master, dfs_mod.keys()))
# Get observations and model timeseries data as a DataFrame
# df_obs = dfs_obs[flight_ID]
# df_mod = dfs_mod[flight_ID]
# Only consider data during SLRs?
if just_SLR:
df_obs = df_obs.loc[df_obs['IS_SLR'] == True, :]
f... | |
request, please pass async_req=True
>>> thread = api.security_get_security_group_categories_v1(async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data... | |
columns.append(p.key)
elif hasattr(p, 'columns'):
if len(p.columns) > 1:
filtered = tools.filter_foreign_columns(self.model.__table__, p.columns)
if len(filtered) == 0:
continue
elif len(filtered) > 1:
warnings.warn('Can not convert multiple-column properties (%s.%s)' % (self.model, p.key))
continue
column =... | |
<reponame>tomasdubec/openstack-cinder<gh_stars>0
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); y... | |
# type: (...) -> models.AdminApiTokenGetResponse
"""
Displays API tokens for the specified administrators.
Args:
admins (list[FixedReference], optional):
A list of admins to query for. Overrides admin_ids and admin_names keyword arguments.
admin_ids (list[str], optional):
A list of admin IDs. If after filterin... | |
<gh_stars>1-10
"""Classification with abstention network architecture."""
import numpy as np
np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
__author__ = "<NAME> and <NAME>"
__date__ = "March 17, 2021"
#----------------------------------------------------------------
def define_experime... | |
not isinstance(d, list):
d = [d]
for d1 in d:
for f in qualified_method(d1):
if f not in seen:
self.add_call(node, name, f)
seen.add(f)
return name
def visit_Assign(self, node):
for v in node.targets:
if isinstance(v, ast.Attribute):
self.add_attr(v)
def visit_Attribute(self, node):
ops = self.traces[nod... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
from Tea.model import TeaModel
from typing import List
class Config(TeaModel):
"""
Model for initing client
"""
def __init__(
self,
access_key_id: str = None,
access_key_secret: str = None,
security_token: str = None,... | |
<filename>legtool/gait/ripple.py
# Copyright 2014 <NAME>, <EMAIL>.
#
# 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 applic... | |
<filename>src/third_party/red_tamarin_stable/tamarin-cental/aot/AOTStubs.py
#!/usr/bin/env python
# -*- Mode: Python; indent-tabs-mode: nil -*-
# vi: set ts=4 sw=4 expandtab:
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# fil... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
import math
import random
import sys
from typing import Union
from scipy.stats import binom
# Stupid black magic to suppress rare `divide by zero encountered in _binom_cdf` warning when calling binom for first
# time with very particular va... | |
in [group, mesh]:
print "[X] The input objects are incorrect or the Mesh module was not yet loaded."; return
#-
# Set father object
father = None
if infa == True: father = group
#-
if False: pass
else:# All checks done
# Get input objects
[dist, step] = thick_and_size
try:
... | |
<reponame>husensofteng/msstitch
import argparse
shared_options = {
'fn': {'driverattr': 'fn', 'dest': 'infile', 'type': 'file', 'clarg': '-i',
'help': 'Input file of {} format'},
'outfile': {'driverattr': 'outfile', 'dest': 'outfile', 'type': str,
'clarg': '-o', 'help': 'Output file', 'required': False},
'outdir'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.