input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<reponame>mpopatia/rovewithme<filename>startup/views.py
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.utils.html import escape, strip_tags
from django.views.decorators.csrf import csrf_exempt
from django.core.urlresolvers import reverse
from django.contrib.au... | |
<gh_stars>0
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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 requ... | |
= \
row[FeatureCounts.splice_out_all_colname] / mean_profile_3p
ratio_5p_spliced_in_border = \
row[FeatureCounts.splice_in_borders_colname] / mean_profile_5p
ratio_3p_spliced_out_border = \
row[FeatureCounts.splice_out_borders_colname] / mean_profile_3p
ratio_5p_unspliced = \
row[FeatureCounts.unspliced_5pSS_... | |
<gh_stars>1000+
# 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... | |
<reponame>Soton-Song/valentine
import operator
import time
from collections import defaultdict
from enum import Enum
import numpy as np
from datasketch import MinHash, MinHashLSH
from nltk.corpus import stopwords
import algorithms.sem_prop.ontomatch.matcher_lib_utils as utils
from algorithms.sem_prop.dataanalysis imp... | |
a tuple of the distance and por - a dictionary keyed by edge
"""
# help cython static type
#
similarity: cython.double = 0.0
distance: cython.double = 0.0
max_dist: cython.double = 0.0
por: dict = {}
edge_key: EdgeKeyType
edges_to_process: Set[EdgeKeyType]
# filter edge_keys as required
#
edges_to_process... | |
get_policy_version(self, policy_name, version_id):
policy = self.get_policy(policy_name)
if not policy:
raise ResourceNotFoundException()
for version in policy.versions:
if version.version_id == version_id:
return version
raise ResourceNotFoundException()
def list_policy_versions(self, policy_name):
policy = ... | |
has_select_all(self, max_len: Optional[int] = None):
if max_len is None or max_len > len(self.children):
max_len = len(self.children)
for i in range(max_len):
if isinstance(self.children[i], SelectItemAllColumns):
return True
return False
def is_valid_group_by_index(self, index: int):
return (0 < index <= len(... | |
import sys
import numpy as np
from .orcadaq import OrcaDecoder, get_ccc
class ORCAStruck3302(OrcaDecoder):
"""
ORCA decoder for Struck 3302 digitizer data
"""
def __init__(self, *args, **kwargs):
self.decoder_name = 'ORSIS3302DecoderForEnergy'
self.orca_class_name = 'ORSIS3302Model'
self.decoded_values_templ... | |
<reponame>maxtaylordavies/BigGAN-PyTorch<filename>datasets.py
''' Datasets
This file contains definitions for our CIFAR, ImageFolder, and HDF5 datasets
'''
import os
import os.path
import sys
from PIL import Image
import numpy as np
from tqdm import tqdm, trange
import h5py as h5
import torch
import torchvi... | |
modify summary with #cont keyword
summary = ' '.join(tags_list) + ":" + title
# Call new function
# NOTE: Weird syntax in new_command requires passing a list
return new_command([summary])
cont_command.parser = subparsers.add_parser(
'cont',
description="Same as lifelogger new, but copies summary from previous ... | |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 8 14:27:24 2018
@author: Meagatron
"""
#Matrix Profile Version 1.4.0
#A Python implementation of the matrix profile algorithm described in <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2016): 'Matrix Profile I: All Pairs Similarity Joi... | |
mask_val=np.nan,
edge_blend=None, interp_zeros=False):
""" Rotates an cube (3d array or image sequence) providing a vector or
corresponding angles. Serves for rotating an ADI sequence to a common north
given a vector with the corresponding parallactic angles for each frame. By
default bicubic interpolation is used... | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 18 14:34:01 2018
@author: <NAME>
"""
import numpy as np
import itertools
import scipy.stats
from sklearn.utils.validation import check_random_state
class AbstractHyper(object):
""" abstract class representing an hyperparameter (or a set of hyperpara... | |
value for the enrichment property.
:type value: str
:param endpoint_names: Required. The list of endpoints for which the enrichment is applied to
the message.
:type endpoint_names: list[str]
"""
_validation = {
'key': {'required': True},
'value': {'required': True},
'endpoint_names': {'required': True, 'min_i... | |
# Copyright 2016 Cisco Systems.
# 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 by applicable law or ... | |
# coding: utf-8
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | |
1000,
i_max_out: Optional[int] = 1000,
i_max_ring: Optional[int] = 500,
additional_metrics: Optional[Tuple[list, float]] = None,
population_metrics: Optional[list] = None,
size_in_MW: Optional[bool] = False,
branching_propensity: Optional[float] = None,
metrics_weights: Optional[Tuple[list, nparray]] = None,
ve... | |
fixed length experiments but
are inapplicable to long-running services except in the offline
scenario
- [ ] Using knowledge of the LoadGen implementation to predict upcoming
lulls or spikes in the server scenario
- [ ] Treating beams in a beam search differently. For example,
employing different precision for different... | |
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | |
"""
This script serves to do recurrence analysis on the sv-gene pairs identified
We do the following things:
1. From the top 100 of each SV type (so top 400), which genes are there? Which are the top 15 most recurrent?
2. For these genes, also check which other mutations are found in these genes in different... | |
<reponame>clovaai/StatAssist-GradBoost<filename>frostnet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD
from timm.models.registry import register_model
def _cfg(url=''):
return {
... | |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# -*- coding: UTF-8 -*-
import unittest
import os
import numpy as np
import gc
import onnxruntime as onnxrt
import threading
import sys
from helper import get_name
from onnxruntime.capi.onnxruntime_pybind11_state import Fail... | |
#!/usr/bin/python
import os, glob, hashlib, pickle, argparse, shutil, ntpath
import os, glob, hashlib, pickle, argparse, shutil, multiprocessing, signal, sys
from multiprocessing import Pool
from functools import partial
######################### Classes ##############################
class AndroidDensity:
def __init... | |
cases.
This function converts these IOB tags to the easier-to-consume IOB2 format;
see
https://en.wikipedia.org/wiki/Inside%E2%80%93outside%E2%80%93beginning_(tagging)
for details. Basically, every entity in IOB2 format begins with a `B` tag.
The `I` tag is only used for the second, third, etc. tokens of an entit... | |
# SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2015, ARM Limited and contributors.
#
# 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
#
# ... | |
<reponame>DailyDreaming/toil-rnaseq
from __future__ import print_function
import errno
import os
import textwrap
from collections import OrderedDict, defaultdict
from urlparse import urlparse
from toil_rnaseq.utils.expando import Expando
schemes = ('file', 'http', 's3', 'ftp', 'gdc')
_iter_types = (list, tuple, set,... | |
#!/usr/bin/env python
#
# module_tests.py: testing modules / external sources.
#
# Subversion is a tool for revision control.
# See http://subversion.apache.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# o... | |
<reponame>microsoftgraph/msgraph-cli-archived<filename>msgraph/cli/command_modules/identitydirmgt/azext_identitydirmgt/generated/action.py
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See Licens... | |
# ex:set ts=4 sw=4: <- for vim
#
# EPANET Output File Tool Internal Plugin which reads EPANET 2.00.12 Output File
#
import EPANETOutputFilePlugin
import struct
import gettext
class InternalPlugin(EPANETOutputFilePlugin.EOFTPlugin):
def __init__(self):
# TODO initialise translations?
# since this is an internal plu... | |
unzip
run_shell_cmd("gunzip {}.gz".format(out_results[subsample_bed_key]))
# -----------------------------------------
# ANALYSIS 4 - plot this out
# inputs: stable groups
# outputs: heatmaps with histone marks
# -----------------------------------------
logger.info("ANALYSIS: plot out the heatmaps with the or... | |
i in range(len(U) - 1):
area += (U[i + 1][0] - U[i][0]) * (U[i + 1][1] + U[i][1])
part = area * 1.0 / G
cuts = []
iL = 0
iU = 0
w = U[0][1] - L[0][1]
a = 0
return cuts
def func_845fd3d315d84ec1a089aba57a7df9de(U, G, L):
for i in range(len(U) - 1):
area += (U[i + 1][0] - U[i][0]) * (U[i + 1][1] + U[i][1])
p... | |
= type_view_form_data(action="copy",
type_type_id="testtype",
type_entity_id="copytype"
)
u = entitydata_edit_url(
"copy", "testcoll", "testtype", entity_id="entity1", view_id="Type_view"
)
r = self.client.post(u, f)
self.assertEqual(r.status_code, 401)
self.assertEqual(r.reason_phrase, "Unauthorized")
retu... | |
depressivo grave sem sintomas psicóticos'),
('F32.3', 'Episódio depressivo grave com sintomas psicóticos'),
('F32.8', 'Outros episódios depressivos'),
('F32.9', 'Episódio depressivo não especificado'),
('F33.0', 'Transtorno depressivo recorrente, episódio atual leve'),
('F33.1', 'Transtorno depressivo recorrente, ... | |
self.shifted_pdb_info:
self.shifted_pdb_info.show_summary(out=out)
if self.shifted_ncs_info:
self.shifted_ncs_info.show_summary(out=out)
if self.output_ncs_au_pdb_info:
print("\nOutput PDB file with dummy atoms representing the NCS AU:", file=out)
self.output_ncs_au_pdb_info.show_summary(out=out)
if self.outpu... | |
Array index 25
aver_dark_B4,
vari_dark_B4, -- Array index 27
bias
FROM image_t
WHERE state >= :state
AND type = :type
AND session = :session
AND night = :night
ORDER BY tstamp ASC
''', row)
return cursor
# we are not using the image_v VIEW for the time being
# We display the RAW data without dark and bias ... | |
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from decimal import Decimal
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.test import TestCase
from projects.models import Project
... | |
x_axis_type(self, value: int):
"""
:param int value:
"""
self.axis_system.XAxisType = value
@property
def y_axis_direction(self) -> Reference:
"""
.. note::
:class: toggle
CAA V5 Visual Basic Help (2020-07-06 14:02:20.222384)
| o Property YAxisDirection() As Reference
|
| Reads or sets the geometric po... | |
if len(sea_dev.additional_veas) > 0:
for vea in sea_dev.additional_veas:
if vea.pvid == port_vlan_id:
return sea_dev
return
def _add_vlan_to_existing_vea(self, host, vios, vlan_id, vea_dev, sea_dev):
"""
Add a VLAN id to an existing VeaDevice object.
:param host: The Host DOM object that IVM runs on
:param v... | |
<filename>tests/fairseq_layers.py
"""
Copyright 2021 The LightSeq Team
Copyright Facebook Fairseq
We use layers from Facebook Fairseq as our baseline for unit test
"""
from typing import Dict, List, Optional, Callable
import math
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional ... | |
#%%
import os
import xml
import heapq
import warnings
import numpy as np
import pandas as pd
from tqdm import tqdm
from shapely import wkt
import geopandas as gpd
from xml.dom import minidom
from collections import deque
import matplotlib.pyplot as plt
from haversine import haversine, Unit
from shapely.geometry import ... | |
'T':7, 'F':11, 'H':10, 'K':9,
'D':8, 'C':6, 'R':11, 'P':7, 'Q':9, 'N':8, 'W':14, '-':0}
parse = GPCRDBParsingPDB()
ref_length = 0
conserved_count = 0
non_cons_count = 0
trimmed_res_num = 0
switched_count = 0
non_cons_res_templates, conserved_residues = OrderedDict(), OrderedDict()
trimmed_residues = []
incons... | |
input = """mask = 01111X0011X11110XX11X110111001X00001
mem[26252] = 2785
mem[5529] = 156
mem[43194] = 29224
mem[64799] = 11208
mem[1727] = 138064713
mem[51786] = 67480
mask = 00010000011011101X0000X001X01001X0X0
mem[8820] = 143936540
mem[33783] = 33161
mem[60979] = 17936311
mem[19136] = 48558314
mem[55023] = 718791450
... | |
cubic polynomial cannot compute
result_vector=None
segment_1_recalculate = True
realroots=[]
#Check for zero values in segment 1
for i in realroots:
if 0 < i < tList[2]: segment_1_recalculate=True #If a zero occurs in this segment, we need to split it into two segments, 1.1 and 1.2
if segment_1_recalc... | |
None:
unit = self.na_helper.safe_get(self.parameters, ['san_application_template', 'total_size_unit'])
if unit is None:
unit = self.parameters['size_unit']
self.parameters['san_application_template']['total_size'] *= netapp_utils.POW2_BYTE_MAP[unit]
self.debug = dict()
# self.debug['got'] = 'empty' # uncomment t... | |
<reponame>jeffg2k/avclass
import logging
import operator
import re
import string
import sys
from avclass import util
from collections import defaultdict, namedtuple
from typing import AnyStr, Callable, Collection, Dict, List, Optional, Set, Tuple, Union
logger = logging.getLogger(__name__)
# Prefix to identify plat... | |
"""
Routes and views for the flask application.
"""
from datetime import datetime, timedelta, date
from dateutil import parser
from flask import Flask, render_template, redirect, url_for, flash, request, jsonify
from flask_cors import CORS
import requests
import json
import uuid
import pandas as pd
from timer import T... | |
# Import libraries
import pandas as pd
import numpy as np
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from joblib import load
# Import application
from app import app
model = load('assets/final_m... | |
import argparse
import numpy as np
import os
import pprint
import yaml
# HACK: Get logger to print to stdout
import sys
sys.ps1 = '>>> ' # Make it "interactive"
import tensorflow as tf
from multiprocessing import Queue
from lib.config import cfg_from_file, cfg_from_list, cfg
from lib.data_process import make_data_pr... | |
represented as a class variable - with a specific
YANG type.
YANG Description: List of Rendered Service Paths (RSP).
"""
__slots__ = ('_path_helper', '_extmethods', '__id','__name','__nsd_connection_point_ref',)
_yang_name = 'rsp'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self... | |
import argparse
import sys
import os
import ggutils.s3_access as s3_access
import smalltrain as st
try:
# For the case smalltrain is installed as Python library
print('try to load smalltrain modules from Python library')
from smalltrain.model.nn_model import NNModel
print('smalltrain modules are ready to be loa... | |
db_timestamp, db_size, db_flags) "
"VALUES(%s, %s, %s, %s, %s, %s)")
self.DbModify(query_string,
(client_host_name, db_name, db_pretty_name,
db_timestamp, db_size, db_flags))
# Record the db_id now, if it succeeded, and the following inserts fail,
# we can at least back some of the inserts out so we can try agai... | |
import json
import os
import random
from collections import defaultdict
from os import listdir, mkdir, makedirs
from os.path import abspath, basename, dirname, exists, isfile, join
from re import search, sub
from datetime import datetime
import click
import pandas as pd
from roboai_cli.util.cli import print_error, pr... | |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions o... | |
<reponame>alvinwatner/protein_folding
"""
=====================================================
Protein Folding 2D Hydrophobic-Polar Model Simulation
=====================================================
Protein Folding is well known optimization combinatorial problem, there are some models to adress the folding p... | |
<gh_stars>0
"""
THIS CODE IS AUTO-GENERATED. DO NOT EDIT.
GL ES 2.0 API based on the Angle library (i.e. DirectX)
"""
import ctypes
from .angle import _lib
_lib.glActiveTexture.argtypes = ctypes.c_uint,
# void = glActiveTexture(GLenum texture)
def glActiveTexture(texture):
_lib.glActiveTexture(texture)
_lib.gl... | |
import random
from tyckiting_client import messages
from tyckiting_client import actions
from collections import Counter
class BaseAi:
def __init__(self, team_id, config=None):
"""
Initializes the AI, storing the configuration values as fields
Args:
team_id: Team identifier as an integer, shouldn't be needed... | |
<reponame>BobDenny/alpyca-client
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# telescope - Implements ASCOM Alpaca Telescope device classes and enums
#
# Part of the Alpyca Client application interface package
#
# Author: <NAME> <<EMAIL>> (rbd)
# <NAME> <<EMAI... | |
import random
from math import sqrt
from enum import Enum, auto
import torch
from torch import nn
from torch.autograd import Function
from torch.nn import functional as F
from torch.nn import init
import constants
from logger import LOGGER
from inference.perspective import make_homography_kornia, warp_hom... | |
def wrapper(self, wrapper):
self._wrapper = wrapper
@property
def wrapped(self) -> "PayloadType":
return self._wrapped
@wrapped.setter
def wrapped(self, wrapped):
if isinstance(wrapped, PayloadType) or wrapped is None:
self._wrapped = wrapped
else:
self._wrapped_ = PayloadType(ptype=wrapped)
@property
de... | |
molecular entities when we click on the labels. It is
a list of objects and has None for characters such as spaces
"""
if not self.sequenceIndex.has_key(mol):
posy = None
else:
# delete all canvas items for that molecule
if not self.isVisible[mol]:
self.showSequence(mol)
self.canvas.delete(mol.molTag)
# comp... | |
from paddle.fluid.initializer import Constant
from paddle.fluid.param_attr import ParamAttr
import paddle.fluid as fluid
class Fdresnext():
def __init__(self):
pass
def net(self, x2paddle_input):
x2paddle_fdresnext_fc_bias = fluid.layers.create_parameter(dtype='float32', shape=[121],
name='x2paddle_fdresnext_fc_... | |
********** PROBLEM SOLVING ****************
U.P.E.R.
1. UNDERSTAND:
Before doing anything else, make sure you understand precisely what the problem is asking. A helpful starting point could be transcribing the technical description of the problem into your own words.
Questions
Here is a list of starter questions tha... | |
will paginate through responses from :py:meth:`LexModelBuildingService.Client.get_bots`.
See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBots>`_
**Request Syntax**
::
response_iterator = paginator.paginate(
nameContains='string',
PaginationConfig={
'MaxItems':... | |
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
from torch.utils.data import TensorDataset, DataLoader
from torch import optim
import numpy as np
from copy import deepcopy
import pdb
class Learner(nn.Module):
"""
"""
def __init__(self, config):
"""
:param config... | |
<reponame>dhyon/go-spacemesh
import base64
from datetime import datetime
import pytest
from pytest_testconfig import config as testconfig
import re
import random
from random import choice
from string import ascii_lowercase
import time
# noinspection PyUnresolvedReferences
import tests.config as cnf
from tests.context ... | |
= self.get_id(tableDesc)
if not tableId:
#try to find the table from the first node
#table not found, create it
tableId = self.create_node_from_path(tableDesc,properties={"type":"table"})
if tableId:
columnsId = self.create_node(parent=tableId, name="columns", properties={"type": "referencer"})
variablesId = se... | |
self.get_dataset_LL(
mod_params,
self.obs[ii],
cur_pred,
self.eval_mask[ii],
CL_offset)
dataset_avg_nLLs.append(cur_nLL)
hp_offset += LFC_mats[ii].shape[0]
CL_offset += LFC_mats[ii].shape[1]
self.avg_effect_loss = tf.add_n(dataset_avg_nLLs)
#calc R2
self.R2 = 1 - self.nLL / tot_SS
#calc regularization pe... | |
<filename>RPSNetwork.py<gh_stars>0
"""
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, ... | |
def objective_hyperopt(space):
"""
Objective function, taking set of hyperparameters and returning mean validation accuracy of k-fold cross-validation.
"""
xgb_ordinal_hyperopt = xgb.XGBRegressor(**space, objective="reg:squarederror", verbosity=0, nthread=-1, seed=1)
xgb_ordinal_hyperopt.fit(trainX_ordinal, tr... | |
self._table = {'data': None}
# build list of currently added Species.
self._species = None
self._species_list = ReturnTable.objects.filter(ret=a_return)
# self._species_list.append(_species.name)
# if (_species.has_rows()):
# self._species_saved.append(_species.name)
# self._species = _species.name
self.get_spe... | |
in the entire bot",
cog_name="developer"
)
@is_developer()
async def disable_command(self, ctx, cmds: Greedy[CommandConverter]=None):
"""Allows a developer to disable a command in the whole bot
:param ctx: The context of where the message was sent
:param cmd: The command to disable
"""
# Check if there is no... | |
try:
from urllib.parse import quote_plus
except ImportError:
from urllib import quote_plus
import processout
import json
from processout.networking.request import Request
from processout.networking.response import Response
# The content of this file was automatically generated
class Card(object):
def __init__(s... | |
<filename>micropsi_core/tests/test_node_netapi.py<gh_stars>100-1000
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
Tests for netapi, i.e. the interface native modules will be developed against
"""
import pytest
from micropsi_core import runtime as micropsi
def prepare(fixed_nodenet):
nodenet = micropsi.get_no... | |
logger.info('finised reading clusters from %s', h5_path)
return result_clusters, result_annotations
def delete_clusters(h5_path, label=DEFAULT_ALGO_NAME):
"""
delete the clustering results with the given label from the h5 file.
:param str h5_path: h5_path to the h5 file
:param str label: the name/label for of t... | |
+ ' ]\n'
tag_str += indent_str + ']'
else:
tag_str += ' ]'
return tag_str
def __getitem__(self, attr_index):
'''
Returns the masked, unshifted value of the flag defined
by the descriptor: self[DESC][attr_index].
If attr_index is a string, uses self.desc['NAME_MAP'].get(attr_index)
as attr_index.
Being un... | |
<filename>zipline/pipeline/mixins.py
"""
Mixins classes for use with Filters and Factors.
"""
from textwrap import dedent
from numpy import (
array,
full,
recarray,
vstack,
)
from pandas import NaT as pd_NaT
from zipline.errors import (
WindowLengthNotPositive,
UnsupportedDataType,
NoFurtherDataError,
)
from z... | |
# -*- coding: utf-8 -*-
'''
The MIT License
Copyright (c) 2009 Marici, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, co... | |
# modules_torch.py
import os, sys, pickle, time, shutil, logging, copy
import math, numpy, scipy
numpy.random.seed(545)
import torch
torch.manual_seed(545)
from modules import make_logger
'''
This file contains handy modules of using PyTorch
'''
########################
# PyTorch-based Layers #
####################... | |
{} is not 3.".format(
ads[0].serial))
return False
call_conf_id = None
for call_id in calls:
if call_id != call_ab_id and call_id != call_ac_id:
call_conf_id = call_id
if not call_conf_id:
self.log.error("Merge call fail, no new conference call id.")
return False
if not verify_incall_state(self.log, [ads[0], ... | |
assert tnsnamesParser.ruleNames[ctx.getRuleIndex()] == self._tnsStack.pop
# Enter a parse tree produced by tnsnamesParser#ipc_params.
def enterIpc_params(self, ctx: tnsnamesParser.Ipc_paramsContext):
self._tnsStack.push(tnsnamesParser.ruleNames[ctx.getRuleIndex()])
# Exit a parse tree produced by tnsnamesParser#i... | |
import numpy as np
import pandas as pd
import time
# https://github.com/UNSW-CEEM/Bill_Calculator
# Prepared by <NAME> (<EMAIL>)
# You can learn how to use this function by running the Tariff Calculation Example notebook in this repository
# Inputs: Tariff and Load profile (30 min interval, one year,
# timestamps are... | |
<gh_stars>0
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import tensorflow_probability as tfp
import datetime
import os, sys
from argparse import ArgumentParser
# Debug module
# from tensorflow.python import debug as tf_debug
import numpy as np
import warn... | |
# -*- coding: utf-8 -*-
"""Veil https api client."""
import asyncio
import json
import logging
from types import TracebackType
from typing import Dict, Optional, Type
from urllib.parse import urlencode
from uuid import UUID, uuid4
try:
import ujson
except ImportError: # pragma: no cover
ujson = None
try:
import ai... | |
<reponame>axis-edge/pulumi-kubernetes
# coding=utf-8
# *** WARNING: this file was generated by pulumigen. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ..... | |
# -*- coding: utf-8 -*-
# Copyright 2013, <NAME>
#
# 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 agree... | |
"""
Copyright 2016 Google Inc. 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 by applicable law or agreed to in wr... | |
"""
library functions for the CIJOE test runner, `cij_runner`.
"""
from __future__ import print_function
from subprocess import Popen, STDOUT
from xml.dom import minidom
import shutil
import copy
import time
import os
import yaml
import cij.test
import cij
HOOK_PATTERNS = {
"enter": [
"%s.sh",
"%s_enter.sh",
"%s_... | |
<filename>src/sqlfluff/parser/segments_base.py
"""Base segment definitions.
Here we define:
- BaseSegment. This is the root class for all segments, and is
designed to hold other subsegments.
- RawSegment. This is designed to be the root segment, without
any children, and the output of the lexer.
- UnparsableS... | |
spec.get("databook order")
full_name = spec["display name"]
if databook_order is None:
order = np.inf
else:
order = databook_order
pages[databook_page].append((spec.name, order))
data.tdve[spec.name] = TimeDependentValuesEntry(full_name, data.tvec, allowed_units=[framework.get_databook_units(full_name)], commen... | |
tensor and length the same as
number of classes.
from_logits (bool): whether the output tensor is normalized as a probability (total equal to 1)
ignore_index (int or list of int):
cutoff (None or decimal): the cutoff point of probability for classification, should be None of a number
less than 1..
is_target_oneho... | |
import argparse
import math
import random
import os
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from tqdm import tqdm
import torchvision.da... | |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | |
== 'outbound':
self.partner_type = 'supplier'
elif self.payment_type not in ('inbound', 'outbound'):
self.partner_type = False
# Set payment method domain
res = self._onchange_journal()
if not res.get('domain', {}):
res['domain'] = {}
jrnl_filters = self._compute_journal_domain_and_types()
journal_types = jrnl... | |
<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import sys
sys.path.insert(0, '..')
from algorithms.dbscan_gmm import DBSCAN_GMM
from algorithms.grid_based_dbscan import GridBasedDBSCAN
from algorithms.grid_based_dbscan_gmm import GridBasedDBSCAN_GMM
from utilities.plot_utils import ... | |
the operator is spin conserving. The result will
be accumulated to self
Args:
coeff (complex): scalar coefficient to be multiplied to the result
idata (FqeData): input FqeData to which the operators are applied
daga (List[int]): indices corresponding to the alpha creation \
operators in the Hamiltonian
undag... | |
running cannot both be true', owner='nbaker')
FACTORY_TUNABLES = {'description':'\n A test that verifies if any of the users of the selected participant are\n running a specific interaction.\n ',
'participant':TunableEnumEntry(description='\n The participant of the interaction used to fetch the users against\n whic... | |
cenrace11cats * votingage", "detailed")
geos_qs_props_dict[CC.QUERIESPROP][level] = (Fr(1,1024),Fr(1,1024),Fr(1,1024),Fr(1,1024),
Fr(1,1024),Fr(1,1024),Fr(1018,1024))
return geos_qs_props_dict
class Strategy2b_ST_CTY_B_isoTot_Ordering:
@staticmethod
def make(levels):
# levels = USGeolevelsNoTractGroup.getLevel... | |
"""
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 numpy as np
import torch
def to_tensor(data):
"""
Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginar... | |
<filename>sedenoss/sedenoss/models.py
from torchtools.optim import Ranger
from torchtools.nn import Mish
import pytorch_lightning as pl
from sedenoss.utils import *
from sedenoss.loss import SI_SDR_Loss
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
EPS = 1e-8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.