uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cf90c921a6fa239a67630918 | train | function | def read_bitcoin_config(dbdir):
"""Read the mnpro.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
... | def read_bitcoin_config(dbdir):
| """Read the mnpro.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
... | () == "Darwin":
return os.path.expanduser("~/Library/Application Support/Mnpro/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Mnpro")
return os.path.expanduser("~/.mnpro")
def read_bitcoin_config(dbdir):
| 64 | 64 | 178 | 8 | 56 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | read_bitcoin_config | read_bitcoin_config | 43 | 63 | 43 | 43 | 941ae61d3007e36f80645aab66591dcd59320560 | bigcode/the-stack | train |
297531a68ffead1696f84a7b | train | function | def compute_amount_in(mnprod, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = mnprod.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
| def compute_amount_in(mnprod, txinfo):
| result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = mnprod.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
| signed_rawtx = mnprod.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(mnprod, txinfo):
| 64 | 64 | 76 | 11 | 52 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | compute_amount_in | compute_amount_in | 182 | 188 | 182 | 182 | 9fb00632528041eef7a304c776bbd3c3dc20b8cd | bigcode/the-stack | train |
e659f028f04a41b35965f690 | train | function | def unlock_wallet(mnprod):
info = mnprod.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
mnprod.walletpa... | def unlock_wallet(mnprod):
| info = mnprod.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
mnprod.walletpassphrase(passphrase, 5)
... | '] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(mnprod):
| 64 | 64 | 119 | 7 | 57 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | unlock_wallet | unlock_wallet | 84 | 97 | 84 | 84 | a8df9513da41b763f718e736e2221761b32b9a08 | bigcode/the-stack | train |
d32e2965330e8f07dd45c518 | train | function | def determine_db_dir():
"""Return the default location of the mnpro data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Mnpro/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Mnpro")
return os.pat... | def determine_db_dir():
| """Return the default location of the mnpro data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Mnpro/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Mnpro")
return os.path.expanduser("~/.mnpro")... | n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
| 64 | 64 | 78 | 5 | 59 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | determine_db_dir | determine_db_dir | 35 | 41 | 35 | 35 | 87be19217929aed637ca0f23c4d2149de85cdf2f | bigcode/the-stack | train |
54e7a473b1a75c87d85f7ff2 | train | function | def sanity_test_fee(mnprod, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = mnprod.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(mnprod, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
rais... | def sanity_test_fee(mnprod, txdata_hex, max_fee):
| class FeeError(RuntimeError):
pass
try:
txinfo = mnprod.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(mnprod, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fe... | result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(mnprod, txdata_hex, max_fee):
| 70 | 70 | 234 | 15 | 54 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | sanity_test_fee | sanity_test_fee | 196 | 217 | 196 | 196 | b49e38c4d6ae23e58142cdc8ad32b147e1a964b6 | bigcode/the-stack | train |
0629b61b21237ee5265a547c | train | function | def create_tx(mnprod, fromaddresses, toaddress, amount, fee):
all_coins = list_available(mnprod)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[add... | def create_tx(mnprod, fromaddresses, toaddress, amount, fee):
| all_coins = list_available(mnprod)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["tot... | this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(mnp... | 103 | 103 | 344 | 17 | 86 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | create_tx | create_tx | 142 | 180 | 142 | 142 | 66fcc7013b8e44d8cd6bd0c9e0502b9874fc8d12 | bigcode/the-stack | train |
8944f09ced3b16af78e41d93 | train | function | def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
| def compute_amount_out(txinfo):
| result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
| ")
for vin in txinfo['vin']:
in_info = mnprod.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
| 64 | 64 | 41 | 7 | 56 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | compute_amount_out | compute_amount_out | 190 | 194 | 190 | 190 | 1caea3a2f9ccddc94ec1911a145d89bbbb767699 | bigcode/the-stack | train |
4cc4b14126fd10f12e69e53d | train | function | def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
| def check_json_precision():
| """Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
|
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
| 64 | 64 | 80 | 5 | 59 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | check_json_precision | check_json_precision | 28 | 33 | 28 | 28 | ad7e4d25a16ab6766304b8df5eaf0f8f9c5d66b1 | bigcode/the-stack | train |
9d9b925c603152a1093dc897 | train | function | def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
... | def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
| outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
| {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
| 64 | 64 | 103 | 26 | 37 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | select_coins | select_coins | 131 | 140 | 131 | 132 | 097bd56cbfceefa0a184f76dfaed58c7d6570e2a | bigcode/the-stack | train |
845bf069ad1b937d58feb315 | train | function | def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get MNPRs from")
parser.add_option("--to", dest="to", default=None,
help="address to get sen... | def main():
| import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get MNPRs from")
parser.add_option("--to", dest="to", default=None,
help="address to get send MNPRs to")... | _out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny... | 145 | 145 | 484 | 3 | 142 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | main | main | 219 | 264 | 219 | 219 | 38b58d31ad53f1d54b613e9a7e19947376d77054 | bigcode/the-stack | train |
bf57beb12f5e5f1e9e5b2733 | train | function | def connect_JSON(config):
"""Connect to a mnpro JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 38843 if testnet else 3230
connect = "http://%s:%s@127.0.0.1:%s"%(... | def connect_JSON(config):
| """Connect to a mnpro JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 38843 if testnet else 3230
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config[... | ('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "mnpro.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
| 71 | 71 | 237 | 5 | 66 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | connect_JSON | connect_JSON | 65 | 82 | 65 | 65 | 34ec3cf5f67686a55af735992e7b55a0af9eee13 | bigcode/the-stack | train |
185ded627f254de347b7ae51 | train | function | def list_available(mnprod):
address_summary = dict()
address_to_account = dict()
for info in mnprod.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = mnprod.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
... | def list_available(mnprod):
| address_summary = dict()
address_to_account = dict()
for info in mnprod.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = mnprod.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = mnprod.getrawtran... | t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
mnprod.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = mnprod.getinfo()
return int(info['unlocked_until']) > time.time()
def lis... | 79 | 79 | 264 | 7 | 72 | mn-pro/MNPROV2-WALLET-UPDATE | contrib/spendfrom/spendfrom.py | Python | list_available | list_available | 99 | 129 | 99 | 99 | c1176e6081c535096058ac077c5ff12b6db8c21b | bigcode/the-stack | train |
5247904b5d3e4edbb29672ff | train | class | class MemStatsCollector:
"""
A Memory statistic collector.
It works in two phases.
Phase 1. Collection Phase: collect memory usage statistics of CPU and GPU.
The first iteration of DNN training.
Phase 2. Runtime Phase: use the read-only collected stats
The rest iterations of DNN training.
... | class MemStatsCollector:
| """
A Memory statistic collector.
It works in two phases.
Phase 1. Collection Phase: collect memory usage statistics of CPU and GPU.
The first iteration of DNN training.
Phase 2. Runtime Phase: use the read-only collected stats
The rest iterations of DNN training.
It has a Sampling cou... | from colossalai.utils.memory_tracer.model_data_memtracer import GLOBAL_MODEL_DATA_TRACER
from colossalai.utils.memory import colo_device_memory_used
from colossalai.utils.memory_tracer import SyncCudaMemoryMonitor
import torch
import time
from typing import List
class MemStatsCollector:
| 60 | 256 | 1,136 | 5 | 54 | feifeibear/ColossalAI | colossalai/utils/memory_tracer/memstats_collector.py | Python | MemStatsCollector | MemStatsCollector | 9 | 143 | 9 | 9 | 298cc956251d4ad2eae7bfd3273a8f6739b9ee4d | bigcode/the-stack | train |
d1c7e55b20dfa50f70d3edb0 | train | class | class SeparatethousandsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="separatethousands", parent_name="heatmap.colorbar", **kwargs
):
super(SeparatethousandsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_... | class SeparatethousandsValidator(_plotly_utils.basevalidators.BooleanValidator):
| def __init__(
self, plotly_name="separatethousands", parent_name="heatmap.colorbar", **kwargs
):
super(SeparatethousandsValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
**k... | import _plotly_utils.basevalidators
class SeparatethousandsValidator(_plotly_utils.basevalidators.BooleanValidator):
| 23 | 64 | 95 | 15 | 7 | andresgreen-byte/Laboratorio-1--Inversion-de-Capital | env/Lib/site-packages/plotly/validators/heatmap/colorbar/_separatethousands.py | Python | SeparatethousandsValidator | SeparatethousandsValidator | 4 | 13 | 4 | 4 | b5a6295bdf25df311844932cbf1381ca8429f241 | bigcode/the-stack | train |
edd7cf7466a3201d2b85d2cf | train | function | def _doc_params(cls):
"""Return a tuple of the doc params."""
axis_descr = (
f"{{{', '.join([f'{a} ({i})' for i, a in enumerate(cls._AXIS_ORDERS)])}}}"
)
name = cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else "scalar"
name2 = cls.__name__
return axis_descr, name, name2
| def _doc_params(cls):
| """Return a tuple of the doc params."""
axis_descr = (
f"{{{', '.join([f'{a} ({i})' for i, a in enumerate(cls._AXIS_ORDERS)])}}}"
)
name = cls._constructor_sliced.__name__ if cls._AXIS_LEN > 1 else "scalar"
name2 = cls.__name__
return axis_descr, name, name2
| self._find_valid_index(how="first")
@final
@doc(first_valid_index, position="last", klass=_shared_doc_kwargs["klass"])
def last_valid_index(self) -> Hashable | None:
return self._find_valid_index(how="last")
def _doc_params(cls):
| 64 | 64 | 98 | 6 | 58 | smpurkis/pandas | pandas/core/generic.py | Python | _doc_params | _doc_params | 11,412 | 11,419 | 11,412 | 11,412 | 6fbdce53724f097db0dad1fd399b00ad4189ab3b | bigcode/the-stack | train |
78772603d00e1b72d3e628f6 | train | class | class NDFrame(PandasObject, indexing.IndexingMixin):
"""
N-dimensional analogue of DataFrame. Store multi-dimensional in a
size-mutable, labeled data structure
Parameters
----------
data : BlockManager
axes : list
copy : bool, default False
"""
_internal_names: list[str] = [
... | class NDFrame(PandasObject, indexing.IndexingMixin):
| """
N-dimensional analogue of DataFrame. Store multi-dimensional in a
size-mutable, labeled data structure
Parameters
----------
data : BlockManager
axes : list
copy : bool, default False
"""
_internal_names: list[str] = [
"_mgr",
"_cacher",
"_item_cache... | :
from pandas._libs.tslibs import BaseOffset
from pandas.core.frame import DataFrame
from pandas.core.indexers.objects import BaseIndexer
from pandas.core.resample import Resampler
from pandas.core.series import Series
# goal is to be able to define the docs close to function, while still being
#... | 256 | 256 | 92,428 | 12 | 244 | smpurkis/pandas | pandas/core/generic.py | Python | NDFrame | NDFrame | 198 | 11,409 | 198 | 198 | bba7327b3eb6a6394fa63ffd4a6d1e8fa2fad45f | bigcode/the-stack | train |
c68365b6a7017fbc84ff7c20 | train | function | def _align_as_utc(
left: NDFrameT, right: NDFrameT, join_index: Index | None
) -> tuple[NDFrameT, NDFrameT]:
"""
If we are aligning timezone-aware DatetimeIndexes and the timezones
do not match, convert both to UTC.
"""
if is_datetime64tz_dtype(left.index.dtype):
if left.index.tz != righ... | def _align_as_utc(
left: NDFrameT, right: NDFrameT, join_index: Index | None
) -> tuple[NDFrameT, NDFrameT]:
| """
If we are aligning timezone-aware DatetimeIndexes and the timezones
do not match, convert both to UTC.
"""
if is_datetime64tz_dtype(left.index.dtype):
if left.index.tz != right.index.tz:
if join_index is not None:
# GH#33671 ensure we don't change the index on... | the operation. If fewer than
``min_count`` non-NA values are present the result will be NA.
"""
def _align_as_utc(
left: NDFrameT, right: NDFrameT, join_index: Index | None
) -> tuple[NDFrameT, NDFrameT]:
| 64 | 64 | 159 | 39 | 25 | smpurkis/pandas | pandas/core/generic.py | Python | _align_as_utc | _align_as_utc | 12,116 | 12,133 | 12,116 | 12,118 | 79b4782c1d68f2eb93f30c3e85dc03982be0725a | bigcode/the-stack | train |
193dc805371afda11f2a1a81 | train | function | @app.route("/score_alt", methods=["POST"])
def score_alt():
result = model.score(request.data, return_image=True, img_dim=1750)
t = urllib.parse.unquote(result["image"])
image = base64.b64decode(t)
return send_file(
BytesIO(image),
as_attachment=True,
attachment_filename="pred... | @app.route("/score_alt", methods=["POST"])
def score_alt():
| result = model.score(request.data, return_image=True, img_dim=1750)
t = urllib.parse.unquote(result["image"])
image = base64.b64decode(t)
return send_file(
BytesIO(image),
as_attachment=True,
attachment_filename="pred.png",
mimetype="image/png",
)
| .score(request.data, return_image=False, img_dim=1750)
js = json.dumps({"count": int(np.round(result["pred"]))})
resp = Response(js, status=200, mimetype="application/json")
return resp
@app.route("/score_alt", methods=["POST"])
def score_alt():
| 64 | 64 | 84 | 14 | 49 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | score_alt | score_alt | 122 | 135 | 122 | 124 | 8700df62f5a26f0a7e2f753a706e0a80e74f7572 | bigcode/the-stack | train |
ec225a74793868764967ba39 | train | function | @app.route("/uploadfile", methods=["POST"])
def use_upload_file():
uploaded_file = request.files["file"]
request_data = uploaded_file.read()
# score
result = model.score(request_data, return_image=True, img_dim=1750)
pred = result["pred"]
scored_image = result["image"]
txt = "Predicted co... | @app.route("/uploadfile", methods=["POST"])
def use_upload_file():
| uploaded_file = request.files["file"]
request_data = uploaded_file.read()
# score
result = model.score(request_data, return_image=True, img_dim=1750)
pred = result["pred"]
scored_image = result["image"]
txt = "Predicted count: {0}".format(pred)
logger.info("use uploaded file")
ret... | "])
def load():
return render_template(
"index.html", image_names=image_names, actual_counts=actual_counts
)
@app.route("/upload/<filename>")
def send_image(filename):
return send_from_directory("images", filename)
@app.route("/uploadfile", methods=["POST"])
def use_upload_file():
| 64 | 64 | 109 | 15 | 49 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | use_upload_file | use_upload_file | 75 | 88 | 75 | 76 | aacfdde188219b0b45956560b451bfe73f6fcb86 | bigcode/the-stack | train |
8176ac2888311747f64d67ca | train | function | @app.route("/sitefile", methods=["POST"])
def use_site_file():
target = os.path.join(APP_ROOT, "images")
result = request.form["fileindex"]
local_image = "/".join([target, result])
with open(local_image, "rb") as f:
file_bytes = f.read()
# score
result = model.score(file_bytes, return... | @app.route("/sitefile", methods=["POST"])
def use_site_file():
| target = os.path.join(APP_ROOT, "images")
result = request.form["fileindex"]
local_image = "/".join([target, result])
with open(local_image, "rb") as f:
file_bytes = f.read()
# score
result = model.score(file_bytes, return_image=True, img_dim=1750)
pred = result["pred"]
score... | "]
scored_image = result["image"]
txt = "Predicted count: {0}".format(pred)
logger.info("use uploaded file")
return render_template("result.html", scored_image=scored_image, txt=txt)
@app.route("/sitefile", methods=["POST"])
def use_site_file():
| 64 | 64 | 136 | 15 | 49 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | use_site_file | use_site_file | 91 | 109 | 91 | 92 | 0c5f5d6a83b927ab7334e2e6840e016c4ab93f96 | bigcode/the-stack | train |
7c50d954a5e0d8403a79869f | train | function | @app.route("/", methods=["GET"])
def load():
return render_template(
"index.html", image_names=image_names, actual_counts=actual_counts
)
| @app.route("/", methods=["GET"])
def load():
| return render_template(
"index.html", image_names=image_names, actual_counts=actual_counts
)
| CrowdCountModelPose(gpu_id)
# model = CrowdCountModelMCNN(gpu_id, model_path=mcnn_model_path)
model = Router(gpu_id, mcnn_model_path=mcnn_model_path, cutoff_pose=20, cutoff_mcnn=50)
@app.route("/", methods=["GET"])
def load():
| 64 | 64 | 33 | 10 | 54 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | load | load | 63 | 67 | 63 | 64 | b1c37cf80c79e5a2557f218f6ad6fd9929f9e9c0 | bigcode/the-stack | train |
b70d41eb98ce8d7e2eee8fbf | train | function | @app.route("/upload/<filename>")
def send_image(filename):
return send_from_directory("images", filename)
| @app.route("/upload/<filename>")
def send_image(filename):
| return send_from_directory("images", filename)
| cnn_model_path=mcnn_model_path, cutoff_pose=20, cutoff_mcnn=50)
@app.route("/", methods=["GET"])
def load():
return render_template(
"index.html", image_names=image_names, actual_counts=actual_counts
)
@app.route("/upload/<filename>")
def send_image(filename):
| 64 | 64 | 22 | 12 | 52 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | send_image | send_image | 70 | 72 | 70 | 71 | e64c29fda72337267e50a8f9bd47de460ef8f168 | bigcode/the-stack | train |
de9a17e4452ce4cf5191862f | train | function | @app.route("/score", methods=["POST"])
def score():
result = model.score(request.data, return_image=False, img_dim=1750)
js = json.dumps({"count": int(np.round(result["pred"]))})
resp = Response(js, status=200, mimetype="application/json")
return resp
| @app.route("/score", methods=["POST"])
def score():
| result = model.score(request.data, return_image=False, img_dim=1750)
js = json.dumps({"count": int(np.round(result["pred"]))})
resp = Response(js, status=200, mimetype="application/json")
return resp
| _dim=1750)
pred = result["pred"]
scored_image = result["image"]
txt = "Predicted count: {0}".format(pred)
return render_template("result.html", scored_image=scored_image, txt=txt)
@app.route("/score", methods=["POST"])
def score():
| 64 | 64 | 66 | 12 | 52 | muminkoykiran/computervision-recipes | contrib/crowd_counting/crowdcounting/demo/app-advanced.py | Python | score | score | 112 | 119 | 112 | 114 | 3f9a0a867a7233d48d2199c113b9879083c46883 | bigcode/the-stack | train |
f2d3c54a59771830bea54fb1 | train | class | class TrajInfo(AttrDict):
"""
Because it inits as an AttrDict, this has the methods of a dictionary,
e.g. the attributes can be iterated through by traj_info.items()
Intent: all attributes not starting with underscore "_" will be logged.
(Can subclass for more fields.)
Convention: traj_info fiel... | class TrajInfo(AttrDict):
| """
Because it inits as an AttrDict, this has the methods of a dictionary,
e.g. the attributes can be iterated through by traj_info.items()
Intent: all attributes not starting with underscore "_" will be logged.
(Can subclass for more fields.)
Convention: traj_info fields CamelCase, opt_info fie... | next_observation", "done", "env_info"])
class BatchSpec(namedtuple("BatchSpec", "T B")):
"""
T: int Number of time steps, >=1.
B: int Number of separate trajectory segments (i.e. # env instances), >=1.
"""
__slots__ = ()
@property
def size(self):
return self.T * self.B
class Tra... | 95 | 95 | 318 | 8 | 86 | Improbable-AI/curiosity_baselines | rlpyt/samplers/collections.py | Python | TrajInfo | TrajInfo | 29 | 59 | 29 | 29 | 1b41e48ae3788e0a6c86119083f559930574e4d6 | bigcode/the-stack | train |
12459eaece8e924cc1f0bc70 | train | class | class BatchSpec(namedtuple("BatchSpec", "T B")):
"""
T: int Number of time steps, >=1.
B: int Number of separate trajectory segments (i.e. # env instances), >=1.
"""
__slots__ = ()
@property
def size(self):
return self.T * self.B
| class BatchSpec(namedtuple("BatchSpec", "T B")):
| """
T: int Number of time steps, >=1.
B: int Number of separate trajectory segments (i.e. # env instances), >=1.
"""
__slots__ = ()
@property
def size(self):
return self.T * self.B
| ["action", "prev_action", "agent_info", "bootstrap_value"])
EnvSamples = namedarraytuple("EnvSamples",
["reward", "prev_reward", "observation","next_observation", "done", "env_info"])
class BatchSpec(namedtuple("BatchSpec", "T B")):
| 63 | 64 | 75 | 14 | 49 | Improbable-AI/curiosity_baselines | rlpyt/samplers/collections.py | Python | BatchSpec | BatchSpec | 17 | 26 | 17 | 17 | 450543903e91a3b86044a8083767727a42bd6215 | bigcode/the-stack | train |
c2dcc74670a4d227790cf5a4 | train | function | def rotate_pc_along_y(pc, rot_angle):
"""
params pc: (N, 3+C), (N, 3) is in the rectified camera coordinate
params rot_angle: rad scalar
Output pc: updated pc with XYZ rotated
"""
cosval = np.cos(rot_angle)
sinval = np.sin(rot_angle)
rotmat = np.array([[cosval, -sinval], [sinval, cosval]... | def rotate_pc_along_y(pc, rot_angle):
| """
params pc: (N, 3+C), (N, 3) is in the rectified camera coordinate
params rot_angle: rad scalar
Output pc: updated pc with XYZ rotated
"""
cosval = np.cos(rot_angle)
sinval = np.sin(rot_angle)
rotmat = np.array([[cosval, -sinval], [sinval, cosval]])
pc[:, [0, 2]] = np.dot(pc[:, [0... | x = points[:, 0]
y = points[:, 1]
z = points[:, 2]
return (a*x + b*y + c*z + d) / np.sqrt(a**2 + b**2 + c**2)
def rotate_pc_along_y(pc, rot_angle):
| 64 | 64 | 126 | 11 | 53 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | rotate_pc_along_y | rotate_pc_along_y | 72 | 82 | 72 | 72 | 82c807746843e9522ec2fa845483d2805f9c9169 | bigcode/the-stack | train |
8fe85147452a96cef5c2a60b | train | function | def objs_to_scores(obj_list):
scores = np.zeros((obj_list.__len__()), dtype=np.float32)
for k, obj in enumerate(obj_list):
scores[k] = obj.score
return scores
| def objs_to_scores(obj_list):
| scores = np.zeros((obj_list.__len__()), dtype=np.float32)
for k, obj in enumerate(obj_list):
scores[k] = obj.score
return scores
| boxes3d[k, 3], boxes3d[k, 4], boxes3d[k, 5], boxes3d[k, 6] \
= obj.loc, obj.h, obj.w, obj.l, obj.ry
return boxes3d
def objs_to_scores(obj_list):
| 64 | 64 | 46 | 7 | 56 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | objs_to_scores | objs_to_scores | 262 | 266 | 262 | 262 | 200f8632d0964947bb585d6a11e1cf0c4751ee85 | bigcode/the-stack | train |
a9aef2a0233eb57513c4a9cb | train | function | def get_objects_from_file(label_file):
with open(label_file, 'r') as f:
lines = f.readlines()
objects = [Object3d(line) for line in lines]
return objects
| def get_objects_from_file(label_file):
| with open(label_file, 'r') as f:
lines = f.readlines()
objects = [Object3d(line) for line in lines]
return objects
| '''
Copied from PointRCNN
'''
import numpy as np
from scipy.spatial import Delaunay
import scipy
import torch
def get_objects_from_file(label_file):
| 36 | 64 | 44 | 8 | 27 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | get_objects_from_file | get_objects_from_file | 10 | 14 | 10 | 10 | 222d1f4eded69f47fdc69aa163cfd5e55cdce085 | bigcode/the-stack | train |
e3fabec9b9f6e4877c1629c2 | train | function | def enlarge_box3d(boxes3d, extra_width):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
large_boxes3d = boxes3d.copy()
else:
large_boxes3d = boxes3d.clone()
large_boxes3d[:, 3:6] += extra_width * 2
large_boxes3d[:, 1] += extra_width
... | def enlarge_box3d(boxes3d, extra_width):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
large_boxes3d = boxes3d.copy()
else:
large_boxes3d = boxes3d.clone()
large_boxes3d[:, 3:6] += extra_width * 2
large_boxes3d[:, 1] += extra_width
return large_boxes3d
| half_w
boxes_bev[:, 2], boxes_bev[:, 3] = cu + half_l, cv + half_w
boxes_bev[:, 4] = boxes3d[:, 6]
return boxes_bev
def enlarge_box3d(boxes3d, extra_width):
| 64 | 64 | 119 | 13 | 50 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | enlarge_box3d | enlarge_box3d | 199 | 209 | 199 | 199 | 40431838d7b65947a706d4d4db62b9fc31d61fa5 | bigcode/the-stack | train |
98362dababb3c6db35b77b38 | train | function | def corners3d_to_frustums2d(corners):
azims = np.arctan2(corners[:, :, 2], corners[:, :, 0])
azims_min = np.min(azims, axis=1)
azims_max = np.max(azims, axis=1)
frustum2d = np.vstack((azims_min, azims_max)).T
return frustum2d
| def corners3d_to_frustums2d(corners):
| azims = np.arctan2(corners[:, :, 2], corners[:, :, 0])
azims_min = np.min(azims, axis=1)
azims_max = np.max(azims, axis=1)
frustum2d = np.vstack((azims_min, azims_max)).T
return frustum2d
| )
corners_rotated = corners_rotated + centers.unsqueeze(dim=2).expand(-1, -1, 8)
corners_rotated = corners_rotated.permute(0, 2, 1)
return corners_rotated
def corners3d_to_frustums2d(corners):
| 64 | 64 | 91 | 13 | 50 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | corners3d_to_frustums2d | corners3d_to_frustums2d | 175 | 180 | 175 | 175 | d335ab1e6b959d5e8914f090a4475069f9b4125f | bigcode/the-stack | train |
1b68a52bd7b07e8377f22913 | train | class | class Calibration(object):
def __init__(self, calib_file):
if isinstance(calib_file, str):
calib = get_calib_from_file(calib_file)
else:
calib = calib_file
self.P2 = calib['P2'] # 3 x 4
self.R0 = calib['R0'] # 3 x 3
self.V2C = calib['Tr_velo2cam'] ... | class Calibration(object):
| def __init__(self, calib_file):
if isinstance(calib_file, str):
calib = get_calib_from_file(calib_file)
else:
calib = calib_file
self.P2 = calib['P2'] # 3 x 4
self.R0 = calib['R0'] # 3 x 3
self.V2C = calib['Tr_velo2cam'] # 3 x 4
# Camera i... | [0, 2]].T)
if bottom_a.is_valid and bottom_b.is_valid:
# check is valid, A valid Polygon may not possess any overlapping exterior or interior rings.
bottom_overlap = bottom_a.intersection(bottom_b).area
else:
bottom_overlap = 0.
overl... | 256 | 256 | 1,486 | 4 | 252 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | Calibration | Calibration | 324 | 440 | 324 | 324 | 8a68e718d744f4c3835c4a6eff187f183d33cd04 | bigcode/the-stack | train |
9c8a1970defa93136da2aae4 | train | function | def boxes3d_to_bev_torch(boxes3d):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:return:
boxes_bev: (N, 5) [x1, y1, x2, y2, ry]
"""
boxes_bev = boxes3d.new(torch.Size((boxes3d.shape[0], 5)))
cu, cv = boxes3d[:, 0], boxes3d[:, 2]
half_l, half_w = boxes3d[:, 5] / 2, boxes3d[:, 4]... | def boxes3d_to_bev_torch(boxes3d):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:return:
boxes_bev: (N, 5) [x1, y1, x2, y2, ry]
"""
boxes_bev = boxes3d.new(torch.Size((boxes3d.shape[0], 5)))
cu, cv = boxes3d[:, 0], boxes3d[:, 2]
half_l, half_w = boxes3d[:, 5] / 2, boxes3d[:, 4] / 2
boxes_bev[:, 0], boxes_bev... | = np.min(azims, axis=1)
azims_max = np.max(azims, axis=1)
frustum2d = np.vstack((azims_min, azims_max)).T
return frustum2d
def boxes3d_to_bev_torch(boxes3d):
| 66 | 66 | 220 | 14 | 51 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | boxes3d_to_bev_torch | boxes3d_to_bev_torch | 183 | 196 | 183 | 183 | 62362516e4df3f36de751772bfbc865e04abffc8 | bigcode/the-stack | train |
a80b248fb5742714536f6f4c | train | function | def box3d_remove_roof(boxes3d, h_prop=0.35):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
rf_boxes3d = boxes3d.copy()
else:
rf_boxes3d = boxes3d.clone()
dh = rf_boxes3d[:, 3] * h_prop
rf_boxes3d[:, 3] -= dh
return rf_boxes3d
| def box3d_remove_roof(boxes3d, h_prop=0.35):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
rf_boxes3d = boxes3d.copy()
else:
rf_boxes3d = boxes3d.clone()
dh = rf_boxes3d[:, 3] * h_prop
rf_boxes3d[:, 3] -= dh
return rf_boxes3d
| dh = rg_boxes3d[:, 3] * h_prop
rg_boxes3d[:, 3] -= dh
rg_boxes3d[:, 1] -= dh
return rg_boxes3d
def box3d_remove_roof(boxes3d, h_prop=0.35):
| 64 | 64 | 121 | 19 | 44 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | box3d_remove_roof | box3d_remove_roof | 225 | 235 | 225 | 225 | 286827294a74d23e8141d7107d11d6b8db44d4e1 | bigcode/the-stack | train |
4744db6a25054ed67e642e36 | train | function | def get_pc_in_camera_flag(pts_rect, calib, img_shape):
pts_img, pts_rect_depth = calib.rect_to_img(pts_rect)
val_flag_1 = np.logical_and(pts_img[:, 0] >= 0, pts_img[:, 0] < img_shape[0])
val_flag_2 = np.logical_and(pts_img[:, 1] >= 0, pts_img[:, 1] < img_shape[1])
val_flag_merge = np.logical_and(val_fl... | def get_pc_in_camera_flag(pts_rect, calib, img_shape):
| pts_img, pts_rect_depth = calib.rect_to_img(pts_rect)
val_flag_1 = np.logical_and(pts_img[:, 0] >= 0, pts_img[:, 0] < img_shape[0])
val_flag_2 = np.logical_and(pts_img[:, 1] >= 0, pts_img[:, 1] < img_shape[1])
val_flag_merge = np.logical_and(val_flag_1, val_flag_2)
pts_valid_flag = np.logical_and(va... | 'P3': P3.reshape(3, 4),
'R0': R0.reshape(3, 3),
'Tr_velo2cam': Tr_velo_to_cam.reshape(3, 4)}
def get_pc_in_camera_flag(pts_rect, calib, img_shape):
| 63 | 64 | 138 | 15 | 48 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | get_pc_in_camera_flag | get_pc_in_camera_flag | 36 | 44 | 36 | 37 | 142f79bfb06e590a10d33cf21953ccb71ddec58c | bigcode/the-stack | train |
559517f50d0d36661f1388dd | train | function | def cls_type_to_id(cls_type):
TYPE_ID_CONVERSION = {
'Car': 0,
'Cyclist': 1,
'Pedestrian': 2,
}
if cls_type not in TYPE_ID_CONVERSION.keys():
return -1
return TYPE_ID_CONVERSION[cls_type]
| def cls_type_to_id(cls_type):
| TYPE_ID_CONVERSION = {
'Car': 0,
'Cyclist': 1,
'Pedestrian': 2,
}
if cls_type not in TYPE_ID_CONVERSION.keys():
return -1
return TYPE_ID_CONVERSION[cls_type]
| d / union3d
iou_bev[i][j] = bottom_overlap / (bottom_a.area + bottom_b.area - bottom_overlap)
if need_bev:
return iou3d, iou_bev
return iou3d
def cls_type_to_id(cls_type):
| 64 | 64 | 67 | 8 | 55 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | cls_type_to_id | cls_type_to_id | 312 | 321 | 312 | 313 | 582de6f90a9fd849c99d82643dfb71670d8346be | bigcode/the-stack | train |
6f757cfc1cd4cc1d04da972b | train | function | def filter_objects(objects, black_list=['DontCare', 'Misc']):
valid_objects = []
for obj in objects:
if obj.cls_type not in black_list:
valid_objects.append(obj)
return valid_objects
| def filter_objects(objects, black_list=['DontCare', 'Misc']):
| valid_objects = []
for obj in objects:
if obj.cls_type not in black_list:
valid_objects.append(obj)
return valid_objects
| ] < img_shape[1])
val_flag_merge = np.logical_and(val_flag_1, val_flag_2)
pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0)
return pts_valid_flag
def filter_objects(objects, black_list=['DontCare', 'Misc']):
| 64 | 64 | 46 | 14 | 49 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | filter_objects | filter_objects | 47 | 52 | 47 | 47 | 22952375f980dc3fa1b661e3b6c37b2be622f878 | bigcode/the-stack | train |
9aefe333fe0edeadaaea4cde | train | class | class Object3d(object):
TYPE_ID_CONVERSION = {
'Car': 0,
'Cyclist': 1,
'Pedestrian': 2,
}
def __init__(self, line):
label = line.strip().split(' ')
self.src = line
self.cls_type = label[0]
self.cls_id = self.cls_type_to_id(self.cls_ty... | class Object3d(object):
| TYPE_ID_CONVERSION = {
'Car': 0,
'Cyclist': 1,
'Pedestrian': 2,
}
def __init__(self, line):
label = line.strip().split(' ')
self.src = line
self.cls_type = label[0]
self.cls_id = self.cls_type_to_id(self.cls_type)
self.trucatio... | _to_rect(self, u, v, d):
"""
Can only process valid u, v, d, which means u, v can not beyond the image shape, reprojection error 0.02
:param u: (N)
:param v: (N)
:param d: (N), the distance between camera and 3d points, d^2 = x^2 + y^2 + z^2
:return:
"""
a... | 256 | 256 | 1,260 | 6 | 249 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | Object3d | Object3d | 443 | 538 | 443 | 444 | b0c649fe3397af2e5e97222781ebdd2205586442 | bigcode/the-stack | train |
ddfaabcb9259e24c3e46167c | train | function | def rotate_pc_along_y_torch(pc, rot_angle):
"""
:param pc: (N, 512, 3 + C)
:param rot_angle: (N)
:return:
TODO: merge with rotate_pc_along_y_torch in bbox_transform.py
"""
cosa = torch.cos(rot_angle).view(-1, 1) # (N, 1)
sina = torch.sin(rot_angle).view(-1, 1) # (N, 1)
raw_1 = tor... | def rotate_pc_along_y_torch(pc, rot_angle):
| """
:param pc: (N, 512, 3 + C)
:param rot_angle: (N)
:return:
TODO: merge with rotate_pc_along_y_torch in bbox_transform.py
"""
cosa = torch.cos(rot_angle).view(-1, 1) # (N, 1)
sina = torch.sin(rot_angle).view(-1, 1) # (N, 1)
raw_1 = torch.cat([cosa, -sina], dim=1) # (N, 2)
r... | val = np.cos(rot_angle)
sinval = np.sin(rot_angle)
rotmat = np.array([[cosval, -sinval], [sinval, cosval]])
pc[:, [0, 2]] = np.dot(pc[:, [0, 2]], np.transpose(rotmat))
return pc
def rotate_pc_along_y_torch(pc, rot_angle):
| 79 | 79 | 265 | 13 | 65 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | rotate_pc_along_y_torch | rotate_pc_along_y_torch | 85 | 103 | 85 | 85 | ccc88c0ec4b446f68d4bda84e5910526ac36911e | bigcode/the-stack | train |
e7a283215506b03a3b147bf5 | train | function | def boxes3d_to_corners3d(boxes3d, rotate=True):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:param rotate:
:return: corners3d: (N, 8, 3)
"""
boxes_num = boxes3d.shape[0]
h, w, l = boxes3d[:, 3], boxes3d[:, 4], boxes3d[:, 5]
x_corners = np.array([l / 2., l / 2., -l / 2., -l / 2., l ... | def boxes3d_to_corners3d(boxes3d, rotate=True):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:param rotate:
:return: corners3d: (N, 8, 3)
"""
boxes_num = boxes3d.shape[0]
h, w, l = boxes3d[:, 3], boxes3d[:, 4], boxes3d[:, 5]
x_corners = np.array([l / 2., l / 2., -l / 2., -l / 2., l / 2., l / 2., -l / 2., -l / 2.], dtype=np.float3... | view(-1, 1) # (N, 1)
sina = torch.sin(rot_angle).view(-1, 1) # (N, 1)
raw_1 = torch.cat([cosa, -sina], dim=1) # (N, 2)
raw_2 = torch.cat([sina, cosa], dim=1) # (N, 2)
R = torch.cat((raw_1.unsqueeze(dim=1), raw_2.unsqueeze(dim=1)), dim=1) # (N, 2, 2)
pc_temp = pc[:, :, [0, 2]] # (N, 512, 2)
... | 211 | 211 | 705 | 17 | 193 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | boxes3d_to_corners3d | boxes3d_to_corners3d | 106 | 142 | 106 | 106 | b9798df367ec89ff3dbf300cd1c8dfd861d7c778 | bigcode/the-stack | train |
d7d6af6a8ac39e0a6740e6bc | train | function | def in_hull(p, hull):
"""
:param p: (N, K) test points
:param hull: (M, K) M corners of a box
:return (N) bool
"""
try:
if not isinstance(hull, Delaunay):
hull = Delaunay(hull)
flag = hull.find_simplex(p) >= 0
except scipy.spatial.qhull.QhullError:
print('... | def in_hull(p, hull):
| """
:param p: (N, K) test points
:param hull: (M, K) M corners of a box
:return (N) bool
"""
try:
if not isinstance(hull, Delaunay):
hull = Delaunay(hull)
flag = hull.find_simplex(p) >= 0
except scipy.spatial.qhull.QhullError:
print('Warning: not a hull %s... | 3d = boxes3d.copy()
else:
rf_boxes3d = boxes3d.clone()
dh = rf_boxes3d[:, 3] * h_prop
rf_boxes3d[:, 3] -= dh
return rf_boxes3d
def in_hull(p, hull):
| 64 | 64 | 132 | 8 | 55 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | in_hull | in_hull | 237 | 251 | 237 | 237 | 591d92b3d9b990ba593348994f4c2b628f5ce298 | bigcode/the-stack | train |
28b2276929f21801c874b389 | train | function | def objs_to_boxes3d(obj_list):
boxes3d = np.zeros((obj_list.__len__(), 7), dtype=np.float32)
for k, obj in enumerate(obj_list):
boxes3d[k, 0:3], boxes3d[k, 3], boxes3d[k, 4], boxes3d[k, 5], boxes3d[k, 6] \
= obj.loc, obj.h, obj.w, obj.l, obj.ry
return boxes3d
| def objs_to_boxes3d(obj_list):
| boxes3d = np.zeros((obj_list.__len__(), 7), dtype=np.float32)
for k, obj in enumerate(obj_list):
boxes3d[k, 0:3], boxes3d[k, 3], boxes3d[k, 4], boxes3d[k, 5], boxes3d[k, 6] \
= obj.loc, obj.h, obj.w, obj.l, obj.ry
return boxes3d
| _simplex(p) >= 0
except scipy.spatial.qhull.QhullError:
print('Warning: not a hull %s' % str(hull))
flag = np.zeros(p.shape[0], dtype=np.bool)
return flag
def objs_to_boxes3d(obj_list):
| 64 | 64 | 109 | 9 | 54 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | objs_to_boxes3d | objs_to_boxes3d | 254 | 259 | 254 | 254 | c32fd7c60e17d5bcecaa0bf5d77a8f06e82844d5 | bigcode/the-stack | train |
ac52225560e31b933e9d0d6b | train | function | def get_calib_from_file(calib_file):
with open(calib_file) as f:
lines = f.readlines()
obj = lines[2].strip().split(' ')[1:]
P2 = np.array(obj, dtype=np.float32)
obj = lines[3].strip().split(' ')[1:]
P3 = np.array(obj, dtype=np.float32)
obj = lines[4].strip().split(' ')[1:]
R0 = np.... | def get_calib_from_file(calib_file):
| with open(calib_file) as f:
lines = f.readlines()
obj = lines[2].strip().split(' ')[1:]
P2 = np.array(obj, dtype=np.float32)
obj = lines[3].strip().split(' ')[1:]
P3 = np.array(obj, dtype=np.float32)
obj = lines[4].strip().split(' ')[1:]
R0 = np.array(obj, dtype=np.float32)
obj ... | Delaunay
import scipy
import torch
def get_objects_from_file(label_file):
with open(label_file, 'r') as f:
lines = f.readlines()
objects = [Object3d(line) for line in lines]
return objects
def get_calib_from_file(calib_file):
| 64 | 64 | 200 | 10 | 53 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | get_calib_from_file | get_calib_from_file | 17 | 33 | 17 | 17 | a007c0cccd18635acb79416c3f6359a2e53e3048 | bigcode/the-stack | train |
8fce50fe7bf64c5d735dd964 | train | function | def get_iou3d(corners3d, query_corners3d, need_bev=False):
"""
:param corners3d: (N, 8, 3) in rect coords
:param query_corners3d: (M, 8, 3)
:return:
"""
from shapely.geometry import Polygon
A, B = corners3d, query_corners3d
N, M = A.shape[0], B.shape[0]
iou3d = np.zeros((N, M), d... | def get_iou3d(corners3d, query_corners3d, need_bev=False):
| """
:param corners3d: (N, 8, 3) in rect coords
:param query_corners3d: (M, 8, 3)
:return:
"""
from shapely.geometry import Polygon
A, B = corners3d, query_corners3d
N, M = A.shape[0], B.shape[0]
iou3d = np.zeros((N, M), dtype=np.float32)
iou_bev = np.zeros((N, M), dtype=np.fl... | ):
boxes3d = np.zeros((obj_list.__len__(), 7), dtype=np.float32)
for k, obj in enumerate(obj_list):
boxes3d[k, 0:3], boxes3d[k, 3], boxes3d[k, 4], boxes3d[k, 5], boxes3d[k, 6] \
= obj.loc, obj.h, obj.w, obj.l, obj.ry
return boxes3d
def objs_to_scores(obj_list):
scores = np.zeros((o... | 169 | 169 | 566 | 22 | 146 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | get_iou3d | get_iou3d | 269 | 309 | 269 | 269 | bb4ae830c5968f6d0952b7e5c0d90df20143c69b | bigcode/the-stack | train |
991416ebc3eb8dd77c6cd9e8 | train | function | def dist_to_plane(plane, points):
"""
Calculates the signed distance from a 3D plane to each point in a list of points
:param plane: (a, b, c, d)
:param points: (N, 3)
:return: (N), signed distance of each point to the plane
"""
a, b, c, d = plane
points = np.array(points)
x = point... | def dist_to_plane(plane, points):
| """
Calculates the signed distance from a 3D plane to each point in a list of points
:param plane: (a, b, c, d)
:param points: (N, 3)
:return: (N), signed distance of each point to the plane
"""
a, b, c, d = plane
points = np.array(points)
x = points[:, 0]
y = points[:, 1]
z... | 0)
return pts_valid_flag
def filter_objects(objects, black_list=['DontCare', 'Misc']):
valid_objects = []
for obj in objects:
if obj.cls_type not in black_list:
valid_objects.append(obj)
return valid_objects
def dist_to_plane(plane, points):
| 64 | 64 | 145 | 9 | 54 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | dist_to_plane | dist_to_plane | 55 | 69 | 55 | 55 | 9cd35ec120b3b8dd993cc32f13c7755e39a3cb65 | bigcode/the-stack | train |
f4e581d04d07a126fa19864d | train | function | def box3d_remove_ground(boxes3d, h_prop=0.15):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
rg_boxes3d = boxes3d.copy()
else:
rg_boxes3d = boxes3d.clone()
dh = rg_boxes3d[:, 3] * h_prop
rg_boxes3d[:, 3] -= dh
rg_boxes3d[:, 1] -... | def box3d_remove_ground(boxes3d, h_prop=0.15):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
"""
if isinstance(boxes3d, np.ndarray):
rg_boxes3d = boxes3d.copy()
else:
rg_boxes3d = boxes3d.clone()
dh = rg_boxes3d[:, 3] * h_prop
rg_boxes3d[:, 3] -= dh
rg_boxes3d[:, 1] -= dh
return rg_boxes3d
| 3d = boxes3d.clone()
large_boxes3d[:, 3:6] += extra_width * 2
large_boxes3d[:, 1] += extra_width
return large_boxes3d
def box3d_remove_ground(boxes3d, h_prop=0.15):
| 64 | 64 | 132 | 18 | 45 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | box3d_remove_ground | box3d_remove_ground | 212 | 223 | 212 | 212 | 28be118780ec7d39a9446037ad2096993b106dc8 | bigcode/the-stack | train |
560dfe25c951f3e00b998df1 | train | function | def boxes3d_to_corners3d_torch(boxes3d, flip=False):
"""
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:return: corners_rotated: (N, 8, 3)
"""
boxes_num = boxes3d.shape[0]
h, w, l, ry = boxes3d[:, 3:4], boxes3d[:, 4:5], boxes3d[:, 5:6], boxes3d[:, 6:7]
if flip:
ry = ry + np.pi
ce... | def boxes3d_to_corners3d_torch(boxes3d, flip=False):
| """
:param boxes3d: (N, 7) [x, y, z, h, w, l, ry]
:return: corners_rotated: (N, 8, 3)
"""
boxes_num = boxes3d.shape[0]
h, w, l, ry = boxes3d[:, 3:4], boxes3d[:, 4:5], boxes3d[:, 5:6], boxes3d[:, 6:7]
if flip:
ry = ry + np.pi
centers = boxes3d[:, 0:3]
zeros = torch.cuda.FloatT... | [:, :, 2]
x_loc, y_loc, z_loc = boxes3d[:, 0], boxes3d[:, 1], boxes3d[:, 2]
x = x_loc.reshape(-1, 1) + x_corners.reshape(-1, 8)
y = y_loc.reshape(-1, 1) + y_corners.reshape(-1, 8)
z = z_loc.reshape(-1, 1) + z_corners.reshape(-1, 8)
corners = np.concatenate((x.reshape(-1, 8, 1), y.reshape(-1, 8, 1... | 175 | 175 | 586 | 19 | 156 | dashidhy/SMOKE | smoke/utils/kitti_utils.py | Python | boxes3d_to_corners3d_torch | boxes3d_to_corners3d_torch | 145 | 172 | 145 | 145 | e8f78dcd62e4d47badd11a84ae586b60dd956590 | bigcode/the-stack | train |
facf13c274e440d7cf22e561 | train | function | def fail_json(*args, **kwargs):
"""function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
| def fail_json(*args, **kwargs):
| """function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
| mock.MagicMock()
def exit_json(*args, **kwargs):
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs):
| 64 | 64 | 41 | 9 | 55 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | fail_json | fail_json | 36 | 39 | 36 | 36 | 944832b03e9a018031c48e1a1fef1334a690b4a5 | bigcode/the-stack | train |
6fc20c8e78cc6750d8eacaee | train | class | class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
| class AnsibleExitJson(Exception):
| """Exception class to be raised by module.exit_json and caught by the test case"""
pass
| kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
def fail_json(*args, **kwargs):
"""function to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
class AnsibleExitJson(Exception):
| 64 | 64 | 28 | 7 | 57 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | AnsibleExitJson | AnsibleExitJson | 42 | 44 | 42 | 42 | f96d56ec5fcde067182aa492e7585ea288ba46b0 | bigcode/the-stack | train |
50109797011cedcf5e109b26 | train | class | class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught by the test case"""
pass
| class AnsibleFailJson(Exception):
| """Exception class to be raised by module.fail_json and caught by the test case"""
pass
| to patch over fail_json; package return data into an exception"""
kwargs['failed'] = True
raise AnsibleFailJson(kwargs)
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
class AnsibleFailJson(Exception):
| 64 | 64 | 28 | 7 | 56 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | AnsibleFailJson | AnsibleFailJson | 47 | 49 | 47 | 47 | 3a6506771379473f1ecf2c68de5cc25addd3b29a | bigcode/the-stack | train |
db989b7575a1c791063739dd | train | class | class FakeCloud(object):
"""This is a fake conn object
"""
instance = mock.MagicMock()
instance.to_dict = mock.MagicMock(return_value={'a': 'b'})
instance.id = 1
instance.job_id = 'fake_job_id'
create_rds_instance = mock.MagicMock(return_value=instance)
delete_rds_instance = mock.Magic... | class FakeCloud(object):
| """This is a fake conn object
"""
instance = mock.MagicMock()
instance.to_dict = mock.MagicMock(return_value={'a': 'b'})
instance.id = 1
instance.job_id = 'fake_job_id'
create_rds_instance = mock.MagicMock(return_value=instance)
delete_rds_instance = mock.MagicMock(return_value=None)
... | import json
from unittest import TestCase, mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
from ansible_collections.opentelekomcloud.cloud.plugins.modules import (
rds_instance
)
class FakeCloud(object):
| 56 | 64 | 118 | 5 | 51 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | FakeCloud | FakeCloud | 13 | 26 | 13 | 13 | 7d49eab67a5a49606253b438b32d099da2b71778 | bigcode/the-stack | train |
7646c695c9c00e02d72c71d4 | train | function | def exit_json(*args, **kwargs):
"""function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
| def exit_json(*args, **kwargs):
| """function to patch over exit_json; package return data into an exception"""
if 'changed' not in kwargs:
kwargs['changed'] = False
raise AnsibleExitJson(kwargs)
| = mock.MagicMock(return_value=instance)
delete_rds_instance = mock.MagicMock(return_value=None)
rds = mock.MagicMock()
rds.find_instance = mock.MagicMock()
rds.delete_instance = mock.MagicMock()
def exit_json(*args, **kwargs):
| 64 | 64 | 50 | 9 | 55 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | exit_json | exit_json | 29 | 33 | 29 | 29 | ad3ca9a3f4bfcbbe6bde64a06f07a8c2420b8f14 | bigcode/the-stack | train |
47b322825ce42f266b633019 | train | class | class RdsInstanceTest(TestCase):
def setUp(self):
self.mock_module_helper = mock.patch.multiple(
basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json)
self.mock_module_helper.start()
self.addCleanup(self.mock_module_helper.stop)
self.con... | class RdsInstanceTest(TestCase):
| def setUp(self):
self.mock_module_helper = mock.patch.multiple(
basic.AnsibleModule,
exit_json=exit_json,
fail_json=fail_json)
self.mock_module_helper.start()
self.addCleanup(self.mock_module_helper.stop)
self.conn = FakeCloud()
self.modul... | _instance = mock.MagicMock(return_value=instance)
delete_rds_instance = mock.MagicMock(return_value=None)
rds = mock.MagicMock()
rds.find_instance = mock.MagicMock()
rds.delete_instance = mock.MagicMock()
def exit_json(*args, **kwargs):
"""function to patch over exit_json; package return data into... | 256 | 256 | 863 | 8 | 248 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | RdsInstanceTest | RdsInstanceTest | 58 | 180 | 58 | 59 | 6d3a4ab394df4a9064e9e3d73c32094011687c0f | bigcode/the-stack | train |
0b2d24ca4ad2d0f828302334 | train | function | def set_module_args(args):
"""prepare arguments so that they will be picked up during module creation"""
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args)
| def set_module_args(args):
| """prepare arguments so that they will be picked up during module creation"""
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args)
| (kwargs)
class AnsibleExitJson(Exception):
"""Exception class to be raised by module.exit_json and caught by the test case"""
pass
class AnsibleFailJson(Exception):
"""Exception class to be raised by module.fail_json and caught by the test case"""
pass
def set_module_args(args):
| 64 | 64 | 45 | 6 | 57 | OpenTelekomCloud/ansible_collections | tests/unit/modules/rds_instance/test_rds_instance.py | Python | set_module_args | set_module_args | 52 | 55 | 52 | 52 | adddedf246fda431a84eeef9a0fcb5431b4fe42f | bigcode/the-stack | train |
0acdd46a397a249b39a1a128 | train | function | def stop_process():
try:
global do_process
if do_process:
print('终止任务')
ctrl = Control(app=app)
ctrl.revoke(str(do_process.id), terminate=True)
do_process = None
except Exception as e:
logger.error(e)
| def stop_process():
| try:
global do_process
if do_process:
print('终止任务')
ctrl = Control(app=app)
ctrl.revoke(str(do_process.id), terminate=True)
do_process = None
except Exception as e:
logger.error(e)
| Response,StreamingHttpResponse
from .models import TCompModel
from .tasks import dotest
from config.settings import UPLOAD_DIR, TEST_TEMPLATE_DIR
from commoninterface.utils import make_zip
logger = logging.getLogger('ghost')
do_process = None
# Create your views here.
def stop_process():
| 64 | 64 | 61 | 4 | 60 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | stop_process | stop_process | 22 | 31 | 22 | 22 | 832b5203566a83d60be11592ceb9d2d123453234 | bigcode/the-stack | train |
31f06a02c41fa87af168dbec | train | function | @csrf_exempt
def show_tempcomp_history(request):
response = {}
try:
params =TCompModel.objects.all()
response['params'] = json.loads(serializers.serialize("json", params))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = s... | @csrf_exempt
def show_tempcomp_history(request):
| response = {}
try:
params =TCompModel.objects.all()
response['params'] = json.loads(serializers.serialize("json", params))
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
retur... | (file_iterator(zip_file))
# response['content-type'] = 'application/octet-stream'
response['content-type'] = 'application/zip'
response['Content-Disposition'] = "attachment; filename = {}".format('export.zip')
return response
@csrf_exempt
def show_tempcomp_history(request):
| 64 | 64 | 93 | 12 | 51 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | show_tempcomp_history | show_tempcomp_history | 75 | 86 | 75 | 76 | c00d6cd257d86ebc6413c5144b5b14ef31259a96 | bigcode/the-stack | train |
590eebcd96aa4c148289124b | train | function | @csrf_exempt
def tempcomp_upload(request):
try:
if request.method == 'POST':
tcomp_params = TCompModel()
data = request.POST
fsvip = data.get('fsvip', None)
boardip = data.get('boardip', None)
file = request.FILES.get('file', None)
por... | @csrf_exempt
def tempcomp_upload(request):
| try:
if request.method == 'POST':
tcomp_params = TCompModel()
data = request.POST
fsvip = data.get('fsvip', None)
boardip = data.get('boardip', None)
file = request.FILES.get('file', None)
port = data.get('port', '')
if fi... | response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
@csrf_exempt
def clear_tempcomp_history(request):
# 清空数据库历史记录
response = {}
try:
TCompModel.objects.all().delete()
response['msg'] = 'success'
response['error_num'] = 0
except Exception... | 121 | 121 | 406 | 11 | 110 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | tempcomp_upload | tempcomp_upload | 101 | 146 | 101 | 102 | 27b4abb971740cbcdf4373d529a6496fcf023e53 | bigcode/the-stack | train |
a31348d4040fcf1b0d5194e2 | train | function | @csrf_exempt
def set_tempcomp_history(request):
try:
if request.method == 'POST':
postbody = request.body
data = json.loads(postbody)
port = data.get('port', '')
print(data)
thconf = {}
if port:
thconf = {
... | @csrf_exempt
def set_tempcomp_history(request):
| try:
if request.method == 'POST':
postbody = request.body
data = json.loads(postbody)
port = data.get('port', '')
print(data)
thconf = {}
if port:
thconf = {
"PORT": port
}
... | do_process=None
return JsonResponse({'result': ret,'message':message,'filepath':endpath})
else:
return JsonResponse({'result': False,'message': '测试模板缺失'})
except Exception as e:
logger.error('lvboqi_upload error:{}'.format(e))
return JsonResponse({'result... | 88 | 89 | 299 | 12 | 76 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | set_tempcomp_history | set_tempcomp_history | 148 | 184 | 148 | 149 | 28cf38529f4254876fa05d3a4c5ced88523c6609 | bigcode/the-stack | train |
c03d201d20e1ea6d4a76b8f7 | train | function | def write_file(fp):
if fp is None:
return None
dir = UPLOAD_DIR
if not os.path.exists(dir):
os.mkdir(dir)
filepath = os.path.join(dir, fp.name)
destination = open(filepath, 'wb+')
try:
for chunk in fp.chunks():
destination.write(chunk)
return filepath
... | def write_file(fp):
| if fp is None:
return None
dir = UPLOAD_DIR
if not os.path.exists(dir):
os.mkdir(dir)
filepath = os.path.join(dir, fp.name)
destination = open(filepath, 'wb+')
try:
for chunk in fp.chunks():
destination.write(chunk)
return filepath
except Exception... | _process():
try:
global do_process
if do_process:
print('终止任务')
ctrl = Control(app=app)
ctrl.revoke(str(do_process.id), terminate=True)
do_process = None
except Exception as e:
logger.error(e)
def write_file(fp):
| 64 | 64 | 91 | 5 | 59 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | write_file | write_file | 33 | 48 | 33 | 33 | 228f297dec7da4166586b2cea37d56633cc9c955 | bigcode/the-stack | train |
5f7becdc0ded8f683187e4a4 | train | function | @csrf_exempt
def big_file_download(request):
def file_iterator(file_name, chunk_size=512):
with open(file_name,'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
postbody = request.... | @csrf_exempt
def big_file_download(request):
| def file_iterator(file_name, chunk_size=512):
with open(file_name,'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
postbody = request.body
data = json.loads(postbody)
the_... | os.path.join(dir, fp.name)
destination = open(filepath, 'wb+')
try:
for chunk in fp.chunks():
destination.write(chunk)
return filepath
except Exception:
return None
finally:
destination.close()
@csrf_exempt
def big_file_download(request):
| 64 | 64 | 196 | 11 | 53 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | big_file_download | big_file_download | 50 | 73 | 50 | 51 | 410e82d1cc761699e3227e584b04561b436c115a | bigcode/the-stack | train |
1a23e9fbd93e04a0ab64c84e | train | function | @csrf_exempt
def clear_tempcomp_history(request):
# 清空数据库历史记录
response = {}
try:
TCompModel.objects.all().delete()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonRespon... | @csrf_exempt
def clear_tempcomp_history(request):
# 清空数据库历史记录
| response = {}
try:
TCompModel.objects.all().delete()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
| 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
@csrf_exempt
def clear_tempcomp_history(request):
# 清空数据库历史记录
| 64 | 64 | 86 | 20 | 44 | coderdq/vuetest | WEB21-1-12/WEB2/tempcomp/views.py | Python | clear_tempcomp_history | clear_tempcomp_history | 88 | 99 | 88 | 90 | e9fb126a83b0b7858717e8c837abcbc153db6665 | bigcode/the-stack | train |
158e4f1f987a35c0e16976ef | train | function | def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
... | def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
| if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
... | ig_import_helper
else:
import _hankel
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
| 64 | 64 | 129 | 19 | 45 | poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/hankel.py | Python | _swig_setattr_nondynamic | _swig_setattr_nondynamic | 37 | 48 | 37 | 37 | a2796cdcb7531ea3c2396b4348b7f4b3a0e76b7e | bigcode/the-stack | train |
9123a3e113657c3cb957f5e4 | train | function | def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
| def _swig_repr(self):
| try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
| 0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
| 64 | 64 | 59 | 7 | 57 | poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/hankel.py | Python | _swig_repr | _swig_repr | 59 | 62 | 59 | 59 | 4eddd4ed8741875cdf5c4f1eec34af6dd3075dcc | bigcode/the-stack | train |
0612220c3bda6b74fe01cf3b | train | function | def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
| def _swig_setattr(self,class_type,name,value):
| return _swig_setattr_nondynamic(self,class_type,name,value,0)
| ig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
| 64 | 64 | 30 | 12 | 52 | poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/hankel.py | Python | _swig_setattr | _swig_setattr | 50 | 51 | 50 | 50 | 114f2441fba95e316198424891d5b750117feafe | bigcode/the-stack | train |
bf10006b79d14d04c9a475ff | train | class | class DiscreteHankelTransform(_object):
__swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, DiscreteHankelTransform, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, DiscreteHankelTransform, name)
__repr__ = _swig_repr
de... | class DiscreteHankelTransform(_object):
| __swig_setmethods__ = {}
__setattr__ = lambda self, name, value: _swig_setattr(self, DiscreteHankelTransform, name, value)
__swig_getmethods__ = {}
__getattr__ = lambda self, name: _swig_getattr(self, DiscreteHankelTransform, name)
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
... | try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
class DiscreteHankelTransform(_object):
| 97 | 97 | 324 | 10 | 86 | poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/hankel.py | Python | DiscreteHankelTransform | DiscreteHankelTransform | 72 | 88 | 72 | 72 | 181d0ca6b4c34facf0c5b386c1cb7c8d5f3983da | bigcode/the-stack | train |
1fd06faafaff744342ea8a77 | train | function | def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
| def _swig_getattr(self,class_type,name):
| if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
| ] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
| 64 | 64 | 55 | 11 | 53 | poojavade/Genomics_Docker | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/hankel.py | Python | _swig_getattr | _swig_getattr | 53 | 57 | 53 | 53 | be89c1384010ba055c25fd0236cc9b82ea164367 | bigcode/the-stack | train |
0de2bbf6e8bae07a45b1ffdb | train | class | class CleanDatabase(object):
def __init__(self):
self.db_tables = [User, PaperSignal, PaperTrade, CurrentQuote, PaperTradedStrategy, ExamplePaperTraderModel,
BackTestTrade, BackTestReport, ExampleBackTesterModel,
VisualizationType, Trade, Order, Signal, St... | class CleanDatabase(object):
| def __init__(self):
self.db_tables = [User, PaperSignal, PaperTrade, CurrentQuote, PaperTradedStrategy, ExamplePaperTraderModel,
BackTestTrade, BackTestReport, ExampleBackTesterModel,
VisualizationType, Trade, Order, Signal, StrategyConfig, StrategyType, I... |
from backtester.models import BackTestTrade
from papertrader.models import ExamplePaperTraderModel
from papertrader.models import PaperTradedStrategy
from papertrader.models import CurrentQuote
from papertrader.models import PaperTrade
from papertrader.models import PaperSignal
class CleanDatabase(object):
| 64 | 64 | 116 | 5 | 58 | Varun487/CapstoneProject_TradingSystem | restapi/services/Initialization/clean_database.py | Python | CleanDatabase | CleanDatabase | 26 | 36 | 26 | 26 | 04e98afa2ad41fc6851c17a05c29acfdf56c2596 | bigcode/the-stack | train |
9e9654daf88973a7e0ea67b0 | train | class | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
| class TreeNode:
| def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
| 介于 0 和 104 之间。
每个节点的值介于 -104 和 104 之间。
树中的所有值 互不相同 。
给定的树为二叉搜索树。
'''
from typing import List
# Definition for a binary tree node.
class TreeNode:
| 64 | 64 | 39 | 4 | 60 | wanglongjiang/leetcode | medium/538-convert-bst-to-greater-tree.py | Python | TreeNode | TreeNode | 23 | 27 | 23 | 23 | f4cae1903f6ca58676b99dd066098002b526a6e2 | bigcode/the-stack | train |
df8c116330e6abdc639ba304 | train | function | def fromList(li: List[int]):
if len(li) == 0:
return None
root = TreeNode(val=li[0])
queue = [root]
i = 1
while i < len(li):
node = queue[0]
del queue[0]
if li[i] is not None:
node.left = TreeNode(val=li[i])
queue.append(node.left)
i +=... | def fromList(li: List[int]):
| if len(li) == 0:
return None
root = TreeNode(val=li[0])
queue = [root]
i = 1
while i < len(li):
node = queue[0]
del queue[0]
if li[i] is not None:
node.left = TreeNode(val=li[i])
queue.append(node.left)
i += 1
if i < len(li):
... | else:
node.val += parentSum
if node.left:
return recu(node.left, node.val)
return node.val
if root:
recu(root, 0)
return root
# list数据按照bfs遍历得到
def fromList(li: List[int]):
| 64 | 64 | 135 | 8 | 55 | wanglongjiang/leetcode | medium/538-convert-bst-to-greater-tree.py | Python | fromList | fromList | 58 | 76 | 58 | 58 | f94e4266b4426f3283882bee998055256a65b5d1 | bigcode/the-stack | train |
45ab76ae01ac152d496a8601 | train | function | def toList(node: TreeNode):
li = []
if node is None:
return li
queue = [node]
li.append(node.val)
while len(queue) > 0:
node = queue[0]
del queue[0]
if node.left:
queue.append(node.left)
li.append(node.left.val)
else:
li.app... | def toList(node: TreeNode):
| li = []
if node is None:
return li
queue = [node]
li.append(node.val)
while len(queue) > 0:
node = queue[0]
del queue[0]
if node.left:
queue.append(node.left)
li.append(node.left.val)
else:
li.append(None)
if node.ri... | (val=li[i])
queue.append(node.left)
i += 1
if i < len(li):
if li[i]:
node.right = TreeNode(val=li[i])
queue.append(node.right)
i += 1
return root
def toList(node: TreeNode):
| 64 | 64 | 164 | 8 | 55 | wanglongjiang/leetcode | medium/538-convert-bst-to-greater-tree.py | Python | toList | toList | 79 | 107 | 79 | 79 | d3773a4c145b20a0a347d11602448a48bef6b059 | bigcode/the-stack | train |
da6544f84ad5714a24370189 | train | class | class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
def recu(node: TreeNode, parentSum):
if node.right:
node.val += recu(node.right, parentSum)
else:
node.val += parentSum
if node.left:
return recu(node.left, n... | class Solution:
| def convertBST(self, root: TreeNode) -> TreeNode:
def recu(node: TreeNode, parentSum):
if node.right:
node.val += recu(node.right, parentSum)
else:
node.val += parentSum
if node.left:
return recu(node.left, node.val)
... | 子树,其和为node.val+右子树累计+父节点累计
根据上面的信息可以写出递归函数
时间复杂度:O(n),所有节点都需要遍历一次
空间复杂度:O(logn),递归深度为logn
'''
class Solution:
| 63 | 64 | 93 | 3 | 60 | wanglongjiang/leetcode | medium/538-convert-bst-to-greater-tree.py | Python | Solution | Solution | 41 | 54 | 41 | 41 | 09a9de169598a49535bf94ee4f40ea55ed6b5b63 | bigcode/the-stack | train |
c4a18d25f461689c788966b4 | train | function | def pytest_addoption(parser):
# group = parser.getgroup("pytester", "pytester (self-tests) options")
parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available"))
parser.addoption('--runpytest', default="inprocess", dest="runp... | def pytest_addoption(parser):
# group = parser.getgroup("pytester", "pytester (self-tests) options")
| parser.addoption('--lsof',
action="store_true", dest="lsof", default=False,
help=("run FD checks if lsof is available"))
parser.addoption('--runpytest', default="inprocess", dest="runpytest",
choices=("inprocess", "subprocess", ),
help=("run pytest sub runs in tests ... | _
from _pytest._code import Source
import py
import pytest
from _pytest.main import Session, EXIT_OK
from _pytest.assertion.rewrite import AssertionRewritingHook
def pytest_addoption(parser):
# group = parser.getgroup("pytester", "pytester (self-tests) options")
| 64 | 64 | 120 | 26 | 37 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | pytest_addoption | pytest_addoption | 22 | 31 | 22 | 23 | dcae8cebc35d24ca162bf964f5b7d9148d4174c3 | bigcode/the-stack | train |
d52bd79b3805842f993af807 | train | class | class PytestArg:
def __init__(self, request):
self.request = request
def gethookrecorder(self, hook):
hookrecorder = HookRecorder(hook._pm)
self.request.addfinalizer(hookrecorder.finish_recording)
return hookrecorder
| class PytestArg:
| def __init__(self, request):
self.request = request
def gethookrecorder(self, hook):
hookrecorder = HookRecorder(hook._pm)
self.request.addfinalizer(hookrecorder.finish_recording)
return hookrecorder
| at least by pytest-xdist plugin
@pytest.fixture
def _pytest(request):
""" Return a helper which offers a gethookrecorder(hook)
method which returns a HookRecorder instance which helps
to make assertions about called hooks.
"""
return PytestArg(request)
class PytestArg:
| 64 | 64 | 62 | 5 | 59 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | PytestArg | PytestArg | 166 | 173 | 166 | 166 | 27c01c6501b2c1d7daaa5447d77ff8cd62d63b7c | bigcode/the-stack | train |
9d9509dfa35cc00ac3bdd2f4 | train | class | class Testdir:
"""Temporary test directory with tools to test/run pytest itself.
This is based on the ``tmpdir`` fixture but provides a number of
methods which aid with testing pytest itself. Unless
:py:meth:`chdir` is used all methods will use :py:attr:`tmpdir` as
current working directory.
... | class Testdir:
| """Temporary test directory with tools to test/run pytest itself.
This is based on the ``tmpdir`` fixture but provides a number of
methods which aid with testing pytest itself. Unless
:py:meth:`chdir` is used all methods will use :py:attr:`tmpdir` as
current working directory.
Attributes:
... | def __init__(self, ret, outlines, errlines, duration):
self.ret = ret
self.outlines = outlines
self.errlines = errlines
self.stdout = LineMatcher(outlines)
self.stderr = LineMatcher(errlines)
self.duration = duration
def parseoutcomes(self):
""" Return a ... | 256 | 256 | 5,261 | 4 | 252 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | Testdir | Testdir | 382 | 1,021 | 382 | 382 | 242660388de32f90a4f9f52c9984acbbae6ee439 | bigcode/the-stack | train |
6ff8278ed898527aaa7b6402 | train | function | @pytest.fixture(name='LineMatcher')
def LineMatcher_fixture(request):
return LineMatcher
| @pytest.fixture(name='LineMatcher')
def LineMatcher_fixture(request):
| return LineMatcher
| assert passed == len(realpassed)
assert skipped == len(realskipped)
assert failed == len(realfailed)
def clear(self):
self.calls[:] = []
@pytest.fixture
def linecomp(request):
return LineComp()
@pytest.fixture(name='LineMatcher')
def LineMatcher_fixture(request):
| 64 | 64 | 18 | 13 | 51 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | LineMatcher_fixture | LineMatcher_fixture | 325 | 327 | 325 | 326 | de0a3a81ee3a560ca8fd0d52b1d8b075565b20a8 | bigcode/the-stack | train |
424c0bb79afaf1943e526803 | train | class | class ParsedCall:
def __init__(self, name, kwargs):
self.__dict__.update(kwargs)
self._name = name
def __repr__(self):
d = self.__dict__.copy()
del d['_name']
return "<ParsedCall %r(**%r)>" %(self._name, d)
| class ParsedCall:
| def __init__(self, name, kwargs):
self.__dict__.update(kwargs)
self._name = name
def __repr__(self):
d = self.__dict__.copy()
del d['_name']
return "<ParsedCall %r(**%r)>" %(self._name, d)
| ook._pm)
self.request.addfinalizer(hookrecorder.finish_recording)
return hookrecorder
def get_public_names(l):
"""Only return names from iterator l without a leading underscore."""
return [x for x in l if x[0] != "_"]
class ParsedCall:
| 63 | 64 | 71 | 4 | 59 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | ParsedCall | ParsedCall | 181 | 189 | 181 | 181 | f3b8f1fc6b1ce0cdc8e62397db2d13057f432629 | bigcode/the-stack | train |
33a0a56f26e266d5f251afa4 | train | class | class HookRecorder:
"""Record all hooks called in a plugin manager.
This wraps all the hook calls in the plugin manager, recording
each call before propagating the normal calls.
"""
def __init__(self, pluginmanager):
self._pluginmanager = pluginmanager
self.calls = []
def... | class HookRecorder:
| """Record all hooks called in a plugin manager.
This wraps all the hook calls in the plugin manager, recording
each call before propagating the normal calls.
"""
def __init__(self, pluginmanager):
self._pluginmanager = pluginmanager
self.calls = []
def before(hook_name, h... | return executable
pytest.skip("no suitable %s found" % (name,))
return executable
# used at least by pytest-xdist plugin
@pytest.fixture
def _pytest(request):
""" Return a helper which offers a gethookrecorder(hook)
method which returns a HookRecorder instance which helps
to... | 256 | 256 | 984 | 4 | 252 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | HookRecorder | HookRecorder | 192 | 317 | 192 | 192 | e717600bbb99099c260e00aae12168ad30bfa9f3 | bigcode/the-stack | train |
4929f80331c86b2b21533632 | train | class | class RunResult:
"""The result of running a command.
Attributes:
:ret: The return value.
:outlines: List of lines captured from stdout.
:errlines: List of lines captures from stderr.
:stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
reconstruct stdout or the commonly u... | class RunResult:
| """The result of running a command.
Attributes:
:ret: The return value.
:outlines: List of lines captured from stdout.
:errlines: List of lines captures from stderr.
:stdout: :py:class:`LineMatcher` of stdout, use ``stdout.str()`` to
reconstruct stdout or the commonly used
``stdo... | passed == len(realpassed)
assert skipped == len(realskipped)
assert failed == len(realfailed)
def clear(self):
self.calls[:] = []
@pytest.fixture
def linecomp(request):
return LineComp()
@pytest.fixture(name='LineMatcher')
def LineMatcher_fixture(request):
return LineMatcher
... | 110 | 110 | 368 | 4 | 106 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | RunResult | RunResult | 336 | 378 | 336 | 336 | 1a6bf8cb7ebfa6d562c66da094d8307b65493e62 | bigcode/the-stack | train |
1b3d72a1a2965cc0b62401ee | train | function | def get_public_names(l):
"""Only return names from iterator l without a leading underscore."""
return [x for x in l if x[0] != "_"]
| def get_public_names(l):
| """Only return names from iterator l without a leading underscore."""
return [x for x in l if x[0] != "_"]
| :
def __init__(self, request):
self.request = request
def gethookrecorder(self, hook):
hookrecorder = HookRecorder(hook._pm)
self.request.addfinalizer(hookrecorder.finish_recording)
return hookrecorder
def get_public_names(l):
| 64 | 64 | 35 | 6 | 57 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | get_public_names | get_public_names | 176 | 178 | 176 | 176 | 43f36c2f21f47c49fb4093f34b211cb82dad747e | bigcode/the-stack | train |
01f447025f8071f04d345339 | train | class | class LineComp:
def __init__(self):
self.stringio = py.io.TextIO()
def assert_contains_lines(self, lines2):
""" assert that lines2 are contained (linearly) in lines1.
return a list of extralines found.
"""
__tracebackhide__ = True
val = self.stringio.getvalue... | class LineComp:
| def __init__(self):
self.stringio = py.io.TextIO()
def assert_contains_lines(self, lines2):
""" assert that lines2 are contained (linearly) in lines1.
return a list of extralines found.
"""
__tracebackhide__ = True
val = self.stringio.getvalue()
self.... | _timeout
return child
def getdecoded(out):
try:
return out.decode("utf-8")
except UnicodeDecodeError:
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
py.io.saferepr(out),)
class LineComp:
| 64 | 64 | 116 | 4 | 60 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | LineComp | LineComp | 1,031 | 1,044 | 1,031 | 1,031 | b06e919933324d07bae58c84808e05099f7466a4 | bigcode/the-stack | train |
bc579768fa30c17243996d87 | train | function | @pytest.fixture
def linecomp(request):
return LineComp()
| @pytest.fixture
def linecomp(request):
| return LineComp()
| ):
realpassed, realskipped, realfailed = self.listoutcomes()
assert passed == len(realpassed)
assert skipped == len(realskipped)
assert failed == len(realfailed)
def clear(self):
self.calls[:] = []
@pytest.fixture
def linecomp(request):
| 63 | 64 | 13 | 8 | 55 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | linecomp | linecomp | 320 | 322 | 320 | 321 | 25f6577118abae6695bbcc1c8b8bd7513e57e66e | bigcode/the-stack | train |
323e41dc07ed59245c07ad28 | train | function | def getdecoded(out):
try:
return out.decode("utf-8")
except UnicodeDecodeError:
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
py.io.saferepr(out),)
| def getdecoded(out):
| try:
return out.decode("utf-8")
except UnicodeDecodeError:
return "INTERNAL not-utf8-decodeable, truncated string:\n%s" % (
py.io.saferepr(out),)
| pexpect does not work reliably on freebsd")
logfile = self.tmpdir.join("spawn.out").open("wb")
child = pexpect.spawn(cmd, logfile=logfile)
self.request.addfinalizer(logfile.close)
child.timeout = expect_timeout
return child
def getdecoded(out):
| 64 | 64 | 54 | 5 | 58 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | getdecoded | getdecoded | 1,023 | 1,028 | 1,023 | 1,023 | b1edc254acc1fd5214397ca5a31f296b45e1de07 | bigcode/the-stack | train |
40a876b25850e8224dfc50b5 | train | function | @pytest.fixture
def testdir(request, tmpdir_factory):
return Testdir(request, tmpdir_factory)
| @pytest.fixture
def testdir(request, tmpdir_factory):
| return Testdir(request, tmpdir_factory)
| )
assert failed == len(realfailed)
def clear(self):
self.calls[:] = []
@pytest.fixture
def linecomp(request):
return LineComp()
@pytest.fixture(name='LineMatcher')
def LineMatcher_fixture(request):
return LineMatcher
@pytest.fixture
def testdir(request, tmpdir_factory):
| 64 | 64 | 22 | 12 | 51 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | testdir | testdir | 330 | 332 | 330 | 331 | b60b2ee577cabb43050cba640bfda29ce0d3557c | bigcode/the-stack | train |
20f26c028e10309daeed9c82 | train | function | @pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4",
'pypy', 'pypy3'])
def anypython(request):
name = request.param
executable = getexecutable(name)
if executable is None:
if sys.platform == "win32":
executable = winpymap.get(name, None)
... | @pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4",
'pypy', 'pypy3'])
def anypython(request):
| name = request.param
executable = getexecutable(name)
if executable is None:
if sys.platform == "win32":
executable = winpymap.get(name, None)
if executable:
executable = py.path.local(executable)
if executable.check():
retu... | pyenv's 127.
executable = None
cache[name] = executable
return executable
@pytest.fixture(params=['python2.6', 'python2.7', 'python3.3', "python3.4",
'pypy', 'pypy3'])
def anypython(request):
| 64 | 64 | 123 | 42 | 21 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | anypython | anypython | 142 | 155 | 142 | 144 | ec7705b294af8d7bf97e5fd5e7875db244445c37 | bigcode/the-stack | train |
a0fd49098e033035673e9d50 | train | class | class LineMatcher:
"""Flexible matching of text.
This is a convenience class to test large texts like the output of
commands.
The constructor takes a list of lines without their trailing
newlines, i.e. ``text.splitlines()``.
"""
def __init__(self, lines):
self.lines = lines
... | class LineMatcher:
| """Flexible matching of text.
This is a convenience class to test large texts like the output of
commands.
The constructor takes a list of lines without their trailing
newlines, i.e. ``text.splitlines()``.
"""
def __init__(self, lines):
self.lines = lines
self._log_outpu... | = pexpect.spawn(cmd, logfile=logfile)
self.request.addfinalizer(logfile.close)
child.timeout = expect_timeout
return child
def getdecoded(out):
try:
return out.decode("utf-8")
except UnicodeDecodeError:
return "INTERNAL not-utf8-decodeable, truncated str... | 206 | 206 | 688 | 4 | 202 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | LineMatcher | LineMatcher | 1,047 | 1,140 | 1,047 | 1,047 | 21a99f2fe115ce124b9200253f9eff20bdbeade3 | bigcode/the-stack | train |
96ad2918ec638d67f00392fa | train | class | class LsofFdLeakChecker(object):
def get_open_files(self):
out = self._exec_lsof()
open_files = self._parse_lsof_output(out)
return open_files
def _exec_lsof(self):
pid = os.getpid()
return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)
def _parse_lsof_output(self, ou... | class LsofFdLeakChecker(object):
| def get_open_files(self):
out = self._exec_lsof()
open_files = self._parse_lsof_output(out)
return open_files
def _exec_lsof(self):
pid = os.getpid()
return py.process.cmdexec("lsof -Ffn0 -p %d" % pid)
def _parse_lsof_output(self, out):
def isopen(line):
... | ),
help=("run pytest sub runs in tests using an 'inprocess' "
"or 'subprocess' (python -m main) method"))
def pytest_configure(config):
# This might be called multiple times. Only take the first.
global _pytest_fullpath
try:
_pytest_fullpath
except NameError:
... | 151 | 151 | 506 | 8 | 143 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | LsofFdLeakChecker | LsofFdLeakChecker | 49 | 107 | 49 | 49 | 0d2d14ab9ad9845cb3ad1b4953c2f13aed2ccb69 | bigcode/the-stack | train |
6452245887573b19895ad245 | train | function | def pytest_configure(config):
# This might be called multiple times. Only take the first.
global _pytest_fullpath
try:
_pytest_fullpath
except NameError:
_pytest_fullpath = os.path.abspath(pytest.__file__.rstrip("oc"))
_pytest_fullpath = _pytest_fullpath.replace("$py.class", ".py... | def pytest_configure(config):
# This might be called multiple times. Only take the first.
| global _pytest_fullpath
try:
_pytest_fullpath
except NameError:
_pytest_fullpath = os.path.abspath(pytest.__file__.rstrip("oc"))
_pytest_fullpath = _pytest_fullpath.replace("$py.class", ".py")
if config.getvalue("lsof"):
checker = LsofFdLeakChecker()
if checker.m... | ",
choices=("inprocess", "subprocess", ),
help=("run pytest sub runs in tests using an 'inprocess' "
"or 'subprocess' (python -m main) method"))
def pytest_configure(config):
# This might be called multiple times. Only take the first.
| 63 | 64 | 110 | 20 | 43 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | pytest_configure | pytest_configure | 34 | 46 | 34 | 35 | e7a5bbab41dceb6887000c5f6fff16e8c851f989 | bigcode/the-stack | train |
8e5f1b2d51c1a4418842b765 | train | function | @pytest.fixture
def _pytest(request):
""" Return a helper which offers a gethookrecorder(hook)
method which returns a HookRecorder instance which helps
to make assertions about called hooks.
"""
return PytestArg(request)
| @pytest.fixture
def _pytest(request):
| """ Return a helper which offers a gethookrecorder(hook)
method which returns a HookRecorder instance which helps
to make assertions about called hooks.
"""
return PytestArg(request)
| ap.get(name, None)
if executable:
executable = py.path.local(executable)
if executable.check():
return executable
pytest.skip("no suitable %s found" % (name,))
return executable
# used at least by pytest-xdist plugin
@pytest.fixture
def _pytes... | 64 | 64 | 51 | 8 | 55 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | _pytest | _pytest | 158 | 164 | 158 | 159 | 4d17eeba1ed952a67dff33c6a71d2f9e0a83b0ac | bigcode/the-stack | train |
f073b5d015b55af7044fd703 | train | function | def getexecutable(name, cache={}):
try:
return cache[name]
except KeyError:
executable = py.path.local.sysfind(name)
if executable:
import subprocess
popen = subprocess.Popen([str(executable), "--version"],
universal_newlines=True, stderr=subproces... | def getexecutable(name, cache={}):
| try:
return cache[name]
except KeyError:
executable = py.path.local.sysfind(name)
if executable:
import subprocess
popen = subprocess.Popen([str(executable), "--version"],
universal_newlines=True, stderr=subprocess.PIPE)
out, err = pope... | Python32\python.exe',
'python3.3': r'C:\Python33\python.exe',
'python3.4': r'C:\Python34\python.exe',
'python3.5': r'C:\Python35\python.exe',
}
def getexecutable(name, cache={}):
| 64 | 64 | 164 | 9 | 55 | neer201/catboost_SE | contrib/python/pytest/_pytest/pytester.py | Python | getexecutable | getexecutable | 121 | 140 | 121 | 121 | 5ec538c85ff47a1c4ecdf374c5e2fb55e922269b | bigcode/the-stack | train |
42cb64c7aaca4a98530c71ac | train | class | class Pemeriksaan:
def __init__(self, idpasien, idDokter, status):
self.__idPasien = idpasien
self.__idDokter = idDokter
self.__tanggalPemeriksaan = date.today()
self.__status = status
@property
def idPasien(self):
return self.__idPasien
@idPasien.setter
def... | class Pemeriksaan:
| def __init__(self, idpasien, idDokter, status):
self.__idPasien = idpasien
self.__idDokter = idDokter
self.__tanggalPemeriksaan = date.today()
self.__status = status
@property
def idPasien(self):
return self.__idPasien
@idPasien.setter
def idPasien(self, idP... | from datetime import date
class Pemeriksaan:
| 9 | 64 | 193 | 4 | 4 | MohFahmi27/OOP-Project-Python | Class/Pemeriksaan.py | Python | Pemeriksaan | Pemeriksaan | 4 | 33 | 4 | 4 | bce07905c1f6fc985b2515efc8b3d39c62c522c1 | bigcode/the-stack | train |
1237fa269e55a0aa5880b481 | train | class | class Reminders(Base):
__tablename__ = 'reminders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer,ForeignKey(Users.id))
content_id = Column(Integer, ForeignKey(Content.id))
creation_date = Column(DateTime(timezone=True))
reminder_time = Column(DateTime(timezone=True))
remi... | class Reminders(Base):
| __tablename__ = 'reminders'
id = Column(Integer, primary_key=True)
user_id = Column(Integer,ForeignKey(Users.id))
content_id = Column(Integer, ForeignKey(Content.id))
creation_date = Column(DateTime(timezone=True))
reminder_time = Column(DateTime(timezone=True))
reminder_type = Column(Strin... |
import os
from models.core.sqlalchemy_config import * #delete all the above and see if it works
from models.conversation import Conversation, Content
from models.user import Users
session = get_session()
Base = get_base()
class Reminders(Base):
| 53 | 64 | 90 | 5 | 48 | PervasiveWellbeingTech/Popbots-Engine | models/reminders.py | Python | Reminders | Reminders | 10 | 21 | 10 | 11 | e58f6bcd52289d24badec2827337f60acf7fa048 | bigcode/the-stack | train |
51f24b432c18adf8debd9acf | train | function | def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return... | def _swig_setattr_nondynamic_method(set):
| def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
| (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
| 64 | 64 | 79 | 12 | 51 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | _swig_setattr_nondynamic_method | _swig_setattr_nondynamic_method | 76 | 83 | 76 | 76 | 170b9273534f9743a98c1ee050d51ec916743fbd | bigcode/the-stack | train |
c00e8901ea5227825ae92ce4 | train | function | def get_first_fixup_ea(*args):
"""
get_first_fixup_ea() -> ea_t
Get the first address with fixup information
@return: the first address with fixup information, or BADADDR
"""
return _ida_fixup.get_first_fixup_ea(*args)
| def get_first_fixup_ea(*args):
| """
get_first_fixup_ea() -> ea_t
Get the first address with fixup information
@return: the first address with fixup information, or BADADDR
"""
return _ida_fixup.get_first_fixup_ea(*args)
| up.set_fixup(*args)
def del_fixup(*args):
"""
del_fixup(source)
Delete fixup information.
@param source (C++: ea_t)
"""
return _ida_fixup.del_fixup(*args)
def get_first_fixup_ea(*args):
| 64 | 64 | 67 | 10 | 54 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | get_first_fixup_ea | get_first_fixup_ea | 377 | 386 | 377 | 377 | 4eb3e62c092d80e0b52a2957238a6ffd3211406f | bigcode/the-stack | train |
4910c4a5d022fcc5bc5e3670 | train | class | class fixup_data_t(object):
"""
Proxy of C++ fixup_data_t class
"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
sel = _swig_property(_ida_fixup.fixup_data_t_sel_get, _ida_fixup.fixup_data_t_sel_set)
off = _swig... | class fixup_data_t(object):
| """
Proxy of C++ fixup_data_t class
"""
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
sel = _swig_property(_ida_fixup.fixup_data_t_sel_get, _ida_fixup.fixup_data_t_sel_set)
off = _swig_property(_ida_fixup.fixup_d... | Is fixup processed by processor module?
@param type (C++: fixup_type_t)
"""
return _ida_fixup.is_fixup_custom(*args)
FIXUPF_REL = _ida_fixup.FIXUPF_REL
"""
fixup is relative to the linear address `base' . Otherwise fixup is
relative to the start of the segment with `sel' selector.
"""
FIXUPF_EXTDEF = _ida_... | 256 | 256 | 1,188 | 7 | 249 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | fixup_data_t | fixup_data_t | 159 | 321 | 159 | 159 | a4759b472d08b87db20a5f0493322e417e9e2868 | bigcode/the-stack | train |
be12716c6512c2e755f0f505 | train | function | def gen_fix_fixups(*args):
"""
gen_fix_fixups(_from, to, size)
Relocate the bytes with fixup information once more (generic
function). This function may be called from 'loader_t::move_segm()' if
it suits the goal. If 'loader_t::move_segm' is not defined then this
function will be called automatically when... | def gen_fix_fixups(*args):
| """
gen_fix_fixups(_from, to, size)
Relocate the bytes with fixup information once more (generic
function). This function may be called from 'loader_t::move_segm()' if
it suits the goal. If 'loader_t::move_segm' is not defined then this
function will be called automatically when moving segments or rebasin... | , size) -> bool
Does the specified address range contain any fixup information?
@param ea (C++: ea_t)
@param size (C++: asize_t)
"""
return _ida_fixup.contains_fixups(*args)
def gen_fix_fixups(*args):
| 64 | 64 | 180 | 8 | 56 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | gen_fix_fixups | gen_fix_fixups | 537 | 554 | 537 | 537 | 5e3d385842707834d34b4c9177fee03181fb594f | bigcode/the-stack | train |
cb065de448a33972931f5f28 | train | function | def get_fixup_desc(*args):
"""
get_fixup_desc(source, fd) -> char const *
Get FIXUP description comment.
@param source (C++: ea_t)
@param fd (C++: const fixup_data_t &)
"""
return _ida_fixup.get_fixup_desc(*args)
| def get_fixup_desc(*args):
| """
get_fixup_desc(source, fd) -> char const *
Get FIXUP description comment.
@param source (C++: ea_t)
@param fd (C++: const fixup_data_t &)
"""
return _ida_fixup.get_fixup_desc(*args)
| changed, the size of the changed
data depends on the fixup type. (C++: ea_t)
@param fd (C++: const fixup_data_t &)
"""
return _ida_fixup.patch_fixup_value(*args)
def get_fixup_desc(*args):
| 64 | 64 | 74 | 8 | 56 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | get_fixup_desc | get_fixup_desc | 461 | 472 | 461 | 461 | 0c0e3155c98ed9f4ef729f8c4e22b1a6b2499ee6 | bigcode/the-stack | train |
84e9690c674b1a816440f9e0 | train | function | def get_next_fixup_ea(*args):
"""
get_next_fixup_ea(ea) -> ea_t
Find next address with fixup information
@param ea: current address (C++: ea_t)
@return: the next address with fixup information, or BADADDR
"""
return _ida_fixup.get_next_fixup_ea(*args)
| def get_next_fixup_ea(*args):
| """
get_next_fixup_ea(ea) -> ea_t
Find next address with fixup information
@param ea: current address (C++: ea_t)
@return: the next address with fixup information, or BADADDR
"""
return _ida_fixup.get_next_fixup_ea(*args)
| get_first_fixup_ea() -> ea_t
Get the first address with fixup information
@return: the first address with fixup information, or BADADDR
"""
return _ida_fixup.get_first_fixup_ea(*args)
def get_next_fixup_ea(*args):
| 64 | 64 | 82 | 10 | 54 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | get_next_fixup_ea | get_next_fixup_ea | 388 | 398 | 388 | 388 | 3133cc9493583e5e4f3741479ac973e8c3ca0f79 | bigcode/the-stack | train |
87f16c222d74e30bd47e8fce | train | function | def get_fixup_value(*args):
"""
get_fixup_value(ea, type) -> uval_t
Get the operand value. This function get fixup bytes from data or an
instruction at `ea' and convert them to the operand value (maybe
partially). It is opposite in meaning to the 'patch_fixup_value()' .
For example, FIXUP_HI8 read a byte ... | def get_fixup_value(*args):
| """
get_fixup_value(ea, type) -> uval_t
Get the operand value. This function get fixup bytes from data or an
instruction at `ea' and convert them to the operand value (maybe
partially). It is opposite in meaning to the 'patch_fixup_value()' .
For example, FIXUP_HI8 read a byte at 'patch_fixup_value()' `e... | get_fixup_handler(*args):
"""
get_fixup_handler(type) -> fixup_handler_t const *
Get handler of standard or custom fixup.
@param type (C++: fixup_type_t)
"""
return _ida_fixup.get_fixup_handler(*args)
def get_fixup_value(*args):
| 70 | 70 | 234 | 8 | 62 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | get_fixup_value | get_fixup_value | 424 | 442 | 424 | 424 | b8e512b4a9e877a5cb07a057a589b91cbc067b4b | bigcode/the-stack | train |
8814dab78c6a4d26ebb83db2 | train | function | def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
| def _swig_setattr(self,class_type,name,value):
| return _swig_setattr_nondynamic(self,class_type,name,value,0)
| ig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
| 64 | 64 | 30 | 12 | 52 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | _swig_setattr | _swig_setattr | 54 | 55 | 54 | 54 | 114f2441fba95e316198424891d5b750117feafe | bigcode/the-stack | train |
2220505705c7df00e693f0f8 | train | function | def patch_fixup_value(*args):
"""
patch_fixup_value(ea, fd) -> bool
Patch the fixup bytes. This function updates data or an instruction at
`ea' to the fixup bytes. For example, FIXUP_HI8 updates a byte at `ea'
to the high byte of `fd->off' , or AArch64's custom fixup BRANCH26
updates low 26 bits of the in... | def patch_fixup_value(*args):
| """
patch_fixup_value(ea, fd) -> bool
Patch the fixup bytes. This function updates data or an instruction at
`ea' to the fixup bytes. For example, FIXUP_HI8 updates a byte at `ea'
to the high byte of `fd->off' , or AArch64's custom fixup BRANCH26
updates low 26 bits of the insn at `ea' to the value of `fd... | fixup bytes from, the size of the fixup
bytes depends on the fixup type. (C++: ea_t)
@param type (C++: fixup_type_t)
"""
return _ida_fixup.get_fixup_value(*args)
def patch_fixup_value(*args):
| 64 | 64 | 192 | 8 | 56 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | patch_fixup_value | patch_fixup_value | 444 | 459 | 444 | 444 | 7a94ea7488386c17f549796654bc9ae0b3b31c3e | bigcode/the-stack | train |
582063ac8eccb732b527b750 | train | function | def get_prev_fixup_ea(*args):
"""
get_prev_fixup_ea(ea) -> ea_t
Find previous address with fixup information
@param ea: current address (C++: ea_t)
@return: the previous address with fixup information, or BADADDR
"""
return _ida_fixup.get_prev_fixup_ea(*args)
| def get_prev_fixup_ea(*args):
| """
get_prev_fixup_ea(ea) -> ea_t
Find previous address with fixup information
@param ea: current address (C++: ea_t)
@return: the previous address with fixup information, or BADADDR
"""
return _ida_fixup.get_prev_fixup_ea(*args)
| next address with fixup information
@param ea: current address (C++: ea_t)
@return: the next address with fixup information, or BADADDR
"""
return _ida_fixup.get_next_fixup_ea(*args)
def get_prev_fixup_ea(*args):
| 64 | 64 | 82 | 10 | 54 | dodieboy/Np_class | REM/Tool/IDA 7.3/python/ida_fixup.py | Python | get_prev_fixup_ea | get_prev_fixup_ea | 400 | 410 | 400 | 400 | 9145a36c7af42f96a29330013ed496d4463239cb | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.