input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 <NAME>
# Use of this source code is governed by the MIT License
###############################################################################
from . im... | |
root of unity, use the cyclotomic algorithm
algorithm = 'cyclotomic'
break
else:
num = prod(one - q**i for i in range(n-k+1, n+1))
try:
try:
return num // denom
except TypeError:
return num / denom
except (TypeError, ZeroDivisionError):
# use substitution instead
return q_binomial(n, k)(q)
if algorithm == ... | |
<reponame>ecosoft-odoo/mh-doodba
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under... | |
not None:
oprot.writeFieldBegin('responseSize', TType.I64, 4)
oprot.writeI64(self.responseSize)
oprot.writeFieldEnd()
if self.clientAddress is not None:
oprot.writeFieldBegin('clientAddress', TType.STRING, 5)
oprot.writeString(self.clientAddress.encode('utf-8') if sys.version_info[0] == 2 else self.clientAddress)... | |
<gh_stars>0
"""
PySC2_A3C_AtariNetNew.py
A script for training and running an A3C agent on the PySC2 environment, with reference to DeepMind's paper:
[1] Vinyals, Oriol, et al. "Starcraft II: A new challenge for reinforcement learning." arXiv preprint arXiv:1708.04782 (2017).
Advantage estimation uses generalized advan... | |
("Path to file containing set of stop terms, one term "
"per line."),
'required': True
}
}
def __init__(self, session, config, parent):
FileAssistedNormalizer.__init__(self, session, config, parent)
self.stoplist = {}
lines = self._processPath(session, 'stoplist')
for sw in lines:
self.stoplist[sw.strip()] =... | |
),
delete_after = 5
)
row = column = -1
valid = False
continue
# The direction is valid, set the offsets
if valid:
for offset in range(ship["length"]):
board.set_at(row_value(offset), column, ship["number"])
break
# The ship would exceed the vertical bounds
else:
row = column = -1
await ... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.6.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# hide
# skip
from fastai.text.all impor... | |
<reponame>SwellMai/Terminator-800
#!/usr/bin/env python
import rospy
import os
import message_filters
from sensor_msgs.msg import LaserScan
from nav_msgs.msg import Odometry
from geometry_msgs.msg import PoseStamped, Twist
import numpy as np
from tf.transformations import euler_from_quaternion
import math
class node(... | |
values(self, value):
"""
Setter for **self.values** attribute.
Parameters
----------
value : object
Attribute value.
"""
raise AttributeError('"{0}" attribute is read only!'.format('values'))
@property
def items(self):
"""
Property for **self.items** attribute. This is a convenient attribute
used to ite... | |
<reponame>kigero/rules_haxe<gh_stars>0
"""
Haxe utility functions.
"""
load(":providers.bzl", "HaxeLibraryInfo", "HaxeProjectInfo")
def determine_source_root(path):
"""
Determine the source root for a given path, based on whether the path is in the external directory.
Args:
path: The path to check.
Returns:
T... | |
# =============================================================================
# Copyright 2020 NVIDIA. All Rights Reserved.
# Copyright 2019 The Google Research 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 obt... | |
import datetime
import pytz
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from django.utils import timezone
from schedule.models import Calendar, Event, EventRelation, Rule
class TestEvent(TestCase):
def ... | |
result = df.fillna({"a": 0}, downcast="infer")
modin_df = pd.DataFrame(frame_data).fillna({"a": 0}, downcast="infer")
df_equals(modin_df, result)
def test_ffill2():
test_data = TestData()
test_data.tsframe["A"][:5] = np.nan
test_data.tsframe["A"][-5:] = np.nan
modin_df = pd.DataFrame(test_data.tsframe)
df_equa... | |
belong to the group, and their access rights. This value will be empty. It will be removed from the payload response in an upcoming release. To retrieve user information on an artifact, please consider using the Get Group User APIs, or the PostWorkspaceInfo API with the getArtifactUser parameter.
workbooks: str[]
Lis... | |
from django.db import models
from django.contrib.gis.db import models
from stdimage.models import StdImageField
from django.utils.text import slugify
from markdown import markdown
from django.utils.safestring import mark_safe
from django.conf import settings
import bleach
from unidecode import unidecode
from django.url... | |
<reponame>annapowellsmith/openpresc
from contextlib import contextmanager
import subprocess
import sys
import tempfile
import warnings
from google.cloud import bigquery as gcbq
from google.cloud.exceptions import Conflict, NotFound
from six import reraise
import pandas as pd
from django.conf import settings
from dja... | |
different lengths to confirm that attention masks are operational in XLA
sentences = [
"Translate English to German: Today is a beautiful day.",
"Translate English to German: I have four cats, three dogs, two birds, and a horse.",
]
input_ids = tokenizer(sentences, return_tensors="tf", padding=True).input_ids
xl... | |
860),
(408, 727), (803, 844), (640, 684), (1, 626), (505, 847), (341, 888), (249, 747), (333, 720), (64, 891),
(195, 939), (227, 581), (244, 822),
(145, 990), (556, 822), (93, 458), (82, 327), (520, 896), (501, 955), (111, 308), (298, 564), (127, 723),
(340, 560), (834, 944), (208, 553),
(818, 986), (560, 617), (2... | |
len(message_chain[Image]) != 0:
message += '[图片]'
flash_image = message_chain[FlashImage]
if len(flash_image) != 0:
message += '[闪照]'
# ===================================================================================
# ===================================================================================
# 基本信息... | |
<reponame>TobiasSchalau/privacy-evaluator
from privacy_evaluator.attacks.attack import Attack
from privacy_evaluator.classifiers.classifier import Classifier
import privacy_evaluator.utils.data_utils as data_utils
from privacy_evaluator.utils.trainer import trainer
from privacy_evaluator.models.tf.conv_net_meta_classif... | |
<reponame>Giuseppe5/NeMo
# Copyright (c) 2019 NVIDIA Corporation
# If you want to add your own data layer, you should put its name in
# __all__ so that it can be imported with 'from text_data_layers import *'
__all__ = ['TextDataLayer',
'BertSentenceClassificationDataLayer',
'BertJointIntentSlotDataLayer',
'BertJ... | |
<reponame>henrysky/gaia_tools
# Tools for cross-matching catalogs
import csv
import sys
import os
import os.path
import platform
import shutil
import subprocess
import tempfile
import warnings
WIN32= platform.system() == 'Windows'
import numpy
import astropy.coordinates as acoords
from astropy.table import Table
from ... | |
/ CTP': 'سبل المعيشة/برنامج التحويلات النقدية',
'Livelihood Manager': 'مدير سبل المعيشة',
'Livelihoods': 'سبل العيش',
'Load Cleaned Data into Database': 'تحميل البيانات الكاملة إلى قاعدة البيانات',
'loading': 'جار التحميل',
'Loading': 'جار التحميل',
'Local Acronym': 'اسم المختصر المحلي',
'Local Currency': 'العمل... | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange
from collections import namedtuple, OrderedDict
import tensorflow as tf
from tensorflow.python.training import moving_averages
_BATCH_NORM_DECAY = 0.9 #0.997
_BATCH_NORM_EPSILON = ... | |
<gh_stars>1-10
######################################################################
# <NAME>, mai 2019
#
# methodologie
#
# 1) on rassemble les fichiers netcdf des differentes eccc en un seul fichier netCDF.
#
# 2) on scan les fichiers sources annuels en cherchant une variable et on sauve
# ce qu'on trouve dans des f... | |
it again. Use cmd manually_correct_theme')
if item.theme_end != -1 and item.type == "episode":
if (not skip_done and item.correct_theme_start) or not item.correct_theme_start:
click.echo('Found theme_start at %s %s theme_end %s %s' % (item.theme_start,
item.theme_start_str, item.theme_end, item.theme_end_str))
... | |
<gh_stars>1-10
#!/usr/bin/env python
#
# Copyright 2016 - The Android Open Source Project
#
# 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
#
# Un... | |
"""Core classes and functions for GuideMaker."""
import os
import re
import yaml
import logging
import gzip
import hashlib
import statistics
import nmslib
import regex
import gc
from typing import List, Dict, TypeVar, Generator
from itertools import product
from Bio import SeqIO
from Bio.SeqUtils import GC
from pybedto... | |
<gh_stars>1-10
# coding=utf-8
# Copyright 2022 The Google Research 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 required ... | |
# coding: utf-8
# Little utilities we use internally
from abc import ABCMeta
import os
import signal
import sys
import pathlib
from functools import wraps, update_wrapper
import typing as t
import threading
import collections
from async_generator import isasyncgen
from ._deprecate import warn_deprecated
import tri... | |
<reponame>melinath/philo
#encoding: utf-8
import datetime
from hashlib import sha1
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.db.models.options import get_verbose_name as convert_camelcase
from django.utils import simplejson as json
fro... | |
)
return
if 67 - 67: I1IiiI
if 93 - 93: ooOoO0o . Ii1I + IiII / Oo0Ooo % I11i
if 40 - 40: Oo0Ooo % OoOoOO00 . IiII / I1IiiI % OoooooooOO
if 33 - 33: OOooOOo - OoooooooOO . iII111i
if 2 - 2: I11i + i1IIi
if 52 - 52: I11i - OoO0O00 % I1Ii111 . OOooOOo
if 90 - 90: O0 - Oo0Ooo / i1IIi * iIii1I11I1II1 % o0oOOo0O0Ooo... | |
import socketio
import json
import os
import io
import requests
import socket
import time
from flask import Flask, request, jsonify, Response
from minio import Minio
from pymongo import MongoClient
# from minio.error import S3Error
# Example of how the analysis is getting saved
#--------------------------------------... | |
<gh_stars>1-10
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
"""
Manages WrapperFormatter objects.
WrapperFormatter objects can be used for wrapping CLI column celldata in order
for the CLI table (using prettyTable) to fit the terminal screen
The basic idea is:
Once cell... | |
frma = "https://tw.rpi.edu/Courses/Ontologies/2018/FRMA/FRMA/"
lio = "https://w3id.org/lio/v1#"
# treeClassQuery = """
# select *
# where{
# ?class a owl:Class.
# ?class rdfs:label ?name.
#
# OPTIONAL {
# ?class rdfs:subClassOf ?super .
# ?super a owl:Class.
# ?super rdfs:label ?super_name.
# }
# }
# """
correctQue... | |
<gh_stars>1-10
# ----------------------------------------------------------------------------------------------------------------------
# Analytics API
# ----------------------------------------------------------------------------------------------------------------------
# imports
import datetime
import os
import io
... | |
<filename>dss_server.py
# -*- coding: utf-8 -*-
"""
dss_server.py
Provides class DSSServer, a configuration-based master server for DSN antennae.
If this is run as a standalone program then the appropriate environment should
be activated.
On crux ``pipenv`` is the environment manager. ``/home/ops/dss-monitor-control... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
https://docs.python.org/2/library/subprocess.html#popen-objects
http://stackoverflow.com/questions/1606795/catching-stdout-in-realtime-from-subprocess
http://askubuntu.com/questions/458041/find-x-window-name
http://stackoverflow.com/questions/9681959/how-can-i-use-xdot... | |
<reponame>CHIMEFRB/ch_util
"""
Tools for point source calibration
This module contains tools for performing point-source calibration.
"""
from abc import ABCMeta, abstractmethod
import inspect
import logging
import numpy as np
import scipy.stats
from scipy.optimize import curve_fit
from scipy.interpolate import inte... | |
Ps_z[:, :, 0]
theta = np.arctan2(Ps_y, Ps_x)
phi = np.arctan2(Ps_z, np.sqrt(Ps_x ** 2 + Ps_y ** 2))
a = 2 * np.pi / (Ws - 1)
b = np.pi - a * (Ws - 1)
self.map_x = (1.0 / a) * (theta - b)
a = -np.pi / (Hs - 1)
b = np.pi / 2
self.map_y = (1.0 / a) * (phi - b)
output = cv2.remap(
img,
self.map_x.astype(np.f... | |
<filename>pygeom/geom3d/cubicspline.py
from .line import Line
from .vector import Vector
from numpy.matlib import zeros
from numpy.linalg import solve
from matplotlib.pyplot import figure
from mpl_toolkits.mplot3d import Axes3D
class CubicSpline(object):
u"""This class stores a 3D parametric cubic spline."""
pnts = ... | |
待启用的直播域名。
:type DomainName: str
"""
self.DomainName = None
def _deserialize(self, params):
self.DomainName = params.get("DomainName")
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... | |
<reponame>oliviersultan/qlik-py-tools<gh_stars>100-1000
import os
import sys
import ast
import time
import string
import locale
import pickle
import warnings
import numpy as np
import pandas as pd
from pathlib import Path
import ServerSideExtension_pb2 as SSE
# Suppress warnings
if not sys.warnoptions:
warnings.sim... | |
dtype=float, sep=';', count=-1) for delaystr in delays_str]
# delay_settings = NP.asarray(delays_list)
# delay_settings *= 435e-12
# delays = NP.copy(delay_settings)
h = 0.7 # Hubble constant coefficient
cosmodel100 = CP.FlatLambdaCDM(H0=100.0, Om0=0.27) # Using H0 = 100 km/s/Mpc
cosmodel = CP.FlatLambdaCDM(H0=h*100.0... | |
import random
import numpy as np
from chessbot_utils import fast_predict, create_piece_decoder, flatten_board
from math import inf
import chess
import chess.engine
# import cProfile
# import pstats
class Player:
def __init__(
self, team: int, encoder: dict, score_encoder: dict, boosted_rewards: bool
):
self.tea... | |
if the artifact has existing alaises.
"""
mutation = gql(
"""
mutation DeleteArtifact($artifactID: ID!, $deleteAliases: Boolean) {
deleteArtifact(input: {
artifactID: $artifactID
deleteAliases: $deleteAliases
}) {
artifact {
id
}
}
}
"""
)
self.client.execute(
mutation,
variable_values={"artifactID": ... | |
or
signal_v_field not in radar.fields):
warn('Unable to obtain spectral differential reflectivity. ' +
'Missing fields')
return None, None
subtract_noise = dscfg.get('subtract_noise', False)
lag = dscfg.get('lag', 0)
zdr = pyart.retrieve.compute_differential_reflectivity_iq(
radar, subtract_noise=subtract_noi... | |
filename = './' + filename
dirname = os.path.join(filebase, os.path.split(filename)[0])
try:
split_path = re.split(r'[/\\]', dirname)
subpaths = [os.path.sep.join(split_path[:i]) for i in range(1, len(split_path)+1)]
for subpath in subpaths:
if not os.path.exists(subpath):
os.makedirs(dirname)
if self.made_dir ... | |
elif type == kThreadWaitPThreadRWLockRead:
s += "pthread rwlock %x for reading" % context
elif type == kThreadWaitPThreadRWLockWrite:
s += "pthread rwlock %x for writing" % context
elif type == kThreadWaitPThreadCondVar:
s += "pthread condvar %x" % context
elif type == kThreadWaitWorkloopSyncWait:
s += "workloop... | |
# 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 torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.iterative_refinement_generator import DecoderOut
from... | |
x)
_BIN_OPS_SEARCH_ORDER.append(
(_FLIPPED_OPS[op], b_type, a_type, flipped)
)
_COMPARISON_OPS: Set[BinFn] = {
ops.eq,
ops.ne,
ops.ge,
ops.gt,
ops.le,
ops.lt,
}
_ARITHMETIC_OPS: Set[BinFn] = {
ops.add,
ops.sub,
ops.mul,
ops.truediv,
ops.floordiv,
ops.mod,
ops.pow,
}
_BITWISE_OPS: Set[BinFn] = {
ops.... | |
# -*- coding: utf-8 -*-
# cython: profile=False
"""
Created on Fri Nov 4 13:05:59 2011
@author: <NAME>
TODO:
Look into using e.g. sp.linalg.fblas.zgemm._cpointer from cython? Or
link it to blas at compile time using distutils...
"""
import scipy as sp
import scipy.linalg as la
#import scipy.sparse as spa
class ey... | |
'Private Const a As Integer = 10, b As String = "hello", c As String * 10 = 43',
])
# << Parsing tests >> (10 of 61)
# Odds and ends
tests.extend([
"Private WithEvents A As Button",
])
# << Parsing tests >> (11 of 61)
# Bare calls
tests.extend([
"subr",
"object.method",
"object.method.method2.method",
])
# Explicit... | |
"int veclen2__Fii(int ix, int iy)")
del_items(0x800454BC)
SetType(0x800454BC, "void set_light_bands__Fv()")
del_items(0x80045530)
SetType(0x80045530, "void SetLightFX__FiisssUcUcUc(int x, int y, short s_r, short s_g, int s_b, int d_r, int d_g, int d_b)")
del_items(0x8004559C)
SetType(0x8004559C, "void DoLighting__Fiiii... | |
brain surface where the data has been measured, e.g., 'white' or 'pial'. This will become part of the file name that is loaded. For white, nothing will be added. Defaults to 'white'.
hemi : {'both', 'lh', 'rh'}
The hemisphere that should be loaded.
subjects_dir: string
A string representing the full path to a dir... | |
fill=color_neuron, outline=color_neuron)
if lay_scheme[gNum][2]:
#center
self.canvas_brain.create_rectangle(x_group_preset + nr_bound_w + colNum * (
neuron_draw_size + nr_bound_w) + neuron_draw_size / 3,
nr_preset + down_shift + nr_bound_h + neuron_draw_size / 3,
x_group_preset + nr_bound_w + colNum * (
neuron_... | |
"""General functions and classes to support PsychoPy experiments."""
from __future__ import division
import os
import sys
import time
import json
import socket
import warnings
import argparse
import subprocess
from glob import glob
from string import letters
from math import floor
from subprocess import call
from ppri... | |
# PyeMap: A python package for automatic identification of electron and hole transfer pathways in proteins.
# Copyright(C) 2017-2020 <NAME>, <NAME>, <NAME> (Boston University, USA)
"""Finds shortest paths in graph given a source and optionally a target node.
Defines implementations of yen's and dijkstra's algorithms f... | |
result = self.enode(
(' '.join(cmd)).format(**locals()),
shell='vtysh'
)
if result:
raise determine_exception(result)(result)
def vlan_trunk_allowed(
self, vlan_id):
"""
Allow VLAN on the trunk port
This function runs the following vtysh command:
::
# vlan trunk allowed {vlan_id}
:param vlan_id: <1-4... | |
<filename>tests/test_flatql_parser.py
import pytest
from flatql.parser.ast import FlatQL, QualifiedName, FunctionCall, Comparison, Between, In, IsNull, \
Literal, Like, View, Column, Identifier, Table, BinaryExpression, ParenExpression, CaseExpression, \
LogicalExpression, ArrayLiteral
from flatql.parser.flatql_pars... | |
* 4, self.expr.name.repeat(4)),
(lambda s: s[1:], self.expr.name.slice(1)),
(lambda s: s[1: 6], self.expr.name.slice(1, 6)),
(lambda s: s.title(), self.expr.name.title()),
(lambda s: s.rjust(20, '0'), self.expr.name.zfill(20)),
]
fields = [it[1].rename('id'+str(i)) for i, it in enumerate(methods_to_fields)]
ex... | |
import csv
import datetime
import logging
import time
from io import StringIO
import numpy as np
import pandas as pd
from django.db.models import Q
from django.utils import timezone
from iotile_cloud.utils.gid import IOTileBlockSlug, IOTileDeviceSlug, IOTileStreamSlug, IOTileVariableSlug
from apps.physicaldevice.mo... | |
the "Get Discoveries
by range" API.
Args:
id(basestring): Discovery ID.
headers(dict): Dictionary of HTTP Headers to send with the Request
.
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
MyDict: JSON response. Access the object... | |
Det N_common_animate_dobj PP_loc [0.5]
NP_animate_iobj -> Det N_common_animate_iobj [0.5] | N_prop_iobj [0.5]
NP_animate_nsubj -> Det N_common_animate_nsubj [0.5] | N_prop_nsubj [0.5]
NP_on -> Det N_on PP_loc [0.1] | Det N_on [0.9]
NP_in -> Det N_in PP_loc [0.1] | Det N_in [0.9]
NP_beside -> Det N_beside PP_loc [0.1] |... | |
#!/usr/bin/env python3
import hashlib
import json
import jsonschema
import os
import pathlib
import requests
import shutil
import stat
import sys
try:
from xpload_config import *
except ImportError:
__version__ = "0.0.0-notinstalled"
XPLOAD_CONFIG_SEARCH_PATHS = [".", "config"]
pass
general_schema = {
"definit... | |
of using private
methods in a hackish way) in Python 2.4, so is now deprecated.
Use *_from_string as described above.
More: Python 2.4 has a new email package, and the private functions
are gone. So this won't even work. We have to do something to
get this to work, for the 1.0.x branch, so use a different ugly
h... | |
"""Defines the database models for a batch"""
from __future__ import unicode_literals
import logging
from collections import namedtuple
import django.contrib.postgres.fields
from django.db import connection, models, transaction
from django.db.models import F, Q
from django.utils.timezone import now
from batch.config... | |
<reponame>HazyResearch/domino
from __future__ import annotations
from collections import defaultdict
from multiprocessing.sharedctypes import Value
from typing import Union
import meerkat as mk
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from domino.utils import convert_to_numpy, unpack_args
fr... | |
depth2dtype = {
# cv.IPL_DEPTH_8U: 'uint8',
# cv.IPL_DEPTH_8S: 'int8',
# cv.IPL_DEPTH_16U: 'uint16',
# cv.IPL_DEPTH_16S: 'int16',
# cv.IPL_DEPTH_32S: 'int32',
# cv.IPL_DEPTH_32F: 'float32',
# cv.IPL_DEPTH_64F: 'float64',
# }
# arrdtype=im.depth
# a = np.fromstring(
# im.tostring(),
# dtype=depth2dtype[im.depth],
# cou... | |
wavelet object used in the creation of `wt`.
weighting_function : function
Function used in the creation of `wt`.
signal_dtype : dtype
dtype of signal used in the creation of `wt`.
deep_copy : bool
If true (default), the mother wavelet object used in the creation of
the wavelet object will be fully copied and... | |
<gh_stars>0
import torch
import numpy as np
import pandas as pd
from transformers import ElectraModel, ElectraTokenizer, AutoTokenizer
from konlpy.tag import Mecab
import os
import re
import pickle
import json
from datautils import utils
from build_koelectra_vocab import build_vocab
# nltk.download("punkt")
# 차원 확인용... | |
<reponame>ztanml/ptpqp
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 15:21:45 2015
@author: zhaoshiwen
@email: <EMAIL>
"""
import numpy as np
class MELD:
def __init__(self, Y, Yt, k, Phi = np.array([])):
"""
Yt: the type of y_j
0: categorical: levels are 0,1,2,...
1: distribution with mean across the real ... | |
\
"filename*=UTF-8''{utf_filename}".format(
utf_filename=quote(basename.encode('utf-8'))
)
os.remove(fund_file_path)
return response
@f_app_blueprint.route('/del_file', methods=['POST', 'GET'])
@login_required
@permission
def del_file():
"""
删除文件
:by hdhuang
:return:
"""
fid = request.json['fid']
fund_fil... | |
== others_dict[k_o]) > 0 else 0
# store
ref_accs.append(running_ref_acc)
acc_025ious.append(running_acc_025iou)
acc_05ious.append(running_acc_05iou)
# aggregate
scores["overall"][k_o] = {}
scores["overall"][k_o]["ref_acc"] = np.mean(ref_accs)
scores["overall"][k_o]["acc@0.25iou"] = np.mean(acc_025ious)
score... | |
distance from each face
for j in range(0, nVertices):
# define the vector from the point of interest to the first point of the face
pa = np.array([vertices[j, 0]-points[i, 0], vertices[j, 1]-points[i, 1]])
# find perpendicular distance from point to current surface (vector projection)
d_vec = np.vdot(pa, unit_no... | |
<gh_stars>0
"""
This script is generally for the purpose of extracting quantities of interest
from the Sapphire-generated Metadata object as it exists in V0.10.1
This will simply be a placeholder until a more robust way of writing and storing
the output data can be
"""
import pickle
from ase.io import read
import n... | |
tol=tol):
"""Compute hyp1f1 using the Taylor series, with recurrence to avoid
the dangerous regions where |a| > |b| and sign(a) = -sign(z).
"""
if np.sign(z) == -np.sign(a) and np.abs(a) > np.abs(b):
if a < 0 and b > 0:
w0 = taylor_series(a, -int(a) + b + 1, z, maxiters, tol)
w1 = taylor_series(a, -int(a) + b, ... | |
' ' + '0.0'
pu = str(p0x) + ' ' + str(p1y) + ' ' + '0.0'
e = "%s %s %s %s %s" % (p0, pb, p1, pu, p0)
i = []
if exts[1] is not None:
for h in exts[1]:
p0x = h[0]
p0y = h[1]
p0 = str(p0x) + ' ' + str(p0y) + ' ' + '0.0'
p1x = h[2]
p1y = h[3]
p1 = str(p1x) + ' ' + str(p1y) + ' ' + '0.0'
pb = str(p1x) + ' ' +... | |
-3.09699342998118032, 6.33537134263541457],
[-1.47214250606392016, -2.97011207363773355, 6.07581622020240708],
[-1.4762301901536552, -2.85321801458269464, 5.83669163417894676],
[-1.48000830776230541, -2.74517669988169555, 5.61567668388842467],
[-1.48351074240884162, -2.6450191531320435, 5.41078918064620229],
[-1.4... | |
/ N_t * left_impurity)
where ``N`` is the total number of samples, ``N_t`` is the number of
samples at the current node, ``N_t_L`` is the number of samples in the
left child, and ``N_t_R`` is the number of samples in the right child.
``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum,
if ``sam... | |
range(9)]
for batch in tqdm(train_data.get_batches(
config.im_batch_size, num_batches=num_steps),
total=num_steps, ascii=True, smoothing=1):
# start from 0 or the previous step
global_step = sess.run(models[0].global_step) + 1
validation_performance = None
if (global_step % config.save_period == 0) or \
(confi... | |
5 / 100.
HIGH_LUMINOSITY = 255 * 98 / 100.
hsl = self.get_value()
if hsl[1] <= LOW_SATURATION:
# If we're given a color with a very low saturation, the user is
# searching for a black/white/grey and we need to take saturation
# and lightness into consideration, but ignore hue.
clauses = [
Q('range', **{'colors... | |
#!/usr/bin/env python
# coding: utf-8
# <img src="imagenes/rn3.png" width="200">
# <img src="http://www.identidadbuho.uson.mx/assets/letragrama-rgb-150.jpg" width="200">
# # [Curso de Redes Neuronales](https://curso-redes-neuronales-unison.github.io/Temario/)
#
# # Redes neuronales multicapa y el algoritmo de *b-pro... | |
<reponame>acorg/ssm-report<filename>py/ssm_report/obsolete/settings_report.py
error OBSOLETE
import sys, os, copy, datetime
import logging; module_logger = logging.getLogger(__name__)
from pathlib import Path
from acmacs_base.json import write_json
# -------------------------------------------------------------------... | |
composite instance
inline_composite = inst.create_inline_composite(already_captured)
self.valid_instances.add(inline_composite)
else:
self.valid_instances.add(inst)
# Always add any reductions to our parent
for reduction in state.reduction_instances:
assert reduction not in self.owner.reductions
self.owner.redu... | |
; //...................................... RECOMMENDED - A place to acknowledge various types of support for the project that produced this data. (ACDD)
:license = "" ; //............................................. RECOMMENDED - Describe the restrictions to data access and distribution. (ACDD)
:standard_name_vocabu... | |
tensor3D
# c0 = tensor.alloc(numpy_floatX(0.), beam_width, options['dim_proj'])
u0 = tensor.alloc(numpy_floatX(0.), hidi.shape[0], beam_width)
hiddeni, celli, probi = _ptr_probs(xi_mask, xi, hidi, celi, u0, hids, hiddens_mask)
f_probi = theano.function(inputs=[xi_mask, xi, hidi, celi, hids, p_mask, p], outputs=[hid... | |
file
extcat = np.genfromtxt(xmatchexternal,
usecols=externalcolnums,
delimiter=externalcolsep,
names=externalcolnames,
dtype=externalcoldtypes)
ext_cosdecl = np.cos(np.radians(extcat['decl']))
ext_sindecl = np.sin(np.radians(extcat['decl']))
ext_cosra = np.cos(np.radians(extcat['ra']))
ext_sinra = np.sin(np.r... | |
<filename>rosaceae/bins.py<gh_stars>1-10
# -*- coding: UTF-8 -*-
"""
rosaceae.bin
~~~~~~~~~~~~
This module implements data binning.
"""
from __future__ import print_function
import numpy as np
import pandas as pd
from itertools import combinations
from sklearn.tree import DecisionTreeClassifier
def bin_frequency(x... | |
<reponame>jma712/DIRECT<filename>src/main_disent.py<gh_stars>1-10
'''
Disentangled multiple cause effect learning
2020-07-08
'''
import time
import numpy as np
import torch
from torch import optim
from torch import nn
from torch.nn import functional as F
from torchvision.utils import save_image
from torch.utils.data i... | |
translate_status_exception(
error, self, "get_manual_journal_attachment_by_id"
)
def get_manual_journal_attachments(
self,
xero_tenant_id,
manual_journal_id,
_return_http_data_only=True,
_preload_content=True,
_request_timeout=None,
):
"""Retrieves attachment for a specific manual journal # noqa: E501
OAut... | |
increases max_viking to 16 if air units detected
self.maxmedivacs = 0
self.liberator_left = 0
self.max_siege = 0
self.max_barracks = 1 # maxamount of barracks
self.build_barracks_addons = False
self.super_fast_barracks = False
self.barracks_reactor_first = False
self.delay_barracs = False
self.maxfactory = 2
... | |
tree.child.where_condition is not None:
where_str = "\t\t\tif("
where_str +=__where_convert_to_java__(tree.child.where_condition.where_condition_exp,buf_dict)
where_str += "){\n"
print >>fo,where_str
buf_dict = {}
for tn in tree.table_list:
buf_dict[tn] = line_buffer
print >>fo,"\t\t\tif(" + adv_count_output ... | |
multi-library test)",
)
collection.create_external_integration(ExternalIntegration.OPDS_IMPORT)
library.collections.append(collection)
return collection
def test_authentication(self):
"""It's possible to authenticate with multiple libraries and make a
request that runs in the context of each different library.
... | |
"""Agent manager to handle plugin to agent RPC and periodic tasks."""
# coding=utf-8
# Copyright (c) 2016-2018, F5 Networks, 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://ww... | |
from socket import socket, AF_INET, SOCK_STREAM, getprotobyname
from hashlib import sha256, sha512, md5, sha1, sha384, sha224, blake2b, blake2s, shake_128, sha3_512, sha3_384, sha3_256, shake_256, shake_128
from argparse import ArgumentParser
from Cryptodome.Cipher.AES import new, MODE_GCM, MODE_CBC
from Cryptodome... | |
#!/usr/bin/env python
import os.path
import sys
import subprocess
def replace(msg, to_replace):
for k in to_replace:
msg = msg.replace(k[0], k[1])
return msg
class Base:
def __init__(self, name, data_type, return_type):
self.names = [("NAME", name.replace(" ", "_")),
("DATA", data_type)]
self.names.extend(... | |
{
'commands': [{
'name': 'get-mapping-fields'
}],
'ismappable': True
}})
structure_validator = StructureValidator(integration.yml.path, predefined_scheme='integration')
validator = IntegrationValidator(structure_validator)
assert validator.is_mapping_fields_command_exist()
def test_mapping_fields_command_don... | |
<filename>myresources/crocodile/core.py
"""
A collection of classes extending the functionality of Python's builtins.
email <EMAIL>
"""
# Typing
# Path
import os
import sys
from pathlib import Path
import string
import random
# Numerical
import numpy as np
# import pandas as pd # heavy weight, avoid unless necessary.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.