input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
Set degrees
surf.degree_u = 3
surf.degree_v = 2
# Set control points
control_points = [[0, 0, 0], [0, 4, 0], [0, 8, -3],
[2, 0, 6], [2, 4, 0], [2, 8, 0],
[4, 0, 0], [4, 4, 0], [4, 8, 3],
[6, 0, 0], [6, 4, -3], [6, 8, 0]]
surf.set_ctrlpts(control_points, 4, 3)
# Set knot vectors
surf.knotvector_u = [0, 0, 0,... | |
+ colorname1 + "'\n"
else: # rf. https://www.w3schools.com/colors/colors_names.asp
user_tab_header += indent + param_name_button + ".style.button_color = '" + colorname2 + "'\n"
user_tab_header += "\n" + indent + full_name + " = " + widgets[child.attrib['type']] + "(\n"
# Try to calculate and provide a "good" delt... | |
sys.exit(1)
max_flow = 0
path_capacities = []
for path in paths:
capacity = path_capacity(links, path)
path_capacities.append(capacity)
max_flow += capacity
for i in range(len(paths)):
weight = path_capacities[i] * 1.0 / max_flow
all_paths[src, dst].append((paths[i], weight))
# Compute sort information on OD... | |
ndimage.zoom(ori, np.array(img.shape)/np.array(ori.shape, dtype=float), order=0)
if mask.shape != img.shape:
mask = ndimage.zoom(mask, np.array(img.shape)/np.array(mask.shape, dtype=float), order=0)
if coh is None:
coh = np.ones_like(img)
fig = plt.figure()
plt.imshow(img, cmap='gray')
plt.hold(True)
fo... | |
- 65.41*m.x840 - 53.98*m.x852
- 56.41*m.x863 - 56.41*m.x879 - 64.04*m.x894 - 64.04*m.x931 - 86.37*m.x968 - 20.03*m.x979
- 20.03*m.x995 - 52.86*m.x1021 - 52.86*m.x1027 - 52.86*m.x1049 - 87.05*m.x1063 - 28.6*m.x1084
- 38.28*m.x1113 - 38.72*m.x1137 - 35.81*m.x1168 - 50.75*m.x1187 - 65.41*m.x1197
- 20.03*m.x1237 <= 0)
... | |
entity_id)
task_key = entity.get('key')
self.prefs[entity_key][task_key]['isFolded'] = not self.prefs[entity_key][task_key]['isFolded']
def page_fwd(self, *args, **kwargs):
self.prefs['current_page'] += 1
def page_bkw(self, *args, **kwargs):
self.prefs['current_page'] = max(self.prefs['current_page'] - 1, 0)
... | |
"""
HKEX Simulation
Message handle
"""
import selectors
import struct
from time import sleep
from bitarray import bitarray
from datetime import datetime
from ocgmock .msg_type import MsgType
from ocgmock .exec_type import ExecType
from ocgmock .ord_status import OrdStatus
from ocgmock .util.utils import... | |
<gh_stars>1-10
#!/usr/bin/env python
"""
WordAPI.py
Copyright 2014 Wordnik, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by ... | |
<reponame>Falsejoey/NabBot
import asyncio
import calendar
import datetime as dt
import random
import re
import time
import urllib.parse
from operator import attrgetter
from typing import Optional
import discord
from discord.ext import commands
from nabbot import NabBot
from utils import checks
from utils.config impor... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 11:39:43 2018
Demonstration of CPU implementation against the GPU one
@authors: <NAME>, <NAME>
"""
import matplotlib.pyplot as plt
import numpy as np
import os
import timeit
from ccpi.filters.regularisers import ROF_TV, FGP_TV, SB_TV, TGV, LLT_... | |
<gh_stars>1-10
from __future__ import print_function, division
__all__ = ['KanesMethod']
from sympy import Symbol, zeros, Matrix, diff, solve_linear_system_LU, eye
from sympy.core.compatibility import reduce
from sympy.utilities import default_sort_key
from sympy.physics.mechanics.essential import ReferenceFrame, dyn... | |
- m.x542 - m.x554 == 0)
m.c615 = Constraint(expr= m.x328 - m.x520 - m.x532 - m.x544 - m.x556 == 0)
m.c616 = Constraint(expr= m.x331 - m.x522 - m.x534 - m.x546 - m.x558 == 0)
m.c617 = Constraint(expr= - 712.572602172813*m.b2 + m.x417 - m.x837 >= -712.572602172813)
m.c618 = Constraint(expr= - 712.572602172813*m.b3 + ... | |
# flake8: noqa
"""
Tests copied from cpython test suite:
https://github.com/python/cpython/blob/3.9/Lib/test/test_complex.py
"""
# stdlib
from math import atan2
from math import copysign
from math import isnan
import operator
from random import random
import sys
import unittest
# third party
import pytest
# syft abs... | |
ID: %s' % routerId)
routerDataObj = deviceGroupObj.RouterData.find()
routerIdMultivalue = routerDataObj.RouterId
routerIdList = self.getMultivalueValues(routerIdMultivalue)
if routerId in routerIdList:
pimObj = deviceGroupObj.Ethernet.find().Ipv4.find().PimV4Interface.find()
pimV4JoinPruneList = pimObj.PimV4Join... | |
<filename>Pymongo/prod/mylib.py
#!/usr/bin/python
from bson import BSON, Binary, Code, decode_all
from bson.json_util import loads, dumps
from bson.objectid import ObjectId
from pymongo import InsertOne, DeleteOne, ReplaceOne
import pprint, datetime, time, calendar, sys, os, errno, glob, shutil
import tarfile, gzip
... | |
A length
:meth:`~DiscreteQuadraticModel.num_interactions` array. If
the case interactions were defined in a sparse matrix, these
would be the row indices.
- `icol`: A length
:meth:`~DiscreteQuadraticModel.num_interactions` array. If
the case interactions were defined in a sparse matrix, these
would be the column... | |
from kivy.config import Config
Config.set('graphics','resizable',0)
from kivy.app import App
from kivy.metrics import cm,dp,sp,Metrics
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix... | |
<gh_stars>0
# Copyright (c) 2021, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (includ... | |
from __future__ import division
import re
import unittest
import mock
import pytest
from ddtrace.constants import AUTO_KEEP
from ddtrace.constants import AUTO_REJECT
from ddtrace.constants import SAMPLE_RATE_METRIC_KEY
from ddtrace.constants import SAMPLING_AGENT_DECISION
from ddtrace.constants import SAMPLING_LIMIT... | |
import math
import numpy as np
import pandas as pd
from analysis.osu.mania.map_data import ManiaMapData
from osu.local.hitobject.mania.mania import Mania
from misc.numpy_utils import NumpyUtils
class ManiaActionData():
FREE = 0 # Finger free to float
PRESS = 1 # Finger must impart force to press key
HOLD = 2 # F... | |
# create filter options argument group
group = optparse.OptionGroup(p, "Filter Options")
group.add_option('--uuid', '-u', type="string", action="append", help="Service UUID(s) to match", metavar="UUID")
group.add_option('--mac', '-m', type="string", action="append", help="MAC address(es) to match format :: xxXXxxXXx... | |
resources = p.run()
self.assertEqual(len(resources), 1)
def test_config_source(self):
factory = self.replay_flight_data("test_security_group_config_source")
p = self.load_policy(
{
"name": "sg-test",
"resource": "security-group",
"filters": [{"GroupId": "sg-6c7fa917"}],
},
session_factory=factory,
)
d_reso... | |
<reponame>int-brain-lab/ibllib
'''
Computes task related output
'''
import numpy as np
from scipy.stats import ranksums, wilcoxon, ttest_ind, ttest_rel
from ._statsmodels import multipletests
from sklearn.metrics import roc_auc_score
import pandas as pd
from brainbox.population.decode import get_spike_counts_in_bins
... | |
"""
Copyright © 2021-2022 The Johns Hopkins University Applied Physics Laboratory LLC
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 t... | |
is this value negative?"""
return self._negative
@property
def isinf(self):
"""Is this value infinite?"""
return self._isinf
@property
def isnan(self):
"""Is this value NaN?"""
return self._isnan
# rounding envelopes and inexactness
_inexact : bool = None # approximate bit
_interval_full : bool = None #... | |
.redirect_incompatible_row_settings_py3 import RedirectIncompatibleRowSettings
from .staging_settings_py3 import StagingSettings
from .tabular_translator_py3 import TabularTranslator
from .copy_translator_py3 import CopyTranslator
from .salesforce_sink_py3 import SalesforceSink
from .dynamics_sink_py3 import Dynam... | |
str, slc_type: int, slc_state: int, slc_resource_type: str,
properties, slc_graph_id: str = None, lease_start: datetime = None, lease_end: datetime = None):
"""
Update a slice
@param slc_guid slice id
@param slc_name slice name
@param slc_type slice type
@param slc_state slice state
@param slc_resource_type sli... | |
# -*- coding: utf-8 -*-
"""
flaskbb.cli.commands
~~~~~~~~~~~~~~~~~~~~
This module contains the main commands.
:copyright: (c) 2016 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import sys
import os
import time
import requests
import binascii
from datetime import datetime
import click
fro... | |
216, 1875, 1885, 217, 1876, 1886, 1895,
218, 59, 60, 61, 62, 15, 1613, 2471,
1679, 27, 1623, 3328, 3548, 1689, 2482, 3768,
2603, 1745, 1755, 39, 1632, 3337, 3557, 1698,
3382, 6186, 3602, 3777, 3822, 1764, 2493, 3988,
2614, 3997, 4042, 2724, 1811, 1821, 1830, 51,
1640, 3345, 3565, 1706, 3390, 6194, 3610, 3785,
38... | |
<reponame>aixiwang/iot_data_svr
# -*- coding=gbk -*-
#-----------------------------------------------------------
# Copyright (c) 2015 by <NAME> <<EMAIL>>
#-----------------------------------------------------------
import random, time
import os
import sys
import thread, threading, subprocess
#import mosquit... | |
date_all:
index = line.index(data)
first_line = line[0: index]
sec_line = line[index + len(data):]
# 计算时差,获取目标时间
data = re.sub(r"[个]?小时前", '', data)
hours_delta = int(data)
target_time = now - timedelta(hours=hours_delta)
time_str = '“' + time_to_str(target_time) + "”"
placeholder = random_str()
placeholders_... | |
#!/usr/bin/env python
import numpy as np
import inspect
import functools
from collections.abc import Iterable
from abc import abstractmethod
from dash.development.base_component import Component as DashComponentBase
from dash.development.base_component import ComponentMeta as DashComponentMeta
import dash_bootstrap_c... | |
the idea is we just need to abort the wrapped
function call.
<Side Effects>
A new reference is created to every non-simple type of object. That is,
everything except objects of type str, unicode, int, etc.
<Returns>
The deep copy of obj with circular/recursive references preserved.
"""
try:
# If this is a top-... | |
infer in ["BayesInference","ASIRInference"]:
InferenceObject.drawposteriorexamples ( ax=ax_plot )
plotThres ( InferenceObject, ax=ax_plot )
plotPMF ( InferenceObject, ax=ax_plot, showdesc=True )
if infer in ["BayesInference","ASIRInference"]:
distname = "posterior"
observed = -2*N.log ( InferenceObject.nulleviden... | |
= median(onchip_energy_eff_ug_r_list_u6_wspm + onchip_energy_eff_ug_r_list_u7_wspm + onchip_energy_eff_ug_r_list_u8_wspm)
onchip_energy_eff_ug_r_list_ux_wspm_max = max(onchip_energy_eff_ug_r_list_u6_wspm + onchip_energy_eff_ug_r_list_u7_wspm + onchip_energy_eff_ug_r_list_u8_wspm)
print("unary 256c (baseline) :", onch... | |
draw = ImageDraw.Draw(process)
# puts in background
bg_image = bg_image.resize((85, 105), Image.ANTIALIAS)
bg_image = bg_image.crop((0,0, 85, 105))
result.paste(bg_image, (0,0))
# draw transparent overlay
draw.rectangle([(0, 40), (85, 105)], fill=(30, 30 ,30, 220)) # white portion
draw.rectangle([(15... | |
state_dict[conv_name + '.batch_norm.weight']
offset = state_dict[conv_name + '.batch_norm.bias']
m = state_dict[conv_name + '.batch_norm._mean']
v = state_dict[conv_name + '.batch_norm._variance']
if fpn.coord_conv:
copy_conv_bn(yolo_block.tip.conv, w, scale, offset, m, v, use_gpu)
else:
copy_conv_bn(yolo_block.... | |
>>> import scikitplot.plotters as skplt
>>> rf = RandomForestClassifier()
>>> skplt.plot_learning_curve(rf, X, y)
<matplotlib.axes._subplots.AxesSubplot object at 0x7fe967d64490>
>>> plt.show()
.. image:: _static/examples/plot_learning_curve.png
:align: center
:alt: Learning Curve
"""
if ax is None:
fig, ax ... | |
row_tots=row_tots, col_tots=col_tots, grand_tot=grand_tot,
attach_rlabels=attach_rlabels)
def select_col(self, key, where=None):
"""
determines rows in table that satisfy the conditions given by where and returns
the values of key in the remaining rows
args:
key: column label of data to return
kwds:
where:... | |
#!/usr/bin/env python
import pyami.quietscipy
#builtin
import os
import re
import sys
import time
import subprocess
import glob
from optparse import OptionParser
#appion
from appionlib import basicScript
from appionlib import apParam
from appionlib import apDisplay
from appionlib import apProject
from appionlib impor... | |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing import sequence
from deprecated import deprecated
import os
import numpy as np
f... | |
<filename>xdwlib/basedocument.py
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 fileformat=unix expandtab :
"""basedocument.py -- BaseDocument, base class for Document/DocumentInBinder
Copyright (C) 2010 <NAME> <<EMAIL>> All rights reserved.
This software is subject to the provisions of the Zope Public License... | |
column
if json_file is not None:
# load file and
with open(json_file,'r+') as f:
json_map = json.load(f)
# if no JSON mapping file was specified then create a default one for variable-term mappings
# create a json_file filename from the output file filename
if output_file is None:
output_file = os.path.join(... | |
<reponame>perlmutter/tomopyui
import numpy as np
import copy
import pathlib
from ipywidgets import *
from tomopyui._sharedvars import *
from abc import ABC, abstractmethod
from tomopyui.widgets.view import (
BqImViewer_Projections_Parent,
BqImViewer_Projections_Child,
BqImViewer_Projections_Child,
)
from tomopyui.b... | |
print(best_reward)
# Back-propagate
while node:
node.visits += 1
node.value += sum_reward
node = node.parent
sum_reward = 0
for action in best_actions:
if self.render:
env.render()
_, reward, terminal, _ = env.step(action)
sum_reward += reward
if terminal:
break
env.monitor.close()
toret.ap... | |
GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, POINTER(GLvoid)], None)
# /usr/include/GL/gl.h:1531
glTexSubImage3D = _link_function('glTexSubImage3D', None, [GLenum, GLint, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei, GLenum, GLenum, POINTER(GLvoid)], None)
# /usr/include/GL/gl.h:1538
glCopyTexSubImage3D = _lin... | |
<filename>jnpr/openclos/underlayRestRoutes.py
'''
Created on Sep 2, 2014
@author: moloyc
'''
import os
import bottle
from sqlalchemy.orm import exc
import StringIO
import zipfile
import traceback
import json
import util
import logging
from bottle import error, request, response, PluginError, ServerAdapter
from excep... | |
torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
z = torch.randint(low=-100, high=100, size=(2, 3, 4)).to(dtype)
for dim in range(4):
res = torch.stack((x, y, z), dim)
res_neg = torch.stack((x, y, z), dim - 4)
expected_size = x.size()[:dim] + (3,) + x.size()[dim:]
self.assertEqual(res, res_neg)
self.a... | |
"""
File contains the groovy scripts used by Nexus 3 script api as objects
that may be used in the nexus3 state module.
I put these here as it made it easy to sync the groovy with the module itself
"""
create_blobstore = """
import groovy.json.JsonSlurper
parsed_args = new JsonSlurper().parseText(args)
existingBlob... | |
import json
import os
import time
import re
import asyncio
import async_timeout
import aiohttp
import aiofiles
import aiodns
import aiobotocore
import sys
import logging
from time import mktime, strptime
from datetime import datetime, timedelta
ACCESS_LOG_NAME="edgex_access"
MAX_SINGLE_OBJ=5* 1024 * 1024 * 1024 #... | |
<filename>reddit_user.py
# -*- coding: utf-8 -*-
import csv
import datetime
import re
import json
import time
import sys
import calendar
from collections import Counter
from itertools import groupby
from urlparse import urlparse
import requests
import pytz
from subreddits import subreddits_dict, ignore_text_subs, de... | |
item in self.celldefs
if item["name"] == cellname
)
except Exception:
celldef = None
else:
newpad["iolib"] = celldef["iolib"]
newpad["width"] = celldef["width"]
newpad["height"] = celldef["height"]
newpad["class"] = celldef["class"]
newpad["subclass"] = celldef["subclass"]
newpad["x"] = float(placex) / floa... | |
x1 x2
print ('OP_2DUP')
val1 = stack[-2] # x1
val2 = stack[-1] # x2
stack.append(val1) # x1 x2 x1
stack.append(val2) # x1 x2 x1 x2
elif code == OP_3DUP: # x1 x2 x3
print ('OP_3DUP')
val1 = stack[-3] # x1
val2 = stack[-2] # x2
val2 = stack[-1] # x3
stack.append(val1) # x1 x2 x3 x1
stack.append(val2) # x1 x2 ... | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# ======================================================================================================================== #
# Project : Explainable Recommendation (XRec) #
# Version : 0.1.0 #
# File : \criteo.py #
# Language : Python 3.8 #
# -------------------------------... | |
},
bases=('gedungbangunan.skpdasalgedungbangunan',),
),
migrations.CreateModel(
name='SKPDAsalGedungBangunanDPKP',
fields=[
],
options={
'verbose_name': '40 SKPD Asal Gedung DPKP',
'proxy': True,
'verbose_name_plural': '40 SKPD Asal Gedung DPKP',
},
bases=('gedungbangunan.skpdasalgedungbangunan',),
),
mig... | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
# Gameboard Discord Bot
# - Grant "Gmanicus" Scrits at Geek Overdrive Studios
# Thanks for checking out my code.
# Pinterest library
from py3pin.Pinterest import Pinterest
# Libraries for parsing
import json
from parse import *
import play_scraper
import requests... | |
group.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or
server error without risk of executing that same action again. Retry tokens expire after 24
hours, but can be invalidated before then due to conflicting operations (e.g., if a resou... | |
np.sum(samples1 == 1)
seen_pixels[1] += np.sum(samples2 == 1)
assert seen_components[0] < seen_components[1]
assert seen_pixels[0] / seen_components[0] > seen_pixels[1] / seen_components[1]
# different sizes in percent, given as StochasticParameter
param1 = iap.FromLowerResolution(iap.Binomial(0.5), size_percent... | |
from __future__ import absolute_import
import __builtin__
import re
from textwrap import dedent
from assemblyline.common.charset import translate_str
from assemblyline.al.common.heuristics import Heuristic
from assemblyline.al.common.result import Result, ResultSection, SCORE
from assemblyline.al.common.result import... | |
(Sequence[EvaluatableNode]) -> EvaluatableNode
return Struct(self.type_, new_children)
def _evaluate_node(self, values):
# type: (List[TypedSeries]) -> TypedSeries
value_types = [value.type_ for value in values]
type_ = implicitly_coerce(self.type_, BQStructType([None] * len(values), value_types))
if self.type_:... | |
<filename>Packs/AzureSQLManagement/Integrations/AzureSQLManagement/AzureSQLManagement.py
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
import urllib3
import copy
# Disable insecure warnings
urllib3.disable_warnings()
''' CONSTANTS '''
DATE_FORMAT = '%Y-%m-%dT%H:... | |
accessrule_identifier = 'testString'
# Invoke method
response = service.get_account_access_rule(
accessrule_identifier,
headers={}
)
# Check for correct operation
assert len(responses.calls) == 1
assert response.status_code == 200
#--------------------------------------------------------
# test_get_accoun... | |
<filename>scripts/functions.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from tqdm import tqdm
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm
from sklearn.neighbors import KNeighborsRegressor
from sk... | |
value):
"""
The SNMP Write Community String is like a password. It is sent along with each SNMP Set-Request and allows (or denies) chaning MIBs values.
:type value: string
"""
self.attributes['ApV2.SNMP Write Community'] = value
@property
def snmp_v3_user(self):
"""
:rtype: str
"""
return self.attributes['A... | |
# Copyright (c) 2016 Baidu, 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 ag... | |
import numpy as np
import xarray as xr
from . import Tidegauge, general_utils
import matplotlib.dates as mdates
import utide as ut
import scipy.signal as signal
from coast import stats_util, crps_util
class TidegaugeAnalysis:
"""
This contains analysis methods suitable for use with the dataset structure
of Tidegau... | |
MangadexClient
"""
with open(file_name, "r", encoding="utf-8") as file:
data = load(file)
username = data.get("username", None)
password = data.get("password", None)
refresh_token = data.get("refresh_token", None)
api_url = data.get("api_url", DEFAULT_API_URL)
anonymous = cls._boolean(str(data.get("anonymous", ... | |
"""
This module provides PKCS#11 integration for pyHanko, by providing a wrapper
for `python-pkcs11 <https://github.com/danni/python-pkcs11>`_ that can be
seamlessly plugged into a :class:`~.signers.PdfSigner`.
"""
import asyncio
import binascii
import logging
from typing import Optional, Set
from asn1crypto import x5... | |
import warnings
import networkx as nx
import numpy as np
import scipy.sparse as sp
from sklearn import metrics
class DataUtils:
def __init__(self, graph_file):
with np.load(graph_file, allow_pickle=True) as loader:
loader = dict(loader)
self.A = sp.csr_matrix((loader['adj_data'], loader['adj_indices'],
loader['a... | |
<gh_stars>1000+
#On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah <NAME>.
#Author : <NAME>
#Date : 07/03/09
#version :2.6.1
"""
collections module's extras in python 2.6.1 were used in my program, DVMextrapolating
DVMgordonsModel and CAPM subclasses of namedtuple Python cla... | |
#!/usr/local/bin/python3.8
__author__ = "<NAME>"
__credits__ = ["ivosh", "laura"]
__version__ = "1.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "production"
__dev_version__ = "v1"
__spec__= "GaiaAPI connector"
import requests
import urllib3
import json
import sys
import time
import getpass
import ... | |
* np.dot(lam_top.T, lam_bottom)
else:
return s
def cpd_symmetrize(factors, permdict, adjust_scale=True, weights=None):
"""
Produce a symmetric CPD decomposition.
:param factors: CPD factors
:param permdict: dictionary of tuple: tuple pairs.
keys are tuples containing the permutation
values are tuples of any o... | |
31, 16, 876, 532],
[706, 99, 684, 613, 93, 504, 584, 599, 513, 638,
645, 334, 448, 148, 802, 805, 255, 759, 176],
[262, 671, 68, 389, 36, 561, 104, 285, 968, 896,
20, 912, 215, 161, 564, 476, 828, 815, 331],
[74, 29, 857, 758, 382, 578, 150, 745, 684, 558,
384, 439, 118, 599, 779, 378, 816, 996, 206],
[83, 545, ... | |
if ``pn`` is close to 1, this approximation gives
incorrect results.
Here we calculate this probability by inverting the Binomial
problem. Given that (see ``p_multitrial_from_single_trial``)
the probability of getting more than one hit in n trials,
given the single-trial probability *p*, is
.. math ::
P (k \g... | |
ChanX = ['_']*self.chanx_len
_ = [self._set_bit(ChanX, e.attrib['index'])
for e in chan.findall('./driver_node[@type="CHANX"]')]
ChanY = ['_']*self.chany_len
_ = [self._set_bit(ChanY, e.attrib['index'])
for e in chan.findall('./driver_node[@type="CHANY"]')]
flags = ChanX if side in ['top', 'bottom'] else ChanY
a... | |
3:
print("This projection does not calculate that axis, using qr/(sqrt(h^2+k^2)) instead")
xRoiData=self.ctrROI.getArrayRegion(self.grid_qx, self.imgLeft)
#axis = qr
elif self.p.param('Profile tools', 'Axis of interest').value() == 3:
#h-k
if projection == 0:
xRoiData=self.ctrROI.getArrayRegion(self.gr... | |
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import itertools
import re
from copy import copy
from powerline.lib.unicode import unicode
from powerline.lint.markedjson.error import echoerr, DelayedEchoErr, NON_PRINTABLE_STR
from powerline.lint.self... | |
<filename>speakeasy/winenv/api/kernelmode/wdfldr.py
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved.
import uuid
import speakeasy.winenv.arch as e_arch
import speakeasy.winenv.defs.nt.ddk as ddk
import speakeasy.winenv.defs.wdf as wdf
import speakeasy.winenv.defs.usb as usbdefs
import speakeasy.winenv.defs.nt... | |
#!/usr/bin/env python
import argparse
import concurrent.futures
import logging
import os
import re
import threading
import time
import cv2
import numpy as np
import tensorboardX
import torch
from scipy import ndimage
from robot import SimRobot
from trainer import Trainer
from utils import utils, viz
from utils.logge... | |
for zero-based stress period indices. For example, ["rch.rech",[0,4,10,15]]
would setup constant (uniform) multiplier parameters for recharge for stress
period 1,5,11,and 16.
temporal_list_props ([[`str`,[`int`]]]): list-type input stress-period level multiplier parameters.
A nested list of list-type input elements... | |
import bisect
import collections
import os
import queue
import random
import subprocess
import threading
import time
import traceback
from hydrus.core import HydrusData
from hydrus.core import HydrusExceptions
from hydrus.core import HydrusGlobals as HG
NEXT_THREAD_CLEAROUT = 0
THREADS_TO_THREAD_INFO = {}
THREAD_INF... | |
= [n for n in list(parallel.sub) if n.kind == 'Reversed'][0]
nets['lstm2'] = rev.sub[0]
hidden = int(nets['lstm1'].attribute[0].value)
weights = {} # type: Dict[str, torch.Tensor]
for n in nets:
weights[n] = {}
for w in list(nets[n].weights):
weights[n][w.name] = torch.Tensor(w.value).view(list(w.dim))
if mo... | |
ML_SSE_m128_v4float32),
type_strict_match(*(3*(ML_SSE_m128_v2float64,))):
XmmIntrin("_mm_or_pd", arity = 2,
output_precision = ML_SSE_m128_v2float64),
},
},
},
Conversion: {
None: {
lambda _: True: {
# not supported in SSE (else fallback on generic erroneous
# implementation)
type_strict_match(ML_Int32, ML_... | |
- start_t))
if not self.it in dset.iterations:
raise ValueError("it: {} is missing in dset for v_n: {}\n{}"
.format(self.it, key, dset.iterations))
# saving data for iteration
outfname = self.outpath + str(self.it) + '_' + key + ".h5"
dfile = h5py.File(outfname, "w")
if self.description is not None:
dfile.cr... | |
# -*- coding: utf-8 -*-
import logging
import numpy as np
import torch
from torch import nn
from ..layers import TextEncoder, ImageEncoder, VectorDecoder
from ..layers import FeatureEncoder, MaxMargin, FF
from ..layers import BiLSTMp
from ..layers import SimpleGRUDecoder, ConditionalDecoder, ZSpaceAtt
from ..utils.mi... | |
<filename>pde/tools/parameters.py
"""
Infrastructure for managing classes with parameters
One aim is to allow easy management of inheritance of parameters.
.. autosummary::
:nosignatures:
Parameter
DeprecatedParameter
HideParameter
Parameterized
get_all_parameters
.. codeauthor:: <NAME> <<EMAIL>>
"""
import ... | |
"""peewee-validates is a validator module designed to work with the Peewee ORM."""
import datetime
import re
from decimal import Decimal
from decimal import InvalidOperation
from inspect import isgeneratorfunction
from inspect import isgenerator
from collections import Iterable
import peewee
from dateutil.parser impo... | |
< len(target)-1:
self.bytecodes.append(bytecode.dup())
self.bytecodes.append(bytecode.pushbyte(idx))
self.bytecodes.append(bytecode.getproperty(
abc.MultinameL(abc.NamespaceSetInfo(abc.NSPackage('')))))
self.do_assign(node)
else:
raise NotImplementedError(target)
def do_assign(self, target):
with self.assign(... | |
from tkinter import *
from tkinter import ttk
import numpy as np
import io
import base64
from PIL import ImageTk, Image
import requests
import os
import matplotlib
from matplotlib import image as mpimg
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
url = "http://vcm-9111.vm.duke.edu:5000/"
# url = "ht... | |
Qualifier='string'
)
:type FunctionName: string
:param FunctionName: [REQUIRED]\nThe name of the Lambda function, version, or alias.\n\nName formats\n\nFunction name - my-function (name-only), my-function:v1 (with alias).\nFunction ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function .\nPartial ARN -... | |
from django.shortcuts import render, get_object_or_404
from blog.models import Post, Comment
from users.models import Follow, Profile
import sys
from django.contrib.auth.models import User
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins imp... | |
<filename>apps/content/views.py
from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import (
ListAPIView,
ListCreateAPIView,
ListAPIView,
RetrieveUpdateAPIView,)
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from re... | |
1
def notify_gen_regvar_def(self, canon, user, cmt):
"""
generate register variable definition line
args:
canon - canonical register name (case-insensitive)
user - user-defined register name
cmt - comment to appear near definition
returns: 0-ok
"""
return 1
def notify_setsgr(self, start_ea, end_ea, regnum,... | |
"""
with pytest.raises(vtq.QueryInitError) as excinfo:
query = vtq.Query(
coords=SkyCoord('00h42.5m', '+41d12m'),
source_names=['test', 'test2'],
)
assert str(excinfo.value).startswith(
"The number of entered source names"
)
def test_init_failure_invalid_planet(self) -> None:
"""
Tests the initialisation f... | |
| x-tcp:// | DB-dialect+driver://. "
"For empty scheme, params are a file path with '-' meaning standard output. "
"For x-tcp scheme, params are TCP host[:port=14380]. "
"For DB, use SQLAlchemy engine URL. "
"(default=sqlite:///<dagman-output-file>.stampede.db)",
default=None,
)
grp.add_option(
"-e",
"--encoding... | |
with negative, (n)empty, not empty",
"expected_options": ["empty,not empty"],
"expected_negatives": ["empty"],
"expected_lca_count": 1,
},
)
@ddt.unpack
def test_negative_lca_create(self, lca_to_import, expected_options,
expected_negatives, expected_lca_count):
"""Test LCA with negative options is created when... | |
<reponame>jiosue/PythonGames
# -*- coding: utf-8 -*-
""" Robot Vacuum Cleaner """
from collections import deque
import random
import os
if os.sys.version_info.major > 2:
xrange = range
import tkinter as tk
else:
import Tkinter as tk
#### METHODS ####
def scale_vector(vector, velocity):
"""
Cr... | |
self.halfedges
f = H[:,1]
vi = H[:,0]
vj = H[H[:,2],0]
if order:
i = self.face_ordered_halfedges()
f = f[i]
vi = vi[i]
vj = vj[i]
else:
i = np.where(H[:,1] >= 0)[0]
f = f[i]
vi = vi[i]
vj = vj[i]
if sort:
i = np.argsort(f)
vi = vi[i]
vj = vj[i]
return f, vi, vj
def face_vertices_iterators(self):
H ... | |
"""
The ``util`` module is used to contain utility functions and classes that have
practical utility within the context of this application but which could
conceivably be co-opted to serve in a different context for a different
application if needed. As such, there are no hardcoded magic numbers or any such
application... | |
# MINLP written by GAMS Convert at 04/21/18 13:52:24
#
# Equation counts
# Total E G L N X C B
# 1499 337 504 658 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 1009 673 336 0 0 0 0 0
# FX 7 7 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 4423 3943 480 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.