input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
slot; this should usually be avoided.) If there are any
unfilled slots for which no default value is specified, a "TypeError"
exception is raised. Otherwise, the list of filled slots is used as
the argument list for the call.
**CPython implementation detail:** An implementation may provide
built-in functions whose pos... | |
<filename>Final Solution/0478-22-PRE-F-M-19 Task 3 1-2-3.py<gh_stars>1-10
# ** DECLARE CONSTANTS
# These are the options of the various properties of the pizza available
sizesAvailable = ["Small", "Medium", "Large"] # The size of the pizza
basesAvailable = ["Thick", "Thin"] # The type of base of the pizza
toppingsAvai... | |
context=None,
gis=None,
estimate=False,
future=False):
"""
.. image:: _static/images/create_watersheds/create_watersheds.png
The ``create_watersheds`` method determines the watershed, or upstream contributing area, for each point
in your analysis layer. For example, suppose you have point features representing ... | |
import numpy as np
import pandas as pd
import scipy.stats as si
'''
This section is highly dependent upon knowledge of the black & scholes formula
for option pricing and using Monte Carlo methods to price options. There are
a number of terms such as d1, d2, delta, gamma, vega that are specific to
option ricing and I w... | |
value None
Returns
-------
None
"""
if parameters is None:
parameters = self
return parameters.set_path(
path=self._translated_path(path),
new_value=new_value
)
def override(self, override):
"""Override container content recursively.
Parameters
----------
override : dict, str
Depending type follow... | |
*\
(l == data.ds.parameters['MaximumRefinementLevel']))
return answer
def _above_chiaki_threshold(field,data):
C_f = data[('gas','C_Fraction')].value
Fe_f = data[('gas','Fe_Fraction')].value
H_f = data[('gas','H_fraction')].value
return physics.chiaki_threshold(C_f, Fe_f, H_f, return_value=False).astype(np.fl... | |
else:
TRef.alterField(DB_ACTUAL.getName(), self.tabla, subaccion.campo, 'Null', False)
elif isinstance(self.accion, AlterTableDrop):
if self.accion.tipo == ALTER_TABLE_DROP.COLUMN:
sint = self.accion.ejecutar(ts)
#Comprobamos la existencia del campo
if not TRef.columnExist(DB_ACTUAL.getName(),self.tabla,self.acci... | |
<reponame>duc90/marvin
#!/usr/bin/env python
# encoding: utf-8
#
# @Author: <NAME>
# @Date: Nov 1, 2017
# @Filename: general.py
# @License: BSD 3-Clause
# @Copyright: <NAME>
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import collections
import inspect
... | |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitati... | |
('sep_conv_3x3', 1),
('skip_connect', 0),
('sep_conv_5x5', 1)],
normal_concat=range(2, 6),
reduce=[('avg_pool_3x3', 0),
('avg_pool_3x3', 1),
('avg_pool_3x3', 0),
('skip_connect', 2),
('skip_connect', 2),
('max_pool_3x3', 0),
('avg_pool_3x3', 0),
('skip_connect', 2)],
reduce_concat=range(2, 6))
PDARTS_TS_CI... | |
2 * np.pi) - np.pi
)
def interpolate_angle(x, xp, yp):
"""
Interpolate an angular quantity on domain [-pi, pi) and avoid
discountinuities.
"""
cosy = np.interp(x, xp, np.cos(yp))
siny = np.interp(x, xp, np.sin(yp))
return np.arctan2(siny, cosy)
# Inclination of the starry map = 90 - latitude of the central... | |
<gh_stars>0
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
from scipy import interpolate
np.nan
"""
*****************************************************************************************************************************
Filter class is comprising methods for data filtering and smoothing functionality
... | |
"""rio_tiler.utils: utility functions."""
import os
from io import BytesIO
from typing import Any, Dict, Generator, Optional, Sequence, Tuple, Union
import numpy
from affine import Affine
from boto3.session import Session as boto3_session
from rasterio import windows
from rasterio.crs import CRS
from rasterio.enums i... | |
"projection target") most often contains the same environmental
predictors but represents data captured at a different temporal or spatial location. For
example, a user could generate a model predicting habitat suitability using recorded
presence points and certain environmental predictors such as elevation, landcov... | |
import logging
from django import forms
from django.core.exceptions import ImproperlyConfigured
from .models import Event, EventProposal, EventTrack, SpeakerProposal
logger = logging.getLogger("bornhack.%s" % __name__)
class SpeakerProposalForm(forms.ModelForm):
"""
The SpeakerProposalForm. Takes a list of Event... | |
in [delr, delc]:
if isinstance(delrc, float) or isinstance(delrc, int):
msg = (
"delr and delcs must be an array or sequences equal in "
"length to the number of rows/columns."
)
raise TypeError(msg)
self.delc = np.atleast_1d(np.array(delc)).astype(
np.float64
) # * length_multiplier
self.delr = np.atleast_1... | |
import numpy as np
import math
import sys
import pickle
def Coord2Pixels(lat, lon, min_lat, min_lon, max_lat, max_lon, sizex, sizey):
#print(max_lat, min_lat, sizex)
ilat = sizex - int((lat-min_lat) / ((max_lat - min_lat)/sizex))
#ilat = int((lat-min_lat) / ((max_lat - min_lat)/sizex))
ilon = int((lon-min_lon) / ... | |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import traceback
from collec... | |
#!/usr/bin/env python3
'''
lib/ycmd/server.py
Server abstraction layer.
Defines a server class that represents a connection to a ycmd server process.
Information about the actual server process is available via the properties.
The ycmd server handlers are exposed as methods on this class. To send a
request to the se... | |
<reponame>luxius-luminus/pai<filename>contrib/profiler/profiler.py
# Copyright (c) Microsoft Corporation
# All rights reserved.
#
# MIT License
#
# 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... | |
/ summary screen widget. Display the total of selected Account Balances
total_selected_transactions: One-click. Shows a popup total of the register txn amounts selected on screen
Extension (.mxt) and Script (.py) Versions available:
extract_data Extract various data to screen and/or csv.. Consolidation of:
- stockglan... | |
from tesi_ao import main220316
import matplotlib.pyplot as plt
import numpy as np
from astropy.io import fits
from tesi_ao.mems_command_to_position_linearization_measurer import CommandToPositionLinearizationMeasurer
from tesi_ao.mems_command_to_position_linearization_analyzer import CommandToPositionLinearization... | |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | |
EXAMPLES::
sage: f1(x) = 1
sage: f2(x) = 1 - x
sage: f = Piecewise([[(0,1),f1],[(1,2),f2]])
doctest:...: DeprecationWarning: use lower-case piecewise instead
See http://trac.sagemath.org/14801 for details.
sage: f.extend_by_zero_to(-1, 3)
doctest:...: DeprecationWarning: use lower-case piecewise instead
See... | |
self.auth_client.get(self.url + '?keys={}'.format(
k8s_config_maps.K8S_CONFIG_MAPS_JOBS))
assert resp.status_code == status.HTTP_200_OK
assert resp.data[0] == conf.get(k8s_config_maps.K8S_CONFIG_MAPS_JOBS, to_dict=True)
assert resp.data[0]['value'] == data
# Experiment
resp = self.auth_client.get(self.url + '?ke... | |
element in enumerate(result):
try:
user = await self.client.fetch_user(element)
a = user.name
except AttributeError:
a = '?'
embed.add_field(name=str(int(index + 1)),
value=f"``{random.choice(kamo)}`` | {a} - {result[element]['money']} {emoji}",
inline=False)
await ctx.send(embed=embed)
@commands.command(nam... | |
outline file is yamlized before being
# copied into the outline session. If not, the script
# is copied as is. Default is True.
self.__serialize = serialize
#
# The path to a native outline script. If a path
# is specified in the constructor, then it must
# be a path to a native (not serialized) outline
# scri... | |
properties array (numpy array with shape ``(3, nx, ny, nz)``)
:type mat: ndarray
:returns: None
"""
if self.ndim == 3:
assert (mat.shape[1:] == self.nx), "heterogeneous material properties shape must match grid sizes"
else:
assert (mat.shape[1:] == self.nx[0:2]), "heterogeneous material properties shape must mat... | |
\
HttpResponseReader.read()
"""
protocol = HttpClientProtocol()
transport_mock = TransportMock()
protocol.connection_made(transport_mock)
writer = await protocol.write_request(
HttpRequestMethod.POST, uri="/", headers={"content-type": "1"}
)
writer.write(os.urandom(1))
await writer.flush()
writer.finish()... | |
+ ')'
like_which = "like_memcpy"
code2 = todo_code_template
if dest_param:
if copylen:
code += '\n{\n'
code += ' unsigned int osc_abort = OSC_DEF_ABORT_STATE;\n\n'
code += ' if (' + copylen + ' > dest_len) {\n'
code += ' if (osc_log) {\n'
code += ' danger_error("' + funcname + '", dest_len, ' + copylen + ');\n... | |
'quoting': {},
'tags': [],
'vars': {},
'target_database': 'some_snapshot_db',
'target_schema': 'some_snapshot_schema',
'unique_key': 'id',
'extra': 'even more',
'strategy': 'check',
'check_cols': ['a', 'b'],
}
@pytest.fixture
def complex_set_snapshot_config_object():
cfg = CheckSnapshotConfig(
column_types... | |
import json
import time
from BucketLib.BucketOperations import BucketHelper
from cb_tools.cbstats import Cbstats
from cbas_base import CBASBaseTest
from couchbase_helper.documentgenerator import doc_generator
from memcached.helper.data_helper import MemcachedClientHelper
from remote.remote_util import RemoteMachineShe... | |
<filename>GFPy/Ocean.py
# -*- coding: utf-8 -*-
"""
This module contains functions that read (and plot) various
oceanographic instrument data. This includes:
- CTD (incl. mini CTD)
- ADCP
- drifter
- mooring
The functions are optimized for the file formats typically used
in student cruises at the Geophysical Institute... | |
in query.lower():
query = query.split('&')[0]
try:
results = await self.bot.lavalink.get_tracks(query, node=node)
except asyncio.TimeoutError:
results = {'playlistInfo': {},
'loadType': 'NO_MATCHES', 'tracks': []}
if isinstance(results, dict):
return results
return {'playlistInfo': {}, 'loadType': 'NO_MATCHES... | |
('metal')
self.log = logging.getLogger ("simpleTAL.TemplateCompiler")
def setTALPrefix (self, prefix):
self.tal_namespace_prefix = prefix
self.tal_namespace_omittag = '%s:omit-tag' % self.tal_namespace_prefix
self.tal_attribute_map = {}
self.tal_attribute_map ['%s:attributes'%prefix] = TAL_ATTRIBUTES
... | |
import glob
import os
from pathlib import Path
import yaml
from typing import Any, Dict, List, Union
import warnings
from .data_interface import MagicDataInterface
from .self_aware_data import SelfAwareData, SelfAwareDataInterface
DIRS_TO_IGNORE = ['__pycache__']
class DataDirectoryManager:
config_file_name = '.... | |
False:
dfs[which_ix] = df2
if is_print and df2_isempty == False:
st.write(df2)
#display(df2)
printed_header = True
return dfs
#---------------------------------------------------------
def handleCityGraph(keep_early_arr, city, choice_ix, id_list, fsu, bookings_f, feeders, is_print=True, delay=45):
# Need to i... | |
"""
Copyright (c) 2014-2019 Wind River Systems, Inc.
SPDX-License-Identifier: Apache-2.0
"""
from six.moves import configparser
import mock
import os
import pytest
import sys
import controllerconfig.common.exceptions as exceptions
from controllerconfig import validate
from controllerconfig import DEFAULT_CONFIG
sy... | |
<gh_stars>1-10
import argparse
import os
import time
import math
import random
import hashlib
import numpy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim.lr_scheduler as lr_scheduler
import data
import model
from utils import rankloss, get_batch, repackage_hidd... | |
<reponame>jflatorreg/scikit-maad
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 6 17:59:44 2018
This script gives an example of how to use scikit-MAAD for ecoacoustics indices
"""
#
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: New BSD License
print(__doc__)
# Clear all the variables
fr... | |
None,
connector: dict = None,
):
"""
Decorator that registers coroutine as a slash command.\n
All decorator args must be passed as keyword-only args.\n
1 arg for command coroutine is required for ctx(:class:`.model.SlashContext`),
and if your slash command has some args, then those args are also required.\n
All... | |
<reponame>ricsinaruto/ParlAI
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from .torch_agent_v1 import TorchAgent, Output, Beam
from .utils_v1 import padded_tensor
fr... | |
"""
self.unit = None
""" Individual or family.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(ExplanationOfBenefitBenefitBalance, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(ExplanationOfBenefitBenefitBalance, self).elementProperties()... | |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import *
engine = create_engine('postgresql://catalog:catalog@localhost:5432/catalog')
base.Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Create a first user for entering items
user = u... | |
<filename>adascreen/screening_rules.py
import numpy as np
class AbstractScreeningRule(object):
""" Base class for LASSO screening rules. """
tol = 1e-9 # tolerance
name = 'None' # name of associated lasso screening rule
isComplete = True # does NOT screen out possibly non-zero coefficients
def __init__(self, na... | |
<gh_stars>10-100
#!/usr/bin/env python
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | |
<reponame>IBM/open-prediction-service-hub<gh_stars>1-10
#!/usr/bin/env python3
#
# Copyright 2020 IBM
# 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-... | |
<filename>SSINS/incoherent_noise_spectrum.py<gh_stars>1-10
"""
The incoherent noise spectrum class.
"""
import numpy as np
import os
from pyuvdata import UVFlag
import yaml
from functools import reduce
import warnings
from itertools import combinations
from SSINS.match_filter import Event
class INS(UVFlag):
"""
De... | |
[]
for m in agent.mods:
if m.position is None:
if m.residue is not None:
residue_str =\
ist.amino_acids[m.residue]['full_name']
mod_lst.append(residue_str)
else:
mod_lst.append('an unknown residue')
elif m.position is not None and m.residue is None:
mod_lst.append('amino acid %s' % m.position)
else:
mod_lst... | |
import random
from dataclasses import dataclass
from typing import Any, Callable, cast, List, Sequence, TypeVar, Union
T = TypeVar('T')
c_str = Callable[[], str]
S = Union[str, c_str]
def is_function(x: Any) -> bool:
return hasattr(x, '__call__')
def random_element(*itens: T) -> T:
return random.sample(itens, 1)[0... | |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""
Provides a set of coordinate frames.
----
.. include license and copyright
.. include:: ../include/copy.rst
----
.. include common links, assuming primary doc root is up one directory
.. include:: ../include/links.rst
"""
... | |
<gh_stars>0
from django.db import models
from djangotoolbox.fields import ListField, SetField, DictField, EmbeddedModelField
from django_mongodb_engine.contrib import MongoDBManager
# 20161115, <EMAIL>: reduce data model to fields curently in use by B2Note app.
#
# class CssStyleSheet(models.Model):
# type = models... | |
and word[4] != "O" and word[4] != "o" :
print("\nWrong!\n")
numberOfErrors = numberOfErrors + 1
wrongChars = wrongChars + "o" + ", "
if guessChar == "P" or guessChar == "p" :
if word[1] == "P" or word[1] == "p" :
toGuess = toGuess[:1] + "p" + toGuess[2:]
if word[2] == "P" or word[2] == "p" :
... | |
# Enter a parse tree produced by Fortran77Parser#controlFmt.
def enterControlFmt(self, ctx:Fortran77Parser.ControlFmtContext):
pass
# Exit a parse tree produced by Fortran77Parser#controlFmt.
def exitControlFmt(self, ctx:Fortran77Parser.ControlFmtContext):
pass
# Enter a parse tree produced by Fortran77Parser#... | |
0: x_seams.add(trim_x_start)
if trim_y_start != 0: y_seams.add(trim_y_end)
blur_rects = []
blur_size = 5
for x_seam in x_seams:
left = x_seam - blur_size
right = x_seam + blur_size
top, bottom = 0, h
blur_rects.append((slice(top, bottom), slice(left, right)))
for y_seam in y_seams:
top = y_seam - blur_size
... | |
"""
The ``sde`` module contains functions to fit the single diode equation.
Function names should follow the pattern "fit_" + fitting method.
"""
import numpy as np
from pvlib.ivtools.utils import _schumaker_qspline
# set constant for numpy.linalg.lstsq parameter rcond
# rcond=-1 for numpy<1.14, rcond=None for nu... | |
= dict((f.name, f) for f in spark.catalog.listFunctions("default"))
self.assertTrue(len(functions) > 200)
self.assertTrue("+" in functions)
self.assertTrue("like" in functions)
self.assertTrue("month" in functions)
self.assertTrue("to_date" in functions)
self.assertTrue("to_timestamp" in functions)
self.assertTr... | |
<filename>examples/run_chemistry_parser.py<gh_stars>0
# coding=utf-8
# Copyright 2019 The HuggingFace Inc. team.
# Copyright (c) 2019 The HuggingFace 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... | |
#!/usr/bin/env python
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn
from tensorflow.python.eager import context
from tensorflow.python.layers import utils
from tensorflow... | |
<gh_stars>0
# -*- coding: utf-8 -*-
#
# PublicKey/DSA.py : DSA signature primitive
#
# Written in 2008 by <NAME> <<EMAIL>>
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain ... | |
from copy import copy
import pandas as pd
import numpy as np
from cached_property import cached_property
from hashlib import md5
from .utils import integral_trapz
from .core_utils import IdentifedObject, IdentifedCachedObject
# register signal name dictionary
global __signal_names__
__signal_names__ = ... | |
<reponame>svenhofstede/great_expectations
import logging
import os
import sys
import uuid
import click
from great_expectations import exceptions as ge_exceptions
from great_expectations.cli import toolkit
from great_expectations.cli.pretty_printing import cli_message
from great_expectations.core import ExpectationSui... | |
# IMPORT PACKAGES FOR ANALYSING
# ///////////////////////////////////////////////////////////////
import string
import pandas as pd
from PIL import Image
import numpy as np
import os
from PySide6.QtWidgets import QFileDialog
from iminuit import Minuit
import matplotlib.pyplot as plt
from matplotlib.offsetbox import An... | |
<filename>Lib/site-packages/qwt/dyngrid_layout.py<gh_stars>0
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 <NAME>, for the original C++ code
# Copyright (c) 2015 <NAME>, for the Python translation/optimization
# (see LICENSE file for more details)
"""
qwt.dyngrid_layout
-... | |
#!/usr/bin/env python3
# coding: utf-8
"""
@file: st_pipeline.py
@description:
@author: <NAME>
@email: <EMAIL>
@last modified by: <NAME>
change log:
2021/07/20 create file.
"""
from ..preprocess.qc import cal_qc
from ..preprocess.filter import filter_cells, filter_genes, filter_coordinates
from ..algorithm.normaliza... | |
<filename>py/fiberassign/test/test_assign.py
"""
Test fiberassign target operations.
"""
import os
import shutil
import unittest
from datetime import datetime
import json
import numpy as np
import fitsio
import desimodel
from fiberassign.utils import option_list, GlobalTimers
from fiberassign.hardware import l... | |
<filename>tests/cli_unittest.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import os
import os.path
import pty
import re
import subprocess
import sys
import threading
import... | |
<gh_stars>0
'''Main connection to TWS client.
Defines the EClientSocket class, which implements a socket connection to
the TWS socket server, through which the entire API operates.
'''
from __future__ import with_statement
__copyright__ = "Copyright (c) 2008 <NAME>"
__version__ = "$Id$"
import tws._EClientErrors ... | |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey has `on_delete` set to the desired behavior.
# * Remove `managed = False` lines if you wish... | |
<reponame>Rahlubenru/workload-automation<gh_stars>0
# Copyright 2013-2015 ARM 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | |
import logging
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from typing import Union, List, ClassVar, DefaultDict, Set
import pytest
from dataclass_wizard import property_wizard
from ..conftest import Literal, Annotated, PY39_OR_ABOVE, PY310_OR_ABOVE
log ... | |
_return_http_data_only (bool): response data without head status
code and headers. Default is True.
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): timeout setting for this request. If
... | |
<gh_stars>0
from bs4 import BeautifulSoup as BS # Can parse xml or html docs
from datetime import datetime
from dateutil import parser
from src.data_processing.xbrl_pd_methods import XbrlExtraction
import pandas as pd
import os
import csv
import time
import sys
import math
import time
import multiprocessing as mp
impor... | |
i in m.split('|')]
# zero polynomial on restriction
if len([i for i, e in enumerate(split_m) \
if e > 0 and i not in f]) > 0:
continue
out_m = [e for i, e in enumerate(split_m) if i in f]
out_m = '|'.join([str(i) for i in out_m])
out_p[out_m] = c
# map dt to range of f
out_form['|'.join([str(f[i]) for ... | |
import matplotlib.pyplot as plt
import numpy as np
from scipy.linalg import expm,logm
import tensorflow as tf
import vis
import os
import argparse
import nibabel as nib
import warnings
import scipy.interpolate as spi
'''
In this file we include several basic functions that were not present natively in tensorflow,
and... | |
<gh_stars>1-10
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.... | |
unique_fkey_indices < operations.INVALID_INDEX
safe_unique_fkey_indices = unique_fkey_indices[invalid_filter]
# the predicate results are in the same space as the unique_fkey_indices, which
# means they may still contain invalid indices, so filter those now
safe_values_to_join = raw_values_to_join[invalid_filter]
... | |
<reponame>scottwedge/OpenStack-Stein<gh_stars>0
# 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... | |
import pickle
import numpy as np
from numpy.testing import (
assert_almost_equal,
assert_equal,
assert_,
assert_allclose,
)
from scipy.stats import cauchy
from refnx._lib import flatten
from refnx.reflect import (
SLD,
Structure,
Spline,
Slab,
Stack,
Erf,
Linear,
Exponential,
Interface,
MaterialSLD,
Mix... | |
cache XML
global _COINCO_XML
if _COINCO_XML is None:
with gzip.open(ASSETS['coinco_patched']['fp'], 'r') as f:
_COINCO_XML = BeautifulSoup(f.read(), 'xml')
# Load and cache splits
global _COINCO_DEV_IDS
global _COINCO_TEST_IDS
if _COINCO_DEV_IDS is None:
assert _COINCO_TEST_IDS is None
with open(ASSETS['coin... | |
for ds in dsolve_sol] == [f(x), g(x)]
assert [ds.rhs.equals(ss.rhs) for ds, ss in zip(dsolve_sol, sol)]
assert checksysodesol(eqs, sol) == (True, [0, 0]) # XFAIL
@XFAIL
def test_linear_2eq_order1_type6_path2():
# This is the reverse of the equations above and should also be handled by
# type6.
eqs = [
Eq(diff(g... | |
full_rect.set_stroke(WHITE, 0)
full_rect.color_using_background_image(self.background_image_file)
title = TextMobject("Output Space")
title.scale(1.5)
title.to_edge(UP, buff = MED_SMALL_BUFF)
title.set_stroke(BLACK, 1)
# self.add_foreground_mobjects(title)
plane = NumberPlane()
plane.fade(0.5)
plane.axes.set... | |
isZero(*args, **kwargs):
pass
def reorder(*args, **kwargs):
pass
def reorderIt(*args, **kwargs):
pass
def setToAlternateSolution(*args, **kwargs):
pass
def setToClosestCut(*args, **kwargs):
pass
def setToClosestSolution(*args, **kwargs):
pass
def setValue(*args, **kwargs):
pass
... | |
if Sy < round(0 + 400 * math.sin(tel)) and Sx > round(1200 + 400 * math.cos(tel)): # 1200, 0
inn = True
if Sy < round(0 + 300 * math.sin(tel)) and Sx > round(1200 + 300 * math.cos(tel)):
dod = True
break
tel = round(tel + 0.01, 2)
elif room == "R4":
tel = 0
for a in range(628):
if Sy < round(0 + 400 *... | |
<filename>stix2/test/v21/test_environment.py
import os
import pytest
import stix2
import stix2.environment
import stix2.equivalence.graph
import stix2.equivalence.object
import stix2.exceptions
from .constants import (
ATTACK_PATTERN_ID, ATTACK_PATTERN_KWARGS, CAMPAIGN_ID, CAMPAIGN_KWARGS,
FAKE_TIME, IDENTITY_ID, ... | |
This is the default
reaction.upper_bound = 1000. # This is the default
reaction.add_metabolites({pp2coa_SEOc: -1.0,
h_SEOc: -1.0,
nadh_SEOc: -1.0,
nad_SEOc: 1.0,
ppcoa_SEOc: 1.0})
model.add_reactions([reaction])
print(reaction.name + ": " + str(reaction.check_mass_balance()))
#propionate CoA transferase
... | |
<reponame>RomanoViolet/Udacity-LaneDetection<gh_stars>1-10
#LaneDetectionUtils.py
import os
import sys
import cv2
import numpy as np
np.seterr(all='raise')
import pickle
import configuration
from skimage.feature import hog
from skimage import exposure
from scipy import ndimage
'''
Read in stored camera calibrations
''... | |
# Copyright (C) 2007 - 2009 The MITRE Corporation. See the toplevel
# file LICENSE for license terms.
# This script does the real work of the installation. The first
# thing it needs to check is whether it was invoked with Python
# 2.6 or later. Notice that this is NOT an executable Python
# script; it must be called ... | |
{'parameters_name_suffix': 'suffix'},
{'parameters_name_suffix': 'suffix', 'lambda_angles': 1.0},
{'parameters_name_suffix': 'suffix', 'lambda_sterics': 0.5, 'lambda_angles': 0.5}]
for test_kwargs in test_cases:
state = MyState(**test_kwargs)
# Check which parameters are defined/undefined in the constructed stat... | |
i in range(1, ilith+1):
if m == 0:
b4[0, m, i] = 2. / 3. / np.sqrt(5.) * \
omega**2 * radius[i] * \
hlm[i].coeffs[0, l, m] * p402020
elif m == 1:
b4[0, m, i] = 2. / 3. / np.sqrt(5.) * \
omega**2 * radius[i] * \
hlm[i].coeffs[0, l, m] * p412021
elif m == 2:
b4[0, m, i] = 2. / 3. / np.sqrt(5.) * \
omega**2 * r... | |
################################################################################
#
# GuiWinKHR2Feet
#
""" Graphical User Interface KHR-2 BrainPack Feet Window
Graphical User Interface (GUI) Tkinter window displays current
RoadNarrows BrainPack feet sensor data, plus simple display options.
Author: <NAME>
Email: <EMA... | |
port, punch)).start()
os.system('cls')
print("\033[97m[-] Sending Attack.")
time.sleep(1)
os.system('cls')
print("\033[97m[\] Sending Attack..")
time.sleep(1)
os.system('cls')
print("\033[97m[|] Sending Attack...")
time.sleep(1)
os.system('cls')
print("\... | |
str
value : str
'''
address_ = Address.from_json(address) if address else None
port_ = port
scope_ = scope
space_id_ = space_id
space_name_ = space_name
type__ = type_
value_ = value
# Validate arguments against known Juju API types.
if address_ is not None and not isinstance(address_, (dict, Address)):
ra... | |
<gh_stars>0
from contextlib import contextmanager
import numpy as np
import torch
import torch.nn.functional as F
from .core import extend
from .utils import disable_param_grad
from .gradient import data_loader_gradient
from .operations import *
from .symmatrix import SymMatrix, Kron, Diag, UnitWise
from .matrices imp... | |
= None,
num_tokens_to_remove: int = 0,
truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
stride: int = 0,
) -> Tuple[List[int], List[int], List[int]]:
if num_tokens_to_remove <= 0:
return ids, pair_ids, []
if not isinstance(truncation_strategy, TruncationStrategy):
truncation_strategy = Tr... | |
for Simper App'
})
return html_report
def _generate_variable_stats_html_report(self, anosim_res, permanova_res, permdisp_res):
output_directory = os.path.join(self.scratch, str(uuid.uuid4()))
logging.info('Start generating html report in {}'.format(output_directory))
html_report = list()
self._mkdir_p(output_... | |
"""
Kenshoto's Elf parser
This package will let you use programatic ninja-fu
when trying to parse Elf binaries. The API is based
around several objects representing constructs in the
Elf binary format. The Elf object itself contains
parsed metadata and lists of things like section headers
and relocation entries. Addit... | |
<reponame>lusindazc/det_reid<filename>multi_people/runcam11_goods_connected_multi-1217.py
#me : 2018-11-27
# @Author : <NAME>,<NAME>
# @Description : Give an interface to one cam
# @last_modification: 2018-12-10
#---------------------------------
import HKIPcamera
import cv2
from loadconfig import *
import rospy # B... | |
import numpy as np
import torch
from torch.optim import Adam
import gym
import time
import yaml
import safe_rl.algos.cppo.core as core
from safe_rl.utils.logx import EpochLogger
from safe_rl.utils.mpi_pytorch import setup_pytorch_for_mpi, sync_params, mpi_avg_grads
from safe_rl.utils.mpi_tools import (mpi_fork, mpi_avg... | |
d in range(len(a.shape))])
if no_value:
code += indent + 'yield ' + index
else:
code += indent + 'yield ' + 'a[%s]' % index + ', (' + index + ')'
exec code
return nested_loops, code
def compute_histogram(samples, nbins=50, piecewise_constant=True):
"""
Given a numpy array samples with random samples, this func... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.