input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
the SMILES separated by new lines.
"""
with open(smiles_file, 'r') as smiles_file_fd:
for line in smiles_file_fd:
self.smiles.append(line.strip())
return
def obtain_SMILES_from_table(self, drugbankids, drugbank_smiles_file):
"""
Obtains the SMILES of a drug from an input table and stores them into a list.
"""... | |
along each of the leading diagonals.
1=lst, 2=days, 3=triads.
'dlst' [scalar] LST interval (in mins) or difference between LST
pairs which will be determined and used for
cross-power spectrum. Will only apply if values under
'axes' contains the LST axis(=1).
'dlst_range'
[scalar, numpy array, or NoneType] Spe... | |
#!/usr/bin/env python3
import calendar
import json
import os
import pickle
import platform
import sys
import unittest
import warnings
import yaml
from io import StringIO
from contextlib import redirect_stderr, redirect_stdout
from collections import OrderedDict
from random import randint, shuffle
from jsonargparse imp... | |
"""Input and output (IO) of information from and to the persistence layer.
Currently, input and output of both, datasets and recipes can be handled.
Datasets
========
Both, data and metadata contained in datasets as well as the information
stored in recipes for recipe-driven data analysis can be read and written.
... | |
the FLT file.
"""
import pyregion
mask_files = glob.glob(flt_file.replace('_flt.fits','.*.mask.reg').replace('_flc.fits','.*.mask.reg').replace('_c0m.fits','.*.mask.reg').replace('_c0f.fits','.*.mask.reg'))
if len(mask_files) == 0:
return True
logstr = '# Region mask for {0}: {1}'.format(flt_file, mask_files... | |
follow_val_x, '$\mathregular{^%s}\!$' % follow_val_x) #
# Deal with formatting of y axis labels
y_ax_lab = ''
y_ax_lab_components = plot_dict['y_label'].split(' \\n ')
if len(y_ax_lab_components) > 1:
for k in range(len(y_ax_lab_components)):
if k < len(y_ax_lab_components) - 1:
y_ax_lab += y_ax_lab_components[... | |
outstanding perturbations in this iteration
mapped_x, mapped_unnormalized_x = compute_x_after_mapping_back(
domain,
url_id,
html,
html_fname,
working_dir=working_dir,
browser_id=browser_id,
final_domain=final_domain
)
return mapped_x, mapped_unnormalized_x, original_url, url
def _deprocess_x(self, x,... | |
= other + va
assert isinstance(result2, Other)
assert_equal(tuple(result2),
(self.Vec2(1,0), self.Vec2(4,1), self.Vec2(6,1)))
def test_add_vector_to_array(self):
va = self.Vec2Array([(0,1), (2,3), (3,4)]) + self.Vec2(-2,3)
assert isinstance(va, self.Vec2Array), repr(va)
assert_equal(tuple(va),
(self.Vec2(-2,4... | |
<filename>scripts/PT_WebExtractor_v2_0/extras/Merge_Inventories/Merge_PT_to_XL.py
import os
import sys
import argparse
import glob
import traceback
import codecs
import fileinput
import datetime
import time
import dateutil.parser as parser
import csv
import collections
import re
from StringIO import String... | |
REGEXP attached.
"""
self.__test_clean_regexp_good_h(self.STR, "1e.+")
def test_clean_regexp_int_good(self):
"""
Testing clean() on an int with a good REGEXP attached.
"""
# Note that this would be a pretty dumb regexp to put on an integer!
self.__test_clean_regexp_good_h(self.STR, "bar")
def test_clean_rege... | |
<gh_stars>0
# encoding=utf8
"""Particle swarm algorithm module."""
import numpy as np
from niapy.algorithms.algorithm import Algorithm
from niapy.util import full_array
from niapy.util.repair import reflect
__all__ = [
'ParticleSwarmAlgorithm',
'ParticleSwarmOptimization',
'CenterParticleSwarmOptimization',
'Mu... | |
'session_token',
'uid',
'payload',
],
'nullable': [
],
'enum': [
],
'validation': [
]
},
root_map={
'validations': {
},
'allowed_values': {
},
'openapi_types': {
'session_token':
(str,),
'uid':
(int,),
'payload':
(StringId,),
},
'attribute_map': {
'session_token': 'sessionToken',
'uid': 'uid',... | |
equivalences that go away because of cexs in cex_list"""
#### global f_name
#### abc('&r %s_gores.aig'%f_name)
#### for j in range(len(cex_list)):
#### cex_put(cex_list[j])
#### run_command('&resim') #put the jth cex into the cex space and use it to refine the equivs
#### abc('&w %s_gores.aig'%f_name)
#### return
#### ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
main
====
Typical GUI screen, adapted from prior pyqt work
Attributes:
na
Todo:
* clean up docstrings (ideally to sphinx format, but to numpy/scipy
minimally)
Related projects:
Adapted from initial toy project https://github.com/sonlexqt/whack-a-mole
which is under MIT l... | |
"Dragon Tooth+4",
854005: "Dragon Tooth+5",
855000: "Large Club",
855001: "Large Club+1",
855002: "Large Club+2",
855003: "Large Club+3",
855004: "Large Club+4",
855005: "Large Club+5",
855006: "Large Club+6",
855007: "Large Club+7",
855008: "Large Club+8",
855009: "Large Club+9",
855010: "Large... | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Configuration file (powered by YACS)."""
import os
from pycls.core.io import pathmgr
from yacs.config import CfgN... | |
UnaryExpression(Keyword('waypointloiterradius'), Array, Number),
UnaryExpression(Keyword('waypointloitertype'), Array, String),
UnaryExpression(Keyword('waypointname'), Array, String),
UnaryExpression(Keyword('waypointposition'), Array, Array),
UnaryExpression(Keyword('waypoints'), Object, Array),
UnaryExpression(... | |
'mwot',
'n': 'wikinews',
'netvillage': 'netvillage',
'nkcells': 'nkcells',
'nomcom': 'nomcom',
'nosmoke': 'nosmoke',
'nost': 'nost',
'oeis': 'oeis',
'oldwikisource': 'oldwikisource',
'olpc': 'olpc',
'onelook': 'onelook',
'openfacts': 'openfacts',
'openstreetmap': 'openstreetmap',
'openwetware': 'openwetwar... | |
import math
from PySide2 import QtGui
from .core import Object
__author__ = "<NAME>"
class Point(Object):
def __init__(self, x = 0, y = 0):
super(Point, self).__init__()
if not isinstance(x, (int, float)):
x = 0
if not isinstance(y, (int, float)):
y = 0
self.x = x
self.y = y
def __str__(self)... | |
<gh_stars>10-100
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ------------------------------------------------------------------... | |
+ m.x2328 + m.x2428 + m.x2528 + m.x2628 + m.x2728
+ m.x2828 + m.x2928 == 1)
m.c3030 = Constraint(expr= m.x29 + m.x129 + m.x229 + m.x329 + m.x429 + m.x529 + m.x629 + m.x729 + m.x829 + m.x929
+ m.x1029 + m.x1129 + m.x1229 + m.x1329 + m.x1429 + m.x1529 + m.x1629 + m.x1729 + m.x1829
+ m.x1929 + m.x2029 + m.x2129 + m.x2... | |
% l)
self.save_flow(up_flow_f, '%s_flow_f_upflow' % l)
self.save_flow(up_flow_b, '%s_flow_b_upflow' % l)
x2_warp = self.warping_layer(x2, flow_f)
x1_warp = self.warping_layer(x1, flow_b)
# if norm feature
if self.if_norm_before_cost_volume:
x1, x2_warp = network_tools.normalize_features((x1, x2_warp), normalize=... | |
<filename>roboticstoolbox/blocks/arm.py
import numpy as np
from math import sin, cos, atan2, tan, sqrt, pi
import matplotlib.pyplot as plt
import time
from spatialmath import base, SE3
from bdsim.components import TransferBlock, FunctionBlock, SourceBlock
from bdsim.graphics import GraphicsBlock
from roboticstoolbox... | |
<filename>tools/upgrade/errors.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import re
import subprocess
import sys
from collections import d... | |
<filename>model_lr_and_gdbt_and_xgboost/feature_construct/feature_construct_part_1.py
import pandas as pd
import numpy as np
'''
this file for data_set_part_1
'''
##### file path
# input
path_df_D = "tianchi_fresh_comp_train_user.csv"
path_df_part_1 = "df_part_1.csv"
path_df_part_2 = "df_part_2.csv"... | |
annotate the item.
"""
return pulumi.get(self, "comment")
@pulumi.output_type
class LoadBalancerMonitorHeader(dict):
def __init__(__self__, *,
header: str,
values: Sequence[str]):
"""
:param str header: The header name.
:param Sequence[str] values: A list of string values for the header.
"""
pulumi.set(__se... | |
"""
Distributed Cloud Emulator (dcemulator)
(c) 2015 by <NAME> <<EMAIL>>
"""
import logging
import site
import time
from subprocess import Popen
import os
import re
import urllib2
from functools import partial
from mininet.net import Containernet
from mininet.node import Controller, DefaultController, OVSSwitch, OVSK... | |
import os
import time
import PIL
import numpy as np
import scipy.sparse
import cv2
from sklearn.cluster import DBSCAN
from collections import Counter
#from utils.cython_bbox import bbox_overlaps
#from utils.boxes_grid import get_boxes_grid
#import subprocess
#import cPickle
#from fast_rcnn.config import cfg
#import mat... | |
or 'application/octet-stream').split('/', 1)
if maintype == 'image':
att = MIMEImage(data, _subtype=subtype)
else:
att = MIMEBase(maintype, subtype)
att.set_payload(data)
encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(fn))
return att
def add_attachme... | |
be populated by parsing raw responses
# - these are aggregated into project_campaign_response_summary
#
#tablename = "project_campaign_response"
#define_table(tablename,
# message_id(),
# This is a component, so needs to be a super_link
# - can't override field name, ondelete or requires
# super_link("parameter... | |
<gh_stars>0
import os
import sys
import json
import numpy as np
import tensorflow as tf
from tqdm import tqdm
from nn import *
from myLSTM import *
class BaseModel(object):
def __init__(self, params, mode, num_words, word2vec, idx2word):
self.params = params
self.mode = mode
self.batch_size = params.batch_size i... | |
<filename>reinvent-2019/drone-zone/ground-control.py
#!/usr/bin/env python
import argparse
import base64
import csv
import json
import logging
import os
import sys
import tempfile
import time
import uuid
import cv2
import numpy as np
import olympe
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient
from AWSIoT... | |
: 2 * mini_batch_size]
# ...
# ```
#
# Note that the last mini-batch might end up smaller than `mini_batch_size=64`. Let $\lfloor s \rfloor$ represents $s$ rounded down to the nearest integer (this is `math.floor(s)` in Python). If the total number of examples is not a multiple of `mini_batch_size=64` then there will ... | |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# observingconditions - Implements ASCOM Alpaca ObservingConditions device class
#
# Part of the Alpyca Client application interface package
#
# Author: <NAME> <<EMAIL>> (rbd)
#
# Python Compatibility: Requires Pytho... | |
# -*- coding: utf-8 -*-
"""
Survey_Estimate3dCoord.py
***************************************************************************
* *
* 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 ... | |
QubitHamiltonian = bravyi_kitaev_tree(FermionicHamiltonian)
else:
raise ValueError('unknown transformation')
if threshold is None:
return QubitHamiltonian
else:
from openfermion.ops import QubitOperator
reduced_QubitHamiltonian = QubitOperator()
for key in QubitHamiltonian.terms:
if np.abs(QubitHamiltonian.te... | |
<filename>albaceaScript.py
#!/usr/bin/env python3
################################################################################################
#
# AlbaceaScript: based on the Glacier Protocol (http://glacierprotocol.org)
#
# It is designed specifically for use in the context of executing the broader Glacier
# Prot... | |
import numpy as np
import scipy.io as scio
import scipy.sparse as scsp
import h5py as hp
from util import read_mymat73, read_mymat, build_img_dataset, process_ad_dataset, mv_dataset, mv_tabular_collate, AverageMeter, save_roc_pr_curve_data, get_all_labels, \
load_print_results, filter_nan_grad, read_dataset, build_vad... | |
# based on x360_imports.idc by xorloser
# work out which name generating function to use
#
# args: name of the library to get name from
# version of the library to get name from
# id that represents the function/data in the library
# returns: generated name
def DoNameGen(libName, version, id):
# remove the extension... | |
from typing import Callable, Dict, Optional, Sequence, Tuple
from functools import partial
import numpy as np
import torch
from torch import Tensor
from torch.nn import functional as F
# @TODO:
# after full classification metrics re-implementation, make a reference to
# https://github.com/scikit-learn/scikit-learn/b... | |
<reponame>machinezone/kubespec<filename>kubespec/certmanager/v1alpha3.py<gh_stars>1-10
# Code is generated: DO NOT EDIT
# Copyright 2019 Machine Zone, Inc. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from kubespec import context
from kube... | |
import os, math, ctypes
import numpy as np
from OpenGL import GL
from art import VERT_LENGTH
from palette import MAX_COLORS
# inactive layer alphas
LAYER_VIS_FULL = 1
LAYER_VIS_DIM = 0.25
LAYER_VIS_NONE = 0
class TileRenderable:
"""
3D visual representation of an Art. Each layer is rendered as grids of
rectangula... | |
<gh_stars>0
from collections import defaultdict
from enum import Enum, auto
import logging
import numpy as np
from PfgUtil import debug_mode
class TransformationOption(Enum):
NONE = auto()
AGGREGATE_CALLS = auto()
VERTICAL_STACK_CPU = auto()
COLLAPSE_GROUPS = auto()
class ColourMode(Enum):
BY_PARENT = auto()
B... | |
"""
Code take from <NAME>'s excellent python tracing library: https://github.com/donkirkby/live-py-plugin
"""
import argparse
from ast import (fix_missing_locations, iter_fields, parse, Add, Assign, AST,
Attribute, BitAnd, BitOr, BitXor, Call, Div, Ellipsis,
ExceptHandler, Expr, ExtSlice, FloorDiv, ImportFrom, Inde... | |
have a cache, return *None*
"""
if node in self.model.cache:
return self.model.cache[node].has(content)
def local_cache_lookup(self, node, content):
"""Check if the local cache of a node has a content object, without
changing the internal state of the cache.
The local cache is an area of the cache of a node re... | |
<gh_stars>1-10
import importlib
import os.path
import warnings
import numpy as np
import pysb
from pysb.simulator import ScipyOdeSimulator
from scipy.stats import norm, uniform
from ..sampled_parameter import SampledParameter
default_solver = ScipyOdeSimulator
def is_numbers(inputString):
return all(char.isdigit()... | |
a freq argument as current index has none."
raise ValueError(msg)
if freq is None:
freq = self.freq
return PeriodIndex(self.values, freq=freq)
def order(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-... | |
returned by getList."""
result = _convert_dict(
asset, {
'name': 'id',
},
defaults={'type': 'Image'})
return result
def _convert_asset_type_for_get_list_result(asset_type):
"""Converts an EarthEngineAsset.Type to the format returned by getList."""
return _convert_value(
asset_type, {
'IMAGE': 'Image',
'IMA... | |
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method portal_members_id_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `portal_m... | |
2min and 30 min data
two_minute = [327587572,247923021,149505899,147921014,471015233,383553764,166698220,
41232189,298165335,198456033,181240911,165370459,219752116,27533327,
39464221,441120034,140282069,32869782,365653206,229980646]
thirty_minute = [219820925,229945862,440765193,8591766,417544924,144599609,2074404... | |
import codecs
import csv
from io import StringIO, BytesIO
from unittest.mock import MagicMock
from zipfile import ZipFile
import pytest
from export.enums import FileFormat
from logs.logic.reporting.filters import (
DateDimensionFilter,
ForeignKeyDimensionFilter,
ExplicitDimensionFilter,
)
from logs.logic.reporting... | |
<filename>code/multidop_time.py<gh_stars>0
import matplotlib
# Needed for Blues
matplotlib.use('agg')
from matplotlib import rcParams
from matplotlib import pyplot as plt
# PyART
import pyart
import gzip
import sys
from scipy import ndimage
import shutil, os
from datetime import timedelta, datetime
import numpy as np
i... | |
# FileName:AWGboard.py
# Author:
# E-mail:
# All right reserved.
# Modified: 2019.2.18
# Description:The class of AWG
import os
import socket
import time
import numpy as np
from . import AWGBoardDefines
# import AWGBoardDefines
import struct
from itertools import repeat
awg_para = {
'000423' : [[1.030,1.025,1.018,1.... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 09:10:58 2020
Module for visualising Metrica tracking and event data
Data can be found at: https://github.com/metrica-sports/sample-data
@author: <NAME> (@EightyFivePoint)
"""
import matplotlib.pyplot as plt
import numpy as np
import matplotlib... | |
from smartvadhis2.cli import remove_keys, print_error_categories
def test_remove_keys():
metadata = {
"programStages": [
{
"lastUpdated": "2018-04-19T13:38:20.185",
"id": "pQ8gaWKD3pi",
"created": "2018-03-07T19:31:51.060",
"name": "<NAME>",
"executionDateLabel": "Date of death",
"allowGenerateNextVisit": Fa... | |
#!/usr/bin/env
"""
Read in two extracted light curves (interest band and reference band), split
into segments, compute the power spectra per band and cross spectrum of each
segment, averages cross spectrum of all the segments, and computes frequency
lags between the two bands.
Example call:
python simple_cross_spectra... | |
<reponame>CUAHSI/qa-automation-engine<gh_stars>1-10
""" Runs various smoke tests for the data.cuahsi.org """
from hc_macros import (
Search,
Marker,
Services,
Keywords,
Advanced,
Filter,
About,
QuickStart,
Zendesk,
Workspace,
ResourceCreator,
)
from hc_elements import ZendeskArticlePage
from cuahsi_base.uti... | |
<gh_stars>1-10
# coding=utf-8
# Copyright 2019 The Open AI Team Authors and The HuggingFace Inc. 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/LICEN... | |
settings are in default_hparams() function in mask_rcnn_params.py.
labels: The input labels in a dictionary. The labels include groundtruth
masks, boxes and classes.
class_targets: A tensor with a shape of [batch_size, batch_size_per_im,
num_classes] representing the classification target of each object.
box_targe... | |
with density sensor."""
xknx = XKNX()
sensor = Sensor(
xknx, "TestSensor", group_address_state="1/2/3", value_type="density"
)
sensor.sensor_value.payload = DPTArray(
(
0x44,
0xA5,
0xCB,
0x27,
)
)
self.assertEqual(sensor.resolve_state(), 1326.3485107421875)
self.assertEqual(sensor.unit_of_measurement(), ... | |
from django.db import transaction
from django.db.models import Q
from rest_framework import exceptions
from rest_framework.serializers import (
CharField,
DateField,
FloatField,
IntegerField,
ListField,
PrimaryKeyRelatedField,
)
from ..core import serializers
from . import models, validators
from .jexl import Qu... | |
shape[axis] = mult.shape[axis]
mult = mult.reshape(shape)
return (digits * mult).sum(axis=axis, keepdims=keepdims)
def numbers_to_digits(numbers, n_digits, base=10):
""" Convert number to array of digits, assumed little-endian. """
numbers = numbers.copy()
digits = []
for i in range(n_digits):
digits.append(nu... | |
"""
Removes a template.
Returns:
dict:
"""
return self._router_request(
self._make_request_data(
'deleteTemplate',
dict(uid=self.uid),
)
)
def get_data_sources(self):
"""
Gets data sources configured for a template.
Returns:
list(ZenossDataSource):
"""
ds_data = self._router_request(
self._make_req... | |
# don't want to modify the original (there's a big
# chance that we break it).
# Copy it every time, because the source file might
# have changed since last time we ran.
assert file.filename.exists(), "File doesn't exist: %s" % file.filename
tmpfile = Filename.temporary('', "p3d_" + file.filename.getBasename())
... | |
list of locales for available DisplayText translations
that can be performed using this form.
return: (osid.locale.LocaleList) - a list of available locales
or an empty list if no translation operations are
available
compliance: mandatory - This method must be implemented.
"""
raise Unimplemented()
def set_l... | |
<reponame>xuuuuuuchen/PASTA
import tensorflow as tf
def Combining_Affine_Para(tensors):
imgs = tensors[0]
array = tensors[1]
n_batch = tf.shape(imgs)[0]
tx = tf.squeeze(tf.slice(array, [0,0], [n_batch, 1]), 1)
ty = tf.squeeze(tf.slice(array, [0,1], [n_batch, 1]), 1)
sin0 = tf.squeeze(tf.slice(array, [0,2... | |
#!/bin/env python3
"""Main executable for running puppetmaster."""
import bisect
import json
import os
import random
import statistics
from argparse import ArgumentParser, Namespace
from multiprocessing import Pool
from pathlib import PurePath
from typing import Dict, List, Sequence, Set
try:
import matplotlib.pyplot... | |
import moderngl
from .p4dyna.equation import Equation
from numpy.random import random
class ParticleSystem:
def __init__(self, game, brender, fname, target, miss, move_data):
self.game = game
self.brender = brender # meh
self.N = 500000
self.particles = 0
self.fname = fname
self.target = target
self.miss = mi... | |
# coding: utf-8
#
# Copyright 2017 The Oppia 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | |
<gh_stars>100-1000
import numpy as np
import torch.nn as nn
from mmcv.cnn import normal_init
from ..registry import HEADS
from ..utils import ConvModule, bias_init_with_prob
from .anchor_head import AnchorHead
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..losses import sigmoid_focal_loss,... | |
from __future__ import division
import logging
try:
from Queue import Empty
except:
from queue import Empty
from redis import StrictRedis
from time import time, sleep
from threading import Thread
from collections import defaultdict
# @modified 20190522 - Task #3034: Reduce multiprocessing Manager list usage
# Use Red... | |
ticket_dependences=ticket_dependences_code_list)
if form.is_valid():
main_ticket = form.cleaned_data['ticket']
note = form.cleaned_data['note']
if Ticket2Ticket.main_is_already_used(main_ticket):
messages.add_message(request, messages.ERROR,
_("La dipendenza non può essere aggiunta. "
"La richiesta <b>{}</b> è d... | |
#!/usr/bin/env python3
""" Helper functions and classes for GUI controls """
import logging
import re
import tkinter as tk
from tkinter import ttk
from itertools import zip_longest
from functools import partial
from .tooltip import Tooltip
from .utils import ContextMenu, FileHandler, get_config, get_images
logger = ... | |
<gh_stars>0
#!/usr/bin/env python3
# Copyright (c) 2022 <NAME>. All rights reserved
# coding=utf-8
# -*- coding: utf8 -*
# reference [1]: https://zhuanlan.zhihu.com/p/22252270
# reference [2]: https://zh.d2l.ai/chapter_optimization/adadelta.html
import copy
import numpy as np
try:
from OptimizerClass import Iterat... | |
import sys
import logging
import time
import argparse
import os
import shutil
import tarfile
import subprocess
sys.path.append(".")
try:
from . import util
from . import configuration
except:
import util
import configuration
def process_hl7_shell_commands(my_config, target_file):
process_shell_commands(my_conf... | |
from logging import PlaceHolder
from sqlite3 import Cursor
import streamlit as st
from hydralit import HydraHeadApp
from db import db_conn as oracle_db
import streamlit as st
import pandas as pd
import numpy as np
import datetime
import altair as alt
import pydeck as pdk
from PIL import Image
import matplotlib.pyplot a... | |
import re
import xml.etree.ElementTree as ET
from os import path
from collections import Counter
import argparse
import csv
import json
import os
import random
# package local imports
import sys
import uuid
import matplotlib.pyplot as plt
import math
from dateutil.parser import parse
from tdigest import TDigest
impo... | |
well_id_to_cell_map_48 = {
1: {
'col_and_row': u'A1',
'row': 1,
'col': 1,
'well_id': 1,
},
2: {
'col_and_row': u'A2',
'row': 1,
'col': 2,
'well_id': 2,
},
3: {
'col_and_row': u'A3',
'row': 1,
'col': 3,
'well_id': 3,
},
4: {
'col_and_row': u'A4',
'row': 1,
'col': 4,
'well_id': 4,
},
5: {
'... | |
"""
Contains the abstraction for a commit in GitLab.
"""
from typing import Optional
from typing import Set
from typing import Union
from urllib.parse import quote_plus
from IGitt import ElementDoesntExistError
from IGitt.GitHub.GitHubCommit import get_diff_index
from IGitt.GitLab import GitLabMixin
from IGitt.GitLab ... | |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version 3.10.1-0-g8feb16b3)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################... | |
#!/usr/bin/env python
# Functions:
# parse_phenotypes
# parse_groups
# parse_ignore_samples
#
# ignore_samples
# calc_association
# center_scores
#
# write_prism_file
# plot_boxplot
# plot_waterfall
def parse_phenotypes(phenotypes):
# list of phenotypes.
# e.g. ["STEM", "EMT"]
# Return (potentially empty) list of... | |
<gh_stars>0
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# no... | |
helix: int
"""index of the :any:`Helix` on which this :any:`Domain` resides."""
forward: bool
"""Whether the strand "points" forward (i.e., its 3' end has a larger offset than its 5' end).
If :any:`Domain.forward` is ``True``, then
:any:`Domain.start` is the 5' end of the :any:`Domain` and
:any:`Domain.end` is... | |
drug scores.
@param method str: normalize by the average or max within the vectors
@return Returns None
"""
# dimensions include drugs or features (e.g. "proteins")
# methods are average ('avg') or max ('max')
dvs = {} # drug vectors
cc = 0
if dimension == 'drugs':
for vec in self.values:
for vi in range(len(... | |
<reponame>cmc333333/parsons
import logging
import re
from parsons.etl import Table
from parsons.utilities import check_env
from parsons.utilities.api_connector import APIConnector
logger = logging.getLogger(__name__)
class Mailchimp():
"""
Instantiate Mailchimp Class
`Args:`
api_key:
The Mailchimp-provided app... | |
the URL to check it is indeed on the domain
- Issue the URL to check effective roles on project1 - this
should return 3 roles.
"""
role_list = []
for _ in range(4):
role = unit.new_role_ref()
PROVIDERS.role_api.create_role(role['id'], role)
role_list.append(role)
domain = unit.new_domain_ref()
PROVIDERS.res... | |
f.write(bygene_lorad_conf_contents)
f.close()
bygene_gss_conf_template = open('conf-bygene-gss-template.txt','r').read()
bygene_gss_conf_filename = os.path.join(bygene_gss_dir,'lorad-gss.conf')
bygene_gss_conf_contents = re.sub('__FIRST_SITE_COI__', '1', bygene_gss_conf_template, re.M | re.S)
bygene_gss_conf_cont... | |
"out_right_tag_with-conflict_with-rerun"
target.TaggedOutputLocalTarget._already_changed = False
# Wait for the beginning of the next second
pause.until(int(time.time()) + 1.01)
# The t1 task has no conflict
# Note that we have to specify the prefix in the target to avoid conflict. If we do not,
# the default p... | |
<filename>pirates/economy/SimpleStoreGUI.py
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.gui.DirectGui import *
from pandac.PandaModules import *
from pirates.ai import HolidayGlobals
from pirates.battle import WeaponGlobals
from pirates.economy import EconomyGlobals
from pirates.economy.... | |
new input parameter vector for the predator prey and grass model. Population max 5000, Energy gains max 200, reproduction chance max 0.25
def generate_parameter_vector(lim):
new = [0]*len(lim)
for i in range(len(lim)):
if type(lim[i][0])==int:
new[i] = str(int(random.uniform(lim[i][0],lim[i][1])))
else:
new[i] = ... | |
<filename>panoptic_benchmark/structures/segmentation_mask.py
import cv2
import copy
import torch
import numpy as np
from panoptic_benchmark.layers.misc import interpolate
import pycocotools.mask as mask_utils
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
""" ABSTRACT
Segmentations come in either:
1) Binary ma... | |
<filename>BesselHelmert.py
###################
# A "plugin like" implementation of the Bessel Helmert tab for trui
# simlk, March 2013
###################
# Copyright (c) 2013, National Geodata Agency, Denmark
# (Geodatastyrelsen), <EMAIL>
#
# Permission to use, copy, modify, and/or distribute this software for any
# p... | |
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__clas... | |
self.device1 = Mock(**self.empty_output)
ipv6_vrf_all_interface_obj = ShowIpv6VrfAllInterface(device=self.device1)
with self.assertRaises(SchemaEmptyParserError):
parsed_output = ipv6_vrf_all_interface_obj.parse()
def test_golden(self):
self.device = Mock(**self.golden_output)
ipv6_vrf_all_interface_obj = ShowIp... | |
xlabelname=None,
format='png'):
"""Plotting decoding of the response with respect to dose.
Params
------
df : `DataFrame`
Table with columns=[perturbation_key, contvar_key, response_name].
The last column is always "response".
contvar_key : str
Name of the column in df for values to use for x axis.
perturba... | |
True to negate the shifted points.
Returns
-------
ndata : ndarray
Array of shifted NMR data.
"""
return roll(data, pts, neg)
def roll(data, pts=0.0, neg=False):
"""
Roll axis
Parameters
----------
data : ndarray
Array of NMR data.
pts : int
Number of points to shift. Positive value will right shift ... | |
<gh_stars>10-100
'''
Jabber Protocol.
'''
from common import pref, netcall
from digsby.loadbalance import DigsbyLoadBalanceManager
from hashlib import sha256
from jabber.JabberProtocol import JabberProtocol
from jabber.threadstream import ThreadStream
from logging import getLogger
from peak.util.imports import lazyMod... | |
<reponame>JetBrains-Research/pubtrends
import logging
import numpy as np
import pandas as pd
from networkx.readwrite import json_graph
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.preprocessing import StandardScaler
from pysrc.papers.analysis.citations import find_top_cited_pap... | |
#!/usr/bin/env python
"""The classes in this module aid the specification of tally `units` in
:py:class:`pyne.simplesim.cards.ICellSurfTally` (see examples below). The class
focuses on the ability to specify cells and surfaces that are nested within
universes or other cells in nearly arbitrarily complex ways. Apart fr... | |
genes for the junctions that aren't in our
# database. We can associate each start and end with a gene and use this.
start_gene = dict(zip(extDF['chrom:start'], extDF.gene))
end_gene = dict(zip(extDF['chrom:end'], extDF.gene))
genes = []
for ind in annotDF[annotDF.ext_annotated == False].index:
cur_start = anno... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.