input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>redun/tests/test_tasks.py
import pickle
import sys
from collections import namedtuple
from typing import Any, Callable, NamedTuple, Tuple
import pytest
import redun
from redun import Task, task
from redun.expression import Expression
from redun.scheduler import set_arg_defaults
from redun.task import Func, ... | |
from unittest.mock import MagicMock
import pytest
from spacy.language import Language
from spacy.tokens import Span
from peerscout.keyword_extract.spacy_keyword import (
get_span_without_apostrophe,
get_normalized_span_text,
is_conjunction_token,
join_spans,
get_text_list,
get_noun_chunk_for_noun_token,
get_n... | |
# import time
# import pdb
# import threading
# import logging
# from multiprocessing import Pool, Process
# import pytest
# from utils.utils import *
# from common.constants import *
# COMPACT_TIMEOUT = 180
# field_name = default_float_vec_field_name
# binary_field_name = default_binary_vec_field_name
# default_singl... | |
""" Cisco_IOS_XR_ip_iarm_v6_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR ip\-iarm\-v6 package operational data.
This module contains definitions
for the following management objects\:
ipv6arm\: IPv6 Address Repository Manager (IPv6 ARM)
operational data
Copyright (c) 2013\-2018 by ... | |
<reponame>TotoArt/arnheim
# Copyright 2021 DeepMind Technologies Limited
#
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by app... | |
sentNo=%s' % (quote_attrib(self.sentNo), ))
if self.paragNo is not None and 'paragNo' not in already_processed:
already_processed.append('paragNo')
outfile.write(' paragNo=%s' % (quote_attrib(self.paragNo), ))
if self.aPos is not None and 'aPos' not in already_processed:
already_processed.append('aPos')
outfile.w... | |
13
msg.contentMetadata = {'mid': mid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Amid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Bmid}
cl.sendMessage1(msg)
msg.contentType = 13
msg.contentMetadata = {'mid': Cmid}
cl.sendMessage1(msg)
msg.contentType... | |
finished_event.wait())
except OperationCancelled:
break
if finished_event.is_set():
self.logger.debug("stopping fast_sync_chains_importer_loop because finished_event is set")
break
self.logger.debug("fast_sync_chains_importer_loop importing chains")
await self.handle_priority_import_chains(chains, save_block_... | |
technically allowed for odd reasons
if debug:
print(
"Reject: Invalid SMARTS",
)
# print(ff_subtract.compact_str())
continue
if blank:
if debug:
print(
"Reject: This bit would not separate the data",
)
continue
if occluding: # occluding_split:
if (
self.bit_search_limit is None
or bit.bits() <= self... | |
<reponame>thewahome/msgraph-cli
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code... | |
import argparse
from datetime import datetime
import time
import os
from tqdm import trange, tqdm
from timeit import default_timer as timer
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from perlin import TileableNoise
from math import sin, pi
from random import random, seed, unifor... | |
1.1)):
included_result = JsonLdProcessor.arrayify(
self._expand(active_ctx, active_property, value, options))
if not all(_is_subject(v) for v in included_result):
raise JsonLdError(
'Invalid JSON-LD syntax; "values of @included '
'must expand to node objects.',
'jsonld.SyntaxError',
{'value': value}, code='inva... | |
<filename>pyscf/cc/gccsd.py
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. 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/li... | |
noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
... | |
<reponame>strombergdev/frameio-python-sync
import fnmatch
import mimetypes
import os
from datetime import datetime, timedelta, timezone
from threading import Thread
from time import sleep, time
import requests
from dateutil import parser
from requests import auth
import config
from db_handler import db_queue
from fra... | |
None
data = None if load_from_fname else self.data
writer.write(load_from_fname, group_name="load_from_fname")
writer.write(fname, group_name="fname")
writer.write(data, group_name="Zdata")
writer.write(self.get_lut_range(), group_name="lut_range")
writer.write(self.z(), group_name="z")
self.imageparam.update_pa... | |
# -*- coding: utf-8 -*-
import sys
import os
import imp
if sys.version_info[0] == 2:
imp.reload(sys)
sys.setdefaultencoding('utf8')
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import datetime
import re
from collections import OrderedDict
from ordered_xml import OrderedXMLElement as Element, ... | |
<reponame>janithwanni/icecaps
import os
import sys
import random
import tensorflow as tf
import copy
import re
from collections import defaultdict, OrderedDict
from icecaps.util.vocabulary import Vocabulary
class DataHeader:
def __init__(self, name, data_type, vocab_file=None, vocab_mode="read"):
self.name = name
... | |
forTrain and MR.attributeValues.keys() != set(alingedAttributes) and 'none' in MR.attributeValues:
directReferenceSequence[0].attribute = 'none'
if passport or not forTrain:
if forTrain:
directReferenceSequence = inferNaiveAlignments(MR, directReferenceSequence)
DI = DatasetInstance(MR, directReferenceSequence, se... | |
= None ):
"""Generates style-mixed grid of images, emulating Figure 3 in Karras et al. 2019."""
assert any( len( zs ) for zs in ( zs_coarse, zs_middle, zs_fine, ) )
if self.ds_mean is None or self.ds_std is None:
raise ValueError( "This model does not hold any information about your dataset's mean and/or std.\n" + ... | |
<reponame>tor4z/batchgenerators<filename>batchgenerators/transforms/spatial_transforms.py<gh_stars>0
# Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | |
#! /usr/bin/python
# Bisync
# Copyright (C) 2012 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This prog... | |
<reponame>julienroy13/alfred
# USAGE
# TODO: write description of how to use it (maybe in the help from argparse?)
# ASSUMPTIONS: alfred.prepare_schedule assumes the following structure:
# 1. a folder named 'schedules' containing containing a separate folder for each schedule (search)
# 2. in each of these folders, ei... | |
of media objects.
"""
class ResponseMediaType(proto.Enum):
r"""Format of response media type."""
RESPONSE_MEDIA_TYPE_UNSPECIFIED = 0
AUDIO = 1
class ResponseMediaObject(proto.Message):
r"""Response media object for media content card.
Attributes:
name (str):
Required. Name of media card.
description (str)... | |
file for {}::{} - {}.root".format(counter, name, channel, directory + "/" + channel + "/"+ name))
rootDict[name].Close()
def BTaggingYieldsAnalyzer(directory, outDirectory="{}", globKey="*.root", stripKey=".root", includeSampleNames=None,
excludeSampleNames=None, mode="RECREATE", doNumpyValidation=False, forceDefau... | |
<filename>mango/client.py<gh_stars>1-10
# # ⚠ Warning
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LI... | |
0:
raise SVNExpectedStderr
else:
svntest.verify.compare_and_display_lines(
"Standard error output", "STDERR:", expected_stderr, errput)
# The expected error occurred, so don't try to verify the result
return
if revs:
# verify revs as wc states
for rev in range(len(revs)):
svntest.actions.run_and_verify_svn(s... | |
self._ortho_unique
def _set_ortho_unique(self, valeur):
raise AttributeError("ortho_unique ne peut pas etre modifie")
def _get_dico_multiple(self):
return self._dico_multiple
def _set_dico_multiple(self, dico_multiple):
self._dico_multiple = dico_multiple
self._ortho_multiple = list(set([w for w, _ in dico_mu... | |
<gh_stars>0
from __future__ import unicode_literals
import datetime
import hashlib
import logging
import re
import string
import warnings
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import MultipleObjectsReturned
fro... | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
import json
import math
import queue
import os
import scipy.io
import numpy as np
IMAGE_LENGTH = IMAGE_WIDTH = IMAGE_HEIGHT = 768
NEAR_DISTANCE = 200
TYPES = ["unmovable", "tree", "movable"]
CATEGORIES_UNMOVABLE = ["house", "bus", "truck", "car", "bench", "chair"]
CATEGORIES... | |
<filename>examples/dave_nodes/src/bimanual_simple_demo.py<gh_stars>0
#!/usr/bin/env python
from __future__ import print_function
from six.moves import input
import sys
import copy
import rospy
import moveit_commander
import moveit_msgs.msg
import geometry_msgs.msg
import tf
import numpy as np
import time
from gazebo... | |
<reponame>johnoneill98/idem-azurerm
# -*- coding: utf-8 -*-
"""
Azure Resource Manager (ARM) Blob Container State Module
.. versionadded:: 2.0.0
:maintainer: <<EMAIL>>
:configuration: This module requires Azure Resource Manager credentials to be passed via acct. Note that the
authentication parameters are case sensi... | |
'%s.%s' % (
self.visit(node.value),
node.attr) # Don't visit node.attr: it is always a string.
#@+node:ekr.20141012064706.18419: *4* f.Bytes
def do_Bytes(self, node): # Python 3.x only.
return str(node.s)
#@+node:ekr.20141012064706.18420: *4* f.Call & f.keyword
# Call(expr func, expr* args, keyword* keywords, ex... | |
<filename>sdk/python/pulumi_rancher2/cluster_template.py
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing im... | |
object
:param force (java.lang.Boolean): Force to import the file and replace the object having the same name.
"""
appWrapper = self._wrapper
files = {'file': (name, open(filename, 'rb'), 'application/xml')}
r = appWrapper.session.post(url='https://' + appWrapper.host + '/bps/api/v2/core/network/operations/importN... | |
for s in self.get_steps(state=wf_states.RUNNING):
try:
self.kill_step_calculations(s)
except InvalidOperation as e:
error_message = ("'{}' for workflow with pk= {}"
"".format(e.message,self.pk))
error_messages.append(error_message)
for w in s.get_sub_workflows():
if verbose:
print "Killing workflow with pk... | |
<filename>mist/lang/function.py
import os
import tempfile
import re
import xml.etree.ElementTree as ET
import json
from jsonpath_ng.ext import parse
import csv
import asyncio
import inspect
from functools import partial
import uuid
from mist.lang.exceptions import (MistException, MistAbortException, MistUndefinedVaria... | |
import discord
from discord.ext import commands
from __main__ import settings, botdata, invite_link, httpgetter
from cogs.utils.helpers import *
from cogs.utils.botdata import UserInfo
from cogs.utils import checks, botdatatypes
from cogs.audio import AudioPlayerNotFoundError
from sqlalchemy import func
import cogs.uti... | |
it is replaced by fraction=replace_fraction * (1 + cutting_waste)
cost_result.costs.loc[:, (dt_rep, 'Replacement')] = replacement
dt_rep += life_time
# Add the result to the collection of results
self.cost_results[window_material.IuId] = cost_result
return cost_result
def __shade_or_blind_material(self, mate... | |
<filename>tests/structures.py
#
# Copyright (C) 2019-2020 Intel Corporation. All Rights Reserved.
#
#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 limitat... | |
Dict[str,str]:
"""Parse a keyword_plan path into its component segments."""
m = re.match(r"^customers/(?P<customer_id>.+?)/keywordPlans/(?P<keyword_plan_id>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def keyword_plan_ad_group_path(customer_id: str,keyword_plan_ad_group_id: str,) -> str:
"""Retur... | |
axis.set_yticks([])
axis.text(0, 0, 'No data available.', ha='center', va='center', size=15)
except (Exception, psycopg2.DatabaseError) as error:
self.log.exception(error)
finally:
self.pool.putconn(conn)
def draw_highscore_kills(self, ctx, figure, period, server, limit):
SQL_PARTS = {
'Air Targets': 'SUM(s.ki... | |
intent, body, subject, audit_trail=None,
retention_policy=None):
"""Asyncronously sends a notification via email.
Args:
to: string. Recipient email address. Must have a valid form, but we
cannot know that the address can actually be delivered to.
sender: string. Email address of the sender of the
notification.... | |
'rho'
# default_dic['v_n_y'] = 'r'
default_dic['xmin'] = 1e-9
default_dic['xmax'] = 2e-5
default_dic['ymin'] = 0
default_dic['ymax'] = 250
default_dic['yscale'] = None
elif vn1vn2 == "rho_Ye":
v_n_x = 'rho'
v_n_y = 'Ye'
# default_dic['v_n_x'] = 'rho'
# default_dic['v_n_y'] = 'Ye'
default_dic['xmin'] = 1e-9
... | |
received by a destination which will not record the shipment directly into the system."))
if status != SHIP_STATUS_RECEIVED:
if settings.get_inv_send_packaging():
if status == SHIP_STATUS_IN_PROCESS:
# Insert in front of 'Send Shipment'
index = -1
else:
# Append at end
index = len(actions)
actions.insert(ind... | |
SETS #########################################################################
# <NAME>. & <NAME>. (1994), Fast algorithms for mining association rules in large databases.
# Based on: https://gist.github.com/1423287
class Apriori:
def __init__(self):
self._candidates = []
self._support = {}
def C1(self, sets):... | |
return name
return None
#===================================================================
# setup
#===================================================================
def setUp(self):
super(HandlerCase, self).setUp()
# if needed, select specific backend for duration of test
handler = self.handler
backend ... | |
row_cleaned[EXERCISE_QUESTIONS_OPTION_A_KEY]
all_answers.append(ansA)
ansB = row_cleaned.get(EXERCISE_QUESTIONS_OPTION_B_KEY, None)
if ansB:
all_answers.append(ansB)
ansC = row_cleaned.get(EXERCISE_QUESTIONS_OPTION_C_KEY, None)
if ansC:
all_answers.append(ansC)
ansD = row_cleaned.get(EXERCISE_QUESTIONS_OPTION_D... | |
# ActivitySim
# See full license in LICENSE.txt.
from builtins import zip
import logging
import os
from operator import itemgetter
import numpy as np
import pandas as pd
import cytoolz as tz
import cytoolz.curried
logger = logging.getLogger(__name__)
def si_units(x, kind='B', digits=3, shift=1000):
# nano micr... | |
gd_pooling.GDMaxPooling(self.parent, kx=kernel_size,
ky=kernel_size,
sliding=(stride, stride),
device=self.device)
grad_pool.input = Array(bottom)
grad_pool.input.map_write()
grad_pool.err_output = Array(top_err)
grad_pool.err_output.map_write()
grad_pool.input_offset = fwd_pool.input_offset
grad_pool.link_... | |
continues with the next element.
#
# The next element is a number, so do not have upvalues. Then tries with upvalues from b.
# If it does not have success, tries look at the next element. but the next element is again a. So, it skip it.
# Then, as new.head_name() == new.get_lookup_name(), (because F is a symbol) tr... | |
<reponame>Rainyan/discord-bot-ntpug
#!/usr/bin/env python3
"""Discord bot for organizing PUGs (pick-up games).
Built for Neotokyo, but should work for any two-team game with even number
of players total.
Usage:
Commands:
Commands are prefixed with a character defined by the config value
"NTBOT_CMD_PREFIX", by d... | |
self.textColorbar_OrigImg = Label(self.containerPost)
self.textColorbar_OrigImg.config(text = "Colorbar Limits")
# ===== Entry: X-Displacement Contour Start Caxis =====
self.editCS_X = Entry(self.containerPost)
self.editCS_X.configure(bg = "White", fg = "Black", justify = CENTER)
self.editCS_X.delete(0,END... | |
QualificationSummaryV30
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['orcid', 'put_code'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = local... | |
<filename>src/oci/file_storage/models/snapshot.py
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http... | |
import re
import string
def p2to3isunicode(s, t):
""" Helper for python 2/3 to detect unicode string """
try:
return isinstance(s, unicode) or isinstance(t, unicode) # p2
except NameError:
return isinstance(s, str) or isinstance(t, str) # p3
def p2to3itervalues(g):
""" Helper for itervalues """
try:
return g.... | |
if isStart:
for train in self.trains():
if not trainFilter.check(train):
continue
started = 0 # 0: 未开始;1:开始但不是始发站;2:开始且是始发站。
for st_dict_train in train.stationDicts():
st_dict_line = self.stationByDict(st_dict_train['zhanming'])
if st_dict_line is None:
continue
if stationEqual(st_dict_line['zhanming'], fromOr... | |
= tf.shape(signal)[-1]
zeros = tf.zeros([batch_size, 1, channels], dtype=tf.float64)
if last_sof is None:
last_sof = zeros
if last_sin is None:
last_sin = zeros
sof = last_sof
i = tf.constant(0)
def body(i, sof, last_sin):
last_sof = tf.slice(sof, [0, i, 0], [-1, 1, -1])
cur_sin = tf.slice(signal, [0, i, 0],... | |
in UserRepresentation
:return: user_id
"""
lower_user_name = username.lower()
users = self.get_users(query={"search": lower_user_name})
return next((user["id"] for user in users if user["username"] == lower_user_name), None)
def get_user(self, user_id):
"""
Get representation of the user
:param user_id: Use... | |
<reponame>NTHU-NLPLAB/DimSim
# coding: utf-8
# In[656]:
from pypinyin import pinyin, lazy_pinyin, Style
import sys
import math
import itertools
import pickle
import os
'''
@liushaohua
本更改仅限个人使用,仅仅使用编码方式,对拼音进行一个统一编码
'''
# In[657]:
work_dir = os.path.abspath(__file__)
indexOfLastSlash = work_dir.rfind("/")
wor... | |
CJK UNIFIED IDEOGRAPH-4E2D': None,
'SQUARED CJK UNIFIED IDEOGRAPH-4E8C': None,
'SQUARED CJK UNIFIED IDEOGRAPH-4EA4': None,
'SQUARED CJK UNIFIED IDEOGRAPH-518D': None,
'SQUARED CJK UNIFIED IDEOGRAPH-521D': None,
'SQUARED CJK UNIFIED IDEOGRAPH-524D': None,
'SQUARED CJK UNIFIED IDEOGRAPH-53CC': None,
'SQUARED CJK UNIFIED ... | |
= %d;" % (
user_id, post_id)
try:
cur.execute(query)
con.commit()
except Exception as e:
print(e)
print("\n\nError!\n")
return
# viewTableDel('20')
def unLike():
global cur
# viewTableDel('21')
user_id = input("Enter the User Id of the User who wants to unlike: ")
page_id = input("Enter the Page ID of th... | |
<gh_stars>0
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 applicab... | |
self.object_type)
self.originator = "-"
self.originator_name = "-"
else:
raise ValueError("%s only works with integrity flag for now!" % self.object_type)
# sanitize the input
if "linux" in self.flags:
self.victim = self.victim if self.victim else "*"
else:
self.originator = self.originator.lower()
self.ori... | |
while i < len(path):
p = path[i]
old_node = node
wild_node = old_node._nodes.get('*', None)
node = old_node._nodes.get(p, None)
if node:
if wild_node:
# this is a fall-back node, push it
stack.append((i, wild_node, wildcard))
elif wild_node:
node = wild_node
elif wildcard:
# if there is an active wildcard, ... | |
recoveryDir == "":
tolog("!!WARNING!!1190!! verifyRecoveryDir failed")
return False
tolog("Using workdir: %s, recoveryDir: %s" % (workdir, recoveryDir))
JS = JobState()
# grab all job state files from the workdir
from glob import glob
job_state_files = glob("%s/jobState-*.pickle" % (workdir))
# purge any tes... | |
request thread.
"""
all_params = ['body'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise Typ... | |
no unit cover
if header: # pragma: no unit cover
return (
f"{header}: {name}\n"
f" Input: {test[:2]}\n"
f" Want: {test[2:5]}\n"
f" Got: ({got_intersect}, {got_begin}, {got_finish})"
)
return ""
box: FabBox = FabBox()
# Z axis spans
a: Vector = Vector(0, 0, -2)
b: Vector = Vector(0, 0, -1.5)
c: Vector = ... | |
# Generates C++ include files for the SPIR-V instructions.
import sys
import json
import re
HEADER = "#ifndef %s\n#define %s\n\n// Automatically generated by generate_ops.py. DO NOT EDIT.\n\n"
FOOTER = "\n#endif // %s\n"
IMPL_RE = re.compile(r"void Interpreter::step(.*)\(const Insn(.*)& insn\)")
EMIT_RE = re.compile... | |
FusedBatchNormV3s of this type always end with /FusedBatchNormV3 in the name
# Everything preceding the cond is the scope name
match_name = re.match('(.+)/FusedBatchNormV3', op.name)
if match_name:
op_info.module_name = match_name.group(1)
op_to_module_dict.update({op: op_info})
return True
except: # pylint: dis... | |
"""
This module provides the `PerformanceMetrics` class and supporting
functionality for tracking and computing model performance.
"""
from collections import defaultdict, namedtuple
import logging
import os
import warnings
import pandas as pd
import numpy as np
from sklearn.metrics import average_precision_score
from... | |
<reponame>gopro/gopro-lib-node.gl<gh_stars>10-100
#!/usr/bin/env python
#
# Copyright 2020 GoPro Inc.
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ... | |
content: str = None,
tx_hash: str = None,
tx_time: str = None,
error_code: str = None,
error_msg: str = None,
is_success: bool = None,
version: int = None,
):
# 操作内容
self.content = content
# 链上哈希
self.tx_hash = tx_hash
# 上链时间
self.tx_time = tx_time
# 上链失败的错误码
self.error_code = error_code
# 上链失败的错误信息
se... | |
v1, dtype=dtype)
img_bg = np.full((1, 2, 3), v2, dtype=dtype)
alphas = np.zeros((1, 2, 3), dtype=np.float64)
alphas[:, :, 0] = [1.0, 0.0]
alphas[:, :, 1] = [0.0, 1.0]
alphas[:, :, 2] = [1.0, 0.0]
img_blend = blend.blend_alpha(img_fg, img_bg, alphas, eps=0)
assert img_blend.dtype.name == np.dtype(dtype).name
ass... | |
port aggregate id not present for the LAG"
# Add port channel member
fvs = swsscommon.FieldValuePairs([("status", "enabled")])
psTbl_lagMember.set(f"{test_lag1_name}:{test_lag1_member}", fvs)
# Check for presence of lag member added
lagmemberkeys = asic_db.wait_for_n_keys("ASIC_STATE:SAI_OBJECT_TYPE_LAG_MEMBER... | |
reporting_ocpaws_network_summary (usage_start, cluster_id, cluster_alias, product_code, source_uuid)
;
CREATE MATERIALIZED VIEW reporting_ocpaws_database_summary AS(
SELECT row_number() OVER(ORDER BY usage_start, cluster_id, cluster_alias, product_code) as id,
usage_start as usage_start,
usage_start as usage_end,
... | |
galpy is now right-handed, astropy right-handed
assert numpy.fabs(gcRpZ[0]-c.rho.to(u.kpc).value) < 10.**-10., "lbd to galcencyl conversion using galpy's methods does not agree with astropy"
assert numpy.fabs(gcRpZ[1]-c.phi.to(u.rad).value) < 10.**-10., "lbd to galcencyl conversion using galpy's methods does not agre... | |
'group_id': group_id,
'upgrade_unit_list': upgrade_unit_list,
})
def create(self,
upgrade_unit_group,
):
"""
Create a group
:type upgrade_unit_group: :class:`com.vmware.nsx.model_client.UpgradeUnitGroup`
:param upgrade_unit_group: (required)
:rtype: :class:`com.vmware.nsx.model_client.UpgradeUnitGroup`
:re... | |
<gh_stars>0
######################################################
#
# Copyright (c) 2003-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Ea... | |
#https://github.com/arielf/weight-loss/blob/master/vw-varinfo2
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 expandtab
"""
vw-varinfo2: vw dataset summary & variable importance
This is new & simpler implementation of the original vw-varinfo
It is designed to be simpler and faster. There's less dep... | |
(self.cell_direct.num_keys, 1), dtype = np.float32,
)
for cell_id in self.cell_direct.id_dict.keys():
if cell_id in cell_latent_flags.keys():
latent_flags[
self.cell_direct.id_dict[cell_id], 0,
] = cell_latent_flags[cell_id]
self.cell_latent_flags = tf.constant(latent_flags)
cell_pointers = np.zeros(
shape ... | |
- 2.51*m.x1164 - 31.22*m.x1176 - 4.51*m.x1186 - 65.22*m.x1200
- 18.48*m.x1226 - 53.2*m.x1234 <= 0)
m.c67 = Constraint(expr= - 4.44*m.x88 - 4.44*m.x96 - 4.44*m.x103 - 4.44*m.x112 - 4.44*m.x119 - 4.44*m.x128
+ 0.389999999999999*m.x140 + 0.389999999999999*m.x150 + 0.389999999999999*m.x159
+ 0.389999999999999*m.x168 - ... | |
# coding: utf-8
"""
Schemas
The CRM uses schemas to define how custom objects should store and represent information in the HubSpot CRM. Schemas define details about an object's type, properties, and associations. The schema can be uniquely identified by its **object type ID**. # noqa: E501
The version of the Ope... | |
<filename>config/oktoberkite/control/crosswind.py
# Copyright 2020 Makani Technologies LLC
#
# 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
#
# U... | |
'{self.original_d}' to new_d '{self.new_d}'"
)
shutil.copytree(self.original_d, self.new_d)
self.logger.log(
f"copying original_d '{self.original_d}' to new_d '{self.new_d}'"
)
self.original_file_d = self.new_d / "org"
if self.original_file_d.exists():
self.logger.lraise(f"'org' subdir already exists in new_d ... | |
#import datetime
import os
import glob
import sys
import re
import json
from config import *
from collections import Counter
#this = sys.modules[__name__]
def mut_to_string(mut):
return '-'.join([mut['operatorDescription'], mut['class'], mut['operatorClass'], mut['method'], str(mut['mutationStart']), str(mut['mutati... | |
439, 57, 16))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(235, 0, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPal... | |
import numpy as np
from numpy.random import default_rng
def random_normal_data(tr_no, voxel_no):
"""
Helper function generating random standard normal data with given TR and voxel numbers.
Output is a 2D numpy ndarray with shape (tr_no, voxel_no)
"""
mu, sigma = 0, 1
data = default_rng().normal(mu, sigma, (tr_... | |
totals=True,
),
)
# Resource Configuration
configure(tablename,
context = {"project": "project_id",
},
create_next = URL(c="project", f="location",
args=["[id]", "beneficiary"]),
deduplicate = S3Duplicate(primary = ("project_id",
"location_id",
),
),
filter_widgets = filter_widgets,
list_fields = list_fi... | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import sys
import splunk
from splunk import rest
from random import choice
import re
from re import search
import time
import logging
import xml.dom.minidom
import xml.sax.saxutils
import os
import json
import requests
from requests import get
import socket
import csv
fro... | |
<filename>mvsnet/preprocess.py
#!/usr/bin/env python
"""
Copyright 2019, <NAME>, HKUST.
Training preprocesses.
"""
from __future__ import print_function
import os
import time
import glob
import random
import math
import re
import sys
import imageio
import cv2
import numpy as np
import tensorflow as tf
import scipy.i... | |
import logging
from collections import Counter
from dataclasses import dataclass, field
from typing import Any
from typing import Counter as CounterType
from typing import Dict, Iterable, List, Optional, Tuple, Type, Union, ValuesView
from arango import ArangoClient
from arango.database import StandardDatabase
from my... | |
u'IND',
'numeric': 356,
'independent': True,
},
{
'name': u'Indonesia',
'alpha2': u'ID',
'alpha3': u'IDN',
'numeric': 360,
'independent': True,
},
{
'name': u'Iran (Islamic Republic of)',
'alpha2': u'IR',
'alpha3': u'IRN',
'numeric': 364,
'independent': True,
},
{
'name': u'Iraq',
'alpha2': u'IQ',
... | |
# coding: utf-8
"""
OpenAPI
tinkoff.ru/invest OpenAPI. # noqa: E501
The version of the OpenAPI document: 1.0.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from openap... | |
<reponame>krbjila/labrad_tools
# -*- coding: utf-8 -*-
"""
@author: ziegler
"""
import numpy as np
import time
from .sdk import sdk
from .recorder import recorder
class exception(Exception):
def __str__(self):
return ('pco.exception Exception:', self.args)
class Camera(object):
# -------------------------... | |
import tensorflow as tf
from tensorflow.keras.layers import Dense, Conv2D
from tensorflow.keras import Model
from tensorflow_addons.layers import GroupNormalization
import os
from nn import get_timestep_embedding, downsample, upsample, resnet_block, attn_block
'''
h5 files for cifar and lsuns adapted from https://www.... | |
<gh_stars>0
# Authors: <NAME>, Dr. <NAME>
# Written for Machine Learning, INFO 521, at the University of Arizona
# December 2016
# Code adapted from Stanford's: http://ufldl.stanford.edu/wiki/index.php/Neural_Networks, and ideas from https://github.com/jatinshah/ufldl_tutorial
# Utilities for neural net
# References:... | |
Function(V).interpolate(f_expression)
# Dirichlet BCs
bc_multiplier = DirichletBC(W.sub(2), p_exact, "on_boundary")
# Hybridization parameter
beta_0 = Constant(1.0e0)
beta = beta_0 / h
# beta = beta_0
# Numerical flux trace
u_hat = u + beta * (p - lambda_h) * n
# HDG classical form
a = (dot(u, v) - div(v)... | |
The magic of truth and lies and iPods",
"<NAME> - Lets transform energy -- with natural gas",
"<NAME> - Exposing the invisible",
"<NAME> - How synchronized hammer strikes could generate nuclear fusion",
"<NAME> - A warriors cry against child marriage",
"<NAME> - Why arent we more compassionate",
"<NAME> - Computi... | |
<filename>support/python_dev/opf_python/pyniggli.py<gh_stars>10-100
"""Contains the main class and functions for the niggli reduced
cell. As described in the papers found at:
https://www.mendeley.com/viewer/?fileId=74bc20b9-a7a5-8e3d-4608-6ce09ea453e0&documentId=7b2a0aec-6dcf-3475-8834-96ddbb760220
https://www.mendel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.