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
9536de7464c1d12a13439798
train
function
def find_numbers(tokens): """ Find numbers and numeric words in token list :param list tokens: List of tokens :return: (tokens, numbers) :rtype: tuple """ num_words = ["zero","one","two","three","four","five","six","seven", "eight","nine","ten","eleven","twelve","thirteen","fourtee...
def find_numbers(tokens):
""" Find numbers and numeric words in token list :param list tokens: List of tokens :return: (tokens, numbers) :rtype: tuple """ num_words = ["zero","one","two","three","four","five","six","seven", "eight","nine","ten","eleven","twelve","thirteen","fourteen", "fifteen","six...
support in sentence replacements and more cases if query_lower == "today": return datetime.datetime.today().strftime("%m/%d/%Y") if query_lower == "tomorrow": return (datetime.datetime.today() + datetime.timedelta(days = 1)).strftime("%m/%d/%Y") return query def find_numbers(tokens):
71
71
239
5
65
jvm123/botstory
botstory/nlp.py
Python
find_numbers
find_numbers
84
111
84
84
dcd590e4eb93cbbe425a8e611e3d3ee17ba29ec9
bigcode/the-stack
train
7f611aaea0808ab0eff479fa
train
function
def find_nouns(tagged_words, skip_words_in_nlp = 0): """ Compile a list of nouns in tagged word list Note: treebankTagger works better than standard nltk.pos_words(). Tags can be compiled with treebank_tagger = nltk.data.load( 'taggers/maxent_treebank_pos_tagger/english.pickle') ...
def find_nouns(tagged_words, skip_words_in_nlp = 0):
""" Compile a list of nouns in tagged word list Note: treebankTagger works better than standard nltk.pos_words(). Tags can be compiled with treebank_tagger = nltk.data.load( 'taggers/maxent_treebank_pos_tagger/english.pickle') tagged_words = treebank_tagger.tag(tokens) ...
(tokens): #enmerate(tokens_without_date): # Replace numeric words in sentence with the actual numeric value if token.lower() in num_words: number = num_words.index(token.lower()) tokens[i] = str(number) for token in tokens: #tokens_without_date: if token.isnumeric():...
95
95
317
17
77
jvm123/botstory
botstory/nlp.py
Python
find_nouns
find_nouns
113
153
113
113
552a2e7c2a25da2eb6a932b8654ca4a0f6d560d5
bigcode/the-stack
train
97c578eecd4217f9ada105ca
train
class
class WarpedVRT(WarpedVRTReaderBase, WindowMethodsMixin, TransformMethodsMixin): """A virtual warped dataset. Abstracts the details of raster warping and allows access to data that is reprojected when read. This class is backed by an in-memory GDAL VRTWarpedDataset VRT file. Attri...
class WarpedVRT(WarpedVRTReaderBase, WindowMethodsMixin, TransformMethodsMixin):
"""A virtual warped dataset. Abstracts the details of raster warping and allows access to data that is reprojected when read. This class is backed by an in-memory GDAL VRTWarpedDataset VRT file. Attributes ---------- src_dataset : dataset The dataset object to be virtually warped....
"""rasterio.vrt: a module concerned with GDAL VRTs""" import xml.etree.ElementTree as ET import rasterio from rasterio._warp import WarpedVRTReaderBase from rasterio.dtypes import _gdal_typename from rasterio.enums import MaskFlags from rasterio.env import env_ctx_if_needed from rasterio.path import parse_path, vsi_p...
124
141
470
22
101
mraspaud/rasterio
rasterio/vrt.py
Python
WarpedVRT
WarpedVRT
15
73
15
16
238740c3a07b2d21b79f3314de9196b6bd095f3f
bigcode/the-stack
train
0fe27e9c0b90b2777cdcdfe3
train
function
def _boundless_vrt_doc( src_dataset, nodata=None, background=None, hidenodata=False, width=None, height=None, transform=None, masked=False): """Make a VRT XML document. Parameters ---------- src_dataset : Dataset The dataset to wrap. background : int or float, optional ...
def _boundless_vrt_doc( src_dataset, nodata=None, background=None, hidenodata=False, width=None, height=None, transform=None, masked=False):
"""Make a VRT XML document. Parameters ---------- src_dataset : Dataset The dataset to wrap. background : int or float, optional The background fill value for the boundless VRT. masked : book If True, the src_dataset is replaced by its valid data mask. Returns -...
of src_nodata, or 0 (gdal default). warp_extras : dict GDAL extra warp options. See http://www.gdal.org/structGDALWarpOptions.html. Examples -------- >>> with rasterio.open('tests/data/RGB.byte.tif') as src: ... with WarpedVRT(src, crs='EPSG:3857') as vrt: ... data...
256
256
1,747
37
219
mraspaud/rasterio
rasterio/vrt.py
Python
_boundless_vrt_doc
_boundless_vrt_doc
76
218
76
78
5b439bc7eb5dc1bc906064cd345526b78646baf8
bigcode/the-stack
train
08c1c996a579f237b280251a
train
function
def not16_logic(args): a = args[0] out = [(1 << 16) - a] return out
def not16_logic(args):
a = args[0] out = [(1 << 16) - a] return out
from src.TestCaseGenerator import * input_variables = [Var("in", 16, "B")] output_variables = [Var("out", 16, "B")] # args = [a] # It is guaranteed that the input is 16 bits at most def not16_logic(args):
62
64
29
6
55
AdilRas/Nand2TetrisCaseGenerator
Chips/Not16.py
Python
not16_logic
not16_logic
9
12
9
9
01d30c2eea9982164f7d3a6e7787e745f88636de
bigcode/the-stack
train
126ab960e0a4bc71f9a1d400
train
class
class ExampleIDatasetFormPlugin(plugins.SingletonPlugin, tk.DefaultDatasetForm): '''An example IDatasetForm CKAN plugin. Uses a tag vocabulary to add a custom metadata field to datasets. ''' plugins.implements(plugins.IConfigurer, inherit=False) plugins.implements(plugins.IDatasetForm, inh...
class ExampleIDatasetFormPlugin(plugins.SingletonPlugin, tk.DefaultDatasetForm):
'''An example IDatasetForm CKAN plugin. Uses a tag vocabulary to add a custom metadata field to datasets. ''' plugins.implements(plugins.IConfigurer, inherit=False) plugins.implements(plugins.IDatasetForm, inherit=False) plugins.implements(plugins.ITemplateHelpers, inherit=False) # These ...
')({'ignore_auth': True}, {}) context = {'user': user['name']} try: data = {'id': 'country_codes'} tk.get_action('vocabulary_show')(context, data) logging.info("Example genre vocabulary already exists, skipping.") except tk.ObjectNotFound: logging.info("Creating vocab 'countr...
256
256
1,057
17
238
eccenca/ckan
ckanext/example_idatasetform/plugin.py
Python
ExampleIDatasetFormPlugin
ExampleIDatasetFormPlugin
43
167
43
44
84dbbdc017291ae1f94cbbe764ac45b6e54e8f42
bigcode/the-stack
train
cb21df012913cc24ed76e93b
train
function
def country_codes(): '''Return the list of country codes from the country codes vocabulary.''' create_country_codes() try: country_codes = tk.get_action('tag_list')( data_dict={'vocabulary_id': 'country_codes'}) return country_codes except tk.ObjectNotFound: retur...
def country_codes():
'''Return the list of country codes from the country codes vocabulary.''' create_country_codes() try: country_codes = tk.get_action('tag_list')( data_dict={'vocabulary_id': 'country_codes'}) return country_codes except tk.ObjectNotFound: return None
'de', u'fr', u'es'): logging.info( "Adding tag {0} to vocab 'country_codes'".format(tag)) data = {'name': tag, 'vocabulary_id': vocab['id']} tk.get_action('tag_create')(context, data) def country_codes():
64
64
67
4
60
eccenca/ckan
ckanext/example_idatasetform/plugin.py
Python
country_codes
country_codes
32
40
32
32
dc3f902e3204f21078fb3d95d46fe58fd7aa4acd
bigcode/the-stack
train
3b16ddb1b989f1ab4d9311ed
train
function
def create_country_codes(): '''Create country_codes vocab and tags, if they don't exist already. Note that you could also create the vocab and tags using CKAN's API, and once they are created you can edit them (e.g. to add and remove possible dataset country code values) using the API. ''' use...
def create_country_codes():
'''Create country_codes vocab and tags, if they don't exist already. Note that you could also create the vocab and tags using CKAN's API, and once they are created you can edit them (e.g. to add and remove possible dataset country code values) using the API. ''' user = tk.get_action('get_site_...
import logging import ckan.plugins as plugins import ckan.plugins.toolkit as tk def create_country_codes():
24
75
251
5
18
eccenca/ckan
ckanext/example_idatasetform/plugin.py
Python
create_country_codes
create_country_codes
7
29
7
7
80d7b02824ab0858b71dc11f801c092d8422b6c6
bigcode/the-stack
train
6df2b4f3a6f9eec203365f33
train
class
class PanasonicDehumidifierOnTimer(PanasonicBaseEntity, NumberEntity): @property def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = int(status.get("0x00", -1)) == 0 return _is_on_status @property def label(self) -> str: retu...
class PanasonicDehumidifierOnTimer(PanasonicBaseEntity, NumberEntity): @property
def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = int(status.get("0x00", -1)) == 0 return _is_on_status @property def label(self) -> str: return f"{self.nickname} {LABEL_DEHUMIDIFIER_ON_TIMER}" @property def icon(self)...
"] if command["CommandType"] == "0x0b" ] ) > 0 ) if is_on_timer_supported: numbers.append( PanasonicACOnTimer( coordinator,...
91
91
306
20
70
sugoi-wada/panasonic_smart_app
custom_components/panasonic_smart_app/number.py
Python
PanasonicDehumidifierOnTimer
PanasonicDehumidifierOnTimer
118
155
118
119
4167b6800bc349c1b0c422569db36149c8b77487
bigcode/the-stack
train
88b911fa7cd020c783c79c15
train
class
class PanasonicACOffTimer(PanasonicBaseEntity, NumberEntity): @property def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = bool(int(status.get("0x00", 0))) return _is_on_status @property def label(self) -> str: return f"{sel...
class PanasonicACOffTimer(PanasonicBaseEntity, NumberEntity): @property
def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = bool(int(status.get("0x00", 0))) return _is_on_status @property def label(self) -> str: return f"{self.nickname} {LABEL_CLIMATE_OFF_TIMER}" @property def icon(self) -> ...
: return CLIMATE_ON_TIMER_MAX @property def unit_of_measurement(self) -> str: return UNIT_MINUTE async def async_set_value(self, value: float) -> None: await self.client.set_command(self.auth, 139, int(value)) await self.coordinator.async_request_refresh() class PanasonicAC...
87
87
293
18
69
sugoi-wada/panasonic_smart_app
custom_components/panasonic_smart_app/number.py
Python
PanasonicACOffTimer
PanasonicACOffTimer
241
278
241
242
436bd9fbb7cff5529471daafbd9da0f159fc42d0
bigcode/the-stack
train
5bab7b5b995f77eb9f08db93
train
function
async def async_setup_entry(hass, entry, async_add_entities) -> bool: client = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR] devices = coordinator.data commands = client.get_commands() numbers = [] for index, device in enumerate...
async def async_setup_entry(hass, entry, async_add_entities) -> bool:
client = hass.data[DOMAIN][entry.entry_id][DATA_CLIENT] coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR] devices = coordinator.data commands = client.get_commands() numbers = [] for index, device in enumerate(devices): current_device_commands = [ command ...
LABEL_CLIMATE_OFF_TIMER, UNIT_HOUR, UNIT_MINUTE, ICON_ON_TIMER, ICON_OFF_TIMER, CLIMATE_ON_TIMER_MIN, CLIMATE_ON_TIMER_MAX, CLIMATE_OFF_TIMER_MIN, CLIMATE_OFF_TIMER_MAX, DEHUMIDIFIER_ON_TIMER_MIN, DEHUMIDIFIER_ON_TIMER_MAX, DEHUMIDIFIER_OFF_TIMER_MIN, DEHUMIDIFIER_OFF_TI...
121
121
406
17
104
sugoi-wada/panasonic_smart_app
custom_components/panasonic_smart_app/number.py
Python
async_setup_entry
async_setup_entry
33
115
33
33
0f27469795e34ce618825a3a83eeb2ce7aaa5838
bigcode/the-stack
train
9d4bc9686ec0f1fc41d39271
train
class
class PanasonicDehumidifierOffTimer(PanasonicBaseEntity, NumberEntity): @property def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = bool(int(status.get("0x00", 0))) return _is_on_status @property def label(self) -> str: ret...
class PanasonicDehumidifierOffTimer(PanasonicBaseEntity, NumberEntity): @property
def available(self) -> bool: status = self.coordinator.data[self.index]["status"] _is_on_status = bool(int(status.get("0x00", 0))) return _is_on_status @property def label(self) -> str: return f"{self.nickname} {LABEL_DEHUMIDIFIER_OFF_TIMER}" @property def icon(self...
return DEHUMIDIFIER_ON_TIMER_MAX @property def unit_of_measurement(self) -> str: return UNIT_HOUR async def async_set_value(self, value: float) -> None: await self.client.set_command(self.auth, 213, int(value)) await self.coordinator.async_request_refresh() class PanasonicDehumidi...
90
90
303
20
70
sugoi-wada/panasonic_smart_app
custom_components/panasonic_smart_app/number.py
Python
PanasonicDehumidifierOffTimer
PanasonicDehumidifierOffTimer
158
195
158
159
0933cfb48fcf285bd26a38f0da5c60c8d786ecde
bigcode/the-stack
train
6f38526c7f793b03de0c6bd3
train
class
class PanasonicACOnTimer(PanasonicBaseEntity, NumberEntity): @property def available(self) -> bool: status = self.coordinator.data[self.index]["status"] if status.get("0x00") == None: return False _is_on_status = int(status.get("0x00")) == 0 return _is_on_status ...
class PanasonicACOnTimer(PanasonicBaseEntity, NumberEntity): @property
def available(self) -> bool: status = self.coordinator.data[self.index]["status"] if status.get("0x00") == None: return False _is_on_status = int(status.get("0x00")) == 0 return _is_on_status @property def label(self) -> str: return f"{self.nickname} {LA...
-> int: return DEHUMIDIFIER_OFF_TIMER_MAX @property def unit_of_measurement(self) -> str: return UNIT_HOUR async def async_set_value(self, value: float) -> None: await self.client.set_command(self.auth, 130, int(value)) await self.coordinator.async_request_refresh() class ...
92
92
309
18
74
sugoi-wada/panasonic_smart_app
custom_components/panasonic_smart_app/number.py
Python
PanasonicACOnTimer
PanasonicACOnTimer
198
238
198
199
344b8aacd7db1a33eab073079fb2ed05376b2a20
bigcode/the-stack
train
dd4c9657f4ac330b5fefbcd7
train
function
def geçenler(istasyon): import sqlite3 dere=sqlite3.connect("/home/beyhan/Belgeler/Python/KDU/rıhtım.db") im=dere.cursor() #im.execute("create table if not exists hatlar('hat','durak1','durak2','durak3','durak4','durak5')") im.execute("select * from hatlar") tablo=im.fetchall() #dere.close()...
def geçenler(istasyon):
import sqlite3 dere=sqlite3.connect("/home/beyhan/Belgeler/Python/KDU/rıhtım.db") im=dere.cursor() #im.execute("create table if not exists hatlar('hat','durak1','durak2','durak3','durak4','durak5')") im.execute("select * from hatlar") tablo=im.fetchall() #dere.close() global istasyondan_...
ondan_geçen[sayaç]) sayaç -=1 print("Ayrım bölgesi ####################") del istasyondan_geçen #denemeler.geçenler("İzmit") #print(istasyondan_geçen) def geçenler(istasyon):
64
64
173
7
57
StartaBafras/KS-
kvi.py
Python
geçenler
geçenler
47
62
47
47
c2adc3da2b6d1b2a8d37de5721c3e21c32cd4e4d
bigcode/the-stack
train
f5e19d7bae77f42f0e52892e
train
class
class StringPreHandler: @classmethod def del_keyword(cls, target, rules): """ 该方法删除一字符串中所有匹配某一规则字串 可用于清理一个字符串中的空白符和语气助词 :param target: 待处理字符串 :param rules: 删除规则 :return: 清理工作完成后的字符串 """ pattern = re.compile(rules) res = pattern.sub('', targ...
class StringPreHandler: @classmethod
def del_keyword(cls, target, rules): """ 该方法删除一字符串中所有匹配某一规则字串 可用于清理一个字符串中的空白符和语气助词 :param target: 待处理字符串 :param rules: 删除规则 :return: 清理工作完成后的字符串 """ pattern = re.compile(rules) res = pattern.sub('', target) return res @classmethod ...
""" TencentBlueKing is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available. Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the...
193
256
1,732
9
183
xiashuqin89/bk-chatbot
src/backend/component/nlp/time/StringPreHandler.py
Python
StringPreHandler
StringPreHandler
20
191
20
21
09acd1ed8c26951c80daf81bfde7ce3560b6fc66
bigcode/the-stack
train
b256f88e6ebd26067fcdf905
train
class
class ApiV1Client(BaseClient): def __init__(self, api_key): self.api_key = api_key def login(self): pass
class ApiV1Client(BaseClient):
def __init__(self, api_key): self.api_key = api_key def login(self): pass
# coding: utf-8 from .shared import BaseClient __author__ = 'tsantana' class ApiV1Client(BaseClient):
31
64
34
8
23
adm-github/tvdb_client
tvdb_client/clients/ApiV1Client.py
Python
ApiV1Client
ApiV1Client
7
13
7
8
f4955b1509a6b760dcbfdcea871ebf7de8cdf056
bigcode/the-stack
train
8a0dad6e8020c52e6549df1b
train
function
def parse_option(): parser = argparse.ArgumentParser('Swin Transformer weight conversion from PyTorch to TensorFlow', add_help=False) parser.add_argument( '--cfg', type=str, metavar="FILE", help='path to config file', default="configs/swin_tiny_patch4_window7_224.yaml" ...
def parse_option():
parser = argparse.ArgumentParser('Swin Transformer weight conversion from PyTorch to TensorFlow', add_help=False) parser.add_argument( '--cfg', type=str, metavar="FILE", help='path to config file', default="configs/swin_tiny_patch4_window7_224.yaml" ) parser.add_...
import argparse import tensorflow as tf from config import get_config from models.build import build_model def parse_option():
25
73
246
4
20
VcampSoldiers/Swin-Transformer-Tensorflow
main.py
Python
parse_option
parse_option
8
43
8
8
cf630e02f800437af6e44a0f6a0727ebe14fe7d5
bigcode/the-stack
train
0bf9c4e76cbfa872f1b9b5fd
train
function
def main(args, config): swin_transformer = build_model(config, load_pretrained=bool(args.resume), weights_type=args.weights_type) print( swin_transformer( tf.zeros([ 1, config.MODEL.SWIN.IN_CHANS, config.DATA.IMG_SIZE, config.DA...
def main(args, config):
swin_transformer = build_model(config, load_pretrained=bool(args.resume), weights_type=args.weights_type) print( swin_transformer( tf.zeros([ 1, config.MODEL.SWIN.IN_CHANS, config.DATA.IMG_SIZE, config.DATA.IMG_SIZE ...
k", "imagenet_22k", "imagenet_22kto1k"}, default="imagenet_1k", ) args = parser.parse_args() config = get_config(args, include_top=bool(args.include_top)) return args, config def main(args, config):
64
64
75
6
57
VcampSoldiers/Swin-Transformer-Tensorflow
main.py
Python
main
main
45
56
45
45
78c0465fc5a71499510e8fd9c537b61a59674402
bigcode/the-stack
train
e6622be76dd30747407611d8
train
class
class Records: websocket_connections = [] loop = None captcha_timeout = 60*60 #seconds captcha_length = 5 image_captcha = ImageCaptcha(fonts=["./FreeMono.ttf"]) def __init__(self, server_loop): self.loop = server_loop pass def check_http_request_auth(self, user_name, ma...
class Records:
websocket_connections = [] loop = None captcha_timeout = 60*60 #seconds captcha_length = 5 image_captcha = ImageCaptcha(fonts=["./FreeMono.ttf"]) def __init__(self, server_loop): self.loop = server_loop pass def check_http_request_auth(self, user_name, maybe_hash): ...
import os import re import google.protobuf.json_format as json_format from os import listdir from os.path import isfile, join from messages_pb2 import Message, Algorithm import asyncio import math, datetime, time from captcha.image import ImageCaptcha import json import random import smtplib from email.mime.text impor...
94
256
2,784
3
90
CrazedCoding/MetaHumanity.xyz
records.py
Python
Records
Records
18
321
18
18
de775003112b5c94ee6531412e5e51bb74efd01f
bigcode/the-stack
train
8b01dd813431d4a01ca7d8e2
train
function
@com.on_message() def handle_message(msg): print(f'handle_message: {msg}') socketio.emit('serial_message', data={'message': str(msg)})
@com.on_message() def handle_message(msg):
print(f'handle_message: {msg}') socketio.emit('serial_message', data={'message': str(msg)})
from flask import Blueprint, current_app from flask_socketio import SocketIO from flask_serial import COM arduino_bp = Blueprint('arduino', __name__) com = COM(current_app) socketio = SocketIO() @com.on_message() def handle_message(msg):
56
64
35
10
46
JackLilhammers/flask-serial
example/arduino/routes/arduino.py
Python
handle_message
handle_message
12
15
12
13
593190d9ebfdf8bba87a0278ed0afd1d4836a1ee
bigcode/the-stack
train
58008956ecbc795488b368cf
train
function
@pytest.fixture(scope='function') def ray_session_fixture(): """Initializes Ray and shuts down Ray. Yields: None: Yield is for purposes of pytest module style. All statements before the yield are apart of module setup, and all statements after the yield are apart of modul...
@pytest.fixture(scope='function') def ray_session_fixture():
"""Initializes Ray and shuts down Ray. Yields: None: Yield is for purposes of pytest module style. All statements before the yield are apart of module setup, and all statements after the yield are apart of module teardown. """ if not ray.is_initialized(): ...
apart of module teardown. """ if not ray.is_initialized(): ray.init(local_mode=True, ignore_reinit_error=True, log_to_driver=False, include_webui=False) yield if ray.is_initialized(): ray.shutdown() @pytest.fixture(scope='fun...
64
64
122
11
53
fangqyi/garage
tests/fixtures/sampler/ray_fixtures.py
Python
ray_session_fixture
ray_session_fixture
26
44
26
27
2f658994267224831305dc5e00b72c0e9ac045cd
bigcode/the-stack
train
cd815914ed0b79f6668cf810
train
function
@pytest.fixture(scope='function') def ray_local_session_fixture(): """Initializes Ray and shuts down Ray in local mode. Yields: None: Yield is for purposes of pytest module style. All statements before the yield are apart of module setup, and all statements after the yiel...
@pytest.fixture(scope='function') def ray_local_session_fixture():
"""Initializes Ray and shuts down Ray in local mode. Yields: None: Yield is for purposes of pytest module style. All statements before the yield are apart of module setup, and all statements after the yield are apart of module teardown. """ if not ray.is_initial...
"""Pytest fixtures for intializing ray during ray related tests.""" import pytest import ray @pytest.fixture(scope='function') def ray_local_session_fixture():
33
64
115
12
20
fangqyi/garage
tests/fixtures/sampler/ray_fixtures.py
Python
ray_local_session_fixture
ray_local_session_fixture
6
23
6
7
ab0df37428c0fdd28ce508f0303f18425673bf51
bigcode/the-stack
train
319e6e0a49bdb7391914bb23
train
function
def main(): import sys import logging from daemon import DockerNdpDaemon logger = logging.getLogger(__name__) try: import config logging.basicConfig(format=config.logger.format) logging.root.setLevel(config.logger.level) daemon = DockerNdpDaemon( confi...
def main():
import sys import logging from daemon import DockerNdpDaemon logger = logging.getLogger(__name__) try: import config logging.basicConfig(format=config.logger.format) logging.root.setLevel(config.logger.level) daemon = DockerNdpDaemon( config.docker.soc...
def main():
3
64
97
3
0
pommes/docker-ndp-proxy
app/main.py
Python
main
main
1
20
1
1
21243c4df70f4cb442b614810ca44778bd14d699
bigcode/the-stack
train
5ddc6eb9185f5f6eb911c6f7
train
function
def read_losses(features, seed_num, search=False, pathstr=''): if search: path = pathstr + 'search/' + str(features) + '/' else: path = pathstr + 'fixed/' + str(features) + '/' fname = path + 'run_' + str(seed_num) dbfile = open(fname, 'rb') db = pickle.load(dbfile) dbfile.clos...
def read_losses(features, seed_num, search=False, pathstr=''):
if search: path = pathstr + 'search/' + str(features) + '/' else: path = pathstr + 'fixed/' + str(features) + '/' fname = path + 'run_' + str(seed_num) dbfile = open(fname, 'rb') db = pickle.load(dbfile) dbfile.close() return db
import numpy as np import pickle import math import statistics import matplotlib.pyplot as plt import argparse def read_losses(features, seed_num, search=False, pathstr=''):
38
64
93
15
22
armahmood/repn-learning
rrstep.py
Python
read_losses
read_losses
8
17
8
8
e48094633782bba3a8ab95ef87d65041aa3d125d
bigcode/the-stack
train
3ed50c54fa5ed420ddf71d28
train
function
def main(): parser = argparse.ArgumentParser(description="Plots Graphs from losses") parser.add_argument("-se", "--search", action='store_true', help="run experiment with search") parser.add_argument("-f", "--features", nargs='+', type=int, default=[100, 300, 1000], ...
def main():
parser = argparse.ArgumentParser(description="Plots Graphs from losses") parser.add_argument("-se", "--search", action='store_true', help="run experiment with search") parser.add_argument("-f", "--features", nargs='+', type=int, default=[100, 300, 1000], he...
import numpy as np import pickle import math import statistics import matplotlib.pyplot as plt import argparse def read_losses(features, seed_num, search=False, pathstr=''): if search: path = pathstr + 'search/' + str(features) + '/' else: path = pathstr + 'fixed/' + str(features) + '/' f...
227
256
924
3
223
armahmood/repn-learning
rrstep.py
Python
main
main
30
101
30
30
e401a1228e40c08d211c8e6ea73d80c13d50f0d6
bigcode/the-stack
train
3eef990c2fd76ed1ec8d55bf
train
function
def calculate_average(features, seeds, search=False, pathstr=''): net_loss=[] for seed_num in seeds: if search: net_loss1 = read_losses(features, seed_num, search=True, pathstr=pathstr) net_loss.append(statistics.mean(net_loss1[-10000:])) else: net_loss1 = r...
def calculate_average(features, seeds, search=False, pathstr=''):
net_loss=[] for seed_num in seeds: if search: net_loss1 = read_losses(features, seed_num, search=True, pathstr=pathstr) net_loss.append(statistics.mean(net_loss1[-10000:])) else: net_loss1 = read_losses(features, seed_num, pathstr=pathstr) net_los...
'fixed/' + str(features) + '/' fname = path + 'run_' + str(seed_num) dbfile = open(fname, 'rb') db = pickle.load(dbfile) dbfile.close() return db def calculate_average(features, seeds, search=False, pathstr=''):
64
64
108
15
48
armahmood/repn-learning
rrstep.py
Python
calculate_average
calculate_average
19
28
19
19
67c5565537ce155dac3fa0d49d3f452126909e11
bigcode/the-stack
train
3d149b559c0008d061372f32
train
function
def bla(evl): def wrap(event): print('wrap:', event) evl.subscribe(handler) return wrap
def bla(evl):
def wrap(event): print('wrap:', event) evl.subscribe(handler) return wrap
#!/usr/bin/env python3 from notify_engine import EventLoop from time import sleep def handler(event): print('handler:', event) def bla(evl):
35
64
27
5
30
kloliks/notify_engine
samples/consumer.py
Python
bla
bla
11
16
11
11
6279f1217b430ae9f064d322c609f9006724c90c
bigcode/the-stack
train
c32f6d665816f6e74715816c
train
function
def handler(event): print('handler:', event)
def handler(event):
print('handler:', event)
#!/usr/bin/env python3 from notify_engine import EventLoop from time import sleep def handler(event):
23
64
11
4
18
kloliks/notify_engine
samples/consumer.py
Python
handler
handler
7
8
7
7
21fdd2a1dc26a455ac4b639b09ea628cde8f82e1
bigcode/the-stack
train
6f888ee507b04a07dd254fba
train
function
def run(evl): evl.subscribe(bla(evl)) while True: evl.run() sleep(0.1)
def run(evl):
evl.subscribe(bla(evl)) while True: evl.run() sleep(0.1)
#!/usr/bin/env python3 from notify_engine import EventLoop from time import sleep def handler(event): print('handler:', event) def bla(evl): def wrap(event): print('wrap:', event) evl.subscribe(handler) return wrap def run(evl):
62
64
30
5
56
kloliks/notify_engine
samples/consumer.py
Python
run
run
19
23
19
19
0ec09b331431cc8291327adf3eb82e74386730c9
bigcode/the-stack
train
29127aa20b978c05e60760ef
train
class
@pytest.mark.workspaceonly @pytest.mark.unittest class TestCliWorkspace(object): def test_directory_paths(self, mocker, monkeypatch): # create fake config directory base = tempfile.mkdtemp() fake_dir = tempfile.mkdtemp(prefix="config", dir=base) full_file_name = "smart.yaml" ...
@pytest.mark.workspaceonly @pytest.mark.unittest class TestCliWorkspace(object):
def test_directory_paths(self, mocker, monkeypatch): # create fake config directory base = tempfile.mkdtemp() fake_dir = tempfile.mkdtemp(prefix="config", dir=base) full_file_name = "smart.yaml" os.path.join(fake_dir, full_file_name) # create fake fixture data to be ...
import logging import os import shutil import tempfile import pytest import ultron8 from ultron8.core import workspace from tests.conftest import fixtures_path logger = logging.getLogger(__name__) @pytest.mark.workspaceonly @pytest.mark.unittest class TestCliWorkspace(object):
61
256
2,326
16
45
bossjones/ultron8
tests/core/test_workspace.py
Python
TestCliWorkspace
TestCliWorkspace
16
292
16
18
74aee46538a3a84dbf4b6d2d8c6b6c5006ff0b90
bigcode/the-stack
train
e024161ac3d4a05826b32734
train
class
class TicketAdminPanel(Component): implements(IAdminPanelProvider, IAdminCommandProvider) abstract = True _type = 'undefined' _label = N_("(Undefined)"), N_("(Undefined)") # i18n note: use gettext() whenever referring to the above as text labels, # and don't use it whenever using ...
class TicketAdminPanel(Component):
implements(IAdminPanelProvider, IAdminCommandProvider) abstract = True _type = 'undefined' _label = N_("(Undefined)"), N_("(Undefined)") # i18n note: use gettext() whenever referring to the above as text labels, # and don't use it whenever using them as field names (after # ...
.ticket import model from trac.ticket.api import TicketSystem from trac.ticket.roadmap import MilestoneModule from trac.util import as_int, getuser from trac.util.datefmt import format_date, format_datetime, \ get_datetime_format_hint, parse_date, user_time from trac.util.text import excep...
112
112
376
6
105
mikiec84/trac
trac/ticket/admin.py
Python
TicketAdminPanel
TicketAdminPanel
31
75
31
32
f75bca69d8787a02b7926c98594bcf409fdb29ec
bigcode/the-stack
train
b4f07c203edcc5a007164940
train
class
class SeverityAdminPanel(AbstractEnumAdminPanel): _type = 'severity' _enum_cls = model.Severity _label = model.Severity.label
class SeverityAdminPanel(AbstractEnumAdminPanel):
_type = 'severity' _enum_cls = model.Severity _label = model.Severity.label
type = 'priority' _enum_cls = model.Priority _label = model.Priority.label class ResolutionAdminPanel(AbstractEnumAdminPanel): _type = 'resolution' _enum_cls = model.Resolution _label = model.Resolution.label class SeverityAdminPanel(AbstractEnumAdminPanel):
64
64
36
9
54
mikiec84/trac
trac/ticket/admin.py
Python
SeverityAdminPanel
SeverityAdminPanel
799
802
799
799
6721f3af0e89a292e4d591cbcc0683291a342818
bigcode/the-stack
train
b9f15913917286bc44ef61b6
train
class
class ResolutionAdminPanel(AbstractEnumAdminPanel): _type = 'resolution' _enum_cls = model.Resolution _label = model.Resolution.label
class ResolutionAdminPanel(AbstractEnumAdminPanel):
_type = 'resolution' _enum_cls = model.Resolution _label = model.Resolution.label
else: return with self.env.db_transaction: enum1.update() enum2.update() class PriorityAdminPanel(AbstractEnumAdminPanel): _type = 'priority' _enum_cls = model.Priority _label = model.Priority.label class ResolutionAdminPanel(AbstractEnumAdminPanel):
64
64
34
9
54
mikiec84/trac
trac/ticket/admin.py
Python
ResolutionAdminPanel
ResolutionAdminPanel
793
796
793
793
e652680474e7993d914a33c44818e3f6108d94c4
bigcode/the-stack
train
3fb81fc83cad59dcac844a32
train
class
class MilestoneAdminPanel(TicketAdminPanel): _type = 'milestones' _label = N_("Milestone"), N_("Milestones") # TicketAdminPanel methods def get_admin_panels(self, req): perm = req.perm('admin', 'ticket/' + self._type) if 'MILESTONE_ADMIN' in perm or \ 'MILESTONE_VIEW' ...
class MilestoneAdminPanel(TicketAdminPanel):
_type = 'milestones' _label = N_("Milestone"), N_("Milestones") # TicketAdminPanel methods def get_admin_panels(self, req): perm = req.perm('admin', 'ticket/' + self._type) if 'MILESTONE_ADMIN' in perm or \ 'MILESTONE_VIEW' in perm and 'TICKET_ADMIN' in perm: ...
complete_add(self, args): if len(args) == 2: return self.get_user_list() def _complete_name(self, args): if len(args) == 1: return self.get_component_list() def _complete_chown(self, args): if len(args) == 1: return self.get_component_list() ...
256
256
1,859
10
246
mikiec84/trac
trac/ticket/admin.py
Python
MilestoneAdminPanel
MilestoneAdminPanel
223
450
223
224
905d33c0a8035d55361fee5b78c258d452b2c456
bigcode/the-stack
train
f38dfba2a45365f6dcfd3f44
train
class
class VersionAdminPanel(TicketAdminPanel): _type = 'versions' _label = N_("Version"), N_("Versions") # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, version): # Detail view? if version: ver = model.Version(self.env, version) if req.meth...
class VersionAdminPanel(TicketAdminPanel):
_type = 'versions' _label = N_("Version"), N_("Versions") # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, version): # Detail view? if version: ver = model.Version(self.env, version) if req.method == 'POST': if req.args.ge...
(self.env)], [_("Name"), _("Due"), _("Completed")]) def _do_add(self, name, due=None): milestone = model.Milestone(self.env) milestone.name = name if due is not None: milestone.due = parse_date(due, hint='datetime', loca...
256
256
1,147
9
247
mikiec84/trac
trac/ticket/admin.py
Python
VersionAdminPanel
VersionAdminPanel
453
604
453
454
506b4aafb197e59301635d801445dc97f5f93378
bigcode/the-stack
train
72b18f19b1931ae1c7de270e
train
class
class AbstractEnumAdminPanel(TicketAdminPanel): abstract = True _type = 'unknown' _enum_cls = None # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, path_info): label = [gettext(each) for each in self._label] data = {'label_singular': label[0], 'label_plura...
class AbstractEnumAdminPanel(TicketAdminPanel):
abstract = True _type = 'unknown' _enum_cls = None # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, path_info): label = [gettext(each) for each in self._label] data = {'label_singular': label[0], 'label_plural': label[1], 'type': self._type}...
for v in model.Version.select(self.env)] def _complete_name(self, args): if len(args) == 1: return self.get_version_list() def _do_list(self): print_table([(v.name, format_date(v.time, console_date_format) if v.time else None) ...
256
256
1,489
10
246
mikiec84/trac
trac/ticket/admin.py
Python
AbstractEnumAdminPanel
AbstractEnumAdminPanel
607
784
607
608
8cd27063a40d7003bd6cc9ce761f806888848c5c
bigcode/the-stack
train
d755958ee12948c26d6b9fd0
train
class
class TicketAdmin(Component): """trac-admin command provider for ticket administration.""" implements(IAdminCommandProvider) # IAdminCommandProvider methods def get_admin_commands(self): yield ('ticket remove', '<ticket#>', 'Remove ticket', None, self._do_remove) yield ...
class TicketAdmin(Component):
"""trac-admin command provider for ticket administration.""" implements(IAdminCommandProvider) # IAdminCommandProvider methods def get_admin_commands(self): yield ('ticket remove', '<ticket#>', 'Remove ticket', None, self._do_remove) yield ('ticket remove_comment', '<ti...
_type = 'type' _enum_cls = model.Type _label = model.Type.label _command_type = 'ticket_type' _command_help = { 'list': 'Show possible %s', 'add': 'Add a %s', 'change': 'Change a %s', 'remove': 'Remove a %s', 'order': 'Move a %s up or down in the list', }...
101
101
338
5
96
mikiec84/trac
trac/ticket/admin.py
Python
TicketAdmin
TicketAdmin
820
857
820
820
e1d652965946d58de4bda285307b6a7bb50dc672
bigcode/the-stack
train
0e2a136b51997f06f791334d
train
class
class PriorityAdminPanel(AbstractEnumAdminPanel): _type = 'priority' _enum_cls = model.Priority _label = model.Priority.label
class PriorityAdminPanel(AbstractEnumAdminPanel):
_type = 'priority' _enum_cls = model.Priority _label = model.Priority.label
.env): if int(float(enum2.value)) == enum1.value: enum2.value = int(float(enum2.value) - direction) break else: return with self.env.db_transaction: enum1.update() enum2.update() class PriorityAdminPanel(AbstractEnumAdminPan...
64
64
32
9
55
mikiec84/trac
trac/ticket/admin.py
Python
PriorityAdminPanel
PriorityAdminPanel
787
790
787
787
db6d7b35169a439351c003306778f73dffd45105
bigcode/the-stack
train
fcbe78119cae10d47a7dec32
train
class
class TicketTypeAdminPanel(AbstractEnumAdminPanel): _type = 'type' _enum_cls = model.Type _label = model.Type.label _command_type = 'ticket_type' _command_help = { 'list': 'Show possible %s', 'add': 'Add a %s', 'change': 'Change a %s', 'remove': 'Remove a %s', ...
class TicketTypeAdminPanel(AbstractEnumAdminPanel):
_type = 'type' _enum_cls = model.Type _label = model.Type.label _command_type = 'ticket_type' _command_help = { 'list': 'Show possible %s', 'add': 'Add a %s', 'change': 'Change a %s', 'remove': 'Remove a %s', 'order': 'Move a %s up or down in the list', }...
_enum_cls = model.Resolution _label = model.Resolution.label class SeverityAdminPanel(AbstractEnumAdminPanel): _type = 'severity' _enum_cls = model.Severity _label = model.Severity.label class TicketTypeAdminPanel(AbstractEnumAdminPanel):
64
64
106
10
53
mikiec84/trac
trac/ticket/admin.py
Python
TicketTypeAdminPanel
TicketTypeAdminPanel
805
817
805
805
4b84717f9d1193dee2f02c3bcbd69f09c802a0a8
bigcode/the-stack
train
d89dc980f4895f09abc758e4
train
class
class ComponentAdminPanel(TicketAdminPanel): _type = 'components' _label = N_("Component"), N_("Components") # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, component): # Detail view? if component: comp = model.Component(self.env, component) ...
class ComponentAdminPanel(TicketAdminPanel):
_type = 'components' _label = N_("Component"), N_("Components") # TicketAdminPanel methods def _render_admin_panel(self, req, cat, page, component): # Detail view? if component: comp = model.Component(self.env, component) if req.method == 'POST': ...
): yield ('ticket', _('Ticket System'), self._type, gettext(self._label[1])) def render_admin_panel(self, req, cat, page, path_info): # Trap AssertionErrors and convert them to TracErrors try: return self._render_admin_panel(req, cat, page, path_info) ...
255
256
1,030
9
246
mikiec84/trac
trac/ticket/admin.py
Python
ComponentAdminPanel
ComponentAdminPanel
78
220
78
79
6d0f38dc41458a32bad2d184a1bd27273797a9a5
bigcode/the-stack
train
b37087fd425201441e8d29dd
train
function
def _verify_bsgs(group, base, gens): """ Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will...
def _verify_bsgs(group, base, gens):
""" Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will serve for more robust testing. ...
for element in elements: if commutes_with_gens(element): centralizer_list.append(element) return centralizer_list elif hasattr(other, 'getitem'): return _naive_list_centralizer(self, PermutationGroup(other)) elif hasattr(other, 'array_form'): return _n...
90
90
303
12
78
lefevre-fraser/openmeta-mms
bin/Python27/Lib/site-packages/sympy/combinatorics/testutil.py
Python
_verify_bsgs
_verify_bsgs
69
104
69
69
e0e66662085e6f029f7e9e95a1b19804d05d04df
bigcode/the-stack
train
661dfbfa65b2f9985ecf78fe
train
function
def _verify_normal_closure(group, arg, closure=None): from sympy.combinatorics.perm_groups import PermutationGroup """ Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== ...
def _verify_normal_closure(group, arg, closure=None):
from sympy.combinatorics.perm_groups import PermutationGroup """ Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== >>> from sympy.combinatorics.named_groups import (...
naive_list_centralizer,\ sympy.combinatorics.perm_groups.PermutationGroup.centralizer,\ _cmp_perm_lists """ if centr is None: centr = group.centralizer(arg) centr_list = list(centr.generate_dimino()) centr_list_naive = _naive_list_centralizer(group, arg) return _cmp_perm_lists(centr...
102
102
341
13
89
lefevre-fraser/openmeta-mms
bin/Python27/Lib/site-packages/sympy/combinatorics/testutil.py
Python
_verify_normal_closure
_verify_normal_closure
141
182
141
141
ba82c6242473a9cbafacabf3b5d6ef738a4bf9ee
bigcode/the-stack
train
58f7cf180f097841ea1766bb
train
function
def _naive_list_centralizer(self, other): from sympy.combinatorics.perm_groups import PermutationGroup """ Return a list of elements for the centralizer of a subgroup/set/element. This is a brute-force implementation that goes over all elements of the group and checks for membership in the centrali...
def _naive_list_centralizer(self, other):
from sympy.combinatorics.perm_groups import PermutationGroup """ Return a list of elements for the centralizer of a subgroup/set/element. This is a brute-force implementation that goes over all elements of the group and checks for membership in the centralizer. It is used to test ``.centralizer...
0, 4, 3]) >>> c = Permutation([3, 4, 0, 1, 2]) >>> ls1 = [a, b, c] >>> ls2 = [b, c, a] >>> _cmp_perm_lists(ls1, ls2) True """ return set([tuple(a) for a in first]) == \ set([tuple(a) for a in second]) def _naive_list_centralizer(self, other):
108
108
362
12
96
lefevre-fraser/openmeta-mms
bin/Python27/Lib/site-packages/sympy/combinatorics/testutil.py
Python
_naive_list_centralizer
_naive_list_centralizer
31
67
31
31
61e16d9274250c67b95c7d77a17375f10286e846
bigcode/the-stack
train
1b9b9199614e957fd8a134cc
train
function
def _cmp_perm_lists(first, second): """ Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.per...
def _cmp_perm_lists(first, second):
""" Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>>...
from sympy.combinatorics.util import _distribute_gens_by_base from sympy.combinatorics import Permutation rmul = Permutation.rmul def _cmp_perm_lists(first, second):
45
68
227
9
35
lefevre-fraser/openmeta-mms
bin/Python27/Lib/site-packages/sympy/combinatorics/testutil.py
Python
_cmp_perm_lists
_cmp_perm_lists
6
29
6
6
3c13a0f9ac4d653f8e725cf4776e90fb241ca2ff
bigcode/the-stack
train
770e7f7a9949c1a5e8b503ef
train
function
def _verify_centralizer(group, arg, centr=None): """ Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup,...
def _verify_centralizer(group, arg, centr=None):
""" Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.com...
group for i in range(len(base)): candidate = PermutationGroup(strong_gens_distr[i]) if current_stabilizer.order() != candidate.order(): return False current_stabilizer = current_stabilizer.stabilizer(base[i]) if current_stabilizer.order() != 1: return False retur...
89
89
298
13
75
lefevre-fraser/openmeta-mms
bin/Python27/Lib/site-packages/sympy/combinatorics/testutil.py
Python
_verify_centralizer
_verify_centralizer
106
139
106
106
0ebc284d855faeb2e437d323923c7cba9719dc1a
bigcode/the-stack
train
b555e25a48c6410a301bd13f
train
function
def scale_down_sample(image_tensor, layer_count): re = tf.reshape(image_tensor, (batch_size, layer_sizes[layer_count], layer_sizes[layer_count], 1)) pool = tf.layers.average_pooling2d(re, [2,2], 2) back = tf.reshape(pool, (batch_size, layer_sizes[layer_count-1]**2)) return back
def scale_down_sample(image_tensor, layer_count):
re = tf.reshape(image_tensor, (batch_size, layer_sizes[layer_count], layer_sizes[layer_count], 1)) pool = tf.layers.average_pooling2d(re, [2,2], 2) back = tf.reshape(pool, (batch_size, layer_sizes[layer_count-1]**2)) return back
2].reshape(next_size, 2, next_size, 2).max(axis=(1, 3)) re = re.reshape(next_size**2) new_arr[i] = re return downsize_real(new_arr, layer_count +1) def scale_down_sample(image_tensor, layer_count):
64
64
80
10
54
antonstagge/pro_gan
helpers.py
Python
scale_down_sample
scale_down_sample
47
51
47
47
6baf3b5474d18d76594e4472d55aa7b8e1350f5b
bigcode/the-stack
train
a88d74641f5848c5b91c81fb
train
function
def downsize_real(batch_images, layer_count): if layer_count == 2: return batch_images current_size = int(np.sqrt(batch_images.shape[1])) next_size = int(current_size / 2) new_arr = np.ndarray((batch_size, next_size**2)) for i, image in enumerate(batch_images): image = image.reshape(...
def downsize_real(batch_images, layer_count):
if layer_count == 2: return batch_images current_size = int(np.sqrt(batch_images.shape[1])) next_size = int(current_size / 2) new_arr = np.ndarray((batch_size, next_size**2)) for i, image in enumerate(batch_images): image = image.reshape(current_size, current_size) re = image...
enumerate(X): j = n // nh_nw[1] i = n % nh_nw[1] img[j*h:j*h+h, i*w:i*w+w, :] = x scipy.misc.imsave(save_path, img) def downsize_real(batch_images, layer_count):
64
64
151
10
54
antonstagge/pro_gan
helpers.py
Python
downsize_real
downsize_real
34
45
34
34
9a44981d2591e52cfe629ce57d2e74dda5bc52e2
bigcode/the-stack
train
a005f6ac3675cc814779452d
train
function
def save_visualization(X, nh_nw, save_path='./images/sample.jpg'): h,w = X.shape[1], X.shape[2] img = np.zeros((h * nh_nw[0], w * nh_nw[1], 3)) for n,x in enumerate(X): j = n // nh_nw[1] i = n % nh_nw[1] img[j*h:j*h+h, i*w:i*w+w, :] = x scipy.misc.imsave(save_path, img)
def save_visualization(X, nh_nw, save_path='./images/sample.jpg'):
h,w = X.shape[1], X.shape[2] img = np.zeros((h * nh_nw[0], w * nh_nw[1], 3)) for n,x in enumerate(X): j = n // nh_nw[1] i = n % nh_nw[1] img[j*h:j*h+h, i*w:i*w+w, :] = x scipy.misc.imsave(save_path, img)
_batch_x = data_x[current_index:current_index + batch_size] data_batch_y = data_y[current_index:current_index + batch_size] current_index += batch_size yield data_batch_x, data_batch_y def save_visualization(X, nh_nw, save_path='./images/sample.jpg'):
64
64
115
17
46
antonstagge/pro_gan
helpers.py
Python
save_visualization
save_visualization
23
32
23
23
35589a19f14976b1780e8f1f655df3a613ef5187
bigcode/the-stack
train
df1d41995f87993c1bedbc25
train
function
def scale_up_sample(image_tensor, layer_count): re = tf.reshape(image_tensor, (batch_size, layer_sizes[layer_count-1],layer_sizes[layer_count-1], 1)) near_neigh = tf.image.resize_nearest_neighbor(re, size=(layer_sizes[layer_count], layer_sizes[layer_count])) back = tf.reshape(near_neigh, [batch_size, layer_...
def scale_up_sample(image_tensor, layer_count):
re = tf.reshape(image_tensor, (batch_size, layer_sizes[layer_count-1],layer_sizes[layer_count-1], 1)) near_neigh = tf.image.resize_nearest_neighbor(re, size=(layer_sizes[layer_count], layer_sizes[layer_count])) back = tf.reshape(near_neigh, [batch_size, layer_sizes[layer_count]**2]) return back
], layer_sizes[layer_count], 1)) pool = tf.layers.average_pooling2d(re, [2,2], 2) back = tf.reshape(pool, (batch_size, layer_sizes[layer_count-1]**2)) return back def scale_up_sample(image_tensor, layer_count):
64
64
89
10
53
antonstagge/pro_gan
helpers.py
Python
scale_up_sample
scale_up_sample
53
57
53
53
ad24a4af1d8270a4903c01e9c467d7e56881f78e
bigcode/the-stack
train
a656c04d95e0cf5eb7ef78c6
train
function
def get_batches(batch_size, data_x, data_y): """ Return batch_size of the data vector at a time """ current_index = 0 while current_index + batch_size <= data_x.shape[0]: data_batch_x = data_x[current_index:current_index + batch_size] data_batch_y = data_y[current_index:current_inde...
def get_batches(batch_size, data_x, data_y):
""" Return batch_size of the data vector at a time """ current_index = 0 while current_index + batch_size <= data_x.shape[0]: data_batch_x = data_x[current_index:current_index + batch_size] data_batch_y = data_y[current_index:current_index + batch_size] current_index += batc...
_one_hot(X): # X = np.asarray(X).flatten() one_hot = np.zeros((len(X), 10)) for i in range(len(X)): one_hot[i, X[i]] = 1. return one_hot def get_batches(batch_size, data_x, data_y):
64
64
99
12
51
antonstagge/pro_gan
helpers.py
Python
get_batches
get_batches
11
21
11
11
a2d3f44fc8df08e5e92601b9664548f65cf3adcb
bigcode/the-stack
train
4b8264659791dfa2c080dff1
train
function
def make_one_hot(X): # X = np.asarray(X).flatten() one_hot = np.zeros((len(X), 10)) for i in range(len(X)): one_hot[i, X[i]] = 1. return one_hot
def make_one_hot(X): # X = np.asarray(X).flatten()
one_hot = np.zeros((len(X), 10)) for i in range(len(X)): one_hot[i, X[i]] = 1. return one_hot
import scipy.misc import numpy as np def make_one_hot(X): # X = np.asarray(X).flatten()
25
64
54
16
8
antonstagge/pro_gan
helpers.py
Python
make_one_hot
make_one_hot
4
9
4
5
0e96f85d9364ce0a328e1f7864ef110194c6cf65
bigcode/the-stack
train
7caf29ae6d1efa810f29b6b4
train
class
class CreateTransaction(PokepayRequest): def __init__(self, shop_id, customer_id, private_money_id, **rest_args): self.path = "/transactions" self.method = "POST" self.body_params = {"shop_id": shop_id, "customer_id": customer_id, "priv...
class CreateTransaction(PokepayRequest):
def __init__(self, shop_id, customer_id, private_money_id, **rest_args): self.path = "/transactions" self.method = "POST" self.body_params = {"shop_id": shop_id, "customer_id": customer_id, "private_money_id": private_money_id} ...
# DO NOT EDIT: File is generated by code generator. from pokepay_partner_python_sdk.pokepay.request.request import PokepayRequest from pokepay_partner_python_sdk.pokepay.response.transaction import Transaction class CreateTransaction(PokepayRequest):
56
64
89
9
46
pokepay/pokepay-partner-python-sdk
pokepay/request/create_transaction.py
Python
CreateTransaction
CreateTransaction
7
15
7
7
5041fa8b15286cf7e098eaa4be3c0ef3cc34e402
bigcode/the-stack
train
91d34e603bb51f8041de1d63
train
class
class Interval(object): __slots__ = ['start', 'end'] def __init__(self, start, end=None, delta=None): """ Create Interval object with datetime start and end :param start: the beginning :type start: datetime :param end: this is the end my only truly friend the end ...
class Interval(object):
__slots__ = ['start', 'end'] def __init__(self, start, end=None, delta=None): """ Create Interval object with datetime start and end :param start: the beginning :type start: datetime :param end: this is the end my only truly friend the end :type end: datetime | N...
FORMAT', 'get_datetime', ] # bucket size in seconds BUCKET_SIZE = 600 SEC_IN_DAY = 3600 * 24 FORMAT = "%Y-%m-%dT%H:%M:%S" def dt(date): return datetime.strptime(date, FORMAT) class Interval(object):
64
64
158
4
60
immunochomik/notmany
notmany/store/base.py
Python
Interval
Interval
28
49
28
28
1c3abb2105d5b037ec3e692015c1a15a693dec16
bigcode/the-stack
train
6a224b653dfb36d34272e344
train
function
def naive_tstamp(dt): return (dt - datetime(1970, 1, 1)).total_seconds()
def naive_tstamp(dt):
return (dt - datetime(1970, 1, 1)).total_seconds()
) in [int, float]: return datetime.fromtimestamp(timestamp) if isinstance(timestamp, str): # deal with optional milliseconds _format = FORMAT + '.%f' if '.' in timestamp else FORMAT return datetime.strptime(timestamp, _format) return timestamp def naive_tstamp(dt):
64
64
25
6
57
immunochomik/notmany
notmany/store/base.py
Python
naive_tstamp
naive_tstamp
68
69
68
68
d1e013bac716499aa47fa40e4aca456181638a7f
bigcode/the-stack
train
06625334bea3b76b66dda515
train
class
@six.add_metaclass(ABCMeta) class BucketBase(object): __slots__ = ['name', 'start', 'length'] def __init__(self, name, start, length): assert isinstance(start, datetime), 'Start has to be a datetime' assert isinstance(length, int), 'Length has to be a int' self.name = name self....
@six.add_metaclass(ABCMeta) class BucketBase(object):
__slots__ = ['name', 'start', 'length'] def __init__(self, name, start, length): assert isinstance(start, datetime), 'Start has to be a datetime' assert isinstance(length, int), 'Length has to be a int' self.name = name self.start = start self.length = length def __...
abstractmethod def forget(self, name, interval=None): """ Delete buckets in the interval :param name: :param interval: interval to delete :type interval: Interval :return: """ @six.add_metaclass(ABCMeta) class BucketBase(object):
63
64
151
14
49
immunochomik/notmany
notmany/store/base.py
Python
BucketBase
BucketBase
210
235
210
211
cb7c87539ad7c28cb5a2905fcb4d4b3c2285b743
bigcode/the-stack
train
a02e3a3dbea6eb7adaf92f64
train
function
def get_datetime(timestamp): if type(timestamp) in [int, float]: return datetime.fromtimestamp(timestamp) if isinstance(timestamp, str): # deal with optional milliseconds _format = FORMAT + '.%f' if '.' in timestamp else FORMAT return datetime.strptime(timestamp, _format) r...
def get_datetime(timestamp):
if type(timestamp) in [int, float]: return datetime.fromtimestamp(timestamp) if isinstance(timestamp, str): # deal with optional milliseconds _format = FORMAT + '.%f' if '.' in timestamp else FORMAT return datetime.strptime(timestamp, _format) return timestamp
(start) if end is None: self.end = self.start + delta else: self.end = get_datetime(end) if self.start > self.end: raise RuntimeError('Invalid interval start after end') def stamp(date): return datetime.strptime(date, FORMAT) def get_datetime(timestamp...
64
64
67
5
59
immunochomik/notmany
notmany/store/base.py
Python
get_datetime
get_datetime
56
65
56
56
c9bebe0fcd4f58a1a2e9d5bef2018ee546f403f1
bigcode/the-stack
train
6d048022d476a25e5f175ecc
train
function
def stamp(date): return datetime.strptime(date, FORMAT)
def stamp(date):
return datetime.strptime(date, FORMAT)
: timedelta | None """ self.start = get_datetime(start) if end is None: self.end = self.start + delta else: self.end = get_datetime(end) if self.start > self.end: raise RuntimeError('Invalid interval start after end') def stamp(date):
64
64
12
4
60
immunochomik/notmany
notmany/store/base.py
Python
stamp
stamp
52
53
52
52
a0ad26a74fdf301dd300d5006d70e8918e905f69
bigcode/the-stack
train
6a4991f6bc260f319dc470bd
train
function
def dt(date): return datetime.strptime(date, FORMAT)
def dt(date):
return datetime.strptime(date, FORMAT)
'StoreSetupError', 'Interval', 'FORMAT', 'get_datetime', ] # bucket size in seconds BUCKET_SIZE = 600 SEC_IN_DAY = 3600 * 24 FORMAT = "%Y-%m-%dT%H:%M:%S" def dt(date):
64
64
12
4
60
immunochomik/notmany
notmany/store/base.py
Python
dt
dt
24
25
24
24
d034cd5e12a2844095a7a9caca3388df66b090ee
bigcode/the-stack
train
a01449bebfaca64a1331618d
train
class
@six.add_metaclass(ABCMeta) class StoreBase(object): def __init__(self, bucket_size=BUCKET_SIZE): if bucket_size % 60: raise NotImplementedError('Currently buckets have to be in minutes') if bucket_size > 3600 * 24: raise NotImplementedError('We do not support buckets larger...
@six.add_metaclass(ABCMeta) class StoreBase(object):
def __init__(self, bucket_size=BUCKET_SIZE): if bucket_size % 60: raise NotImplementedError('Currently buckets have to be in minutes') if bucket_size > 3600 * 24: raise NotImplementedError('We do not support buckets larger than 24 h') self._bucket_size = bucket_size ...
else: self.end = get_datetime(end) if self.start > self.end: raise RuntimeError('Invalid interval start after end') def stamp(date): return datetime.strptime(date, FORMAT) def get_datetime(timestamp): if type(timestamp) in [int, float]: return datetime.fromti...
223
223
745
14
208
immunochomik/notmany
notmany/store/base.py
Python
StoreBase
StoreBase
89
207
89
91
76e48ff61469cb0e91c59236a99b17f7b259ee22
bigcode/the-stack
train
76addf5c86cbe9ffc5440ef3
train
class
class StoreSetupError(Exception): pass
class StoreSetupError(Exception):
pass
:param record: 'cpu:7.5,foo:8' :return: """ data = {} for pair in record.split(','): elem = pair.split(':') data[elem[0]] = float(elem[1]) return data class StoreSetupError(Exception):
64
64
9
6
57
immunochomik/notmany
notmany/store/base.py
Python
StoreSetupError
StoreSetupError
85
86
85
85
04521fc72a34886e35b63bd3fffe27b3d430a7fe
bigcode/the-stack
train
7411f7f65ff765d461c27bac
train
function
def record_to_data(record): """ :param record: 'cpu:7.5,foo:8' :return: """ data = {} for pair in record.split(','): elem = pair.split(':') data[elem[0]] = float(elem[1]) return data
def record_to_data(record):
""" :param record: 'cpu:7.5,foo:8' :return: """ data = {} for pair in record.split(','): elem = pair.split(':') data[elem[0]] = float(elem[1]) return data
optional milliseconds _format = FORMAT + '.%f' if '.' in timestamp else FORMAT return datetime.strptime(timestamp, _format) return timestamp def naive_tstamp(dt): return (dt - datetime(1970, 1, 1)).total_seconds() def record_to_data(record):
64
64
66
6
58
immunochomik/notmany
notmany/store/base.py
Python
record_to_data
record_to_data
72
82
72
72
7fa97c013304b3ddbe3c179c391a880b88be7ef8
bigcode/the-stack
train
77647342c5c73848bc539908
train
class
class OkAddCaseButton(windowButton): def __init__(self, parent=None): windowButton.__init__(self, parent) self.setStyleSheet("windowButton{" "height: 24px;" "width: 24px;" "background: url(:/images/plus_24x24_gray.png)" "}" ...
class OkAddCaseButton(windowButton):
def __init__(self, parent=None): windowButton.__init__(self, parent) self.setStyleSheet("windowButton{" "height: 24px;" "width: 24px;" "background: url(:/images/plus_24x24_gray.png)" "}" "windowButton:hover {...
(Qt.QPushButton): def __init__(self, parent=None): Qt.QPushButton.__init__(self, parent) self.setFocusPolicy(Qt.Qt.NoFocus) self.setMaximumSize(26, 26) self.setFlat(1) class OkAddCaseButton(windowButton):
63
64
101
8
55
ghold/OneKeySql
onekey/OkButton.py
Python
OkAddCaseButton
OkAddCaseButton
61
71
61
61
73ebe1c16548d4821571a1bc98f1e7a1c3b3c8a1
bigcode/the-stack
train
7bfa2ab79d34ce7f1e353f78
train
class
class OkModuleButton(Qt.QPushButton): def __init__(self, text, image, parent=None): Qt.QPushButton.__init__(self, text, parent) self.setMinimumSize(200, 35) self.image = image self.setFlat(1) self.setCheckable(True) self.setFocusPolicy(Qt.Qt.NoFocus) ...
class OkModuleButton(Qt.QPushButton):
def __init__(self, text, image, parent=None): Qt.QPushButton.__init__(self, text, parent) self.setMinimumSize(200, 35) self.image = image self.setFlat(1) self.setCheckable(True) self.setFocusPolicy(Qt.Qt.NoFocus) self.setStyleSheet("QPushButton{" ...
from PyQt4 import Qt class OkModuleButton(Qt.QPushButton):
17
78
260
9
7
ghold/OneKeySql
onekey/OkButton.py
Python
OkModuleButton
OkModuleButton
3
31
3
3
6517f3d2214e40e10dc89d9502faa1f1983f7a4d
bigcode/the-stack
train
5dbc29cd4ad93cea7afda7a7
train
class
class OkExecButton(Qt.QPushButton): def __init__(self, text, parent=None): Qt.QPushButton.__init__(self, text, parent) self.setStyleSheet("QPushButton{" "border:1px solid #000000;" "background-color: #656565;" "height: 25px;" ...
class OkExecButton(Qt.QPushButton):
def __init__(self, text, parent=None): Qt.QPushButton.__init__(self, text, parent) self.setStyleSheet("QPushButton{" "border:1px solid #000000;" "background-color: #656565;" "height: 25px;" "font-size: 16px;" ...
"}" "QPushButton:hover{" "color: #fff;" "border: 0px;" "padding-left: 36px;" "background: #4da6ea url("+self.image+") no-repeat" "}") class OkExecButton(Qt.QPushButton):
63
64
168
9
54
ghold/OneKeySql
onekey/OkButton.py
Python
OkExecButton
OkExecButton
33
52
33
33
53ad0470ca24ba58709f97c1272dbcf21e65e482
bigcode/the-stack
train
2a121468ae002caa3d307780
train
class
class OkCancelButton(windowButton): def __init__(self, parent=None): windowButton.__init__(self, parent) self.setStyleSheet("windowButton{" "height: 24px;" "width: 24px;" "background: url(:/images/xmark_24x24_gray.png)" "}" ...
class OkCancelButton(windowButton):
def __init__(self, parent=None): windowButton.__init__(self, parent) self.setStyleSheet("windowButton{" "height: 24px;" "width: 24px;" "background: url(:/images/xmark_24x24_gray.png)" "}" "windowButton:hover ...
;" "width: 24px;" "background: url(:/images/plus_24x24_gray.png)" "}" "windowButton:hover {" "background: url(:/images/plus_24x24_blue.png)" "}") class OkCancelButton(windowButton):
63
64
100
7
56
ghold/OneKeySql
onekey/OkButton.py
Python
OkCancelButton
OkCancelButton
73
83
73
73
068b9b2e2a758dd37d49d9c20a00278e2fd186b2
bigcode/the-stack
train
46e46fff90999eeaa282eb0a
train
class
class windowButton(Qt.QPushButton): def __init__(self, parent=None): Qt.QPushButton.__init__(self, parent) self.setFocusPolicy(Qt.Qt.NoFocus) self.setMaximumSize(26, 26) self.setFlat(1)
class windowButton(Qt.QPushButton):
def __init__(self, parent=None): Qt.QPushButton.__init__(self, parent) self.setFocusPolicy(Qt.Qt.NoFocus) self.setMaximumSize(26, 26) self.setFlat(1)
#FFF;" "}" "QPushButton:hover{" "border:1px solid #9BBAAC;" "}" "QPushButton:focus{" "border:1px solid #7ECEFD;" "}") class windowButton(Qt.QPushButton):
63
64
58
8
55
ghold/OneKeySql
onekey/OkButton.py
Python
windowButton
windowButton
54
59
54
54
8a03b0d8c3b58ad0f882564419bfdc1523ee013c
bigcode/the-stack
train
ce55dc12168a5f6d08acd768
train
function
def _compare_interp_time_tables(first_interp_time_table, second_interp_time_table): """Compares two tables with interpolation times. :param first_interp_time_table: pandas DataFrame created by `nwp_model_utils.get_times_needed_for_interp`. :param second_interp_time_t...
def _compare_interp_time_tables(first_interp_time_table, second_interp_time_table):
"""Compares two tables with interpolation times. :param first_interp_time_table: pandas DataFrame created by `nwp_model_utils.get_times_needed_for_interp`. :param second_interp_time_table: Same. :return: are_tables_equal: Boolean flag. """ first_column_names = list(first_interp_time_ta...
.5 - 5 * HALF_ROOT3, -10 - 10 * HALF_ROOT3], [10, 7.5 - 5 * HALF_ROOT3, -10 - 10 * HALF_ROOT3] ]) def _compare_interp_time_tables(first_interp_time_table, second_interp_time_table):
64
64
210
17
47
dopplerchase/GewitterGefahr
gewittergefahr/gg_utils/nwp_model_utils_test.py
Python
_compare_interp_time_tables
_compare_interp_time_tables
213
241
213
214
907bcbb231b13f72ad299a552ce14f7f09c9f24d
bigcode/the-stack
train
046849679cd49a659f2210b2
train
class
class NwpModelUtilsTests(unittest.TestCase): """Each method is a unit test for nwp_model_utils.py.""" def test_check_grid_name_narr221(self): """Ensures correct output from check_grid_name. In this case, model is NARR and grid is NCEP 221. """ nwp_model_utils.check_grid_name( ...
class NwpModelUtilsTests(unittest.TestCase):
"""Each method is a unit test for nwp_model_utils.py.""" def test_check_grid_name_narr221(self): """Ensures correct output from check_grid_name. In this case, model is NARR and grid is NCEP 221. """ nwp_model_utils.check_grid_name( model_name=nwp_model_utils.NARR_M...
10 - 10 * HALF_ROOT3], [10, 7.5 - 5 * HALF_ROOT3, -10 - 10 * HALF_ROOT3] ]) def _compare_interp_time_tables(first_interp_time_table, second_interp_time_table): """Compares two tables with interpolation times. :param first_interp_time_table: pandas DataFrame created by ...
256
256
4,795
10
245
dopplerchase/GewitterGefahr
gewittergefahr/gg_utils/nwp_model_utils_test.py
Python
NwpModelUtilsTests
NwpModelUtilsTests
244
803
244
244
814de420d2c4567c904342ee0d79b43e462fe0dc
bigcode/the-stack
train
08ff53626a4d469c8ae37bee
train
class
class RedditCredInfo(BaseSettings): # Create credential at https://www.reddit.com/prefs/apps # Also refer https://praw.readthedocs.io/en/latest/getting_started/authentication.html # Currently Password Flow, Read Only Mode and Saved Refresh Token Mode are supported client_id: SecretStr = Field(None, env=...
class RedditCredInfo(BaseSettings): # Create credential at https://www.reddit.com/prefs/apps # Also refer https://praw.readthedocs.io/en/latest/getting_started/authentication.html # Currently Password Flow, Read Only Mode and Saved Refresh Token Mode are supported
client_id: SecretStr = Field(None, env="reddit_client_id") client_secret: SecretStr = Field(None, env="reddit_client_secret") user_agent: str = "Test User Agent" redirect_uri: Optional[str] = None refresh_token: Optional[SecretStr] = Field(None, env="reddit_refresh_token") username: Optional[str...
SourceConfig class RedditCredInfo(BaseSettings): # Create credential at https://www.reddit.com/prefs/apps # Also refer https://praw.readthedocs.io/en/latest/getting_started/authentication.html # Currently Password Flow, Read Only Mode and Saved Refresh Token Mode are supported
64
64
173
61
2
kuutsav/obsei
obsei/source/reddit_source.py
Python
RedditCredInfo
RedditCredInfo
17
28
17
20
59228a8f5820176f1bc9ad4c20f692e4e2ee7e0a
bigcode/the-stack
train
6ce08f883ea2e12b73241f95
train
class
class RedditConfig(BaseSourceConfig): # This is done to avoid exposing member to API response _reddit_client: Reddit = PrivateAttr() TYPE: str = "Reddit" subreddits: List[str] post_ids: Optional[List[str]] = None lookup_period: Optional[str] = None include_post_meta: Optional[bool] = True ...
class RedditConfig(BaseSourceConfig): # This is done to avoid exposing member to API response
_reddit_client: Reddit = PrivateAttr() TYPE: str = "Reddit" subreddits: List[str] post_ids: Optional[List[str]] = None lookup_period: Optional[str] = None include_post_meta: Optional[bool] = True post_meta_field: str = "post_meta" cred_info: Optional[RedditCredInfo] = Field(None) de...
redirect_uri: Optional[str] = None refresh_token: Optional[SecretStr] = Field(None, env="reddit_refresh_token") username: Optional[str] = Field(None, env="reddit_username") password: Optional[SecretStr] = Field(None, env="reddit_password") read_only: bool = True class RedditConfig(BaseSourceConfig): ...
88
88
295
20
67
kuutsav/obsei
obsei/source/reddit_source.py
Python
RedditConfig
RedditConfig
31
64
31
32
6141afaf1677b2b4f237a2ac0cd6179dade541b5
bigcode/the-stack
train
1676eccc7e363b02ea5740ed
train
class
class RedditSource(BaseSource): NAME: str = "Reddit" def lookup(self, config: RedditConfig, **kwargs) -> List[TextPayload]: # type: ignore[override] source_responses: List[TextPayload] = [] # Get data from state id: str = kwargs.get("id", None) state: Optional[Dict[str, Any]] ...
class RedditSource(BaseSource):
NAME: str = "Reddit" def lookup(self, config: RedditConfig, **kwargs) -> List[TextPayload]: # type: ignore[override] source_responses: List[TextPayload] = [] # Get data from state id: str = kwargs.get("id", None) state: Optional[Dict[str, Any]] = ( None ...
: Any): super().__init__(**data) self.cred_info = self.cred_info or RedditCredInfo() self._reddit_client = Reddit( client_id=self.cred_info.client_id.get_secret_value(), client_secret=self.cred_info.client_secret.get_secret_value(), redirect_uri=self.cred_in...
186
186
620
6
179
kuutsav/obsei
obsei/source/reddit_source.py
Python
RedditSource
RedditSource
67
149
67
67
54fa6dbc4c6380f040bda9614837146dd181a1b3
bigcode/the-stack
train
78c6c2a99828dfa56f396f6f
train
function
def _test_logistic(data): """ One iteration of LOGISTIC """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.sigmoid(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def _test_logistic(data):
""" One iteration of LOGISTIC """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.sigmoid(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
1, 3)), np.arange(6).reshape((2, 1, 1, 3)), np.arange(6).reshape((2, 1, 1, 3))], 1) ####################################################################### # Logistic # -------- def _test_logistic(data):
64
64
70
7
56
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_logistic
_test_logistic
840
845
840
840
d18062a4c9894b63d9f8309c608f1783bc699c32
bigcode/the-stack
train
b39905199156062b512bb90f
train
function
def test_all_elemwise(): _test_forward_elemwise(_test_add) _test_forward_elemwise(partial(_test_add, fused_activation_function="RELU")) _test_forward_elemwise(partial(_test_add, fused_activation_function="RELU6")) _test_forward_elemwise(_test_sub) _test_forward_elemwise(partial(_test_sub, fused_acti...
def test_all_elemwise():
_test_forward_elemwise(_test_add) _test_forward_elemwise(partial(_test_add, fused_activation_function="RELU")) _test_forward_elemwise(partial(_test_add, fused_activation_function="RELU6")) _test_forward_elemwise(_test_sub) _test_forward_elemwise(partial(_test_sub, fused_activation_function="RELU")) ...
0, dtype=np.float32).reshape((2, 1, 3))]) testop([np.arange(3.0, dtype=np.float32).reshape((1, 3)), np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3))]) def test_all_elemwise():
73
73
245
6
67
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_all_elemwise
test_all_elemwise
636
652
636
636
1cd88f2bb1a981a660cef572c9bd5e7c5885477b
bigcode/the-stack
train
dd96c113cc7e3497d183183f
train
function
def test_forward_pad(): """ Pad """ _test_pad([np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)), np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32)]) _test_pad([np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)), np.array([[2, 2], [1, 1], [1, 1]], dtype...
def test_forward_pad():
""" Pad """ _test_pad([np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 1, 3)), np.array([[1, 1], [2, 2], [1, 1], [2, 2]], dtype=np.int32)]) _test_pad([np.arange(1.0, 7.0, dtype=np.float32).reshape((2, 1, 3)), np.array([[2, 2], [1, 1], [1, 1]], dtype=np.int32)]) _test_p...
].shape, dtype=data[0].dtype, name='in')] out = array_ops.pad(in_data[0], ops.convert_to_tensor(data[1], dtype=data[1].dtype)) compare_tflite_with_tvm([data[0]], ['in:0'], in_data, [out]) def test_forward_pad():
69
69
232
5
64
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_pad
test_forward_pad
789
798
789
789
c4818aeafe25241e3448d441f0b7aa14e1480480
bigcode/the-stack
train
6119e3b9b8be226e7b438160
train
function
def test_forward_batch_to_space_nd(): # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d _test_batch_to_space_nd( input_shape=[4, 1, 1, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]] ) _test_batch_to_space_nd( input_shape=[4, 1, ...
def test_forward_batch_to_space_nd(): # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d
_test_batch_to_space_nd( input_shape=[4, 1, 1, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]] ) _test_batch_to_space_nd( input_shape=[4, 1, 1, 3], block_shape=[2, 2], crops=[[0, 0], [0, 0]] ) _test_batch_to_space_nd( input_shape=[4, 2, 2, 1],...
, block_shape, crops) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_batch_to_space_nd(): # test cases: https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d
64
64
180
36
28
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_batch_to_space_nd
test_forward_batch_to_space_nd
287
305
287
288
ecda74674f233f30b06f844138a37e865d956d27
bigcode/the-stack
train
65bdd66943d1675f66c9d1db
train
function
def test_forward_tile(): _test_forward_tile((2, ), (3, ), "int32") _test_forward_tile((2, 2), (2, 3), "float32")
def test_forward_tile():
_test_forward_tile((2, ), (3, ), "int32") _test_forward_tile((2, 2), (2, 3), "float32")
astype(dtype) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = array_ops.tile(in_data, reps) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_tile():
64
64
43
5
59
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_tile
test_forward_tile
267
269
267
267
73f5e2da13ad2d2ae8e24a8a50ddf1ba203f1b36
bigcode/the-stack
train
05e79b5089a14dba1eebd433
train
function
def with_fused_activation_function(input_tensor, fn_name): if fn_name is None or fn_name == "NONE": return input_tensor if fn_name == "RELU": return nn_ops.relu(input_tensor) if fn_name == "RELU6": return nn_ops.relu6(input_tensor) if fn_name == "RELU_N1_TO_1": return mat...
def with_fused_activation_function(input_tensor, fn_name):
if fn_name is None or fn_name == "NONE": return input_tensor if fn_name == "RELU": return nn_ops.relu(input_tensor) if fn_name == "RELU6": return nn_ops.relu6(input_tensor) if fn_name == "RELU_N1_TO_1": return math_ops.maximum(-1, math_ops.minimum(input_tensor, 1)) if...
_names), out_names=out_names) for i in range(len(tflite_output)): tvm.testing.assert_allclose(tflite_output[i], tvm_output[i], atol=1e-5, rtol=1e-5) def with_fused_activation_function(input_tensor, fn_name):
64
64
130
12
52
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
with_fused_activation_function
with_fused_activation_function
155
166
155
155
6f6d4c5f159172cc6a01174f117d7ac81b32bf48
bigcode/the-stack
train
e7a7feffb24fc5d908ea780e
train
function
def test_all_reduce(): _test_forward_reduce(_test_reduce_min) _test_forward_reduce(_test_reduce_max) _test_forward_reduce(_test_reduce_mean) _test_forward_reduce(_test_reduce_prod) _test_forward_reduce(_test_reduce_sum)
def test_all_reduce():
_test_forward_reduce(_test_reduce_min) _test_forward_reduce(_test_reduce_max) _test_forward_reduce(_test_reduce_mean) _test_forward_reduce(_test_reduce_prod) _test_forward_reduce(_test_reduce_sum)
2], dtype=np.int32)] testop(data0) testop(data0, keep_dims=False) testop(data0, keep_dims=True) testop(data1) testop(data1, keep_dims=False) testop(data1, keep_dims=True) def test_all_reduce():
64
64
55
5
59
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_all_reduce
test_all_reduce
738
743
738
738
0553f64267557c25ed9f7ee53ae3fd5d521adb71
bigcode/the-stack
train
6756d84d191f7417d1af5efc
train
function
def test_forward_tanh(): """ TANH """ _test_tanh(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
def test_forward_tanh():
""" TANH """ _test_tanh(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
TANH """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.sigmoid(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_tanh():
64
64
35
6
58
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_tanh
test_forward_tanh
878
880
878
878
af7d917c99147ceb09c1d00a75d050fe41caaafd
bigcode/the-stack
train
fc98d9550a9a4b0c2b048b64
train
function
def _test_squeeze(data, squeeze_dims=None): """ One iteration of squeeze """ if squeeze_dims is None: squeeze_dims = [] with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) if squeeze_dims: out = array_ops.squeeze(in_data, s...
def _test_squeeze(data, squeeze_dims=None):
""" One iteration of squeeze """ if squeeze_dims is None: squeeze_dims = [] with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) if squeeze_dims: out = array_ops.squeeze(in_data, squeeze_dims) else: out =...
_reduce_min) _test_forward_reduce(_test_reduce_max) _test_forward_reduce(_test_reduce_mean) _test_forward_reduce(_test_reduce_prod) _test_forward_reduce(_test_reduce_sum) ####################################################################### # Squeeze # ------- def _test_squeeze(data, squeeze_dims=No...
63
64
104
11
52
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_squeeze
_test_squeeze
750
764
750
750
68c6a6af4611463bfa51a1709f440bb24946e4ce
bigcode/the-stack
train
6db0fccf7f1d28d371724902
train
function
def test_forward_cast(): """ CAST """ _test_cast(np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.int32) _test_cast(np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.uint8) _test_cast(np.arange(6.0, dtype=np.int32).reshape((1, 6)), cast_dtype=tf.int64)
def test_forward_cast():
""" CAST """ _test_cast(np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.int32) _test_cast(np.arange(6.0, dtype=np.float32).reshape((1, 6)), cast_dtype=tf.uint8) _test_cast(np.arange(6.0, dtype=np.int32).reshape((1, 6)), cast_dtype=tf.int64)
CAST """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.cast(in_data, cast_dtype) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_cast():
64
64
96
5
59
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_cast
test_forward_cast
245
249
245
245
79cf388dc33a584297f5898fca45b4e3fee690e4
bigcode/the-stack
train
dc88957fc0cc66f741c6b801
train
function
def test_forward_space_to_batch_nd(): # test cases: https://www.tensorflow.org/api_docs/python/tf/space_to_batch_nd _test_space_to_batch_nd( input_shape=[1, 2, 2, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]] ) _test_space_to_batch_nd( input_shape=[1, 2, 2, 3], ...
def test_forward_space_to_batch_nd(): # test cases: https://www.tensorflow.org/api_docs/python/tf/space_to_batch_nd
_test_space_to_batch_nd( input_shape=[1, 2, 2, 1], block_shape=[2, 2], paddings=[[0, 0], [0, 0]] ) _test_space_to_batch_nd( input_shape=[1, 2, 2, 3], block_shape=[2, 2], paddings=[[0, 0], [0, 0]] ) _test_space_to_batch_nd( input_shape=[1, 4, ...
array_ops.space_to_batch_nd(in_data, block_shape, paddings) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_space_to_batch_nd(): # test cases: https://www.tensorflow.org/api_docs/python/tf/space_to_batch_nd
67
67
226
30
37
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_space_to_batch_nd
test_forward_space_to_batch_nd
323
347
323
324
31753413327555daf5d2c3500201395330d21d7f
bigcode/the-stack
train
fb396d465cd61ed3ce3f3700
train
function
def test_forward_inception_v3_net(): """Test the Inception V3 TF Lite model.""" # InceptionV3 tflite_model_file = tf_testing.get_workload_official( "https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/upload_20180427/inception_v3_2018_04_27.tgz", "inception_v3.tfli...
def test_forward_inception_v3_net():
"""Test the Inception V3 TF Lite model.""" # InceptionV3 tflite_model_file = tf_testing.get_workload_official( "https://storage.googleapis.com/download.tensorflow.org/models/tflite/model_zoo/upload_20180427/inception_v3_2018_04_27.tgz", "inception_v3.tflite") with open(tflite_model_file,...
, data, 'input') tvm.testing.assert_allclose(np.squeeze(tvm_output[0]), np.squeeze(tflite_output[0]), rtol=1e-5, atol=1e-5) ####################################################################### # Inception # ------------ def test_forward_inception_v3_net():
65
65
218
9
55
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_inception_v3_net
test_forward_inception_v3_net
981
993
981
981
1faf3fb3db4c2f37d9d7c56614c85885f2654c35
bigcode/the-stack
train
08bf64a0aa5e4721160bb9e9
train
function
def test_forward_reshape(): _test_reshape(np.arange(6.0, dtype=np.float32), [2, 3]) _test_reshape(np.arange(6), [-1, 2]) _test_reshape(np.arange(6), [3, -1]) _test_reshape(np.arange(6), [-1])
def test_forward_reshape():
_test_reshape(np.arange(6.0, dtype=np.float32), [2, 3]) _test_reshape(np.arange(6), [-1, 2]) _test_reshape(np.arange(6), [3, -1]) _test_reshape(np.arange(6), [-1])
""" with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = array_ops.reshape(in_data, out_shape) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_reshape():
64
64
74
6
58
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_reshape
test_forward_reshape
471
475
471
471
632d17407d5580eed31e69a3821bee55bc56b3b9
bigcode/the-stack
train
d6af02b76f57415d7ef66495
train
function
def _test_forward_transpose(ishape, axes=()): data = np.random.uniform(size=ishape).astype(np.float32) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) if not axes: out = array_ops.transpose(in_data) else: out = a...
def _test_forward_transpose(ishape, axes=()):
data = np.random.uniform(size=ishape).astype(np.float32) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) if not axes: out = array_ops.transpose(in_data) else: out = array_ops.transpose(in_data, axes) com...
6, 5), -2, 3, 'float32') _test_split((1, 3, 5, 6), -1, 3, 'float32') ####################################################################### # transpose # --------- def _test_forward_transpose(ishape, axes=()):
63
64
102
13
50
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_forward_transpose
_test_forward_transpose
210
221
210
210
b90d26d64984e293d85ab165292443cd9bd87976
bigcode/the-stack
train
d602a5fba1c4bd9fd6391747
train
function
def _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype='int32'): data = np.random.uniform(0, 5, size=input_shape).astype(dtype) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dtype=dtype) out = array_ops.space_to_batch_nd(in_data, block_shape, p...
def _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype='int32'):
data = np.random.uniform(0, 5, size=input_shape).astype(dtype) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dtype=dtype) out = array_ops.space_to_batch_nd(in_data, block_shape, paddings) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out...
2, 1], block_shape=[2, 2], crops=[[0, 0], [0, 0]] ) ###################################################################### # SpaceToBatchND # -------------- def _test_space_to_batch_nd(input_shape, block_shape, paddings, dtype='int32'):
63
64
103
21
42
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_space_to_batch_nd
_test_space_to_batch_nd
312
320
312
312
5c43a2923dbd0fcfb34c7d4a03fb171d803d2fd3
bigcode/the-stack
train
3ce944b3bb0b1951f31674ee
train
function
def convert_to_list(x): if not isinstance(x, list): x = [x] return x
def convert_to_list(x):
if not isinstance(x, list): x = [x] return x
tensorflow import lite as interpreter_wrapper except ImportError: from tensorflow.contrib import lite as interpreter_wrapper import tvm.relay.testing.tf as tf_testing from packaging import version as package_version ####################################################################### # Generic run functions f...
64
64
24
6
58
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
convert_to_list
convert_to_list
47
50
47
47
71f3bcf7bd0ac623417c943eac3ff0a7ba207f7e
bigcode/the-stack
train
261136a07aad69effa95ea2d
train
function
def test_forward_relu(): """ ReLU """ _test_relu(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
def test_forward_relu():
""" ReLU """ _test_relu(np.arange(6.0, dtype=np.float32).reshape((1, 6)))
iteration of ReLU """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = nn_ops.relu(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_relu():
64
64
33
5
59
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_relu
test_forward_relu
893
895
893
893
7647b5f2c9affc51db4ebae52bf926c2e1a8c27c
bigcode/the-stack
train
657e146544ef6ed26bbeec8d
train
function
def test_forward_mobilenet_v1(): """Test the Mobilenet V1 TF Lite model.""" # MobilenetV1 tflite_model_file = tf_testing.get_workload_official( "http://download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz", "mobilenet_v1_1.0_224.tflite") with open(tflite_model_...
def test_forward_mobilenet_v1():
"""Test the Mobilenet V1 TF Lite model.""" # MobilenetV1 tflite_model_file = tf_testing.get_workload_official( "http://download.tensorflow.org/models/mobilenet_v1_2018_08_02/mobilenet_v1_1.0_224.tgz", "mobilenet_v1_1.0_224.tflite") with open(tflite_model_file, "rb") as f: tflite_...
ully_connected([5, 1, 1, 150], [150, 100]) _test_fully_connected([5, 1, 1, 150], [150, 100], [100]) ####################################################################### # Mobilenet # --------- def test_forward_mobilenet_v1():
66
66
222
9
57
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_mobilenet_v1
test_forward_mobilenet_v1
949
961
949
949
6d018c3e60db86a300e2c89833c274a21b776f71
bigcode/the-stack
train
ca435960a4941b5da7c083ff
train
function
def _test_pooling_iteration(input_shape, **kwargs): """ One iteration of pool operation with given shapes and attributes """ x = -np.arange( np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1 with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dty...
def _test_pooling_iteration(input_shape, **kwargs):
""" One iteration of pool operation with given shapes and attributes """ x = -np.arange( np.prod(input_shape), dtype=np.float32).reshape(input_shape) - 1 with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dtype='float32') out = nn_ops.pool(in_data, **k...
_nd( input_shape=[2, 2, 4, 1], block_shape=[2, 2], paddings=[[0, 0], [2, 0]] ) ####################################################################### # Pooling # ------- def _test_pooling_iteration(input_shape, **kwargs):
64
64
108
12
52
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_pooling_iteration
_test_pooling_iteration
352
362
352
352
8966a836b45984e2d01d135a46ffea17fed2a43a
bigcode/the-stack
train
34f7f0d48e020f6c5cc81a2e
train
function
def test_forward_squeeze(): """ Squeeze """ _test_squeeze(np.arange(6).reshape((1, 2, 1, 3)), [0, 2]) _test_squeeze(np.arange(6).reshape((2, 1, 3, 1)), [1, 3])
def test_forward_squeeze():
""" Squeeze """ _test_squeeze(np.arange(6).reshape((1, 2, 1, 3)), [0, 2]) _test_squeeze(np.arange(6).reshape((2, 1, 3, 1)), [1, 3])
=data.shape, dtype=data.dtype) if squeeze_dims: out = array_ops.squeeze(in_data, squeeze_dims) else: out = array_ops.squeeze(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_squeeze():
64
64
69
6
58
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_squeeze
test_forward_squeeze
767
770
767
767
12670b5d66d506969e53f2f1f4f1985f6a16ddf3
bigcode/the-stack
train
8f54d3adb24e665890ac356e
train
function
def test_forward_transpose(): _test_forward_transpose((2, 2)) _test_forward_transpose((2, 3, 4)) _test_forward_transpose((7, 8, 8, 10)) _test_forward_transpose((2, 3, 4), (1, 2, 0)) _test_forward_transpose((2, 3, 4), (0, 1, 2)) _test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2)) _test_forwar...
def test_forward_transpose():
_test_forward_transpose((2, 2)) _test_forward_transpose((2, 3, 4)) _test_forward_transpose((7, 8, 8, 10)) _test_forward_transpose((2, 3, 4), (1, 2, 0)) _test_forward_transpose((2, 3, 4), (0, 1, 2)) _test_forward_transpose((2, 3, 4, 5), (3, 0, 1, 2)) _test_forward_transpose((2, 3, 4, 5), ())
(shape=data.shape, dtype=data.dtype) if not axes: out = array_ops.transpose(in_data) else: out = array_ops.transpose(in_data, axes) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out]) def test_forward_transpose():
64
64
148
6
58
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_transpose
test_forward_transpose
224
231
224
224
1aa79445bf79a52620e218b1949549e582ef5340
bigcode/the-stack
train
98504645930e72661a5ec0e7
train
function
def _test_batch_to_space_nd(input_shape, block_shape, crops, dtype='int32'): data = np.random.uniform(0, 5, size=input_shape).astype(dtype) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dtype=dtype) out = array_ops.batch_to_space_nd(in_data, block_shape, crop...
def _test_batch_to_space_nd(input_shape, block_shape, crops, dtype='int32'):
data = np.random.uniform(0, 5, size=input_shape).astype(dtype) with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=input_shape, dtype=dtype) out = array_ops.batch_to_space_nd(in_data, block_shape, crops) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
, ), (3, ), "int32") _test_forward_tile((2, 2), (2, 3), "float32") ###################################################################### # BatchToSpaceND # -------------- def _test_batch_to_space_nd(input_shape, block_shape, crops, dtype='int32'):
63
64
101
20
43
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_batch_to_space_nd
_test_batch_to_space_nd
276
284
276
276
c3d8e0493215a0f4119dbbaa7cb6b4e3521ac308
bigcode/the-stack
train
6dcb7c261fc93b65523337ba
train
function
def test_forward_fully_connected(): """ Fully Connected """ _test_fully_connected([1, 1, 1, 150], [150, 100]) _test_fully_connected([1, 1, 1, 150], [150, 100], [100]) _test_fully_connected([5, 1, 1, 150], [150, 100]) _test_fully_connected([5, 1, 1, 150], [150, 100], [100])
def test_forward_fully_connected():
""" Fully Connected """ _test_fully_connected([1, 1, 1, 150], [150, 100]) _test_fully_connected([1, 1, 1, 150], [150, 100], [100]) _test_fully_connected([5, 1, 1, 150], [150, 100]) _test_fully_connected([5, 1, 1, 150], [150, 100], [100])
='float32') out = nn_ops.bias_add(out, in_bias) data_array = np.reshape(data_array, tensor_in_sizes).astype('float32') compare_tflite_with_tvm(data_array, 'Placeholder:0', [in_data], [out]) def test_forward_fully_connected():
64
64
114
7
57
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_fully_connected
test_forward_fully_connected
937
942
937
937
90f877a0e431d98613f8503e2c7c82f1502881a2
bigcode/the-stack
train
42b5d65a5057b238e476b623
train
function
def _test_greater(data): """ One iteration of greater """ return _test_elemwise(math_ops.greater, data)
def _test_greater(data):
""" One iteration of greater """ return _test_elemwise(math_ops.greater, data)
""" return _test_elemwise(math_ops.maximum, data) ####################################################################### # Minimum # ------- def _test_minimum(data): """ One iteration of minimum """ return _test_elemwise(math_ops.minimum, data) ############################################################...
63
64
27
7
56
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_greater
_test_greater
623
625
623
623
8963a058f096845050185cdecff05b5c231b1b6c
bigcode/the-stack
train
493317b8fbb7b0dcb6c82893
train
function
def test_forward_ssd_mobilenet_v1(): """Test the SSD Mobilenet V1 TF Lite model.""" # SSD MobilenetV1 tflite_model_file = tf_testing.get_workload_official( "https://raw.githubusercontent.com/dmlc/web-data/master/tensorflow/models/object_detection/ssd_mobilenet_v1_coco_2018_01_28_nopp.tgz", "...
def test_forward_ssd_mobilenet_v1():
"""Test the SSD Mobilenet V1 TF Lite model.""" # SSD MobilenetV1 tflite_model_file = tf_testing.get_workload_official( "https://raw.githubusercontent.com/dmlc/web-data/master/tensorflow/models/object_detection/ssd_mobilenet_v1_coco_2018_01_28_nopp.tgz", "ssd_mobilenet_v1_coco_2018_01_28_nopp...
input') tvm_predictions = np.squeeze(tvm_output) tvm_sorted_labels = tvm_predictions.argsort()[-3:][::-1] tvm.testing.assert_allclose(tvm_sorted_labels, tflite_sorted_labels) ####################################################################### # SSD Mobilenet # ------------- def test_forward_ssd_mobilen...
72
72
241
11
61
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
test_forward_ssd_mobilenet_v1
test_forward_ssd_mobilenet_v1
1,073
1,085
1,073
1,073
02161cfee8e1df56428a9b9471bc898b6dba3a8d
bigcode/the-stack
train
d1a9fefc4b40cb024ea4a49a
train
function
def _test_maximum(data): """ One iteration of maximum """ return _test_elemwise(math_ops.maximum, data)
def _test_maximum(data):
""" One iteration of maximum """ return _test_elemwise(math_ops.maximum, data)
_test_elemwise(math_ops.divide, data, fused_activation_function) ####################################################################### # Power # ----- def _test_pow(data): """ One iteration of power """ return _test_elemwise(math_ops.pow, data) ###############################################################...
63
64
26
7
56
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_maximum
_test_maximum
609
611
609
609
9937575d8a2dec41542c46e3a7a9c1ab3c18e0e6
bigcode/the-stack
train
fed90ab7ac11fea3ddaa729b
train
function
def _test_tanh(data): """ One iteration of TANH """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.sigmoid(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
def _test_tanh(data):
""" One iteration of TANH """ with tf.Graph().as_default(): in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype) out = math_ops.sigmoid(in_data) compare_tflite_with_tvm(data, 'Placeholder:0', [in_data], [out])
'Placeholder:0', [in_data], [out]) def test_forward_softmax(): """ Softmax """ _test_softmax(np.arange(6.0, dtype=np.float32).reshape((1, 6))) ####################################################################### # Tanh # -------- def _test_tanh(data):
64
64
70
7
56
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_tanh
_test_tanh
871
876
871
871
4b0f213cda884e2288f5350ccf49aedb1a45b08c
bigcode/the-stack
train
4b82bc8667690ddd2a120ecd
train
function
def _test_concatenation(data, axis): """ One iteration of concatenation """ assert len(data) >= 1 with tf.Graph().as_default(): in_data = [ array_ops.placeholder(shape=tensor.shape, dtype=tensor.dtype, name="in_{}".format(idx)) for idx, tensor in enumerate(data)] ou...
def _test_concatenation(data, axis):
""" One iteration of concatenation """ assert len(data) >= 1 with tf.Graph().as_default(): in_data = [ array_ops.placeholder(shape=tensor.shape, dtype=tensor.dtype, name="in_{}".format(idx)) for idx, tensor in enumerate(data)] out = array_ops.concat(in_data, axis=ax...
uiltinOperator import BuiltinOperator if 'RESIZE_NEAREST_NEIGHBOR' in dir(BuiltinOperator()): _test_resize(tf.image.resize_nearest_neighbor, data, align_corners=False) ####################################################################### # Concatenation # ------------- def _test_concatenation(data, axis...
64
64
124
11
53
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_concatenation
_test_concatenation
513
525
513
513
e52294cde1076e4485486ad0252d77d3745bb9b4
bigcode/the-stack
train
53facc0a242e43bfcc649bb9
train
function
def _test_pack(data, axis): """ One iteration of pack """ assert len(data) >= 1 with tf.Graph().as_default(): in_data = [ array_ops.placeholder(shape=tensor.shape, dtype=tensor.dtype, name="in_{}".format(idx)) for idx, tensor in enumerate(data)] out = array_ops.pack...
def _test_pack(data, axis):
""" One iteration of pack """ assert len(data) >= 1 with tf.Graph().as_default(): in_data = [ array_ops.placeholder(shape=tensor.shape, dtype=tensor.dtype, name="in_{}".format(idx)) for idx, tensor in enumerate(data)] out = array_ops.pack(in_data, axis=axis) ...
_pad([np.arange(1.0, 4.0, dtype=np.float32).reshape((1, 3)), np.array([[1, 1], [2, 2]], dtype=np.int32)]) ####################################################################### # Pack # ------------- def _test_pack(data, axis):
64
64
120
8
56
ElaineBao/tvm
tests/python/frontend/tflite/test_forward.py
Python
_test_pack
_test_pack
805
817
805
805
e3a695af51cdba4f477b3b4c8871bb3d0df272fe
bigcode/the-stack
train