input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method symbol_assign_disk_pool_ownership" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'system_id' is set
if ('system_id' not in params) or (params['system_id'] is None):
raise ValueError("Missing the required... | |
fifth and sixth are alpha3.
energy_alpha_simulation = compute_energy_array(data, "alpha", "end", m_a)
z_alpha = data["alpha_z_end"]
# Loop over all slices (i.e. cells in the z direction)
for slice_number in range(1, size_z):
## Kinetic energy in the lab frame before fusion
E_kinetic_com_before = E_com[slice_num... | |
from __future__ import division
import sys
import os
sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True
__author__ = "COSAL"
from mos.search.cacher import tfidf_cache
from mos.search_store.code_store import CodeStore, ASTDistanceStore, ExecStore
from mos.search_store.elastic_store import ContextSto... | |
in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
def forward(self, X):
h_relu1 = self.slice1(X)
h_relu2 = self.slice2(h_relu1)
h_relu3 = self.slice3(h_relu2)
h_relu4 = self.slice4(h_relu3)
h_relu5 = ... | |
target, source, env):
"""
In python 3, and in some of our tests, sys.stdout is
a String io object, and it takes unicode strings only
This code assumes s is a regular string.
"""
sys.stdout.write(s + "\n")
def __call__(self, target, source, env,
exitstatfunc=_null,
presub=_null,
show=_null,
execute=_null,
c... | |
"""Python3 Steven
common proability distrubution
"""
import os
import numpy as np
import matplotlib.pyplot as plt
# from sympy import integrate
# import math
# from scipy.special import gamma,beta,factorial
# from permutationAndCom import permut,combinat
from distributions import *
from plotCommon import plotSub, scatt... | |
title, year, imdb, tvdb, season,
episode, tvshowtitle, localtvshowtitle, aliases, premiered, i[0], i[1]))
s = [i[0] + (i[1],) for i in zip(sourceDict, threads)]
s = [(i[3].getName(), i[0], i[2]) for i in s]
mainsourceDict = [i[0] for i in s if i[2] == 0]
sourcelabelDict = dict([(i[0], i[1].upper()) for i in s])
... | |
of times that this couple occurs, and the state of the
couple.
Raises
------
TypeError
If any of the required arguments is missing
"""
cursor = self.db.cursor()
if state is not None:
cursor.execute(state_query, (repo_url, state))
else:
cursor.execute(query, (repo_url,))
return cursor.fetchall()
def updat... | |
<gh_stars>0
from __future__ import unicode_literals
import uritemplate
import wac
from balanced import exc, config, utils
registry = wac.ResourceRegistry(route_prefix='/')
class JSONSchemaCollection(wac.ResourceCollection):
@property
def href(self):
return self.uri
class ObjectifyMixin(wac._ObjectifyMixin):... | |
fill. If `True`, fill all
possible fields.
Each event will have the data filled for the intersection
of it's external keys and the fields requested filled.
Default is False
handler_registry : dict, optional
mapping asset specs (strings) to handlers (callable classes)
Yields
------
event : Event
The event,... | |
'''
Script with all sampling methods.
Computation of effective sampling size from:
https://github.com/jwalton3141/jwalton3141.github.io
following definition from:
ref Gelman, Andrew, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>. 2013. Bayesian Data Analysis. Third Edition. London: Chapman & Hall / CRC Press.
'''
impor... | |
description = """a module that holds helper functions for the injection simulations and subsequent skymap analysis"""
authors = "<NAME> (<EMAIL>), <NAME> (<EMAIL>)"
#-------------------------------------------------
import numpy as np
import healpy as hp
import astropy
from astropy.time import Time as astropyTime
fr... | |
# Copyright 2003-2008 by <NAME>. All rights reserved.
# Revisions copyright 2008-2017 by <NAME>.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of t... | |
<gh_stars>1-10
'''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 2B of Nirikshak Bot (NB)... | |
be the same length as
the length of `data` and each element will be applied to each shape
otherwise the same value will be used for all shapes.
opacity : float | list
Opacity of the shapes, must be between 0 and 1.
z_index : int | list
Specifier of z order priority. Shapes with higher z order are
displayed ontop... | |
@mock.patch('requests.request')
def test_get_target_info_by_initiator_negative(
self,
mock_request):
"""Test get target info by initiator."""
mock_request.side_effect = ([
FakeLoginResponse(),
FakeGetBasicInfo114Response(),
FakeLoginResponse(),
FakeNoAuthPassedResponse()] + [
FakeLoginResponse(),
FakeNoAuthP... | |
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""
This is an implementation of a state-emitting MarkovModel. I am using
terminology similar to Manning and Schutze.
Functions:
train_bw Train a ma... | |
<filename>tests/integration/sts/topology/graph_test.py
# Copyright 2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | |
False
# -------------------------------------------------------------------------
def as_dict(self, options=None):
sublayers = self.sublayers
if sublayers:
sublayer = sublayers[0]
name = s3_str(current.T(sublayer.name))
name_safe = re.sub("'", "", name)
ldict = {"name": name_safe,
"id": sublayer.layer_id,
}... | |
"linkType" : int(stringArray[6])
}
else:
postFieldsDictBacktrackQuery = {
"originEntityID" : entityID1,
"query" : stringArray[4]
}
request = Request(url=queryURL, data=bytes(json.dumps(postFieldsDictBacktrackQuery), encoding='utf-8'))
backtrackQueryResponse = urlopen(request).read().decode('utf8')
try... | |
<filename>ding/framework/task.py<gh_stars>0
from asyncio import InvalidStateError
from asyncio.tasks import FIRST_EXCEPTION
import time
import asyncio
import concurrent.futures
import fnmatch
import math
from types import GeneratorType
from typing import Any, Awaitable, Callable, Generator, Iterable, List, Optional, Se... | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'ar'
import os
import sys
import glob
import time
import json
try:
import cPickle as pickle
except:
import pickle
import matplotlib.pyplot as plt
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten, Convolution... | |
if param_labels is None:
param_labels = ['', '']
tmp = [[params, mean_score, scores.std()]
for parameters, mean_score, scores in grid_scores.grid_scores_]
param, means, stddev = list(zip(*tmp))
param_range_0 = grid_scores.param_grid[params[0]]
param_range_1 = grid_scores.param_grid[params[1]]
mat_size = (len(par... | |
"98",
"name": "MediumPurple3",
"hex": "#875fd7",
"rgb": "rgb(135,95,215)",
"hsl": "hsl(260,60%,60%)"
},
"99": {
"term": "99",
"name": "SlateBlue",
"hex": "#875fff",
"rgb": "rgb(135,95,255)",
"hsl": "hsl(255,100%,68%)"
},
"100": {
"term": "100",
"name": "Yellow7",
"hex": "#878700",
"rgb": "rgb(135,135,0... | |
<reponame>Official-CalcOS/CalcOS-1.1
import math
from math import sqrt
import statistics
import time
import os
import webbrowser
print("© 2020 - 2021 CalcOS by <NAME>. All Rights Reserved.")
time.sleep(2)
clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
print("Searching for OS")... | |
# -*- coding: utf-8 -*-
"""Implementation of the ``wgs_sv_calling`` step
The (germline) ``wgs_sv_calling`` step takes as the input the results of the ``ngs_mapping`` step
(aligned NGS reads) and performs germline SV calling on them. The result are called SVs in VCF
format.
In contrast to WGS CNV calling, WGS SV calli... | |
history. Instead, /etc/apt/trusted.gpg.d is used directly to drop
# gpg
key_asc = _get_key_by_keyid(key)
# write the key in GPG format so that apt-key list shows it
key_gpg = _dearmor_gpg_key(key_asc)
_write_apt_gpg_keyfile(key_name=key, key_material=key_gpg)
def _get_keyid_by_gpg_key(key_material):
"""Get a GP... | |
# Copyright 2020, 2021 Emory University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | |
<filename>FinsterTab/W2020/DataForecast.py
# import libraries to be used in this code module
import pandas as pd
from statsmodels.tsa.arima_model import ARIMA
from sklearn.ensemble import RandomForestRegressor
from sklearn.svm import SVR
from math import sqrt
from statistics import stdev
import numpy as np
import xgboo... | |
#!/usr/bin/env python3
"""
Copyright::
+===================================================+
| © 2021 Privex Inc. |
| https://www.privex.io |
+===================================================+
| |
| Python PIP Wrapper Library |
| License: X11/MIT |
| Repo: https://github.com/Privex/pipwrapper |
| |
| C... | |
from expression.abstract_expression import ExpressionType
from expression.comparison_expression import ComparisonExpression
from expression.constant_value_expression import ConstantValueExpression
from query_planner.logical_projection_plan import LogicalProjectionPlan
from query_planner.logical_inner_join_plan import L... | |
<reponame>malneni/cantools
# Load and dump a CAN database in SYM format.
import collections
from itertools import groupby
import re
import logging
from collections import OrderedDict as odict
from decimal import Decimal
from typing import Callable, Iterator, List, Optional as TypingOptional
import textparser
from tex... | |
"""
Implement the small version of NASBench dataset for Monodepth estimation
"""
import functools
# import pandas as pd
# from peewee import CharField, FloatField, ForeignKeyField, IntegerField, Model
from peewee import fn
from playhouse.sqlite_ext import SqliteExtDatabase
from playhouse.shortcuts import model_to_d... | |
<reponame>santanshy/GamestonkTerminal<gh_stars>1-10
import argparse
import datetime
import os
import traceback
from warnings import simplefilter
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters
from TimeSeriesCrossValidation import splitTr... | |
<reponame>Zamwell/pandapower
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2019 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import functools
import os
from time import time
import numpy as np
import pandas as pd
try:
import ... | |
['basicAuth'] # noqa: E501
return self.api_client.call_api(
'/platform/3/snapshot/schedules', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='CreateSnapshotScheduleResponse', # noqa: E501
auth_settings=auth_settings,
async_re... | |
""" Module for finding patterns in arc line spectra
.. include common links, assuming primary doc root is up one directory
.. include:: ../include/links.rst
"""
import numpy as np
import inspect
from astropy.io import fits
from pypeit.core.wavecal import autoid
from pypeit.core.wavecal import defs
from pypeit.core ... | |
Expression(self, valid_name))
self._initialize_column(valid_name)
def _initialize_column(self, name):
self._save_assign_expression(name)
def _sparse_matrix(self, column):
column = _ensure_string_from_expression(column)
return self._sparse_matrices.get(column)
def add_columns(self, names, columns):
from scipy... | |
not allowed.
"""
return pulumi.get(self, "topology_key")
@property
@pulumi.getter(name="labelSelector")
def label_selector(self) -> Optional['outputs.DatadogAgentSpecClusterChecksRunnerAffinityPodAntiAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTermLabelSelector']:
"""
A label query over a ... | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import math
from multiprocessing import Array, Value
from numbers import Number
import numpy as np
from scipy import linalg
from six import string_types
from sklearn.decomposition import PCA, IncrementalPCA
from sklea... | |
"""
<abs> ::= D_i^t | NonD
NonD ::= S_o^ [<NonD>*]
| Top
| Bot
"""
from __future__ import annotations
from typing import (
Union,
Callable,
Optional,
Iterable,
Sequence,
TypeVar,
Type,
NamedTuple,
TYPE_CHECKING,
cast,
)
from collections import defaultdict, OrderedDict
from contextlib import contextmanager
... | |
<reponame>PhanterJR/www_sme
import phanterpwa.frontend.helpers as helpers
import phanterpwa.frontend.components.widgets as widgets
import phanterpwa.frontend.forms as forms
import phanterpwa.frontend.components.modal as modal
import phanterpwa.frontend.preloaders as preloaders
from org.transcrypt.stubs.browser import _... | |
import base64
import json
import logging
import os
import pathlib
import re
import subprocess
import tempfile
import warnings
from collections import defaultdict
from typing import Dict, List, Optional, Set, Tuple
import backoff
import google.auth
import google.auth.exceptions
import google.auth.transport.requests
imp... | |
<reponame>nicproulx/mne-python
import os
import os.path as op
import shutil
import glob
import warnings
import numpy as np
from scipy import sparse
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_equal, assert_true, assert_false, assert_raises
from mne.datasets i... | |
#!/usr/bin/env python2.7
import getpass
import logging
import os
import re
import sys
from abc import ABCMeta, abstractmethod, abstractproperty
from collections import defaultdict, namedtuple, OrderedDict
from textwrap import dedent
from generation_context import GenerationContext
from generation_utils import Generat... | |
#!/usr/bin/env python
import os
import re
import sys
import logging
from collections import namedtuple, OrderedDict, Iterable
from functools import partial
if sys.version_info.major >= 3:
from inspect import signature
else:
from funcsigs import signature
logger = logging.getLogger('map_folder_structure')
# ====... | |
<filename>scopy/ScoRepresent/pubchem.py
# -*- coding: utf-8 -*-
#Created on Wed Jul 17 10:15:43 2019
#
#@Author: <NAME>, <NAME>
#@Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China
#@Homepage: http://www.scbdd.com
#@Mail: <EMAIL>; <EMAIL>
#@Blog: https://blog.moyule.me
import os
from rdkit... | |
# -*- coding: utf-8 -*-
"""
@file
@brief Quelques questions d'ordre général autour du langage Python.
"""
import os
import io
import re
def entier_grande_taille():
"""
.. faqref::
:tag: python
:title: Quel est l'entier le plus grand ?
La version 3 du langage Python a supprimé la constante ``sys.maxint``
qui... | |
<reponame>Tehsurfer/mapclientplugins.meshgeneratorstep
"""
Created on Aug 29, 2017
@author: <NAME>
"""
import types
from threeWrapper import BlackfynnGet
from PySide import QtGui, QtCore
from functools import partial
from mapclientplugins.meshgeneratorstep.model.fiducialmarkermodel import FIDUCIAL_MARKER_LABELS
fr... | |
method='sidak', alpha=DEFAULT_ALPHA):
if method not in set(list(CORRECTIONS.keys()) + list(CORRECTIONS.values())):
raise ValueError('Correction method {!r} not supported'.format(method))
self.method = CORRECTIONS[method] if method in CORRECTIONS else method
self.alpha_orig = alpha
self.alpha_corrected = eval(self... | |
of the IoTHub.
:param iothub_transport_provider: Transport protocol used to connect to IoTHub
:type iothub_transport_provider: IoTHubTransportProvider(Enum)
:param iothub_name: The IoT Hub name to which the device is connecting
:type iothub_name: str
:param iothub_suffix: The suffix part of the IoTHub uri (e.g., ... | |
= os.path.join(folder, 'SocialCareByClassStackedBarChart.pdf')
pp = PdfPages(path)
pp.savefig(fig)
pp.close()
# Chart 26: informal and formal social care received and unmet social care needs per recipient by social class (mean of last 20 years)
fig, ax = plt.subplots()
p1, = ax.plot(output['year'], ou... | |
:rtype: :class:`bool`
"""
return (rack_position.row_index < (self.number_rows) and
rack_position.column_index < (self.number_columns))
def __len__(self):
"""
The number of positions for this rack shape.
"""
return self.number_rows * self.number_columns
def __eq__(self, other):
"""
Equality is based on the ... | |
ns = GetWsdlNamespace(info.version)
method = _SetWsdlMethod(ns, info.wsdlName, mm)
if method != mm:
raise RuntimeError(
"Duplicate wsdl method %s %s (new class %s vs existing %s)" % \
(ns, info.wsdlName, mm.info.type, method.info.type))
dic[mWsdl] = mm
dic[mName] = mm
name = vmodlName
result = _AddType(LazyTyp... | |
<reponame>vddesai1871/oppia
# coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | |
"""show_spanning_tree.py
supported commands:
* show spanning-tree detail
* show spanning-tree mst detail
* show spanning-tree summary
* show errdisable recovery
* show spanning-tree
* show spanning-tree mst <WORD>
* show spanning-tree vlan <WORD>
* show spanning-tree mst configuration
"""
import re
from geni... | |
<filename>hintgen/astTools.py
import ast, copy, pickle
from .tools import log
from .namesets import *
from .display import printFunction
def cmp(a, b):
if type(a) == type(b) == complex:
return (a.real > b.real) - (a.real < b.real)
return (a > b) - (a < b)
def tree_to_str(a):
return repr(pickle.dumps(a))
def str... | |
<gh_stars>10-100
import os
import os.path
import csv
import re
def words(filename):
f = open(os.path.join("data", "rectangle_raw", filename), "r")
for line in f:
for word in line.split():
yield word
def write_dict(dic, filename):
p = os.path.join("data", "rectangle", filename.replace(" ", "_"))
d = os.path.di... | |
math.exp(
-(X / 2 * (z_co / z_counter) ** 2)
/ (X + abs(z_co * z_counter) * xi * (nu_co + nu_counter))
)
elif xi < xi_critical:
common_factor = -(xi * X / 2) / (
X * abs(z_counter) + (nu_counter * z_counter ** 2 + nu_co * z_co ** 2)
)
gamma_counter = math.exp(common_factor * z_counter ** 2)
gamma_co = math.ex... | |
5.1.2
**License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
"""
self._set_all_groups_to_plane(plane)
def set_all_new_groups_to_plane(self, plane):
"""
Set all groups that are not in any plane to this plane
:param plane: Plane Inde... | |
restated restatement restatements
restates restating restaurateur restaurateurs restfully restfulness
restively restiveness restock restocked restocking restocks
restorative restoratives restorer restorers restrictively restroom
restrooms restructurings restudied restudies restudy restudying
resupplied resupplies resup... | |
# -*- coding: utf-8 -*-
#
# inventory/categories/api/tests/test_categories_api.py
#
from django.contrib.auth import get_user_model
from rest_framework.reverse import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from inventory.categories.models import Category
from inventory.c... | |
# import XML libraries
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import HTMLParser
# Function to create an XML structure
def make_problem_XML(
problem_title='Missing title',
problem_text=False,
label_text='Enter your answer below.',
description_text=False,
answers=[{'correctness': 'true... | |
1)
self.gridLayout_10.addWidget(self.jointAxisGroup_3, 0, 0, 1, 2)
self.analogGB_3 = QtWidgets.QGroupBox(self.joint3tab)
self.analogGB_3.setObjectName("analogGB_3")
self.gridLayout_118 = QtWidgets.QGridLayout(self.analogGB_3)
self.gridLayout_118.setContentsMargins(8, 8, 8, 8)
self.gridLayout_118.setSpacing(5)
se... | |
import re
import uuid
import json
class MagicTrait:
'An inventory of magical data references'
def __delattr__(self, name):
'Processes delete properties'
self.__delitem__(name)
def __delitem__(self, key):
'Deletes the item accessed like an array'
# if it exists
if key in self.__dict__.keys():
#remove it
del... | |
validate=dict(json={'target': 'active'})),
dict(method='GET',
uri=self.get_mock_url(
resource='nodes',
append=[self.fake_baremetal_node['uuid']]),
json=self.fake_baremetal_node),
])
self.assertRaises(
exc.OpenStackCloudException,
self.cloud.node_set_provision_state,
self.fake_baremetal_node['uuid'],
'active... | |
"""This module hosts unit tests for the cli."""
import os
from pathlib import Path
import sys
from unittest.mock import MagicMock
from click.testing import CliRunner
from docker.errors import ImageNotFound
import paramiko
import pytest
from yaml.composer import ComposerError
from build_magic import __version__ as ve... | |
<filename>controllerClass.py
# coding=utf-8
import os
import re
import time
import socket
import inspect
import threading
import subprocess
import logger
gsmThreadName = 'gsmReceptor'
gprsThreadName = 'gprsReceptor'
wifiThreadName = 'wifiReceptor'
emailThreadName = 'emailReceptor'
ethernetThreadName = 'ethernetRece... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from .neural_blocks import (
SkipConnMLP, UpdateOperator, FourierEncoder, PositionalEncoder, NNEncoder
)
from .utils import (
dir_to_elev_azim, autograd, sample_random_hemisphere, laplace_cdf, load_sigmoid,
)
import src.refl as refl
fro... | |
<filename>nemo/collections/tts/helpers/common.py<gh_stars>0
# Copyright (c) 2022, NVIDIA CORPORATION. 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.apach... | |
machine_name: name of machine
Returns:
true if there has been a pole slip at machine
"""
var = "outofstep"
pole_var = self.result.loc[:, (machine_name, var)].values
pole_slip = False
if np.count_nonzero(pole_var) > 0:
pole_slip = True
return pole_slip
def get_rotor_angles_static(self, machine_names=None):... | |
<reponame>mehak151/unfurl
#!/usr/bin/env python
# Copyright (c) 2020 <NAME>
# SPDX-License-Identifier: MIT
"""
Applies a Unfurl ensemble
For each configuration, run it if required, then record the result
"""
from __future__ import print_function
from .job import runJob
from .support import Status
from . import __vers... | |
"""
Base BZT classes
Copyright 2019 BlazeMeter 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 applicable law or agreed to in w... | |
import pandas, numpy
import functools
from plotly import graph_objs as go
from plotly.subplots import make_subplots
X_FIGURE_BUFFER = 0.03
from ...viz import colors, _pick_color
from ... import styles
import logging
_logger = logging.getLogger('EMAT.explore')
def _y_maximum(fig):
return sum(t.y for t in fig.selec... | |
3 9
4 4 16
5 5 25
6 6 36
7 7 49
8 8 64
9 9 81
>>> dff = df[df.x<=2]
>>> dff
# x y
0 0 0
1 1 1
2 2 4
>>> dff = dff.filter(dff.x >=7, mode="or")
>>> dff
# x y
0 0 0
1 1 1
2 2 4
3 7 49
4 8 64
5 9 81
"""
df = self.copy()
df.select(expression, name=FILTER_SELECTION_NAME, mode=mode)
df._cached_filter... | |
hresult = SCardIntroduceCardType(hcontext, znewcardName,
znewcardPrimGuid, znewcardPrimGuid + znewcardSecGuid,
znewcardATR, znewcardMask)
if hresult != SCARD_S_SUCCESS:
raise error, 'Failed to introduce card type: ' + SCardGetErrorMessage(hresult)
...
"""
return _scard.SCardIntroduceCardType(hcontext, cardname... | |
from time import sleep
from functools import wraps, partial
import logging
from pydbus import SystemBus, Variant
from .bzutils import BluezInterfaceObject
from .object_manager import BluezObjectManager
from . import error as bz
from .pydbus_backfill import ProxyMethodAsync
from gi.repository.GLib import Error as GLib... | |
cls._rest_interaction(rest_communication.patch_entry, *args, **kwargs)
class GenerateHamiltonInputEPP(StepEPP):
# define the rows and columns in the input plate (standard 96 well plate pattern)
plate_rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
plate_columns = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',... | |
self._offset == self._failure:
self._expected.append('[0-9a-zA-Z_]')
self._offset = index13
if address12 is FAILURE:
address12 = TreeNode(self._input[self._offset:self._offset], self._offset, [])
self._offset = self._offset
else:
address12 = FAILURE
if address12 is not FAILURE:
elements5.append(address12)
els... | |
requirementUseCases(:req)',{'req':reqName},'MySQL error getting redmine use cases');
if len(ucs) == 0:
ucs.append('None')
return ucs
def getRequirementBacklog(self,reqName):
bis = self.responseList('call requirementBacklog(:req)',{'req':reqName},'MySQL error getting backlog items');
if len(bis) == 0:
bis.append... | |
be configured.
Only packets addressed to these ports will be forwarded to the backends
configured with this forwarding rule.
You can only use one of ports and portRange, or allPorts.
The three are mutually exclusive.
You may specify a maximum of up to 5 ports, which can be non-contiguous.
:param pulumi.Input[str]... | |
<filename>Cartwheel/lib/Python26/Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/ed_pages.py
###############################################################################
# Name: ed_pages.py #
# Purpose: The main editor notebook #
# Author: <NAME> <<EMAIL>> #
# Copyright: (c) 2008 <NAME> <<EMAIL>> #
# Licens... | |
import frappe
from frappe import _
@frappe.whitelist()
def create_verify(doc, method):
applicant = frappe.get_doc("Applicant", doc.applicant_id)
# frappe.errprint(doc)
if doc.name1 == "Employment Check1":
emp1_id = frappe.db.get_value("Verify Employment Check1", {
"applicant_id": doc.applicant_id})
if emp1_id:
... | |
import math
import numpy as np
import torch
from torch import optim
from torch import nn
import torch.utils.data
from torch.nn import (
BatchNorm1d,
Dropout,
LeakyReLU,
Linear,
Module,
ReLU,
Sequential,
Sigmoid,
)
from torch.autograd import Variable
import warnings
from .data_sampler import DataSampler
from ct... | |
<reponame>tellor-io/algorandTellorV2
from time import time
import pytest
from algosdk import constants
from algosdk import encoding
from algosdk.algod import AlgodClient
from algosdk.error import AlgodHTTPError
from algosdk.logic import get_application_address
from conftest import App
from src.scripts.scripts import ... | |
beam.
d : float
Diameter of an incoming parallel beam.
plot_fan : bool or int
Plot a fan of rays.
axis : matplotlib.Axis
label : str
Label of the plotted line
Keyword Arguments
-----------------
kws passed to plt.plot(**pltkws)
Returns
-------
maplotlib.figure
"""
try:
heights = iter(h)
except TypeEr... | |
instance_uuid, None,
mountpoint, 'ro')
vol = db.volume_get(context.get_admin_context(), volume_id)
self.assertEqual("in-use", vol['status'])
self.assertEqual('attached', attachment['attach_status'])
self.assertEqual(mountpoint, attachment['mountpoint'])
self.assertEqual(instance_uuid, attachment['instance_uuid'])... | |
ins_code, atom_name, alt_conf_internal=""):
res_info = residue_info(imol, chain_id, resno, "")
if (not res_info):
return False
else:
ret = get_atom_from_residue(atom_name, res_info, alt_conf_internal)
return ret
#
def residue_info_dialog_displayed_qm():
if (residue_info_dialog_is_displayed == 1):
return True... | |
be calculated.
:type dliq: float or None
:arg bool chkvals: If True (default False) and all values are given,
this function will calculate the disequilibrium and raise a
warning if the results are not within a given tolerance.
:arg float chktol: Tolerance to use when checking values (default
_CHKTOL).
:arg dliq0... | |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | |
import asyncio
import logging
import aiopg
import psycopg2
from psycopg2.extras import RealDictCursor
LATEST_BLOCK_NUM = """
SELECT max(block_num) FROM blocks
"""
LOGGER = logging.getLogger(__name__)
class Database(object):
"""Manages connection to the postgres database and makes async queries
"""
def __init__(... | |
@property
@pulumi.getter
def ip(self) -> str:
return pulumi.get(self, "ip")
@property
@pulumi.getter(name="ipRange")
def ip_range(self) -> str:
return pulumi.get(self, "ip_range")
@property
@pulumi.getter
def port(self) -> int:
return pulumi.get(self, "port")
@property
@pulumi.getter(name="portRange")
... | |
stack:
# Note... these tests are in reverse, since the exception
# winds its way up the stack.
stack.Add(_mk_kls())
stack.Add(_mk_kls(ValueError, suppress=True))
stack.Add(_mk_kls(IndexError, exception_kls=ValueError))
stack.Add(_mk_kls(IndexError))
stack.Add(_mk_kls(exception_kls=IndexError))
stack.Add(_mk_kls... | |
# Run from home directory with python -m pytest tests
import copy
import pytest
import random
import numpy as np
import torch.nn as nn
import torch
from nn_builder.pytorch.RNN import RNN
import torch.optim as optim
N = 250
X = torch.randn((N, 5, 15))
X[0:125, 0, 3] += 20.0
y = X[:, 0, 3] > 5.0
y = y.float()
def test_... | |
<reponame>Elrine/discord-dK2-destin
from typing import List, Tuple, Union
import sqlalchemy
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.elements import False_, True_
from sqlalchemy.sql.expression import insert, select, update
import discord_bot.model as model
from sqlalchemy import create_engi... | |
import random
import operator
class locale(object):
"""Holds the characteristics of a state or district ("locale")
All margins are assumed to be Democratic % - Republican %
I chose this semi-arbitrarily, on the basis that Biden was leading in most polls, so using positive
Democratic margins would reduce the lik... | |
32.12*m.x892 - 32.12*m.x901 - 32.12*m.x910 - 32.12*m.x926
- 55.08*m.x938 - 55.08*m.x948 - 55.08*m.x963 - 54.66*m.x975 - 54.66*m.x983 - 54.66*m.x993
- 54.66*m.x1002 - 33.09*m.x1017 - 33.09*m.x1025 - 33.09*m.x1034 - 33.09*m.x1044 - 40.24*m.x1082
+ 14.55*m.x1094 + 16.17*m.x1124 - 21.13*m.x1164 + 4.59*m.x1176 + 3.18*m.x... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""CARLA Enhance dataset and datamodule.
"""
from __future__ import annotations
import glob
import os
import random
from typing import Callable
from typing import Optional
import matplotlib.pyplot as plt
from torch.utils.data import random_split
from onevision.cv impor... | |
= client_options.ClientOptions(credentials_file="credentials.json")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options, transport=transport_name)
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.... | |
def addFeatures(self, features, gdbVersion='', rollbackOnFailure=True):
"""add new features to feature service layer
features -- esri JSON representation of features
ex:
adds = [{"geometry":
{"x":-10350208.415443439,
"y":5663994.806146532,
"spatialReference":
{"wkid":102100}},
"attributes":
{"Utility_Type":... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.