blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
838027b05c4975fc5f55b86184077144347a1bad
4f21e3301c1a8699745528177b3210b4f1a1f1d5
/week10/project2/library/settings.py
4dbdb1bf1faf2c3a9ac45fabe288d8e6aa05c0ca
[]
no_license
ndina/webdev2019
7fd0250b662b378d55e24e931f82d0b2538d63a5
eae4808e2f0bfcdd5a366fd4692c041b96faaa0b
refs/heads/master
2020-05-03T22:05:12.392913
2019-05-04T02:46:56
2019-05-04T02:46:56
167,550,783
0
1
null
null
null
null
UTF-8
Python
false
false
2,688
py
""" Django settings for library project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u2iir6bmw(y%pu*23y%sm1u#8y#o7_qchko#=r*_rtqy_-ge+e' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'library.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'library.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static')
cdc14ab92541df567c2da2c71eab1580caecb1c9
73dadaa1c10ba149cf42fe3600edee9565b2e418
/pythonBasicsHandsOn.py
92dfdf4b8dab6dd981c4aea7320a988e9e35c5e3
[]
no_license
Sankarb475/Python_Learning
078826e5087bf1c6d2e18e9176af1bad3e345eb1
1b0d929a66f99b86bfd41590c1ce8781385223a0
refs/heads/master
2022-06-14T07:45:10.053327
2022-06-09T05:11:44
2022-06-09T05:11:44
167,215,150
0
1
null
null
null
null
UTF-8
Python
false
false
10,865
py
# Shallow Copy and Deep Copy # When you use "=" to create a copy of an object, It only creates a new variable that shares the reference of the original object. a = [1,2,3,4] b = a a.append(5) a[2] = 100 print(a,b) => [1, 2, 100, 4, 5] [1, 2, 100, 4, 5] -- Shallow copy creates a copy of t import copy a = [1,2,3,4] b = copy.copy(a) b.append(5) print(a,b) -- [1, 2, 3, 4] [1, 2, 3, 4, 5] import copy a = [1,2,3,4] b = copy.copy(a) b[0] = 100 print(a,b) -- [1, 2, 3, 4] [100, 2, 3, 4] import copy a = [[1],[2],[3],[4]] b = copy.copy(a) a.append(5) a[0][0] = 100 print(a,b) -- [[100], [2], [3], [4], 5] [[100], [2], [3], [4]] -- Deep Copy it creates a completely new object with the elements of the existing object and they have no relation at all. import copy old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] new_list = copy.deepcopy(old_list) old_list[1][0] = 'BB' print("Old list:", old_list) print("New list:", new_list) Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]] New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]] ================================================================================ # Python args and kargs The special syntax **kwargs in function definitions in python is used to pass a keyworded, variable-length argument list. def myFun(**kwargs): for key, value in kwargs.items(): print ("%s == %s" %(key, value)) # Driver code myFun(first ='Geeks', mid ='for', last='Geeks') -- The special syntax *args in function definitions in python is used to pass a variable number of arguments to a function You cant pass a key-worded parameter. def myFun(*argv): for arg in argv: print (arg) myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks') # Python Decorators -- A design pattern to in python - takes in a function, adds some functionality and returns it. -- This is also called metaprogramming because a part of the program tries to modify another part of the program at compile time def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary") >>> ordinary() I am ordinary >>> # let's decorate this ordinary function >>> pretty = make_pretty(ordinary) >>> pretty() I got decorated I am ordinary #Python Serialization =============================================== Pickling is the process whereby a Python object hierarchy is converted into a byte stream (usually not human readable) to be written to a file, this is also known as Serialization. Unpickling is the reverse operation, whereby a byte stream is converted back into a working Python object hierarchy. import pickle # serializes pickle.dump() #deserializes pickle.load() '''to run python in command prompt, use "python", (windows :considering you have set up environment variable) The interactive prompt runs code and echoes results as you go, but it doesn’t save your code in a file ''' # enumerate() in python ==> it will give you the index numbers while iterating >>> for n,i in enumerate(arr): ... print(n,i) ... 0 6 1 4 2 2 3 1 4 3 5 5 6 7 >>> arr [6, 4, 2, 1, 3, 5, 7] #to get current working directory >>> import os >>> os.getcwd() '/Users/sankar.biswas' #changing current direcctory >>> os.chdir('/Users/sankar.biswas/Desktop/Python/coding') >>> os.getcwd() '/Users/sankar.biswas/Desktop/Python/coding' # to run a python script from command prompt python file1.py #saving the output in a file python script1.py > saveit.txt # "dir" - you can use it to fetch a list of all the names available inside a module >>> import sys >>> dir(sys) ['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework', '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_coroutine_wrapper', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions'] # the " exec(open('module.py').read())" built-in function call is another way to launch files from the interactive prompt without having to import and later reload #you can also find out the functions you can apply on a variable using "dir" >>> a = 234 >>> dir(a) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__' , '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] # this will help you get a knowledge on the functionality of the function, dial 'q' to escape >>> help(a.__abs__) # Pattern Matching >>> match = re.match('Hello[ \t]*(.*)world', 'Hello Python world') >>> match <re.Match object; span=(0, 18), match='Hello Python world'> >>> match.group(1) 'Python ' >>> match = re.match('[/:](.*)[/:](.*)[/:](.*)', '/usr/home:lumberjack') >>> match.groups() ('usr', 'home', 'lumberjack') >>> re.split('[/:]', '/usr/home/lumberjack') ['', 'usr', 'home', 'lumberjack'] #List Operations >>> L = [123, 'spam', 1.23] >>> len(L) 3 >>> L*2 [123, 'spam', 1.23, 123, 'spam', 1.23] >>> L[:] [123, 'spam', 1.23] >>> L[2:] [1.23] >>> L[:-1] [123, 'spam'] >>> L.append(23) [123, 'spam', 1.23, 23] >>> L.pop(2) 1.23 >>> L [123, 'spam', 23] >>> list = [1,23,4,56,33,656,564] >>> list.sort() >>> list [1, 4, 23, 33, 56, 564, 656] #adding multiple elements to an existing list >>> L [123, 'abc', 1.23, {}] >>> L.extend([5,6,7]) >>> L [123, 'abc', 1.23, {}, 5, 6, 7] #deleting all the elements >>> L.clear() >>> L [] #deleting a single element by index >>> L = [123, 'abc', 1.23, {}] >>> del L[0] >>> L ['abc', 1.23, {}] #selecting a partcular column from a 2D list >>> list2D = [[1,2,3],[4,5,6],[7,8,9]] >>> list2D[1][2] 6 >>> col2 = [row[1] for row in list2D] #Give me row[1] (2nd element) for each row in matrix M, in a new list. >>> col2 [2, 5, 8] >>> M ['bb', 'aa', 'cc'] >>> M.sort() >>> M ['aa', 'bb', 'cc'] >>> [row[1] for row in M if row[1] % 2 == 0] #Filter out odd items [2, 8] #diagonal matrix >>> diag = [M[i][i] for i in [0, 1, 2]] >>> diag [1, 5, 9] # Repeat characters in a string >>> doubles = [c * 2 for c in 'spam'] >>> doubles ['ss', 'pp', 'aa', 'mm'] >>> list(range(4)) [0, 1, 2, 3] >>> a = list(range(-6,7,2)) >>> a [-6, -4, -2, 0, 2, 4, 6] >>> [[x ** 2, x **3] for x in range(4)] [[0, 0], [1, 1], [4, 8], [9, 27]] >>> [[x, x / 2, x * 2] for x in range(-6, 7, 2) if x > 0] [[2, 1.0, 4], [4, 2.0, 8], [6, 3.0, 12]] >>> [[x, int(x / 2), x * 2] for x in range(-6, 7, 2) if x > 0] [[2, 1, 4], [4, 2, 8], [6, 3, 12]] >>> G = (sum(row) for row in M) >>> G <generator object <genexpr> at 0x105b29408> >>> next(G) 6 >>> next(G) 15 >>> next(G) 24 '''Dictionaries :: Dictionaries, the only mapping type (not a sequence) in Python’s core objects set, are also mutable ''' >>> D = {} >>> type(D) <class 'dict'> >>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'} >>> D {'food': 'Spam', 'quantity': 4, 'color': 'pink'} #using dict to define a dictionary >>> bob1 = dict(name='Bob', job='dev', age=40) >>> bob1 {'age': 40, 'name': 'Bob', 'job': 'dev'} #zipping way to define dictionary >>> bob2 = dict(zip(['name', 'job', 'age'], ['Bob', 'dev', 40])) >>> bob2 {'name': 'Bob', 'job': 'dev', 'age': 40} #Complex nesting of different types in python - one of the advantage of using python, complex nesting is easy to implement >>> rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'jobs': ['dev', 'mgr'], 'age': 40.5} >>> rec['jobs'][1] 'mgr' >>> rec['name']['last'] 'Smith' >>> rec['jobs'].append('support') >>> rec {'name': {'first': 'Bob', 'last': 'Smith'}, 'jobs': ['dev', 'mgr', 'support'], 'age': 40.5} #In Python, when we lose the last reference to the object—by assigning its variable to something else >>> rec = 0 #Python has a feature known as garbage collection that cleans up unused memory as your program runs and frees you from having to manage such details in your code. >>> D = {'a': 1, 'b': 2, 'c': 3} #so now, what ".get" does is it will select the data with the key 'x' in dictionary D, if it doesnyt find it, it will return 0 >>> value = D.get('x', 0) >>> value 0 #Sorting Keys: for Loops >>> sorted(D) ['a', 'b', 'c'] >>> Ks = list(D.keys()) >>> Ks ['a', 'c', 'b'] >>> Ks.sort() >>> Ks ['a', 'b', 'c'] #Tuples :: tuples are sequences, like lists, but they are immutable. Functionally, they’re used to represent fixed collections of items. >>> T = (1, 2, 3, 4, 5) >>> len(T) 5 >>> T + (5,6) (1, 2, 3, 4, 5, 5, 6) >>> T (1, 2, 3, 4, 5) >>> T[0] 1 >>> T.index(4) 3 >>> T.count(4) 1 #tuples provide a sort of integrity constraint #String slicing, so the last number is the gap of skipping, that is 1,3,5,... will be skipped >>> S = "I a m s a d" >>> S[::2] 'Iamsad' #the third index if given negative will reverse the selection >>> S[::-2] 'dasmaI' >>> S 'I evol being alone' >>> S[5:1:-1] 'love' >>> >>> S[::-1] 'enola gnieb love I' #converting whatever we have into string >>> repr(42) '42' #converting into ASCII >>> ord('A') 65 #converting integer to binary >>> bin(13) '0b1101' #converting binary to integer >>> int('1101', 2) 13
aa08416cec64433ef17052cae24d44ab961b544f
2d9a17e2b896d2f6a90913a4ba02d41f0ede5dd0
/_gsinfo/qiyecxb-ct/qycxb_spider.py
c629ad7e0a0c3154e2b6a4ad7ae34b42379b6c08
[]
no_license
wolfwhoami/xxxxx
1cf2ed2c8ed78048d87cccf2953ca86c0871a783
670787ec71127bc05c1645cc3d8ef7c3a91fe84b
refs/heads/master
2020-03-30T00:44:55.864817
2016-12-16T01:45:03
2016-12-16T01:45:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
17,218
py
#!/usr/bin/env python # -*- coding:utf8 -*- import os import sys sys.path.append(sys.path[0]+"/..") print sys.path import time from spider.spider import Spider, AccountErrors import re from spider.savebin import BinSaver import random import threading import traceback import spider.util from spider.savebin import FileSaver from qycxb_AES import CCIQ_AES filter_name = set() bloom = set() class QycxbSpider(Spider): """ 根据企业基本信息查询详情 121.40.186.237:18889:ipin:helloipin """ def __init__(self): self._can_use_proxy_num = 0 self.is_debug = False if self.is_debug: Spider.__init__(self, 1) #self.proxy_error_cnt = 0 else: self.proxies_dict = [] self.read_proxy("../../_ct_proxy/proxy_all_filter.txt") Spider.__init__(self, len(self.proxies_dict)) self._aes_ = CCIQ_AES() #成功的 self.query_success = FileSaver("beijing_query_detail1.txt") #失败的 self.query_failure = FileSaver("beijing_query_detail_failure1.txt") #已经爬取过的 self.already_cname_list = FileSaver("beijing_already_detail1.txt") #初始化已经爬过的公司 self.init_cname() self.extJsons = ["Hoi6oX70l9whauZmjq8jVAmoe3UspXXhX9mPG+KAeqs1rKZVr/uapICH92P/Crryt63u28aP4QP665AzcT/jN5Go1o3bvwMvVIkuN9e60k6WI2pVFBrwZMvxwW6BnQukSzDSlyPvEhgpR5DIHQEV6C51hMgp4Zc3OkTSsyezAm4=", "ctlCXDvoyaH2pCIArrgvXp7zrZTzpz2Q5rukh+aWvupEFABw6P2AvbmaN+HJ7IZgDJ/kgBkJt/rLppSGitYCPKGR2IGv6OXZsrJGgbRB3G3Ac4K8xpX3aMB5s8Ci2a/YpTpioZxAvptqJsQUCoNn0tLCOVM4XxMJQWbrErkOcl4=", "ctlCXDvoyaH2pCIArrgvXp7zrZTzpz2Q5rukh+aWvupEFABw6P2AvbmaN+HJ7IZgDJ/kgBkJt/rLppSGitYCPKGR2IGv6OXZsrJGgbRB3G1U2wdOlL49/aDwt3NZNp4TGa5iBFpYLm69F/6PPFoXIR/Aw5p48//8OgZFpddDUwQ="] self.user_agents = ["=CCIQ/2.0.1 (iPhone; iOS 9.1; Scale/2.00)", "=CCIQ/2.0.1 (iPhone; iOS 8.1.3; Scale/2.00)", "=CCIQ/2.0.1 (iPhone; iOS 8.4; Scale/2.00)"] self.is_first = True self.init_time = 0 def req_all(self, url, encryptedJson, retry=0): number = random.randrange(0, 3, 1) self.select_user_agent(self.user_agents[number]) param = spider.util.utf8str({"encryptedJson":self._aes_.encrypt(spider.util.utf8str(encryptedJson)), "extJson":self.extJsons[number]}) param = param.replace('/', "\/") if self.is_first: self.init_time = time.time() print '初始化时间',self.init_time self.is_first = False if self.is_debug: res = self.request_url(url, headers={"Content-Type": "application/json"}, data=param, proxies={'http': 'http://ipin:[email protected]:3428', 'https': 'https://ipin:[email protected]:3428'}) #res = self.request_url(url, headers={"Content-Type": "application/json"}, data=param, proxies={'http': 'http://137.135.166.225:8120', 'https': 'https://137.135.166.225:8120'}) else: res = self.request_url(url, headers={"Content-Type": "application/json"}, data=param, proxies=self.proxies_dict[self.get_tid()]) if res is None: if retry < 3: time.sleep(3) return self.req_all(url, encryptedJson, retry=(retry+1)) else: return None if res.code == 200: time.sleep(random.randrange(30, 50, 1)) else: time.sleep(5) return res def init_cname(self): with open("beijing_already_detail1.txt", "r") as f: for line in f: filter_name.add(line.strip()) def wait_q_breakable(self): lt = 0 while True: if not self.job_queue.empty() or not self.job_queue2.empty() or not self.job_queue3.empty(): time.sleep(5) if time.time() < lt + 1 and self._running_count == 0: return True time.sleep(2) lt = time.time() if self._worker_count == 0: return False def dispatch(self): with open("all_company_list.txt", "r") as f: cnt = 0 for line in f: line = line.strip() cnt += 1 if line in filter_name: #print cnt, "already spider!!!" continue job = {"line": line, "cnt": cnt, "retry": 1} self.add_job(job, True) self.wait_q_breakable() self.add_job(None, True) def record_spider(self, line, cname): """ 已经爬过的,无论成功失败都算爬过. """ filter_name.add(line) self.already_cname_list.append(line) bloom.add(cname) def run_job(self, jobid): line = jobid.get("line") cnt = jobid.get("cnt") retry = jobid.get("retry") self.get_detail(line, cnt, retry) #time.sleep(random.randrange(5, 11, 1)) def get_detail(self, line, cnt, retry): tid = self.get_tid() param = None try: param = eval(line) except Exception as err: print 'tid=%d --- cnt=%d --- data is not json, return'%(tid, cnt) self.record_spider(line, 'UNKNOW') return cname = param['oc_name'] if cname in bloom: cname = param['query_name'] if cname in bloom: print 'query_name:%s aleready crawler...' % cname return ccode = param['oc_code'] carea = param['oc_area'] url = "http://appsvc.qiye.qianzhan.com/OrgCompany.svc/orgcompany/combine/detail" encryptedJson = { "bl_oc_code" : ccode,#code, #"71526726X" "v1" : "QZOrgV005", "isDirect" : "0", "bl_oc_name" : cname,#cname, #"腾讯科技" "bl_oc_area" : carea #area #"4403" } res = self.req_all(url, encryptedJson) res_code = 0 if res is None: if self.get_fail_cnt(1, 'failcount-none') < 10: self.re_add_job({'line': line,'cnt': cnt, 'retry': retry}) print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d " % (tid, cnt, cname, retry, res_code) return else: self.re_add_job({'line': line, 'cnt': cnt, 'retry': (retry+1)}) self._can_use_proxy_num -= 1 raise AccountErrors.NoAccountError("Maybe the proxy invalid,failcount-none = [ %d ]" % self.get_fail_cnt(0, 'failcount-none')) else: setattr(self._curltls, 'failcount-none', 0) res_code = res.code if (res_code >= 400 and res_code < 500) or res_code == 202 : self.re_add_job({'line': line,'cnt': cnt, 'retry': (retry+1)}) print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d " % (tid, cnt, cname, retry, res_code) if self.get_fail_cnt(1, 'failcount-400') > 5: self._can_use_proxy_num -= 1 raise AccountErrors.NoAccountError("Maybe the proxy invalid,failcount-400 = [ %d ]" % self.get_fail_cnt(0, 'failcount-400')) return else: setattr(self._curltls, 'failcount-400', 0) if res_code >= 500: self.re_add_job({'line': line, 'cnt': cnt, 'retry': (retry+1)}) print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d " % (tid, cnt, cname, retry, res_code) time.sleep(retry*2) return elif res_code == 200: try: c = eval(res.text)['c'] except Exception as err: print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d res.text exception " % (tid, cnt, cname, retry, res_code)#, "\n", res.text #param["error_type"] = "res_text_error" #self.query_failure.append(spider.util.utf8str(param)) #self.record_spider(line, cname) self.re_add_job({'line': line, 'cnt': cnt, 'retry': retry}) return if len(c) == 0: print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d --- exception 'C' IS NULL" % (tid, cnt, cname, retry, res_code) param["error_type"] = "c=0" self.query_failure.append(spider.util.utf8str(param)) self.record_spider(line, cname) return result = CCIQ_AES("BF1856A312580D41256311147089E1CC").decrypt(c) try: detail = eval(result) except Exception as err: print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d --- exception result:%s" % (tid, cnt, cname, retry, res_code, result) param["error_type"] = "result_error" self.query_failure.append(spider.util.utf8str(param)) self.record_spider(line, cname) return #股东信息 listGD = self.get_gd(carea, ccode, cname) if listGD is not None: #print "tid=", tid, " listGD=", spider.util.utf8str(listGD) detail['listGD'] = listGD['listGD'] #投资信息 list_inversted = self.get_inversted(cname) if list_inversted is not None: #print "tid=", tid, " list_inversted=", spider.util.utf8str(list_inversted) detail['inversted'] = list_inversted['inversted'] #获取分支机构信息 branch = [] list_branch = self.get_branch(cname, list_branch=branch) if list_branch is not None: #print "tid=", tid, " list_branch=", spider.util.utf8str(list_branch) detail['Branch'] = list_branch #['Branch'] self.query_success.append(spider.util.utf8str(detail)) self.record_spider(line, cname) print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d @@@ success:\n %s" % (tid, cnt, cname, retry, res_code, spider.util.utf8str(detail)) else: param["error_type"] = "unknown_error:%d" % res_code self.query_failure.append(spider.util.utf8str(param)) self.record_spider(line, cname) print "tid=%d --- cnt=%d --- cname=%s --- retry=%d --- res.code=%d --- exception UNKNOW ERROR" % (tid, cnt, cname, retry, res_code) return def get_gd(self, area, code, cname, retry=0): """ 获取股东信息 """ url = "http://appsvc.qiye.qianzhan.com/OrgCompany.svc/orgcompany/gd/detail" encryptedJson = { "bl_oc_area" : area, "v1" : "QZOrgV005", "bl_oc_code" : code } res = self.req_all(url, encryptedJson) if res is None: return None if res.code == 200: try: c = eval(res.text)['c'] if len(c) == 0: print "get_gd --- cname=%s --- retry=%d --- reason:len(c)=0" % (cname, retry) return None result = CCIQ_AES("BF1856A312580D41256311147089E1CC").decrypt(c) return eval(result) except Exception as err: print "get_gd --- cname=%s --- retry=%d --- reason:%s" % (cname, retry, err) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_gd(area, code, cname, retry=retry) else: return None else: print "get_gd --- cname=%s --- retry=%d --- res.code=%d" % (cname, retry, res.code) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_gd(area, code, cname, retry=retry) else: return None def get_inversted(self, cname, retry=0): """ 查询投资信息 """ url = "http://appsvc.qiye.qianzhan.com/OrgCompany.svc/orgcompany/map/invesment" encryptedJson = { "input" : cname, "v1" : "QZOrgV005" } res = self.req_all(url, encryptedJson) if res is None: return None if res.code == 200: try: c = eval(res.text)['c'] if len(c) == 0: print "get_inversted --- cname=%s --- retry=%d --- reason:len(c)=0" % (cname, retry) return None result = CCIQ_AES("BF1856A312580D41256311147089E1CC").decrypt(c) return eval(result) except Exception as err: print "get_inversted --- cname=%s --- retry=%d --- reason:%s" % (cname, retry, err) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_inversted(cname, retry=retry) else: return None else: print "get_inversted --- cname=%s --- retry=%d --- res.code=%d" % (cname, retry, res.code) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_inversted(cname, retry=retry) else: return None def get_branch(self,cname, now_page=1, list_branch=[], retry=0): """ 查询分支机构 """ url = "http://appsvc.qiye.qianzhan.com/OrgCompany.svc/orgcompany/branch/select/page" encryptedJson = { "companyName" : cname, "v1" : "QZOrgV005", "page" : now_page, "pagesize" : "10" } res = self.req_all(url, encryptedJson) if res is None: return None if res.code == 200: try: c = eval(res.text)['c'] if len(c) == 0: print "get_branch --- cname=%s --- retry=%d --- reason:len(c)=0" % (cname, retry) return None result = CCIQ_AES("BF1856A312580D41256311147089E1CC").decrypt(c) temp = eval(result) if temp is not None: for t in temp['Branch']: list_branch.append(t) if len(temp['Branch']) == 10: if now_page > 3: return list_branch now_page += 1 print cname, "翻页 -----------------------------------> now_page", now_page return self.get_branch(cname, now_page=now_page, list_branch=list_branch, retry=retry) else: return list_branch else: print "get_branch --- cname=%s --- retry=%d --- now_page=%d --- res.code=%d --- Branch is NULL" % (cname, retry, now_page) return None except Exception as err: print "get_branch --- cname=%s --- retry=%d --- reason:%s" % (cname, retry, err) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_branch(cname, now_page=now_page, list_branch=list_branch, retry=retry) else: return None else: print "get_branch --- cname=%s --- retry=%d --- res.code=%d" % (cname, retry, res.code) if retry < 5: retry += 1 time.sleep(retry*1.5) return self.get_branch(cname, now_page=now_page, list_branch=list_branch, retry=retry) else: return None def get_fail_cnt(self, addv , type): fc = getattr(self._curltls, type, 0) if (addv): fc += addv setattr(self._curltls, type, fc) return fc def event_handler(self, evt, msg, **kwargs): if evt == 'DONE': msg += '企业查询宝APP公司详情detail查询已经停止...' spider.util.sendmail('[email protected]', '%s DONE' % sys.argv[0], msg) def read_proxy(self,fn): with open(fn, 'r') as f: for line in f: line = line.strip() self._match_proxy(line) print " loaded [ %d ] proxis " % len(self.proxies_dict) def _match_proxy(self,line): m = re.match('([0-9.]+):(\d+):([a-z0-9]+):([a-z0-9._-]+)$', line, re.I) m1 = re.match('([0-9.]+):(\d+):([a-z0-9]+)$', line, re.I) if m: prstr = '%s:%s@%s:%s' % (m.group(3), m.group(4), m.group(1), m.group(2)) proxies = {'http': 'http://' + prstr, 'https': 'https://' + prstr} elif m1: prstr = '%s:%s' % (m1.group(1), m1.group(2)) proxies = {'http': 'http://' + prstr, 'https': 'https://' + prstr} else: proxies = {'http': 'http://' + line, 'https': 'https://' + line} self.proxies_dict.append(proxies) if __name__ == "__main__": s = QycxbSpider() s.run() #s.get_branch("江苏武进建工集团有限公司")
e3d781a3f7d2d498cb5c6001e32a838461a0daa6
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_054/ch2_2020_09_16_11_34_55_516156.py
cb769d528b4f741eaac3317840c0153eb23c362a
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
143
py
# Está função é para calcular a velocidade média def velocidade_media (d,t): velocidade_media = d / t return velocidade_média
c0e29612bc1ab99f21ed31d148930eda30c512c3
2a67dc681af4c4b9ef7a8e18c2ff75377dc5b44f
/aws.ses.EventDestination.sns-destination-python/__main__.py
d32f60d788281d4b38651670141a088b90714d15
[]
no_license
ehubbard/templates-aws
e323b693a18234defe6bd56ffcc64095dc58e3a1
2ae2e7a5d05490078017fed6d132dcdde1f21c63
refs/heads/master
2022-11-17T13:53:14.531872
2020-07-10T21:56:27
2020-07-10T21:56:27
null
0
0
null
null
null
null
UTF-8
Python
false
false
315
py
import pulumi import pulumi_aws as aws sns = aws.ses.EventDestination("sns", configuration_set_name=aws_ses_configuration_set["example"]["name"], enabled=True, matching_types=[ "bounce", "send", ], sns_destination={ "topic_arn": aws_sns_topic["example"]["arn"], })
aa103ea582f1fe1dccda82638cc5841b408a0c7a
321b4ed83b6874eeb512027eaa0b17b0daf3c289
/988/988.smallest-string-starting-from-leaf.233252752.Accepted.leetcode.py
22432d1b1812c2fa9c180ef407130c342025bc17
[]
no_license
huangyingw/submissions
7a610613bdb03f1223cdec5f6ccc4391149ca618
bfac1238ecef8b03e54842b852f6fec111abedfa
refs/heads/master
2023-07-25T09:56:46.814504
2023-07-16T07:38:36
2023-07-16T07:38:36
143,352,065
0
1
null
null
null
null
UTF-8
Python
false
false
455
py
class Solution(object): def smallestFromLeaf(self, root): self.result = "~" def dfs(node, A): if node: A.append(chr(node.val + ord('a'))) if not node.left and not node.right: self.result = min(self.result, "".join(reversed(A))) dfs(node.left, A) dfs(node.right, A) A.pop() dfs(root, []) return self.result
5cb9c51015c50cab850bea8216889f5c99c937d9
487ce91881032c1de16e35ed8bc187d6034205f7
/codes/CodeJamCrawler/16_0_2_neat/16_0_2_Jormungandr_Revenge_of_the_pancakes.py
d9925b4d479f3e794bba1c134eedd620908d2b23
[]
no_license
DaHuO/Supergraph
9cd26d8c5a081803015d93cf5f2674009e92ef7e
c88059dc66297af577ad2b8afa4e0ac0ad622915
refs/heads/master
2021-06-14T16:07:52.405091
2016-08-21T13:39:13
2016-08-21T13:39:13
49,829,508
2
0
null
2021-03-19T21:55:46
2016-01-17T18:23:00
Python
UTF-8
Python
false
false
1,096
py
#!/usr/bin/env python __author__ = 'Bill' def check_pancakes(n): """(check_pancakes): function to test for all face up :param n: the pancakes string """ for ch in n: if ch == '-': return False return True def flip_pancakes(n): """(flip_pancakes): function to flip pancakes :param n: the pancakes string """ n = list(n) dict = {'+':'-', '-':'+'} first = n[0] i = 0 for ch in n: if ch != first: break i += 1 for j in xrange(i): n[j] = dict[first] n = "".join(n) return n from misc import input_, output_ num_cases, cases = input_('B-large.in') Results = [] for case in cases: case = case.rstrip('\n') i = 0 face_up = check_pancakes(case) if face_up == True: Results.append(i) else: while check_pancakes(case) == False: case = flip_pancakes(case) i += 1 Results.append(i) output_(Results, 'Revenge_of_the_pancakes_large.out')
43762e6631bb0431b80bd2656e2d2522d44b3bed
3d228d5eac44b31d460dd81767b43309b7356577
/extra/graph/company_tree.py
f1637b2f1a04bcbe1902f64e15364798ff383c47
[ "BSD-3-Clause" ]
permissive
lsbardel/mathfun
da65a6f09faacdb4815111dae287c9b974acf928
98e7c210409c2b5777e91059c3651cef4f3045dd
refs/heads/master
2021-05-02T08:56:05.565539
2020-07-30T09:14:04
2020-07-30T09:14:04
26,242,622
0
0
null
null
null
null
UTF-8
Python
false
false
41
py
from mathfun.graph.template import Graph
3da8f7b040ba3e4364324d6671fd5826cd2494b7
1dacbf90eeb384455ab84a8cf63d16e2c9680a90
/pkgs/odo-0.4.2-py27_0/lib/python2.7/site-packages/odo/backends/sparksql.py
80e27ad318d1981f6194e3e20d84b782da1089e7
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
wangyum/Anaconda
ac7229b21815dd92b0bd1c8b7ec4e85c013b8994
2c9002f16bb5c265e0d14f4a2314c86eeaa35cb6
refs/heads/master
2022-10-21T15:14:23.464126
2022-10-05T12:10:31
2022-10-05T12:10:31
76,526,728
11
10
Apache-2.0
2022-10-05T12:10:32
2016-12-15T05:26:12
Python
UTF-8
Python
false
false
9,639
py
from __future__ import division, print_function, absolute_import import os import glob import itertools import tempfile import shutil from functools import partial from collections import Iterator from datetime import datetime, date import pandas as pd import toolz from toolz.curried import get, map, memoize from toolz import pipe, concat, curry from pyspark import RDD, SQLContext, HiveContext from pyspark.sql import SchemaRDD from pyspark.rdd import PipelinedRDD import datashape from datashape import dshape, Record, DataShape, Option, Tuple from datashape.predicates import isdimension, isrecord, iscollection from .. import append, discover, convert from ..core import ooc_types from ..directory import Directory from ..temp import Temp from ..chunks import chunks from .json import JSONLines, JSON from .csv import CSV from pyspark.sql import DataFrame as SparkDataFrame from pyspark.sql.types import ( ByteType, ShortType, IntegerType, LongType, FloatType, DoubleType, StringType, BinaryType, BooleanType, TimestampType, DateType, ArrayType, StructType, StructField ) base = int, float, datetime, date, bool, str _names = ('tmp%d' % i for i in itertools.count()) @append.register(SQLContext, object) def iterable_to_sql_context(ctx, seq, **kwargs): return append(ctx, append(ctx._sc, seq, **kwargs), **kwargs) def register_table(ctx, srdd, name=None): if name is None: name = next(_names) ctx.registerDataFrameAsTable(srdd, name) @append.register(SQLContext, (JSONLines, Directory(JSONLines))) def jsonlines_to_sparksql(ctx, json, dshape=None, name=None, schema=None, samplingRatio=0.25, **kwargs): # if we're passing in schema, assume that we know what we're doing and # bypass any automated dshape inference if dshape is not None and schema is None: schema = dshape_to_schema(dshape.measure if isrecord(dshape.measure) else dshape) srdd = ctx.jsonFile(json.path, schema=schema, samplingRatio=samplingRatio) register_table(ctx, srdd, name=name) return srdd @convert.register(list, (SparkDataFrame, SchemaRDD), cost=200.0) def sparksql_dataframe_to_list(df, dshape=None, **kwargs): result = df.collect() if (dshape is not None and iscollection(dshape) and not isrecord(dshape.measure)): return list(map(get(0), result)) return result @convert.register(base, (SparkDataFrame, SchemaRDD), cost=200.0) def spark_df_to_base(df, **kwargs): return df.collect()[0][0] @append.register(SQLContext, RDD) def rdd_to_sqlcontext(ctx, rdd, name=None, dshape=None, **kwargs): """ Convert a normal PySpark RDD to a SparkSQL RDD or Spark DataFrame Schema inferred by ds_to_sparksql. Can also specify it explicitly with schema keyword argument. """ # TODO: assumes that we don't have e.g., 10 * 10 * {x: int, y: int} if isdimension(dshape.parameters[0]): dshape = dshape.measure sql_schema = dshape_to_schema(dshape) sdf = ctx.applySchema(rdd, sql_schema) if name is None: name = next(_names) register_table(ctx, sdf, name=name) ctx.cacheTable(name) return sdf def scala_set_to_set(ctx, x): from py4j.java_gateway import java_import # import scala java_import(ctx._jvm, 'scala') # grab Scala's set converter and convert to a Python set return set(ctx._jvm.scala.collection.JavaConversions.setAsJavaSet(x)) @discover.register(SQLContext) def discover_sqlcontext(ctx): table_names = sorted(map(str, ctx.tableNames())) dshapes = zip(table_names, map(discover, map(ctx.table, table_names))) return datashape.DataShape(datashape.Record(dshapes)) @discover.register((SparkDataFrame, SchemaRDD)) def discover_spark_data_frame(df): schema = df.schema() if callable(df.schema) else df.schema return datashape.var * schema_to_dshape(schema) def chunk_file(filename, chunksize): """Stream `filename` in chunks of size `chunksize`. Parameters ---------- filename : str File to chunk chunksize : int Number of bytes to hold in memory at a single time """ with open(filename, mode='rb') as f: for chunk in iter(partial(f.read, chunksize), b''): yield chunk @append.register(JSONLines, (SparkDataFrame, SchemaRDD)) def spark_df_to_jsonlines(js, df, pattern='part-*', chunksize=1 << 23, # 8MB **kwargs): tmpd = tempfile.mkdtemp() try: try: df.save(tmpd, source='org.apache.spark.sql.json', mode='overwrite') except AttributeError: shutil.rmtree(tmpd) df.toJSON().saveAsTextFile(tmpd) except: raise else: files = glob.glob(os.path.join(tmpd, pattern)) with open(js.path, mode='ab') as f: pipe(files, map(curry(chunk_file, chunksize=chunksize)), concat, map(f.write), toolz.count) finally: shutil.rmtree(tmpd) return js @convert.register((SparkDataFrame, SchemaRDD), (RDD, PipelinedRDD)) def rdd_to_spark_df_or_srdd(rdd, **kwargs): return append(HiveContext(rdd.context), rdd, **kwargs) try: from .hdfs import HDFS except ImportError: pass else: @append.register(HDFS(JSONLines), (Iterator, object, SparkDataFrame, SchemaRDD)) @append.register(HDFS(JSON), (list, object)) @append.register(HDFS(CSV), (chunks(pd.DataFrame), pd.DataFrame, object)) def append_spark_to_hdfs(target, source, **kwargs): tmp = convert(Temp(target.subtype), source, **kwargs) return append(target, tmp, **kwargs) def dshape_to_schema(ds): """Convert datashape to SparkSQL type system. Examples -------- >>> print(dshape_to_schema('int32')) # doctest: +SKIP IntegerType >>> print(dshape_to_schema('5 * int32') # doctest: +SKIP ArrayType(IntegerType,false) >>> print(dshape_to_schema('5 * ?int32')) # doctest: +SKIP ArrayType(IntegerType,true) >>> print(dshape_to_schema('{name: string, amount: int32}')) # doctest: +SKIP StructType(List(StructField(name,StringType,false),StructField(amount,IntegerType,false) # doctest: +SKIP)) >>> print(dshape_to_schema('10 * {name: string, amount: ?int32}')) # doctest: +SKIP ArrayType(StructType(List(StructField(name,StringType,false),StructField(amount,IntegerType,true))),false) """ if isinstance(ds, str): return dshape_to_schema(dshape(ds)) if isinstance(ds, Tuple): raise TypeError('Please provide a Record dshape for these column ' 'types: %s' % (ds.dshapes,)) if isinstance(ds, Record): return StructType([ StructField(name, dshape_to_schema(deoption(typ)), isinstance(typ, datashape.Option)) for name, typ in ds.fields]) if isinstance(ds, DataShape): if isdimension(ds[0]): elem = ds.subshape[0] if isinstance(elem, DataShape) and len(elem) == 1: elem = elem[0] return ArrayType(dshape_to_schema(deoption(elem)), isinstance(elem, Option)) else: return dshape_to_schema(ds[0]) if ds in dshape_to_sparksql: return dshape_to_sparksql[ds] raise NotImplementedError() def schema_to_dshape(schema): if type(schema) in sparksql_to_dshape: return sparksql_to_dshape[type(schema)] if isinstance(schema, ArrayType): dshape = schema_to_dshape(schema.elementType) return datashape.var * (Option(dshape) if schema.containsNull else dshape) if isinstance(schema, StructType): fields = [(field.name, Option(schema_to_dshape(field.dataType)) if field.nullable else schema_to_dshape(field.dataType)) for field in schema.fields] return datashape.dshape(Record(fields)) raise NotImplementedError('SparkSQL type not known %r' % type(schema).__name__) def deoption(ds): """ >>> deoption('int32') ctype("int32") >>> deoption('?int32') ctype("int32") """ if isinstance(ds, str): ds = dshape(ds) if isinstance(ds, DataShape) and not isdimension(ds[0]): return deoption(ds[0]) if isinstance(ds, Option): return ds.ty else: return ds # see http://spark.apache.org/docs/latest/sql-programming-guide.html#spark-sql-datatype-reference sparksql_to_dshape = { ByteType: datashape.int8, ShortType: datashape.int16, IntegerType: datashape.int32, LongType: datashape.int64, FloatType: datashape.float32, DoubleType: datashape.float64, StringType: datashape.string, BinaryType: datashape.bytes_, BooleanType: datashape.bool_, TimestampType: datashape.datetime_, DateType: datashape.date_, # sql.ArrayType: ?, # sql.MapTYpe: ?, # sql.StructType: ? } dshape_to_sparksql = { datashape.int16: ShortType(), datashape.int32: IntegerType(), datashape.int64: LongType(), datashape.float32: FloatType(), datashape.float64: DoubleType(), datashape.real: DoubleType(), datashape.time_: TimestampType(), datashape.date_: DateType(), datashape.datetime_: TimestampType(), datashape.bool_: BooleanType(), datashape.string: StringType() } ooc_types |= set([SparkDataFrame, SchemaRDD]) SQLContext = memoize(SQLContext) HiveContext = memoize(HiveContext)
7e718881b9c46f43e2cc9329438179cd7fbc6988
85a9ffeccb64f6159adbd164ff98edf4ac315e33
/pysnmp/CISCO-CDSTV-FSI-MIB.py
cb16a25f5a07fa321bae26f7dbc8039adcc9a510
[ "Apache-2.0" ]
permissive
agustinhenze/mibs.snmplabs.com
5d7d5d4da84424c5f5a1ed2752f5043ae00019fb
1fc5c07860542b89212f4c8ab807057d9a9206c7
refs/heads/master
2020-12-26T12:41:41.132395
2019-08-16T15:51:41
2019-08-16T15:53:57
237,512,469
0
0
Apache-2.0
2020-01-31T20:41:36
2020-01-31T20:41:35
null
UTF-8
Python
false
false
6,231
py
# # PySNMP MIB module CISCO-CDSTV-FSI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CDSTV-FSI-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:35:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") CiscoURLString, = mibBuilder.importSymbols("CISCO-TC", "CiscoURLString") InetAddressType, InetPortNumber, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetPortNumber", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") TimeTicks, Counter32, Integer32, ObjectIdentity, MibIdentifier, iso, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ModuleIdentity, Counter64, Unsigned32, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter32", "Integer32", "ObjectIdentity", "MibIdentifier", "iso", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ModuleIdentity", "Counter64", "Unsigned32", "Bits", "Gauge32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ciscoCdstvFsiMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 735)) ciscoCdstvFsiMIB.setRevisions(('2010-05-10 00:00',)) if mibBuilder.loadTexts: ciscoCdstvFsiMIB.setLastUpdated('201005100000Z') if mibBuilder.loadTexts: ciscoCdstvFsiMIB.setOrganization('Cisco Systems, Inc.') ciscoCdstvFsiMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 735, 0)) ciscoCdstvFsiMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 735, 1)) ciscoCdstvFsiMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 735, 2)) ciscoCdstvFsiMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 735, 2, 1)) cdstvFsiIpAddressType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 1), InetAddressType()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiIpAddressType.setStatus('current') cdstvFsiIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 2), InetAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiIpAddress.setStatus('current') cdstvFsiServerPort = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 3), InetPortNumber()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiServerPort.setStatus('current') cdstvFsiFtpClientPort = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 4), InetPortNumber()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiFtpClientPort.setStatus('current') cdstvFsiFtpOutServerPort = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 5), InetPortNumber()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiFtpOutServerPort.setStatus('current') cdstvFsiFtpOutLoginTTL = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 6), Unsigned32()).setUnits('hops').setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiFtpOutLoginTTL.setStatus('current') cdstvFsiLogLevel = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("off", 1), ("low", 2), ("high", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiLogLevel.setStatus('current') cdstvFsiContentRootPath = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 8), SnmpAdminString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiContentRootPath.setStatus('current') cdstvFsiAsyncCallbackURL = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 735, 1, 9), CiscoURLString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cdstvFsiAsyncCallbackURL.setStatus('current') ciscoCdstvFsiMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 735, 2, 2)) ciscoCdstvFsiMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 735, 2, 1, 1)).setObjects(("CISCO-CDSTV-FSI-MIB", "ciscoCdstvFsiMIBMainObjectGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoCdstvFsiMIBCompliance = ciscoCdstvFsiMIBCompliance.setStatus('current') ciscoCdstvFsiMIBMainObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 735, 2, 2, 1)).setObjects(("CISCO-CDSTV-FSI-MIB", "cdstvFsiIpAddress"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiServerPort"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiFtpClientPort"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiFtpOutServerPort"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiFtpOutLoginTTL"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiLogLevel"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiContentRootPath"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiAsyncCallbackURL"), ("CISCO-CDSTV-FSI-MIB", "cdstvFsiIpAddressType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoCdstvFsiMIBMainObjectGroup = ciscoCdstvFsiMIBMainObjectGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-CDSTV-FSI-MIB", ciscoCdstvFsiMIBConform=ciscoCdstvFsiMIBConform, PYSNMP_MODULE_ID=ciscoCdstvFsiMIB, cdstvFsiFtpClientPort=cdstvFsiFtpClientPort, ciscoCdstvFsiMIBObjects=ciscoCdstvFsiMIBObjects, cdstvFsiIpAddress=cdstvFsiIpAddress, cdstvFsiServerPort=cdstvFsiServerPort, cdstvFsiContentRootPath=cdstvFsiContentRootPath, ciscoCdstvFsiMIB=ciscoCdstvFsiMIB, ciscoCdstvFsiMIBCompliance=ciscoCdstvFsiMIBCompliance, ciscoCdstvFsiMIBMainObjectGroup=ciscoCdstvFsiMIBMainObjectGroup, cdstvFsiIpAddressType=cdstvFsiIpAddressType, ciscoCdstvFsiMIBCompliances=ciscoCdstvFsiMIBCompliances, ciscoCdstvFsiMIBNotifs=ciscoCdstvFsiMIBNotifs, cdstvFsiAsyncCallbackURL=cdstvFsiAsyncCallbackURL, cdstvFsiFtpOutServerPort=cdstvFsiFtpOutServerPort, cdstvFsiFtpOutLoginTTL=cdstvFsiFtpOutLoginTTL, cdstvFsiLogLevel=cdstvFsiLogLevel, ciscoCdstvFsiMIBGroups=ciscoCdstvFsiMIBGroups)
56749342e68294136dbbbacb342a3d9b2f01f30b
18b3ad3b0e1f7f10969738251e1201d01dfbc6bf
/backup_files/samplepy/passbyvalue.py
26689727f2944f32dee1688daef3ff1dc4632725
[]
no_license
sahthi/backup2
11d509b980e731c73733b1399a8143780779e75a
16bed38f0867fd7c766c2a008c8d43b0660f0cb0
refs/heads/master
2020-03-21T12:39:56.890129
2018-07-09T08:12:46
2018-07-09T08:12:46
138,565,151
0
0
null
null
null
null
UTF-8
Python
false
false
180
py
def changeme(mylist): mylist = [1,2,3,4 ] print "values inside the function",mylist return mylist = [10,20,30] changeme(mylist) print"values outside the function ",mylist
057695d4910d814affa1cef49fbca93b9b520c88
df690ac0484ff04cb63f71f528a9d0a0e557d6a3
/.history/ws_20210608130810.py
59216ed4c38672800e718b0909e4e451e853a45b
[]
no_license
khanhdk0000/Mqtt-Web-Socket
437777c740c68d4197353e334f6fe6a629094afd
4f9e49a3817baa9ebc4e4f8dcffc21b6ea9d0134
refs/heads/master
2023-06-20T17:08:09.447381
2021-06-08T17:42:37
2021-06-08T17:42:37
375,090,458
0
0
null
null
null
null
UTF-8
Python
false
false
3,612
py
from flask import Flask, jsonify, request from flask_sock import Sock import time app = Flask(__name__) sock = Sock(app) import threading BROKER = 'io.adafruit.com' USER = 'khanhdk0000' PASSWORD = 'aio_FfID10QWNVSKUC2j15nLtOSeckin' TOPIC = 'khanhdk0000/feeds/' LIGHT = 'light' SOUND = 'sound' TEMP = 'temp' LCD = 'iot_led' BUZZER = 'buzzer' ######## # USER = 'CSE_BBC' # PASSWORD = 'aio_FfID10QWNVSKUC2j15nLtOSeckin' # TOPIC = 'CSE_BBC/feeds/' # USER1 = 'CSE_BBC1' # PASSWORD1 = 'aio_FfID10QWNVSKUC2j15nLtOSeckin' # TOPIC1 = 'CSE_BBC1/feeds/' # LIGHT = 'bk-iot-light' # SOUND = 'bk-iot-sound' # TEMP = 'bk-iot-temp-humid' # LCD = 'bk-iot-lcd' # BUZZER = 'bk-iot-speaker' resLight = '"id":"13","name":"LIGHT","data":"0","unit":""' prevLight = resLight resTemp = '"id":"7","name":"SOUND","data":"0","unit":""' prevTemp = resTemp resSound = '"id":"12","name":"TEMP-HUMID","data":"0","unit":""' prevSound = resSound def mqttGet(user, password,topic,device): import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) if rc == 0: print('good') else: print('no good') def on_disconnect(client, userdata, flags, rc=0): print("Disconnected result code " + str(rc)) def on_message(client, userdata, message): if device == LIGHT: global resLight message = str(message.payload.decode("utf-8")) print(message) resLight = message elif device == TEMP: global resTemp message = str(message.payload.decode("utf-8")) print(message) resTemp = message elif device == SOUND: global resSound message = str(message.payload.decode("utf-8")) print(message) resSound = message client = mqtt.Client() client.username_pw_set(username=user,password=password) client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_message = on_message client.connect(BROKER, 1883, 60) client.subscribe(topic) client.loop_forever() t1 = threading.Thread(target=mqttGet, name=mqttGet, args=(USER, PASSWORD,TOPIC + LIGHT, LIGHT)) t1.start() t2 = threading.Thread(target=mqttGet, name=mqttGet, args=(USER, PASSWORD,TOPIC + TEMP, TEMP)) t2.start() t3 = threading.Thread(target=mqttGet, name=mqttGet, args=(USER, PASSWORD,TOPIC + SOUND, SOUND)) t3.start() def mqttPost(topic, user,pass,payload): import paho.mqtt.publish as publish publish.single(topic,hostname="io.adafruit.com",auth={"username":user, "password":pass},payload = payload) @sock.route('/light') def light(ws): global resLight, prevLight while True: if prevLight == resLight: continue else: ws.send(resLight) prevLight = resLight @sock.route('/sound') def sound(ws): global resSound, prevSound while True: if prevSound == resSound: continue else: ws.send(resSound) prevSound = resSound @sock.route('/temp') def temp(ws): global resTemp, prevTemp while True: if prevTemp == resTemp: continue else: ws.send(resTemp) prevTemp = resTemp @app.route('/postlcd', methods=["POST"]) def testpost(): input_json = request.get_json(force=True) domain = input_json['data'] print('receive data', domain) mqttPost(TOPIC+LCD, U) return 'yea:' + domain if __name__ == '__main__': app.run(debug=True)
09f47ffa874febc1dd80bb23531d909ac281739b
694c187c8a00bee8c670c1690170099bad9b16b3
/hindex.py
edded2784cbd958ce569e1997c2a49c5589810d0
[]
no_license
ajayvenkat10/Competitive
301f220b6d296f7e34328f192c43c4d7ef208cb1
14f2ecebe10eb19f72cc412dd0c414b3b1de9b4d
refs/heads/master
2022-11-20T14:31:33.590099
2020-07-23T15:39:14
2020-07-23T15:39:14
281,599,951
0
0
null
null
null
null
UTF-8
Python
false
false
450
py
t = int(input()) for _ in range(t): n = int(input()) arr = list(map(int, input().split())) final = [1] val = 2 for i in range(1,len(arr)): count = 0 for j in range(i+1): if(arr[j] >= val): count += 1 if(count>=val): final.append(val) val += 1 else: final.append(val-1) print("Case #%d: " % (_+1) , end="") print(*final)
6452090ca100845c839848f14ac2d04f85352f4d
934235f70a390a3ba0d7b464cddd10872f31cda3
/rango/server/.history/tango_with_django/rango/admin_20210103130028.py
361f6ca167ae05dc1771706293718383039c718e
[]
no_license
deji100/Projects
6919041ba23e77a5c74e5ab7692bfcee38ececcb
17e64d954d1d7805be57ec5d8d4344e4944889e6
refs/heads/master
2023-04-30T05:25:03.143303
2021-05-20T15:00:43
2021-05-20T15:00:43
338,844,691
0
0
null
null
null
null
UTF-8
Python
false
false
521
py
from django.contrib import admin from .models import Category, Page, User # Register your models here. class PageInline(admin.StackedInline): list_display = ('title', 'category', 'url') # fields = ('title', 'url', 'category') model class CategoryAdmin(admin.ModelAdmin): list_display = ('name', 'views', 'likes') # prepopulated_fields = {'slug': ('name',)} inlines = [PageInline] admin.site.register(Category, CategoryAdmin) admin.site.register(Page, PageAdmin) admin.site.register(User)
0ea09ec878674f42ce2fb633727af303b0ff9662
830398bc5ae951b153ff695a40be7239742bc73e
/exercises/parse_dhcp_snooping.py
27114f9e94d30bcea5c6296a1383f9c2e461987f
[]
no_license
dmikos/pyneng
ff67f1d617a97d73103a7785a7bf86140e7baa82
543fb0d9fc63a2afee45d2465af3a4c3966e4a86
refs/heads/master
2021-01-25T14:56:44.181140
2018-04-23T04:31:00
2018-04-23T04:31:00
123,739,447
0
1
null
null
null
null
UTF-8
Python
false
false
669
py
# -*- coding: utf-8 -*- import re #'00:09:BB:3D:D6:58 10.1.10.2 86250 dhcp-snooping 10 FastEthernet0/1' regex = re.compile('(?P<mac>\S+) +(?P<ip>\S+) +\d+ +\S+ +(?P<vlan>\d+) +(?P<port>\S+)') result = [] with open('dhcp_snooping.txt') as data: for line in data: match = regex.search(line) if match: result.append(match.groupdict()) print('К коммутатору подключено {} устройства'.format(len(result))) for num, comp in enumerate(result, 1): print('Параметры устройства {}:'.format(num)) for key in comp: print('{:10}: {:10}'.format(key,comp[key]))
8435baa0b8beaab331ff8904a8889f896a8d23c0
9ae6ce54bf9a2a86201961fdbd5e7b0ec913ff56
/google/ads/googleads/v9/services/services/third_party_app_analytics_link_service/transports/__init__.py
502d5cf2169f355fb53779b340f3900e0e913770
[ "Apache-2.0" ]
permissive
GerhardusM/google-ads-python
73b275a06e5401e6b951a6cd99af98c247e34aa3
676ac5fcb5bec0d9b5897f4c950049dac5647555
refs/heads/master
2022-07-06T19:05:50.932553
2022-06-17T20:41:17
2022-06-17T20:41:17
207,535,443
0
0
Apache-2.0
2019-09-10T10:58:55
2019-09-10T10:58:55
null
UTF-8
Python
false
false
1,141
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict from typing import Dict, Type from .base import ThirdPartyAppAnalyticsLinkServiceTransport from .grpc import ThirdPartyAppAnalyticsLinkServiceGrpcTransport # Compile a registry of transports. _transport_registry = ( OrderedDict() ) # type: Dict[str, Type[ThirdPartyAppAnalyticsLinkServiceTransport]] _transport_registry["grpc"] = ThirdPartyAppAnalyticsLinkServiceGrpcTransport __all__ = ( "ThirdPartyAppAnalyticsLinkServiceTransport", "ThirdPartyAppAnalyticsLinkServiceGrpcTransport", )
ce7050ab38a7683c7b476a80901ac6beac9d0799
4fbd844113ec9d8c526d5f186274b40ad5502aa3
/algorithms/python3/maximize_distance_to_closest_person.py
37e744aa546a7f515c70e1f156bc63f0f499ee8d
[]
no_license
capric8416/leetcode
51f9bdc3fa26b010e8a1e8203a7e1bcd70ace9e1
503b2e303b10a455be9596c31975ee7973819a3c
refs/heads/master
2022-07-16T21:41:07.492706
2020-04-22T06:18:16
2020-04-22T06:18:16
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,203
py
# !/usr/bin/env python # -*- coding: utf-8 -*- """ In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty.  There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.  Return that maximum distance to closest person. Example 1: Input: [1,0,0,0,1,0,1] Output: 2 Explanation: If Alex sits in the second open seat (seats[2]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. Example 2: Input: [1,0,0,0] Output: 3 Explanation: If Alex sits in the last seat, the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. Note: 1 <= seats.length <= 20000 seats contains only 0s or 1s, at least one 0, and at least one 1. """ """ ==================== body ==================== """ class Solution: def maxDistToClosest(self, seats): """ :type seats: List[int] :rtype: int """ """ ==================== body ==================== """
d86e1749616a76d2d38d3047025c8bd2f53d42fd
53438732c6bc70b0d15eea99d961d6036f8839df
/Auth1/venv/bin/pip3.7
7e7d4a7ec99e985fd6466a5c34625337413e6453
[]
no_license
Amarjeet2629/MyPycharmProjects
6e07c972dce8ef12453ae0246bcbfcfd03cba1fb
179a87f327d7c036a6192d0c6e372f2f1e3588ff
refs/heads/master
2023-05-07T20:32:22.091132
2021-04-20T17:06:15
2021-04-20T17:06:15
224,671,445
0
0
null
2023-04-21T20:51:29
2019-11-28T14:32:13
Python
UTF-8
Python
false
false
410
7
#!/home/amarjeet-pc/PycharmProjects/Auth1/venv/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'pip==19.0.3','console_scripts','pip3.7' __requires__ = 'pip==19.0.3' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('pip==19.0.3', 'console_scripts', 'pip3.7')() )
a4a27e3eb0c39273105293f96a89dc9b05e6f10a
b6a84594f8c29d968014faaddd49abeb7537a5fc
/python/1040.moving-stones-until-consecutive-ii.py
799deed3b361b4636ffa827b1e859308649b708d
[]
no_license
nickyfoto/lc
8a6af3df114e693e265d0ede03f4d4e1283e010e
3633b4df3e24968057c7d684689b931c5a8032d3
refs/heads/master
2020-09-16T19:23:07.765917
2020-06-07T17:18:06
2020-06-07T17:18:06
223,866,098
0
0
null
null
null
null
UTF-8
Python
false
false
1,913
py
# # @lc app=leetcode id=1040 lang=python3 # # [1040] Moving Stones Until Consecutive II # # https://leetcode.com/problems/moving-stones-until-consecutive-ii/description/ # # algorithms # Medium (52.07%) # Likes: 152 # Dislikes: 231 # Total Accepted: 4.5K # Total Submissions: 8.7K # Testcase Example: '[7,4,9]' # # On an infinite number line, the position of the i-th stone is given by # stones[i].  Call a stone an endpoint stone if it has the smallest or largest # position. # # Each turn, you pick up an endpoint stone and move it to an unoccupied # position so that it is no longer an endpoint stone. # # In particular, if the stones are at say, stones = [1,2,5], you cannot move # the endpoint stone at position 5, since moving it to any position (such as 0, # or 3) will still keep that stone as an endpoint stone. # # The game ends when you cannot make any more moves, ie. the stones are in # consecutive positions. # # When the game ends, what is the minimum and maximum number of moves that you # could have made?  Return the answer as an length 2 array: answer = # [minimum_moves, maximum_moves] # # # # Example 1: # # # Input: [7,4,9] # Output: [1,2] # Explanation: # We can move 4 -> 8 for one move to finish the game. # Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. # # # # Example 2: # # # Input: [6,5,4,3,10] # Output: [2,3] # We can move 3 -> 8 then 10 -> 7 to finish the game. # Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. # Notice we cannot move 10 -> 2 to finish the game, because that would be an # illegal move. # # # # Example 3: # # # Input: [100,101,104,102,103] # Output: [0,0] # # # # # # Note: # # # 3 <= stones.length <= 10^4 # 1 <= stones[i] <= 10^9 # stones[i] have distinct values. # # # # # # # # # # @lc code=start class Solution: def numMovesStonesII(self, stones): pass # @lc code=end
9adf50d27141869fb0693ddeb11ca31431191545
bd93fa910151c278be8249055bc084e5a5c35a6a
/Python/DjangoTest2/booktest/models.py
3735ebb85498b072da8a92f26cec7a80e612790c
[]
no_license
ahojcn/practice-code
bd81595b80239cd2550183093566bd536a83ed3f
b65f4e76271479269463e92fd3fd41585c2ac792
refs/heads/master
2021-07-10T14:15:08.036592
2020-07-09T11:32:16
2020-07-09T11:32:16
153,059,349
2
2
null
null
null
null
UTF-8
Python
false
false
704
py
from django.db import models # Create your models here. # 创建模型 class BookInfo(models.Model): """图书模型类""" # 图书名 btitle = models.CharField(max_length=20) # 出版日期 bpub_date = models.DateField() def __str__(self): return self.btitle class HeroInfo(models.Model): """书中的英雄人物类""" # 英雄名 hname = models.CharField(max_length=20) # 性别 Boolean 类型,默认 False 代表男 hgender = models.BooleanField(default=False) # 备注 hcomment = models.CharField(max_length=128) # 关系 hbook = models.ForeignKey(BookInfo, on_delete=None) def __str__(self): return self.hname
8d1a3522d4cfd4b873a8f1089516307ab89e8605
d0281cecabd070c399d18612bbb3ba11913c0ab1
/venv/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py
2f6941ef65e3378a7104657698538b9f1db55d8d
[ "MIT" ]
permissive
yuxuan1995liu/darkflowyolo_detection
f0b7aa0a667591da9736fb2860d6080b2fc41577
a7807e9b85833e3f877d46bb60e8fa7d0596a10b
refs/heads/master
2022-11-03T04:00:42.996414
2019-05-10T01:58:59
2019-05-10T01:58:59
185,880,108
0
1
MIT
2022-10-30T16:38:49
2019-05-09T22:28:01
Python
UTF-8
Python
false
false
514,131
py
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: array_ops.cc """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _core from tensorflow.python.eager import execute as _execute from tensorflow.python.framework import dtypes as _dtypes from tensorflow.python.framework import errors as _errors from tensorflow.python.framework import tensor_shape as _tensor_shape from tensorflow.core.framework import op_def_pb2 as _op_def_pb2 # Needed to trigger the call to _set_call_cpp_shape_fn. from tensorflow.python.framework import common_shapes as _common_shapes from tensorflow.python.framework import op_def_registry as _op_def_registry from tensorflow.python.framework import ops as _ops from tensorflow.python.framework import op_def_library as _op_def_library from tensorflow.python.util.deprecation import deprecated_endpoints from tensorflow.python.util import dispatch as _dispatch from tensorflow.python.util.tf_export import tf_export def batch_matrix_band_part(input, num_lower, num_upper, name=None): r"""TODO: add doc. Args: input: A `Tensor`. num_lower: A `Tensor` of type `int64`. num_upper: A `Tensor` of type `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchMatrixBandPart", name, _ctx._post_execution_callbacks, input, num_lower, num_upper) return _result except _core._FallbackException: try: return batch_matrix_band_part_eager_fallback( input, num_lower, num_upper, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BatchMatrixBandPart", input=input, num_lower=num_lower, num_upper=num_upper, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BatchMatrixBandPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_band_part_eager_fallback(input, num_lower, num_upper, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_matrix_band_part """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) num_lower = _ops.convert_to_tensor(num_lower, _dtypes.int64) num_upper = _ops.convert_to_tensor(num_upper, _dtypes.int64) _inputs_flat = [input, num_lower, num_upper] _attrs = ("T", _attr_T) _result = _execute.execute(b"BatchMatrixBandPart", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchMatrixBandPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_diag(diagonal, name=None): r"""TODO: add doc. Args: diagonal: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `diagonal`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchMatrixDiag", name, _ctx._post_execution_callbacks, diagonal) return _result except _core._FallbackException: try: return batch_matrix_diag_eager_fallback( diagonal, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BatchMatrixDiag", diagonal=diagonal, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BatchMatrixDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_diag_eager_fallback(diagonal, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_matrix_diag """ _ctx = ctx if ctx else _context.context() _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], _ctx) _inputs_flat = [diagonal] _attrs = ("T", _attr_T) _result = _execute.execute(b"BatchMatrixDiag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchMatrixDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_diag_part(input, name=None): r"""TODO: add doc. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchMatrixDiagPart", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return batch_matrix_diag_part_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BatchMatrixDiagPart", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BatchMatrixDiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_diag_part_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_matrix_diag_part """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"BatchMatrixDiagPart", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchMatrixDiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_set_diag(input, diagonal, name=None): r"""TODO: add doc. Args: input: A `Tensor`. diagonal: A `Tensor`. Must have the same type as `input`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchMatrixSetDiag", name, _ctx._post_execution_callbacks, input, diagonal) return _result except _core._FallbackException: try: return batch_matrix_set_diag_eager_fallback( input, diagonal, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BatchMatrixSetDiag", input=input, diagonal=diagonal, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BatchMatrixSetDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_matrix_set_diag_eager_fallback(input, diagonal, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_matrix_set_diag """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], _ctx) (input, diagonal) = _inputs_T _inputs_flat = [input, diagonal] _attrs = ("T", _attr_T) _result = _execute.execute(b"BatchMatrixSetDiag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchMatrixSetDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_to_space(input, crops, block_size, name=None): r"""BatchToSpace for 4-D tensors of type T. This is a legacy version of the more general BatchToSpaceND. Rearranges (permutes) data from batch into blocks of spatial data, followed by cropping. This is the reverse transformation of SpaceToBatch. More specifically, this op outputs a copy of the input tensor where values from the `batch` dimension are moved in spatial blocks to the `height` and `width` dimensions, followed by cropping along the `height` and `width` dimensions. Args: input: A `Tensor`. 4-D tensor with shape `[batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth]`. Note that the batch size of the input tensor must be divisible by `block_size * block_size`. crops: A `Tensor`. Must be one of the following types: `int32`, `int64`. 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies how many elements to crop from the intermediate result across the spatial dimensions as follows: crops = [[crop_top, crop_bottom], [crop_left, crop_right]] block_size: An `int` that is `>= 2`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchToSpace", name, _ctx._post_execution_callbacks, input, crops, "block_size", block_size) return _result except _core._FallbackException: try: return batch_to_space_eager_fallback( input, crops, block_size=block_size, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. block_size = _execute.make_int(block_size, "block_size") _, _, _op = _op_def_lib._apply_op_helper( "BatchToSpace", input=input, crops=crops, block_size=block_size, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "block_size", _op.get_attr("block_size"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "BatchToSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_to_space_eager_fallback(input, crops, block_size, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_to_space """ _ctx = ctx if ctx else _context.context() block_size = _execute.make_int(block_size, "block_size") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (crops,) = _execute.args_to_matching_eager([crops], _ctx, _dtypes.int32) _inputs_flat = [input, crops] _attrs = ("T", _attr_T, "block_size", block_size, "Tidx", _attr_Tidx) _result = _execute.execute(b"BatchToSpace", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchToSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export(v1=['batch_to_space_nd', 'manip.batch_to_space_nd']) @deprecated_endpoints('batch_to_space_nd', 'manip.batch_to_space_nd') def batch_to_space_nd(input, block_shape, crops, name=None): r"""BatchToSpace for N-D tensors of type T. This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of shape `block_shape + [batch]`, interleaves these blocks back into the grid defined by the spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as the input. The spatial dimensions of this intermediate result are then optionally cropped according to `crops` to produce the output. This is the reverse of SpaceToBatch. See below for a precise description. Args: input: A `Tensor`. N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, where spatial_shape has M dimensions. block_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D with shape `[M]`, all values must be >= 1. crops: A `Tensor`. Must be one of the following types: `int32`, `int64`. 2-D with shape `[M, 2]`, all values must be >= 0. `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input dimension `i + 1`, which corresponds to spatial dimension `i`. It is required that `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. This operation is equivalent to the following steps: 1. Reshape `input` to `reshaped` of shape: [block_shape[0], ..., block_shape[M-1], batch / prod(block_shape), input_shape[1], ..., input_shape[N-1]] 2. Permute dimensions of `reshaped` to produce `permuted` of shape [batch / prod(block_shape), input_shape[1], block_shape[0], ..., input_shape[M], block_shape[M-1], input_shape[M+1], ..., input_shape[N-1]] 3. Reshape `permuted` to produce `reshaped_permuted` of shape [batch / prod(block_shape), input_shape[1] * block_shape[0], ..., input_shape[M] * block_shape[M-1], input_shape[M+1], ..., input_shape[N-1]] 4. Crop the start and end of dimensions `[1, ..., M]` of `reshaped_permuted` according to `crops` to produce the output of shape: [batch / prod(block_shape), input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], ..., input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], input_shape[M+1], ..., input_shape[N-1]] Some examples: (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: ``` [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] ``` The output tensor has shape `[1, 2, 2, 1]` and value: ``` x = [[[[1], [2]], [[3], [4]]]] ``` (2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: ``` [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]], [[10, 11, 12]]] ``` The output tensor has shape `[1, 2, 2, 3]` and value: ``` x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] ``` (3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`: ``` x = [[[[1], [3]], [[9], [11]]], [[[2], [4]], [[10], [12]]], [[[5], [7]], [[13], [15]]], [[[6], [8]], [[14], [16]]]] ``` The output tensor has shape `[1, 4, 4, 1]` and value: ``` x = [[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]] ``` (4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [2, 0]]`: ``` x = [[[[0], [1], [3]]], [[[0], [9], [11]]], [[[0], [2], [4]]], [[[0], [10], [12]]], [[[0], [5], [7]]], [[[0], [13], [15]]], [[[0], [6], [8]]], [[[0], [14], [16]]]] ``` The output tensor has shape `[2, 2, 4, 1]` and value: ``` x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]] ``` name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BatchToSpaceND", name, _ctx._post_execution_callbacks, input, block_shape, crops) return _result except _core._FallbackException: try: return batch_to_space_nd_eager_fallback( input, block_shape, crops, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( batch_to_space_nd, input=input, block_shape=block_shape, crops=crops, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "BatchToSpaceND", input=input, block_shape=block_shape, crops=crops, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( batch_to_space_nd, input=input, block_shape=block_shape, crops=crops, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tblock_shape", _op.get_attr("Tblock_shape"), "Tcrops", _op.get_attr("Tcrops")) _execute.record_gradient( "BatchToSpaceND", _inputs_flat, _attrs, _result, name) _result, = _result return _result def batch_to_space_nd_eager_fallback(input, block_shape, crops, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function batch_to_space_nd """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tblock_shape, (block_shape,) = _execute.args_to_matching_eager([block_shape], _ctx, _dtypes.int32) _attr_Tcrops, (crops,) = _execute.args_to_matching_eager([crops], _ctx, _dtypes.int32) _inputs_flat = [input, block_shape, crops] _attrs = ("T", _attr_T, "Tblock_shape", _attr_Tblock_shape, "Tcrops", _attr_Tcrops) _result = _execute.execute(b"BatchToSpaceND", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BatchToSpaceND", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('bitcast') def bitcast(input, type, name=None): r"""Bitcasts a tensor from one type to another without copying data. Given a tensor `input`, this operation returns a tensor that has the same buffer data as `input` with datatype `type`. If the input datatype `T` is larger than the output datatype `type` then the shape changes from [...] to [..., sizeof(`T`)/sizeof(`type`)]. If `T` is smaller than `type`, the operator requires that the rightmost dimension be equal to sizeof(`type`)/sizeof(`T`). The shape then goes from [..., sizeof(`type`)/sizeof(`T`)] to [...]. *NOTE*: Bitcast is implemented as a low-level cast, so machines with different endian orderings will give different results. Args: input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `uint32`, `uint64`, `int8`, `int16`, `complex64`, `complex128`, `qint8`, `quint8`, `qint16`, `quint16`, `qint32`. type: A `tf.DType` from: `tf.bfloat16, tf.half, tf.float32, tf.float64, tf.int64, tf.int32, tf.uint8, tf.uint16, tf.uint32, tf.uint64, tf.int8, tf.int16, tf.complex64, tf.complex128, tf.qint8, tf.quint8, tf.qint16, tf.quint16, tf.qint32`. name: A name for the operation (optional). Returns: A `Tensor` of type `type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Bitcast", name, _ctx._post_execution_callbacks, input, "type", type) return _result except _core._FallbackException: try: return bitcast_eager_fallback( input, type=type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( bitcast, input=input, type=type, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. type = _execute.make_type(type, "type") try: _, _, _op = _op_def_lib._apply_op_helper( "Bitcast", input=input, type=type, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( bitcast, input=input, type=type, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "type", _op.get_attr("type")) _execute.record_gradient( "Bitcast", _inputs_flat, _attrs, _result, name) _result, = _result return _result def bitcast_eager_fallback(input, type, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function bitcast """ _ctx = ctx if ctx else _context.context() type = _execute.make_type(type, "type") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "type", type) _result = _execute.execute(b"Bitcast", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Bitcast", _inputs_flat, _attrs, _result, name) _result, = _result return _result def broadcast_args(s0, s1, name=None): r"""Return the shape of s0 op s1 with broadcast. Given `s0` and `s1`, tensors that represent shapes, compute `r0`, the broadcasted shape. `s0`, `s1` and `r0` are all integer vectors. Args: s0: A `Tensor`. Must be one of the following types: `int32`, `int64`. s1: A `Tensor`. Must have the same type as `s0`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `s0`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BroadcastArgs", name, _ctx._post_execution_callbacks, s0, s1) return _result except _core._FallbackException: try: return broadcast_args_eager_fallback( s0, s1, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BroadcastArgs", s0=s0, s1=s1, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BroadcastArgs", _inputs_flat, _attrs, _result, name) _result, = _result return _result def broadcast_args_eager_fallback(s0, s1, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function broadcast_args """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([s0, s1], _ctx, _dtypes.int32) (s0, s1) = _inputs_T _inputs_flat = [s0, s1] _attrs = ("T", _attr_T) _result = _execute.execute(b"BroadcastArgs", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BroadcastArgs", _inputs_flat, _attrs, _result, name) _result, = _result return _result _broadcast_gradient_args_outputs = ["r0", "r1"] _BroadcastGradientArgsOutput = _collections.namedtuple( "BroadcastGradientArgs", _broadcast_gradient_args_outputs) def broadcast_gradient_args(s0, s1, name=None): r"""Return the reduction indices for computing gradients of s0 op s1 with broadcast. This is typically used by gradient computations for a broadcasting operation. Args: s0: A `Tensor`. Must be one of the following types: `int32`, `int64`. s1: A `Tensor`. Must have the same type as `s0`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (r0, r1). r0: A `Tensor`. Has the same type as `s0`. r1: A `Tensor`. Has the same type as `s0`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BroadcastGradientArgs", name, _ctx._post_execution_callbacks, s0, s1) _result = _BroadcastGradientArgsOutput._make(_result) return _result except _core._FallbackException: try: return broadcast_gradient_args_eager_fallback( s0, s1, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "BroadcastGradientArgs", s0=s0, s1=s1, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "BroadcastGradientArgs", _inputs_flat, _attrs, _result, name) _result = _BroadcastGradientArgsOutput._make(_result) return _result def broadcast_gradient_args_eager_fallback(s0, s1, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function broadcast_gradient_args """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([s0, s1], _ctx, _dtypes.int32) (s0, s1) = _inputs_T _inputs_flat = [s0, s1] _attrs = ("T", _attr_T) _result = _execute.execute(b"BroadcastGradientArgs", 2, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BroadcastGradientArgs", _inputs_flat, _attrs, _result, name) _result = _BroadcastGradientArgsOutput._make(_result) return _result @_dispatch.add_dispatch_list @tf_export('broadcast_to') def broadcast_to(input, shape, name=None): r"""Broadcast an array for a compatible shape. Broadcasting is the process of making arrays to have compatible shapes for arithmetic operations. Two shapes are compatible if for each dimension pair they are either equal or one of them is one. When trying to broadcast a Tensor to a shape, it starts with the trailing dimensions, and works its way forward. For example, ``` >>> x = tf.constant([1, 2, 3]) >>> y = tf.broadcast_to(x, [3, 3]) >>> sess.run(y) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]], dtype=int32) ``` In the above example, the input Tensor with the shape of `[1, 3]` is broadcasted to output Tensor with shape of `[3, 3]`. Args: input: A `Tensor`. A Tensor to broadcast. shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. An 1-D `int` Tensor. The shape of the desired output. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "BroadcastTo", name, _ctx._post_execution_callbacks, input, shape) return _result except _core._FallbackException: try: return broadcast_to_eager_fallback( input, shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( broadcast_to, input=input, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "BroadcastTo", input=input, shape=shape, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( broadcast_to, input=input, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "BroadcastTo", _inputs_flat, _attrs, _result, name) _result, = _result return _result def broadcast_to_eager_fallback(input, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function broadcast_to """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tidx, (shape,) = _execute.args_to_matching_eager([shape], _ctx, _dtypes.int32) _inputs_flat = [input, shape] _attrs = ("T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"BroadcastTo", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "BroadcastTo", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('debugging.check_numerics', v1=['debugging.check_numerics', 'check_numerics']) @deprecated_endpoints('check_numerics') def check_numerics(tensor, message, name=None): r"""Checks a tensor for NaN and Inf values. When run, reports an `InvalidArgument` error if `tensor` has any values that are not a number (NaN) or infinity (Inf). Otherwise, passes `tensor` as-is. Args: tensor: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. message: A `string`. Prefix of the error message. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "CheckNumerics", name, _ctx._post_execution_callbacks, tensor, "message", message) return _result except _core._FallbackException: try: return check_numerics_eager_fallback( tensor, message=message, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( check_numerics, tensor=tensor, message=message, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. message = _execute.make_str(message, "message") try: _, _, _op = _op_def_lib._apply_op_helper( "CheckNumerics", tensor=tensor, message=message, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( check_numerics, tensor=tensor, message=message, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "message", _op.get_attr("message")) _execute.record_gradient( "CheckNumerics", _inputs_flat, _attrs, _result, name) _result, = _result return _result def check_numerics_eager_fallback(tensor, message, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function check_numerics """ _ctx = ctx if ctx else _context.context() message = _execute.make_str(message, "message") _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], _ctx) _inputs_flat = [tensor] _attrs = ("T", _attr_T, "message", message) _result = _execute.execute(b"CheckNumerics", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "CheckNumerics", _inputs_flat, _attrs, _result, name) _result, = _result return _result def concat(concat_dim, values, name=None): r"""Concatenates tensors along one dimension. Args: concat_dim: A `Tensor` of type `int32`. 0-D. The dimension along which to concatenate. Must be in the range [0, rank(values)). values: A list of at least 2 `Tensor` objects with the same type. The `N` Tensors to concatenate. Their ranks and types must match, and their sizes must match in all dimensions except `concat_dim`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `values`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Concat", name, _ctx._post_execution_callbacks, concat_dim, values) return _result except _core._FallbackException: try: return concat_eager_fallback( concat_dim, values, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'concat' Op, not %r." % values) _attr_N = len(values) _, _, _op = _op_def_lib._apply_op_helper( "Concat", concat_dim=concat_dim, values=values, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T")) _execute.record_gradient( "Concat", _inputs_flat, _attrs, _result, name) _result, = _result return _result def concat_eager_fallback(concat_dim, values, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function concat """ _ctx = ctx if ctx else _context.context() if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'concat' Op, not %r." % values) _attr_N = len(values) _attr_T, values = _execute.args_to_matching_eager(list(values), _ctx) concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) _inputs_flat = [concat_dim] + list(values) _attrs = ("N", _attr_N, "T", _attr_T) _result = _execute.execute(b"Concat", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Concat", _inputs_flat, _attrs, _result, name) _result, = _result return _result def concat_offset(concat_dim, shape, name=None): r"""Computes offsets of concat inputs within its output. For example: ``` # 'x' is [2, 2, 7] # 'y' is [2, 3, 7] # 'z' is [2, 5, 7] concat_offset(2, [x, y, z]) => [0, 0, 0], [0, 2, 0], [0, 5, 0] ``` This is typically used by gradient computations for a concat operation. Args: concat_dim: A `Tensor` of type `int32`. The dimension along which to concatenate. shape: A list of at least 2 `Tensor` objects with type `int32`. The `N` int32 vectors representing shape of tensors being concatenated. name: A name for the operation (optional). Returns: A list with the same length as `shape` of `Tensor` objects with type `int32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ConcatOffset", name, _ctx._post_execution_callbacks, concat_dim, shape) return _result except _core._FallbackException: try: return concat_offset_eager_fallback( concat_dim, shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(shape, (list, tuple)): raise TypeError( "Expected list for 'shape' argument to " "'concat_offset' Op, not %r." % shape) _attr_N = len(shape) _, _, _op = _op_def_lib._apply_op_helper( "ConcatOffset", concat_dim=concat_dim, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N")) _execute.record_gradient( "ConcatOffset", _inputs_flat, _attrs, _result, name) return _result def concat_offset_eager_fallback(concat_dim, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function concat_offset """ _ctx = ctx if ctx else _context.context() if not isinstance(shape, (list, tuple)): raise TypeError( "Expected list for 'shape' argument to " "'concat_offset' Op, not %r." % shape) _attr_N = len(shape) concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) shape = _ops.convert_n_to_tensor(shape, _dtypes.int32) _inputs_flat = [concat_dim] + list(shape) _attrs = ("N", _attr_N) _result = _execute.execute(b"ConcatOffset", _attr_N, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ConcatOffset", _inputs_flat, _attrs, _result, name) return _result def concat_v2(values, axis, name=None): r"""Concatenates tensors along one dimension. Args: values: A list of at least 2 `Tensor` objects with the same type. List of `N` Tensors to concatenate. Their ranks and types must match, and their sizes must match in all dimensions except `concat_dim`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. 0-D. The dimension along which to concatenate. Must be in the range [-rank(values), rank(values)). name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `values`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ConcatV2", name, _ctx._post_execution_callbacks, values, axis) return _result except _core._FallbackException: try: return concat_v2_eager_fallback( values, axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'concat_v2' Op, not %r." % values) _attr_N = len(values) _, _, _op = _op_def_lib._apply_op_helper( "ConcatV2", values=values, axis=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T"), "Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "ConcatV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def concat_v2_eager_fallback(values, axis, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function concat_v2 """ _ctx = ctx if ctx else _context.context() if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'concat_v2' Op, not %r." % values) _attr_N = len(values) _attr_T, values = _execute.args_to_matching_eager(list(values), _ctx) _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = list(values) + [axis] _attrs = ("N", _attr_N, "T", _attr_T, "Tidx", _attr_Tidx) _result = _execute.execute(b"ConcatV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ConcatV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def conjugate_transpose(x, perm, name=None): r"""Shuffle dimensions of x according to a permutation and conjugate the result. The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` `y[i,j,k,...,s,t,u] == conj(x[perm[i], perm[j], perm[k],...,perm[s], perm[t], perm[u]])` Args: x: A `Tensor`. perm: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ConjugateTranspose", name, _ctx._post_execution_callbacks, x, perm) return _result except _core._FallbackException: try: return conjugate_transpose_eager_fallback( x, perm, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "ConjugateTranspose", x=x, perm=perm, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tperm", _op.get_attr("Tperm")) _execute.record_gradient( "ConjugateTranspose", _inputs_flat, _attrs, _result, name) _result, = _result return _result def conjugate_transpose_eager_fallback(x, perm, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function conjugate_transpose """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Tperm, (perm,) = _execute.args_to_matching_eager([perm], _ctx, _dtypes.int32) _inputs_flat = [x, perm] _attrs = ("T", _attr_T, "Tperm", _attr_Tperm) _result = _execute.execute(b"ConjugateTranspose", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ConjugateTranspose", _inputs_flat, _attrs, _result, name) _result, = _result return _result def const(value, dtype, name=None): r"""Returns a constant tensor. Args: value: A `tf.TensorProto`. Attr `value` is the tensor to return. dtype: A `tf.DType`. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Const", name, _ctx._post_execution_callbacks, "value", value, "dtype", dtype) return _result except _core._FallbackException: try: return const_eager_fallback( value=value, dtype=dtype, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. value = _execute.make_tensor(value, "value") dtype = _execute.make_type(dtype, "dtype") _, _, _op = _op_def_lib._apply_op_helper( "Const", value=value, dtype=dtype, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("value", _op.get_attr("value"), "dtype", _op.get_attr("dtype")) _execute.record_gradient( "Const", _inputs_flat, _attrs, _result, name) _result, = _result return _result def const_eager_fallback(value, dtype, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function const """ _ctx = ctx if ctx else _context.context() value = _execute.make_tensor(value, "value") dtype = _execute.make_type(dtype, "dtype") _inputs_flat = [] _attrs = ("value", value, "dtype", dtype) _result = _execute.execute(b"Const", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Const", _inputs_flat, _attrs, _result, name) _result, = _result return _result def debug_gradient_identity(input, name=None): r"""Identity op for gradient debugging. This op is hidden from public in Python. It is used by TensorFlow Debugger to register gradient tensors for gradient debugging. This op operates on non-reference-type tensors. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "DebugGradientIdentity", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return debug_gradient_identity_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "DebugGradientIdentity", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "DebugGradientIdentity", _inputs_flat, _attrs, _result, name) _result, = _result return _result def debug_gradient_identity_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function debug_gradient_identity """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"DebugGradientIdentity", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "DebugGradientIdentity", _inputs_flat, _attrs, _result, name) _result, = _result return _result def debug_gradient_ref_identity(input, name=None): r"""Identity op for gradient debugging. This op is hidden from public in Python. It is used by TensorFlow Debugger to register gradient tensors for gradient debugging. This op operates on reference-type tensors. Args: input: A mutable `Tensor`. name: A name for the operation (optional). Returns: A mutable `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: raise RuntimeError("debug_gradient_ref_identity op does not support eager execution. Arg 'output' is a ref.") # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "DebugGradientRefIdentity", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "DebugGradientRefIdentity", _inputs_flat, _attrs, _result, name) _result, = _result return _result def debug_gradient_ref_identity_eager_fallback(input, name=None, ctx=None): raise RuntimeError("debug_gradient_ref_identity op does not support eager execution. Arg 'output' is a ref.") def deep_copy(x, name=None): r"""Makes a copy of `x`. Args: x: A `Tensor`. The source tensor of type `T`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "DeepCopy", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: try: return deep_copy_eager_fallback( x, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "DeepCopy", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "DeepCopy", _inputs_flat, _attrs, _result, name) _result, = _result return _result def deep_copy_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function deep_copy """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"DeepCopy", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "DeepCopy", _inputs_flat, _attrs, _result, name) _result, = _result return _result def depth_to_space(input, block_size, data_format="NHWC", name=None): r"""DepthToSpace for tensors of type T. Rearranges data from depth into blocks of spatial data. This is the reverse transformation of SpaceToDepth. More specifically, this op outputs a copy of the input tensor where values from the `depth` dimension are moved in spatial blocks to the `height` and `width` dimensions. The attr `block_size` indicates the input block size and how the data is moved. * Chunks of data of size `block_size * block_size` from depth are rearranged into non-overlapping blocks of size `block_size x block_size` * The width the output tensor is `input_depth * block_size`, whereas the height is `input_height * block_size`. * The Y, X coordinates within each block of the output image are determined by the high order component of the input channel index. * The depth of the input tensor must be divisible by `block_size * block_size`. The `data_format` attr specifies the layout of the input and output tensors with the following options: "NHWC": `[ batch, height, width, channels ]` "NCHW": `[ batch, channels, height, width ]` "NCHW_VECT_C": `qint8 [ batch, channels / 4, height, width, 4 ]` It is useful to consider the operation as transforming a 6-D Tensor. e.g. for data_format = NHWC, Each element in the input tensor can be specified via 6 coordinates, ordered by decreasing memory layout significance as: n,iY,iX,bY,bX,oC (where n=batch index, iX, iY means X or Y coordinates within the input image, bX, bY means coordinates within the output block, oC means output channels). The output would be the input transposed to the following layout: n,iY,bY,iX,bX,oC This operation is useful for resizing the activations between convolutions (but keeping all data), e.g. instead of pooling. It is also useful for training purely convolutional models. For example, given an input of shape `[1, 1, 1, 4]`, data_format = "NHWC" and block_size = 2: ``` x = [[[[1, 2, 3, 4]]]] ``` This operation will output a tensor of shape `[1, 2, 2, 1]`: ``` [[[[1], [2]], [[3], [4]]]] ``` Here, the input has a batch of 1 and each batch element has shape `[1, 1, 4]`, the corresponding output will have 2x2 elements and will have a depth of 1 channel (1 = `4 / (block_size * block_size)`). The output element shape is `[2, 2, 1]`. For an input tensor with larger depth, here of shape `[1, 1, 1, 12]`, e.g. ``` x = [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] ``` This operation, for block size of 2, will return the following tensor of shape `[1, 2, 2, 3]` ``` [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] ``` Similarly, for the following input of shape `[1 2 2 4]`, and a block size of 2: ``` x = [[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]] ``` the operator will return the following tensor of shape `[1 4 4 1]`: ``` x = [[[ [1], [2], [5], [6]], [ [3], [4], [7], [8]], [ [9], [10], [13], [14]], [ [11], [12], [15], [16]]]] ``` Args: input: A `Tensor`. block_size: An `int` that is `>= 2`. The size of the spatial block, same as in Space2Depth. data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "DepthToSpace", name, _ctx._post_execution_callbacks, input, "block_size", block_size, "data_format", data_format) return _result except _core._FallbackException: try: return depth_to_space_eager_fallback( input, block_size=block_size, data_format=data_format, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. block_size = _execute.make_int(block_size, "block_size") if data_format is None: data_format = "NHWC" data_format = _execute.make_str(data_format, "data_format") _, _, _op = _op_def_lib._apply_op_helper( "DepthToSpace", input=input, block_size=block_size, data_format=data_format, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "block_size", _op.get_attr("block_size"), "data_format", _op.get_attr("data_format")) _execute.record_gradient( "DepthToSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result def depth_to_space_eager_fallback(input, block_size, data_format="NHWC", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function depth_to_space """ _ctx = ctx if ctx else _context.context() block_size = _execute.make_int(block_size, "block_size") if data_format is None: data_format = "NHWC" data_format = _execute.make_str(data_format, "data_format") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "block_size", block_size, "data_format", data_format) _result = _execute.execute(b"DepthToSpace", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "DepthToSpace", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('quantization.dequantize', v1=['quantization.dequantize', 'dequantize']) @deprecated_endpoints('dequantize') def dequantize(input, min_range, max_range, mode="MIN_COMBINED", name=None): r"""Dequantize the 'input' tensor into a float Tensor. [min_range, max_range] are scalar floats that specify the range for the 'input' data. The 'mode' attribute controls exactly which calculations are used to convert the float values to their quantized equivalents. In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: ``` if T == qint8: in[i] += (range(T) + 1)/ 2.0 out[i] = min_range + (in[i]* (max_range - min_range) / range(T)) ``` here `range(T) = numeric_limits<T>::max() - numeric_limits<T>::min()` *MIN_COMBINED Mode Example* If the input comes from a QuantizedRelu6, the output type is quint8 (range of 0-255) but the possible range of QuantizedRelu6 is 0-6. The min_range and max_range values are therefore 0.0 and 6.0. Dequantize on quint8 will take each value, cast to float, and multiply by 6 / 255. Note that if quantizedtype is qint8, the operation will additionally add each value by 128 prior to casting. If the mode is 'MIN_FIRST', then this approach is used: ```c++ num_discrete_values = 1 << (# of bits in T) range_adjust = num_discrete_values / (num_discrete_values - 1) range = (range_max - range_min) * range_adjust range_scale = range / num_discrete_values const double offset_input = static_cast<double>(input) - lowest_quantized; result = range_min + ((input - numeric_limits<T>::min()) * range_scale) ``` *SCALED mode Example* `SCALED` mode matches the quantization approach used in `QuantizeAndDequantize{V2|V3}`. If the mode is `SCALED`, we do not use the full range of the output type, choosing to elide the lowest possible value for symmetry (e.g., output range is -127 to 127, not -128 to 127 for signed 8 bit quantization), so that 0.0 maps to 0. We first find the range of values in our tensor. The range we use is always centered on 0, so we find m such that ```c++ m = max(abs(input_min), abs(input_max)) ``` Our input tensor range is then `[-m, m]`. Next, we choose our fixed-point quantization buckets, `[min_fixed, max_fixed]`. If T is signed, this is ``` num_bits = sizeof(T) * 8 [min_fixed, max_fixed] = [-(1 << (num_bits - 1) - 1), (1 << (num_bits - 1)) - 1] ``` Otherwise, if T is unsigned, the fixed-point range is ``` [min_fixed, max_fixed] = [0, (1 << num_bits) - 1] ``` From this we compute our scaling factor, s: ```c++ s = (2 * m) / (max_fixed - min_fixed) ``` Now we can dequantize the elements of our tensor: ```c++ result = input * s ``` Args: input: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. min_range: A `Tensor` of type `float32`. The minimum scalar value possibly produced for the input. max_range: A `Tensor` of type `float32`. The maximum scalar value possibly produced for the input. mode: An optional `string` from: `"MIN_COMBINED", "MIN_FIRST", "SCALED"`. Defaults to `"MIN_COMBINED"`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Dequantize", name, _ctx._post_execution_callbacks, input, min_range, max_range, "mode", mode) return _result except _core._FallbackException: try: return dequantize_eager_fallback( input, min_range, max_range, mode=mode, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( dequantize, input=input, min_range=min_range, max_range=max_range, mode=mode, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if mode is None: mode = "MIN_COMBINED" mode = _execute.make_str(mode, "mode") try: _, _, _op = _op_def_lib._apply_op_helper( "Dequantize", input=input, min_range=min_range, max_range=max_range, mode=mode, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( dequantize, input=input, min_range=min_range, max_range=max_range, mode=mode, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "mode", _op.get_attr("mode")) _execute.record_gradient( "Dequantize", _inputs_flat, _attrs, _result, name) _result, = _result return _result def dequantize_eager_fallback(input, min_range, max_range, mode="MIN_COMBINED", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function dequantize """ _ctx = ctx if ctx else _context.context() if mode is None: mode = "MIN_COMBINED" mode = _execute.make_str(mode, "mode") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) min_range = _ops.convert_to_tensor(min_range, _dtypes.float32) max_range = _ops.convert_to_tensor(max_range, _dtypes.float32) _inputs_flat = [input, min_range, max_range] _attrs = ("T", _attr_T, "mode", mode) _result = _execute.execute(b"Dequantize", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Dequantize", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.tensor_diag', v1=['linalg.tensor_diag', 'diag']) @deprecated_endpoints('diag') def diag(diagonal, name=None): r"""Returns a diagonal tensor with a given diagonal values. Given a `diagonal`, this operation returns a tensor with the `diagonal` and everything else padded with zeros. The diagonal is computed as follows: Assume `diagonal` has dimensions [D1,..., Dk], then the output is a tensor of rank 2k with dimensions [D1,..., Dk, D1,..., Dk] where: `output[i1,..., ik, i1,..., ik] = diagonal[i1, ..., ik]` and 0 everywhere else. For example: ``` # 'diagonal' is [1, 2, 3, 4] tf.diag(diagonal) ==> [[1, 0, 0, 0] [0, 2, 0, 0] [0, 0, 3, 0] [0, 0, 0, 4]] ``` Args: diagonal: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. Rank k tensor where k is at most 1. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `diagonal`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Diag", name, _ctx._post_execution_callbacks, diagonal) return _result except _core._FallbackException: try: return diag_eager_fallback( diagonal, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( diag, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "Diag", diagonal=diagonal, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( diag, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Diag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def diag_eager_fallback(diagonal, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function diag """ _ctx = ctx if ctx else _context.context() _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], _ctx) _inputs_flat = [diagonal] _attrs = ("T", _attr_T) _result = _execute.execute(b"Diag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Diag", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.tensor_diag_part', v1=['linalg.tensor_diag_part', 'diag_part']) @deprecated_endpoints('diag_part') def diag_part(input, name=None): r"""Returns the diagonal part of the tensor. This operation returns a tensor with the `diagonal` part of the `input`. The `diagonal` part is computed as follows: Assume `input` has dimensions `[D1,..., Dk, D1,..., Dk]`, then the output is a tensor of rank `k` with dimensions `[D1,..., Dk]` where: `diagonal[i1,..., ik] = input[i1, ..., ik, i1,..., ik]`. For example: ``` # 'input' is [[1, 0, 0, 0] [0, 2, 0, 0] [0, 0, 3, 0] [0, 0, 0, 4]] tf.diag_part(input) ==> [1, 2, 3, 4] ``` Args: input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`. Rank k tensor where k is even and not zero. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "DiagPart", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return diag_part_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( diag_part, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "DiagPart", input=input, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( diag_part, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "DiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def diag_part_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function diag_part """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"DiagPart", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "DiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def edit_distance(hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape, normalize=True, name=None): r"""Computes the (possibly normalized) Levenshtein Edit Distance. The inputs are variable-length sequences provided by SparseTensors (hypothesis_indices, hypothesis_values, hypothesis_shape) and (truth_indices, truth_values, truth_shape). The inputs are: Args: hypothesis_indices: A `Tensor` of type `int64`. The indices of the hypothesis list SparseTensor. This is an N x R int64 matrix. hypothesis_values: A `Tensor`. The values of the hypothesis list SparseTensor. This is an N-length vector. hypothesis_shape: A `Tensor` of type `int64`. The shape of the hypothesis list SparseTensor. This is an R-length vector. truth_indices: A `Tensor` of type `int64`. The indices of the truth list SparseTensor. This is an M x R int64 matrix. truth_values: A `Tensor`. Must have the same type as `hypothesis_values`. The values of the truth list SparseTensor. This is an M-length vector. truth_shape: A `Tensor` of type `int64`. truth indices, vector. normalize: An optional `bool`. Defaults to `True`. boolean (if true, edit distances are normalized by length of truth). The output is: name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "EditDistance", name, _ctx._post_execution_callbacks, hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape, "normalize", normalize) return _result except _core._FallbackException: try: return edit_distance_eager_fallback( hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape, normalize=normalize, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if normalize is None: normalize = True normalize = _execute.make_bool(normalize, "normalize") _, _, _op = _op_def_lib._apply_op_helper( "EditDistance", hypothesis_indices=hypothesis_indices, hypothesis_values=hypothesis_values, hypothesis_shape=hypothesis_shape, truth_indices=truth_indices, truth_values=truth_values, truth_shape=truth_shape, normalize=normalize, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("normalize", _op.get_attr("normalize"), "T", _op.get_attr("T")) _execute.record_gradient( "EditDistance", _inputs_flat, _attrs, _result, name) _result, = _result return _result def edit_distance_eager_fallback(hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape, normalize=True, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function edit_distance """ _ctx = ctx if ctx else _context.context() if normalize is None: normalize = True normalize = _execute.make_bool(normalize, "normalize") _attr_T, _inputs_T = _execute.args_to_matching_eager([hypothesis_values, truth_values], _ctx) (hypothesis_values, truth_values) = _inputs_T hypothesis_indices = _ops.convert_to_tensor(hypothesis_indices, _dtypes.int64) hypothesis_shape = _ops.convert_to_tensor(hypothesis_shape, _dtypes.int64) truth_indices = _ops.convert_to_tensor(truth_indices, _dtypes.int64) truth_shape = _ops.convert_to_tensor(truth_shape, _dtypes.int64) _inputs_flat = [hypothesis_indices, hypothesis_values, hypothesis_shape, truth_indices, truth_values, truth_shape] _attrs = ("normalize", normalize, "T", _attr_T) _result = _execute.execute(b"EditDistance", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "EditDistance", _inputs_flat, _attrs, _result, name) _result, = _result return _result def empty(shape, dtype, init=False, name=None): r"""Creates a tensor with the given shape. This operation creates a tensor of `shape` and `dtype`. Args: shape: A `Tensor` of type `int32`. 1-D. Represents the shape of the output tensor. dtype: A `tf.DType`. init: An optional `bool`. Defaults to `False`. If True, initialize the returned tensor with the default value of dtype. Otherwise, the implementation is free not to initializethe tensor's content. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Empty", name, _ctx._post_execution_callbacks, shape, "dtype", dtype, "init", init) return _result except _core._FallbackException: try: return empty_eager_fallback( shape, dtype=dtype, init=init, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. dtype = _execute.make_type(dtype, "dtype") if init is None: init = False init = _execute.make_bool(init, "init") _, _, _op = _op_def_lib._apply_op_helper( "Empty", shape=shape, dtype=dtype, init=init, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "init", _op.get_attr("init")) _execute.record_gradient( "Empty", _inputs_flat, _attrs, _result, name) _result, = _result return _result def empty_eager_fallback(shape, dtype, init=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function empty """ _ctx = ctx if ctx else _context.context() dtype = _execute.make_type(dtype, "dtype") if init is None: init = False init = _execute.make_bool(init, "init") shape = _ops.convert_to_tensor(shape, _dtypes.int32) _inputs_flat = [shape] _attrs = ("dtype", dtype, "init", init) _result = _execute.execute(b"Empty", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Empty", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ensure_shape(input, shape, name=None): r"""Ensures that the tensor's shape matches the expected shape. Raises an error if the input tensor's shape does not match the specified shape. Returns the input tensor otherwise. Args: input: A `Tensor`. A tensor, whose shape is to be validated. shape: A `tf.TensorShape` or list of `ints`. The expected (possibly partially specified) shape of the input tensor. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "EnsureShape", name, _ctx._post_execution_callbacks, input, "shape", shape) return _result except _core._FallbackException: try: return ensure_shape_eager_fallback( input, shape=shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "EnsureShape", input=input, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("shape", _op.get_attr("shape"), "T", _op.get_attr("T")) _execute.record_gradient( "EnsureShape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ensure_shape_eager_fallback(input, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function ensure_shape """ _ctx = ctx if ctx else _context.context() shape = _execute.make_shape(shape, "shape") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("shape", shape, "T", _attr_T) _result = _execute.execute(b"EnsureShape", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "EnsureShape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def expand_dims(input, axis, name=None): r"""Inserts a dimension of 1 into a tensor's shape. Given a tensor `input`, this operation inserts a dimension of 1 at the dimension index `axis` of `input`'s shape. The dimension index `axis` starts at zero; if you specify a negative number for `axis` it is counted backward from the end. This operation is useful if you want to add a batch dimension to a single element. For example, if you have a single image of shape `[height, width, channels]`, you can make it a batch of 1 image with `expand_dims(image, 0)`, which will make the shape `[1, height, width, channels]`. Other examples: ``` # 't' is a tensor of shape [2] shape(expand_dims(t, 0)) ==> [1, 2] shape(expand_dims(t, 1)) ==> [2, 1] shape(expand_dims(t, -1)) ==> [2, 1] # 't2' is a tensor of shape [2, 3, 5] shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5] shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5] shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1] ``` This operation requires that: `-1-input.dims() <= dim <= input.dims()` This operation is related to `squeeze()`, which removes dimensions of size 1. Args: input: A `Tensor`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. 0-D (scalar). Specifies the dimension index at which to expand the shape of `input`. Must be in the range `[-rank(input) - 1, rank(input)]`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ExpandDims", name, _ctx._post_execution_callbacks, input, axis) return _result except _core._FallbackException: try: return expand_dims_eager_fallback( input, axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "ExpandDims", input=input, dim=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tdim", _op.get_attr("Tdim")) _execute.record_gradient( "ExpandDims", _inputs_flat, _attrs, _result, name) _result, = _result return _result def expand_dims_eager_fallback(input, axis, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function expand_dims """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tdim, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _inputs_flat = [input, axis] _attrs = ("T", _attr_T, "Tdim", _attr_Tdim) _result = _execute.execute(b"ExpandDims", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ExpandDims", _inputs_flat, _attrs, _result, name) _result, = _result return _result def extract_image_patches(images, ksizes, strides, rates, padding, name=None): r"""Extract `patches` from `images` and put them in the "depth" output dimension. Args: images: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. ksizes: A list of `ints` that has length `>= 4`. The size of the sliding window for each dimension of `images`. strides: A list of `ints` that has length `>= 4`. 1-D of length 4. How far the centers of two consecutive patches are in the images. Must be: `[1, stride_rows, stride_cols, 1]`. rates: A list of `ints` that has length `>= 4`. 1-D of length 4. Must be: `[1, rate_rows, rate_cols, 1]`. This is the input stride, specifying how far two consecutive patch samples are in the input. Equivalent to extracting patches with `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling them spatially by a factor of `rates`. This is equivalent to `rate` in dilated (a.k.a. Atrous) convolutions. padding: A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. We specify the size-related attributes as: ```python ksizes = [1, ksize_rows, ksize_cols, 1] strides = [1, strides_rows, strides_cols, 1] rates = [1, rates_rows, rates_cols, 1] ``` name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `images`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ExtractImagePatches", name, _ctx._post_execution_callbacks, images, "ksizes", ksizes, "strides", strides, "rates", rates, "padding", padding) return _result except _core._FallbackException: try: return extract_image_patches_eager_fallback( images, ksizes=ksizes, strides=strides, rates=rates, padding=padding, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(ksizes, (list, tuple)): raise TypeError( "Expected list for 'ksizes' argument to " "'extract_image_patches' Op, not %r." % ksizes) ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] if not isinstance(strides, (list, tuple)): raise TypeError( "Expected list for 'strides' argument to " "'extract_image_patches' Op, not %r." % strides) strides = [_execute.make_int(_i, "strides") for _i in strides] if not isinstance(rates, (list, tuple)): raise TypeError( "Expected list for 'rates' argument to " "'extract_image_patches' Op, not %r." % rates) rates = [_execute.make_int(_i, "rates") for _i in rates] padding = _execute.make_str(padding, "padding") _, _, _op = _op_def_lib._apply_op_helper( "ExtractImagePatches", images=images, ksizes=ksizes, strides=strides, rates=rates, padding=padding, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("ksizes", _op.get_attr("ksizes"), "strides", _op.get_attr("strides"), "rates", _op.get_attr("rates"), "T", _op.get_attr("T"), "padding", _op.get_attr("padding")) _execute.record_gradient( "ExtractImagePatches", _inputs_flat, _attrs, _result, name) _result, = _result return _result def extract_image_patches_eager_fallback(images, ksizes, strides, rates, padding, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function extract_image_patches """ _ctx = ctx if ctx else _context.context() if not isinstance(ksizes, (list, tuple)): raise TypeError( "Expected list for 'ksizes' argument to " "'extract_image_patches' Op, not %r." % ksizes) ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] if not isinstance(strides, (list, tuple)): raise TypeError( "Expected list for 'strides' argument to " "'extract_image_patches' Op, not %r." % strides) strides = [_execute.make_int(_i, "strides") for _i in strides] if not isinstance(rates, (list, tuple)): raise TypeError( "Expected list for 'rates' argument to " "'extract_image_patches' Op, not %r." % rates) rates = [_execute.make_int(_i, "rates") for _i in rates] padding = _execute.make_str(padding, "padding") _attr_T, (images,) = _execute.args_to_matching_eager([images], _ctx) _inputs_flat = [images] _attrs = ("ksizes", ksizes, "strides", strides, "rates", rates, "T", _attr_T, "padding", padding) _result = _execute.execute(b"ExtractImagePatches", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ExtractImagePatches", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('extract_volume_patches') def extract_volume_patches(input, ksizes, strides, padding, name=None): r"""Extract `patches` from `input` and put them in the "depth" output dimension. 3D extension of `extract_image_patches`. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. 5-D Tensor with shape `[batch, in_planes, in_rows, in_cols, depth]`. ksizes: A list of `ints` that has length `>= 5`. The size of the sliding window for each dimension of `input`. strides: A list of `ints` that has length `>= 5`. 1-D of length 5. How far the centers of two consecutive patches are in `input`. Must be: `[1, stride_planes, stride_rows, stride_cols, 1]`. padding: A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. We specify the size-related attributes as: ```python ksizes = [1, ksize_planes, ksize_rows, ksize_cols, 1] strides = [1, stride_planes, strides_rows, strides_cols, 1] ``` name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ExtractVolumePatches", name, _ctx._post_execution_callbacks, input, "ksizes", ksizes, "strides", strides, "padding", padding) return _result except _core._FallbackException: try: return extract_volume_patches_eager_fallback( input, ksizes=ksizes, strides=strides, padding=padding, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( extract_volume_patches, input=input, ksizes=ksizes, strides=strides, padding=padding, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(ksizes, (list, tuple)): raise TypeError( "Expected list for 'ksizes' argument to " "'extract_volume_patches' Op, not %r." % ksizes) ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] if not isinstance(strides, (list, tuple)): raise TypeError( "Expected list for 'strides' argument to " "'extract_volume_patches' Op, not %r." % strides) strides = [_execute.make_int(_i, "strides") for _i in strides] padding = _execute.make_str(padding, "padding") try: _, _, _op = _op_def_lib._apply_op_helper( "ExtractVolumePatches", input=input, ksizes=ksizes, strides=strides, padding=padding, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( extract_volume_patches, input=input, ksizes=ksizes, strides=strides, padding=padding, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("ksizes", _op.get_attr("ksizes"), "strides", _op.get_attr("strides"), "T", _op.get_attr("T"), "padding", _op.get_attr("padding")) _execute.record_gradient( "ExtractVolumePatches", _inputs_flat, _attrs, _result, name) _result, = _result return _result def extract_volume_patches_eager_fallback(input, ksizes, strides, padding, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function extract_volume_patches """ _ctx = ctx if ctx else _context.context() if not isinstance(ksizes, (list, tuple)): raise TypeError( "Expected list for 'ksizes' argument to " "'extract_volume_patches' Op, not %r." % ksizes) ksizes = [_execute.make_int(_i, "ksizes") for _i in ksizes] if not isinstance(strides, (list, tuple)): raise TypeError( "Expected list for 'strides' argument to " "'extract_volume_patches' Op, not %r." % strides) strides = [_execute.make_int(_i, "strides") for _i in strides] padding = _execute.make_str(padding, "padding") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("ksizes", ksizes, "strides", strides, "T", _attr_T, "padding", padding) _result = _execute.execute(b"ExtractVolumePatches", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ExtractVolumePatches", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_args', v1=['quantization.fake_quant_with_min_max_args', 'fake_quant_with_min_max_args']) @deprecated_endpoints('fake_quant_with_min_max_args') def fake_quant_with_min_max_args(inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None): r"""Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. Attributes `[min; max]` define the clamping range for the `inputs` data. `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and then de-quantized and output as floats in `[min; max]` interval. `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. Quantization is called fake since the output is still in floating point. Args: inputs: A `Tensor` of type `float32`. min: An optional `float`. Defaults to `-6`. max: An optional `float`. Defaults to `6`. num_bits: An optional `int`. Defaults to `8`. narrow_range: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxArgs", name, _ctx._post_execution_callbacks, inputs, "min", min, "max", max, "num_bits", num_bits, "narrow_range", narrow_range) return _result except _core._FallbackException: try: return fake_quant_with_min_max_args_eager_fallback( inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_args, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if min is None: min = -6 min = _execute.make_float(min, "min") if max is None: max = 6 max = _execute.make_float(max, "max") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxArgs", inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_args, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("min", _op.get_attr("min"), "max", _op.get_attr("max"), "num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxArgs", _inputs_flat, _attrs, _result, name) _result, = _result return _result def fake_quant_with_min_max_args_eager_fallback(inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_args """ _ctx = ctx if ctx else _context.context() if min is None: min = -6 min = _execute.make_float(min, "min") if max is None: max = 6 max = _execute.make_float(max, "max") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) _inputs_flat = [inputs] _attrs = ("min", min, "max", max, "num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxArgs", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxArgs", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_args_gradient', v1=['quantization.fake_quant_with_min_max_args_gradient', 'fake_quant_with_min_max_args_gradient']) @deprecated_endpoints('fake_quant_with_min_max_args_gradient') def fake_quant_with_min_max_args_gradient(gradients, inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None): r"""Compute gradients for a FakeQuantWithMinMaxArgs operation. Args: gradients: A `Tensor` of type `float32`. Backpropagated gradients above the FakeQuantWithMinMaxArgs operation. inputs: A `Tensor` of type `float32`. Values passed as inputs to the FakeQuantWithMinMaxArgs operation. min: An optional `float`. Defaults to `-6`. max: An optional `float`. Defaults to `6`. num_bits: An optional `int`. Defaults to `8`. narrow_range: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxArgsGradient", name, _ctx._post_execution_callbacks, gradients, inputs, "min", min, "max", max, "num_bits", num_bits, "narrow_range", narrow_range) return _result except _core._FallbackException: try: return fake_quant_with_min_max_args_gradient_eager_fallback( gradients, inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_args_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if min is None: min = -6 min = _execute.make_float(min, "min") if max is None: max = 6 max = _execute.make_float(max, "max") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxArgsGradient", gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_args_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("min", _op.get_attr("min"), "max", _op.get_attr("max"), "num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxArgsGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result def fake_quant_with_min_max_args_gradient_eager_fallback(gradients, inputs, min=-6, max=6, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_args_gradient """ _ctx = ctx if ctx else _context.context() if min is None: min = -6 min = _execute.make_float(min, "min") if max is None: max = 6 max = _execute.make_float(max, "max") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) _inputs_flat = [gradients, inputs] _attrs = ("min", min, "max", max, "num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxArgsGradient", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxArgsGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_vars', v1=['quantization.fake_quant_with_min_max_vars', 'fake_quant_with_min_max_vars']) @deprecated_endpoints('fake_quant_with_min_max_vars') def fake_quant_with_min_max_vars(inputs, min, max, num_bits=8, narrow_range=False, name=None): r"""Fake-quantize the 'inputs' tensor of type float via global float scalars `min` and `max` to 'outputs' tensor of same shape as `inputs`. `[min; max]` define the clamping range for the `inputs` data. `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and then de-quantized and output as floats in `[min; max]` interval. `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. This operation has a gradient and thus allows for training `min` and `max` values. Args: inputs: A `Tensor` of type `float32`. min: A `Tensor` of type `float32`. max: A `Tensor` of type `float32`. num_bits: An optional `int`. Defaults to `8`. narrow_range: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxVars", name, _ctx._post_execution_callbacks, inputs, min, max, "num_bits", num_bits, "narrow_range", narrow_range) return _result except _core._FallbackException: try: return fake_quant_with_min_max_vars_eager_fallback( inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxVars", inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxVars", _inputs_flat, _attrs, _result, name) _result, = _result return _result def fake_quant_with_min_max_vars_eager_fallback(inputs, min, max, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_vars """ _ctx = ctx if ctx else _context.context() if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) min = _ops.convert_to_tensor(min, _dtypes.float32) max = _ops.convert_to_tensor(max, _dtypes.float32) _inputs_flat = [inputs, min, max] _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxVars", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxVars", _inputs_flat, _attrs, _result, name) _result, = _result return _result _fake_quant_with_min_max_vars_gradient_outputs = ["backprops_wrt_input", "backprop_wrt_min", "backprop_wrt_max"] _FakeQuantWithMinMaxVarsGradientOutput = _collections.namedtuple( "FakeQuantWithMinMaxVarsGradient", _fake_quant_with_min_max_vars_gradient_outputs) @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_vars_gradient', v1=['quantization.fake_quant_with_min_max_vars_gradient', 'fake_quant_with_min_max_vars_gradient']) @deprecated_endpoints('fake_quant_with_min_max_vars_gradient') def fake_quant_with_min_max_vars_gradient(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None): r"""Compute gradients for a FakeQuantWithMinMaxVars operation. Args: gradients: A `Tensor` of type `float32`. Backpropagated gradients above the FakeQuantWithMinMaxVars operation. inputs: A `Tensor` of type `float32`. Values passed as inputs to the FakeQuantWithMinMaxVars operation. min, max: Quantization interval, scalar floats. min: A `Tensor` of type `float32`. max: A `Tensor` of type `float32`. num_bits: An optional `int`. Defaults to `8`. The bitwidth of the quantization; between 2 and 8, inclusive. narrow_range: An optional `bool`. Defaults to `False`. Whether to quantize into 2^num_bits - 1 distinct values. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). backprops_wrt_input: A `Tensor` of type `float32`. backprop_wrt_min: A `Tensor` of type `float32`. backprop_wrt_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxVarsGradient", name, _ctx._post_execution_callbacks, gradients, inputs, min, max, "num_bits", num_bits, "narrow_range", narrow_range) _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) return _result except _core._FallbackException: try: return fake_quant_with_min_max_vars_gradient_eager_fallback( gradients, inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxVarsGradient", gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxVarsGradient", _inputs_flat, _attrs, _result, name) _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) return _result def fake_quant_with_min_max_vars_gradient_eager_fallback(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_vars_gradient """ _ctx = ctx if ctx else _context.context() if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) min = _ops.convert_to_tensor(min, _dtypes.float32) max = _ops.convert_to_tensor(max, _dtypes.float32) _inputs_flat = [gradients, inputs, min, max] _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxVarsGradient", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxVarsGradient", _inputs_flat, _attrs, _result, name) _result = _FakeQuantWithMinMaxVarsGradientOutput._make(_result) return _result @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_vars_per_channel', v1=['quantization.fake_quant_with_min_max_vars_per_channel', 'fake_quant_with_min_max_vars_per_channel']) @deprecated_endpoints('fake_quant_with_min_max_vars_per_channel') def fake_quant_with_min_max_vars_per_channel(inputs, min, max, num_bits=8, narrow_range=False, name=None): r"""Fake-quantize the 'inputs' tensor of type float and one of the shapes: `[d]`, `[b, d]` `[b, h, w, d]` via per-channel floats `min` and `max` of shape `[d]` to 'outputs' tensor of same shape as `inputs`. `[min; max]` define the clamping range for the `inputs` data. `inputs` values are quantized into the quantization range (`[0; 2^num_bits - 1]` when `narrow_range` is false and `[1; 2^num_bits - 1]` when it is true) and then de-quantized and output as floats in `[min; max]` interval. `num_bits` is the bitwidth of the quantization; between 2 and 16, inclusive. This operation has a gradient and thus allows for training `min` and `max` values. Args: inputs: A `Tensor` of type `float32`. min: A `Tensor` of type `float32`. max: A `Tensor` of type `float32`. num_bits: An optional `int`. Defaults to `8`. narrow_range: An optional `bool`. Defaults to `False`. name: A name for the operation (optional). Returns: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxVarsPerChannel", name, _ctx._post_execution_callbacks, inputs, min, max, "num_bits", num_bits, "narrow_range", narrow_range) return _result except _core._FallbackException: try: return fake_quant_with_min_max_vars_per_channel_eager_fallback( inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_per_channel, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxVarsPerChannel", inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_per_channel, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxVarsPerChannel", _inputs_flat, _attrs, _result, name) _result, = _result return _result def fake_quant_with_min_max_vars_per_channel_eager_fallback(inputs, min, max, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_vars_per_channel """ _ctx = ctx if ctx else _context.context() if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) min = _ops.convert_to_tensor(min, _dtypes.float32) max = _ops.convert_to_tensor(max, _dtypes.float32) _inputs_flat = [inputs, min, max] _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxVarsPerChannel", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxVarsPerChannel", _inputs_flat, _attrs, _result, name) _result, = _result return _result _fake_quant_with_min_max_vars_per_channel_gradient_outputs = ["backprops_wrt_input", "backprop_wrt_min", "backprop_wrt_max"] _FakeQuantWithMinMaxVarsPerChannelGradientOutput = _collections.namedtuple( "FakeQuantWithMinMaxVarsPerChannelGradient", _fake_quant_with_min_max_vars_per_channel_gradient_outputs) @_dispatch.add_dispatch_list @tf_export('quantization.fake_quant_with_min_max_vars_per_channel_gradient', v1=['quantization.fake_quant_with_min_max_vars_per_channel_gradient', 'fake_quant_with_min_max_vars_per_channel_gradient']) @deprecated_endpoints('fake_quant_with_min_max_vars_per_channel_gradient') def fake_quant_with_min_max_vars_per_channel_gradient(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None): r"""Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation. Args: gradients: A `Tensor` of type `float32`. Backpropagated gradients above the FakeQuantWithMinMaxVars operation, shape one of: `[d]`, `[b, d]`, `[b, h, w, d]`. inputs: A `Tensor` of type `float32`. Values passed as inputs to the FakeQuantWithMinMaxVars operation, shape same as `gradients`. min, max: Quantization interval, floats of shape `[d]`. min: A `Tensor` of type `float32`. max: A `Tensor` of type `float32`. num_bits: An optional `int`. Defaults to `8`. The bitwidth of the quantization; between 2 and 16, inclusive. narrow_range: An optional `bool`. Defaults to `False`. Whether to quantize into 2^num_bits - 1 distinct values. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (backprops_wrt_input, backprop_wrt_min, backprop_wrt_max). backprops_wrt_input: A `Tensor` of type `float32`. backprop_wrt_min: A `Tensor` of type `float32`. backprop_wrt_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "FakeQuantWithMinMaxVarsPerChannelGradient", name, _ctx._post_execution_callbacks, gradients, inputs, min, max, "num_bits", num_bits, "narrow_range", narrow_range) _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) return _result except _core._FallbackException: try: return fake_quant_with_min_max_vars_per_channel_gradient_eager_fallback( gradients, inputs, min, max, num_bits=num_bits, narrow_range=narrow_range, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_per_channel_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") try: _, _, _op = _op_def_lib._apply_op_helper( "FakeQuantWithMinMaxVarsPerChannelGradient", gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fake_quant_with_min_max_vars_per_channel_gradient, gradients=gradients, inputs=inputs, min=min, max=max, num_bits=num_bits, narrow_range=narrow_range, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_bits", _op.get_attr("num_bits"), "narrow_range", _op.get_attr("narrow_range")) _execute.record_gradient( "FakeQuantWithMinMaxVarsPerChannelGradient", _inputs_flat, _attrs, _result, name) _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) return _result def fake_quant_with_min_max_vars_per_channel_gradient_eager_fallback(gradients, inputs, min, max, num_bits=8, narrow_range=False, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fake_quant_with_min_max_vars_per_channel_gradient """ _ctx = ctx if ctx else _context.context() if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if narrow_range is None: narrow_range = False narrow_range = _execute.make_bool(narrow_range, "narrow_range") gradients = _ops.convert_to_tensor(gradients, _dtypes.float32) inputs = _ops.convert_to_tensor(inputs, _dtypes.float32) min = _ops.convert_to_tensor(min, _dtypes.float32) max = _ops.convert_to_tensor(max, _dtypes.float32) _inputs_flat = [gradients, inputs, min, max] _attrs = ("num_bits", num_bits, "narrow_range", narrow_range) _result = _execute.execute(b"FakeQuantWithMinMaxVarsPerChannelGradient", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "FakeQuantWithMinMaxVarsPerChannelGradient", _inputs_flat, _attrs, _result, name) _result = _FakeQuantWithMinMaxVarsPerChannelGradientOutput._make(_result) return _result @_dispatch.add_dispatch_list @tf_export('fill') def fill(dims, value, name=None): r"""Creates a tensor filled with a scalar value. This operation creates a tensor of shape `dims` and fills it with `value`. For example: ``` # Output tensor has shape [2, 3]. fill([2, 3], 9) ==> [[9, 9, 9] [9, 9, 9]] ``` `tf.fill` differs from `tf.constant` in a few ways: * `tf.fill` only supports scalar contents, whereas `tf.constant` supports Tensor values. * `tf.fill` creates an Op in the computation graph that constructs the actual Tensor value at runtime. This is in contrast to `tf.constant` which embeds the entire Tensor into the graph with a `Const` node. * Because `tf.fill` evaluates at graph runtime, it supports dynamic shapes based on other runtime Tensors, unlike `tf.constant`. Args: dims: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D. Represents the shape of the output tensor. value: A `Tensor`. 0-D (scalar). Value to fill the returned tensor. @compatibility(numpy) Equivalent to np.full @end_compatibility name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `value`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Fill", name, _ctx._post_execution_callbacks, dims, value) return _result except _core._FallbackException: try: return fill_eager_fallback( dims, value, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( fill, dims=dims, value=value, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "Fill", dims=dims, value=value, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( fill, dims=dims, value=value, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "index_type", _op.get_attr("index_type")) _execute.record_gradient( "Fill", _inputs_flat, _attrs, _result, name) _result, = _result return _result def fill_eager_fallback(dims, value, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function fill """ _ctx = ctx if ctx else _context.context() _attr_T, (value,) = _execute.args_to_matching_eager([value], _ctx) _attr_index_type, (dims,) = _execute.args_to_matching_eager([dims], _ctx, _dtypes.int32) _inputs_flat = [dims, value] _attrs = ("T", _attr_T, "index_type", _attr_index_type) _result = _execute.execute(b"Fill", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Fill", _inputs_flat, _attrs, _result, name) _result, = _result return _result def gather(params, indices, validate_indices=True, name=None): r"""Gather slices from `params` according to `indices`. `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). Produces an output tensor with shape `indices.shape + params.shape[1:]` where: ```python # Scalar indices output[:, ..., :] = params[indices, :, ... :] # Vector indices output[i, :, ..., :] = params[indices[i], :, ... :] # Higher rank indices output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :] ``` If `indices` is a permutation and `len(indices) == params.shape[0]` then this operation will permute `params` accordingly. `validate_indices`: DEPRECATED. If this operation is assigned to CPU, values in `indices` are always validated to be within range. If assigned to GPU, out-of-bound indices result in safe but unspecified behavior, which may include raising an error. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/Gather.png" alt> </div> Args: params: A `Tensor`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. validate_indices: An optional `bool`. Defaults to `True`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `params`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Gather", name, _ctx._post_execution_callbacks, params, indices, "validate_indices", validate_indices) return _result except _core._FallbackException: try: return gather_eager_fallback( params, indices, validate_indices=validate_indices, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if validate_indices is None: validate_indices = True validate_indices = _execute.make_bool(validate_indices, "validate_indices") _, _, _op = _op_def_lib._apply_op_helper( "Gather", params=params, indices=indices, validate_indices=validate_indices, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("validate_indices", _op.get_attr("validate_indices"), "Tparams", _op.get_attr("Tparams"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "Gather", _inputs_flat, _attrs, _result, name) _result, = _result return _result def gather_eager_fallback(params, indices, validate_indices=True, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function gather """ _ctx = ctx if ctx else _context.context() if validate_indices is None: validate_indices = True validate_indices = _execute.make_bool(validate_indices, "validate_indices") _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], _ctx) _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [params, indices] _attrs = ("validate_indices", validate_indices, "Tparams", _attr_Tparams, "Tindices", _attr_Tindices) _result = _execute.execute(b"Gather", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Gather", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('gather_nd', v1=['gather_nd', 'manip.gather_nd']) @deprecated_endpoints('manip.gather_nd') def gather_nd(params, indices, name=None): r"""Gather slices from `params` into a Tensor with shape specified by `indices`. `indices` is an K-dimensional integer tensor, best thought of as a (K-1)-dimensional tensor of indices into `params`, where each element defines a slice of `params`: output[\\(i_0, ..., i_{K-2}\\)] = params[indices[\\(i_0, ..., i_{K-2}\\)]] Whereas in `tf.gather` `indices` defines slices into the first dimension of `params`, in `tf.gather_nd`, `indices` defines slices into the first `N` dimensions of `params`, where `N = indices.shape[-1]`. The last dimension of `indices` can be at most the rank of `params`: indices.shape[-1] <= params.rank The last dimension of `indices` corresponds to elements (if `indices.shape[-1] == params.rank`) or slices (if `indices.shape[-1] < params.rank`) along dimension `indices.shape[-1]` of `params`. The output tensor has shape indices.shape[:-1] + params.shape[indices.shape[-1]:] Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, a 0 is stored in the corresponding output value. Some examples below. Simple indexing into a matrix: ```python indices = [[0, 0], [1, 1]] params = [['a', 'b'], ['c', 'd']] output = ['a', 'd'] ``` Slice indexing into a matrix: ```python indices = [[1], [0]] params = [['a', 'b'], ['c', 'd']] output = [['c', 'd'], ['a', 'b']] ``` Indexing into a 3-tensor: ```python indices = [[1]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [[['a1', 'b1'], ['c1', 'd1']]] indices = [[0, 1], [1, 0]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [['c0', 'd0'], ['a1', 'b1']] indices = [[0, 0, 1], [1, 0, 1]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = ['b0', 'b1'] ``` Batched indexing into a matrix: ```python indices = [[[0, 0]], [[0, 1]]] params = [['a', 'b'], ['c', 'd']] output = [['a'], ['b']] ``` Batched slice indexing into a matrix: ```python indices = [[[1]], [[0]]] params = [['a', 'b'], ['c', 'd']] output = [[['c', 'd']], [['a', 'b']]] ``` Batched indexing into a 3-tensor: ```python indices = [[[1]], [[0]]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [[[['a1', 'b1'], ['c1', 'd1']]], [[['a0', 'b0'], ['c0', 'd0']]]] indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [[['c0', 'd0'], ['a1', 'b1']], [['a0', 'b0'], ['c1', 'd1']]] indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]] params = [[['a0', 'b0'], ['c0', 'd0']], [['a1', 'b1'], ['c1', 'd1']]] output = [['b0', 'b1'], ['d0', 'c1']] ``` See also `tf.gather` and `tf.batch_gather`. Args: params: A `Tensor`. The tensor from which to gather values. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `params`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "GatherNd", name, _ctx._post_execution_callbacks, params, indices) return _result except _core._FallbackException: try: return gather_nd_eager_fallback( params, indices, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( gather_nd, params=params, indices=indices, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "GatherNd", params=params, indices=indices, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( gather_nd, params=params, indices=indices, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tparams", _op.get_attr("Tparams"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "GatherNd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def gather_nd_eager_fallback(params, indices, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function gather_nd """ _ctx = ctx if ctx else _context.context() _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], _ctx) _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [params, indices] _attrs = ("Tparams", _attr_Tparams, "Tindices", _attr_Tindices) _result = _execute.execute(b"GatherNd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "GatherNd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def gather_v2(params, indices, axis, name=None): r"""Gather slices from `params` axis `axis` according to `indices`. `indices` must be an integer tensor of any dimension (usually 0-D or 1-D). Produces an output tensor with shape `params.shape[:axis] + indices.shape + params.shape[axis + 1:]` where: ```python # Scalar indices (output is rank(params) - 1). output[a_0, ..., a_n, b_0, ..., b_n] = params[a_0, ..., a_n, indices, b_0, ..., b_n] # Vector indices (output is rank(params)). output[a_0, ..., a_n, i, b_0, ..., b_n] = params[a_0, ..., a_n, indices[i], b_0, ..., b_n] # Higher rank indices (output is rank(params) + rank(indices) - 1). output[a_0, ..., a_n, i, ..., j, b_0, ... b_n] = params[a_0, ..., a_n, indices[i, ..., j], b_0, ..., b_n] ``` <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/Gather.png" alt> </div> Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, a 0 is stored in the corresponding output value. See also `tf.batch_gather` and `tf.gather_nd`. Args: params: A `Tensor`. The tensor from which to gather values. Must be at least rank `axis + 1`. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. Must be in range `[0, params.shape[axis])`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. The axis in `params` to gather `indices` from. Defaults to the first dimension. Supports negative indexes. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `params`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "GatherV2", name, _ctx._post_execution_callbacks, params, indices, axis) return _result except _core._FallbackException: try: return gather_v2_eager_fallback( params, indices, axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "GatherV2", params=params, indices=indices, axis=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tparams", _op.get_attr("Tparams"), "Tindices", _op.get_attr("Tindices"), "Taxis", _op.get_attr("Taxis")) _execute.record_gradient( "GatherV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def gather_v2_eager_fallback(params, indices, axis, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function gather_v2 """ _ctx = ctx if ctx else _context.context() _attr_Tparams, (params,) = _execute.args_to_matching_eager([params], _ctx) _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], _ctx) _inputs_flat = [params, indices, axis] _attrs = ("Tparams", _attr_Tparams, "Tindices", _attr_Tindices, "Taxis", _attr_Taxis) _result = _execute.execute(b"GatherV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "GatherV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('guarantee_const') def guarantee_const(input, name=None): r"""Gives a guarantee to the TF runtime that the input tensor is a constant. The runtime is then free to make optimizations based on this. Only accepts value typed tensors as inputs and rejects resource variable handles as input. Returns the input tensor without modification. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "GuaranteeConst", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return guarantee_const_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( guarantee_const, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "GuaranteeConst", input=input, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( guarantee_const, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "GuaranteeConst", _inputs_flat, _attrs, _result, name) _result, = _result return _result def guarantee_const_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function guarantee_const """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"GuaranteeConst", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "GuaranteeConst", _inputs_flat, _attrs, _result, name) _result, = _result return _result def identity(input, name=None): r"""Return a tensor with the same shape and contents as the input tensor or value. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Identity", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return identity_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Identity", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Identity", _inputs_flat, _attrs, _result, name) _result, = _result return _result def identity_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function identity """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"Identity", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Identity", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('identity_n') def identity_n(input, name=None): r"""Returns a list of tensors with the same shapes and contents as the input tensors. This op can be used to override the gradient for complicated functions. For example, suppose y = f(x) and we wish to apply a custom function g for backprop such that dx = g(dy). In Python, ```python with tf.get_default_graph().gradient_override_map( {'IdentityN': 'OverrideGradientWithG'}): y, _ = identity_n([f(x), x]) @tf.RegisterGradient('OverrideGradientWithG') def ApplyG(op, dy, _): return [None, g(dy)] # Do not backprop to f(x). ``` Args: input: A list of `Tensor` objects. name: A name for the operation (optional). Returns: A list of `Tensor` objects. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "IdentityN", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return identity_n_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( identity_n, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "IdentityN", input=input, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( identity_n, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "IdentityN", _inputs_flat, _attrs, _result, name) return _result def identity_n_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function identity_n """ _ctx = ctx if ctx else _context.context() _attr_T, input = _execute.convert_to_mixed_eager_tensors(input, _ctx) _inputs_flat = list(input) _attrs = ("T", _attr_T) _result = _execute.execute(b"IdentityN", len(input), inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "IdentityN", _inputs_flat, _attrs, _result, name) return _result def immutable_const(dtype, shape, memory_region_name, name=None): r"""Returns immutable tensor from memory region. The current implementation memmaps the tensor from a file. Args: dtype: A `tf.DType`. Type of the returned tensor. shape: A `tf.TensorShape` or list of `ints`. Shape of the returned tensor. memory_region_name: A `string`. Name of readonly memory region used by the tensor, see NewReadOnlyMemoryRegionFromFile in tensorflow::Env. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ImmutableConst", name, _ctx._post_execution_callbacks, "dtype", dtype, "shape", shape, "memory_region_name", memory_region_name) return _result except _core._FallbackException: try: return immutable_const_eager_fallback( dtype=dtype, shape=shape, memory_region_name=memory_region_name, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. dtype = _execute.make_type(dtype, "dtype") shape = _execute.make_shape(shape, "shape") memory_region_name = _execute.make_str(memory_region_name, "memory_region_name") _, _, _op = _op_def_lib._apply_op_helper( "ImmutableConst", dtype=dtype, shape=shape, memory_region_name=memory_region_name, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "shape", _op.get_attr("shape"), "memory_region_name", _op.get_attr("memory_region_name")) _execute.record_gradient( "ImmutableConst", _inputs_flat, _attrs, _result, name) _result, = _result return _result def immutable_const_eager_fallback(dtype, shape, memory_region_name, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function immutable_const """ _ctx = ctx if ctx else _context.context() dtype = _execute.make_type(dtype, "dtype") shape = _execute.make_shape(shape, "shape") memory_region_name = _execute.make_str(memory_region_name, "memory_region_name") _inputs_flat = [] _attrs = ("dtype", dtype, "shape", shape, "memory_region_name", memory_region_name) _result = _execute.execute(b"ImmutableConst", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ImmutableConst", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_add(x, i, v, name=None): r""" Adds v into specified rows of x. Computes y = x; y[i, :] += v; return y. Args: x: A `Tensor`. A `Tensor` of type T. i: A `Tensor` of type `int32`. A vector. Indices into the left-most dimension of `x`. v: A `Tensor`. Must have the same type as `x`. A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "InplaceAdd", name, _ctx._post_execution_callbacks, x, i, v) return _result except _core._FallbackException: try: return inplace_add_eager_fallback( x, i, v, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "InplaceAdd", x=x, i=i, v=v, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "InplaceAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_add_eager_fallback(x, i, v, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function inplace_add """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], _ctx) (x, v) = _inputs_T i = _ops.convert_to_tensor(i, _dtypes.int32) _inputs_flat = [x, i, v] _attrs = ("T", _attr_T) _result = _execute.execute(b"InplaceAdd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "InplaceAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_sub(x, i, v, name=None): r""" Subtracts `v` into specified rows of `x`. Computes y = x; y[i, :] -= v; return y. Args: x: A `Tensor`. A `Tensor` of type T. i: A `Tensor` of type `int32`. A vector. Indices into the left-most dimension of `x`. v: A `Tensor`. Must have the same type as `x`. A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "InplaceSub", name, _ctx._post_execution_callbacks, x, i, v) return _result except _core._FallbackException: try: return inplace_sub_eager_fallback( x, i, v, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "InplaceSub", x=x, i=i, v=v, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "InplaceSub", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_sub_eager_fallback(x, i, v, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function inplace_sub """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], _ctx) (x, v) = _inputs_T i = _ops.convert_to_tensor(i, _dtypes.int32) _inputs_flat = [x, i, v] _attrs = ("T", _attr_T) _result = _execute.execute(b"InplaceSub", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "InplaceSub", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_update(x, i, v, name=None): r""" Updates specified rows with values in `v`. Computes `x[i, :] = v; return x`. Args: x: A `Tensor`. A tensor of type `T`. i: A `Tensor` of type `int32`. A vector. Indices into the left-most dimension of `x`. v: A `Tensor`. Must have the same type as `x`. A `Tensor` of type T. Same dimension sizes as x except the first dimension, which must be the same as i's size. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "InplaceUpdate", name, _ctx._post_execution_callbacks, x, i, v) return _result except _core._FallbackException: try: return inplace_update_eager_fallback( x, i, v, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "InplaceUpdate", x=x, i=i, v=v, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "InplaceUpdate", _inputs_flat, _attrs, _result, name) _result, = _result return _result def inplace_update_eager_fallback(x, i, v, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function inplace_update """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([x, v], _ctx) (x, v) = _inputs_T i = _ops.convert_to_tensor(i, _dtypes.int32) _inputs_flat = [x, i, v] _attrs = ("T", _attr_T) _result = _execute.execute(b"InplaceUpdate", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "InplaceUpdate", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('math.invert_permutation', v1=['math.invert_permutation', 'invert_permutation']) @deprecated_endpoints('invert_permutation') def invert_permutation(x, name=None): r"""Computes the inverse permutation of a tensor. This operation computes the inverse of an index permutation. It takes a 1-D integer tensor `x`, which represents the indices of a zero-based array, and swaps each value with its index position. In other words, for an output tensor `y` and an input tensor `x`, this operation computes the following: `y[x[i]] = i for i in [0, 1, ..., len(x) - 1]` The values must include 0. There can be no duplicate values or negative values. For example: ``` # tensor `x` is [3, 4, 0, 2, 1] invert_permutation(x) ==> [2, 4, 3, 0, 1] ``` Args: x: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "InvertPermutation", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: try: return invert_permutation_eager_fallback( x, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( invert_permutation, x=x, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "InvertPermutation", x=x, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( invert_permutation, x=x, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "InvertPermutation", _inputs_flat, _attrs, _result, name) _result, = _result return _result def invert_permutation_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function invert_permutation """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx, _dtypes.int32) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"InvertPermutation", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "InvertPermutation", _inputs_flat, _attrs, _result, name) _result, = _result return _result _list_diff_outputs = ["out", "idx"] _ListDiffOutput = _collections.namedtuple( "ListDiff", _list_diff_outputs) def list_diff(x, y, out_idx=_dtypes.int32, name=None): r"""Computes the difference between two lists of numbers or strings. Given a list `x` and a list `y`, this operation returns a list `out` that represents all values that are in `x` but not in `y`. The returned list `out` is sorted in the same order that the numbers appear in `x` (duplicates are preserved). This operation also returns a list `idx` that represents the position of each `out` element in `x`. In other words: `out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]` For example, given this input: ``` x = [1, 2, 3, 4, 5, 6] y = [1, 3, 5] ``` This operation would return: ``` out ==> [2, 4, 6] idx ==> [1, 3, 5] ``` Args: x: A `Tensor`. 1-D. Values to keep. y: A `Tensor`. Must have the same type as `x`. 1-D. Values to remove. out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (out, idx). out: A `Tensor`. Has the same type as `x`. idx: A `Tensor` of type `out_idx`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ListDiff", name, _ctx._post_execution_callbacks, x, y, "out_idx", out_idx) _result = _ListDiffOutput._make(_result) return _result except _core._FallbackException: try: return list_diff_eager_fallback( x, y, out_idx=out_idx, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _, _, _op = _op_def_lib._apply_op_helper( "ListDiff", x=x, y=y, out_idx=out_idx, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_idx", _op.get_attr("out_idx")) _execute.record_gradient( "ListDiff", _inputs_flat, _attrs, _result, name) _result = _ListDiffOutput._make(_result) return _result def list_diff_eager_fallback(x, y, out_idx=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function list_diff """ _ctx = ctx if ctx else _context.context() if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _attr_T, _inputs_T = _execute.args_to_matching_eager([x, y], _ctx) (x, y) = _inputs_T _inputs_flat = [x, y] _attrs = ("T", _attr_T, "out_idx", out_idx) _result = _execute.execute(b"ListDiff", 2, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ListDiff", _inputs_flat, _attrs, _result, name) _result = _ListDiffOutput._make(_result) return _result def lower_bound(sorted_inputs, values, out_type=_dtypes.int32, name=None): r"""Applies lower_bound(sorted_search_values, values) along each row. Each set of rows with the same index in (sorted_inputs, values) is treated independently. The resulting row is the equivalent of calling `np.searchsorted(sorted_inputs, values, side='left')`. The result is not a global index to the entire `Tensor`, but rather just the index in the last dimension. A 2-D example: sorted_sequence = [[0, 3, 9, 9, 10], [1, 2, 3, 4, 5]] values = [[2, 4, 9], [0, 2, 6]] result = LowerBound(sorted_sequence, values) result == [[1, 2, 2], [0, 1, 5]] Args: sorted_inputs: A `Tensor`. 2-D Tensor where each row is ordered. values: A `Tensor`. Must have the same type as `sorted_inputs`. 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains the values that will be searched for in `sorted_search_values`. out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A `Tensor` of type `out_type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "LowerBound", name, _ctx._post_execution_callbacks, sorted_inputs, values, "out_type", out_type) return _result except _core._FallbackException: try: return lower_bound_eager_fallback( sorted_inputs, values, out_type=out_type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "LowerBound", sorted_inputs=sorted_inputs, values=values, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "LowerBound", _inputs_flat, _attrs, _result, name) _result, = _result return _result def lower_bound_eager_fallback(sorted_inputs, values, out_type=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function lower_bound """ _ctx = ctx if ctx else _context.context() if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _attr_T, _inputs_T = _execute.args_to_matching_eager([sorted_inputs, values], _ctx) (sorted_inputs, values) = _inputs_T _inputs_flat = [sorted_inputs, values] _attrs = ("T", _attr_T, "out_type", out_type) _result = _execute.execute(b"LowerBound", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "LowerBound", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.band_part', v1=['linalg.band_part', 'matrix_band_part']) @deprecated_endpoints('matrix_band_part') def matrix_band_part(input, num_lower, num_upper, name=None): r"""Copy a tensor setting everything outside a central band in each innermost matrix to zero. The `band` part is computed as follows: Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a tensor with the same shape where `band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]`. The indicator function `in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && (num_upper < 0 || (n-m) <= num_upper)`. For example: ``` # if 'input' is [[ 0, 1, 2, 3] [-1, 0, 1, 2] [-2, -1, 0, 1] [-3, -2, -1, 0]], tf.matrix_band_part(input, 1, -1) ==> [[ 0, 1, 2, 3] [-1, 0, 1, 2] [ 0, -1, 0, 1] [ 0, 0, -1, 0]], tf.matrix_band_part(input, 2, 1) ==> [[ 0, 1, 0, 0] [-1, 0, 1, 0] [-2, -1, 0, 1] [ 0, -2, -1, 0]] ``` Useful special cases: ``` tf.matrix_band_part(input, 0, -1) ==> Upper triangular part. tf.matrix_band_part(input, -1, 0) ==> Lower triangular part. tf.matrix_band_part(input, 0, 0) ==> Diagonal. ``` Args: input: A `Tensor`. Rank `k` tensor. num_lower: A `Tensor`. Must be one of the following types: `int32`, `int64`. 0-D tensor. Number of subdiagonals to keep. If negative, keep entire lower triangle. num_upper: A `Tensor`. Must have the same type as `num_lower`. 0-D tensor. Number of superdiagonals to keep. If negative, keep entire upper triangle. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MatrixBandPart", name, _ctx._post_execution_callbacks, input, num_lower, num_upper) return _result except _core._FallbackException: try: return matrix_band_part_eager_fallback( input, num_lower, num_upper, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( matrix_band_part, input=input, num_lower=num_lower, num_upper=num_upper, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "MatrixBandPart", input=input, num_lower=num_lower, num_upper=num_upper, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( matrix_band_part, input=input, num_lower=num_lower, num_upper=num_upper, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindex", _op.get_attr("Tindex")) _execute.record_gradient( "MatrixBandPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def matrix_band_part_eager_fallback(input, num_lower, num_upper, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function matrix_band_part """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tindex, _inputs_Tindex = _execute.args_to_matching_eager([num_lower, num_upper], _ctx, _dtypes.int64) (num_lower, num_upper) = _inputs_Tindex _inputs_flat = [input, num_lower, num_upper] _attrs = ("T", _attr_T, "Tindex", _attr_Tindex) _result = _execute.execute(b"MatrixBandPart", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MatrixBandPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.diag', v1=['linalg.diag', 'matrix_diag']) @deprecated_endpoints('matrix_diag') def matrix_diag(diagonal, name=None): r"""Returns a batched diagonal tensor with a given batched diagonal values. Given a `diagonal`, this operation returns a tensor with the `diagonal` and everything else padded with zeros. The diagonal is computed as follows: Assume `diagonal` has `k` dimensions `[I, J, K, ..., N]`, then the output is a tensor of rank `k+1` with dimensions [I, J, K, ..., N, N]` where: `output[i, j, k, ..., m, n] = 1{m=n} * diagonal[i, j, k, ..., n]`. For example: ``` # 'diagonal' is [[1, 2, 3, 4], [5, 6, 7, 8]] and diagonal.shape = (2, 4) tf.matrix_diag(diagonal) ==> [[[1, 0, 0, 0] [0, 2, 0, 0] [0, 0, 3, 0] [0, 0, 0, 4]], [[5, 0, 0, 0] [0, 6, 0, 0] [0, 0, 7, 0] [0, 0, 0, 8]]] which has shape (2, 4, 4) ``` Args: diagonal: A `Tensor`. Rank `k`, where `k >= 1`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `diagonal`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MatrixDiag", name, _ctx._post_execution_callbacks, diagonal) return _result except _core._FallbackException: try: return matrix_diag_eager_fallback( diagonal, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( matrix_diag, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "MatrixDiag", diagonal=diagonal, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( matrix_diag, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "MatrixDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def matrix_diag_eager_fallback(diagonal, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function matrix_diag """ _ctx = ctx if ctx else _context.context() _attr_T, (diagonal,) = _execute.args_to_matching_eager([diagonal], _ctx) _inputs_flat = [diagonal] _attrs = ("T", _attr_T) _result = _execute.execute(b"MatrixDiag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MatrixDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.diag_part', v1=['linalg.diag_part', 'matrix_diag_part']) @deprecated_endpoints('matrix_diag_part') def matrix_diag_part(input, name=None): r"""Returns the batched diagonal part of a batched tensor. This operation returns a tensor with the `diagonal` part of the batched `input`. The `diagonal` part is computed as follows: Assume `input` has `k` dimensions `[I, J, K, ..., M, N]`, then the output is a tensor of rank `k - 1` with dimensions `[I, J, K, ..., min(M, N)]` where: `diagonal[i, j, k, ..., n] = input[i, j, k, ..., n, n]`. The input must be at least a matrix. For example: ``` # 'input' is [[[1, 0, 0, 0] [0, 2, 0, 0] [0, 0, 3, 0] [0, 0, 0, 4]], [[5, 0, 0, 0] [0, 6, 0, 0] [0, 0, 7, 0] [0, 0, 0, 8]]] and input.shape = (2, 4, 4) tf.matrix_diag_part(input) ==> [[1, 2, 3, 4], [5, 6, 7, 8]] which has shape (2, 4) ``` Args: input: A `Tensor`. Rank `k` tensor where `k >= 2`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MatrixDiagPart", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return matrix_diag_part_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( matrix_diag_part, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "MatrixDiagPart", input=input, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( matrix_diag_part, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "MatrixDiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result def matrix_diag_part_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function matrix_diag_part """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"MatrixDiagPart", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MatrixDiagPart", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('linalg.set_diag', v1=['linalg.set_diag', 'matrix_set_diag']) @deprecated_endpoints('matrix_set_diag') def matrix_set_diag(input, diagonal, name=None): r"""Returns a batched matrix tensor with new batched diagonal values. Given `input` and `diagonal`, this operation returns a tensor with the same shape and values as `input`, except for the main diagonal of the innermost matrices. These will be overwritten by the values in `diagonal`. The output is computed as follows: Assume `input` has `k+1` dimensions `[I, J, K, ..., M, N]` and `diagonal` has `k` dimensions `[I, J, K, ..., min(M, N)]`. Then the output is a tensor of rank `k+1` with dimensions `[I, J, K, ..., M, N]` where: * `output[i, j, k, ..., m, n] = diagonal[i, j, k, ..., n]` for `m == n`. * `output[i, j, k, ..., m, n] = input[i, j, k, ..., m, n]` for `m != n`. Args: input: A `Tensor`. Rank `k+1`, where `k >= 1`. diagonal: A `Tensor`. Must have the same type as `input`. Rank `k`, where `k >= 1`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MatrixSetDiag", name, _ctx._post_execution_callbacks, input, diagonal) return _result except _core._FallbackException: try: return matrix_set_diag_eager_fallback( input, diagonal, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( matrix_set_diag, input=input, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "MatrixSetDiag", input=input, diagonal=diagonal, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( matrix_set_diag, input=input, diagonal=diagonal, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "MatrixSetDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def matrix_set_diag_eager_fallback(input, diagonal, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function matrix_set_diag """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([input, diagonal], _ctx) (input, diagonal) = _inputs_T _inputs_flat = [input, diagonal] _attrs = ("T", _attr_T) _result = _execute.execute(b"MatrixSetDiag", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MatrixSetDiag", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mirror_pad(input, paddings, mode, name=None): r"""Pads a tensor with mirrored values. This operation pads a `input` with mirrored values according to the `paddings` you specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates how many values to add before the contents of `input` in that dimension, and `paddings[D, 1]` indicates how many values to add after the contents of `input` in that dimension. Both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than `input.dim_size(D)` (or `input.dim_size(D) - 1`) if `copy_border` is true (if false, respectively). The padded size of each dimension D of the output is: `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` For example: ``` # 't' is [[1, 2, 3], [4, 5, 6]]. # 'paddings' is [[1, 1]], [2, 2]]. # 'mode' is SYMMETRIC. # rank of 't' is 2. pad(t, paddings) ==> [[2, 1, 1, 2, 3, 3, 2] [2, 1, 1, 2, 3, 3, 2] [5, 4, 4, 5, 6, 6, 5] [5, 4, 4, 5, 6, 6, 5]] ``` Args: input: A `Tensor`. The input tensor to be padded. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. A two-column matrix specifying the padding sizes. The number of rows must be the same as the rank of `input`. mode: A `string` from: `"REFLECT", "SYMMETRIC"`. Either `REFLECT` or `SYMMETRIC`. In reflect mode the padded regions do not include the borders, while in symmetric mode the padded regions do include the borders. For example, if `input` is `[1, 2, 3]` and `paddings` is `[0, 2]`, then the output is `[1, 2, 3, 2, 1]` in reflect mode, and it is `[1, 2, 3, 3, 2]` in symmetric mode. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MirrorPad", name, _ctx._post_execution_callbacks, input, paddings, "mode", mode) return _result except _core._FallbackException: try: return mirror_pad_eager_fallback( input, paddings, mode=mode, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. mode = _execute.make_str(mode, "mode") _, _, _op = _op_def_lib._apply_op_helper( "MirrorPad", input=input, paddings=paddings, mode=mode, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tpaddings", _op.get_attr("Tpaddings"), "mode", _op.get_attr("mode")) _execute.record_gradient( "MirrorPad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mirror_pad_eager_fallback(input, paddings, mode, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mirror_pad """ _ctx = ctx if ctx else _context.context() mode = _execute.make_str(mode, "mode") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, paddings] _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "mode", mode) _result = _execute.execute(b"MirrorPad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MirrorPad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mirror_pad_grad(input, paddings, mode, name=None): r"""Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor. This operation folds the padded areas of `input` by `MirrorPad` according to the `paddings` you specify. `paddings` must be the same as `paddings` argument given to the corresponding `MirrorPad` op. The folded size of each dimension D of the output is: `input.dim_size(D) - paddings(D, 0) - paddings(D, 1)` For example: ``` # 't' is [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. # 'paddings' is [[0, 1]], [0, 1]]. # 'mode' is SYMMETRIC. # rank of 't' is 2. pad(t, paddings) ==> [[ 1, 5] [11, 28]] ``` Args: input: A `Tensor`. The input tensor to be folded. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. A two-column matrix specifying the padding sizes. The number of rows must be the same as the rank of `input`. mode: A `string` from: `"REFLECT", "SYMMETRIC"`. The mode used in the `MirrorPad` op. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "MirrorPadGrad", name, _ctx._post_execution_callbacks, input, paddings, "mode", mode) return _result except _core._FallbackException: try: return mirror_pad_grad_eager_fallback( input, paddings, mode=mode, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. mode = _execute.make_str(mode, "mode") _, _, _op = _op_def_lib._apply_op_helper( "MirrorPadGrad", input=input, paddings=paddings, mode=mode, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tpaddings", _op.get_attr("Tpaddings"), "mode", _op.get_attr("mode")) _execute.record_gradient( "MirrorPadGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def mirror_pad_grad_eager_fallback(input, paddings, mode, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function mirror_pad_grad """ _ctx = ctx if ctx else _context.context() mode = _execute.make_str(mode, "mode") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, paddings] _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "mode", mode) _result = _execute.execute(b"MirrorPadGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "MirrorPadGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def one_hot(indices, depth, on_value, off_value, axis=-1, name=None): r"""Returns a one-hot tensor. The locations represented by indices in `indices` take value `on_value`, while all other locations take value `off_value`. If the input `indices` is rank `N`, the output will have rank `N+1`, The new axis is created at dimension `axis` (default: the new axis is appended at the end). If `indices` is a scalar the output shape will be a vector of length `depth`. If `indices` is a vector of length `features`, the output shape will be: ``` features x depth if axis == -1 depth x features if axis == 0 ``` If `indices` is a matrix (batch) with shape `[batch, features]`, the output shape will be: ``` batch x features x depth if axis == -1 batch x depth x features if axis == 1 depth x batch x features if axis == 0 ``` Examples ========= Suppose that ``` indices = [0, 2, -1, 1] depth = 3 on_value = 5.0 off_value = 0.0 axis = -1 ``` Then output is `[4 x 3]`: ``` output = [5.0 0.0 0.0] // one_hot(0) [0.0 0.0 5.0] // one_hot(2) [0.0 0.0 0.0] // one_hot(-1) [0.0 5.0 0.0] // one_hot(1) ``` Suppose that ``` indices = [0, 2, -1, 1] depth = 3 on_value = 0.0 off_value = 3.0 axis = 0 ``` Then output is `[3 x 4]`: ``` output = [0.0 3.0 3.0 3.0] [3.0 3.0 3.0 0.0] [3.0 3.0 3.0 3.0] [3.0 0.0 3.0 3.0] // ^ one_hot(0) // ^ one_hot(2) // ^ one_hot(-1) // ^ one_hot(1) ``` Suppose that ``` indices = [[0, 2], [1, -1]] depth = 3 on_value = 1.0 off_value = 0.0 axis = -1 ``` Then output is `[2 x 2 x 3]`: ``` output = [ [1.0, 0.0, 0.0] // one_hot(0) [0.0, 0.0, 1.0] // one_hot(2) ][ [0.0, 1.0, 0.0] // one_hot(1) [0.0, 0.0, 0.0] // one_hot(-1) ] ``` Args: indices: A `Tensor`. Must be one of the following types: `uint8`, `int32`, `int64`. A tensor of indices. depth: A `Tensor` of type `int32`. A scalar defining the depth of the one hot dimension. on_value: A `Tensor`. A scalar defining the value to fill in output when `indices[j] = i`. off_value: A `Tensor`. Must have the same type as `on_value`. A scalar defining the value to fill in output when `indices[j] != i`. axis: An optional `int`. Defaults to `-1`. The axis to fill (default: -1, a new inner-most axis). name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `on_value`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "OneHot", name, _ctx._post_execution_callbacks, indices, depth, on_value, off_value, "axis", axis) return _result except _core._FallbackException: try: return one_hot_eager_fallback( indices, depth, on_value, off_value, axis=axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if axis is None: axis = -1 axis = _execute.make_int(axis, "axis") _, _, _op = _op_def_lib._apply_op_helper( "OneHot", indices=indices, depth=depth, on_value=on_value, off_value=off_value, axis=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("axis", _op.get_attr("axis"), "T", _op.get_attr("T"), "TI", _op.get_attr("TI")) _execute.record_gradient( "OneHot", _inputs_flat, _attrs, _result, name) _result, = _result return _result def one_hot_eager_fallback(indices, depth, on_value, off_value, axis=-1, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function one_hot """ _ctx = ctx if ctx else _context.context() if axis is None: axis = -1 axis = _execute.make_int(axis, "axis") _attr_T, _inputs_T = _execute.args_to_matching_eager([on_value, off_value], _ctx) (on_value, off_value) = _inputs_T _attr_TI, (indices,) = _execute.args_to_matching_eager([indices], _ctx, _dtypes.int64) depth = _ops.convert_to_tensor(depth, _dtypes.int32) _inputs_flat = [indices, depth, on_value, off_value] _attrs = ("axis", axis, "T", _attr_T, "TI", _attr_TI) _result = _execute.execute(b"OneHot", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "OneHot", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ones_like(x, name=None): r"""Returns a tensor of ones with the same shape and type as x. Args: x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `complex64`, `complex128`, `bool`. a tensor of type T. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "OnesLike", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: try: return ones_like_eager_fallback( x, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "OnesLike", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "OnesLike", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ones_like_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function ones_like """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"OnesLike", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "OnesLike", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pack(values, axis=0, name=None): r"""Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor. Packs the `N` tensors in `values` into a tensor with rank one higher than each tensor in `values`, by packing them along the `axis` dimension. Given a list of tensors of shape `(A, B, C)`; if `axis == 0` then the `output` tensor will have the shape `(N, A, B, C)`. if `axis == 1` then the `output` tensor will have the shape `(A, N, B, C)`. Etc. For example: ``` # 'x' is [1, 4] # 'y' is [2, 5] # 'z' is [3, 6] pack([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. pack([x, y, z], axis=1) => [[1, 2, 3], [4, 5, 6]] ``` This is the opposite of `unpack`. Args: values: A list of at least 1 `Tensor` objects with the same type. Must be of same shape and type. axis: An optional `int`. Defaults to `0`. Dimension along which to pack. Negative values wrap around, so the valid range is `[-(R+1), R+1)`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `values`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Pack", name, _ctx._post_execution_callbacks, values, "axis", axis) return _result except _core._FallbackException: try: return pack_eager_fallback( values, axis=axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'pack' Op, not %r." % values) _attr_N = len(values) if axis is None: axis = 0 axis = _execute.make_int(axis, "axis") _, _, _op = _op_def_lib._apply_op_helper( "Pack", values=values, axis=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T"), "axis", _op.get_attr("axis")) _execute.record_gradient( "Pack", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pack_eager_fallback(values, axis=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function pack """ _ctx = ctx if ctx else _context.context() if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'pack' Op, not %r." % values) _attr_N = len(values) if axis is None: axis = 0 axis = _execute.make_int(axis, "axis") _attr_T, values = _execute.args_to_matching_eager(list(values), _ctx) _inputs_flat = list(values) _attrs = ("N", _attr_N, "T", _attr_T, "axis", axis) _result = _execute.execute(b"Pack", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Pack", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pad(input, paddings, name=None): r"""Pads a tensor with zeros. This operation pads a `input` with zeros according to the `paddings` you specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates how many zeros to add before the contents of `input` in that dimension, and `paddings[D, 1]` indicates how many zeros to add after the contents of `input` in that dimension. The padded size of each dimension D of the output is: `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` For example: ``` # 't' is [[1, 1], [2, 2]] # 'paddings' is [[1, 1], [2, 2]] # rank of 't' is 2 pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] [0, 0, 1, 1, 0, 0] [0, 0, 2, 2, 0, 0] [0, 0, 0, 0, 0, 0]] ``` Args: input: A `Tensor`. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Pad", name, _ctx._post_execution_callbacks, input, paddings) return _result except _core._FallbackException: try: return pad_eager_fallback( input, paddings, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Pad", input=input, paddings=paddings, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tpaddings", _op.get_attr("Tpaddings")) _execute.record_gradient( "Pad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pad_eager_fallback(input, paddings, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function pad """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, paddings] _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings) _result = _execute.execute(b"Pad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Pad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pad_v2(input, paddings, constant_values, name=None): r"""Pads a tensor. This operation pads `input` according to the `paddings` and `constant_values` you specify. `paddings` is an integer tensor with shape `[Dn, 2]`, where n is the rank of `input`. For each dimension D of `input`, `paddings[D, 0]` indicates how many padding values to add before the contents of `input` in that dimension, and `paddings[D, 1]` indicates how many padding values to add after the contents of `input` in that dimension. `constant_values` is a scalar tensor of the same type as `input` that indicates the value to use for padding `input`. The padded size of each dimension D of the output is: `paddings(D, 0) + input.dim_size(D) + paddings(D, 1)` For example: ``` # 't' is [[1, 1], [2, 2]] # 'paddings' is [[1, 1], [2, 2]] # 'constant_values' is 0 # rank of 't' is 2 pad(t, paddings) ==> [[0, 0, 0, 0, 0, 0] [0, 0, 1, 1, 0, 0] [0, 0, 2, 2, 0, 0] [0, 0, 0, 0, 0, 0]] ``` Args: input: A `Tensor`. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. constant_values: A `Tensor`. Must have the same type as `input`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "PadV2", name, _ctx._post_execution_callbacks, input, paddings, constant_values) return _result except _core._FallbackException: try: return pad_v2_eager_fallback( input, paddings, constant_values, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "PadV2", input=input, paddings=paddings, constant_values=constant_values, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tpaddings", _op.get_attr("Tpaddings")) _execute.record_gradient( "PadV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def pad_v2_eager_fallback(input, paddings, constant_values, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function pad_v2 """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([input, constant_values], _ctx) (input, constant_values) = _inputs_T _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, paddings, constant_values] _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings) _result = _execute.execute(b"PadV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "PadV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def parallel_concat(values, shape, name=None): r"""Concatenates a list of `N` tensors along the first dimension. The input tensors are all required to have size 1 in the first dimension. For example: ``` # 'x' is [[1, 4]] # 'y' is [[2, 5]] # 'z' is [[3, 6]] parallel_concat([x, y, z]) => [[1, 4], [2, 5], [3, 6]] # Pack along first dim. ``` The difference between concat and parallel_concat is that concat requires all of the inputs be computed before the operation will begin but doesn't require that the input shapes be known during graph construction. Parallel concat will copy pieces of the input into the output as they become available, in some situations this can provide a performance benefit. Args: values: A list of at least 1 `Tensor` objects with the same type. Tensors to be concatenated. All must have size 1 in the first dimension and same shape. shape: A `tf.TensorShape` or list of `ints`. the final shape of the result; should be equal to the shapes of any input but with the number of input values in the first dimension. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `values`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ParallelConcat", name, _ctx._post_execution_callbacks, values, "shape", shape) return _result except _core._FallbackException: try: return parallel_concat_eager_fallback( values, shape=shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'parallel_concat' Op, not %r." % values) _attr_N = len(values) shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "ParallelConcat", values=values, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T"), "shape", _op.get_attr("shape")) _execute.record_gradient( "ParallelConcat", _inputs_flat, _attrs, _result, name) _result, = _result return _result def parallel_concat_eager_fallback(values, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function parallel_concat """ _ctx = ctx if ctx else _context.context() if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'parallel_concat' Op, not %r." % values) _attr_N = len(values) shape = _execute.make_shape(shape, "shape") _attr_T, values = _execute.args_to_matching_eager(list(values), _ctx) _inputs_flat = list(values) _attrs = ("N", _attr_N, "T", _attr_T, "shape", shape) _result = _execute.execute(b"ParallelConcat", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ParallelConcat", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder(dtype, shape=None, name=None): r"""A placeholder op for a value that will be fed into the computation. N.B. This operation will fail with an error if it is executed. It is intended as a way to represent a value that will always be fed, and to provide attrs that enable the fed value to be checked at runtime. Args: dtype: A `tf.DType`. The type of elements in the tensor. shape: An optional `tf.TensorShape` or list of `ints`. Defaults to `None`. (Optional) The shape of the tensor. If the shape has 0 dimensions, the shape is unconstrained. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Placeholder", name, _ctx._post_execution_callbacks, "dtype", dtype, "shape", shape) return _result except _core._FallbackException: try: return placeholder_eager_fallback( dtype=dtype, shape=shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. dtype = _execute.make_type(dtype, "dtype") if shape is None: shape = None shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "Placeholder", dtype=dtype, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "shape", _op.get_attr("shape")) _execute.record_gradient( "Placeholder", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder_eager_fallback(dtype, shape=None, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function placeholder """ _ctx = ctx if ctx else _context.context() dtype = _execute.make_type(dtype, "dtype") if shape is None: shape = None shape = _execute.make_shape(shape, "shape") _inputs_flat = [] _attrs = ("dtype", dtype, "shape", shape) _result = _execute.execute(b"Placeholder", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Placeholder", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder_v2(dtype, shape, name=None): r"""A placeholder op for a value that will be fed into the computation. N.B. This operation will fail with an error if it is executed. It is intended as a way to represent a value that will always be fed, and to provide attrs that enable the fed value to be checked at runtime. Args: dtype: A `tf.DType`. The type of elements in the tensor. shape: A `tf.TensorShape` or list of `ints`. The shape of the tensor. The shape can be any partially-specified shape. To be unconstrained, pass in a shape with unknown rank. name: A name for the operation (optional). Returns: A `Tensor` of type `dtype`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "PlaceholderV2", name, _ctx._post_execution_callbacks, "dtype", dtype, "shape", shape) return _result except _core._FallbackException: try: return placeholder_v2_eager_fallback( dtype=dtype, shape=shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. dtype = _execute.make_type(dtype, "dtype") shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "PlaceholderV2", dtype=dtype, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "shape", _op.get_attr("shape")) _execute.record_gradient( "PlaceholderV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder_v2_eager_fallback(dtype, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function placeholder_v2 """ _ctx = ctx if ctx else _context.context() dtype = _execute.make_type(dtype, "dtype") shape = _execute.make_shape(shape, "shape") _inputs_flat = [] _attrs = ("dtype", dtype, "shape", shape) _result = _execute.execute(b"PlaceholderV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "PlaceholderV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder_with_default(input, shape, name=None): r"""A placeholder op that passes through `input` when its output is not fed. Args: input: A `Tensor`. The default value to produce when `output` is not fed. shape: A `tf.TensorShape` or list of `ints`. The (possibly partial) shape of the tensor. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "PlaceholderWithDefault", name, _ctx._post_execution_callbacks, input, "shape", shape) return _result except _core._FallbackException: try: return placeholder_with_default_eager_fallback( input, shape=shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. shape = _execute.make_shape(shape, "shape") _, _, _op = _op_def_lib._apply_op_helper( "PlaceholderWithDefault", input=input, shape=shape, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("dtype", _op.get_attr("dtype"), "shape", _op.get_attr("shape")) _execute.record_gradient( "PlaceholderWithDefault", _inputs_flat, _attrs, _result, name) _result, = _result return _result def placeholder_with_default_eager_fallback(input, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function placeholder_with_default """ _ctx = ctx if ctx else _context.context() shape = _execute.make_shape(shape, "shape") _attr_dtype, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("dtype", _attr_dtype, "shape", shape) _result = _execute.execute(b"PlaceholderWithDefault", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "PlaceholderWithDefault", _inputs_flat, _attrs, _result, name) _result, = _result return _result def prevent_gradient(input, message="", name=None): r"""An identity op that triggers an error if a gradient is requested. When executed in a graph, this op outputs its input tensor as-is. When building ops to compute gradients, the TensorFlow gradient system will return an error when trying to lookup the gradient of this op, because no gradient must ever be registered for this function. This op exists to prevent subtle bugs from silently returning unimplemented gradients in some corner cases. Args: input: A `Tensor`. any tensor. message: An optional `string`. Defaults to `""`. Will be printed in the error when anyone tries to differentiate this operation. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "PreventGradient", name, _ctx._post_execution_callbacks, input, "message", message) return _result except _core._FallbackException: try: return prevent_gradient_eager_fallback( input, message=message, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if message is None: message = "" message = _execute.make_str(message, "message") _, _, _op = _op_def_lib._apply_op_helper( "PreventGradient", input=input, message=message, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "message", _op.get_attr("message")) _execute.record_gradient( "PreventGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result def prevent_gradient_eager_fallback(input, message="", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function prevent_gradient """ _ctx = ctx if ctx else _context.context() if message is None: message = "" message = _execute.make_str(message, "message") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "message", message) _result = _execute.execute(b"PreventGradient", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "PreventGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result def quantize_and_dequantize(input, signed_input=True, num_bits=8, range_given=False, input_min=0, input_max=0, name=None): r"""Use QuantizeAndDequantizeV2 instead. Args: input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. signed_input: An optional `bool`. Defaults to `True`. num_bits: An optional `int`. Defaults to `8`. range_given: An optional `bool`. Defaults to `False`. input_min: An optional `float`. Defaults to `0`. input_max: An optional `float`. Defaults to `0`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizeAndDequantize", name, _ctx._post_execution_callbacks, input, "signed_input", signed_input, "num_bits", num_bits, "range_given", range_given, "input_min", input_min, "input_max", input_max) return _result except _core._FallbackException: try: return quantize_and_dequantize_eager_fallback( input, signed_input=signed_input, num_bits=num_bits, range_given=range_given, input_min=input_min, input_max=input_max, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if range_given is None: range_given = False range_given = _execute.make_bool(range_given, "range_given") if input_min is None: input_min = 0 input_min = _execute.make_float(input_min, "input_min") if input_max is None: input_max = 0 input_max = _execute.make_float(input_max, "input_max") _, _, _op = _op_def_lib._apply_op_helper( "QuantizeAndDequantize", input=input, signed_input=signed_input, num_bits=num_bits, range_given=range_given, input_min=input_min, input_max=input_max, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("signed_input", _op.get_attr("signed_input"), "num_bits", _op.get_attr("num_bits"), "range_given", _op.get_attr("range_given"), "input_min", _op.get_attr("input_min"), "input_max", _op.get_attr("input_max"), "T", _op.get_attr("T")) _execute.record_gradient( "QuantizeAndDequantize", _inputs_flat, _attrs, _result, name) _result, = _result return _result def quantize_and_dequantize_eager_fallback(input, signed_input=True, num_bits=8, range_given=False, input_min=0, input_max=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantize_and_dequantize """ _ctx = ctx if ctx else _context.context() if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if range_given is None: range_given = False range_given = _execute.make_bool(range_given, "range_given") if input_min is None: input_min = 0 input_min = _execute.make_float(input_min, "input_min") if input_max is None: input_max = 0 input_max = _execute.make_float(input_max, "input_max") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("signed_input", signed_input, "num_bits", num_bits, "range_given", range_given, "input_min", input_min, "input_max", input_max, "T", _attr_T) _result = _execute.execute(b"QuantizeAndDequantize", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizeAndDequantize", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('quantization.quantize_and_dequantize') def quantize_and_dequantize_v2(input, input_min, input_max, signed_input=True, num_bits=8, range_given=False, round_mode="HALF_TO_EVEN", name=None): r"""Quantizes then dequantizes a tensor. This op simulates the precision loss from the quantized forward pass by: 1. Quantizing the tensor to fixed point numbers, which should match the target quantization method when it is used in inference. 2. Dequantizing it back to floating point numbers for the following ops, most likely matmul. There are different ways to quantize. This version uses only scaling, so 0.0 maps to 0. From the specified 'num_bits' in the quantized output type, it determines minimum and maximum representable quantized values. e.g. * [-128, 127] for signed, num_bits = 8, or * [0, 255] for unsigned, num_bits = 8. If range_given == False, the initial input_min, input_max will be determined automatically as the minimum and maximum values in the input tensor, otherwise the specified values of input_min, input_max are used. Note: If the input_min, input_max are specified, they do not need to equal the actual minimum and maximum values in the tensor. e.g. in some cases it may be beneficial to specify these values such that the low probability extremes of the input distribution are clipped. This op determines the maximum scale_factor that would map the initial [input_min, input_max] range to a range that lies within the representable quantized range. It determines the scale from one of input_min and input_max, then updates the other one to maximize the respresentable range. e.g. * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, 5.0]: it would use a scale_factor of -128 / -10.0 = 12.8 In this case, it would update input_max to be 127 / 12.8 = 9.921875 * if the output is signed, num_bits = 8, [input_min, input_max] = [-10.0, 10.0]: it would use a scale_factor of 127 / 10.0 = 12.7 In this case, it would update input_min to be 128.0 / 12.7 = -10.07874 * if the output is unsigned, input_min is forced to be 0, and only the specified input_max is used. After determining the scale_factor and updating the input range, it applies the following to each value in the 'input' tensor. output = round(clamp(value, input_min, input_max) * scale_factor) / scale_factor. The above round function rounds the value based on the given round_mode. Args: input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. Tensor to quantize and then dequantize. input_min: A `Tensor`. Must have the same type as `input`. If `range_given == True`, this specifies the minimum input value that needs to be represented, otherwise it is determined from the min value of the `input` tensor. input_max: A `Tensor`. Must have the same type as `input`. If `range_given == True`, this specifies the maximum input value that needs to be represented, otherwise it is determined from the max value of the `input` tensor. signed_input: An optional `bool`. Defaults to `True`. Whether the quantization is signed or unsigned. (actually this parameter should have been called <b>`signed_output`</b>) num_bits: An optional `int`. Defaults to `8`. The bitwidth of the quantization. range_given: An optional `bool`. Defaults to `False`. Whether the range is given or should be determined from the `input` tensor. round_mode: An optional `string` from: `"HALF_TO_EVEN", "HALF_UP"`. Defaults to `"HALF_TO_EVEN"`. The 'round_mode' attribute controls which rounding tie-breaking algorithm is used when rounding float values to their quantized equivalents. The following rounding modes are currently supported: * HALF_TO_EVEN: this is the default round_mode. * HALF_UP: round towards positive. In this mode 7.5 rounds up to 8 and -7.5 rounds up to -7. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizeAndDequantizeV2", name, _ctx._post_execution_callbacks, input, input_min, input_max, "signed_input", signed_input, "num_bits", num_bits, "range_given", range_given, "round_mode", round_mode) return _result except _core._FallbackException: try: return quantize_and_dequantize_v2_eager_fallback( input, input_min, input_max, signed_input=signed_input, num_bits=num_bits, range_given=range_given, round_mode=round_mode, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( quantize_and_dequantize_v2, input=input, input_min=input_min, input_max=input_max, signed_input=signed_input, num_bits=num_bits, range_given=range_given, round_mode=round_mode, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if range_given is None: range_given = False range_given = _execute.make_bool(range_given, "range_given") if round_mode is None: round_mode = "HALF_TO_EVEN" round_mode = _execute.make_str(round_mode, "round_mode") try: _, _, _op = _op_def_lib._apply_op_helper( "QuantizeAndDequantizeV2", input=input, input_min=input_min, input_max=input_max, signed_input=signed_input, num_bits=num_bits, range_given=range_given, round_mode=round_mode, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( quantize_and_dequantize_v2, input=input, input_min=input_min, input_max=input_max, signed_input=signed_input, num_bits=num_bits, range_given=range_given, round_mode=round_mode, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("signed_input", _op.get_attr("signed_input"), "num_bits", _op.get_attr("num_bits"), "range_given", _op.get_attr("range_given"), "T", _op.get_attr("T"), "round_mode", _op.get_attr("round_mode")) _execute.record_gradient( "QuantizeAndDequantizeV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def quantize_and_dequantize_v2_eager_fallback(input, input_min, input_max, signed_input=True, num_bits=8, range_given=False, round_mode="HALF_TO_EVEN", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantize_and_dequantize_v2 """ _ctx = ctx if ctx else _context.context() if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if num_bits is None: num_bits = 8 num_bits = _execute.make_int(num_bits, "num_bits") if range_given is None: range_given = False range_given = _execute.make_bool(range_given, "range_given") if round_mode is None: round_mode = "HALF_TO_EVEN" round_mode = _execute.make_str(round_mode, "round_mode") _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_min, input_max], _ctx) (input, input_min, input_max) = _inputs_T _inputs_flat = [input, input_min, input_max] _attrs = ("signed_input", signed_input, "num_bits", num_bits, "range_given", range_given, "T", _attr_T, "round_mode", round_mode) _result = _execute.execute(b"QuantizeAndDequantizeV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizeAndDequantizeV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def quantize_and_dequantize_v3(input, input_min, input_max, num_bits, signed_input=True, range_given=True, name=None): r"""Quantizes then dequantizes a tensor. This is almost identical to QuantizeAndDequantizeV2, except that num_bits is a tensor, so its value can change during training. Args: input: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`. input_min: A `Tensor`. Must have the same type as `input`. input_max: A `Tensor`. Must have the same type as `input`. num_bits: A `Tensor` of type `int32`. signed_input: An optional `bool`. Defaults to `True`. range_given: An optional `bool`. Defaults to `True`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizeAndDequantizeV3", name, _ctx._post_execution_callbacks, input, input_min, input_max, num_bits, "signed_input", signed_input, "range_given", range_given) return _result except _core._FallbackException: try: return quantize_and_dequantize_v3_eager_fallback( input, input_min, input_max, num_bits, signed_input=signed_input, range_given=range_given, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if range_given is None: range_given = True range_given = _execute.make_bool(range_given, "range_given") _, _, _op = _op_def_lib._apply_op_helper( "QuantizeAndDequantizeV3", input=input, input_min=input_min, input_max=input_max, num_bits=num_bits, signed_input=signed_input, range_given=range_given, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("signed_input", _op.get_attr("signed_input"), "range_given", _op.get_attr("range_given"), "T", _op.get_attr("T")) _execute.record_gradient( "QuantizeAndDequantizeV3", _inputs_flat, _attrs, _result, name) _result, = _result return _result def quantize_and_dequantize_v3_eager_fallback(input, input_min, input_max, num_bits, signed_input=True, range_given=True, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantize_and_dequantize_v3 """ _ctx = ctx if ctx else _context.context() if signed_input is None: signed_input = True signed_input = _execute.make_bool(signed_input, "signed_input") if range_given is None: range_given = True range_given = _execute.make_bool(range_given, "range_given") _attr_T, _inputs_T = _execute.args_to_matching_eager([input, input_min, input_max], _ctx) (input, input_min, input_max) = _inputs_T num_bits = _ops.convert_to_tensor(num_bits, _dtypes.int32) _inputs_flat = [input, input_min, input_max, num_bits] _attrs = ("signed_input", signed_input, "range_given", range_given, "T", _attr_T) _result = _execute.execute(b"QuantizeAndDequantizeV3", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizeAndDequantizeV3", _inputs_flat, _attrs, _result, name) _result, = _result return _result _quantize_v2_outputs = ["output", "output_min", "output_max"] _QuantizeV2Output = _collections.namedtuple( "QuantizeV2", _quantize_v2_outputs) def quantize_v2(input, min_range, max_range, T, mode="MIN_COMBINED", round_mode="HALF_AWAY_FROM_ZERO", name=None): r"""Quantize the 'input' tensor of type float to 'output' tensor of type 'T'. [min_range, max_range] are scalar floats that specify the range for the 'input' data. The 'mode' attribute controls exactly which calculations are used to convert the float values to their quantized equivalents. The 'round_mode' attribute controls which rounding tie-breaking algorithm is used when rounding float values to their quantized equivalents. In 'MIN_COMBINED' mode, each value of the tensor will undergo the following: ``` out[i] = (in[i] - min_range) * range(T) / (max_range - min_range) if T == qint8: out[i] -= (range(T) + 1) / 2.0 ``` here `range(T) = numeric_limits<T>::max() - numeric_limits<T>::min()` *MIN_COMBINED Mode Example* Assume the input is type float and has a possible range of [0.0, 6.0] and the output type is quint8 ([0, 255]). The min_range and max_range values should be specified as 0.0 and 6.0. Quantizing from float to quint8 will multiply each value of the input by 255/6 and cast to quint8. If the output type was qint8 ([-128, 127]), the operation will additionally subtract each value by 128 prior to casting, so that the range of values aligns with the range of qint8. If the mode is 'MIN_FIRST', then this approach is used: ``` num_discrete_values = 1 << (# of bits in T) range_adjust = num_discrete_values / (num_discrete_values - 1) range = (range_max - range_min) * range_adjust range_scale = num_discrete_values / range quantized = round(input * range_scale) - round(range_min * range_scale) + numeric_limits<T>::min() quantized = max(quantized, numeric_limits<T>::min()) quantized = min(quantized, numeric_limits<T>::max()) ``` The biggest difference between this and MIN_COMBINED is that the minimum range is rounded first, before it's subtracted from the rounded value. With MIN_COMBINED, a small bias is introduced where repeated iterations of quantizing and dequantizing will introduce a larger and larger error. *SCALED mode Example* `SCALED` mode matches the quantization approach used in `QuantizeAndDequantize{V2|V3}`. If the mode is `SCALED`, we do not use the full range of the output type, choosing to elide the lowest possible value for symmetry (e.g., output range is -127 to 127, not -128 to 127 for signed 8 bit quantization), so that 0.0 maps to 0. We first find the range of values in our tensor. The range we use is always centered on 0, so we find m such that ```c++ m = max(abs(input_min), abs(input_max)) ``` Our input tensor range is then `[-m, m]`. Next, we choose our fixed-point quantization buckets, `[min_fixed, max_fixed]`. If T is signed, this is ``` num_bits = sizeof(T) * 8 [min_fixed, max_fixed] = [-(1 << (num_bits - 1) - 1), (1 << (num_bits - 1)) - 1] ``` Otherwise, if T is unsigned, the fixed-point range is ``` [min_fixed, max_fixed] = [0, (1 << num_bits) - 1] ``` From this we compute our scaling factor, s: ```c++ s = (max_fixed - min_fixed) / (2 * m) ``` Now we can quantize the elements of our tensor: ```c++ result = round(input * s) ``` One thing to watch out for is that the operator may choose to adjust the requested minimum and maximum values slightly during the quantization process, so you should always use the output ports as the range for further calculations. For example, if the requested minimum and maximum values are close to equal, they will be separated by a small epsilon value to prevent ill-formed quantized buffers from being created. Otherwise, you can end up with buffers where all the quantized values map to the same float value, which causes problems for operations that have to perform further calculations on them. Args: input: A `Tensor` of type `float32`. min_range: A `Tensor` of type `float32`. The minimum scalar value possibly produced for the input. max_range: A `Tensor` of type `float32`. The maximum scalar value possibly produced for the input. T: A `tf.DType` from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. mode: An optional `string` from: `"MIN_COMBINED", "MIN_FIRST", "SCALED"`. Defaults to `"MIN_COMBINED"`. round_mode: An optional `string` from: `"HALF_AWAY_FROM_ZERO", "HALF_TO_EVEN"`. Defaults to `"HALF_AWAY_FROM_ZERO"`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output, output_min, output_max). output: A `Tensor` of type `T`. output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizeV2", name, _ctx._post_execution_callbacks, input, min_range, max_range, "T", T, "mode", mode, "round_mode", round_mode) _result = _QuantizeV2Output._make(_result) return _result except _core._FallbackException: try: return quantize_v2_eager_fallback( input, min_range, max_range, T=T, mode=mode, round_mode=round_mode, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. T = _execute.make_type(T, "T") if mode is None: mode = "MIN_COMBINED" mode = _execute.make_str(mode, "mode") if round_mode is None: round_mode = "HALF_AWAY_FROM_ZERO" round_mode = _execute.make_str(round_mode, "round_mode") _, _, _op = _op_def_lib._apply_op_helper( "QuantizeV2", input=input, min_range=min_range, max_range=max_range, T=T, mode=mode, round_mode=round_mode, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "mode", _op.get_attr("mode"), "round_mode", _op.get_attr("round_mode")) _execute.record_gradient( "QuantizeV2", _inputs_flat, _attrs, _result, name) _result = _QuantizeV2Output._make(_result) return _result def quantize_v2_eager_fallback(input, min_range, max_range, T, mode="MIN_COMBINED", round_mode="HALF_AWAY_FROM_ZERO", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantize_v2 """ _ctx = ctx if ctx else _context.context() T = _execute.make_type(T, "T") if mode is None: mode = "MIN_COMBINED" mode = _execute.make_str(mode, "mode") if round_mode is None: round_mode = "HALF_AWAY_FROM_ZERO" round_mode = _execute.make_str(round_mode, "round_mode") input = _ops.convert_to_tensor(input, _dtypes.float32) min_range = _ops.convert_to_tensor(min_range, _dtypes.float32) max_range = _ops.convert_to_tensor(max_range, _dtypes.float32) _inputs_flat = [input, min_range, max_range] _attrs = ("T", T, "mode", mode, "round_mode", round_mode) _result = _execute.execute(b"QuantizeV2", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizeV2", _inputs_flat, _attrs, _result, name) _result = _QuantizeV2Output._make(_result) return _result _quantized_concat_outputs = ["output", "output_min", "output_max"] _QuantizedConcatOutput = _collections.namedtuple( "QuantizedConcat", _quantized_concat_outputs) @_dispatch.add_dispatch_list @tf_export('quantization.quantized_concat', v1=['quantization.quantized_concat', 'quantized_concat']) @deprecated_endpoints('quantized_concat') def quantized_concat(concat_dim, values, input_mins, input_maxes, name=None): r"""Concatenates quantized tensors along one dimension. Args: concat_dim: A `Tensor` of type `int32`. 0-D. The dimension along which to concatenate. Must be in the range [0, rank(values)). values: A list of at least 2 `Tensor` objects with the same type. The `N` Tensors to concatenate. Their ranks and types must match, and their sizes must match in all dimensions except `concat_dim`. input_mins: A list with the same length as `values` of `Tensor` objects with type `float32`. The minimum scalar values for each of the input tensors. input_maxes: A list with the same length as `values` of `Tensor` objects with type `float32`. The maximum scalar values for each of the input tensors. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output, output_min, output_max). output: A `Tensor`. Has the same type as `values`. output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedConcat", name, _ctx._post_execution_callbacks, concat_dim, values, input_mins, input_maxes) _result = _QuantizedConcatOutput._make(_result) return _result except _core._FallbackException: try: return quantized_concat_eager_fallback( concat_dim, values, input_mins, input_maxes, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( quantized_concat, concat_dim=concat_dim, values=values, input_mins=input_mins, input_maxes=input_maxes, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'quantized_concat' Op, not %r." % values) _attr_N = len(values) if not isinstance(input_mins, (list, tuple)): raise TypeError( "Expected list for 'input_mins' argument to " "'quantized_concat' Op, not %r." % input_mins) if len(input_mins) != _attr_N: raise ValueError( "List argument 'input_mins' to 'quantized_concat' Op with length %d " "must match length %d of argument 'values'." % (len(input_mins), _attr_N)) if not isinstance(input_maxes, (list, tuple)): raise TypeError( "Expected list for 'input_maxes' argument to " "'quantized_concat' Op, not %r." % input_maxes) if len(input_maxes) != _attr_N: raise ValueError( "List argument 'input_maxes' to 'quantized_concat' Op with length %d " "must match length %d of argument 'values'." % (len(input_maxes), _attr_N)) try: _, _, _op = _op_def_lib._apply_op_helper( "QuantizedConcat", concat_dim=concat_dim, values=values, input_mins=input_mins, input_maxes=input_maxes, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( quantized_concat, concat_dim=concat_dim, values=values, input_mins=input_mins, input_maxes=input_maxes, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T")) _execute.record_gradient( "QuantizedConcat", _inputs_flat, _attrs, _result, name) _result = _QuantizedConcatOutput._make(_result) return _result def quantized_concat_eager_fallback(concat_dim, values, input_mins, input_maxes, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_concat """ _ctx = ctx if ctx else _context.context() if not isinstance(values, (list, tuple)): raise TypeError( "Expected list for 'values' argument to " "'quantized_concat' Op, not %r." % values) _attr_N = len(values) if not isinstance(input_mins, (list, tuple)): raise TypeError( "Expected list for 'input_mins' argument to " "'quantized_concat' Op, not %r." % input_mins) if len(input_mins) != _attr_N: raise ValueError( "List argument 'input_mins' to 'quantized_concat' Op with length %d " "must match length %d of argument 'values'." % (len(input_mins), _attr_N)) if not isinstance(input_maxes, (list, tuple)): raise TypeError( "Expected list for 'input_maxes' argument to " "'quantized_concat' Op, not %r." % input_maxes) if len(input_maxes) != _attr_N: raise ValueError( "List argument 'input_maxes' to 'quantized_concat' Op with length %d " "must match length %d of argument 'values'." % (len(input_maxes), _attr_N)) _attr_T, values = _execute.args_to_matching_eager(list(values), _ctx) concat_dim = _ops.convert_to_tensor(concat_dim, _dtypes.int32) input_mins = _ops.convert_n_to_tensor(input_mins, _dtypes.float32) input_maxes = _ops.convert_n_to_tensor(input_maxes, _dtypes.float32) _inputs_flat = [concat_dim] + list(values) + list(input_mins) + list(input_maxes) _attrs = ("N", _attr_N, "T", _attr_T) _result = _execute.execute(b"QuantizedConcat", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedConcat", _inputs_flat, _attrs, _result, name) _result = _QuantizedConcatOutput._make(_result) return _result _quantized_instance_norm_outputs = ["y", "y_min", "y_max"] _QuantizedInstanceNormOutput = _collections.namedtuple( "QuantizedInstanceNorm", _quantized_instance_norm_outputs) def quantized_instance_norm(x, x_min, x_max, output_range_given=False, given_y_min=0, given_y_max=0, variance_epsilon=1e-05, min_separation=0.001, name=None): r"""Quantized Instance normalization. Args: x: A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. A 4D input Tensor. x_min: A `Tensor` of type `float32`. The value represented by the lowest quantized input. x_max: A `Tensor` of type `float32`. The value represented by the highest quantized input. output_range_given: An optional `bool`. Defaults to `False`. If True, `given_y_min` and `given_y_min` and `given_y_max` are used as the output range. Otherwise, the implementation computes the output range. given_y_min: An optional `float`. Defaults to `0`. Output in `y_min` if `output_range_given` is True. given_y_max: An optional `float`. Defaults to `0`. Output in `y_max` if `output_range_given` is True. variance_epsilon: An optional `float`. Defaults to `1e-05`. A small float number to avoid dividing by 0. min_separation: An optional `float`. Defaults to `0.001`. Minimum value of `y_max - y_min` name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (y, y_min, y_max). y: A `Tensor`. Has the same type as `x`. y_min: A `Tensor` of type `float32`. y_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedInstanceNorm", name, _ctx._post_execution_callbacks, x, x_min, x_max, "output_range_given", output_range_given, "given_y_min", given_y_min, "given_y_max", given_y_max, "variance_epsilon", variance_epsilon, "min_separation", min_separation) _result = _QuantizedInstanceNormOutput._make(_result) return _result except _core._FallbackException: try: return quantized_instance_norm_eager_fallback( x, x_min, x_max, output_range_given=output_range_given, given_y_min=given_y_min, given_y_max=given_y_max, variance_epsilon=variance_epsilon, min_separation=min_separation, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if output_range_given is None: output_range_given = False output_range_given = _execute.make_bool(output_range_given, "output_range_given") if given_y_min is None: given_y_min = 0 given_y_min = _execute.make_float(given_y_min, "given_y_min") if given_y_max is None: given_y_max = 0 given_y_max = _execute.make_float(given_y_max, "given_y_max") if variance_epsilon is None: variance_epsilon = 1e-05 variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") if min_separation is None: min_separation = 0.001 min_separation = _execute.make_float(min_separation, "min_separation") _, _, _op = _op_def_lib._apply_op_helper( "QuantizedInstanceNorm", x=x, x_min=x_min, x_max=x_max, output_range_given=output_range_given, given_y_min=given_y_min, given_y_max=given_y_max, variance_epsilon=variance_epsilon, min_separation=min_separation, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "output_range_given", _op.get_attr("output_range_given"), "given_y_min", _op.get_attr("given_y_min"), "given_y_max", _op.get_attr("given_y_max"), "variance_epsilon", _op.get_attr("variance_epsilon"), "min_separation", _op.get_attr("min_separation")) _execute.record_gradient( "QuantizedInstanceNorm", _inputs_flat, _attrs, _result, name) _result = _QuantizedInstanceNormOutput._make(_result) return _result def quantized_instance_norm_eager_fallback(x, x_min, x_max, output_range_given=False, given_y_min=0, given_y_max=0, variance_epsilon=1e-05, min_separation=0.001, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_instance_norm """ _ctx = ctx if ctx else _context.context() if output_range_given is None: output_range_given = False output_range_given = _execute.make_bool(output_range_given, "output_range_given") if given_y_min is None: given_y_min = 0 given_y_min = _execute.make_float(given_y_min, "given_y_min") if given_y_max is None: given_y_max = 0 given_y_max = _execute.make_float(given_y_max, "given_y_max") if variance_epsilon is None: variance_epsilon = 1e-05 variance_epsilon = _execute.make_float(variance_epsilon, "variance_epsilon") if min_separation is None: min_separation = 0.001 min_separation = _execute.make_float(min_separation, "min_separation") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) x_min = _ops.convert_to_tensor(x_min, _dtypes.float32) x_max = _ops.convert_to_tensor(x_max, _dtypes.float32) _inputs_flat = [x, x_min, x_max] _attrs = ("T", _attr_T, "output_range_given", output_range_given, "given_y_min", given_y_min, "given_y_max", given_y_max, "variance_epsilon", variance_epsilon, "min_separation", min_separation) _result = _execute.execute(b"QuantizedInstanceNorm", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedInstanceNorm", _inputs_flat, _attrs, _result, name) _result = _QuantizedInstanceNormOutput._make(_result) return _result _quantized_reshape_outputs = ["output", "output_min", "output_max"] _QuantizedReshapeOutput = _collections.namedtuple( "QuantizedReshape", _quantized_reshape_outputs) def quantized_reshape(tensor, shape, input_min, input_max, name=None): r"""Reshapes a quantized tensor as per the Reshape op. ``` Args: tensor: A `Tensor`. shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. Defines the shape of the output tensor. input_min: A `Tensor` of type `float32`. The minimum value of the input. input_max: A `Tensor` of type `float32`. The maximum value of the input. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (output, output_min, output_max). output: A `Tensor`. Has the same type as `tensor`. output_min: A `Tensor` of type `float32`. output_max: A `Tensor` of type `float32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "QuantizedReshape", name, _ctx._post_execution_callbacks, tensor, shape, input_min, input_max) _result = _QuantizedReshapeOutput._make(_result) return _result except _core._FallbackException: try: return quantized_reshape_eager_fallback( tensor, shape, input_min, input_max, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "QuantizedReshape", tensor=tensor, shape=shape, input_min=input_min, input_max=input_max, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tshape", _op.get_attr("Tshape")) _execute.record_gradient( "QuantizedReshape", _inputs_flat, _attrs, _result, name) _result = _QuantizedReshapeOutput._make(_result) return _result def quantized_reshape_eager_fallback(tensor, shape, input_min, input_max, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function quantized_reshape """ _ctx = ctx if ctx else _context.context() _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], _ctx) _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], _ctx, _dtypes.int32) input_min = _ops.convert_to_tensor(input_min, _dtypes.float32) input_max = _ops.convert_to_tensor(input_max, _dtypes.float32) _inputs_flat = [tensor, shape, input_min, input_max] _attrs = ("T", _attr_T, "Tshape", _attr_Tshape) _result = _execute.execute(b"QuantizedReshape", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "QuantizedReshape", _inputs_flat, _attrs, _result, name) _result = _QuantizedReshapeOutput._make(_result) return _result def rank(input, name=None): r"""Returns the rank of a tensor. This operation returns an integer representing the rank of `input`. For example: ``` # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] # shape of tensor 't' is [2, 2, 3] rank(t) ==> 3 ``` **Note**: The rank of a tensor is not the same as the rank of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as "order", "degree", or "ndims." Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor` of type `int32`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Rank", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return rank_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Rank", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Rank", _inputs_flat, _attrs, _result, name) _result, = _result return _result def rank_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function rank """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"Rank", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Rank", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ref_identity(input, name=None): r"""Return the same ref tensor as the input ref tensor. Args: input: A mutable `Tensor`. name: A name for the operation (optional). Returns: A mutable `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: raise RuntimeError("ref_identity op does not support eager execution. Arg 'output' is a ref.") # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "RefIdentity", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "RefIdentity", _inputs_flat, _attrs, _result, name) _result, = _result return _result def ref_identity_eager_fallback(input, name=None, ctx=None): raise RuntimeError("ref_identity op does not support eager execution. Arg 'output' is a ref.") @_dispatch.add_dispatch_list @tf_export('reshape', v1=['reshape', 'manip.reshape']) @deprecated_endpoints('manip.reshape') def reshape(tensor, shape, name=None): r"""Reshapes a tensor. Given `tensor`, this operation returns a tensor that has the same values as `tensor` with shape `shape`. If one component of `shape` is the special value -1, the size of that dimension is computed so that the total size remains constant. In particular, a `shape` of `[-1]` flattens into 1-D. At most one component of `shape` can be -1. If `shape` is 1-D or higher, then the operation returns a tensor with shape `shape` filled with the values of `tensor`. In this case, the number of elements implied by `shape` must be the same as the number of elements in `tensor`. For example: ``` # tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9] # tensor 't' has shape [9] reshape(t, [3, 3]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # tensor 't' is [[[1, 1], [2, 2]], # [[3, 3], [4, 4]]] # tensor 't' has shape [2, 2, 2] reshape(t, [2, 4]) ==> [[1, 1, 2, 2], [3, 3, 4, 4]] # tensor 't' is [[[1, 1, 1], # [2, 2, 2]], # [[3, 3, 3], # [4, 4, 4]], # [[5, 5, 5], # [6, 6, 6]]] # tensor 't' has shape [3, 2, 3] # pass '[-1]' to flatten 't' reshape(t, [-1]) ==> [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6] # -1 can also be used to infer the shape # -1 is inferred to be 9: reshape(t, [2, -1]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 5, 5, 5, 6, 6, 6]] # -1 is inferred to be 2: reshape(t, [-1, 9]) ==> [[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 4, 4, 5, 5, 5, 6, 6, 6]] # -1 is inferred to be 3: reshape(t, [ 2, -1, 3]) ==> [[[1, 1, 1], [2, 2, 2], [3, 3, 3]], [[4, 4, 4], [5, 5, 5], [6, 6, 6]]] # tensor 't' is [7] # shape `[]` reshapes to a scalar reshape(t, []) ==> 7 ``` Args: tensor: A `Tensor`. shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. Defines the shape of the output tensor. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Reshape", name, _ctx._post_execution_callbacks, tensor, shape) return _result except _core._FallbackException: try: return reshape_eager_fallback( tensor, shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( reshape, tensor=tensor, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "Reshape", tensor=tensor, shape=shape, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( reshape, tensor=tensor, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tshape", _op.get_attr("Tshape")) _execute.record_gradient( "Reshape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reshape_eager_fallback(tensor, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reshape """ _ctx = ctx if ctx else _context.context() _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], _ctx) _attr_Tshape, (shape,) = _execute.args_to_matching_eager([shape], _ctx, _dtypes.int32) _inputs_flat = [tensor, shape] _attrs = ("T", _attr_T, "Tshape", _attr_Tshape) _result = _execute.execute(b"Reshape", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Reshape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def resource_strided_slice_assign(ref, begin, end, strides, value, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None): r"""Assign `value` to the sliced l-value reference of `ref`. The values of `value` are assigned to the positions in the variable `ref` that are selected by the slice parameters. The slice parameters `begin, `end`, `strides`, etc. work exactly as in `StridedSlice`. NOTE this op currently does not support broadcasting and so `value`'s shape must be exactly the shape produced by the slice of `ref`. Args: ref: A `Tensor` of type `resource`. begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. end: A `Tensor`. Must have the same type as `begin`. strides: A `Tensor`. Must have the same type as `begin`. value: A `Tensor`. begin_mask: An optional `int`. Defaults to `0`. end_mask: An optional `int`. Defaults to `0`. ellipsis_mask: An optional `int`. Defaults to `0`. new_axis_mask: An optional `int`. Defaults to `0`. shrink_axis_mask: An optional `int`. Defaults to `0`. name: A name for the operation (optional). Returns: The created Operation. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ResourceStridedSliceAssign", name, _ctx._post_execution_callbacks, ref, begin, end, strides, value, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) return _result except _core._FallbackException: try: return resource_strided_slice_assign_eager_fallback( ref, begin, end, strides, value, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _, _, _op = _op_def_lib._apply_op_helper( "ResourceStridedSliceAssign", ref=ref, begin=begin, end=end, strides=strides, value=value, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name) return _op _result = None return _result def resource_strided_slice_assign_eager_fallback(ref, begin, end, strides, value, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function resource_strided_slice_assign """ _ctx = ctx if ctx else _context.context() if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _attr_T, (value,) = _execute.args_to_matching_eager([value], _ctx) _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, end, strides], _ctx) (begin, end, strides) = _inputs_Index ref = _ops.convert_to_tensor(ref, _dtypes.resource) _inputs_flat = [ref, begin, end, strides, value] _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) _result = _execute.execute(b"ResourceStridedSliceAssign", 0, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _result = None return _result def reverse(tensor, dims, name=None): r"""Reverses specific dimensions of a tensor. Given a `tensor`, and a `bool` tensor `dims` representing the dimensions of `tensor`, this operation reverses each dimension i of `tensor` where `dims[i]` is `True`. `tensor` can have up to 8 dimensions. The number of dimensions of `tensor` must equal the number of elements in `dims`. In other words: `rank(tensor) = size(dims)` For example: ``` # tensor 't' is [[[[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11]], # [[12, 13, 14, 15], # [16, 17, 18, 19], # [20, 21, 22, 23]]]] # tensor 't' shape is [1, 2, 3, 4] # 'dims' is [False, False, False, True] reverse(t, dims) ==> [[[[ 3, 2, 1, 0], [ 7, 6, 5, 4], [ 11, 10, 9, 8]], [[15, 14, 13, 12], [19, 18, 17, 16], [23, 22, 21, 20]]]] # 'dims' is [False, True, False, False] reverse(t, dims) ==> [[[[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23] [[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]]] # 'dims' is [False, False, True, False] reverse(t, dims) ==> [[[[8, 9, 10, 11], [4, 5, 6, 7], [0, 1, 2, 3]] [[20, 21, 22, 23], [16, 17, 18, 19], [12, 13, 14, 15]]]] ``` Args: tensor: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `half`, `float32`, `float64`, `complex64`, `complex128`, `string`. Up to 8-D. dims: A `Tensor` of type `bool`. 1-D. The dimensions to reverse. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Reverse", name, _ctx._post_execution_callbacks, tensor, dims) return _result except _core._FallbackException: try: return reverse_eager_fallback( tensor, dims, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Reverse", tensor=tensor, dims=dims, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Reverse", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reverse_eager_fallback(tensor, dims, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reverse """ _ctx = ctx if ctx else _context.context() _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], _ctx) dims = _ops.convert_to_tensor(dims, _dtypes.bool) _inputs_flat = [tensor, dims] _attrs = ("T", _attr_T) _result = _execute.execute(b"Reverse", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Reverse", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reverse_sequence(input, seq_lengths, seq_dim, batch_dim=0, name=None): r"""Reverses variable length slices. This op first slices `input` along the dimension `batch_dim`, and for each slice `i`, reverses the first `seq_lengths[i]` elements along the dimension `seq_dim`. The elements of `seq_lengths` must obey `seq_lengths[i] <= input.dims[seq_dim]`, and `seq_lengths` must be a vector of length `input.dims[batch_dim]`. The output slice `i` along dimension `batch_dim` is then given by input slice `i`, with the first `seq_lengths[i]` slices along dimension `seq_dim` reversed. For example: ``` # Given this: batch_dim = 0 seq_dim = 1 input.dims = (4, 8, ...) seq_lengths = [7, 2, 3, 5] # then slices of input are reversed on seq_dim, but only up to seq_lengths: output[0, 0:7, :, ...] = input[0, 7:0:-1, :, ...] output[1, 0:2, :, ...] = input[1, 2:0:-1, :, ...] output[2, 0:3, :, ...] = input[2, 3:0:-1, :, ...] output[3, 0:5, :, ...] = input[3, 5:0:-1, :, ...] # while entries past seq_lens are copied through: output[0, 7:, :, ...] = input[0, 7:, :, ...] output[1, 2:, :, ...] = input[1, 2:, :, ...] output[2, 3:, :, ...] = input[2, 3:, :, ...] output[3, 2:, :, ...] = input[3, 2:, :, ...] ``` In contrast, if: ``` # Given this: batch_dim = 2 seq_dim = 0 input.dims = (8, ?, 4, ...) seq_lengths = [7, 2, 3, 5] # then slices of input are reversed on seq_dim, but only up to seq_lengths: output[0:7, :, 0, :, ...] = input[7:0:-1, :, 0, :, ...] output[0:2, :, 1, :, ...] = input[2:0:-1, :, 1, :, ...] output[0:3, :, 2, :, ...] = input[3:0:-1, :, 2, :, ...] output[0:5, :, 3, :, ...] = input[5:0:-1, :, 3, :, ...] # while entries past seq_lens are copied through: output[7:, :, 0, :, ...] = input[7:, :, 0, :, ...] output[2:, :, 1, :, ...] = input[2:, :, 1, :, ...] output[3:, :, 2, :, ...] = input[3:, :, 2, :, ...] output[2:, :, 3, :, ...] = input[2:, :, 3, :, ...] ``` Args: input: A `Tensor`. The input to reverse. seq_lengths: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D with length `input.dims(batch_dim)` and `max(seq_lengths) <= input.dims(seq_dim)` seq_dim: An `int`. The dimension which is partially reversed. batch_dim: An optional `int`. Defaults to `0`. The dimension along which reversal is performed. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ReverseSequence", name, _ctx._post_execution_callbacks, input, seq_lengths, "seq_dim", seq_dim, "batch_dim", batch_dim) return _result except _core._FallbackException: try: return reverse_sequence_eager_fallback( input, seq_lengths, seq_dim=seq_dim, batch_dim=batch_dim, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. seq_dim = _execute.make_int(seq_dim, "seq_dim") if batch_dim is None: batch_dim = 0 batch_dim = _execute.make_int(batch_dim, "batch_dim") _, _, _op = _op_def_lib._apply_op_helper( "ReverseSequence", input=input, seq_lengths=seq_lengths, seq_dim=seq_dim, batch_dim=batch_dim, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("seq_dim", _op.get_attr("seq_dim"), "batch_dim", _op.get_attr("batch_dim"), "T", _op.get_attr("T"), "Tlen", _op.get_attr("Tlen")) _execute.record_gradient( "ReverseSequence", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reverse_sequence_eager_fallback(input, seq_lengths, seq_dim, batch_dim=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reverse_sequence """ _ctx = ctx if ctx else _context.context() seq_dim = _execute.make_int(seq_dim, "seq_dim") if batch_dim is None: batch_dim = 0 batch_dim = _execute.make_int(batch_dim, "batch_dim") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tlen, (seq_lengths,) = _execute.args_to_matching_eager([seq_lengths], _ctx, _dtypes.int64) _inputs_flat = [input, seq_lengths] _attrs = ("seq_dim", seq_dim, "batch_dim", batch_dim, "T", _attr_T, "Tlen", _attr_Tlen) _result = _execute.execute(b"ReverseSequence", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ReverseSequence", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('reverse', v1=['reverse', 'manip.reverse', 'reverse_v2']) @deprecated_endpoints('manip.reverse', 'reverse_v2') def reverse_v2(tensor, axis, name=None): r"""Reverses specific dimensions of a tensor. NOTE `tf.reverse` has now changed behavior in preparation for 1.0. `tf.reverse_v2` is currently an alias that will be deprecated before TF 1.0. Given a `tensor`, and a `int32` tensor `axis` representing the set of dimensions of `tensor` to reverse. This operation reverses each dimension `i` for which there exists `j` s.t. `axis[j] == i`. `tensor` can have up to 8 dimensions. The number of dimensions specified in `axis` may be 0 or more entries. If an index is specified more than once, a InvalidArgument error is raised. For example: ``` # tensor 't' is [[[[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11]], # [[12, 13, 14, 15], # [16, 17, 18, 19], # [20, 21, 22, 23]]]] # tensor 't' shape is [1, 2, 3, 4] # 'dims' is [3] or 'dims' is [-1] reverse(t, dims) ==> [[[[ 3, 2, 1, 0], [ 7, 6, 5, 4], [ 11, 10, 9, 8]], [[15, 14, 13, 12], [19, 18, 17, 16], [23, 22, 21, 20]]]] # 'dims' is '[1]' (or 'dims' is '[-3]') reverse(t, dims) ==> [[[[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23] [[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]]] # 'dims' is '[2]' (or 'dims' is '[-2]') reverse(t, dims) ==> [[[[8, 9, 10, 11], [4, 5, 6, 7], [0, 1, 2, 3]] [[20, 21, 22, 23], [16, 17, 18, 19], [12, 13, 14, 15]]]] ``` Args: tensor: A `Tensor`. Must be one of the following types: `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `bool`, `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`, `string`. Up to 8-D. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D. The indices of the dimensions to reverse. Must be in the range `[-rank(tensor), rank(tensor))`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ReverseV2", name, _ctx._post_execution_callbacks, tensor, axis) return _result except _core._FallbackException: try: return reverse_v2_eager_fallback( tensor, axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( reverse_v2, tensor=tensor, axis=axis, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "ReverseV2", tensor=tensor, axis=axis, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( reverse_v2, tensor=tensor, axis=axis, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tidx", _op.get_attr("Tidx"), "T", _op.get_attr("T")) _execute.record_gradient( "ReverseV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result def reverse_v2_eager_fallback(tensor, axis, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function reverse_v2 """ _ctx = ctx if ctx else _context.context() _attr_Tidx, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int32) _attr_T, (tensor,) = _execute.args_to_matching_eager([tensor], _ctx) _inputs_flat = [tensor, axis] _attrs = ("Tidx", _attr_Tidx, "T", _attr_T) _result = _execute.execute(b"ReverseV2", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ReverseV2", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('scatter_nd', v1=['scatter_nd', 'manip.scatter_nd']) @deprecated_endpoints('manip.scatter_nd') def scatter_nd(indices, updates, shape, name=None): r"""Scatter `updates` into a new tensor according to `indices`. Creates a new tensor by applying sparse `updates` to individual values or slices within a tensor (initially zero for numeric, empty for string) of the given `shape` according to indices. This operator is the inverse of the `tf.gather_nd` operator which extracts values or slices from a given tensor. This operation is similar to tensor_scatter_add, except that the tensor is zero-initialized. Calling `tf.scatter_nd(indices, values, shape)` is identical to `tensor_scatter_add(tf.zeros(shape, values.dtype), indices, values)` If `indices` contains duplicates, then their updates are accumulated (summed). **WARNING**: The order in which updates are applied is nondeterministic, so the output will be nondeterministic if `indices` contains duplicates -- because of some numerical approximation issues, numbers summed in different order may yield different results. `indices` is an integer tensor containing indices into a new tensor of shape `shape`. The last dimension of `indices` can be at most the rank of `shape`: indices.shape[-1] <= shape.rank The last dimension of `indices` corresponds to indices into elements (if `indices.shape[-1] = shape.rank`) or slices (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of `shape`. `updates` is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:] The simplest form of scatter is to insert individual elements in a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/ScatterNd1.png" alt> </div> In Python, this scatter operation would look like this: ```python indices = tf.constant([[4], [3], [1], [7]]) updates = tf.constant([9, 10, 11, 12]) shape = tf.constant([8]) scatter = tf.scatter_nd(indices, updates, shape) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [0, 11, 0, 10, 9, 0, 0, 12] We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/ScatterNd2.png" alt> </div> In Python, this scatter operation would look like this: ```python indices = tf.constant([[0], [2]]) updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]) shape = tf.constant([4, 4, 4]) scatter = tf.scatter_nd(indices, updates, shape) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]] Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored. Args: indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. updates: A `Tensor`. Updates to scatter into output. shape: A `Tensor`. Must have the same type as `indices`. 1-D. The shape of the resulting tensor. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `updates`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ScatterNd", name, _ctx._post_execution_callbacks, indices, updates, shape) return _result except _core._FallbackException: try: return scatter_nd_eager_fallback( indices, updates, shape, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( scatter_nd, indices=indices, updates=updates, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "ScatterNd", indices=indices, updates=updates, shape=shape, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( scatter_nd, indices=indices, updates=updates, shape=shape, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "ScatterNd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def scatter_nd_eager_fallback(indices, updates, shape, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function scatter_nd """ _ctx = ctx if ctx else _context.context() _attr_T, (updates,) = _execute.args_to_matching_eager([updates], _ctx) _attr_Tindices, _inputs_Tindices = _execute.args_to_matching_eager([indices, shape], _ctx) (indices, shape) = _inputs_Tindices _inputs_flat = [indices, updates, shape] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"ScatterNd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ScatterNd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def scatter_nd_non_aliasing_add(input, indices, updates, name=None): r"""Applies sparse addition to `input` using individual values or slices from `updates` according to indices `indices`. The updates are non-aliasing: `input` is only modified in-place if no other operations will use it. Otherwise, a copy of `input` is made. This operation has a gradient with respect to both `input` and `updates`. `input` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`. `indices` must be integer tensor, containing indices into `input`. It must be shape \\([d_0, ..., d_{Q-2}, K]\\) where `0 < K <= P`. The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or `(P-K)`-dimensional slices (if `K < P`) along the `K`th dimension of `input`. `updates` is `Tensor` of rank `Q-1+P-K` with shape: $$[d_0, ..., d_{Q-2}, input.shape[K], ..., input.shape[P-1]].$$ For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that addition would look like this: input = tf.constant([1, 2, 3, 4, 5, 6, 7, 8]) indices = tf.constant([[4], [3], [1], [7]]) updates = tf.constant([9, 10, 11, 12]) output = tf.scatter_nd_non_aliasing_add(input, indices, updates) with tf.Session() as sess: print(sess.run(output)) The resulting value `output` would look like this: [1, 13, 3, 14, 14, 6, 7, 20] See `tf.scatter_nd` for more details about how to make updates to slices. Args: input: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. A Tensor. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. A Tensor. Must be one of the following types: `int32`, `int64`. A tensor of indices into `input`. updates: A `Tensor`. Must have the same type as `input`. A Tensor. Must have the same type as ref. A tensor of updated values to add to `input`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ScatterNdNonAliasingAdd", name, _ctx._post_execution_callbacks, input, indices, updates) return _result except _core._FallbackException: try: return scatter_nd_non_aliasing_add_eager_fallback( input, indices, updates, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "ScatterNdNonAliasingAdd", input=input, indices=indices, updates=updates, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "ScatterNdNonAliasingAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def scatter_nd_non_aliasing_add_eager_fallback(input, indices, updates, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function scatter_nd_non_aliasing_add """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([input, updates], _ctx) (input, updates) = _inputs_T _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [input, indices, updates] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"ScatterNdNonAliasingAdd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ScatterNdNonAliasingAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def shape(input, out_type=_dtypes.int32, name=None): r"""Returns the shape of a tensor. This operation returns a 1-D integer tensor representing the shape of `input`. For example: ``` # 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]] shape(t) ==> [2, 2, 3] ``` Args: input: A `Tensor`. out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A `Tensor` of type `out_type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Shape", name, _ctx._post_execution_callbacks, input, "out_type", out_type) return _result except _core._FallbackException: try: return shape_eager_fallback( input, out_type=out_type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "Shape", input=input, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "Shape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def shape_eager_fallback(input, out_type=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function shape """ _ctx = ctx if ctx else _context.context() if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "out_type", out_type) _result = _execute.execute(b"Shape", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Shape", _inputs_flat, _attrs, _result, name) _result, = _result return _result def shape_n(input, out_type=_dtypes.int32, name=None): r"""Returns shape of tensors. This operation returns N 1-D integer tensors representing shape of `input[i]s`. Args: input: A list of at least 1 `Tensor` objects with the same type. out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A list with the same length as `input` of `Tensor` objects with type `out_type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ShapeN", name, _ctx._post_execution_callbacks, input, "out_type", out_type) return _result except _core._FallbackException: try: return shape_n_eager_fallback( input, out_type=out_type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if not isinstance(input, (list, tuple)): raise TypeError( "Expected list for 'input' argument to " "'shape_n' Op, not %r." % input) _attr_N = len(input) if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "ShapeN", input=input, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("N", _op.get_attr("N"), "T", _op.get_attr("T"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "ShapeN", _inputs_flat, _attrs, _result, name) return _result def shape_n_eager_fallback(input, out_type=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function shape_n """ _ctx = ctx if ctx else _context.context() if not isinstance(input, (list, tuple)): raise TypeError( "Expected list for 'input' argument to " "'shape_n' Op, not %r." % input) _attr_N = len(input) if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _attr_T, input = _execute.args_to_matching_eager(list(input), _ctx) _inputs_flat = list(input) _attrs = ("N", _attr_N, "T", _attr_T, "out_type", out_type) _result = _execute.execute(b"ShapeN", _attr_N, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ShapeN", _inputs_flat, _attrs, _result, name) return _result def size(input, out_type=_dtypes.int32, name=None): r"""Returns the size of a tensor. This operation returns an integer representing the number of elements in `input`. For example: ``` # 't' is [[[1, 1,, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]] size(t) ==> 12 ``` Args: input: A `Tensor`. out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A `Tensor` of type `out_type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Size", name, _ctx._post_execution_callbacks, input, "out_type", out_type) return _result except _core._FallbackException: try: return size_eager_fallback( input, out_type=out_type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "Size", input=input, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "Size", _inputs_flat, _attrs, _result, name) _result, = _result return _result def size_eager_fallback(input, out_type=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function size """ _ctx = ctx if ctx else _context.context() if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "out_type", out_type) _result = _execute.execute(b"Size", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Size", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _slice(input, begin, size, name=None): r"""Return a slice from 'input'. The output tensor is a tensor with dimensions described by 'size' whose values are extracted from 'input' starting at the offsets in 'begin'. *Requirements*: 0 <= begin[i] <= begin[i] + size[i] <= Di for i in [0, n) Args: input: A `Tensor`. begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. begin[i] specifies the offset into the 'i'th dimension of 'input' to slice from. size: A `Tensor`. Must have the same type as `begin`. size[i] specifies the number of elements of the 'i'th dimension of 'input' to slice. If size[i] is -1, all remaining elements in dimension i are included in the slice (i.e. this is equivalent to setting size[i] = input.dim_size(i) - begin[i]). name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Slice", name, _ctx._post_execution_callbacks, input, begin, size) return _result except _core._FallbackException: try: return _slice_eager_fallback( input, begin, size, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Slice", input=input, begin=begin, size=size, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Index", _op.get_attr("Index")) _execute.record_gradient( "Slice", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _slice_eager_fallback(input, begin, size, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function _slice """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, size], _ctx) (begin, size) = _inputs_Index _inputs_flat = [input, begin, size] _attrs = ("T", _attr_T, "Index", _attr_Index) _result = _execute.execute(b"Slice", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Slice", _inputs_flat, _attrs, _result, name) _result, = _result return _result def snapshot(input, name=None): r"""Returns a copy of the input tensor. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Snapshot", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return snapshot_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Snapshot", input=input, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Snapshot", _inputs_flat, _attrs, _result, name) _result, = _result return _result def snapshot_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function snapshot """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"Snapshot", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Snapshot", _inputs_flat, _attrs, _result, name) _result, = _result return _result def space_to_batch(input, paddings, block_size, name=None): r"""SpaceToBatch for 4-D tensors of type T. This is a legacy version of the more general SpaceToBatchND. Zero-pads and then rearranges (permutes) blocks of spatial data into batch. More specifically, this op outputs a copy of the input tensor where values from the `height` and `width` dimensions are moved to the `batch` dimension. After the zero-padding, both `height` and `width` of the input must be divisible by the block size. Args: input: A `Tensor`. 4-D with shape `[batch, height, width, depth]`. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. 2-D tensor of non-negative integers with shape `[2, 2]`. It specifies the padding of the input with zeros across the spatial dimensions as follows: paddings = [[pad_top, pad_bottom], [pad_left, pad_right]] The effective spatial dimensions of the zero-padded input tensor will be: height_pad = pad_top + height + pad_bottom width_pad = pad_left + width + pad_right The attr `block_size` must be greater than one. It indicates the block size. * Non-overlapping blocks of size `block_size x block size` in the height and width dimensions are rearranged into the batch dimension at each location. * The batch of the output tensor is `batch * block_size * block_size`. * Both height_pad and width_pad must be divisible by block_size. The shape of the output will be: [batch*block_size*block_size, height_pad/block_size, width_pad/block_size, depth] Some examples: (1) For the following input of shape `[1, 2, 2, 1]` and block_size of 2: ``` x = [[[[1], [2]], [[3], [4]]]] ``` The output tensor has shape `[4, 1, 1, 1]` and value: ``` [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] ``` (2) For the following input of shape `[1, 2, 2, 3]` and block_size of 2: ``` x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] ``` The output tensor has shape `[4, 1, 1, 3]` and value: ``` [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]], [[10, 11, 12]]] ``` (3) For the following input of shape `[1, 4, 4, 1]` and block_size of 2: ``` x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]]] ``` The output tensor has shape `[4, 2, 2, 1]` and value: ``` x = [[[[1], [3]], [[9], [11]]], [[[2], [4]], [[10], [12]]], [[[5], [7]], [[13], [15]]], [[[6], [8]], [[14], [16]]]] ``` (4) For the following input of shape `[2, 2, 4, 1]` and block_size of 2: ``` x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]] ``` The output tensor has shape `[8, 1, 2, 1]` and value: ``` x = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] ``` Among others, this operation is useful for reducing atrous convolution into regular convolution. block_size: An `int` that is `>= 2`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SpaceToBatch", name, _ctx._post_execution_callbacks, input, paddings, "block_size", block_size) return _result except _core._FallbackException: try: return space_to_batch_eager_fallback( input, paddings, block_size=block_size, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. block_size = _execute.make_int(block_size, "block_size") _, _, _op = _op_def_lib._apply_op_helper( "SpaceToBatch", input=input, paddings=paddings, block_size=block_size, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tpaddings", _op.get_attr("Tpaddings"), "block_size", _op.get_attr("block_size")) _execute.record_gradient( "SpaceToBatch", _inputs_flat, _attrs, _result, name) _result, = _result return _result def space_to_batch_eager_fallback(input, paddings, block_size, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function space_to_batch """ _ctx = ctx if ctx else _context.context() block_size = _execute.make_int(block_size, "block_size") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, paddings] _attrs = ("T", _attr_T, "Tpaddings", _attr_Tpaddings, "block_size", block_size) _result = _execute.execute(b"SpaceToBatch", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SpaceToBatch", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('space_to_batch_nd', v1=['space_to_batch_nd', 'manip.space_to_batch_nd']) @deprecated_endpoints('manip.space_to_batch_nd') def space_to_batch_nd(input, block_shape, paddings, name=None): r"""SpaceToBatch for N-D tensors of type T. This operation divides "spatial" dimensions `[1, ..., M]` of the input into a grid of blocks of shape `block_shape`, and interleaves these blocks with the "batch" dimension (0) such that in the output, the spatial dimensions `[1, ..., M]` correspond to the position within the grid, and the batch dimension combines both the position within a spatial block and the original batch position. Prior to division into blocks, the spatial dimensions of the input are optionally zero padded according to `paddings`. See below for a precise description. Args: input: A `Tensor`. N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, where spatial_shape has `M` dimensions. block_shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D with shape `[M]`, all values must be >= 1. paddings: A `Tensor`. Must be one of the following types: `int32`, `int64`. 2-D with shape `[M, 2]`, all values must be >= 0. `paddings[i] = [pad_start, pad_end]` specifies the padding for input dimension `i + 1`, which corresponds to spatial dimension `i`. It is required that `block_shape[i]` divides `input_shape[i + 1] + pad_start + pad_end`. This operation is equivalent to the following steps: 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the input according to `paddings` to produce `padded` of shape `padded_shape`. 2. Reshape `padded` to `reshaped_padded` of shape: [batch] + [padded_shape[1] / block_shape[0], block_shape[0], ..., padded_shape[M] / block_shape[M-1], block_shape[M-1]] + remaining_shape 3. Permute dimensions of `reshaped_padded` to produce `permuted_reshaped_padded` of shape: block_shape + [batch] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the batch dimension, producing an output tensor of shape: [batch * prod(block_shape)] + [padded_shape[1] / block_shape[0], ..., padded_shape[M] / block_shape[M-1]] + remaining_shape Some examples: (1) For the following input of shape `[1, 2, 2, 1]`, `block_shape = [2, 2]`, and `paddings = [[0, 0], [0, 0]]`: ``` x = [[[[1], [2]], [[3], [4]]]] ``` The output tensor has shape `[4, 1, 1, 1]` and value: ``` [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] ``` (2) For the following input of shape `[1, 2, 2, 3]`, `block_shape = [2, 2]`, and `paddings = [[0, 0], [0, 0]]`: ``` x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] ``` The output tensor has shape `[4, 1, 1, 3]` and value: ``` [[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]], [[10, 11, 12]]] ``` (3) For the following input of shape `[1, 4, 4, 1]`, `block_shape = [2, 2]`, and `paddings = [[0, 0], [0, 0]]`: ``` x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], [[9], [10], [11], [12]], [[13], [14], [15], [16]]]] ``` The output tensor has shape `[4, 2, 2, 1]` and value: ``` x = [[[[1], [3]], [[9], [11]]], [[[2], [4]], [[10], [12]]], [[[5], [7]], [[13], [15]]], [[[6], [8]], [[14], [16]]]] ``` (4) For the following input of shape `[2, 2, 4, 1]`, block_shape = `[2, 2]`, and paddings = `[[0, 0], [2, 0]]`: ``` x = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]] ``` The output tensor has shape `[8, 1, 3, 1]` and value: ``` x = [[[[0], [1], [3]]], [[[0], [9], [11]]], [[[0], [2], [4]]], [[[0], [10], [12]]], [[[0], [5], [7]]], [[[0], [13], [15]]], [[[0], [6], [8]]], [[[0], [14], [16]]]] ``` Among others, this operation is useful for reducing atrous convolution into regular convolution. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SpaceToBatchND", name, _ctx._post_execution_callbacks, input, block_shape, paddings) return _result except _core._FallbackException: try: return space_to_batch_nd_eager_fallback( input, block_shape, paddings, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( space_to_batch_nd, input=input, block_shape=block_shape, paddings=paddings, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "SpaceToBatchND", input=input, block_shape=block_shape, paddings=paddings, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( space_to_batch_nd, input=input, block_shape=block_shape, paddings=paddings, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tblock_shape", _op.get_attr("Tblock_shape"), "Tpaddings", _op.get_attr("Tpaddings")) _execute.record_gradient( "SpaceToBatchND", _inputs_flat, _attrs, _result, name) _result, = _result return _result def space_to_batch_nd_eager_fallback(input, block_shape, paddings, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function space_to_batch_nd """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tblock_shape, (block_shape,) = _execute.args_to_matching_eager([block_shape], _ctx, _dtypes.int32) _attr_Tpaddings, (paddings,) = _execute.args_to_matching_eager([paddings], _ctx, _dtypes.int32) _inputs_flat = [input, block_shape, paddings] _attrs = ("T", _attr_T, "Tblock_shape", _attr_Tblock_shape, "Tpaddings", _attr_Tpaddings) _result = _execute.execute(b"SpaceToBatchND", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SpaceToBatchND", _inputs_flat, _attrs, _result, name) _result, = _result return _result def space_to_depth(input, block_size, data_format="NHWC", name=None): r"""SpaceToDepth for tensors of type T. Rearranges blocks of spatial data, into depth. More specifically, this op outputs a copy of the input tensor where values from the `height` and `width` dimensions are moved to the `depth` dimension. The attr `block_size` indicates the input block size. * Non-overlapping blocks of size `block_size x block size` are rearranged into depth at each location. * The depth of the output tensor is `block_size * block_size * input_depth`. * The Y, X coordinates within each block of the input become the high order component of the output channel index. * The input tensor's height and width must be divisible by block_size. The `data_format` attr specifies the layout of the input and output tensors with the following options: "NHWC": `[ batch, height, width, channels ]` "NCHW": `[ batch, channels, height, width ]` "NCHW_VECT_C": `qint8 [ batch, channels / 4, height, width, 4 ]` It is useful to consider the operation as transforming a 6-D Tensor. e.g. for data_format = NHWC, Each element in the input tensor can be specified via 6 coordinates, ordered by decreasing memory layout significance as: n,oY,bY,oX,bX,iC (where n=batch index, oX, oY means X or Y coordinates within the output image, bX, bY means coordinates within the input block, iC means input channels). The output would be a transpose to the following layout: n,oY,oX,bY,bX,iC This operation is useful for resizing the activations between convolutions (but keeping all data), e.g. instead of pooling. It is also useful for training purely convolutional models. For example, given an input of shape `[1, 2, 2, 1]`, data_format = "NHWC" and block_size = 2: ``` x = [[[[1], [2]], [[3], [4]]]] ``` This operation will output a tensor of shape `[1, 1, 1, 4]`: ``` [[[[1, 2, 3, 4]]]] ``` Here, the input has a batch of 1 and each batch element has shape `[2, 2, 1]`, the corresponding output will have a single element (i.e. width and height are both 1) and will have a depth of 4 channels (1 * block_size * block_size). The output element shape is `[1, 1, 4]`. For an input tensor with larger depth, here of shape `[1, 2, 2, 3]`, e.g. ``` x = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] ``` This operation, for block_size of 2, will return the following tensor of shape `[1, 1, 1, 12]` ``` [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]] ``` Similarly, for the following input of shape `[1 4 4 1]`, and a block size of 2: ``` x = [[[[1], [2], [5], [6]], [[3], [4], [7], [8]], [[9], [10], [13], [14]], [[11], [12], [15], [16]]]] ``` the operator will return the following tensor of shape `[1 2 2 4]`: ``` x = [[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]] ``` Args: input: A `Tensor`. block_size: An `int` that is `>= 2`. The size of the spatial block. data_format: An optional `string` from: `"NHWC", "NCHW", "NCHW_VECT_C"`. Defaults to `"NHWC"`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SpaceToDepth", name, _ctx._post_execution_callbacks, input, "block_size", block_size, "data_format", data_format) return _result except _core._FallbackException: try: return space_to_depth_eager_fallback( input, block_size=block_size, data_format=data_format, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. block_size = _execute.make_int(block_size, "block_size") if data_format is None: data_format = "NHWC" data_format = _execute.make_str(data_format, "data_format") _, _, _op = _op_def_lib._apply_op_helper( "SpaceToDepth", input=input, block_size=block_size, data_format=data_format, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "block_size", _op.get_attr("block_size"), "data_format", _op.get_attr("data_format")) _execute.record_gradient( "SpaceToDepth", _inputs_flat, _attrs, _result, name) _result, = _result return _result def space_to_depth_eager_fallback(input, block_size, data_format="NHWC", name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function space_to_depth """ _ctx = ctx if ctx else _context.context() block_size = _execute.make_int(block_size, "block_size") if data_format is None: data_format = "NHWC" data_format = _execute.make_str(data_format, "data_format") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "block_size", block_size, "data_format", data_format) _result = _execute.execute(b"SpaceToDepth", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SpaceToDepth", _inputs_flat, _attrs, _result, name) _result, = _result return _result def split(axis, value, num_split, name=None): r"""Splits a tensor into `num_split` tensors along one dimension. Args: axis: A `Tensor` of type `int32`. 0-D. The dimension along which to split. Must be in the range `[-rank(value), rank(value))`. value: A `Tensor`. The tensor to split. num_split: An `int` that is `>= 1`. The number of ways to split. Must evenly divide `value.shape[split_dim]`. name: A name for the operation (optional). Returns: A list of `num_split` `Tensor` objects with the same type as `value`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Split", name, _ctx._post_execution_callbacks, axis, value, "num_split", num_split) return _result except _core._FallbackException: try: return split_eager_fallback( axis, value, num_split=num_split, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. num_split = _execute.make_int(num_split, "num_split") _, _, _op = _op_def_lib._apply_op_helper( "Split", split_dim=axis, value=value, num_split=num_split, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_split", _op.get_attr("num_split"), "T", _op.get_attr("T")) _execute.record_gradient( "Split", _inputs_flat, _attrs, _result, name) return _result def split_eager_fallback(axis, value, num_split, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function split """ _ctx = ctx if ctx else _context.context() num_split = _execute.make_int(num_split, "num_split") _attr_T, (value,) = _execute.args_to_matching_eager([value], _ctx) axis = _ops.convert_to_tensor(axis, _dtypes.int32) _inputs_flat = [axis, value] _attrs = ("num_split", num_split, "T", _attr_T) _result = _execute.execute(b"Split", num_split, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Split", _inputs_flat, _attrs, _result, name) return _result def split_v(value, size_splits, axis, num_split, name=None): r"""Splits a tensor into `num_split` tensors along one dimension. Args: value: A `Tensor`. The tensor to split. size_splits: A `Tensor`. Must be one of the following types: `int32`, `int64`. list containing the sizes of each output tensor along the split dimension. Must sum to the dimension of value along split_dim. Can contain one -1 indicating that dimension is to be inferred. axis: A `Tensor` of type `int32`. 0-D. The dimension along which to split. Must be in the range `[-rank(value), rank(value))`. num_split: An `int` that is `>= 1`. name: A name for the operation (optional). Returns: A list of `num_split` `Tensor` objects with the same type as `value`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "SplitV", name, _ctx._post_execution_callbacks, value, size_splits, axis, "num_split", num_split) return _result except _core._FallbackException: try: return split_v_eager_fallback( value, size_splits, axis, num_split=num_split, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. num_split = _execute.make_int(num_split, "num_split") _, _, _op = _op_def_lib._apply_op_helper( "SplitV", value=value, size_splits=size_splits, split_dim=axis, num_split=num_split, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num_split", _op.get_attr("num_split"), "T", _op.get_attr("T"), "Tlen", _op.get_attr("Tlen")) _execute.record_gradient( "SplitV", _inputs_flat, _attrs, _result, name) return _result def split_v_eager_fallback(value, size_splits, axis, num_split, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function split_v """ _ctx = ctx if ctx else _context.context() num_split = _execute.make_int(num_split, "num_split") _attr_T, (value,) = _execute.args_to_matching_eager([value], _ctx) _attr_Tlen, (size_splits,) = _execute.args_to_matching_eager([size_splits], _ctx, _dtypes.int64) axis = _ops.convert_to_tensor(axis, _dtypes.int32) _inputs_flat = [value, size_splits, axis] _attrs = ("num_split", num_split, "T", _attr_T, "Tlen", _attr_Tlen) _result = _execute.execute(b"SplitV", num_split, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "SplitV", _inputs_flat, _attrs, _result, name) return _result def squeeze(input, axis=[], name=None): r"""Removes dimensions of size 1 from the shape of a tensor. Given a tensor `input`, this operation returns a tensor of the same type with all dimensions of size 1 removed. If you don't want to remove all size 1 dimensions, you can remove specific size 1 dimensions by specifying `axis`. For example: ``` # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t)) ==> [2, 3] ``` Or, to remove specific size 1 dimensions: ``` # 't' is a tensor of shape [1, 2, 1, 3, 1, 1] shape(squeeze(t, [2, 4])) ==> [1, 2, 3, 1] ``` Args: input: A `Tensor`. The `input` to squeeze. axis: An optional list of `ints`. Defaults to `[]`. If specified, only squeezes the dimensions listed. The dimension index starts at 0. It is an error to squeeze a dimension that is not 1. Must be in the range `[-rank(input), rank(input))`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Squeeze", name, _ctx._post_execution_callbacks, input, "squeeze_dims", axis) return _result except _core._FallbackException: try: return squeeze_eager_fallback( input, axis=axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if axis is None: axis = [] if not isinstance(axis, (list, tuple)): raise TypeError( "Expected list for 'axis' argument to " "'squeeze' Op, not %r." % axis) axis = [_execute.make_int(_i, "axis") for _i in axis] _, _, _op = _op_def_lib._apply_op_helper( "Squeeze", input=input, squeeze_dims=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "squeeze_dims", _op.get_attr("squeeze_dims")) _execute.record_gradient( "Squeeze", _inputs_flat, _attrs, _result, name) _result, = _result return _result def squeeze_eager_fallback(input, axis=[], name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function squeeze """ _ctx = ctx if ctx else _context.context() if axis is None: axis = [] if not isinstance(axis, (list, tuple)): raise TypeError( "Expected list for 'axis' argument to " "'squeeze' Op, not %r." % axis) axis = [_execute.make_int(_i, "axis") for _i in axis] _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T, "squeeze_dims", axis) _result = _execute.execute(b"Squeeze", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Squeeze", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('stop_gradient') def stop_gradient(input, name=None): r"""Stops gradient computation. When executed in a graph, this op outputs its input tensor as-is. When building ops to compute gradients, this op prevents the contribution of its inputs to be taken into account. Normally, the gradient generator adds ops to a graph to compute the derivatives of a specified 'loss' by recursively finding out inputs that contributed to its computation. If you insert this op in the graph it inputs are masked from the gradient generator. They are not taken into account for computing gradients. This is useful any time you want to compute a value with TensorFlow but need to pretend that the value was a constant. Some examples include: * The *EM* algorithm where the *M-step* should not involve backpropagation through the output of the *E-step*. * Contrastive divergence training of Boltzmann machines where, when differentiating the energy function, the training must not backpropagate through the graph that generated the samples from the model. * Adversarial training, where no backprop should happen through the adversarial example generation process. Args: input: A `Tensor`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "StopGradient", name, _ctx._post_execution_callbacks, input) return _result except _core._FallbackException: try: return stop_gradient_eager_fallback( input, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( stop_gradient, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "StopGradient", input=input, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( stop_gradient, input=input, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "StopGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result def stop_gradient_eager_fallback(input, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function stop_gradient """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _inputs_flat = [input] _attrs = ("T", _attr_T) _result = _execute.execute(b"StopGradient", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "StopGradient", _inputs_flat, _attrs, _result, name) _result, = _result return _result def strided_slice(input, begin, end, strides, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None): r"""Return a strided slice from `input`. Note, most python users will want to use the Python `Tensor.__getitem__` or `Variable.__getitem__` rather than this op directly. The goal of this op is to produce a new tensor with a subset of the elements from the `n` dimensional `input` tensor. The subset is chosen using a sequence of `m` sparse range specifications encoded into the arguments of this function. Note, in some cases `m` could be equal to `n`, but this need not be the case. Each range specification entry can be one of the following: - An ellipsis (...). Ellipses are used to imply zero or more dimensions of full-dimension selection and are produced using `ellipsis_mask`. For example, `foo[...]` is the identity slice. - A new axis. This is used to insert a new shape=1 dimension and is produced using `new_axis_mask`. For example, `foo[:, ...]` where `foo` is shape `(3, 4)` produces a `(1, 3, 4)` tensor. - A range `begin:end:stride`. This is used to specify how much to choose from a given dimension. `stride` can be any integer but 0. `begin` is an integer which represents the index of the first value to select while `end` represents the index of the last value to select. The number of values selected in each dimension is `end - begin` if `stride > 0` and `begin - end` if `stride < 0`. `begin` and `end` can be negative where `-1` is the last element, `-2` is the second to last. `begin_mask` controls whether to replace the explicitly given `begin` with an implicit effective value of `0` if `stride > 0` and `-1` if `stride < 0`. `end_mask` is analogous but produces the number required to create the largest open interval. For example, given a shape `(3,)` tensor `foo[:]`, the effective `begin` and `end` are `0` and `3`. Do not assume this is equivalent to `foo[0:-1]` which has an effective `begin` and `end` of `0` and `2`. Another example is `foo[-2::-1]` which reverses the first dimension of a tensor while dropping the last two (in the original order elements). For example `foo = [1,2,3,4]; foo[-2::-1]` is `[4,3]`. - A single index. This is used to keep only elements that have a given index. For example (`foo[2, :]` on a shape `(5,6)` tensor produces a shape `(6,)` tensor. This is encoded in `begin` and `end` and `shrink_axis_mask`. Each conceptual range specification is encoded in the op's argument. This encoding is best understand by considering a non-trivial example. In particular, `foo[1, 2:4, None, ..., :-3:-1, :]` will be encoded as ``` begin = [1, 2, x, x, 0, x] # x denotes don't care (usually 0) end = [2, 4, x, x, -3, x] strides = [1, 1, x, x, -1, 1] begin_mask = 1<<4 | 1 << 5 = 48 end_mask = 1<<5 = 32 ellipsis_mask = 1<<3 = 8 new_axis_mask = 1<<2 4 shrink_axis_mask = 1<<0 ``` In this case if `foo.shape` is (5, 5, 5, 5, 5, 5) the final shape of the slice becomes (2, 1, 5, 5, 2, 5). Let us walk step by step through each argument specification. 1. The first argument in the example slice is turned into `begin = 1` and `end = begin + 1 = 2`. To disambiguate from the original spec `2:4` we also set the appropriate bit in `shrink_axis_mask`. 2. `2:4` is contributes 2, 4, 1 to begin, end, and stride. All masks have zero bits contributed. 3. None is a synonym for `tf.newaxis`. This means insert a dimension of size 1 dimension in the final shape. Dummy values are contributed to begin, end and stride, while the new_axis_mask bit is set. 4. `...` grab the full ranges from as many dimensions as needed to fully specify a slice for every dimension of the input shape. 5. `:-3:-1` shows the use of negative indices. A negative index `i` associated with a dimension that has shape `s` is converted to a positive index `s + i`. So `-1` becomes `s-1` (i.e. the last element). This conversion is done internally so begin, end and strides receive x, -3, and -1. The appropriate begin_mask bit is set to indicate the start range is the full range (ignoring the x). 6. `:` indicates that the entire contents of the corresponding dimension is selected. This is equivalent to `::` or `0::1`. begin, end, and strides receive 0, 0, and 1, respectively. The appropriate bits in `begin_mask` and `end_mask` are also set. *Requirements*: `0 != strides[i] for i in [0, m)` `ellipsis_mask must be a power of two (only one ellipsis)` Args: input: A `Tensor`. begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. `begin[k]` specifies the offset into the `k`th range specification. The exact dimension this corresponds to will be determined by context. Out-of-bounds values will be silently clamped. If the `k`th bit of `begin_mask` then `begin[k]` is ignored and the full range of the appropriate dimension is used instead. Negative values causes indexing to start from the highest element e.g. If `foo==[1,2,3]` then `foo[-1]==3`. end: A `Tensor`. Must have the same type as `begin`. `end[i]` is like `begin` with the exception that `end_mask` is used to determine full ranges. strides: A `Tensor`. Must have the same type as `begin`. `strides[i]` specifies the increment in the `i`th specification after extracting a given element. Negative indices will reverse the original order. Out or range values are clamped to `[0,dim[i]) if slice[i]>0` or `[-1,dim[i]-1] if slice[i] < 0` begin_mask: An optional `int`. Defaults to `0`. a bitmask where a bit i being 1 means to ignore the begin value and instead use the largest interval possible. At runtime begin[i] will be replaced with `[0, n-1)` if `stride[i] > 0` or `[-1, n-1]` if `stride[i] < 0` end_mask: An optional `int`. Defaults to `0`. analogous to `begin_mask` ellipsis_mask: An optional `int`. Defaults to `0`. a bitmask where bit `i` being 1 means the `i`th position is actually an ellipsis. One bit at most can be 1. If `ellipsis_mask == 0`, then an implicit ellipsis mask of `1 << (m+1)` is provided. This means that `foo[3:5] == foo[3:5, ...]`. An ellipsis implicitly creates as many range specifications as necessary to fully specify the sliced range for every dimension. For example for a 4-dimensional tensor `foo` the slice `foo[2, ..., 5:8]` implies `foo[2, :, :, 5:8]`. new_axis_mask: An optional `int`. Defaults to `0`. a bitmask where bit `i` being 1 means the `i`th specification creates a new shape 1 dimension. For example `foo[:4, tf.newaxis, :2]` would produce a shape `(4, 1, 2)` tensor. shrink_axis_mask: An optional `int`. Defaults to `0`. a bitmask where bit `i` implies that the `i`th specification should shrink the dimensionality. begin and end must imply a slice of size 1 in the dimension. For example in python one might do `foo[:, 3, :]` which would result in `shrink_axis_mask` being 2. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "StridedSlice", name, _ctx._post_execution_callbacks, input, begin, end, strides, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) return _result except _core._FallbackException: try: return strided_slice_eager_fallback( input, begin, end, strides, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _, _, _op = _op_def_lib._apply_op_helper( "StridedSlice", input=input, begin=begin, end=end, strides=strides, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Index", _op.get_attr("Index"), "begin_mask", _op.get_attr("begin_mask"), "end_mask", _op.get_attr("end_mask"), "ellipsis_mask", _op.get_attr("ellipsis_mask"), "new_axis_mask", _op.get_attr("new_axis_mask"), "shrink_axis_mask", _op.get_attr("shrink_axis_mask")) _execute.record_gradient( "StridedSlice", _inputs_flat, _attrs, _result, name) _result, = _result return _result def strided_slice_eager_fallback(input, begin, end, strides, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function strided_slice """ _ctx = ctx if ctx else _context.context() if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Index, _inputs_Index = _execute.args_to_matching_eager([begin, end, strides], _ctx) (begin, end, strides) = _inputs_Index _inputs_flat = [input, begin, end, strides] _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) _result = _execute.execute(b"StridedSlice", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "StridedSlice", _inputs_flat, _attrs, _result, name) _result, = _result return _result def strided_slice_assign(ref, begin, end, strides, value, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None): r"""Assign `value` to the sliced l-value reference of `ref`. The values of `value` are assigned to the positions in the variable `ref` that are selected by the slice parameters. The slice parameters `begin, `end`, `strides`, etc. work exactly as in `StridedSlice`. NOTE this op currently does not support broadcasting and so `value`'s shape must be exactly the shape produced by the slice of `ref`. Args: ref: A mutable `Tensor`. begin: A `Tensor`. Must be one of the following types: `int32`, `int64`. end: A `Tensor`. Must have the same type as `begin`. strides: A `Tensor`. Must have the same type as `begin`. value: A `Tensor`. Must have the same type as `ref`. begin_mask: An optional `int`. Defaults to `0`. end_mask: An optional `int`. Defaults to `0`. ellipsis_mask: An optional `int`. Defaults to `0`. new_axis_mask: An optional `int`. Defaults to `0`. shrink_axis_mask: An optional `int`. Defaults to `0`. name: A name for the operation (optional). Returns: A mutable `Tensor`. Has the same type as `ref`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: raise RuntimeError("strided_slice_assign op does not support eager execution. Arg 'output_ref' is a ref.") # Add nodes to the TensorFlow graph. if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _, _, _op = _op_def_lib._apply_op_helper( "StridedSliceAssign", ref=ref, begin=begin, end=end, strides=strides, value=value, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Index", _op.get_attr("Index"), "begin_mask", _op.get_attr("begin_mask"), "end_mask", _op.get_attr("end_mask"), "ellipsis_mask", _op.get_attr("ellipsis_mask"), "new_axis_mask", _op.get_attr("new_axis_mask"), "shrink_axis_mask", _op.get_attr("shrink_axis_mask")) _execute.record_gradient( "StridedSliceAssign", _inputs_flat, _attrs, _result, name) _result, = _result return _result def strided_slice_assign_eager_fallback(ref, begin, end, strides, value, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None, ctx=None): raise RuntimeError("strided_slice_assign op does not support eager execution. Arg 'output_ref' is a ref.") def strided_slice_grad(shape, begin, end, strides, dy, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None): r"""Returns the gradient of `StridedSlice`. Since `StridedSlice` cuts out pieces of its `input` which is size `shape`, its gradient will have the same shape (which is passed here as `shape`). The gradient will be zero in any element that the slice does not select. Arguments are the same as StridedSliceGrad with the exception that `dy` is the input gradient to be propagated and `shape` is the shape of `StridedSlice`'s `input`. Args: shape: A `Tensor`. Must be one of the following types: `int32`, `int64`. begin: A `Tensor`. Must have the same type as `shape`. end: A `Tensor`. Must have the same type as `shape`. strides: A `Tensor`. Must have the same type as `shape`. dy: A `Tensor`. begin_mask: An optional `int`. Defaults to `0`. end_mask: An optional `int`. Defaults to `0`. ellipsis_mask: An optional `int`. Defaults to `0`. new_axis_mask: An optional `int`. Defaults to `0`. shrink_axis_mask: An optional `int`. Defaults to `0`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `dy`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "StridedSliceGrad", name, _ctx._post_execution_callbacks, shape, begin, end, strides, dy, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) return _result except _core._FallbackException: try: return strided_slice_grad_eager_fallback( shape, begin, end, strides, dy, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _, _, _op = _op_def_lib._apply_op_helper( "StridedSliceGrad", shape=shape, begin=begin, end=end, strides=strides, dy=dy, begin_mask=begin_mask, end_mask=end_mask, ellipsis_mask=ellipsis_mask, new_axis_mask=new_axis_mask, shrink_axis_mask=shrink_axis_mask, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Index", _op.get_attr("Index"), "begin_mask", _op.get_attr("begin_mask"), "end_mask", _op.get_attr("end_mask"), "ellipsis_mask", _op.get_attr("ellipsis_mask"), "new_axis_mask", _op.get_attr("new_axis_mask"), "shrink_axis_mask", _op.get_attr("shrink_axis_mask")) _execute.record_gradient( "StridedSliceGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def strided_slice_grad_eager_fallback(shape, begin, end, strides, dy, begin_mask=0, end_mask=0, ellipsis_mask=0, new_axis_mask=0, shrink_axis_mask=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function strided_slice_grad """ _ctx = ctx if ctx else _context.context() if begin_mask is None: begin_mask = 0 begin_mask = _execute.make_int(begin_mask, "begin_mask") if end_mask is None: end_mask = 0 end_mask = _execute.make_int(end_mask, "end_mask") if ellipsis_mask is None: ellipsis_mask = 0 ellipsis_mask = _execute.make_int(ellipsis_mask, "ellipsis_mask") if new_axis_mask is None: new_axis_mask = 0 new_axis_mask = _execute.make_int(new_axis_mask, "new_axis_mask") if shrink_axis_mask is None: shrink_axis_mask = 0 shrink_axis_mask = _execute.make_int(shrink_axis_mask, "shrink_axis_mask") _attr_T, (dy,) = _execute.args_to_matching_eager([dy], _ctx) _attr_Index, _inputs_Index = _execute.args_to_matching_eager([shape, begin, end, strides], _ctx) (shape, begin, end, strides) = _inputs_Index _inputs_flat = [shape, begin, end, strides, dy] _attrs = ("T", _attr_T, "Index", _attr_Index, "begin_mask", begin_mask, "end_mask", end_mask, "ellipsis_mask", ellipsis_mask, "new_axis_mask", new_axis_mask, "shrink_axis_mask", shrink_axis_mask) _result = _execute.execute(b"StridedSliceGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "StridedSliceGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('tensor_scatter_add') def tensor_scatter_add(tensor, indices, updates, name=None): r"""Adds sparse `updates` to an existing tensor according to `indices`. This operation creates a new tensor by adding sparse `updates` to the passed in `tensor`. This operation is very similar to `tf.scatter_nd_add`, except that the updates are added onto an existing tensor (as opposed to a variable). If the memory for the existing tensor cannot be re-used, a copy is made and updated. `indices` is an integer tensor containing indices into a new tensor of shape `shape`. The last dimension of `indices` can be at most the rank of `shape`: indices.shape[-1] <= shape.rank The last dimension of `indices` corresponds to indices into elements (if `indices.shape[-1] = shape.rank`) or slices (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of `shape`. `updates` is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:] The simplest form of tensor_scatter_add is to add individual elements to a tensor by index. For example, say we want to add 4 elements in a rank-1 tensor with 8 elements. In Python, this scatter add operation would look like this: ```python indices = tf.constant([[4], [3], [1], [7]]) updates = tf.constant([9, 10, 11, 12]) tensor = tf.ones([8], dtype=tf.int32) updated = tf.tensor_scatter_add(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [1, 12, 1, 11, 10, 1, 1, 13] We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter add operation would look like this: ```python indices = tf.constant([[0], [2]]) updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]) tensor = tf.ones([4, 4, 4]) updated = tf.tensor_scatter_add(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [[[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored. Args: tensor: A `Tensor`. Tensor to copy/update. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. updates: A `Tensor`. Must have the same type as `tensor`. Updates to scatter into output. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TensorScatterAdd", name, _ctx._post_execution_callbacks, tensor, indices, updates) return _result except _core._FallbackException: try: return tensor_scatter_add_eager_fallback( tensor, indices, updates, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_add, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "TensorScatterAdd", tensor=tensor, indices=indices, updates=updates, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_add, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "TensorScatterAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tensor_scatter_add_eager_fallback(tensor, indices, updates, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tensor_scatter_add """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], _ctx) (tensor, updates) = _inputs_T _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [tensor, indices, updates] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"TensorScatterAdd", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TensorScatterAdd", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('tensor_scatter_sub') def tensor_scatter_sub(tensor, indices, updates, name=None): r"""Subtracts sparse `updates` from an existing tensor according to `indices`. This operation creates a new tensor by subtracting sparse `updates` from the passed in `tensor`. This operation is very similar to `tf.scatter_nd_sub`, except that the updates are subtracted from an existing tensor (as opposed to a variable). If the memory for the existing tensor cannot be re-used, a copy is made and updated. `indices` is an integer tensor containing indices into a new tensor of shape `shape`. The last dimension of `indices` can be at most the rank of `shape`: indices.shape[-1] <= shape.rank The last dimension of `indices` corresponds to indices into elements (if `indices.shape[-1] = shape.rank`) or slices (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of `shape`. `updates` is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:] The simplest form of tensor_scatter_sub is to subtract individual elements from a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements. In Python, this scatter subtract operation would look like this: ```python indices = tf.constant([[4], [3], [1], [7]]) updates = tf.constant([9, 10, 11, 12]) tensor = tf.ones([8], dtype=tf.int32) updated = tf.tensor_scatter_sub(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [1, -10, 1, -9, -8, 1, 1, -11] We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter add operation would look like this: ```python indices = tf.constant([[0], [2]]) updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]) tensor = tf.ones([4, 4, 4]) updated = tf.tensor_scatter_sub(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored. Args: tensor: A `Tensor`. Tensor to copy/update. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. updates: A `Tensor`. Must have the same type as `tensor`. Updates to scatter into output. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TensorScatterSub", name, _ctx._post_execution_callbacks, tensor, indices, updates) return _result except _core._FallbackException: try: return tensor_scatter_sub_eager_fallback( tensor, indices, updates, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_sub, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "TensorScatterSub", tensor=tensor, indices=indices, updates=updates, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_sub, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "TensorScatterSub", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tensor_scatter_sub_eager_fallback(tensor, indices, updates, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tensor_scatter_sub """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], _ctx) (tensor, updates) = _inputs_T _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [tensor, indices, updates] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"TensorScatterSub", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TensorScatterSub", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('tensor_scatter_update') def tensor_scatter_update(tensor, indices, updates, name=None): r"""Scatter `updates` into an existing tensor according to `indices`. This operation creates a new tensor by applying sparse `updates` to the passed in `tensor`. This operation is very similar to `tf.scatter_nd`, except that the updates are scattered onto an existing tensor (as opposed to a zero-tensor). If the memory for the existing tensor cannot be re-used, a copy is made and updated. If `indices` contains duplicates, then their updates are accumulated (summed). **WARNING**: The order in which updates are applied is nondeterministic, so the output will be nondeterministic if `indices` contains duplicates -- because of some numerical approximation issues, numbers summed in different order may yield different results. `indices` is an integer tensor containing indices into a new tensor of shape `shape`. The last dimension of `indices` can be at most the rank of `shape`: indices.shape[-1] <= shape.rank The last dimension of `indices` corresponds to indices into elements (if `indices.shape[-1] = shape.rank`) or slices (if `indices.shape[-1] < shape.rank`) along dimension `indices.shape[-1]` of `shape`. `updates` is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:] The simplest form of scatter is to insert individual elements in a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements. <div style="width:70%; margin:auto; margin-bottom:10px; margin-top:20px;"> <img style="width:100%" src="https://www.tensorflow.org/images/ScatterNd1.png" alt> </div> In Python, this scatter operation would look like this: ```python indices = tf.constant([[4], [3], [1], [7]]) updates = tf.constant([9, 10, 11, 12]) tensor = tf.ones([8], dtype=tf.int32) updated = tf.tensor_scatter_update(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [1, 11, 1, 10, 9, 1, 1, 12] We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter operation would look like this: ```python indices = tf.constant([[0], [2]]) updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]]]) tensor = tf.ones([4, 4, 4]) updated = tf.tensor_scatter_update(tensor, indices, updates) with tf.Session() as sess: print(sess.run(scatter)) ``` The resulting tensor would look like this: [[[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]] Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored. Args: tensor: A `Tensor`. Tensor to copy/update. indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. updates: A `Tensor`. Must have the same type as `tensor`. Updates to scatter into output. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `tensor`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TensorScatterUpdate", name, _ctx._post_execution_callbacks, tensor, indices, updates) return _result except _core._FallbackException: try: return tensor_scatter_update_eager_fallback( tensor, indices, updates, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_update, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "TensorScatterUpdate", tensor=tensor, indices=indices, updates=updates, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( tensor_scatter_update, tensor=tensor, indices=indices, updates=updates, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tindices", _op.get_attr("Tindices")) _execute.record_gradient( "TensorScatterUpdate", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tensor_scatter_update_eager_fallback(tensor, indices, updates, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tensor_scatter_update """ _ctx = ctx if ctx else _context.context() _attr_T, _inputs_T = _execute.args_to_matching_eager([tensor, updates], _ctx) (tensor, updates) = _inputs_T _attr_Tindices, (indices,) = _execute.args_to_matching_eager([indices], _ctx) _inputs_flat = [tensor, indices, updates] _attrs = ("T", _attr_T, "Tindices", _attr_Tindices) _result = _execute.execute(b"TensorScatterUpdate", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TensorScatterUpdate", _inputs_flat, _attrs, _result, name) _result, = _result return _result @_dispatch.add_dispatch_list @tf_export('tile', v1=['tile', 'manip.tile']) @deprecated_endpoints('manip.tile') def tile(input, multiples, name=None): r"""Constructs a tensor by tiling a given tensor. This operation creates a new tensor by replicating `input` `multiples` times. The output tensor's i'th dimension has `input.dims(i) * multiples[i]` elements, and the values of `input` are replicated `multiples[i]` times along the 'i'th dimension. For example, tiling `[a b c d]` by `[2]` produces `[a b c d a b c d]`. Args: input: A `Tensor`. 1-D or higher. multiples: A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D. Length must be the same as the number of dimensions in `input` name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Tile", name, _ctx._post_execution_callbacks, input, multiples) return _result except _core._FallbackException: try: return tile_eager_fallback( input, multiples, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( tile, input=input, multiples=multiples, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "Tile", input=input, multiples=multiples, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( tile, input=input, multiples=multiples, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tmultiples", _op.get_attr("Tmultiples")) _execute.record_gradient( "Tile", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tile_eager_fallback(input, multiples, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tile """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) _attr_Tmultiples, (multiples,) = _execute.args_to_matching_eager([multiples], _ctx, _dtypes.int32) _inputs_flat = [input, multiples] _attrs = ("T", _attr_T, "Tmultiples", _attr_Tmultiples) _result = _execute.execute(b"Tile", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Tile", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tile_grad(input, multiples, name=None): r"""Returns the gradient of `Tile`. Since `Tile` takes an input and repeats the input `multiples` times along each dimension, `TileGrad` takes in `multiples` and aggregates each repeated tile of `input` into `output`. Args: input: A `Tensor`. multiples: A `Tensor` of type `int32`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "TileGrad", name, _ctx._post_execution_callbacks, input, multiples) return _result except _core._FallbackException: try: return tile_grad_eager_fallback( input, multiples, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "TileGrad", input=input, multiples=multiples, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "TileGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def tile_grad_eager_fallback(input, multiples, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function tile_grad """ _ctx = ctx if ctx else _context.context() _attr_T, (input,) = _execute.args_to_matching_eager([input], _ctx) multiples = _ops.convert_to_tensor(multiples, _dtypes.int32) _inputs_flat = [input, multiples] _attrs = ("T", _attr_T) _result = _execute.execute(b"TileGrad", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "TileGrad", _inputs_flat, _attrs, _result, name) _result, = _result return _result def transpose(x, perm, name=None): r"""Shuffle dimensions of x according to a permutation. The output `y` has the same rank as `x`. The shapes of `x` and `y` satisfy: `y.shape[i] == x.shape[perm[i]] for i in [0, 1, ..., rank(x) - 1]` Args: x: A `Tensor`. perm: A `Tensor`. Must be one of the following types: `int32`, `int64`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Transpose", name, _ctx._post_execution_callbacks, x, perm) return _result except _core._FallbackException: try: return transpose_eager_fallback( x, perm, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Transpose", x=x, perm=perm, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Tperm", _op.get_attr("Tperm")) _execute.record_gradient( "Transpose", _inputs_flat, _attrs, _result, name) _result, = _result return _result def transpose_eager_fallback(x, perm, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function transpose """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Tperm, (perm,) = _execute.args_to_matching_eager([perm], _ctx, _dtypes.int32) _inputs_flat = [x, perm] _attrs = ("T", _attr_T, "Tperm", _attr_Tperm) _result = _execute.execute(b"Transpose", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Transpose", _inputs_flat, _attrs, _result, name) _result, = _result return _result _unique_outputs = ["y", "idx"] _UniqueOutput = _collections.namedtuple( "Unique", _unique_outputs) def unique(x, out_idx=_dtypes.int32, name=None): r"""Finds unique elements in a 1-D tensor. This operation returns a tensor `y` containing all of the unique elements of `x` sorted in the same order that they occur in `x`. This operation also returns a tensor `idx` the same size as `x` that contains the index of each value of `x` in the unique output `y`. In other words: `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` For example: ``` # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] y, idx = unique(x) y ==> [1, 2, 4, 7, 8] idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] ``` Args: x: A `Tensor`. 1-D. out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (y, idx). y: A `Tensor`. Has the same type as `x`. idx: A `Tensor` of type `out_idx`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Unique", name, _ctx._post_execution_callbacks, x, "out_idx", out_idx) _result = _UniqueOutput._make(_result) return _result except _core._FallbackException: try: return unique_eager_fallback( x, out_idx=out_idx, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _, _, _op = _op_def_lib._apply_op_helper( "Unique", x=x, out_idx=out_idx, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_idx", _op.get_attr("out_idx")) _execute.record_gradient( "Unique", _inputs_flat, _attrs, _result, name) _result = _UniqueOutput._make(_result) return _result def unique_eager_fallback(x, out_idx=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unique """ _ctx = ctx if ctx else _context.context() if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T, "out_idx", out_idx) _result = _execute.execute(b"Unique", 2, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Unique", _inputs_flat, _attrs, _result, name) _result = _UniqueOutput._make(_result) return _result _unique_v2_outputs = ["y", "idx"] _UniqueV2Output = _collections.namedtuple( "UniqueV2", _unique_v2_outputs) def unique_v2(x, axis, out_idx=_dtypes.int32, name=None): r"""Finds unique elements along an axis of a tensor. This operation either returns a tensor `y` containing unique elements along the `axis` of a tensor. The returned unique elements is sorted in the same order as they occur along `axis` in `x`. This operation also returns a tensor `idx` that is the same size as the number of the elements in `x` along the `axis` dimension. It contains the index in the unique output `y`. In other words, for an `1-D` tensor `x` with `axis = None: `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` For example: ``` # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] y, idx = unique(x) y ==> [1, 2, 4, 7, 8] idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] ``` For an `2-D` tensor `x` with `axis = 0`: ``` # tensor 'x' is [[1, 0, 0], # [1, 0, 0], # [2, 0, 0]] y, idx = unique(x, axis=0) y ==> [[1, 0, 0], [2, 0, 0]] idx ==> [0, 0, 1] ``` For an `2-D` tensor `x` with `axis = 1`: ``` # tensor 'x' is [[1, 0, 0], # [1, 0, 0], # [2, 0, 0]] y, idx = unique(x, axis=1) y ==> [[1, 0], [1, 0], [2, 0]] idx ==> [0, 1, 1] ``` Args: x: A `Tensor`. A `Tensor`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. A `Tensor` of type `int32` (default: None). The axis of the Tensor to find the unique elements. out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (y, idx). y: A `Tensor`. Has the same type as `x`. idx: A `Tensor` of type `out_idx`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UniqueV2", name, _ctx._post_execution_callbacks, x, axis, "out_idx", out_idx) _result = _UniqueV2Output._make(_result) return _result except _core._FallbackException: try: return unique_v2_eager_fallback( x, axis, out_idx=out_idx, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _, _, _op = _op_def_lib._apply_op_helper( "UniqueV2", x=x, axis=axis, out_idx=out_idx, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Taxis", _op.get_attr("Taxis"), "out_idx", _op.get_attr("out_idx")) _execute.record_gradient( "UniqueV2", _inputs_flat, _attrs, _result, name) _result = _UniqueV2Output._make(_result) return _result def unique_v2_eager_fallback(x, axis, out_idx=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unique_v2 """ _ctx = ctx if ctx else _context.context() if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int64) _inputs_flat = [x, axis] _attrs = ("T", _attr_T, "Taxis", _attr_Taxis, "out_idx", out_idx) _result = _execute.execute(b"UniqueV2", 2, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UniqueV2", _inputs_flat, _attrs, _result, name) _result = _UniqueV2Output._make(_result) return _result _unique_with_counts_outputs = ["y", "idx", "count"] _UniqueWithCountsOutput = _collections.namedtuple( "UniqueWithCounts", _unique_with_counts_outputs) def unique_with_counts(x, out_idx=_dtypes.int32, name=None): r"""Finds unique elements in a 1-D tensor. This operation returns a tensor `y` containing all of the unique elements of `x` sorted in the same order that they occur in `x`. This operation also returns a tensor `idx` the same size as `x` that contains the index of each value of `x` in the unique output `y`. Finally, it returns a third tensor `count` that contains the count of each element of `y` in `x`. In other words: `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` For example: ``` # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] y, idx, count = unique_with_counts(x) y ==> [1, 2, 4, 7, 8] idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] count ==> [2, 1, 3, 1, 2] ``` Args: x: A `Tensor`. 1-D. out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (y, idx, count). y: A `Tensor`. Has the same type as `x`. idx: A `Tensor` of type `out_idx`. count: A `Tensor` of type `out_idx`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UniqueWithCounts", name, _ctx._post_execution_callbacks, x, "out_idx", out_idx) _result = _UniqueWithCountsOutput._make(_result) return _result except _core._FallbackException: try: return unique_with_counts_eager_fallback( x, out_idx=out_idx, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _, _, _op = _op_def_lib._apply_op_helper( "UniqueWithCounts", x=x, out_idx=out_idx, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_idx", _op.get_attr("out_idx")) _execute.record_gradient( "UniqueWithCounts", _inputs_flat, _attrs, _result, name) _result = _UniqueWithCountsOutput._make(_result) return _result def unique_with_counts_eager_fallback(x, out_idx=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unique_with_counts """ _ctx = ctx if ctx else _context.context() if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T, "out_idx", out_idx) _result = _execute.execute(b"UniqueWithCounts", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UniqueWithCounts", _inputs_flat, _attrs, _result, name) _result = _UniqueWithCountsOutput._make(_result) return _result _unique_with_counts_v2_outputs = ["y", "idx", "count"] _UniqueWithCountsV2Output = _collections.namedtuple( "UniqueWithCountsV2", _unique_with_counts_v2_outputs) def unique_with_counts_v2(x, axis, out_idx=_dtypes.int32, name=None): r"""Finds unique elements along an axis of a tensor. This operation either returns a tensor `y` containing unique elements along the `axis` of a tensor. The returned unique elements is sorted in the same order as they occur along `axis` in `x`. This operation also returns a tensor `idx` and a tensor `count` that are the same size as the number of the elements in `x` along the `axis` dimension. The `idx` contains the index in the unique output `y` and the `count` contains the count in the unique output `y`. In other words, for an `1-D` tensor `x` with `axis = None: `y[idx[i]] = x[i] for i in [0, 1,...,rank(x) - 1]` For example: ``` # tensor 'x' is [1, 1, 2, 4, 4, 4, 7, 8, 8] y, idx, count = unique_with_counts(x) y ==> [1, 2, 4, 7, 8] idx ==> [0, 0, 1, 2, 2, 2, 3, 4, 4] count ==> [2, 1, 3, 1, 2] ``` For an `2-D` tensor `x` with `axis = 0`: ``` # tensor 'x' is [[1, 0, 0], # [1, 0, 0], # [2, 0, 0]] y, idx, count = unique_with_counts(x, axis=0) y ==> [[1, 0, 0], [2, 0, 0]] idx ==> [0, 0, 1] count ==> [2, 1] ``` For an `2-D` tensor `x` with `axis = 1`: ``` # tensor 'x' is [[1, 0, 0], # [1, 0, 0], # [2, 0, 0]] y, idx, count = unique_with_counts(x, axis=1) y ==> [[1, 0], [1, 0], [2, 0]] idx ==> [0, 1, 1] count ==> [1, 2] ``` Args: x: A `Tensor`. A `Tensor`. axis: A `Tensor`. Must be one of the following types: `int32`, `int64`. A `Tensor` of type `int32` (default: None). The axis of the Tensor to find the unique elements. out_idx: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A tuple of `Tensor` objects (y, idx, count). y: A `Tensor`. Has the same type as `x`. idx: A `Tensor` of type `out_idx`. count: A `Tensor` of type `out_idx`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UniqueWithCountsV2", name, _ctx._post_execution_callbacks, x, axis, "out_idx", out_idx) _result = _UniqueWithCountsV2Output._make(_result) return _result except _core._FallbackException: try: return unique_with_counts_v2_eager_fallback( x, axis, out_idx=out_idx, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _, _, _op = _op_def_lib._apply_op_helper( "UniqueWithCountsV2", x=x, axis=axis, out_idx=out_idx, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "Taxis", _op.get_attr("Taxis"), "out_idx", _op.get_attr("out_idx")) _execute.record_gradient( "UniqueWithCountsV2", _inputs_flat, _attrs, _result, name) _result = _UniqueWithCountsV2Output._make(_result) return _result def unique_with_counts_v2_eager_fallback(x, axis, out_idx=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unique_with_counts_v2 """ _ctx = ctx if ctx else _context.context() if out_idx is None: out_idx = _dtypes.int32 out_idx = _execute.make_type(out_idx, "out_idx") _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _attr_Taxis, (axis,) = _execute.args_to_matching_eager([axis], _ctx, _dtypes.int64) _inputs_flat = [x, axis] _attrs = ("T", _attr_T, "Taxis", _attr_Taxis, "out_idx", out_idx) _result = _execute.execute(b"UniqueWithCountsV2", 3, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UniqueWithCountsV2", _inputs_flat, _attrs, _result, name) _result = _UniqueWithCountsV2Output._make(_result) return _result def unpack(value, num, axis=0, name=None): r"""Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors. Unpacks `num` tensors from `value` by chipping it along the `axis` dimension. For example, given a tensor of shape `(A, B, C, D)`; If `axis == 0` then the i'th tensor in `output` is the slice `value[i, :, :, :]` and each tensor in `output` will have shape `(B, C, D)`. (Note that the dimension unpacked along is gone, unlike `split`). If `axis == 1` then the i'th tensor in `output` is the slice `value[:, i, :, :]` and each tensor in `output` will have shape `(A, C, D)`. Etc. This is the opposite of `pack`. Args: value: A `Tensor`. 1-D or higher, with `axis` dimension size equal to `num`. num: An `int` that is `>= 0`. axis: An optional `int`. Defaults to `0`. Dimension along which to unpack. Negative values wrap around, so the valid range is `[-R, R)`. name: A name for the operation (optional). Returns: A list of `num` `Tensor` objects with the same type as `value`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Unpack", name, _ctx._post_execution_callbacks, value, "num", num, "axis", axis) return _result except _core._FallbackException: try: return unpack_eager_fallback( value, num=num, axis=axis, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. num = _execute.make_int(num, "num") if axis is None: axis = 0 axis = _execute.make_int(axis, "axis") _, _, _op = _op_def_lib._apply_op_helper( "Unpack", value=value, num=num, axis=axis, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("num", _op.get_attr("num"), "T", _op.get_attr("T"), "axis", _op.get_attr("axis")) _execute.record_gradient( "Unpack", _inputs_flat, _attrs, _result, name) return _result def unpack_eager_fallback(value, num, axis=0, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unpack """ _ctx = ctx if ctx else _context.context() num = _execute.make_int(num, "num") if axis is None: axis = 0 axis = _execute.make_int(axis, "axis") _attr_T, (value,) = _execute.args_to_matching_eager([value], _ctx) _inputs_flat = [value] _attrs = ("num", num, "T", _attr_T, "axis", axis) _result = _execute.execute(b"Unpack", num, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Unpack", _inputs_flat, _attrs, _result, name) return _result @_dispatch.add_dispatch_list @tf_export('unravel_index') def unravel_index(indices, dims, name=None): r"""Converts a flat index or array of flat indices into a tuple of coordinate arrays. @compatibility(numpy) Equivalent to np.unravel_index @end_compatibility Args: indices: A `Tensor`. Must be one of the following types: `int32`, `int64`. An 0-D or 1-D `int` Tensor whose elements are indices into the flattened version of an array of dimensions dims. dims: A `Tensor`. Must have the same type as `indices`. An 1-D `int` Tensor. The shape of the array to use for unraveling indices. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `indices`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UnravelIndex", name, _ctx._post_execution_callbacks, indices, dims) return _result except _core._FallbackException: try: return unravel_index_eager_fallback( indices, dims, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except (TypeError, ValueError): result = _dispatch.dispatch( unravel_index, indices=indices, dims=dims, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. try: _, _, _op = _op_def_lib._apply_op_helper( "UnravelIndex", indices=indices, dims=dims, name=name) except (TypeError, ValueError): result = _dispatch.dispatch( unravel_index, indices=indices, dims=dims, name=name) if result is not _dispatch.OpDispatcher.NOT_SUPPORTED: return result raise _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("Tidx", _op.get_attr("Tidx")) _execute.record_gradient( "UnravelIndex", _inputs_flat, _attrs, _result, name) _result, = _result return _result def unravel_index_eager_fallback(indices, dims, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function unravel_index """ _ctx = ctx if ctx else _context.context() _attr_Tidx, _inputs_Tidx = _execute.args_to_matching_eager([indices, dims], _ctx, _dtypes.int32) (indices, dims) = _inputs_Tidx _inputs_flat = [indices, dims] _attrs = ("Tidx", _attr_Tidx) _result = _execute.execute(b"UnravelIndex", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UnravelIndex", _inputs_flat, _attrs, _result, name) _result, = _result return _result def upper_bound(sorted_inputs, values, out_type=_dtypes.int32, name=None): r"""Applies upper_bound(sorted_search_values, values) along each row. Each set of rows with the same index in (sorted_inputs, values) is treated independently. The resulting row is the equivalent of calling `np.searchsorted(sorted_inputs, values, side='right')`. The result is not a global index to the entire `Tensor`, but rather just the index in the last dimension. A 2-D example: sorted_sequence = [[0, 3, 9, 9, 10], [1, 2, 3, 4, 5]] values = [[2, 4, 9], [0, 2, 6]] result = UpperBound(sorted_sequence, values) result == [[1, 2, 4], [0, 2, 5]] Args: sorted_inputs: A `Tensor`. 2-D Tensor where each row is ordered. values: A `Tensor`. Must have the same type as `sorted_inputs`. 2-D Tensor with the same numbers of rows as `sorted_search_values`. Contains the values that will be searched for in `sorted_search_values`. out_type: An optional `tf.DType` from: `tf.int32, tf.int64`. Defaults to `tf.int32`. name: A name for the operation (optional). Returns: A `Tensor` of type `out_type`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "UpperBound", name, _ctx._post_execution_callbacks, sorted_inputs, values, "out_type", out_type) return _result except _core._FallbackException: try: return upper_bound_eager_fallback( sorted_inputs, values, out_type=out_type, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _, _, _op = _op_def_lib._apply_op_helper( "UpperBound", sorted_inputs=sorted_inputs, values=values, out_type=out_type, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T"), "out_type", _op.get_attr("out_type")) _execute.record_gradient( "UpperBound", _inputs_flat, _attrs, _result, name) _result, = _result return _result def upper_bound_eager_fallback(sorted_inputs, values, out_type=_dtypes.int32, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function upper_bound """ _ctx = ctx if ctx else _context.context() if out_type is None: out_type = _dtypes.int32 out_type = _execute.make_type(out_type, "out_type") _attr_T, _inputs_T = _execute.args_to_matching_eager([sorted_inputs, values], _ctx) (sorted_inputs, values) = _inputs_T _inputs_flat = [sorted_inputs, values] _attrs = ("T", _attr_T, "out_type", out_type) _result = _execute.execute(b"UpperBound", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "UpperBound", _inputs_flat, _attrs, _result, name) _result, = _result return _result def where(condition, name=None): r"""Returns locations of nonzero / true values in a tensor. This operation returns the coordinates of true elements in `condition`. The coordinates are returned in a 2-D tensor where the first dimension (rows) represents the number of true elements, and the second dimension (columns) represents the coordinates of the true elements. Keep in mind, the shape of the output tensor can vary depending on how many true values there are in `condition`. Indices are output in row-major order. For example: ``` # 'input' tensor is [[True, False] # [True, False]] # 'input' has two true values, so output has two coordinates. # 'input' has rank of 2, so coordinates have two indices. where(input) ==> [[0, 0], [1, 0]] # `condition` tensor is [[[True, False] # [True, False]] # [[False, True] # [False, True]] # [[False, False] # [False, True]]] # 'input' has 5 true values, so output has 5 coordinates. # 'input' has rank of 3, so coordinates have three indices. where(input) ==> [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1], [2, 1, 1]] # `condition` tensor is [[[1.5, 0.0] # [-0.5, 0.0]] # [[0.0, 0.25] # [0.0, 0.75]] # [[0.0, 0.0] # [0.0, 0.01]]] # 'input' has 5 nonzero values, so output has 5 coordinates. # 'input' has rank of 3, so coordinates have three indices. where(input) ==> [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1], [2, 1, 1]] # `condition` tensor is [[[1.5 + 0.0j, 0.0 + 0.0j] # [0.0 + 0.5j, 0.0 + 0.0j]] # [[0.0 + 0.0j, 0.25 + 1.5j] # [0.0 + 0.0j, 0.75 + 0.0j]] # [[0.0 + 0.0j, 0.0 + 0.0j] # [0.0 + 0.0j, 0.01 + 0.0j]]] # 'input' has 5 nonzero magnitude values, so output has 5 coordinates. # 'input' has rank of 3, so coordinates have three indices. where(input) ==> [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1], [2, 1, 1]] ``` Args: condition: A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. name: A name for the operation (optional). Returns: A `Tensor` of type `int64`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Where", name, _ctx._post_execution_callbacks, condition) return _result except _core._FallbackException: try: return where_eager_fallback( condition, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "Where", input=condition, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "Where", _inputs_flat, _attrs, _result, name) _result, = _result return _result def where_eager_fallback(condition, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function where """ _ctx = ctx if ctx else _context.context() _attr_T, (condition,) = _execute.args_to_matching_eager([condition], _ctx, _dtypes.bool) _inputs_flat = [condition] _attrs = ("T", _attr_T) _result = _execute.execute(b"Where", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "Where", _inputs_flat, _attrs, _result, name) _result, = _result return _result def zeros_like(x, name=None): r"""Returns a tensor of zeros with the same shape and type as x. Args: x: A `Tensor`. a tensor of type T. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `x`. """ _ctx = _context._context if _ctx is not None and _ctx._eager_context.is_eager: try: _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "ZerosLike", name, _ctx._post_execution_callbacks, x) return _result except _core._FallbackException: try: return zeros_like_eager_fallback( x, name=name, ctx=_ctx) except _core._SymbolicException: pass # Add nodes to the TensorFlow graph. except _core._NotOkStatusException as e: if name is not None: message = e.message + " name: " + name else: message = e.message _six.raise_from(_core._status_to_exception(e.code, message), None) # Add nodes to the TensorFlow graph. _, _, _op = _op_def_lib._apply_op_helper( "ZerosLike", x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ("T", _op.get_attr("T")) _execute.record_gradient( "ZerosLike", _inputs_flat, _attrs, _result, name) _result, = _result return _result def zeros_like_eager_fallback(x, name=None, ctx=None): r"""This is the slowpath function for Eager mode. This is for function zeros_like """ _ctx = ctx if ctx else _context.context() _attr_T, (x,) = _execute.args_to_matching_eager([x], _ctx) _inputs_flat = [x] _attrs = ("T", _attr_T) _result = _execute.execute(b"ZerosLike", 1, inputs=_inputs_flat, attrs=_attrs, ctx=_ctx, name=name) _execute.record_gradient( "ZerosLike", _inputs_flat, _attrs, _result, name) _result, = _result return _result def _InitOpDefLibrary(op_list_proto_bytes): op_list = _op_def_pb2.OpList() op_list.ParseFromString(op_list_proto_bytes) _op_def_registry.register_op_list(op_list) op_def_lib = _op_def_library.OpDefLibrary() op_def_lib.add_op_list(op_list) return op_def_lib # op { # name: "BatchMatrixBandPart" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "num_lower" # type: DT_INT64 # } # input_arg { # name: "num_upper" # type: DT_INT64 # } # output_arg { # name: "band" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # deprecation { # version: 14 # explanation: "Use MatrixBandPart" # } # } # op { # name: "BatchMatrixDiag" # input_arg { # name: "diagonal" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # deprecation { # version: 14 # explanation: "Use MatrixDiag" # } # } # op { # name: "BatchMatrixDiagPart" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "diagonal" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # deprecation { # version: 14 # explanation: "Use MatrixDiagPart" # } # } # op { # name: "BatchMatrixSetDiag" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "diagonal" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # deprecation { # version: 14 # explanation: "Use MatrixSetDiag" # } # } # op { # name: "BatchToSpace" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "crops" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "block_size" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "BatchToSpaceND" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "block_shape" # type_attr: "Tblock_shape" # } # input_arg { # name: "crops" # type_attr: "Tcrops" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tblock_shape" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tcrops" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Bitcast" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "type" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT64 # type: DT_INT32 # type: DT_UINT8 # type: DT_UINT16 # type: DT_UINT32 # type: DT_UINT64 # type: DT_INT8 # type: DT_INT16 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT16 # type: DT_QUINT16 # type: DT_QINT32 # } # } # } # attr { # name: "type" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT64 # type: DT_INT32 # type: DT_UINT8 # type: DT_UINT16 # type: DT_UINT32 # type: DT_UINT64 # type: DT_INT8 # type: DT_INT16 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT16 # type: DT_QUINT16 # type: DT_QINT32 # } # } # } # } # op { # name: "BroadcastArgs" # input_arg { # name: "s0" # type_attr: "T" # } # input_arg { # name: "s1" # type_attr: "T" # } # output_arg { # name: "r0" # type_attr: "T" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "BroadcastGradientArgs" # input_arg { # name: "s0" # type_attr: "T" # } # input_arg { # name: "s1" # type_attr: "T" # } # output_arg { # name: "r0" # type_attr: "T" # } # output_arg { # name: "r1" # type_attr: "T" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "BroadcastTo" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "shape" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "CheckNumerics" # input_arg { # name: "tensor" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "message" # type: "string" # } # } # op { # name: "Concat" # input_arg { # name: "concat_dim" # type: DT_INT32 # } # input_arg { # name: "values" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "T" # type: "type" # } # } # op { # name: "ConcatOffset" # input_arg { # name: "concat_dim" # type: DT_INT32 # } # input_arg { # name: "shape" # type: DT_INT32 # number_attr: "N" # } # output_arg { # name: "offset" # type: DT_INT32 # number_attr: "N" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 2 # } # } # op { # name: "ConcatV2" # input_arg { # name: "values" # type_attr: "T" # number_attr: "N" # } # input_arg { # name: "axis" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ConjugateTranspose" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "perm" # type_attr: "Tperm" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tperm" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Const" # output_arg { # name: "output" # type_attr: "dtype" # } # attr { # name: "value" # type: "tensor" # } # attr { # name: "dtype" # type: "type" # } # } # op { # name: "DebugGradientIdentity" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # allows_uninitialized_input: true # } # op { # name: "DebugGradientRefIdentity" # input_arg { # name: "input" # type_attr: "T" # is_ref: true # } # output_arg { # name: "output" # type_attr: "T" # is_ref: true # } # attr { # name: "T" # type: "type" # } # allows_uninitialized_input: true # } # op { # name: "DeepCopy" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # is_stateful: true # } # op { # name: "DepthToSpace" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "block_size" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "data_format" # type: "string" # default_value { # s: "NHWC" # } # allowed_values { # list { # s: "NHWC" # s: "NCHW" # s: "NCHW_VECT_C" # } # } # } # } # op { # name: "Dequantize" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "min_range" # type: DT_FLOAT # } # input_arg { # name: "max_range" # type: DT_FLOAT # } # output_arg { # name: "output" # type: DT_FLOAT # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "mode" # type: "string" # default_value { # s: "MIN_COMBINED" # } # allowed_values { # list { # s: "MIN_COMBINED" # s: "MIN_FIRST" # s: "SCALED" # } # } # } # } # op { # name: "Diag" # input_arg { # name: "diagonal" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "DiagPart" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "diagonal" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # } # } # } # } # op { # name: "EditDistance" # input_arg { # name: "hypothesis_indices" # type: DT_INT64 # } # input_arg { # name: "hypothesis_values" # type_attr: "T" # } # input_arg { # name: "hypothesis_shape" # type: DT_INT64 # } # input_arg { # name: "truth_indices" # type: DT_INT64 # } # input_arg { # name: "truth_values" # type_attr: "T" # } # input_arg { # name: "truth_shape" # type: DT_INT64 # } # output_arg { # name: "output" # type: DT_FLOAT # } # attr { # name: "normalize" # type: "bool" # default_value { # b: true # } # } # attr { # name: "T" # type: "type" # } # } # op { # name: "Empty" # input_arg { # name: "shape" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "dtype" # } # attr { # name: "dtype" # type: "type" # } # attr { # name: "init" # type: "bool" # default_value { # b: false # } # } # is_stateful: true # } # op { # name: "EnsureShape" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "shape" # type: "shape" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "ExpandDims" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "dim" # type_attr: "Tdim" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tdim" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ExtractImagePatches" # input_arg { # name: "images" # type_attr: "T" # } # output_arg { # name: "patches" # type_attr: "T" # } # attr { # name: "ksizes" # type: "list(int)" # has_minimum: true # minimum: 4 # } # attr { # name: "strides" # type: "list(int)" # has_minimum: true # minimum: 4 # } # attr { # name: "rates" # type: "list(int)" # has_minimum: true # minimum: 4 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "padding" # type: "string" # allowed_values { # list { # s: "SAME" # s: "VALID" # } # } # } # } # op { # name: "ExtractVolumePatches" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "patches" # type_attr: "T" # } # attr { # name: "ksizes" # type: "list(int)" # has_minimum: true # minimum: 5 # } # attr { # name: "strides" # type: "list(int)" # has_minimum: true # minimum: 5 # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_INT64 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # } # } # } # attr { # name: "padding" # type: "string" # allowed_values { # list { # s: "SAME" # s: "VALID" # } # } # } # } # op { # name: "FakeQuantWithMinMaxArgs" # input_arg { # name: "inputs" # type: DT_FLOAT # } # output_arg { # name: "outputs" # type: DT_FLOAT # } # attr { # name: "min" # type: "float" # default_value { # f: -6 # } # } # attr { # name: "max" # type: "float" # default_value { # f: 6 # } # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "FakeQuantWithMinMaxArgsGradient" # input_arg { # name: "gradients" # type: DT_FLOAT # } # input_arg { # name: "inputs" # type: DT_FLOAT # } # output_arg { # name: "backprops" # type: DT_FLOAT # } # attr { # name: "min" # type: "float" # default_value { # f: -6 # } # } # attr { # name: "max" # type: "float" # default_value { # f: 6 # } # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "FakeQuantWithMinMaxVars" # input_arg { # name: "inputs" # type: DT_FLOAT # } # input_arg { # name: "min" # type: DT_FLOAT # } # input_arg { # name: "max" # type: DT_FLOAT # } # output_arg { # name: "outputs" # type: DT_FLOAT # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "FakeQuantWithMinMaxVarsGradient" # input_arg { # name: "gradients" # type: DT_FLOAT # } # input_arg { # name: "inputs" # type: DT_FLOAT # } # input_arg { # name: "min" # type: DT_FLOAT # } # input_arg { # name: "max" # type: DT_FLOAT # } # output_arg { # name: "backprops_wrt_input" # type: DT_FLOAT # } # output_arg { # name: "backprop_wrt_min" # type: DT_FLOAT # } # output_arg { # name: "backprop_wrt_max" # type: DT_FLOAT # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "FakeQuantWithMinMaxVarsPerChannel" # input_arg { # name: "inputs" # type: DT_FLOAT # } # input_arg { # name: "min" # type: DT_FLOAT # } # input_arg { # name: "max" # type: DT_FLOAT # } # output_arg { # name: "outputs" # type: DT_FLOAT # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "FakeQuantWithMinMaxVarsPerChannelGradient" # input_arg { # name: "gradients" # type: DT_FLOAT # } # input_arg { # name: "inputs" # type: DT_FLOAT # } # input_arg { # name: "min" # type: DT_FLOAT # } # input_arg { # name: "max" # type: DT_FLOAT # } # output_arg { # name: "backprops_wrt_input" # type: DT_FLOAT # } # output_arg { # name: "backprop_wrt_min" # type: DT_FLOAT # } # output_arg { # name: "backprop_wrt_max" # type: DT_FLOAT # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "narrow_range" # type: "bool" # default_value { # b: false # } # } # } # op { # name: "Fill" # input_arg { # name: "dims" # type_attr: "index_type" # } # input_arg { # name: "value" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "index_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Gather" # input_arg { # name: "params" # type_attr: "Tparams" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "Tparams" # } # attr { # name: "validate_indices" # type: "bool" # default_value { # b: true # } # } # attr { # name: "Tparams" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "GatherNd" # input_arg { # name: "params" # type_attr: "Tparams" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "Tparams" # } # attr { # name: "Tparams" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "GatherV2" # input_arg { # name: "params" # type_attr: "Tparams" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "axis" # type_attr: "Taxis" # } # output_arg { # name: "output" # type_attr: "Tparams" # } # attr { # name: "Tparams" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Taxis" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "GuaranteeConst" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # is_stateful: true # } # op { # name: "Identity" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "IdentityN" # input_arg { # name: "input" # type_list_attr: "T" # } # output_arg { # name: "output" # type_list_attr: "T" # } # attr { # name: "T" # type: "list(type)" # has_minimum: true # minimum: 1 # } # } # op { # name: "ImmutableConst" # output_arg { # name: "tensor" # type_attr: "dtype" # } # attr { # name: "dtype" # type: "type" # } # attr { # name: "shape" # type: "shape" # } # attr { # name: "memory_region_name" # type: "string" # } # } # op { # name: "InplaceAdd" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "i" # type: DT_INT32 # } # input_arg { # name: "v" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "InplaceSub" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "i" # type: DT_INT32 # } # input_arg { # name: "v" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "InplaceUpdate" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "i" # type: DT_INT32 # } # input_arg { # name: "v" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "InvertPermutation" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ListDiff" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "out" # type_attr: "T" # } # output_arg { # name: "idx" # type_attr: "out_idx" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_idx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "LowerBound" # input_arg { # name: "sorted_inputs" # type_attr: "T" # } # input_arg { # name: "values" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "out_type" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "MatrixBandPart" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "num_lower" # type_attr: "Tindex" # } # input_arg { # name: "num_upper" # type_attr: "Tindex" # } # output_arg { # name: "band" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tindex" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "MatrixDiag" # input_arg { # name: "diagonal" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "MatrixDiagPart" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "diagonal" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "MatrixSetDiag" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "diagonal" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "MirrorPad" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "mode" # type: "string" # allowed_values { # list { # s: "REFLECT" # s: "SYMMETRIC" # } # } # } # } # op { # name: "MirrorPadGrad" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "mode" # type: "string" # allowed_values { # list { # s: "REFLECT" # s: "SYMMETRIC" # } # } # } # } # op { # name: "OneHot" # input_arg { # name: "indices" # type_attr: "TI" # } # input_arg { # name: "depth" # type: DT_INT32 # } # input_arg { # name: "on_value" # type_attr: "T" # } # input_arg { # name: "off_value" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "axis" # type: "int" # default_value { # i: -1 # } # } # attr { # name: "T" # type: "type" # } # attr { # name: "TI" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_UINT8 # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "OnesLike" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT8 # type: DT_UINT8 # type: DT_INT16 # type: DT_UINT16 # type: DT_INT32 # type: DT_INT64 # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_BOOL # } # } # } # } # op { # name: "Pack" # input_arg { # name: "values" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # } # attr { # name: "axis" # type: "int" # default_value { # i: 0 # } # } # } # op { # name: "Pad" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "PadV2" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # input_arg { # name: "constant_values" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ParallelConcat" # input_arg { # name: "values" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # } # attr { # name: "shape" # type: "shape" # } # } # op { # name: "Placeholder" # output_arg { # name: "output" # type_attr: "dtype" # } # attr { # name: "dtype" # type: "type" # } # attr { # name: "shape" # type: "shape" # default_value { # shape { # unknown_rank: true # } # } # } # } # op { # name: "PlaceholderV2" # output_arg { # name: "output" # type_attr: "dtype" # } # attr { # name: "dtype" # type: "type" # } # attr { # name: "shape" # type: "shape" # } # deprecation { # version: 23 # explanation: "Placeholder now behaves the same as PlaceholderV2." # } # } # op { # name: "PlaceholderWithDefault" # input_arg { # name: "input" # type_attr: "dtype" # } # output_arg { # name: "output" # type_attr: "dtype" # } # attr { # name: "dtype" # type: "type" # } # attr { # name: "shape" # type: "shape" # } # } # op { # name: "PreventGradient" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "message" # type: "string" # default_value { # s: "" # } # } # } # op { # name: "QuantizeAndDequantize" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "signed_input" # type: "bool" # default_value { # b: true # } # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "range_given" # type: "bool" # default_value { # b: false # } # } # attr { # name: "input_min" # type: "float" # default_value { # f: 0 # } # } # attr { # name: "input_max" # type: "float" # default_value { # f: 0 # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # deprecation { # version: 22 # explanation: "Replaced by QuantizeAndDequantizeV2" # } # } # op { # name: "QuantizeAndDequantizeV2" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "input_min" # type_attr: "T" # } # input_arg { # name: "input_max" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "signed_input" # type: "bool" # default_value { # b: true # } # } # attr { # name: "num_bits" # type: "int" # default_value { # i: 8 # } # } # attr { # name: "range_given" # type: "bool" # default_value { # b: false # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # attr { # name: "round_mode" # type: "string" # default_value { # s: "HALF_TO_EVEN" # } # allowed_values { # list { # s: "HALF_TO_EVEN" # s: "HALF_UP" # } # } # } # } # op { # name: "QuantizeAndDequantizeV3" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "input_min" # type_attr: "T" # } # input_arg { # name: "input_max" # type_attr: "T" # } # input_arg { # name: "num_bits" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "signed_input" # type: "bool" # default_value { # b: true # } # } # attr { # name: "range_given" # type: "bool" # default_value { # b: true # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # } # } # } # } # op { # name: "QuantizeV2" # input_arg { # name: "input" # type: DT_FLOAT # } # input_arg { # name: "min_range" # type: DT_FLOAT # } # input_arg { # name: "max_range" # type: DT_FLOAT # } # output_arg { # name: "output" # type_attr: "T" # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "mode" # type: "string" # default_value { # s: "MIN_COMBINED" # } # allowed_values { # list { # s: "MIN_COMBINED" # s: "MIN_FIRST" # s: "SCALED" # } # } # } # attr { # name: "round_mode" # type: "string" # default_value { # s: "HALF_AWAY_FROM_ZERO" # } # allowed_values { # list { # s: "HALF_AWAY_FROM_ZERO" # s: "HALF_TO_EVEN" # } # } # } # } # op { # name: "QuantizedConcat" # input_arg { # name: "concat_dim" # type: DT_INT32 # } # input_arg { # name: "values" # type_attr: "T" # number_attr: "N" # } # input_arg { # name: "input_mins" # type: DT_FLOAT # number_attr: "N" # } # input_arg { # name: "input_maxes" # type: DT_FLOAT # number_attr: "N" # } # output_arg { # name: "output" # type_attr: "T" # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "T" # type: "type" # } # } # op { # name: "QuantizedInstanceNorm" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "x_min" # type: DT_FLOAT # } # input_arg { # name: "x_max" # type: DT_FLOAT # } # output_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "y_min" # type: DT_FLOAT # } # output_arg { # name: "y_max" # type: DT_FLOAT # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_QINT16 # type: DT_QUINT16 # } # } # } # attr { # name: "output_range_given" # type: "bool" # default_value { # b: false # } # } # attr { # name: "given_y_min" # type: "float" # default_value { # f: 0 # } # } # attr { # name: "given_y_max" # type: "float" # default_value { # f: 0 # } # } # attr { # name: "variance_epsilon" # type: "float" # default_value { # f: 1e-05 # } # } # attr { # name: "min_separation" # type: "float" # default_value { # f: 0.001 # } # } # } # op { # name: "QuantizedReshape" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "shape" # type_attr: "Tshape" # } # input_arg { # name: "input_min" # type: DT_FLOAT # } # input_arg { # name: "input_max" # type: DT_FLOAT # } # output_arg { # name: "output" # type_attr: "T" # } # output_arg { # name: "output_min" # type: DT_FLOAT # } # output_arg { # name: "output_max" # type: DT_FLOAT # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tshape" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Rank" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type: DT_INT32 # } # attr { # name: "T" # type: "type" # } # } # op { # name: "RefIdentity" # input_arg { # name: "input" # type_attr: "T" # is_ref: true # } # output_arg { # name: "output" # type_attr: "T" # is_ref: true # } # attr { # name: "T" # type: "type" # } # allows_uninitialized_input: true # } # op { # name: "Reshape" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "shape" # type_attr: "Tshape" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tshape" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ResourceStridedSliceAssign" # input_arg { # name: "ref" # type: DT_RESOURCE # } # input_arg { # name: "begin" # type_attr: "Index" # } # input_arg { # name: "end" # type_attr: "Index" # } # input_arg { # name: "strides" # type_attr: "Index" # } # input_arg { # name: "value" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Index" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "begin_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "end_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "ellipsis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "new_axis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "shrink_axis_mask" # type: "int" # default_value { # i: 0 # } # } # is_stateful: true # } # op { # name: "Reverse" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "dims" # type: DT_BOOL # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_BOOL # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_STRING # } # } # } # } # op { # name: "ReverseSequence" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "seq_lengths" # type_attr: "Tlen" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "seq_dim" # type: "int" # } # attr { # name: "batch_dim" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tlen" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ReverseV2" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "axis" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_UINT8 # type: DT_INT8 # type: DT_UINT16 # type: DT_INT16 # type: DT_INT32 # type: DT_INT64 # type: DT_BOOL # type: DT_BFLOAT16 # type: DT_HALF # type: DT_FLOAT # type: DT_DOUBLE # type: DT_COMPLEX64 # type: DT_COMPLEX128 # type: DT_STRING # } # } # } # } # op { # name: "ScatterNd" # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "updates" # type_attr: "T" # } # input_arg { # name: "shape" # type_attr: "Tindices" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ScatterNdNonAliasingAdd" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "updates" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # type: DT_BOOL # } # } # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Shape" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "out_type" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "ShapeN" # input_arg { # name: "input" # type_attr: "T" # number_attr: "N" # } # output_arg { # name: "output" # type_attr: "out_type" # number_attr: "N" # } # attr { # name: "N" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Size" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "out_type" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Slice" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "begin" # type_attr: "Index" # } # input_arg { # name: "size" # type_attr: "Index" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Index" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Snapshot" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "SpaceToBatch" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "block_size" # type: "int" # has_minimum: true # minimum: 2 # } # } # op { # name: "SpaceToBatchND" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "block_shape" # type_attr: "Tblock_shape" # } # input_arg { # name: "paddings" # type_attr: "Tpaddings" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tblock_shape" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "Tpaddings" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "SpaceToDepth" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "block_size" # type: "int" # has_minimum: true # minimum: 2 # } # attr { # name: "data_format" # type: "string" # default_value { # s: "NHWC" # } # allowed_values { # list { # s: "NHWC" # s: "NCHW" # s: "NCHW_VECT_C" # } # } # } # } # op { # name: "Split" # input_arg { # name: "split_dim" # type: DT_INT32 # } # input_arg { # name: "value" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # number_attr: "num_split" # } # attr { # name: "num_split" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # } # } # op { # name: "SplitV" # input_arg { # name: "value" # type_attr: "T" # } # input_arg { # name: "size_splits" # type_attr: "Tlen" # } # input_arg { # name: "split_dim" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # number_attr: "num_split" # } # attr { # name: "num_split" # type: "int" # has_minimum: true # minimum: 1 # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tlen" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Squeeze" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "squeeze_dims" # type: "list(int)" # default_value { # list { # } # } # has_minimum: true # } # } # op { # name: "StopGradient" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } # op { # name: "StridedSlice" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "begin" # type_attr: "Index" # } # input_arg { # name: "end" # type_attr: "Index" # } # input_arg { # name: "strides" # type_attr: "Index" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Index" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "begin_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "end_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "ellipsis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "new_axis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "shrink_axis_mask" # type: "int" # default_value { # i: 0 # } # } # } # op { # name: "StridedSliceAssign" # input_arg { # name: "ref" # type_attr: "T" # is_ref: true # } # input_arg { # name: "begin" # type_attr: "Index" # } # input_arg { # name: "end" # type_attr: "Index" # } # input_arg { # name: "strides" # type_attr: "Index" # } # input_arg { # name: "value" # type_attr: "T" # } # output_arg { # name: "output_ref" # type_attr: "T" # is_ref: true # } # attr { # name: "T" # type: "type" # } # attr { # name: "Index" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "begin_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "end_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "ellipsis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "new_axis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "shrink_axis_mask" # type: "int" # default_value { # i: 0 # } # } # } # op { # name: "StridedSliceGrad" # input_arg { # name: "shape" # type_attr: "Index" # } # input_arg { # name: "begin" # type_attr: "Index" # } # input_arg { # name: "end" # type_attr: "Index" # } # input_arg { # name: "strides" # type_attr: "Index" # } # input_arg { # name: "dy" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Index" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "begin_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "end_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "ellipsis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "new_axis_mask" # type: "int" # default_value { # i: 0 # } # } # attr { # name: "shrink_axis_mask" # type: "int" # default_value { # i: 0 # } # } # } # op { # name: "TensorScatterAdd" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "updates" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "TensorScatterSub" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "updates" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "TensorScatterUpdate" # input_arg { # name: "tensor" # type_attr: "T" # } # input_arg { # name: "indices" # type_attr: "Tindices" # } # input_arg { # name: "updates" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tindices" # type: "type" # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Tile" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "multiples" # type_attr: "Tmultiples" # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tmultiples" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "TileGrad" # input_arg { # name: "input" # type_attr: "T" # } # input_arg { # name: "multiples" # type: DT_INT32 # } # output_arg { # name: "output" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # deprecation { # version: 3 # explanation: "TileGrad has been replaced with reduce_sum" # } # } # op { # name: "Transpose" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "perm" # type_attr: "Tperm" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Tperm" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Unique" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "idx" # type_attr: "out_idx" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_idx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UniqueV2" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "axis" # type_attr: "Taxis" # } # output_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "idx" # type_attr: "out_idx" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Taxis" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "out_idx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UniqueWithCounts" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "idx" # type_attr: "out_idx" # } # output_arg { # name: "count" # type_attr: "out_idx" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_idx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UniqueWithCountsV2" # input_arg { # name: "x" # type_attr: "T" # } # input_arg { # name: "axis" # type_attr: "Taxis" # } # output_arg { # name: "y" # type_attr: "T" # } # output_arg { # name: "idx" # type_attr: "out_idx" # } # output_arg { # name: "count" # type_attr: "out_idx" # } # attr { # name: "T" # type: "type" # } # attr { # name: "Taxis" # type: "type" # default_value { # type: DT_INT64 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # attr { # name: "out_idx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Unpack" # input_arg { # name: "value" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "T" # number_attr: "num" # } # attr { # name: "num" # type: "int" # has_minimum: true # } # attr { # name: "T" # type: "type" # } # attr { # name: "axis" # type: "int" # default_value { # i: 0 # } # } # } # op { # name: "UnravelIndex" # input_arg { # name: "indices" # type_attr: "Tidx" # } # input_arg { # name: "dims" # type_attr: "Tidx" # } # output_arg { # name: "output" # type_attr: "Tidx" # } # attr { # name: "Tidx" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "UpperBound" # input_arg { # name: "sorted_inputs" # type_attr: "T" # } # input_arg { # name: "values" # type_attr: "T" # } # output_arg { # name: "output" # type_attr: "out_type" # } # attr { # name: "T" # type: "type" # } # attr { # name: "out_type" # type: "type" # default_value { # type: DT_INT32 # } # allowed_values { # list { # type: DT_INT32 # type: DT_INT64 # } # } # } # } # op { # name: "Where" # input_arg { # name: "input" # type_attr: "T" # } # output_arg { # name: "index" # type: DT_INT64 # } # attr { # name: "T" # type: "type" # default_value { # type: DT_BOOL # } # allowed_values { # list { # type: DT_FLOAT # type: DT_DOUBLE # type: DT_INT32 # type: DT_UINT8 # type: DT_INT16 # type: DT_INT8 # type: DT_COMPLEX64 # type: DT_INT64 # type: DT_QINT8 # type: DT_QUINT8 # type: DT_QINT32 # type: DT_BFLOAT16 # type: DT_UINT16 # type: DT_COMPLEX128 # type: DT_HALF # type: DT_UINT32 # type: DT_UINT64 # type: DT_BOOL # } # } # } # } # op { # name: "ZerosLike" # input_arg { # name: "x" # type_attr: "T" # } # output_arg { # name: "y" # type_attr: "T" # } # attr { # name: "T" # type: "type" # } # } _op_def_lib = _InitOpDefLibrary(b"\nm\n\023BatchMatrixBandPart\022\n\n\005input\"\001T\022\r\n\tnum_lower\030\t\022\r\n\tnum_upper\030\t\032\t\n\004band\"\001T\"\t\n\001T\022\004typeB\026\010\016\022\022Use MatrixBandPart\nL\n\017BatchMatrixDiag\022\r\n\010diagonal\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004typeB\022\010\016\022\016Use MatrixDiag\nS\n\023BatchMatrixDiagPart\022\n\n\005input\"\001T\032\r\n\010diagonal\"\001T\"\t\n\001T\022\004typeB\026\010\016\022\022Use MatrixDiagPart\n^\n\022BatchMatrixSetDiag\022\n\n\005input\"\001T\022\r\n\010diagonal\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004typeB\025\010\016\022\021Use MatrixSetDiag\nr\n\014BatchToSpace\022\n\n\005input\"\001T\022\r\n\005crops\"\004Tidx\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\nblock_size\022\003int(\0010\002\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\240\001\n\016BatchToSpaceND\022\n\n\005input\"\001T\022\033\n\013block_shape\"\014Tblock_shape\022\017\n\005crops\"\006Tcrops\032\013\n\006output\"\001T\"\t\n\001T\022\004type\" \n\014Tblock_shape\022\004type\032\0020\003:\006\n\0042\002\003\t\"\032\n\006Tcrops\022\004type\032\0020\003:\006\n\0042\002\003\t\np\n\007Bitcast\022\n\n\005input\"\001T\032\016\n\006output\"\004type\"\"\n\001T\022\004type:\027\n\0252\023\016\023\001\002\t\003\004\021\026\027\006\005\010\022\013\014\017\020\r\"%\n\004type\022\004type:\027\n\0252\023\016\023\001\002\t\003\004\021\026\027\006\005\010\022\013\014\017\020\r\nA\n\rBroadcastArgs\022\007\n\002s0\"\001T\022\007\n\002s1\"\001T\032\007\n\002r0\"\001T\"\025\n\001T\022\004type\032\0020\003:\006\n\0042\002\003\t\nR\n\025BroadcastGradientArgs\022\007\n\002s0\"\001T\022\007\n\002s1\"\001T\032\007\n\002r0\"\001T\032\007\n\002r1\"\001T\"\025\n\001T\022\004type\032\0020\003:\006\n\0042\002\003\t\nZ\n\013BroadcastTo\022\n\n\005input\"\001T\022\r\n\005shape\"\004Tidx\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\nQ\n\rCheckNumerics\022\013\n\006tensor\"\001T\032\013\n\006output\"\001T\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\"\021\n\007message\022\006string\nN\n\006Concat\022\016\n\nconcat_dim\030\003\022\016\n\006values\"\001T*\001N\032\013\n\006output\"\001T\"\014\n\001N\022\003int(\0010\002\"\t\n\001T\022\004type\nI\n\014ConcatOffset\022\016\n\nconcat_dim\030\003\022\014\n\005shape\030\003*\001N\032\r\n\006offset\030\003*\001N\"\014\n\001N\022\003int(\0010\002\nh\n\010ConcatV2\022\016\n\006values\"\001T*\001N\022\014\n\004axis\"\004Tidx\032\013\n\006output\"\001T\"\014\n\001N\022\003int(\0010\002\"\t\n\001T\022\004type\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\nY\n\022ConjugateTranspose\022\006\n\001x\"\001T\022\r\n\004perm\"\005Tperm\032\006\n\001y\"\001T\"\t\n\001T\022\004type\"\031\n\005Tperm\022\004type\032\0020\003:\006\n\0042\002\003\t\n8\n\005Const\032\017\n\006output\"\005dtype\"\017\n\005value\022\006tensor\"\r\n\005dtype\022\004type\n>\n\025DebugGradientIdentity\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\230\001\001\nG\n\030DebugGradientRefIdentity\022\r\n\005input\"\001T\200\001\001\032\016\n\006output\"\001T\200\001\001\"\t\n\001T\022\004type\230\001\001\n(\n\010DeepCopy\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\t\n\001T\022\004type\210\001\001\n\205\001\n\014DepthToSpace\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\nblock_size\022\003int(\0010\002\":\n\013data_format\022\006string\032\006\022\004NHWC:\033\n\031\022\004NHWC\022\004NCHW\022\013NCHW_VECT_C\n\235\001\n\nDequantize\022\n\n\005input\"\001T\022\r\n\tmin_range\030\001\022\r\n\tmax_range\030\001\032\n\n\006output\030\001\"\024\n\001T\022\004type:\t\n\0072\005\013\014\r\017\020\"C\n\004mode\022\006string\032\016\022\014MIN_COMBINED:#\n!\022\014MIN_COMBINED\022\tMIN_FIRST\022\006SCALED\n;\n\004Diag\022\r\n\010diagonal\"\001T\032\013\n\006output\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n>\n\010DiagPart\022\n\n\005input\"\001T\032\r\n\010diagonal\"\001T\"\027\n\001T\022\004type:\014\n\n2\010\016\023\001\002\003\t\010\022\n\271\001\n\014EditDistance\022\026\n\022hypothesis_indices\030\t\022\026\n\021hypothesis_values\"\001T\022\024\n\020hypothesis_shape\030\t\022\021\n\rtruth_indices\030\t\022\021\n\014truth_values\"\001T\022\017\n\013truth_shape\030\t\032\n\n\006output\030\001\"\025\n\tnormalize\022\004bool\032\002(\001\"\t\n\001T\022\004type\nG\n\005Empty\022\t\n\005shape\030\003\032\017\n\006output\"\005dtype\"\r\n\005dtype\022\004type\"\020\n\004init\022\004bool\032\002(\000\210\001\001\nA\n\013EnsureShape\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\016\n\005shape\022\005shape\"\t\n\001T\022\004type\nW\n\nExpandDims\022\n\n\005input\"\001T\022\013\n\003dim\"\004Tdim\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\004Tdim\022\004type\032\0020\003:\006\n\0042\002\003\t\n\274\001\n\023ExtractImagePatches\022\013\n\006images\"\001T\032\014\n\007patches\"\001T\"\027\n\006ksizes\022\tlist(int)(\0010\004\"\030\n\007strides\022\tlist(int)(\0010\004\"\026\n\005rates\022\tlist(int)(\0010\004\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\"\n\007padding\022\006string:\017\n\r\022\004SAME\022\005VALID\n\244\001\n\024ExtractVolumePatches\022\n\n\005input\"\001T\032\014\n\007patches\"\001T\"\027\n\006ksizes\022\tlist(int)(\0010\005\"\030\n\007strides\022\tlist(int)(\0010\005\"\033\n\001T\022\004type:\020\n\0162\014\001\002\003\004\005\006\t\016\021\023\026\027\"\"\n\007padding\022\006string:\017\n\r\022\004SAME\022\005VALID\n\213\001\n\027FakeQuantWithMinMaxArgs\022\n\n\006inputs\030\001\032\013\n\007outputs\030\001\"\023\n\003min\022\005float\032\005%\000\000\300\300\"\023\n\003max\022\005float\032\005%\000\000\300@\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\n\244\001\n\037FakeQuantWithMinMaxArgsGradient\022\r\n\tgradients\030\001\022\n\n\006inputs\030\001\032\r\n\tbackprops\030\001\"\023\n\003min\022\005float\032\005%\000\000\300\300\"\023\n\003max\022\005float\032\005%\000\000\300@\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\ns\n\027FakeQuantWithMinMaxVars\022\n\n\006inputs\030\001\022\007\n\003min\030\001\022\007\n\003max\030\001\032\013\n\007outputs\030\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\n\302\001\n\037FakeQuantWithMinMaxVarsGradient\022\r\n\tgradients\030\001\022\n\n\006inputs\030\001\022\007\n\003min\030\001\022\007\n\003max\030\001\032\027\n\023backprops_wrt_input\030\001\032\024\n\020backprop_wrt_min\030\001\032\024\n\020backprop_wrt_max\030\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\n}\n!FakeQuantWithMinMaxVarsPerChannel\022\n\n\006inputs\030\001\022\007\n\003min\030\001\022\007\n\003max\030\001\032\013\n\007outputs\030\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\n\314\001\n)FakeQuantWithMinMaxVarsPerChannelGradient\022\r\n\tgradients\030\001\022\n\n\006inputs\030\001\022\007\n\003min\030\001\022\007\n\003max\030\001\032\027\n\023backprops_wrt_input\030\001\032\024\n\020backprop_wrt_min\030\001\032\024\n\020backprop_wrt_max\030\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\030\n\014narrow_range\022\004bool\032\002(\000\n^\n\004Fill\022\022\n\004dims\"\nindex_type\022\n\n\005value\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\036\n\nindex_type\022\004type\032\0020\003:\006\n\0042\002\003\t\n\214\001\n\006Gather\022\021\n\006params\"\007Tparams\022\023\n\007indices\"\010Tindices\032\021\n\006output\"\007Tparams\"\034\n\020validate_indices\022\004bool\032\002(\001\"\017\n\007Tparams\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\np\n\010GatherNd\022\021\n\006params\"\007Tparams\022\023\n\007indices\"\010Tindices\032\021\n\006output\"\007Tparams\"\017\n\007Tparams\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\n\226\001\n\010GatherV2\022\021\n\006params\"\007Tparams\022\023\n\007indices\"\010Tindices\022\r\n\004axis\"\005Taxis\032\021\n\006output\"\007Tparams\"\017\n\007Tparams\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\"\025\n\005Taxis\022\004type:\006\n\0042\002\003\t\n7\n\016GuaranteeConst\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\210\001\001\n.\n\010Identity\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n9\n\tIdentityN\022\n\n\005input2\001T\032\013\n\006output2\001T\"\023\n\001T\022\nlist(type)(\0010\001\n^\n\016ImmutableConst\032\017\n\006tensor\"\005dtype\"\r\n\005dtype\022\004type\"\016\n\005shape\022\005shape\"\034\n\022memory_region_name\022\006string\n6\n\nInplaceAdd\022\006\n\001x\"\001T\022\005\n\001i\030\003\022\006\n\001v\"\001T\032\006\n\001y\"\001T\"\t\n\001T\022\004type\n6\n\nInplaceSub\022\006\n\001x\"\001T\022\005\n\001i\030\003\022\006\n\001v\"\001T\032\006\n\001y\"\001T\"\t\n\001T\022\004type\n9\n\rInplaceUpdate\022\006\n\001x\"\001T\022\005\n\001i\030\003\022\006\n\001v\"\001T\032\006\n\001y\"\001T\"\t\n\001T\022\004type\n:\n\021InvertPermutation\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\025\n\001T\022\004type\032\0020\003:\006\n\0042\002\003\t\n\\\n\010ListDiff\022\006\n\001x\"\001T\022\006\n\001y\"\001T\032\010\n\003out\"\001T\032\016\n\003idx\"\007out_idx\"\t\n\001T\022\004type\"\033\n\007out_idx\022\004type\032\0020\003:\006\n\0042\002\003\t\nj\n\nLowerBound\022\022\n\rsorted_inputs\"\001T\022\013\n\006values\"\001T\032\022\n\006output\"\010out_type\"\t\n\001T\022\004type\"\034\n\010out_type\022\004type\032\0020\003:\006\n\0042\002\003\t\nx\n\016MatrixBandPart\022\n\n\005input\"\001T\022\023\n\tnum_lower\"\006Tindex\022\023\n\tnum_upper\"\006Tindex\032\t\n\004band\"\001T\"\t\n\001T\022\004type\"\032\n\006Tindex\022\004type\032\0020\t:\006\n\0042\002\003\t\n3\n\nMatrixDiag\022\r\n\010diagonal\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n6\n\016MatrixDiagPart\022\n\n\005input\"\001T\032\r\n\010diagonal\"\001T\"\t\n\001T\022\004type\nB\n\rMatrixSetDiag\022\n\n\005input\"\001T\022\r\n\010diagonal\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n\215\001\n\tMirrorPad\022\n\n\005input\"\001T\022\025\n\010paddings\"\tTpaddings\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\"&\n\004mode\022\006string:\026\n\024\022\007REFLECT\022\tSYMMETRIC\n\221\001\n\rMirrorPadGrad\022\n\n\005input\"\001T\022\025\n\010paddings\"\tTpaddings\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\"&\n\004mode\022\006string:\026\n\024\022\007REFLECT\022\tSYMMETRIC\n\214\001\n\006OneHot\022\r\n\007indices\"\002TI\022\t\n\005depth\030\003\022\r\n\010on_value\"\001T\022\016\n\toff_value\"\001T\032\013\n\006output\"\001T\"\030\n\004axis\022\003int\032\013\030\377\377\377\377\377\377\377\377\377\001\"\t\n\001T\022\004type\"\027\n\002TI\022\004type\032\0020\t:\007\n\0052\003\004\003\t\n8\n\010OnesLike\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\034\n\001T\022\004type:\021\n\0172\r\016\023\001\002\006\004\005\021\003\t\010\022\n\nM\n\004Pack\022\016\n\006values\"\001T*\001N\032\013\n\006output\"\001T\"\014\n\001N\022\003int(\0010\001\"\t\n\001T\022\004type\"\017\n\004axis\022\003int\032\002\030\000\n_\n\003Pad\022\n\n\005input\"\001T\022\025\n\010paddings\"\tTpaddings\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\nw\n\005PadV2\022\n\n\005input\"\001T\022\025\n\010paddings\"\tTpaddings\022\024\n\017constant_values\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\nV\n\016ParallelConcat\022\016\n\006values\"\001T*\001N\032\013\n\006output\"\001T\"\014\n\001N\022\003int(\0010\001\"\t\n\001T\022\004type\"\016\n\005shape\022\005shape\nC\n\013Placeholder\032\017\n\006output\"\005dtype\"\r\n\005dtype\022\004type\"\024\n\005shape\022\005shape\032\004:\002\030\001\nw\n\rPlaceholderV2\032\017\n\006output\"\005dtype\"\r\n\005dtype\022\004type\"\016\n\005shape\022\005shapeB6\010\027\0222Placeholder now behaves the same as PlaceholderV2.\nX\n\026PlaceholderWithDefault\022\016\n\005input\"\005dtype\032\017\n\006output\"\005dtype\"\r\n\005dtype\022\004type\"\016\n\005shape\022\005shape\nL\n\017PreventGradient\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\007message\022\006string\032\002\022\000\n\354\001\n\025QuantizeAndDequantize\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\030\n\014signed_input\022\004bool\032\002(\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\027\n\013range_given\022\004bool\032\002(\000\"\031\n\tinput_min\022\005float\032\005%\000\000\000\000\"\031\n\tinput_max\022\005float\032\005%\000\000\000\000\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002B\'\010\026\022#Replaced by QuantizeAndDequantizeV2\n\360\001\n\027QuantizeAndDequantizeV2\022\n\n\005input\"\001T\022\016\n\tinput_min\"\001T\022\016\n\tinput_max\"\001T\032\013\n\006output\"\001T\"\030\n\014signed_input\022\004bool\032\002(\001\"\023\n\010num_bits\022\003int\032\002\030\010\"\027\n\013range_given\022\004bool\032\002(\000\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\"?\n\nround_mode\022\006string\032\016\022\014HALF_TO_EVEN:\031\n\027\022\014HALF_TO_EVEN\022\007HALF_UP\n\250\001\n\027QuantizeAndDequantizeV3\022\n\n\005input\"\001T\022\016\n\tinput_min\"\001T\022\016\n\tinput_max\"\001T\022\014\n\010num_bits\030\003\032\013\n\006output\"\001T\"\030\n\014signed_input\022\004bool\032\002(\001\"\027\n\013range_given\022\004bool\032\002(\001\"\023\n\001T\022\004type:\010\n\0062\004\016\023\001\002\n\221\002\n\nQuantizeV2\022\t\n\005input\030\001\022\r\n\tmin_range\030\001\022\r\n\tmax_range\030\001\032\013\n\006output\"\001T\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\024\n\001T\022\004type:\t\n\0072\005\013\014\r\017\020\"C\n\004mode\022\006string\032\016\022\014MIN_COMBINED:#\n!\022\014MIN_COMBINED\022\tMIN_FIRST\022\006SCALED\"R\n\nround_mode\022\006string\032\025\022\023HALF_AWAY_FROM_ZERO:%\n#\022\023HALF_AWAY_FROM_ZERO\022\014HALF_TO_EVEN\n\236\001\n\017QuantizedConcat\022\016\n\nconcat_dim\030\003\022\016\n\006values\"\001T*\001N\022\021\n\ninput_mins\030\001*\001N\022\022\n\013input_maxes\030\001*\001N\032\013\n\006output\"\001T\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\014\n\001N\022\003int(\0010\002\"\t\n\001T\022\004type\n\205\002\n\025QuantizedInstanceNorm\022\006\n\001x\"\001T\022\t\n\005x_min\030\001\022\t\n\005x_max\030\001\032\006\n\001y\"\001T\032\t\n\005y_min\030\001\032\t\n\005y_max\030\001\"\024\n\001T\022\004type:\t\n\0072\005\013\014\r\017\020\"\036\n\022output_range_given\022\004bool\032\002(\000\"\033\n\013given_y_min\022\005float\032\005%\000\000\000\000\"\033\n\013given_y_max\022\005float\032\005%\000\000\000\000\" \n\020variance_epsilon\022\005float\032\005%\254\305\'7\"\036\n\016min_separation\022\005float\032\005%o\022\203:\n\242\001\n\020QuantizedReshape\022\013\n\006tensor\"\001T\022\017\n\005shape\"\006Tshape\022\r\n\tinput_min\030\001\022\r\n\tinput_max\030\001\032\013\n\006output\"\001T\032\016\n\noutput_min\030\001\032\016\n\noutput_max\030\001\"\t\n\001T\022\004type\"\032\n\006Tshape\022\004type\032\0020\003:\006\n\0042\002\003\t\n)\n\004Rank\022\n\n\005input\"\001T\032\n\n\006output\030\003\"\t\n\001T\022\004type\n:\n\013RefIdentity\022\r\n\005input\"\001T\200\001\001\032\016\n\006output\"\001T\200\001\001\"\t\n\001T\022\004type\230\001\001\n[\n\007Reshape\022\013\n\006tensor\"\001T\022\017\n\005shape\"\006Tshape\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\032\n\006Tshape\022\004type\032\0020\003:\006\n\0042\002\003\t\n\203\002\n\032ResourceStridedSliceAssign\022\007\n\003ref\030\024\022\016\n\005begin\"\005Index\022\014\n\003end\"\005Index\022\020\n\007strides\"\005Index\022\n\n\005value\"\001T\"\t\n\001T\022\004type\"\025\n\005Index\022\004type:\006\n\0042\002\003\t\"\025\n\nbegin_mask\022\003int\032\002\030\000\"\023\n\010end_mask\022\003int\032\002\030\000\"\030\n\rellipsis_mask\022\003int\032\002\030\000\"\030\n\rnew_axis_mask\022\003int\032\002\030\000\"\033\n\020shrink_axis_mask\022\003int\032\002\030\000\210\001\001\nK\n\007Reverse\022\013\n\006tensor\"\001T\022\010\n\004dims\030\n\032\013\n\006output\"\001T\"\034\n\001T\022\004type:\021\n\0172\r\004\006\021\005\003\t\n\023\001\002\010\022\007\n\212\001\n\017ReverseSequence\022\n\n\005input\"\001T\022\023\n\013seq_lengths\"\004Tlen\032\013\n\006output\"\001T\"\016\n\007seq_dim\022\003int\"\024\n\tbatch_dim\022\003int\032\002\030\000\"\t\n\001T\022\004type\"\030\n\004Tlen\022\004type\032\0020\t:\006\n\0042\002\003\t\nl\n\tReverseV2\022\013\n\006tensor\"\001T\022\014\n\004axis\"\004Tidx\032\013\n\006output\"\001T\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\"\035\n\001T\022\004type:\022\n\0202\016\004\006\021\005\003\t\n\016\023\001\002\010\022\007\ns\n\tScatterNd\022\023\n\007indices\"\010Tindices\022\014\n\007updates\"\001T\022\021\n\005shape\"\010Tindices\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\n\222\001\n\027ScatterNdNonAliasingAdd\022\n\n\005input\"\001T\022\023\n\007indices\"\010Tindices\022\014\n\007updates\"\001T\032\013\n\006output\"\001T\"!\n\001T\022\004type:\026\n\0242\022\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\n\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nP\n\005Shape\022\n\n\005input\"\001T\032\022\n\006output\"\010out_type\"\t\n\001T\022\004type\"\034\n\010out_type\022\004type\032\0020\003:\006\n\0042\002\003\t\ne\n\006ShapeN\022\r\n\005input\"\001T*\001N\032\025\n\006output\"\010out_type*\001N\"\014\n\001N\022\003int(\0010\001\"\t\n\001T\022\004type\"\034\n\010out_type\022\004type\032\0020\003:\006\n\0042\002\003\t\nO\n\004Size\022\n\n\005input\"\001T\032\022\n\006output\"\010out_type\"\t\n\001T\022\004type\"\034\n\010out_type\022\004type\032\0020\003:\006\n\0042\002\003\t\na\n\005Slice\022\n\n\005input\"\001T\022\016\n\005begin\"\005Index\022\r\n\004size\"\005Index\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\005Index\022\004type:\006\n\0042\002\003\t\n.\n\010Snapshot\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n\177\n\014SpaceToBatch\022\n\n\005input\"\001T\022\025\n\010paddings\"\tTpaddings\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\"\025\n\nblock_size\022\003int(\0010\002\n\251\001\n\016SpaceToBatchND\022\n\n\005input\"\001T\022\033\n\013block_shape\"\014Tblock_shape\022\025\n\010paddings\"\tTpaddings\032\013\n\006output\"\001T\"\t\n\001T\022\004type\" \n\014Tblock_shape\022\004type\032\0020\003:\006\n\0042\002\003\t\"\035\n\tTpaddings\022\004type\032\0020\003:\006\n\0042\002\003\t\n\205\001\n\014SpaceToDepth\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\nblock_size\022\003int(\0010\002\":\n\013data_format\022\006string\032\006\022\004NHWC:\033\n\031\022\004NHWC\022\004NCHW\022\013NCHW_VECT_C\n[\n\005Split\022\r\n\tsplit_dim\030\003\022\n\n\005value\"\001T\032\026\n\006output\"\001T*\tnum_split\"\024\n\tnum_split\022\003int(\0010\001\"\t\n\001T\022\004type\n\213\001\n\006SplitV\022\n\n\005value\"\001T\022\023\n\013size_splits\"\004Tlen\022\r\n\tsplit_dim\030\003\032\026\n\006output\"\001T*\tnum_split\"\024\n\tnum_split\022\003int(\0010\001\"\t\n\001T\022\004type\"\030\n\004Tlen\022\004type\032\0020\t:\006\n\0042\002\003\t\nN\n\007Squeeze\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\037\n\014squeeze_dims\022\tlist(int)\032\002\n\000(\001\n2\n\014StopGradient\022\n\n\005input\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\n\366\001\n\014StridedSlice\022\n\n\005input\"\001T\022\016\n\005begin\"\005Index\022\014\n\003end\"\005Index\022\020\n\007strides\"\005Index\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\005Index\022\004type:\006\n\0042\002\003\t\"\025\n\nbegin_mask\022\003int\032\002\030\000\"\023\n\010end_mask\022\003int\032\002\030\000\"\030\n\rellipsis_mask\022\003int\032\002\030\000\"\030\n\rnew_axis_mask\022\003int\032\002\030\000\"\033\n\020shrink_axis_mask\022\003int\032\002\030\000\n\220\002\n\022StridedSliceAssign\022\013\n\003ref\"\001T\200\001\001\022\016\n\005begin\"\005Index\022\014\n\003end\"\005Index\022\020\n\007strides\"\005Index\022\n\n\005value\"\001T\032\022\n\noutput_ref\"\001T\200\001\001\"\t\n\001T\022\004type\"\025\n\005Index\022\004type:\006\n\0042\002\003\t\"\025\n\nbegin_mask\022\003int\032\002\030\000\"\023\n\010end_mask\022\003int\032\002\030\000\"\030\n\rellipsis_mask\022\003int\032\002\030\000\"\030\n\rnew_axis_mask\022\003int\032\002\030\000\"\033\n\020shrink_axis_mask\022\003int\032\002\030\000\n\207\002\n\020StridedSliceGrad\022\016\n\005shape\"\005Index\022\016\n\005begin\"\005Index\022\014\n\003end\"\005Index\022\020\n\007strides\"\005Index\022\007\n\002dy\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\025\n\005Index\022\004type:\006\n\0042\002\003\t\"\025\n\nbegin_mask\022\003int\032\002\030\000\"\023\n\010end_mask\022\003int\032\002\030\000\"\030\n\rellipsis_mask\022\003int\032\002\030\000\"\030\n\rnew_axis_mask\022\003int\032\002\030\000\"\033\n\020shrink_axis_mask\022\003int\032\002\030\000\nt\n\020TensorScatterAdd\022\013\n\006tensor\"\001T\022\023\n\007indices\"\010Tindices\022\014\n\007updates\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nt\n\020TensorScatterSub\022\013\n\006tensor\"\001T\022\023\n\007indices\"\010Tindices\022\014\n\007updates\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nw\n\023TensorScatterUpdate\022\013\n\006tensor\"\001T\022\023\n\007indices\"\010Tindices\022\014\n\007updates\"\001T\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\030\n\010Tindices\022\004type:\006\n\0042\002\003\t\nc\n\004Tile\022\n\n\005input\"\001T\022\027\n\tmultiples\"\nTmultiples\032\013\n\006output\"\001T\"\t\n\001T\022\004type\"\036\n\nTmultiples\022\004type\032\0020\003:\006\n\0042\002\003\t\nm\n\010TileGrad\022\n\n\005input\"\001T\022\r\n\tmultiples\030\003\032\013\n\006output\"\001T\"\t\n\001T\022\004typeB.\010\003\022*TileGrad has been replaced with reduce_sum\nP\n\tTranspose\022\006\n\001x\"\001T\022\r\n\004perm\"\005Tperm\032\006\n\001y\"\001T\"\t\n\001T\022\004type\"\031\n\005Tperm\022\004type\032\0020\003:\006\n\0042\002\003\t\nP\n\006Unique\022\006\n\001x\"\001T\032\006\n\001y\"\001T\032\016\n\003idx\"\007out_idx\"\t\n\001T\022\004type\"\033\n\007out_idx\022\004type\032\0020\003:\006\n\0042\002\003\t\n|\n\010UniqueV2\022\006\n\001x\"\001T\022\r\n\004axis\"\005Taxis\032\006\n\001y\"\001T\032\016\n\003idx\"\007out_idx\"\t\n\001T\022\004type\"\031\n\005Taxis\022\004type\032\0020\t:\006\n\0042\002\003\t\"\033\n\007out_idx\022\004type\032\0020\003:\006\n\0042\002\003\t\nl\n\020UniqueWithCounts\022\006\n\001x\"\001T\032\006\n\001y\"\001T\032\016\n\003idx\"\007out_idx\032\020\n\005count\"\007out_idx\"\t\n\001T\022\004type\"\033\n\007out_idx\022\004type\032\0020\003:\006\n\0042\002\003\t\n\230\001\n\022UniqueWithCountsV2\022\006\n\001x\"\001T\022\r\n\004axis\"\005Taxis\032\006\n\001y\"\001T\032\016\n\003idx\"\007out_idx\032\020\n\005count\"\007out_idx\"\t\n\001T\022\004type\"\031\n\005Taxis\022\004type\032\0020\t:\006\n\0042\002\003\t\"\033\n\007out_idx\022\004type\032\0020\003:\006\n\0042\002\003\t\nP\n\006Unpack\022\n\n\005value\"\001T\032\020\n\006output\"\001T*\003num\"\014\n\003num\022\003int(\001\"\t\n\001T\022\004type\"\017\n\004axis\022\003int\032\002\030\000\nW\n\014UnravelIndex\022\017\n\007indices\"\004Tidx\022\014\n\004dims\"\004Tidx\032\016\n\006output\"\004Tidx\"\030\n\004Tidx\022\004type\032\0020\003:\006\n\0042\002\003\t\nj\n\nUpperBound\022\022\n\rsorted_inputs\"\001T\022\013\n\006values\"\001T\032\022\n\006output\"\010out_type\"\t\n\001T\022\004type\"\034\n\010out_type\022\004type\032\0020\003:\006\n\0042\002\003\t\nE\n\005Where\022\n\n\005input\"\001T\032\t\n\005index\030\t\"%\n\001T\022\004type\032\0020\n:\026\n\0242\022\001\002\003\004\005\006\010\t\013\014\r\016\021\022\023\026\027\n\n&\n\tZerosLike\022\006\n\001x\"\001T\032\006\n\001y\"\001T\"\t\n\001T\022\004type")
564d81d0051cf261ea8cf3a8060afb2cc81c2406
718f4a6f53da14dbd79031928900a26c4de65ccb
/optimize_NMDA_KIN2.py
bf70c8a044f4ff48aa4d86895cd5e68a6e41e55f
[]
no_license
neurosutras/CA1Sim
ff37e5ae96cc00d923bbcf333d75842c34156b5b
9a5796e5de9b9be477d61837c164fcbccbe3c8ce
refs/heads/master
2023-04-08T01:39:09.559475
2022-01-13T20:20:45
2022-01-13T20:20:45
29,497,263
4
3
null
null
null
null
UTF-8
Python
false
false
7,046
py
__author__ = 'Aaron D. Milstein' from specify_cells import * from plot_results import * import scipy.optimize as optimize import random """ This simulation uses scipy.optimize to iterate through NMDA_KIN mechanism parameters to fit target EPSP kinetics. """ #morph_filename = 'EB1-early-bifurcation.swc' morph_filename = 'EB2-late-bifurcation.swc' #mech_filename = '043015 pas_exp_scale kdr ka_scale ih_sig_scale - EB2' #mech_filename = '072515 optimized basal ka_scale dend_sh_ar_nas - EB2' mech_filename = '102915 interim dendritic excitability' def synaptic_kinetics_error(x, plot=0): """ :param x: list of parameters :param plot: int or bool: method can be called manually to compare actual to target and fit waveforms :return: float: Error """ spike_times = h.Vector([equilibrate]) for i, syn in enumerate(stim_syn_list): syn.target(syn_type).kon = x[0] syn.target(syn_type).koff = x[1] syn.target(syn_type).CC = x[2] syn.target(syn_type).CO = x[3] syn.target(syn_type).Beta = x[4] syn.target(syn_type).Alpha = x[5] syn.source.play(spike_times) sim.run(v_init) t = np.array(sim.tvec) g = np.array(sim.rec_list[0]['vec']) interp_t = np.arange(0, duration, 0.001) interp_g = np.interp(interp_t, t, g) """ Rc = np.interp(interp_t, t, np.array(sim.rec_list[1]['vec'])) Ro = np.interp(interp_t, t, np.array(sim.rec_list[2]['vec'])) Rb = np.interp(interp_t, t, np.array(sim.rec_list[3]['vec'])) Ro_peak = np.max(Ro) Ro_peak_loc = np.where(Ro == Ro_peak)[0][0] Rc_max = Ro_peak + Rc[Ro_peak_loc] + Rb[Ro_peak_loc] """ start, end = time2index(interp_t, equilibrate, duration) y = interp_g[start:end] interp_t = interp_t[start:end] interp_t -= interp_t[0] amp = np.max(y) t_peak = np.where(y == amp)[0][0] y /= amp rise_10 = np.where(y[0:t_peak] >= 0.1)[0][0] rise_90 = np.where(y[0:t_peak] >= 0.9)[0][0] rise_tau = interp_t[rise_90] - interp_t[rise_10] decay_90 = np.where(y[t_peak:] <= 0.9)[0][0] decay_10 = np.where(y[t_peak:] <= 0.1)[0] if decay_10.any(): decay_tau = interp_t[decay_10[0]] - interp_t[decay_90] else: decay_tau = 1000. # large error if trace has not decayed to 10% in 1 second result = {'rise_tau': rise_tau, 'decay_tau': decay_tau} # , 'Rc_max': Rc_max} spike_times = h.Vector([equilibrate + i * 10. for i in range(5)]) for i, syn in enumerate(stim_syn_list): syn.source.play(spike_times) sim.run(v_init) for i, syn in enumerate(stim_syn_list): syn.source.play(h.Vector()) t = np.array(sim.tvec) g = np.array(sim.rec_list[0]['vec']) interp_t = np.arange(0, duration, 0.001) interp_g = np.interp(interp_t, t, g) start, end = time2index(interp_t, equilibrate, duration) yf = interp_g[start:end] interp_t = interp_t[start:end] interp_t -= interp_t[0] facil_amp = np.max(yf) result['facilitation'] = facil_amp / amp yf /= amp Err = 0. for target in result: Err += ((target_val[target] - result[target])/target_range[target])**2. print('[kon, koff, CC, CO, Beta, Alpha]: [%.3f, %.3f, %.3f, %.3f, %.3f, %.3f], Error: %.3E, Rise: %.3f, Decay: ' '%.3f, facilitation: %.2f' % (x[0], x[1], x[2], x[3], x[4], x[5], Err, rise_tau, decay_tau, result['facilitation'])) if plot: plt.plot(interp_t, y) plt.plot(interp_t, yf) plt.show() plt.close() return Err equilibrate = 250. # time to steady-state duration = 1250. v_init = -67. num_syns = 1 cell = CA1_Pyr(morph_filename, mech_filename, full_spines=True) cell.zero_na() syn_type = 'NMDA_KIN2' sim = QuickSim(duration) # look for a trunk bifurcation trunk_bifurcation = [trunk for trunk in cell.trunk if len(trunk.children) > 1 and trunk.children[0].type == 'trunk' and trunk.children[1].type == 'trunk'] # get where the thickest trunk branch gives rise to the tuft if trunk_bifurcation: # follow the thicker trunk trunk = max(trunk_bifurcation[0].children[:2], key=lambda node: node.sec(0.).diam) trunk = (node for node in cell.trunk if cell.node_in_subtree(trunk, node) and 'tuft' in (child.type for child in node.children)).next() else: trunk = (node for node in cell.trunk if 'tuft' in (child.type for child in node.children)).next() tuft = (child for child in trunk.children if child.type == 'tuft').next() trunk = trunk_bifurcation[0] #sim.append_rec(cell, trunk, loc=1., description='trunk vm') spine_list = [] spine_list.extend(trunk.spines) for spine in spine_list: syn = Synapse(cell, spine, [syn_type], stochastic=0) local_random = random.Random() local_random.seed(0) stim_syn_list = [spine_list[i].synapses[0] for i in local_random.sample(range(len(spine_list)), num_syns)] for i, syn in enumerate(stim_syn_list): syn.target(syn_type).mg = 0.1 #syn.target(syn_type).gmax = 0.005 sim.append_rec(cell, syn.node, object=syn.target(syn_type), param='_ref_g') sim.append_rec(cell, syn.node, object=syn.target(syn_type), param='_ref_Rc') sim.append_rec(cell, syn.node, object=syn.target(syn_type), param='_ref_Ro') sim.append_rec(cell, syn.node, object=syn.target(syn_type), param='_ref_Rb') #the target values and acceptable ranges target_val = {'rise_tau': 3., 'decay_tau': 75., 'Rc_max': 0.6, 'facilitation': 1.3} # extrapolating from Chen...Murphy and Harnett...Magee, Popescu et al. target_range = {'rise_tau': 0.1, 'decay_tau': .5, 'Rc_max': 0.01, 'facilitation': 0.01} #the initial guess and bounds #x = [kon, koff, CC, CO, Beta, Alpha) #x0 = [10., .02, 1., 0.1, 0.04, 0.09] #x0 = [26.414, 1.903, 3.185, 5.119, 0.274, 0.0299] #x0 = [44.35, 2.46, 10.34, 1.06, 0.40, 0.045] x0 = [85.47, 0.68, 9.48, 2.56, 0.72, 0.078] xmin = [10., .01, .1, .1, .01, .01] xmax = [100., 10., 20., 20., 1., 1.] #x1 = [1099.70, 0.07, 1.70, 14.12, 4.64, 0.19] # old NMDA_KIN2, unrealistic kon x1 = [68.74, 1.43, 5.86, 3.32, 0.270, 0.034] mytakestep = Normalized_Step(x0, xmin, xmax) minimizer_kwargs = dict(method=null_minimizer) """ result = optimize.basinhopping(synaptic_kinetics_error, x0, niter=720, niter_success=200, disp=True, interval=20, minimizer_kwargs=minimizer_kwargs, take_step=mytakestep) synaptic_kinetics_error(result.x, plot=1) polished_result = optimize.minimize(synaptic_kinetics_error, result.x, method='Nelder-Mead', options={'ftol': 1e-3, 'xtol': 1e-3, 'disp': True}) """ polished_result = optimize.minimize(synaptic_kinetics_error, x0, method='Nelder-Mead', options={'ftol': 1e-3, 'xtol': 1e-3, 'disp': True}) synaptic_kinetics_error(polished_result.x, plot=1) #synaptic_kinetics_error(x1, plot=1)
da748d34cb6a27059cecf0ee84bd84376e2809bf
d5ad13232e3f1ced55f6956bc4cbda87925c8085
/cc_mcc_seq/SNVINDEL/tmp/3.1_tumor_minus_normal_exome_somatic_number/1_tumor_minus_normal_somatic.py
fb9fd44707bd9d72ef21d0edd8631473db5d86f3
[]
no_license
arvin580/SIBS
c0ba9a8a41f59cb333517c286f7d80300b9501a2
0cc2378bf62359ec068336ea4de16d081d0f58a4
refs/heads/master
2021-01-23T21:57:35.658443
2015-04-09T23:11:34
2015-04-09T23:11:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,722
py
def tumor_minus_normal_to_somatic(tumorFile,normalFile,oFile) : dict_Normal=dict() ouFile=open(oFile,'w') inFile=open(normalFile) for line in inFile : line=line.strip() fields=line.split('\t') k='\t'.join(fields[1:-1]) dict_Normal[k]=1 inFile.close() inFile=open(tumorFile) for line in inFile : line=line.strip() fields=line.split('\t') k='\t'.join(fields[1:-1]) if k not in dict_Normal : ouFile.write(line+'\n') ouFile.close() tumor_minus_normal_to_somatic('sum_snp.exome_summary.pass012.ICC10A','sum_snp34.exome_summary.pass012.ICC10B','sum_snp.exome_summary.pass012.ICC10') tumor_minus_normal_to_somatic('sum_snp.exome_summary.pass012.ICC4A','sum_snp34.exome_summary.pass012.ICC4B','sum_snp.exome_summary.pass012.ICC4') tumor_minus_normal_to_somatic('sum_snp.exome_summary.pass012.ICC5A','sum_snp34.exome_summary.pass012.ICC5B','sum_snp.exome_summary.pass012.ICC5') tumor_minus_normal_to_somatic('sum_snp.exome_summary.pass012.ICC9A','sum_snp34.exome_summary.pass012.ICC9B','sum_snp.exome_summary.pass012.ICC9') tumor_minus_normal_to_somatic('sum_snp2.exome_summary.pass012.CHC10A','sum_snp34.exome_summary.pass012.CHC10B','sum_snp.exome_summary.pass012.CHC10') tumor_minus_normal_to_somatic('sum_snp2.exome_summary.pass012.CHC5A','sum_snp34.exome_summary.pass012.CHC5B','sum_snp.exome_summary.pass012.CHC5') tumor_minus_normal_to_somatic('sum_snp2.exome_summary.pass012.CHC6A','sum_snp34.exome_summary.pass012.CHC6B','sum_snp.exome_summary.pass012.CHC6') tumor_minus_normal_to_somatic('sum_snp2.exome_summary.pass012.CHC7A','sum_snp34.exome_summary.pass012.CHC7B','sum_snp.exome_summary.pass012.CHC7')
d22b6020a2b3d2bfacf12fcb9cb93b0bc3d641d9
a30362e51cb3291daf26d0c62e56c42caeec837f
/python/codeup/solved/_1068.py
87813e822e0529ad4c300ab4f9c21997748b240f
[]
no_license
TERADA-DANTE/algorithm
03bf52764c6fcdb93d7c8a0ed7a672834f488412
20bdfa1a5a6b9c378e588b17073e77a0126f7339
refs/heads/master
2023-04-14T21:40:11.250022
2023-04-12T13:00:37
2023-04-12T13:00:37
288,335,057
0
0
null
null
null
null
UTF-8
Python
false
false
131
py
n = int(input()) if 90 <= n: print('A') elif 70 <= n: print('B') elif 40 <= n: print('C') elif 0 <= n: print('D')
b3faa68ddf38c6d15ad43fc82a48744cdae5c15b
56f5b2ea36a2258b8ca21e2a3af9a5c7a9df3c6e
/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377544840/HTT_24Jul_newTES_manzoni_Up_Jobs/Job_225/run_cfg.py
c1d2c055a93f6f5950d43132a49f5e864889fafd
[]
no_license
rmanzoni/HTT
18e6b583f04c0a6ca10142d9da3dd4c850cddabc
a03b227073b2d4d8a2abe95367c014694588bf98
refs/heads/master
2016-09-06T05:55:52.602604
2014-02-20T16:35:34
2014-02-20T16:35:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,499
py
import FWCore.ParameterSet.Config as cms import os,sys sys.path.append('/afs/cern.ch/user/m/manzoni/summer13/CMGTools/CMSSW_5_3_9/src/CMGTools/H2TauTau/prod/25aug_corrMC/up/mc/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0_1377544840/HTT_24Jul_newTES_manzoni_Up_Jobs') from base_cfg import * process.source = cms.Source("PoolSource", noEventSort = cms.untracked.bool(True), inputCommands = cms.untracked.vstring('keep *', 'drop cmgStructuredPFJets_cmgStructuredPFJetSel__PAT'), duplicateCheckMode = cms.untracked.string('noDuplicateCheck'), fileNames = cms.untracked.vstring('/store/cmst3/user/cmgtools/CMG/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_2006.root', '/store/cmst3/user/cmgtools/CMG/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_2007.root', '/store/cmst3/user/cmgtools/CMG/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_2008.root', '/store/cmst3/user/cmgtools/CMG/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_2009.root', '/store/cmst3/user/cmgtools/CMG/DY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph/Summer12_DR53X-PU_S10_START53_V7C-v1/AODSIM/V5_B/PAT_CMG_V5_16_0/cmgTuple_201.root') )
fc8f7fd662fe988e7f5f65c94869efdafc5af3eb
7f0548b7191b7589712af19baebafddae1d0505f
/dojoassignments/python/django/full_stack_django/login_and_registration/apps/login_registration_app/migrations/0001_initial.py
2e5994f927a8fa2ce9b4a5d96fd6c594f3453aa5
[]
no_license
mtjhartley/codingdojo
dd8eab1bd61fb847e44766e89fe3db2340468102
65dc558d19adbe62f85ad61c32cb1c392b56567c
refs/heads/master
2022-12-14T23:06:11.927445
2017-08-16T21:08:35
2017-08-16T21:08:35
92,218,728
1
5
null
2022-12-07T23:59:48
2017-05-23T20:46:03
Python
UTF-8
Python
false
false
884
py
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-06-20 19:02 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=255)), ('last_name', models.CharField(max_length=255)), ('email', models.CharField(max_length=255)), ('password', models.CharField(max_length=45)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ]
ddbc0c95647448fd2b5ee0f7983a9b7eda1fc03c
7b054cd92eece331d2494b1ecbd6ebae76deed55
/ecommerce/urls.py
748d4606d02d80bf738204eb134afca866a6623b
[]
no_license
Tanmoy-Sarkar/Django-Ecommerce-Website
f23ec5a60b64f6b3f614bb9dd7aced2c694d1d75
24810153dcb51ae1d57c1b182b59cb40fbb8a3d2
refs/heads/master
2023-07-03T17:23:58.746887
2021-07-31T08:21:35
2021-07-31T08:21:35
389,021,036
0
0
null
null
null
null
UTF-8
Python
false
false
948
py
"""ecommerce URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path,include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('',include('store.urls')), ] urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
1bc2bad1c8d403cdc99de557444a6e0a0f503eb2
fe3759747f709a41e5ff3acf78872dd6b74f772a
/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal.py
81432c292c6459b54e18f5be8a654084c4f140d5
[ "Apache-2.0" ]
permissive
Januson/openapi-generator
c50e3b52765e41adba9712d745918cea39dfa490
5b6b4c9d4829b57716741dc35b3f1033e5483784
refs/heads/master
2022-10-19T04:16:38.042495
2022-04-23T08:42:21
2022-04-23T08:42:21
238,659,737
0
0
Apache-2.0
2023-09-05T01:01:23
2020-02-06T10:12:38
Java
UTF-8
Python
false
false
2,359
py
# coding: utf-8 """ OpenAPI Petstore This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ import re # noqa: F401 import sys # noqa: F401 import typing # noqa: F401 from frozendict import frozendict # noqa: F401 import decimal # noqa: F401 from datetime import date, datetime # noqa: F401 from frozendict import frozendict # noqa: F401 from petstore_api.schemas import ( # noqa: F401 AnyTypeSchema, ComposedSchema, DictSchema, ListSchema, StrSchema, IntSchema, Int32Schema, Int64Schema, Float32Schema, Float64Schema, NumberSchema, UUIDSchema, DateSchema, DateTimeSchema, DecimalSchema, BoolSchema, BinarySchema, NoneSchema, none_type, Configuration, Unset, unset, ComposedBase, ListBase, DictBase, NoneBase, StrBase, IntBase, Int32Base, Int64Base, Float32Base, Float64Base, NumberBase, UUIDBase, DateBase, DateTimeBase, BoolBase, BinaryBase, Schema, _SchemaValidator, _SchemaTypeChecker, _SchemaEnumMaker ) class Animal( DictSchema ): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ _required_property_names = set(( 'className', )) className = StrSchema color = StrSchema @classmethod @property def _discriminator(cls): return { 'className': { 'Cat': Cat, 'Dog': Dog, } } def __new__( cls, *args: typing.Union[dict, frozendict, ], className: className, color: typing.Union[color, Unset] = unset, _configuration: typing.Optional[Configuration] = None, **kwargs: typing.Type[Schema], ) -> 'Animal': return super().__new__( cls, *args, className=className, color=color, _configuration=_configuration, **kwargs, ) from petstore_api.model.cat import Cat from petstore_api.model.dog import Dog
833980c8158fa0f25d3ae7485542f3655bc24ef9
18e48f22f88fe80ce54d12fdbf9d05a7ca5bd65a
/0x04-python-more_data_structures/3-common_elements.py
bdcdc3ae779109657e7ebde98aeb7e93558c88ae
[]
no_license
SantiagoHerreG/holbertonschool-higher_level_programming
426c4bc9bc080a81b72d2f740c8ed2eb365023eb
ca2612ef3be92a60764d584cf39de3a2ba310f84
refs/heads/master
2020-07-22T19:33:48.507287
2020-02-14T04:34:00
2020-02-14T04:34:00
207,305,022
0
0
null
null
null
null
UTF-8
Python
false
false
105
py
#!/usr/bin/python3 def common_elements(set_1, set_2): new_set = set_1 & set_2 return (new_set)
fd96964145fbc06b436ee1ecbbf561c15f201c00
caf192dbc1ca90fee18bb4ce170d37eb14870ec5
/Chapter-5/7. Caesar cipher.py
f827a177676fc978c4d7d8bfee8324bfba34dc4a
[]
no_license
Dfredude/PythonZelle
858b00f5eacce841173c64b3cecd978dedbeb145
1923fe84df604968eebc5269f23b7c0f167d55f0
refs/heads/main
2023-08-30T21:45:57.070344
2021-10-17T01:32:57
2021-10-17T01:32:57
359,041,963
0
0
null
null
null
null
UTF-8
Python
false
false
496
py
def main(): #Get plaintext(p_text) and key(x) from the user p_text = input("Enter the message you'd like encrypted.\n") key = eval(input("What's the key? : ")) p_text = p_text.lower() #Create string of letters table = "abcdefghijklmnopqrstuvwxyz" #Convert plaintext to ciphertext(c_text) using cipher loop c_text = "" for ch in p_text: c_text = c_text + (table[((ord(ch)) - 97) + key % 52]) print("Your encoded message is {0}.".format(c_text)) main()
80338f57e4494dc5fd84346bfab8cd6f883a4347
b5dabe2e6da0e53498650b3c3f3f944c20f3e050
/dolo/compiler/function_compiler_numexpr.py
e20ec37370ffaf43ad7e04c17d62a3028aaf64d8
[ "BSD-2-Clause" ]
permissive
christophe-gouel/dolo
12d582ecf3289aa9168f5d825da83a6284d5a669
d9aef6d78d19899e2669e49ee6b7ad9aacf0e35d
refs/heads/master
2020-12-24T09:31:19.389548
2018-01-04T20:42:19
2018-01-04T20:42:19
6,064,096
0
0
null
null
null
null
UTF-8
Python
false
false
3,105
py
from __future__ import division from dolo.symbolic.derivatives import DerivativesTree from dolo.symbolic.symbolic import TSymbol from dolo.compiler.function_compiler import compile_multiargument_function as compile_multiargument_function_regular DerivativesTree.symbol_type = TSymbol def compile_multiargument_function(equations, args_list, args_names, parms, fname='anonymous_function', diff=True, return_text=False, order='rows'): return compile_multiargument_function_regular(equations, args_list, args_names, parms, fname=fname, diff=diff, return_text=return_text, use_numexpr=True, order=order) if __name__ == '__main__': import sympy from pprint import pprint [w,x,y,z,t] = vars = sympy.symbols('w, x, y, z, t') [a,b,c,d] = parms = sympy.symbols('a, b, c, d') [k_1,k_2] = s_sym = sympy.symbols('k_1, k_2') [x_1,x_2] = x_sym = sympy.symbols('x_1, x_2') args_list = [ s_sym, x_sym ] from sympy import exp eqs = [ x + y*k_2 + z*exp(x_1 + t), (y + z)**0.3, z, (k_1 + k_2)**0.3, k_2**x_1 ] sdict = {s:eqs[i] for i,s in enumerate(vars) } from dolo.misc.triangular_solver import solve_triangular_system order = solve_triangular_system(sdict, return_order=True) ordered_vars = [ v for v in order ] ordered_eqs = [ eqs[vars.index(v)] for v in order ] pprint(ordered_vars) pprint(ordered_eqs) import numpy floatX = numpy.float32 s0 = numpy.array( [2,5], dtype=floatX) x0 = numpy.array( [2,2], dtype=floatX) p0 = numpy.array( [4,3], dtype=floatX) N = 2000 s1 = numpy.column_stack( [s0]*N ) x1 = numpy.column_stack( [x0]*N ) p1 = numpy.array( [4,3, 6, 7], dtype=floatX ) # f = create_fun() # # test = f(s1,x1,p0) # print(test) args_names = ['s','x'] # # solution = solve_triangular_system(sdict) vals = [sympy.sympify(solution[v]) for v in ordered_vars] from dolo.compiler.compiling import compile_multiargument_function as numpy_compiler from dolo.compiler.compiling_theano import compile_multiargument_function as theano_compiler f_numexpr = compile_multiargument_function( vals, args_list, args_names, parms ) f_numpy = numpy_compiler( vals, args_list, args_names, parms ) f_theano = theano_compiler( vals, args_list, args_names, parms ) n_exp = 1000 import time r = time.time() for i in range(n_exp): res_numexpr = f_numexpr(s1,x1,p1) # res = numpy.row_stack(res) s = time.time() print('Time (numexpr) : '+ str(s-r)) r = time.time() for i in range(n_exp): res_theano = f_theano(s1,x1,p1) # res = numpy.row_stack(res) s = time.time() print('Time (theano) : '+ str(s-r)) r = time.time() for i in range(n_exp): res_numpy = f_numpy(s1,x1,p1) # res = numpy.row_stack(res) s = time.time() print('Time (numpy) : '+ str(s-r)) print( abs(res_numpy - res_theano).max() ) print( abs(res_numexpr - res_numpy).max() )
91dbf8f944594010b21f4e33cdd5c303b603daa0
50948d4cb10dcb1cc9bc0355918478fb2841322a
/azure-mgmt-network/azure/mgmt/network/v2018_02_01/models/outbound_nat_rule.py
509f9e9922798df037d6dab645f99d2111cc92f6
[ "MIT" ]
permissive
xiafu-msft/azure-sdk-for-python
de9cd680b39962702b629a8e94726bb4ab261594
4d9560cfd519ee60667f3cc2f5295a58c18625db
refs/heads/master
2023-08-12T20:36:24.284497
2019-05-22T00:55:16
2019-05-22T00:55:16
187,986,993
1
0
MIT
2020-10-02T01:17:02
2019-05-22T07:33:46
Python
UTF-8
Python
false
false
2,886
py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from .sub_resource import SubResource class OutboundNatRule(SubResource): """Outbound NAT pool of the load balancer. All required parameters must be populated in order to send to Azure. :param id: Resource ID. :type id: str :param allocated_outbound_ports: The number of outbound ports to be used for NAT. :type allocated_outbound_ports: int :param frontend_ip_configurations: The Frontend IP addresses of the load balancer. :type frontend_ip_configurations: list[~azure.mgmt.network.v2018_02_01.models.SubResource] :param backend_address_pool: Required. A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the backend IPs. :type backend_address_pool: ~azure.mgmt.network.v2018_02_01.models.SubResource :param provisioning_state: Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: The name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'backend_address_pool': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'allocated_outbound_ports': {'key': 'properties.allocatedOutboundPorts', 'type': 'int'}, 'frontend_ip_configurations': {'key': 'properties.frontendIPConfigurations', 'type': '[SubResource]'}, 'backend_address_pool': {'key': 'properties.backendAddressPool', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, **kwargs): super(OutboundNatRule, self).__init__(**kwargs) self.allocated_outbound_ports = kwargs.get('allocated_outbound_ports', None) self.frontend_ip_configurations = kwargs.get('frontend_ip_configurations', None) self.backend_address_pool = kwargs.get('backend_address_pool', None) self.provisioning_state = kwargs.get('provisioning_state', None) self.name = kwargs.get('name', None) self.etag = kwargs.get('etag', None)
bedf0931ccef770750040887a803cdba60d8d515
de1f9d660cfb738afdb66e4a2d63a4577c07d9c6
/test/webapi/controllers/test_wmts.py
ad52d78c1aaca58531a54c0ef0ecba42c5079c04
[ "MIT" ]
permissive
rabaneda/xcube
db47eb416db85df891a924063482a7943cae9d4f
0d38ca513987184dbc4a37da1616e4076964d0f1
refs/heads/master
2020-11-24T00:11:17.107630
2020-02-11T10:11:34
2020-02-11T10:11:34
227,877,138
0
0
MIT
2019-12-13T16:14:51
2019-12-13T16:14:50
null
UTF-8
Python
false
false
703
py
import os import unittest from test.webapi.helpers import get_res_test_dir, new_test_service_context from xcube.webapi.controllers.wmts import get_wmts_capabilities_xml class WmtsControllerTest(unittest.TestCase): def test_get_wmts_capabilities_xml(self): self.maxDiff = None with open(os.path.join(get_res_test_dir(), 'WMTSCapabilities.xml')) as fp: expected_capabilities = fp.read() ctx = new_test_service_context() capabilities = get_wmts_capabilities_xml(ctx, 'http://bibo') print(80 * '=') print(capabilities) print(80 * '=') self.assertEqual(expected_capabilities.replace(' ', ''), capabilities.replace(' ', ''))
3be06eb873cdd1760ff6e5f63aa67790705e4936
70cdf0741a22c678401a306229003bf036ffe5a6
/ocbind/interfaces/interface/routed_vlan/ipv4/state/counters/__init__.py
fc80550902dca33ef1415b13bb6c12c3d63fa5ce
[]
no_license
zsblevins/nanog81-hackathon
5001e034339d6b0c6452ae2474f06916bcd715cf
1b64fd207dd69837f947094fbd6d6c1cea3a1070
refs/heads/main
2023-03-03T09:39:28.460000
2021-02-15T13:41:38
2021-02-15T13:41:38
336,698,856
2
0
null
null
null
null
UTF-8
Python
false
false
42,316
py
# -*- coding: utf-8 -*- from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.yangtypes import YANGDynClass from pyangbind.lib.yangtypes import ReferenceType from pyangbind.lib.base import PybindBase from collections import OrderedDict from decimal import Decimal from bitarray import bitarray import six # PY3 support of some PY2 keywords (needs improved) if six.PY3: import builtins as __builtin__ long = int elif six.PY2: import __builtin__ class counters(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module openconfig-interfaces - based on the path /interfaces/interface/routed-vlan/ipv4/state/counters. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: Packet and byte counters for IP transmission and reception for the address family. """ __slots__ = ('_path_helper', '_extmethods', '__in_pkts','__in_octets','__in_error_pkts','__in_forwarded_pkts','__in_forwarded_octets','__in_discarded_pkts','__out_pkts','__out_octets','__out_error_pkts','__out_forwarded_pkts','__out_forwarded_octets','__out_discarded_pkts',) _yang_name = 'counters' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): self._path_helper = False self._extmethods = False self.__in_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__in_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__in_error_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__in_forwarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__in_forwarded_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__in_discarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_error_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_forwarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_forwarded_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) self.__out_discarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return ['interfaces', 'interface', 'routed-vlan', 'ipv4', 'state', 'counters'] def _get_in_pkts(self): """ Getter method for in_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_pkts (oc-yang:counter64) YANG Description: The total number of IP packets received for the specified address family, including those received in error """ return self.__in_pkts def _set_in_pkts(self, v, load=False): """ Setter method for in_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_pkts() directly. YANG Description: The total number of IP packets received for the specified address family, including those received in error """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_pkts = t if hasattr(self, '_set'): self._set() def _unset_in_pkts(self): self.__in_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_in_octets(self): """ Getter method for in_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_octets (oc-yang:counter64) YANG Description: The total number of octets received in input IP packets for the specified address family, including those received in error. """ return self.__in_octets def _set_in_octets(self, v, load=False): """ Setter method for in_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_octets (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_octets is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_octets() directly. YANG Description: The total number of octets received in input IP packets for the specified address family, including those received in error. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_octets must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_octets = t if hasattr(self, '_set'): self._set() def _unset_in_octets(self): self.__in_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_in_error_pkts(self): """ Getter method for in_error_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_error_pkts (oc-yang:counter64) YANG Description: Number of IP packets discarded due to errors for the specified address family, including errors in the IP header, no route found to the IP destination, invalid address, unknown protocol, etc. """ return self.__in_error_pkts def _set_in_error_pkts(self, v, load=False): """ Setter method for in_error_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_error_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_error_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_error_pkts() directly. YANG Description: Number of IP packets discarded due to errors for the specified address family, including errors in the IP header, no route found to the IP destination, invalid address, unknown protocol, etc. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_error_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_error_pkts = t if hasattr(self, '_set'): self._set() def _unset_in_error_pkts(self): self.__in_error_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_in_forwarded_pkts(self): """ Getter method for in_forwarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_forwarded_pkts (oc-yang:counter64) YANG Description: The number of input packets for which the device was not their final IP destination and for which the device attempted to find a route to forward them to that final destination. """ return self.__in_forwarded_pkts def _set_in_forwarded_pkts(self, v, load=False): """ Setter method for in_forwarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_forwarded_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_forwarded_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_forwarded_pkts() directly. YANG Description: The number of input packets for which the device was not their final IP destination and for which the device attempted to find a route to forward them to that final destination. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_forwarded_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_forwarded_pkts = t if hasattr(self, '_set'): self._set() def _unset_in_forwarded_pkts(self): self.__in_forwarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_in_forwarded_octets(self): """ Getter method for in_forwarded_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_forwarded_octets (oc-yang:counter64) YANG Description: The number of octets received in input IP packets for the specified address family for which the device was not their final IP destination and for which the device attempted to find a route to forward them to that final destination. """ return self.__in_forwarded_octets def _set_in_forwarded_octets(self, v, load=False): """ Setter method for in_forwarded_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_forwarded_octets (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_forwarded_octets is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_forwarded_octets() directly. YANG Description: The number of octets received in input IP packets for the specified address family for which the device was not their final IP destination and for which the device attempted to find a route to forward them to that final destination. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_forwarded_octets must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_forwarded_octets = t if hasattr(self, '_set'): self._set() def _unset_in_forwarded_octets(self): self.__in_forwarded_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_in_discarded_pkts(self): """ Getter method for in_discarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_discarded_pkts (oc-yang:counter64) YANG Description: The number of input IP packets for the specified address family, for which no problems were encountered to prevent their continued processing, but were discarded (e.g., for lack of buffer space). """ return self.__in_discarded_pkts def _set_in_discarded_pkts(self, v, load=False): """ Setter method for in_discarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/in_discarded_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_in_discarded_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_in_discarded_pkts() directly. YANG Description: The number of input IP packets for the specified address family, for which no problems were encountered to prevent their continued processing, but were discarded (e.g., for lack of buffer space). """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """in_discarded_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__in_discarded_pkts = t if hasattr(self, '_set'): self._set() def _unset_in_discarded_pkts(self): self.__in_discarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_pkts(self): """ Getter method for out_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_pkts (oc-yang:counter64) YANG Description: The total number of IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device. """ return self.__out_pkts def _set_out_pkts(self, v, load=False): """ Setter method for out_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_pkts() directly. YANG Description: The total number of IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_pkts = t if hasattr(self, '_set'): self._set() def _unset_out_pkts(self): self.__out_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_octets(self): """ Getter method for out_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_octets (oc-yang:counter64) YANG Description: The total number of octets in IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device. """ return self.__out_octets def _set_out_octets(self, v, load=False): """ Setter method for out_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_octets (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_octets is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_octets() directly. YANG Description: The total number of octets in IP packets for the specified address family that the device supplied to the lower layers for transmission. This includes packets generated locally and those forwarded by the device. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_octets must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_octets = t if hasattr(self, '_set'): self._set() def _unset_out_octets(self): self.__out_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_error_pkts(self): """ Getter method for out_error_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_error_pkts (oc-yang:counter64) YANG Description: Number of IP packets for the specified address family locally generated and discarded due to errors, including no route found to the IP destination. """ return self.__out_error_pkts def _set_out_error_pkts(self, v, load=False): """ Setter method for out_error_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_error_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_error_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_error_pkts() directly. YANG Description: Number of IP packets for the specified address family locally generated and discarded due to errors, including no route found to the IP destination. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_error_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_error_pkts = t if hasattr(self, '_set'): self._set() def _unset_out_error_pkts(self): self.__out_error_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-error-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_forwarded_pkts(self): """ Getter method for out_forwarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_forwarded_pkts (oc-yang:counter64) YANG Description: The number of packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination. """ return self.__out_forwarded_pkts def _set_out_forwarded_pkts(self, v, load=False): """ Setter method for out_forwarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_forwarded_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_forwarded_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_forwarded_pkts() directly. YANG Description: The number of packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_forwarded_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_forwarded_pkts = t if hasattr(self, '_set'): self._set() def _unset_out_forwarded_pkts(self): self.__out_forwarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_forwarded_octets(self): """ Getter method for out_forwarded_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_forwarded_octets (oc-yang:counter64) YANG Description: The number of octets in packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination. """ return self.__out_forwarded_octets def _set_out_forwarded_octets(self, v, load=False): """ Setter method for out_forwarded_octets, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_forwarded_octets (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_forwarded_octets is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_forwarded_octets() directly. YANG Description: The number of octets in packets for which this entity was not their final IP destination and for which it was successful in finding a path to their final destination. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_forwarded_octets must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_forwarded_octets = t if hasattr(self, '_set'): self._set() def _unset_out_forwarded_octets(self): self.__out_forwarded_octets = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-forwarded-octets", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) def _get_out_discarded_pkts(self): """ Getter method for out_discarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_discarded_pkts (oc-yang:counter64) YANG Description: The number of output IP packets for the specified address family for which no problem was encountered to prevent their transmission to their destination, but were discarded (e.g., for lack of buffer space). """ return self.__out_discarded_pkts def _set_out_discarded_pkts(self, v, load=False): """ Setter method for out_discarded_pkts, mapped from YANG variable /interfaces/interface/routed_vlan/ipv4/state/counters/out_discarded_pkts (oc-yang:counter64) If this variable is read-only (config: false) in the source YANG file, then _set_out_discarded_pkts is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_out_discarded_pkts() directly. YANG Description: The number of output IP packets for the specified address family for which no problem was encountered to prevent their transmission to their destination, but were discarded (e.g., for lack of buffer space). """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) except (TypeError, ValueError): raise ValueError({ 'error-string': """out_discarded_pkts must be of a type compatible with oc-yang:counter64""", 'defined-type': "oc-yang:counter64", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False)""", }) self.__out_discarded_pkts = t if hasattr(self, '_set'): self._set() def _unset_out_discarded_pkts(self): self.__out_discarded_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-discarded-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/interfaces/ip', defining_module='openconfig-if-ip', yang_type='oc-yang:counter64', is_config=False) in_pkts = __builtin__.property(_get_in_pkts) in_octets = __builtin__.property(_get_in_octets) in_error_pkts = __builtin__.property(_get_in_error_pkts) in_forwarded_pkts = __builtin__.property(_get_in_forwarded_pkts) in_forwarded_octets = __builtin__.property(_get_in_forwarded_octets) in_discarded_pkts = __builtin__.property(_get_in_discarded_pkts) out_pkts = __builtin__.property(_get_out_pkts) out_octets = __builtin__.property(_get_out_octets) out_error_pkts = __builtin__.property(_get_out_error_pkts) out_forwarded_pkts = __builtin__.property(_get_out_forwarded_pkts) out_forwarded_octets = __builtin__.property(_get_out_forwarded_octets) out_discarded_pkts = __builtin__.property(_get_out_discarded_pkts) _pyangbind_elements = OrderedDict([('in_pkts', in_pkts), ('in_octets', in_octets), ('in_error_pkts', in_error_pkts), ('in_forwarded_pkts', in_forwarded_pkts), ('in_forwarded_octets', in_forwarded_octets), ('in_discarded_pkts', in_discarded_pkts), ('out_pkts', out_pkts), ('out_octets', out_octets), ('out_error_pkts', out_error_pkts), ('out_forwarded_pkts', out_forwarded_pkts), ('out_forwarded_octets', out_forwarded_octets), ('out_discarded_pkts', out_discarded_pkts), ])
a21dfa9182883f7045cd35880f722f3d9a36a0ab
45e376ae66b78b17788b1d3575b334b2cb1d0b1c
/tests/terraform/checks/resource/azure/test_SynapseWorkspaceEnablesDataExfilProtection.py
2f0a8e8e46b503edb13ed42ed956bc6d6a70830a
[ "Apache-2.0" ]
permissive
bridgecrewio/checkov
aeb8febed2ed90e61d5755f8f9d80b125362644d
e64cbd27ffb6f09c2c9f081b45b7a821a3aa1a4d
refs/heads/main
2023-08-31T06:57:21.990147
2023-08-30T23:01:47
2023-08-30T23:01:47
224,386,599
5,929
1,056
Apache-2.0
2023-09-14T20:10:23
2019-11-27T08:55:14
Python
UTF-8
Python
false
false
1,453
py
import unittest from pathlib import Path from checkov.runner_filter import RunnerFilter from checkov.terraform.checks.resource.azure.SynapseWorkspaceEnablesDataExfilProtection import check from checkov.terraform.runner import Runner class TestSynapseWorkspaceEnablesDataExfilProtection(unittest.TestCase): def test(self): # given test_files_dir = Path(__file__).parent / "example_SynapseWorkspaceEnablesDataExfilProtection" # when report = Runner().run(root_folder=str(test_files_dir), runner_filter=RunnerFilter(checks=[check.id])) # then summary = report.get_summary() passing_resources = { "azurerm_synapse_workspace.pass", } failing_resources = { "azurerm_synapse_workspace.fail", "azurerm_synapse_workspace.fail2", } passed_check_resources = {c.resource for c in report.passed_checks} failed_check_resources = {c.resource for c in report.failed_checks} self.assertEqual(summary["passed"], 1) self.assertEqual(summary["failed"], 2) self.assertEqual(summary["skipped"], 0) self.assertEqual(summary["parsing_errors"], 0) self.assertEqual(summary["resource_count"], 3) # 3 unknown self.assertEqual(passing_resources, passed_check_resources) self.assertEqual(failing_resources, failed_check_resources) if __name__ == "__main__": unittest.main()
1ebd7b2c006bec2429d3ea7c144429ca6a16ab58
34599596e145555fde0d4264a1d222f951f49051
/pcat2py/class/235864d6-5cc5-11e4-af55-00155d01fe08.py
203705756d386be4768e626b13c813ce06acf1fd
[ "MIT" ]
permissive
phnomcobra/PCAT2PY
dc2fcbee142ce442e53da08476bfe4e68619346d
937c3b365cdc5ac69b78f59070be0a21bdb53db0
refs/heads/master
2021-01-11T02:23:30.669168
2018-02-13T17:04:03
2018-02-13T17:04:03
70,970,520
0
0
null
null
null
null
UTF-8
Python
false
false
1,212
py
#!/usr/bin/python ################################################################################ # 235864d6-5cc5-11e4-af55-00155d01fe08 # # Justin Dierking # [email protected] # [email protected] # # 10/24/2014 Original Construction ################################################################################ class Finding: def __init__(self): self.output = [] self.is_compliant = False self.uuid = "235864d6-5cc5-11e4-af55-00155d01fe08" def check(self, cli): # Initialize Compliance self.is_compliant = False # Execute command and parse capture standard output stdout = cli.system("ls -l /etc/group") # Split output lines self.output = stdout.split('\n') # Process standard output lineNumber = 0 for line in self.output: lineNumber += 1 if len(line.strip()) > 0: subStrings = line.split(' ') if subStrings[3] == "root": self.is_compliant = True return self.is_compliant def fix(self, cli): cli.system("chgrp root /etc/group")
d09e8f1f8f6ce69f17db42f0cc74904c1ba4e74e
e48375c39c0d1fc71742b1964dffdd3af0ff86c0
/nlu/components/sentence_detectors/deep_sentence_detector/deep_sentence_detector.py
ab4ea95db84960ec483781f792af9daed7b121c3
[ "Apache-2.0" ]
permissive
ahmedlone127/nlu
b8da5a84f0e47640cb09616559bf8b84c259f278
614bc2ff94c80a7ebc34a78720ef29a1bf7080e0
refs/heads/master
2023-02-09T05:10:29.631583
2022-05-20T15:16:33
2022-05-20T15:16:33
325,437,640
0
0
null
null
null
null
UTF-8
Python
false
false
700
py
from sparknlp.annotator import * class SentenceDetectorDeep: @staticmethod def get_default_model(): return SentenceDetectorDLModel\ .pretrained()\ .setInputCols(["document"]) \ .setOutputCol("sentence") @staticmethod def get_pretrained_model(name,lang, bucket=None): return SentenceDetectorDLModel.pretrained(name,lang,bucket) \ .pretrained() \ .setInputCols(["document"]) \ .setOutputCol("sentence") # # # @staticmethod # def get_trainable_model(): # return SentenceDetectorDLApproach \ # .setInputCol("document") \ # .setOutputCol("sentence")
6312c87325c4ac19ffd4a502d580ce4c926c0ab6
6f269812a96d47c5670b4a7d5512f01bc7156217
/manage.py
18c1b3390a3f1f98873d26d42fc900e32bb82d06
[]
no_license
kalkins/buk-django
00a1724c19127840ac19182f003e28ed4f4f4480
708071d144b06ab289abdea6046437c40a81d230
refs/heads/dev
2022-12-13T05:51:30.664433
2019-02-12T03:10:04
2019-02-12T03:10:04
77,866,135
4
0
null
2022-12-08T01:28:31
2017-01-02T22:34:59
Python
UTF-8
Python
false
false
801
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "buk.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
70568dbd8fea74a804629bbf8c0ba8699ea10aaf
b0d7d91ccb7e388829abddb31b4aa04a2f9365cd
/archive-20200922/uncategorized/quick_palindrome_check.py
4e1d9675666f0b9bddffa3ece524d351e0e26a37
[]
no_license
clarkngo/python-projects
fe0e0aa02896debe82d1e9de84b1ae7d00932607
139a20063476f9847652b334a8495b7df1e80e27
refs/heads/master
2021-07-02T10:45:31.242041
2020-10-25T08:59:23
2020-10-25T08:59:23
188,570,684
0
0
null
null
null
null
UTF-8
Python
false
false
365
py
# function which return reverse of a string def reverse(s): return s[::-1] def isPalindrome(s): # Calling reverse function rev = reverse(s) # Checking if both string are equal or not if (s == rev): return True return False # Driver code s = "malayalam" ans = isPalindrome(s) if ans == 1: print("Yes") else: print("No")
848b00dce8c68b93c85b751b4d5c57683f6980f1
2ed86a79d0fcd299ad4a01310954c5eddcf01edf
/homeassistant/components/airzone/coordinator.py
ba0296557a1be58bacea112719a507f82be0fb6b
[ "Apache-2.0" ]
permissive
konnected-io/home-assistant
037f12c87bb79e19220192eb918e49db1b1a8b3e
2e65b77b2b5c17919939481f327963abdfdc53f0
refs/heads/dev
2023-05-11T08:57:41.891518
2023-05-07T20:03:37
2023-05-07T20:03:37
109,931,626
24
10
Apache-2.0
2023-02-22T06:24:01
2017-11-08T05:27:21
Python
UTF-8
Python
false
false
1,309
py
"""The Airzone integration.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aioairzone.exceptions import AirzoneError from aioairzone.localapi import AirzoneLocalApi import async_timeout from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import AIOAIRZONE_DEVICE_TIMEOUT_SEC, DOMAIN SCAN_INTERVAL = timedelta(seconds=60) _LOGGER = logging.getLogger(__name__) class AirzoneUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Class to manage fetching data from the Airzone device.""" def __init__(self, hass: HomeAssistant, airzone: AirzoneLocalApi) -> None: """Initialize.""" self.airzone = airzone super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, ) async def _async_update_data(self) -> dict[str, Any]: """Update data via library.""" async with async_timeout.timeout(AIOAIRZONE_DEVICE_TIMEOUT_SEC): try: await self.airzone.update() except AirzoneError as error: raise UpdateFailed(error) from error return self.airzone.data()
3016c687ec5ae81b1cd9d16c05eb06f58500219f
968968aa5e81043cad5af6883f23ef077c36b65f
/load_model.py
87518857933f46b083d4611584a50ca9100d20e9
[]
no_license
Guya-LTD/profanity-detector
59dbcb2e3e2fe4eba29cd49f5f028c48413f035f
ba957c42c4d14dd3c68ef2c48fce317e9db17f8f
refs/heads/main
2023-02-11T18:26:59.205036
2021-01-10T06:41:25
2021-01-10T06:41:25
307,553,959
0
0
null
null
null
null
UTF-8
Python
false
false
495
py
import numpy as np import joblib def _get_profane_prob(prob): return prob[1] def predict(lang, texts): vectorizer = joblib.load(lang + '/vectorizer.joblib') model = joblib.load(lang + '/model.joblib') return model.predict(vectorizer.transform(texts)) def predict_prob(lang, texts): vectorizer = joblib.load(lang + '/vectorizer.joblib') model = joblib.load(lang + '/model.joblib') return np.apply_along_axis(_get_profane_prob, 1, model.predict_proba(vectorizer.transform(texts)))
e6ea4e632b0b731721851c7db5ec5498ae307b76
3cb06711ab1a6e379e5778456fce5770ac994ba9
/python/wait_functions_test_py3.py
02cab39f268b7e1880b29bbcbcffa372099fe449
[ "MIT" ]
permissive
glenn-edgar/chain_flow
7e8238c1f5e5c00f4c5906e2eb356d33c2b4696c
750a9b126de04e46b71a58c5bd3e7500c4d26459
refs/heads/master
2021-01-02T22:41:30.066536
2017-09-05T19:34:57
2017-09-05T19:34:57
99,368,944
0
0
null
null
null
null
UTF-8
Python
false
false
1,444
py
from py_cf_py3.chain_flow_py3 import CF_Base_Interpreter def test_function_1( cf_handle, chainObj, parameters, event ): print("test function 1 ",event) def wait_test_function( cf_handle, chainObj, parameters, event ): print("event",event) return_value = False if event["name"] == "INIT": parameters.append(0) if event["name"] == "TIME_TICK": parameters[-1] = parameters[-1] +1 if parameters[-1] >= parameters[1]: return_value = True return return_value cf = CF_Base_Interpreter() cf.define_chain("Chain_1", False) # wait_tod cf.insert.log("Chain 1 started") cf.insert.wait_tod( "*","*","*",15 ) # wait for 15 seconds cf.insert.one_step( test_function_1) cf.insert.log("Chain 1 is reset") cf.insert.reset( ) cf.define_chain("Chain_2",False) # wait_tod_ge wait_tod_le cf.insert.log("Chain 2 started") cf.insert.wait_tod_ge( "*","*","*",45 ) # wait for 15 seconds cf.insert.check_event( test_function_1, "TIME_TICK" ) cf.insert.wait_tod_le( "*","*","*",15) # wait for 15 seconds cf.insert.reset( ) cf.define_chain("Chain_3",False) #wait_event_count cf.insert.log("Chain 3 started") cf.insert.wait_event_count(count = 10) cf.insert.one_step( test_function_1) cf.insert.reset() cf.define_chain("Chain_4",True) # wait_function cf.insert.log("Chain 4 has started") cf.insert.wait_function(wait_test_function, 10 ) cf.insert.log("Chain 4 is ended ") cf.insert.reset() cf.execute()
cb20e9e52b32e9c6326a763015d867ba85acb885
7b5f7dc5b6a0fc063aeabc9f2408dc867586c129
/env/lib/python2.7/site-packages/sure/old.py
59cef893c4075eff83a691a530ebb8822e678328
[]
no_license
kingbifoe/django-calendar-reminder
687dfa419895cfc67f5fad542179d9d4a716e75d
3325717f53fd9825e036f21f391510f6a754aa93
refs/heads/master
2023-01-02T05:10:47.418059
2016-04-10T19:04:44
2016-04-10T19:04:44
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,705
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # <sure - utility belt for automated testing in python> # Copyright (C) <2010-2013> Gabriel Falcão <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import re import traceback import inspect from copy import deepcopy from pprint import pformat from functools import wraps try: from collections import Iterable except ImportError: Iterable = (list, dict, tuple, set) try: import __builtin__ as builtins except ImportError: import builtins from six import string_types, text_type from sure.core import DeepComparison from sure.core import _get_file_name from sure.core import _get_line_number from sure.core import itemize_length def is_iterable(obj): return hasattr(obj, '__iter__') and not isinstance(obj, string_types) def all_integers(obj): if not is_iterable(obj): return for element in obj: if not isinstance(element, int): return return True def explanation(msg): def dec(func): @wraps(func) def wrap(self, what): ret = func(self, what) assert ret, msg % (self._src, what) return True return wrap return dec class AssertionHelper(object): def __init__(self, src, within_range=None, with_args=None, with_kwargs=None, and_kwargs=None): self._src = src self._attribute = None self._eval = None self._range = None if all_integers(within_range): if len(within_range) != 2: raise TypeError( 'within_range parameter must be a tuple with 2 objects', ) self._range = within_range self._callable_args = [] if isinstance(with_args, (list, tuple)): self._callable_args = list(with_args) self._callable_kw = {} if isinstance(with_kwargs, dict): self._callable_kw.update(with_kwargs) if isinstance(and_kwargs, dict): self._callable_kw.update(and_kwargs) @classmethod def is_a_matcher(cls, func): def match(self, *args, **kw): return func(self._src, *args, **kw) new_matcher = deepcopy(match) new_matcher.__name__ = func.__name__ setattr(cls, func.__name__, new_matcher) return new_matcher def raises(self, exc, msg=None): if not callable(self._src): raise TypeError('%r is not callable' % self._src) try: self._src(*self._callable_args, **self._callable_kw) except BaseException as e: if isinstance(exc, string_types): msg = exc exc = type(e) err = text_type(e) if isinstance(exc, type) and issubclass(exc, BaseException): if not isinstance(e, exc): raise AssertionError( '%r should raise %r, but raised %r:\nORIGINAL EXCEPTION:\n\n%s' % ( self._src, exc, e.__class__, traceback.format_exc(e))) if isinstance(msg, string_types) and msg not in err: raise AssertionError(''' %r raised %s, but the exception message does not match.\n\nEXPECTED:\n%s\n\nGOT:\n%s'''.strip() % ( self._src, type(e).__name__, msg, err)) elif isinstance(msg, string_types) and msg not in err: raise AssertionError( 'When calling %r the exception message does not match. ' \ 'Expected: %r\n got:\n %r' % (self._src, msg, err)) else: raise e else: if inspect.isbuiltin(self._src): _src_filename = '<built-in function>' else: _src_filename = _get_file_name(self._src) if inspect.isfunction(self._src): _src_lineno = _get_line_number(self._src) raise AssertionError( 'calling function %s(%s at line: "%d") with args %r and kwargs %r did not raise %r' % ( self._src.__name__, _src_filename, _src_lineno, self._callable_args, self._callable_kw, exc)) else: raise AssertionError( 'at %s:\ncalling %s() with args %r and kwargs %r did not raise %r' % ( _src_filename, self._src.__name__, self._callable_args, self._callable_kw, exc)) return True def deep_equals(self, dst): deep = DeepComparison(self._src, dst) comparison = deep.compare() if isinstance(comparison, bool): return comparison raise comparison.as_assertion(self._src, dst) def equals(self, dst): if self._attribute and is_iterable(self._src): msg = '%r[%d].%s should be %r, but is %r' for index, item in enumerate(self._src): if self._range: if index < self._range[0] or index > self._range[1]: continue attribute = getattr(item, self._attribute) error = msg % ( self._src, index, self._attribute, dst, attribute) if attribute != dst: raise AssertionError(error) else: return self.deep_equals(dst) return True def looks_like(self, dst): old_src = pformat(self._src) old_dst = pformat(dst) self._src = re.sub(r'\s', '', self._src).lower() dst = re.sub(r'\s', '', dst).lower() error = '%s does not look like %s' % (old_src, old_dst) assert self._src == dst, error return self._src == dst def every_one_is(self, dst): msg = 'all members of %r should be %r, but the %dth is %r' for index, item in enumerate(self._src): if self._range: if index < self._range[0] or index > self._range[1]: continue error = msg % (self._src, dst, index, item) if item != dst: raise AssertionError(error) return True @explanation('%r should differ to %r, but is the same thing') def differs(self, dst): return self._src != dst @explanation('%r should be a instance of %r, but is not') def is_a(self, dst): return isinstance(self._src, dst) def at(self, key): assert self.has(key) if isinstance(self._src, dict): return AssertionHelper(self._src[key]) else: return AssertionHelper(getattr(self._src, key)) @explanation('%r should have %r, but have not') def has(self, that): return that in self def _get_that(self, that): try: that = int(that) except TypeError: that = len(that) return that def len_greater_than(self, that): that = self._get_that(that) length = len(self._src) if length <= that: error = 'the length of the %s should be greater then %d, but is %d' % ( type(self._src).__name__, that, length, ) raise AssertionError(error) return True def len_greater_than_or_equals(self, that): that = self._get_that(that) length = len(self._src) if length < that: error = 'the length of %r should be greater then or equals %d, but is %d' % ( self._src, that, length, ) raise AssertionError(error) return True def len_lower_than(self, that): original_that = that if isinstance(that, Iterable): that = len(that) else: that = self._get_that(that) length = len(self._src) if length >= that: error = 'the length of %r should be lower then %r, but is %d' % ( self._src, original_that, length, ) raise AssertionError(error) return True def len_lower_than_or_equals(self, that): that = self._get_that(that) length = len(self._src) error = 'the length of %r should be lower then or equals %d, but is %d' if length > that: msg = error % ( self._src, that, length, ) raise AssertionError(msg) return True def len_is(self, that): that = self._get_that(that) length = len(self._src) if length != that: error = 'the length of %r should be %d, but is %d' % ( self._src, that, length, ) raise AssertionError(error) return True def len_is_not(self, that): that = self._get_that(that) length = len(self._src) if length == that: error = 'the length of %r should not be %d' % ( self._src, that, ) raise AssertionError(error) return True def like(self, that): return self.has(that) def the_attribute(self, attr): self._attribute = attr return self def in_each(self, attr): self._eval = attr return self def matches(self, items): msg = '%r[%d].%s should be %r, but is %r' get_eval = lambda item: eval( "%s.%s" % ('current', self._eval), {}, {'current': item}, ) if self._eval and is_iterable(self._src): if isinstance(items, string_types): items = [items for x in range(len(items))] else: if len(items) != len(self._src): source = list(map(get_eval, self._src)) source_len = len(source) items_len = len(items) raise AssertionError( '%r has %d items, but the matching list has %d: %r' % (source, source_len, items_len, items), ) for index, (item, other) in enumerate(zip(self._src, items)): if self._range: if index < self._range[0] or index > self._range[1]: continue value = get_eval(item) error = msg % (self._src, index, self._eval, other, value) if other != value: raise AssertionError(error) else: return self.equals(items) return True @builtins.property def is_empty(self): try: lst = list(self._src) length = len(lst) assert length == 0, \ '%r is not empty, it has %s' % (self._src, itemize_length(self._src)) return True except TypeError: raise AssertionError("%r is not iterable" % self._src) @builtins.property def are_empty(self): return self.is_empty def __contains__(self, what): if isinstance(self._src, dict): items = self._src.keys() if isinstance(self._src, Iterable): items = self._src else: items = dir(self._src) return what in items def contains(self, what): assert what in self._src, '%r should be in %r' % (what, self._src) return True def does_not_contain(self, what): assert what not in self._src, \ '%r should NOT be in %r' % (what, self._src) return True doesnt_contain = does_not_contain that = AssertionHelper
d82a7c81e00fa27c5ad59a4fc4811c1928d2518e
63daf225819636397fda6ef7e52783331c27f295
/taobao-sdk/top/api/rest/TmallProductSpecsGetRequest.py
b7150211c3b1b6c63e9ce9e9c0ee66bd56c5f336
[]
no_license
cash2one/language-Python
e332ecfb4e9321a11407b29987ee64d44e552b15
8adb4f2fd2f023f9cc89b4edce1da5f71a3332ab
refs/heads/master
2021-06-16T15:15:08.346420
2017-04-20T02:44:16
2017-04-20T02:44:16
112,173,361
1
0
null
2017-11-27T09:08:57
2017-11-27T09:08:57
null
UTF-8
Python
false
false
356
py
''' Created by auto_sdk on 2014.02.28 ''' from top.api.base import RestApi class TmallProductSpecsGetRequest(RestApi): def __init__(self,domain='gw.api.taobao.com',port=80): RestApi.__init__(self,domain, port) self.cat_id = None self.product_id = None self.properties = None def getapiname(self): return 'tmall.product.specs.get'
ce502221c2081beadd2ed01aa5ddd02cf7cf7901
89a90707983bdd1ae253f7c59cd4b7543c9eda7e
/data_structures_and_algorithms_in_python/ch04/power_fast.py
c7f98d650facb9e5b5bb39c4db5cd09f1ee64c4c
[]
no_license
timothyshull/python_reference_code
692a7c29608cadfd46a6cc409a000023e95b9458
f3e2205dd070fd3210316f5f470d371950945028
refs/heads/master
2021-01-22T20:44:07.018811
2017-03-17T19:17:22
2017-03-17T19:17:22
85,346,735
0
0
null
null
null
null
UTF-8
Python
false
false
267
py
def power(x, n): if n == 0: return 1 else: partial = power(x, n // 2) # rely on truncated division result = partial * partial if n % 2 == 1: # if n odd, include extra factor of x result *= x return result
e8fb8b6c7a2c7ba04314e431ec618dd22761941e
612325535126eaddebc230d8c27af095c8e5cc2f
/src/build/android/pylib/utils/device_dependencies.py
c448396fbc0ab0c74370a723afeb7c9fb47be053
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/proto-quic_1V94
1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673
feee14d96ee95313f236e0f0e3ff7719246c84f7
refs/heads/master
2023-04-01T14:36:53.888576
2019-10-17T02:23:04
2019-10-17T02:23:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,315
py
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import re from pylib import constants _BLACKLIST = [ re.compile(r'.*OWNERS'), # Should never be included. re.compile(r'.*\.crx'), # Chrome extension zip files. re.compile(r'.*\.so'), # Libraries packed into .apk. re.compile(r'.*Mojo.*manifest\.json'), # Some source_set()s pull these in. re.compile(r'.*\.py'), # Some test_support targets include python deps. re.compile(r'.*\.stamp'), # Stamp files should never be included. # Some test_support targets include python deps. re.compile(r'.*\.mojom\.js'), # Chrome external extensions config file. re.compile(r'.*external_extensions\.json'), # Exists just to test the compile, not to be run. re.compile(r'.*jni_generator_tests'), # v8's blobs get packaged into APKs. re.compile(r'.*natives_blob.*\.bin'), re.compile(r'.*snapshot_blob.*\.bin'), ] def DevicePathComponentsFor(host_path, output_directory): """Returns the device path components for a given host path. This returns the device path as a list of joinable path components, with None as the first element to indicate that the path should be rooted at $EXTERNAL_STORAGE. e.g., given '$CHROMIUM_SRC/foo/bar/baz.txt' this would return [None, 'foo', 'bar', 'baz.txt'] This handles a couple classes of paths differently than it otherwise would: - All .pak files get mapped to top-level paks/ - Anything in the output directory gets mapped relative to the output directory rather than the source directory. e.g. given '$CHROMIUM_SRC/out/Release/icu_fake_dir/icudtl.dat' this would return [None, 'icu_fake_dir', 'icudtl.dat'] Args: host_path: The absolute path to the host file. Returns: A list of device path components. """ if host_path.startswith(output_directory): if os.path.splitext(host_path)[1] == '.pak': return [None, 'paks', os.path.basename(host_path)] rel_host_path = os.path.relpath(host_path, output_directory) else: rel_host_path = os.path.relpath(host_path, constants.DIR_SOURCE_ROOT) device_path_components = [None] p = rel_host_path while p: p, d = os.path.split(p) if d: device_path_components.insert(1, d) return device_path_components def GetDataDependencies(runtime_deps_path): """Returns a list of device data dependencies. Args: runtime_deps_path: A str path to the .runtime_deps file. Returns: A list of (host_path, device_path) tuples. """ if not runtime_deps_path: return [] with open(runtime_deps_path, 'r') as runtime_deps_file: rel_host_files = [l.strip() for l in runtime_deps_file if l] output_directory = constants.GetOutDirectory() abs_host_files = [ os.path.abspath(os.path.join(output_directory, r)) for r in rel_host_files] filtered_abs_host_files = [ host_file for host_file in abs_host_files if not any(blacklist_re.match(host_file) for blacklist_re in _BLACKLIST)] return [(f, DevicePathComponentsFor(f, output_directory)) for f in filtered_abs_host_files]
b1dea3c4983f09b3a6dc08bf597ea9ff4f8bd617
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2158/60876/250371.py
2410110cab9dc4be3dd9ff187554b0e5447e6868
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
537
py
string=input() index=0 while string[index]==' ': index+=1 temp="" if string[index]=='-': temp+="-" index+=1 while index<len(string) and string[index].isdigit(): temp+=string[index] index+=1 if int(temp)<-2**(31): print( -2**(31)) else: print(temp) elif not string[index].isdigit(): print(0) else: while index<len(string) and string[index].isdigit(): temp+=string[index] index+=1 if int(temp)>2**31-1: print(2**31-1) else: print(temp)
745598179a1f4f9fc81a7259c54c7e70776b17c7
7083f3e6121a63b0c21e15d8b23c32067d7e4e5e
/scripts/debugging/test_data_utils.py
471d21749014c77fe08ae8e78ca5ffb1b5c2ab15
[]
no_license
nathanin/milk
e46317cf0d1b2162fd301a144f5aa3b889cf5d27
9afb3b01715a4f65a03b7cd45dcd121745b117f8
refs/heads/master
2023-02-22T05:23:06.850961
2019-10-26T19:08:20
2019-10-26T19:08:20
154,750,122
2
0
null
2023-02-15T21:36:19
2018-10-25T23:29:33
Jupyter Notebook
UTF-8
Python
false
false
79
py
import sys sys.path.insert(0, '../..') from milk.utilities import data_utils
4371051b460fbdb7f7e35435ddd12876a32f7a6e
21b0b4c27193898207751c91b8b2ed168a1b1638
/py/py_0198_ambiguous_numbers.py
ca312ac6f6f03c67908c6bd6ae8705a25e557c7b
[ "MIT" ]
permissive
lcsm29/project-euler
67560a4e66968f1671a3d7ecf2dda6c956893dca
fab794ece5aa7a11fc7c2177f26250f40a5b1447
refs/heads/main
2023-07-04T11:45:24.374841
2021-08-07T08:20:41
2021-08-07T08:20:41
371,808,781
0
0
null
null
null
null
UTF-8
Python
false
false
1,130
py
# Solution of; # Project Euler Problem 198: Ambiguous Numbers # https://projecteuler.net/problem=198 # # A best approximation to a real number $x$ for the denominator bound $d$ is a # rational number $\frac r s$ (in reduced form) with $s \le d$, so that any # rational number $\frac p q$ which is closer to $x$ than $\frac r s$ has $q > # d$. Usually the best approximation to a real number is uniquely determined # for all denominator bounds. However, there are some exceptions, e. g. $\frac # 9 {40}$ has the two best approximations $\frac 1 4$ and $\frac 1 5$ for the # denominator bound $6$. We shall call a real number $x$ ambiguous, if there # is at least one denominator bound for which $x$ possesses two best # approximations. Clearly, an ambiguous number is necessarily rational. How # many ambiguous numbers $x=\frac p q, 0 < x < \frac 1 {100}$, are there whose # denominator $q$ does not exceed $10^8$? # # by lcsm29 http://github.com/lcsm29/project-euler import timed def dummy(n): pass if __name__ == '__main__': n = 1000 i = 10000 prob_id = 198 timed.caller(dummy, n, i, prob_id)
cac2318a8b307ad741c58dda75e970b204bed67a
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_4/bgrtej001/piglatin.py
8a3ae80180102da97b97c2eee4594a3e8512b2c3
[]
no_license
MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
UTF-8
Python
false
false
1,182
py
#Tejasvin Bagirathi #Assignment 4, Question 3 def toPigLatin(s): wrdno = 1 new = "" for i in range(len(s)): if s[i] == " ": wrdno+=1 string = s.split(" ") for i in range(wrdno): wrd = string[i] #If word starts with vowel if wrd[0] in "aeiou": wrd = wrd + "way" if wrdno == i: new += wrd else: new += wrd + " " else: k = 0 for c in wrd[:]: if c not in "aeiou": k+=1 else: break wrd = wrd[k:len(wrd)] + "a" + wrd[0:k] + "ay" if wrdno == i: new += wrd else: new += wrd + " " return new def toEnglish(s): sentence=s.split() newsentence="" for word in range(len(sentence)): if sentence[word][-3:]=="way": newsentence+=sentence[word][:-3]+" " elif sentence[word][-2:]=="ay": nWord=sentence[word][:-2] aPos=nWord.rfind("a") newsentence+=nWord[aPos+1:]+nWord[:aPos]+" " return(newsentence)
9fb17ce7b6fb0a7b73112825f591381e23c30c80
fe70774ff6898c5bdb0c941b4f335de576abfdb6
/autotest/test_flopy_io.py
bb09cd2207661c1b0258d7feb56b3d6788f12990
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
robinthibaut/flopy
35af468415d1ba6e1de119a7cb335381304fada9
22ef330bcfb9259fc23735d6b174d27804b624a0
refs/heads/develop
2023-06-30T21:43:24.101593
2023-06-13T19:46:03
2023-06-13T19:46:03
255,560,877
0
0
BSD-3-Clause
2022-10-10T12:23:38
2020-04-14T09:05:42
null
UTF-8
Python
false
false
3,153
py
import os import platform from os import getcwd from os.path import relpath, splitdrive from pathlib import Path from shutil import which import pytest from modflow_devtools.markers import requires_exe from modflow_devtools.misc import set_dir from flopy.utils.flopy_io import line_parse, relpath_safe def test_line_parse(): """t027 test line_parse method in MNW2 Package class""" # ensure that line_parse is working correctly # comment handling line = line_parse("Well-A -1 ; 2a. WELLID,NNODES") assert line == ["Well-A", "-1"] @requires_exe("mf6") @pytest.mark.parametrize("scrub", [True, False]) @pytest.mark.parametrize("use_paths", [True, False]) def test_relpath_safe(function_tmpdir, scrub, use_paths): if ( platform.system() == "Windows" and splitdrive(function_tmpdir)[0] != splitdrive(getcwd())[0] ): if use_paths: assert ( Path(relpath_safe(function_tmpdir)) == function_tmpdir.absolute() ) assert relpath_safe(Path(which("mf6"))) == str( Path(which("mf6")).absolute() ) else: assert ( Path(relpath_safe(str(function_tmpdir))) == function_tmpdir.absolute() ) assert relpath_safe(which("mf6")) == str( Path(which("mf6")).absolute() ) else: if use_paths: assert Path( relpath_safe(function_tmpdir, function_tmpdir.parent) ) == Path(function_tmpdir.name) assert ( Path( relpath_safe( function_tmpdir, function_tmpdir.parent.parent ) ) == Path(function_tmpdir.parent.name) / function_tmpdir.name ) assert relpath_safe(Path(which("mf6"))) == relpath( Path(which("mf6")), Path(getcwd()) ) else: assert Path( relpath_safe(str(function_tmpdir), str(function_tmpdir.parent)) ) == Path(function_tmpdir.name) assert ( Path( relpath_safe( str(function_tmpdir), str(function_tmpdir.parent.parent), ) ) == Path(function_tmpdir.parent.name) / function_tmpdir.name ) assert relpath_safe(which("mf6")) == relpath( which("mf6"), getcwd() ) # test user login obfuscation with set_dir("/"): try: login = os.getlogin() if use_paths: p = relpath_safe(Path.home(), scrub=scrub) else: p = relpath_safe(str(Path.home()), scrub=scrub) if login in str(Path.home()) and scrub: assert "***" in p assert login not in p except OSError: # OSError is possible in CI, e.g. 'No such device or address' pass
5593fcb9ec3b1417a331b3952f8d5f7cd229fa92
11bb0cbe6de2a0a4e94fc0ba610f61894d5593a1
/VBS_Zgamma/Significance/Invert_detajj/data_cards/th2_to_txt.py
40511394bf0a015827f544aacee6e14b17f68643
[]
no_license
AnYpku/PKU-Cluster
0dc4a88445aeb3ca239b2d7d7f796c6a67f3f69c
f9ffbcb7988053f4618fd015c1bb656d92ff51c6
refs/heads/master
2022-11-01T23:46:59.442037
2022-10-21T06:37:43
2022-10-21T06:37:43
188,202,345
0
4
null
null
null
null
UTF-8
Python
false
false
10,414
py
#!/usr/bin/env python from ROOT import gROOT, THStack, TH1D, TList, TFile import sys from math import sqrt from numpy import sum def merge_bin(th1): nbins=th1.GetNbinsX() print 'nbins', nbins th1.SetBinContent(nbins-2,th1.GetBinContent(nbins-2)+th1.GetBinContent(nbins-1)+th1.GetBinContent(nbins)) if th1.GetBinContent(nbins-2)>0: th1.SetBinError(nbins-2,sqrt(th1.GetBinError(nbins-2)*th1.GetBinError(nbins-2)+th1.GetBinError(nbins-1)*th1.GetBinError(nbins-1)+th1.GetBinError(nbins)*th1.GetBinError(nbins))) else: th1.SetBinError(nbins-2,0); print '-----begin to transfer TH2D to txt for Higgs-combine tool----- \n' fdir = '/home/pku/anying/cms/PKU-Cluster/Significance/Invert_detajj/root/' fin = TFile.Open(fdir+'hist_'+sys.argv[1]+'.root') th1_ZA_sig=fin.Get('hist_ZA-EWK'+sys.argv[1]) th1_ZA=fin.Get('hist_ZA'+sys.argv[1]) th1_non_prompt=fin.Get('hist_plj'+sys.argv[1]) th1_TTA=fin.Get('hist_TTA'+sys.argv[1]) th1_VV=fin.Get('hist_VV'+sys.argv[1]) th1_ST=fin.Get('hist_ST'+sys.argv[1]) # the bkg histo and signal histo have already contain the overflow bin in the last bin when creat the histograms genbincontent=[] genbinerror=[] arr={} f=open('/home/pku/anying/cms/PKU-Cluster/Significance/Invert_detajj/Uncer/summary_Mjj_'+sys.argv[1]+'.txt') import re import numpy as np for line in f: if not line.strip(): continue print line line = line.replace('[','') line = line.replace(']','') line = line.replace('\n','') print line arr_Temp = re.split(',|=',line) print arr_Temp name = arr_Temp[0] arr_Temp = np.array(arr_Temp[1:]) #arr_Temp.astype(np.float) arr_Temp = [float(x) for x in arr_Temp] print name arr[name]=arr_Temp print arr print '>>>>begin to read bin content to the txt file>>>>' nbins=th1_ZA_sig.GetNbinsX() print 'nbins', nbins nbins=th1_ZA_sig.GetNbinsX()+1 print 'range in for loop 1 to', nbins for i in range(1,nbins): f = open('./txt/Mjj_%s_bin%i.txt'%(sys.argv[1],i),'w') f.write('imax 1 number of channels\n') f.write('jmax 5 number of processes-1\n') if sys.argv[1].find("18") == -1 and sys.argv[1].find("17") == -1: #16 f.write('kmax * number of nuisance parameters (sources of systematical uncertainties)\n') if sys.argv[1].find("16") == -1 and sys.argv[1].find("18") == -1: #17 f.write('kmax * number of nuisance parameters (sources of systematical uncertainties)\n') if sys.argv[1].find("16") == -1 and sys.argv[1].find("17") == -1: #18 f.write('kmax * number of nuisance parameters (sources of systematical uncertainties)\n') f.write('------------\n') f.write('# we have just one channel, in which we observe 0 events\n') f.write('bin bin%i\n'%(i)) # bincontent of each precess ST_bincontent = th1_ST.GetBinContent(i) if th1_ST.GetBinContent(i)>0 else 0 TTA_bincontent = th1_TTA.GetBinContent(i) if th1_TTA.GetBinContent(i)>0 else 0 VV_bincontent = th1_VV.GetBinContent(i) if th1_VV.GetBinContent(i)>0 else 0 # WA_bincontent = th1_WA.GetBinContent(i) if th1_WA.GetBinContent(i)>0 else 0 non_prompt_bincontent = th1_non_prompt.GetBinContent(i) if th1_non_prompt.GetBinContent(i)>0 else 0 ZA_bincontent = th1_ZA.GetBinContent(i) if th1_ZA.GetBinContent(i)>0 else 0 ZA_sig_bincontent = th1_ZA_sig.GetBinContent(i) if th1_ZA_sig.GetBinContent(i)>0 else 0 # bin error ST_binerror = th1_ST.GetBinError(i)/ST_bincontent if ST_bincontent>0 else 0 ST_binerror = ST_binerror if ST_binerror<1 else 1 ST_binerror = ST_binerror+1 TTA_binerror = th1_TTA.GetBinError(i)/TTA_bincontent if TTA_bincontent>0 else 0 TTA_binerror = TTA_binerror if TTA_binerror<1 else 1 TTA_binerror = TTA_binerror+1 VV_binerror = th1_VV.GetBinError(i)/VV_bincontent if VV_bincontent>0 else 0 VV_binerror = VV_binerror if VV_binerror<1 else 1 VV_binerror = VV_binerror+1 # WA_binerror = th1_WA.GetBinError(i)/WA_bincontent if WA_bincontent>0 else 0 # WA_binerror = WA_binerror if WA_binerror<1 else 1 # WA_binerror = WA_binerror+1 non_prompt_binerror = th1_non_prompt.GetBinError(i)/non_prompt_bincontent if non_prompt_bincontent>0 else 0 non_prompt_binerror = non_prompt_binerror if non_prompt_binerror<1 else 1 non_prompt_binerror =non_prompt_binerror+1 ZA_binerror = th1_ZA.GetBinError(i)/ZA_bincontent if ZA_bincontent>0 else 0 ZA_binerror = ZA_binerror if ZA_binerror<1 else 1 ZA_binerror = ZA_binerror+1 ZA_sig_binerror = th1_ZA_sig.GetBinError(i)/ZA_sig_bincontent if ZA_sig_bincontent>0 else 0 ZA_sig_binerror = ZA_sig_binerror if ZA_sig_binerror<1 else 1 ZA_sig_binerror = ZA_sig_binerror+1 data= ZA_sig_bincontent + ZA_bincontent+non_prompt_bincontent+TTA_bincontent+VV_bincontent+ST_bincontent f.write('observation %0.2f\n'%(data)) f.write('------------\n') f.write('# now we list the expected events for signal and all backgrounds in that bin\n') f.write('# the second process line must have a positive number for backgrounds, and 0 for signal\n') f.write('# then we list the independent sources of uncertainties, and give their effect (syst. error)\n') f.write('# on each process and bin\n') f.write('bin\t') f.write('bin%i\tbin%i\tbin%i\tbin%i\tbin%i\tbin%i\n'%(i,i,i,i,i,i)) f.write('process\t') f.write('Sig\tQCD\tnon_prompt\tTTA\tVV\tST\n') f.write('process\t0\t1\t2\t3\t4\t5\n') f.write('rate\t') f.write('%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\t%0.2f\n'%(ZA_sig_bincontent,ZA_bincontent, non_prompt_bincontent, TTA_bincontent, VV_bincontent, ST_bincontent)) f.write('------------\n') f.write('lumi_%s\tlnN\t'%(sys.argv[1])) if sys.argv[1].find("17")==-1 and sys.argv[1].find("18")==-1: f.write('%0.3f\t%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\n'%(1.022,1.022,1.022,1.022,1.022)) if sys.argv[1].find("16")==-1 and sys.argv[1].find("18")==-1: f.write('%0.3f\t%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\n'%(1.02,1.02,1.02,1.02,1.02)) if sys.argv[1].find("16")==-1 and sys.argv[1].find("17")==-1: f.write('%0.3f\t%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\n'%(1.015,1.015,1.015,1.015,1.015)) f.write('VBS_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('%0.2f\t-\t-\t-\t-\t-\n'%(ZA_sig_binerror)) f.write('QCD_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('-\t%0.2f\t-\t-\t-\t-\n'%(ZA_binerror)) f.write('non_prompt_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('-\t-\t%0.2f\t-\t-\t-\n'%(non_prompt_binerror)) f.write('TTA_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('-\t-\t-\t%0.2f\t-\t-\n'%(TTA_binerror)) f.write('VV_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('-\t-\t-\t-\t%0.2f\t-\n'%(VV_binerror)) f.write('ST_Stat_bin%d_%s\tlnN\t'%(i,sys.argv[1])) f.write('-\t-\t-\t-\t-\t%0.2f\n'%(ST_binerror)) # f.write('fake_%s\tlnN\t'%(sys.argv[1])) if non_prompt_bincontent==0: f.write('-\t-\t-\t-\t-\t-\n') else: f.write('-\t-\t%0.2f\t-\t-\t-\n'%(arr['fake'+sys.argv[1]][i-1])) # f.write('JES_%s\tlnN\t'%(sys.argv[1])) f.write('%0.2f\t%0.2f\t-\t%0.2f\t%0.2f\t%0.2f\n'%(arr['jes'+sys.argv[1]+'_ZA-EWK'][i-1],arr['jes'+sys.argv[1]+'_ZA'][i-1],arr['jes'+sys.argv[1]+'_TTA'][i-1],arr['jes'+sys.argv[1]+'_VV'][i-1],arr['jes'+sys.argv[1]+'_ST'][i-1])) # f.write('JER_%s\tlnN\t'%(sys.argv[1])) f.write('%0.2f\t%0.2f\t-\t%0.2f\t%0.2f\t%0.2f\n'%(arr['jer'+sys.argv[1]+'_ZA-EWK'][i-1],arr['jer'+sys.argv[1]+'_ZA'][i-1],arr['jer'+sys.argv[1]+'_TTA'][i-1],arr['jer'+sys.argv[1]+'_VV'][i-1],arr['jer'+sys.argv[1]+'_ST'][i-1])) # f.write('pdf_EW\tlnN\t') f.write('%0.3f\t-\t-\t-\t-\t-\n'%(arr['Sig_pdf'][i-1])) # f.write('pdf_QCD\tlnN\t') f.write('-\t%0.2f\t-\t-\t-\t-\n'%(arr['QCD_pdf'][i-1])) # f.write('Scale_EW\tlnN\t') f.write('%0.2f\t-\t-\t-\t-\t-\n'%(arr['Sig_scale'][i-1])) # f.write('Scale_muF1\tlnN\t') f.write('-\t%0.3f\t-\t-\t-\t-\n'%(arr['scale_muF1'][i-1])) # f.write('Scale_muR1\tlnN\t') f.write('-\t%0.3f\t-\t-\t-\t-\n'%(arr['scale_muR1'][i-1])) # f.write('Scale_muFmuR\tlnN\t') f.write('-\t%0.3f\t-\t-\t-\t-\n'%(arr['scale_muFmuR'][i-1])) # f.write('interf\tlnN\t') f.write('%0.2f\t-\t-\t-\t-\t-\n'%(arr['interf'][i-1])) # f.write('mu_trigger\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n'%(arr['muon_ZA_trigger'][i-1],arr['muon_TTA_trigger'][i-1],arr['muon_VV_trigger'][i-1],arr['muon_ST_trigger'][i-1],arr['muon_ZA-EWK_trigger'][i-1])) # f.write('mu_eff\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n'%(arr['muon_ZA_all'][i-1],arr['muon_TTA_all'][i-1],arr['muon_VV_all'][i-1],arr['muon_ST_all'][i-1],arr['muon_VV_all'][i-1])) # f.write('ele_reco\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n'%(arr['ele_ZA_reco'][i-1],arr['ele_TTA_reco'][i-1],arr['ele_VV_reco'][i-1],arr['ele_ST_reco'][i-1],arr['ele_ZA-EWK_reco'][i-1])) # f.write('ele_ID\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n'%(arr['ele_ZA_ID'][i-1],arr['ele_TTA_ID'][i-1],arr['ele_VV_ID'][i-1],arr['ele_ST_ID'][i-1],arr['ele_ZA-EWK_ID'][i-1])) # f.write('photon_id\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n'%(arr['photon_ZA_ID'][i-1],arr['photon_TTA_ID'][i-1],arr['photon_VV_ID'][i-1],arr['photon_ST_ID'][i-1],arr['photon_ZA-EWK_ID'][i-1])) # f.write('pileup\tlnN\t') f.write('%0.3f\t-\t%0.3f\t%0.3f\t%0.3f\t%0.3f\n' %(arr['pileup_ZA'][i-1],arr['pileup_TTA'][i-1],arr['pileup_VV'][i-1],arr['pileup_ST'][i-1],arr['pileup_ZA-EWK'][i-1])) # f.write('ttgamma_xs\tlnN\t') f.write('-\t-\t-\t1.1\t-\t-\n') f.write('VV_xs\tlnN\t') f.write('-\t-\t-\t-\t1.1\t-\n') # f.write('pileupId_eff_%s\tlnN\t'%(sys.argv[1])) f.write('%0.2f\t%0.2f\t-\t%0.2f\t%0.2f\t%0.2f\n'%(arr['ZA-EWK_eff'][i-1],arr['ZA_eff'][i-1],arr['TTA_eff'][i-1],arr['VV_eff'][i-1],arr['ST_eff'][i-1])) f.write('pileupId_mis_%s\tlnN\t'%(sys.argv[1])) f.write('%0.2f\t%0.2f\t-\t%0.2f\t%0.2f\t%0.2f\n'%(arr['ZA-EWK_mis'][i-1],arr['ZA_mis'][i-1],arr['TTA_mis'][i-1],arr['VV_mis'][i-1],arr['ST_mis'][i-1])) # if sys.argv[1].find("18") == -1: f.write('l1pref\tlnN\t') f.write('%0.2f\t%0.2f\t-\t%0.2f\t%0.2f\t%0.2f\n'%(arr['l1pref_ZA'][i-1],arr['l1pref_ZA-EWK'][i-1],arr['l1pref_TTA'][i-1],arr['l1pref_VV'][i-1],arr['l1pref_ST'][i-1])) # print 'bin ',i,' ',ZA_binerror,' ',non_prompt_binerror,' ',TTA_binerror,' ',VV_binerror,' ',ST_binerror,' ',WA_binerror,' ',ZA_sig_out_binerror genbincontent[:]=[] genbinerror[:]=[]
2676c8b70cc62e532379d2c46e363e54f2d94d14
97999ecca9e50972cc9e80df27d4768d83498dba
/credentials/migrations/0008_aboutme_resume.py
0ca7767e117e9ddde7e97056617a2f2465605750
[]
no_license
apatten001/portfolio
c79312d13f7a75f909e2d4d66ab6ef275b69543e
4fdb503afccea83b849b62e3b12539e25a0b722f
refs/heads/master
2020-04-25T05:45:20.946946
2019-03-07T16:53:00
2019-03-07T16:53:00
172,554,299
0
0
null
null
null
null
UTF-8
Python
false
false
417
py
# Generated by Django 2.1.5 on 2019-02-27 19:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('credentials', '0007_auto_20190128_1630'), ] operations = [ migrations.AddField( model_name='aboutme', name='resume', field=models.FileField(default='Arnold_Resume.pdf', upload_to=''), ), ]
bf87b37a2e04bb39ba5a09c86b581bd34be15a03
cde373aef58da4226bfadee3d1a7086d22f33414
/Matplotlib/20-AddingMoreIndicatorData.py
6deebcb3c6cd32cf086b49db0aff5da22174f70c
[]
no_license
ravi4all/ML_WeekEnd_Feb
6c66c6e6845062928834986980e5c229a19da6cd
43891ff36cfcd557861b4eebb99c44c68d24954e
refs/heads/master
2021-01-09T06:10:34.007131
2017-06-12T03:57:54
2017-06-12T03:57:54
80,917,805
0
1
null
null
null
null
UTF-8
Python
false
false
3,150
py
import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mticker from matplotlib.finance import candlestick_ohlc from matplotlib import style import numpy as np import urllib import datetime as dt #style.use('ggplot') style.use('fivethirtyeight') MA1 = 10 MA2 = 30 # Will give the moving average def moving_average(values, window): weights = np.repeat(1.0, window)/window smas = np.convolve(values, weights, 'valid') return smas def high_minus_low(highs, lows): return highs-lows # fmt - format def bytespdate2num(fmt, encoding='utf-8'): strconverter = mdates.strpdate2num(fmt) def bytesconverter(b): a = b.decode(encoding) return strconverter(a) return bytesconverter def graph_data(stock): fig = plt.figure() # ax1 is a subplot ax1 = plt.subplot2grid((6,1),(0,0), rowspan=1, colspan=1) plt.title(stock) ax2 = plt.subplot2grid((6,1),(1,0), rowspan=4, colspan=1) plt.xlabel('Date') plt.ylabel('Price') ax3 = plt.subplot2grid((6,1),(5,0), rowspan=1, colspan=1) stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv' source_code = urllib.request.urlopen(stock_price_url).read().decode() stock_data = [] split_source = source_code.split('\n') for line in split_source: split_line = line.split(',') if len(split_line) == 6: if 'values' not in line and 'labels' not in line: stock_data.append(line) date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data, delimiter = ',', unpack = True, converters={0: bytespdate2num('%Y%m%d')}) x = 0 y = len(date) # OHLC : open high low close ohlc = [] while x < y: append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x] ohlc.append(append_me) x += 1 ma1 = moving_average(closep, MA1) ma2 = moving_average(closep, MA2) start = len(date[MA2-1:]) h_l = list(map(high_minus_low, highp, lowp)) ax1.plot_date(date, h_l, '-') candlestick_ohlc(ax2, ohlc, width=0.4, colorup='g', colordown='r') for label in ax2.xaxis.get_ticklabels(): label.set_rotation(45) ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) ax2.xaxis.set_major_locator(mticker.MaxNLocator(10)) ax2.grid(True) bbox_props = dict(boxstyle='larrow', fc='w', ec='k', lw=1) # to display the last price ax2.annotate(str(closep[-1]), (date[-1], closep[-1]), xytext = (date[-1]+4, closep[-1]), bbox=bbox_props) ax3.plot(date[-start:], ma1[-start:]) ax3.plot(date[-start:], ma2[-start:]) #plt.legend() plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0) plt.show() graph_data('ebay')
d3b5d2220dfd64a054fc44c58b941464e11c9a62
bb2b6422476f5bd80171a31517465f9f62e15558
/catkin_ws/build/scan_tools/laser_ortho_projector/catkin_generated/pkg.installspace.context.pc.py
a7beec3bd992862819cd8c913a124d3586a9795b
[]
no_license
Forrest-Z/MyKitAgv
ccd7b1c5fdb3a046bc5267d1827c4a08d89e74a4
db9506ad8c8a9012fb49775e188932e28526337e
refs/heads/master
2022-12-07T17:49:23.140713
2020-09-07T14:25:04
2020-09-07T14:25:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
566
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "${prefix}/include".split(';') if "${prefix}/include" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;nodelet;sensor_msgs;tf;pcl_ros;pcl_conversions;geometry_msgs;message_filters".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-llaser_ortho_projector".split(';') if "-llaser_ortho_projector" != "" else [] PROJECT_NAME = "laser_ortho_projector" PROJECT_SPACE_DIR = "/home/nhamtung/TungNV/MyKitAgv/catkin_ws/install" PROJECT_VERSION = "0.3.2"
34c9d63c64f37b6a17a2adfae7b3bb9d3677a416
0130c8b14927097663157846adc4b146d67d2fda
/tests/common/test_run/softplus_run.py
72090ba2620e11675993ae68cec770d88f6b7703
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-3-Clause", "NCSA", "LLVM-exception", "Zlib", "BSD-2-Clause", "MIT" ]
permissive
Shigangli/akg
e8be3e0ee1eafe3e42b4cc4d424c28f08ef4c0bc
3766c54e0b109541932d147a6b5643a334b82403
refs/heads/master
2023-09-06T05:13:40.571583
2021-11-23T03:44:54
2021-11-23T03:44:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,615
py
# Copyright 2020 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """run function for softplus""" import numpy as np from tests.common.tensorio import compare_tensor from akg.utils import kernel_exec as utils from tests.common.test_op import softplus from tests.common.gen_random import random_gaussian from tests.common.base import get_rtol_atol def softplus_run(shape, dtype, attrs): mod = utils.op_build_test(softplus.softplus, [shape], [dtype], kernel_name="softplus", attrs=attrs) expect, inputs, output = gen_data(dtype, shape) output = utils.mod_launch(mod, (inputs, output), expect=expect) rtol, atol = get_rtol_atol("softplus", dtype) TestCase_Result = compare_tensor( output, expect, rtol=rtol, atol=atol, equal_nan=False) return inputs, output, expect, TestCase_Result def gen_data(dtype, shape): inputs = random_gaussian(shape, miu=1, sigma=0.3).astype(dtype) expect = np.log1p(np.exp(-np.abs(inputs))) + np.maximum(inputs, 0) output = np.full(shape, np.nan, dtype) return expect, inputs, output
43a0cab3c9c839ec46266c935ecdf82958e35ef6
ba3c06f9ae89479fa4987fe841ac09b5b5d71383
/python_for_kids/book/Projects/monster6.py
a10a99ac4030b0d5d0cfab3769dc4e6741f8afab
[]
no_license
mary-tano/python-programming
6d806e25011e770a04a0922d0b71bf38c222d026
829654a3274be939fa529ed94ea568c12f7f1a27
refs/heads/master
2021-05-17T15:30:32.710838
2020-04-01T13:37:18
2020-04-01T13:37:18
250,846,188
0
0
null
null
null
null
UTF-8
Python
false
false
328
py
# Лаборатория Франкенштейна from monsterlab import * # Основная программа Frank = Monster("Фрэнки", "необычный") Frank.show() Albert = GMonster("Альберт", "задумчивый") Albert.show() Sigmund = SMonster("Зигмунд", "веселый") Sigmund.show()
db668ec99a3e918fab75689d177f3b571a030a86
8ef5a09d76a11c56963f18e6a08474a1a8bafe3c
/leet_code/7. Reverse Integer.py
79b791271388c6874618159d647c255bde2e2e06
[]
no_license
roiei/algo
32c4677649c7666db148f6183fbfbf66c8b1969f
ae8bb8bf4ae4026ccaf1dce323b4098547dd35ec
refs/heads/master
2022-04-01T19:21:27.768675
2022-02-19T06:15:29
2022-02-19T06:15:29
169,021,154
0
0
null
null
null
null
UTF-8
Python
false
false
693
py
class Solution: def reverse(self, x: 'int') -> 'int': if x > float('inf') or x < float('-inf'): return 0 sign = 1 if x < 0: sign = -1 xstr = str(x) if -1 == sign: xstr = xstr[1:] xstr = xstr[::-1] skip_cnt = 0 for ch in xstr: if ch != '0': break skip_cnt += 1 res = xstr[skip_cnt:] if '' == res: return 0 if -1 == sign: res = '-' + res return int(res) x = 123 #x = -123 #x = 120 #x = 901000 x = 1534236469 # 0 sol = Solution() print(sol.reverse(x))
1d49c638c84d9cfa20e25fd85489966f882c7123
bfda3af75d94767a5cb265bd68c17cfbf94e3ee1
/rosalind/qrt/rosalind_qrtd_tung.py
c6d0de60e3be4d40377362c4f3b26bdba3ad70ce
[]
no_license
orenlivne/euler
d0e5b956a46eacfe423fbd6c52918beb91eea140
2afdd8bccdc5789c233e955b1ca626cea618eb9b
refs/heads/master
2020-12-29T02:24:36.479708
2016-12-15T21:27:33
2016-12-15T21:27:33
20,263,482
1
1
null
null
null
null
UTF-8
Python
false
false
4,129
py
''' ============================================================ http://rosalind.info/problems/qrtd Given: A list containing n taxa (n<=2000) and two unrooted binary trees T1 and T2 on the given taxa. Both T1 and T2 are given in Newick format. Return: The quartet distance dq(T1,T2). ============================================================ ''' # From http://rosalind.info/problems/qrtd/solutions/. # Need to get the rest of his libraries import time from rosalind import rostree def qrtd(fp): taxa = next(fp).split() t1_str = next(fp) t2_str = next(fp) taxa_id = dict((s,i) for i, s in enumerate(taxa)) all_taxa = set(xrange(len(taxa))) start_time = time.time() def build_tree(t_str): T = rostree.read_newick_str(t_str) #T = make_unrooted_binary(T) for node in T.walk(order=T.POSTORDER): if node.is_leaf: node.id = taxa_id[node.val] node.nodes = set([node.id]) node.rest = all_taxa - node.nodes else: node.nodes = reduce(set.union, map(attrgetter('nodes'), node.children), set()) node.rest = all_taxa - node.nodes # special case to walk unroot tree; the first node is also a leaf node T.id = taxa_id[T.val] T.nodes = set([T.id]) T.rest = all_taxa - T.nodes return T T1 = build_tree(t1_str) T2 = build_tree(t2_str) # link T2 nodes to T1. Mind the special case for root node. id_2_T1 = dict((node.id,node) for node in T1.walk(type=T1.LEAF)) id_2_T1[T1.id] = T1 for node in T2.walk(type=T1.LEAF): node.t1_node = id_2_T1[node.id] T2.t1_node = id_2_T1[T2.id] N = len(taxa) print 'N=',N count = 0 for i, v1 in enumerate(T1.walk(type=T1.INODE)): if v1 is T1: continue if i % 10 == 0: print 'T1 %3d %s' % (time.time() - start_time, i) for A_node in T1.walk(exclude_node=v1): A_node.color = 1 for B_node in v1.left.walk(): B_node.color = 2 for C_node in v1.right.walk(): C_node.color = 3 A1 = v1.rest B1 = v1.left.nodes C1 = v1.right.nodes for v2 in T2.walk(order=T2.POSTORDER): if v2 is T2: pass elif v2.is_leaf: v2.a1 = 0 v2.b1 = 0 v2.c1 = 0 c = v2.t1_node.color if c == 1: v2.a1 = 1 elif c == 2: v2.b1 = 1 else: v2.c1 = 1 else: B = v2.left C = v2.right a1b2 = B.a1 a1c2 = C.a1 a1a2 = len(A1) - a1b2 - a1c2 b1b2 = B.b1 b1c2 = C.b1 b1a2 = len(B1) - b1b2 - b1c2 c1b2 = B.c1 c1c2 = C.c1 c1a2 = len(C1) - c1b2 - c1c2 # rememeber under v2, how many of them intersect with A1, B1 and C1 v2.a1 = a1b2 + a1c2 v2.b1 = b1b2 + b1c2 v2.c1 = c1b2 + c1c2 # 3x3=9 different orientation for T12 and T2, # times in each case two ways to pair B and C from each tree count += a1a2 * (a1a2-1) / 2 * (b1b2 * c1c2 + b1c2 * c1b2) count += a1b2 * (a1b2-1) / 2 * (b1a2 * c1c2 + b1c2 * c1a2) count += a1c2 * (a1c2-1) / 2 * (b1a2 * c1b2 + b1b2 * c1a2) count += b1a2 * (b1a2-1) / 2 * (a1b2 * c1c2 + a1c2 * c1b2) count += b1b2 * (b1b2-1) / 2 * (a1a2 * c1c2 + a1c2 * c1a2) count += b1c2 * (b1c2-1) / 2 * (a1a2 * c1b2 + a1b2 * c1a2) count += c1a2 * (c1a2-1) / 2 * (a1b2 * b1c2 + a1c2 * b1b2) count += c1b2 * (c1b2-1) / 2 * (a1a2 * b1c2 + a1c2 * b1a2) count += c1c2 * (c1c2-1) / 2 * (a1a2 * b1b2 + a1b2 * b1a2) print N * (N - 1) * (N- 2) * (N - 3) / 12 - count if __name__ == "__main__": print qrtd('rosalind_qrtd_sample.dat') #print qrtd('rosalind_qrtd.dat')
710bcc0fb5dcc70b3aacdae1595043478681cdb2
02560440f9f91e583fe98d80ab11e18aa6c7a525
/apps/usuarios/migrations/0003_usuario_correo.py
ad084ca9dc73a72604d08e401a8af1a08f618f45
[]
no_license
eduardogpg/wamadeusV1
a36c89176543e638486009620c5131f46743edbc
82d93293dc6afc95a6661f727162f4055ab83a43
refs/heads/master
2020-12-28T01:57:47.831689
2015-01-08T05:14:25
2015-01-08T05:14:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
452
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('usuarios', '0002_auto_20141215_1710'), ] operations = [ migrations.AddField( model_name='usuario', name='correo', field=models.EmailField(default=' ', max_length=50), preserve_default=False, ), ]
58e06984a80bfb1f133e9e4eee18958f1fe78fb2
0f5bdddfb93154d7f3cf097ede0a8c9ac403e027
/tests/test_rtcrtpreceiver.py
cb6865f41e23a94d28ffbaf0933d26f08ec809e6
[ "BSD-3-Clause" ]
permissive
pslq/aiortc
13061885fc06eef42a05a0d8ad6eb3a3708873a3
b27b27d3509c2a8335aadd949511b24b93530d86
refs/heads/master
2020-03-27T02:17:50.118454
2018-08-22T16:44:03
2018-08-22T17:58:11
145,780,077
1
0
null
2018-08-23T00:54:52
2018-08-23T00:54:52
null
UTF-8
Python
false
false
9,343
py
import asyncio from unittest import TestCase from unittest.mock import patch from aiortc.codecs import PCMU_CODEC from aiortc.exceptions import InvalidStateError from aiortc.mediastreams import AudioFrame from aiortc.rtcrtpparameters import RTCRtpCodecParameters, RTCRtpParameters from aiortc.rtcrtpreceiver import (NackGenerator, RemoteStreamTrack, RTCRtpReceiver, StreamStatistics) from aiortc.rtp import RTP_SEQ_MODULO, RtcpPacket, RtpPacket from aiortc.stats import RTCStatsReport from .utils import dummy_dtls_transport_pair, load, run def create_rtp_packets(count, seq=0): packets = [] for i in range(count): packets.append(RtpPacket( payload_type=0, sequence_number=(seq + i) % RTP_SEQ_MODULO, ssrc=1234, timestamp=i * 160)) return packets class ClosedDtlsTransport: state = 'closed' class NackGeneratorTest(TestCase): def create_generator(self): class FakeReceiver: def __init__(self): self.nack = [] self.pli = [] async def _send_rtcp_nack(self, media_ssrc, lost): self.nack.append((media_ssrc, lost)) async def _send_rtcp_pli(self, media_ssrc, lost): self.pli.append(media_ssrc) receiver = FakeReceiver() return NackGenerator(receiver), receiver def test_no_loss(self): generator, receiver = self.create_generator() for packet in create_rtp_packets(20, 0): run(generator.add(packet)) self.assertEqual(receiver.nack, []) self.assertEqual(receiver.pli, []) self.assertEqual(generator.missing, set()) def test_with_loss(self): generator, receiver = self.create_generator() # receive packets: 0, <1 missing>, 2 packets = create_rtp_packets(3, 0) missing = packets.pop(1) for packet in packets: run(generator.add(packet)) self.assertEqual(receiver.nack, [(1234, [1])]) self.assertEqual(receiver.pli, []) self.assertEqual(generator.missing, set([1])) receiver.nack.clear() # late arrival run(generator.add(missing)) self.assertEqual(receiver.nack, []) self.assertEqual(receiver.pli, []) self.assertEqual(generator.missing, set()) class StreamStatisticsTest(TestCase): def create_counter(self): return StreamStatistics(clockrate=8000, ssrc=0) def test_no_loss(self): counter = self.create_counter() packets = create_rtp_packets(20, 0) # receive 10 packets for packet in packets[0:10]: counter.add(packet) self.assertEqual(counter.max_seq, 9) self.assertEqual(counter.packets_received, 10) self.assertEqual(counter.packets_lost, 0) self.assertEqual(counter.fraction_lost, 0) # receive 10 more packets for packet in packets[10:20]: counter.add(packet) self.assertEqual(counter.max_seq, 19) self.assertEqual(counter.packets_received, 20) self.assertEqual(counter.packets_lost, 0) self.assertEqual(counter.fraction_lost, 0) def test_no_loss_cycle(self): counter = self.create_counter() # receive 10 packets (with sequence cycle) for packet in create_rtp_packets(10, 65530): counter.add(packet) self.assertEqual(counter.max_seq, 3) self.assertEqual(counter.packets_received, 10) self.assertEqual(counter.packets_lost, 0) self.assertEqual(counter.fraction_lost, 0) def test_with_loss(self): counter = self.create_counter() packets = create_rtp_packets(20, 0) packets.pop(1) # receive 9 packets (one missing) for packet in packets[0:9]: counter.add(packet) self.assertEqual(counter.max_seq, 9) self.assertEqual(counter.packets_received, 9) self.assertEqual(counter.packets_lost, 1) self.assertEqual(counter.fraction_lost, 25) # receive 10 more packets for packet in packets[9:19]: counter.add(packet) self.assertEqual(counter.max_seq, 19) self.assertEqual(counter.packets_received, 19) self.assertEqual(counter.packets_lost, 1) self.assertEqual(counter.fraction_lost, 0) @patch('time.time') def test_no_jitter(self, mock_time): counter = self.create_counter() packets = create_rtp_packets(3, 0) mock_time.return_value = 1531562330.00 counter.add(packets[0]) self.assertEqual(counter._jitter_q4, 0) self.assertEqual(counter.jitter, 0) mock_time.return_value = 1531562330.02 counter.add(packets[1]) self.assertEqual(counter._jitter_q4, 0) self.assertEqual(counter.jitter, 0) mock_time.return_value = 1531562330.04 counter.add(packets[2]) self.assertEqual(counter._jitter_q4, 0) self.assertEqual(counter.jitter, 0) @patch('time.time') def test_with_jitter(self, mock_time): counter = self.create_counter() packets = create_rtp_packets(3, 0) mock_time.return_value = 1531562330.00 counter.add(packets[0]) self.assertEqual(counter._jitter_q4, 0) self.assertEqual(counter.jitter, 0) mock_time.return_value = 1531562330.03 counter.add(packets[1]) self.assertEqual(counter._jitter_q4, 80) self.assertEqual(counter.jitter, 5) mock_time.return_value = 1531562330.05 counter.add(packets[2]) self.assertEqual(counter._jitter_q4, 75) self.assertEqual(counter.jitter, 4) class RTCRtpReceiverTest(TestCase): def test_connection_error(self): """ Close the underlying transport before the receiver. """ transport, _ = dummy_dtls_transport_pair() receiver = RTCRtpReceiver('audio', transport) self.assertEqual(receiver.transport, transport) receiver._track = RemoteStreamTrack(kind='audio') receiver._ssrc = 1234 run(receiver.receive(RTCRtpParameters(codecs=[PCMU_CODEC]))) # receive a packet to prime RTCP packet = RtpPacket.parse(load('rtp.bin')) run(receiver._handle_rtp_packet(packet)) # break connection run(transport.close()) # give RTCP time to send a report run(asyncio.sleep(2)) # shutdown run(receiver.stop()) def test_rtp_and_rtcp(self): transport, remote = dummy_dtls_transport_pair() receiver = RTCRtpReceiver('audio', transport) self.assertEqual(receiver.transport, transport) receiver._track = RemoteStreamTrack(kind='audio') run(receiver.receive(RTCRtpParameters(codecs=[PCMU_CODEC]))) # receive RTP packet = RtpPacket.parse(load('rtp.bin')) run(receiver._handle_rtp_packet(packet)) # receive RTCP SR for packet in RtcpPacket.parse(load('rtcp_sr.bin')): run(receiver._handle_rtcp_packet(packet)) # check stats report = run(receiver.getStats()) self.assertTrue(isinstance(report, RTCStatsReport)) self.assertEqual(sorted(report.keys()), ['inbound-rtp', 'remote-outbound-rtp']) # check remote track frame = run(receiver._track.recv()) self.assertTrue(isinstance(frame, AudioFrame)) # shutdown run(receiver.stop()) def test_rtp_empty_video_packet(self): transport, remote = dummy_dtls_transport_pair() receiver = RTCRtpReceiver('video', transport) self.assertEqual(receiver.transport, transport) receiver._track = RemoteStreamTrack(kind='video') run(receiver.receive(RTCRtpParameters(codecs=[ RTCRtpCodecParameters(name='VP8', clockRate=90000, payloadType=100), ]))) # receive RTP with empty payload packet = RtpPacket(payload_type=100) run(receiver._handle_rtp_packet(packet)) # shutdown run(receiver.stop()) def test_send_rtcp_nack(self): transport, remote = dummy_dtls_transport_pair() receiver = RTCRtpReceiver('video', transport) receiver._ssrc = 1234 receiver._track = RemoteStreamTrack(kind='video') run(receiver.receive(RTCRtpParameters(codecs=[ RTCRtpCodecParameters(name='VP8', clockRate=90000, payloadType=100), ]))) # send RTCP feedback NACK run(receiver._send_rtcp_nack(5678, [7654])) # shutdown run(receiver.stop()) def test_send_rtcp_pli(self): transport, remote = dummy_dtls_transport_pair() receiver = RTCRtpReceiver('video', transport) receiver._ssrc = 1234 receiver._track = RemoteStreamTrack(kind='video') run(receiver.receive(RTCRtpParameters(codecs=[ RTCRtpCodecParameters(name='VP8', clockRate=90000, payloadType=100), ]))) # send RTCP feedback PLI run(receiver._send_rtcp_pli(5678)) # shutdown run(receiver.stop()) def test_invalid_dtls_transport_state(self): dtlsTransport = ClosedDtlsTransport() with self.assertRaises(InvalidStateError): RTCRtpReceiver('audio', dtlsTransport)
48067e4ceef655c896f3a35b0571079df7c10a52
97a4d29863d1ce96f366554fdd985c3ce580bb5d
/061.py
f14890c43a1e22228adf9d4732a5d4ba2c6c44f6
[]
no_license
Everfighting/Python-Algorithms
5c3a102fed3a29858f3112d657c69e077efc7e28
235e9b4c66602035be39a8d3b3ad9cf016aebbb9
refs/heads/master
2021-01-20T22:19:18.902687
2018-03-02T05:38:27
2018-03-02T05:38:27
61,302,323
2
0
null
null
null
null
UTF-8
Python
false
false
679
py
#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': a = [] for i in range(10): a.append([]) #创建十行 for j in range(10): a[i].append(0) #每行创建i列 # 杨辉三角边界都为1 for i in range(10): a[i][0] = 1 a[i][i] = 1 # 杨辉三角定义,下一行数值为上一行数与上一行前面数之和(除边界) for i in range(2,10): for j in range(1,i): a[i][j] = a[i - 1][j-1] + a[i - 1][j] from sys import stdout for i in range(10): for j in range(i + 1): stdout.write(str(a[i][j])) stdout.write(' ') print
e1bf319ac4b1a93b08f0dafc5fd453b9cd95d5b1
4e44974b9e59dfd4324d84b12b10f008117814cd
/test_autofit/integration/src/dataset/dataset.py
c3dc9773c00b8b4cc97f43fc249734b1546be650
[ "MIT" ]
permissive
PriyatamNayak/PyAutoFit
2cc2608943f8c3bdbda3b268142e7307014ccaf2
32c0c30acd219030c86a12db82ae54e406fd7119
refs/heads/master
2023-03-04T07:27:41.547966
2021-02-11T23:21:00
2021-02-11T23:21:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,487
py
from astropy.io import fits import numpy as np # The 'dataset.py' module has been extended to give the dataset a name and metadata. class Dataset: def __init__(self, data, noise_map, name=None): """A class containing the data and noise-map of a 1D line dataset. Parameters ---------- data : np.ndarray The array of the data, in arbitrary units. noise_map : np.ndarray An array describing the RMS standard deviation error in each data pixel, in arbitrary units. """ self.data = data self.noise_map = noise_map # The name of the dataset is used by the aggregator, to determine the name of the file the dataset is saved as # and so that when using the aggregator you can know which dataset you are manipulating. self.name = name if name is str else "dataset" @property def xvalues(self): return np.arange(self.data.shape[0]) @classmethod def from_fits(cls, data_path, noise_map_path, name=None): """Load the data and noise-map of a 1D line dataset from ``.fits`` files. Parameters ---------- data_path : str The path on your hard-disk to the ``.fits`` file of the data. noise_map_path : str The path on your hard-disk to the ``.fits`` file of the noise-map. """ data_hdu_list = fits.open(data_path) noise_map_hdu_list = fits.open(noise_map_path) data = np.array(data_hdu_list[0].data) noise_map = np.array(noise_map_hdu_list[0].data) return Dataset(data=data, noise_map=noise_map, name=name) class MaskedDataset: def __init__(self, dataset, mask): """ A masked dataset, which is an image, noise-map and mask. Parameters ---------- dataset: im.Dataset The dataset (the image, noise-map, etc.) mask: msk.Mask2D The 1D mask that is applied to the dataset. """ self.dataset = dataset self.mask = mask self.data = dataset.data * np.invert(mask) self.noise_map = dataset.noise_map * np.invert(mask) @property def xvalues(self): return np.arange(self.data.shape[0]) def signal_to_noise_map(self): return self.data / self.noise_map def with_left_trimmed(self, data_trim_left): if data_trim_left is None: return self # Here, we use the existing masked dataset to create a trimmed dataset. data_trimmed = self.dataset.data[data_trim_left:] noise_map_trimmed = self.dataset.noise_map[data_trim_left:] dataset_trimmed = Dataset(data=data_trimmed, noise_map=noise_map_trimmed) mask_trimmed = self.mask[data_trim_left:] return MaskedDataset(dataset=dataset_trimmed, mask=mask_trimmed) def with_right_trimmed(self, data_trim_right): if data_trim_right is None: return self # We do the same as above, but removing data to the right. data_trimmed = self.dataset.data[:-data_trim_right] noise_map_trimmed = self.dataset.noise_map[:-data_trim_right] dataset_trimmed = Dataset(data=data_trimmed, noise_map=noise_map_trimmed) mask_trimmed = self.mask[:-data_trim_right] return MaskedDataset(dataset=dataset_trimmed, mask=mask_trimmed)
3a59b6324f48032a8c58f34957ffbed79c1fcb08
72f2f37c3c33e5bc02ec6c707a7c858d7990db3a
/examples/tour_examples/driverjs_maps_tour.py
33fb342608c1c2cd08a48da9c5a1aab3f8ac71a0
[ "MIT" ]
permissive
matthewxuda/SeleniumBase
190e4917dec8c731f17fd9d6a1247f8c17086d0c
efd282a860206dad81d0d4e61a472138eb04328d
refs/heads/master
2023-09-01T09:17:57.608760
2021-10-21T02:48:32
2021-10-21T02:48:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,129
py
from seleniumbase import BaseCase class MyTestClass(BaseCase): def test_create_tour(self): self.open("https://www.google.com/maps/@42.3591234,-71.0915634,15z") self.wait_for_element("#searchboxinput", timeout=20) self.wait_for_element("#minimap", timeout=20) self.wait_for_element("#zoom", timeout=20) # Create a website tour using the DriverJS library # Same as: self.create_driverjs_tour() self.create_tour(theme="driverjs") self.add_tour_step( "🗺️ Welcome to Google Maps 🗺️", "html", title="✅ SeleniumBase Tours 🌎", ) self.add_tour_step( "You can type a location into this Search box.", "#searchboxinput" ) self.add_tour_step( "Then click here to view it on the map.", "#searchbox-searchbutton", alignment="bottom", ) self.add_tour_step( "Or click here to get driving directions.", "#searchbox-directions", alignment="bottom", ) self.add_tour_step( "Use this button to get a Satellite view.", "div.widget-minimap-shim", alignment="right", ) self.add_tour_step( "Click here to zoom in.", "#widget-zoom-in", alignment="left" ) self.add_tour_step( "Or click here to zoom out.", "#widget-zoom-out", alignment="left" ) self.add_tour_step( "Use the Menu button for more options.", ".searchbox-hamburger-container", alignment="right", ) self.add_tour_step( "Or click here to see more Google apps.", '[title="Google apps"]', alignment="left", ) self.add_tour_step( "Thanks for using SeleniumBase Tours", "html", title="🚃 End of Guided Tour 🚃", ) self.export_tour() # The default name for exports is "my_tour.js" self.play_tour(interval=0) # If interval > 0, autoplay after N seconds
c216efa4d1718ae2ddfb65ef0d24f2825156d9ab
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03455/s808955934.py
5a703a489b980a233dbc16c583c6ec0ff1dc188d
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
102
py
# ABC 086 A,B= map(int,input().split()) if (A* B)%2==0: ans ='Even' else: ans='Odd' print(ans)
f5e3f313c4584c8f5380fa9186122cf9b6227947
4cda6686b659c0bf34213a4c5faf050c4c866eea
/ExperimentSpecificCode/_2018_2019_Neuroseeker_Paper/_2019_Neuroseeker_Paper_Expanded/_33p1/NeuropixelSim/Sparce/spikesort_and_timelock_analysis.py
841c428d900ac79f30a6bfcc8d9155a019730e56
[]
no_license
georgedimitriadis/themeaningofbrain
da99efcf62af67bc6c2a71e504765026a4491217
f138cf500a3ca6c8d76613c942787d9f073d67a7
refs/heads/master
2023-02-21T10:52:18.771691
2023-02-17T08:23:09
2023-02-17T08:23:09
50,346,965
3
1
null
2017-06-17T16:29:47
2016-01-25T11:42:43
Python
UTF-8
Python
false
false
12,478
py
""" The pipeline for spikesorting this dataset """ import numpy as np from os.path import join import matplotlib.pyplot as plt import pandas as pd from sklearn import preprocessing as preproc from BrainDataAnalysis.Spike_Sorting import positions_on_probe as spp from spikesorting_tsne_guis import clean_kilosort_templates as clean from spikesorting_tsne import preprocessing_kilosort_results as preproc_kilo from ExperimentSpecificCode._2018_2019_Neuroseeker_Paper._2019_Neuroseeker_Paper_Expanded._33p1 \ import constants_33p1 as const_rat from ExperimentSpecificCode._2018_2019_Neuroseeker_Paper._2019_Neuroseeker_Paper_Expanded \ import constants_common as const_com import BrainDataAnalysis.neuroseeker_specific_functions as ns_funcs from ExperimentSpecificCode._2018_Chronic_Neuroseeker_TouchingLight.Common_functions import events_sync_funcs as \ sync_funcs, firing_rates_sync_around_events_funcs as fr_funcs from BrainDataAnalysis.Statistics import binning import common_data_transforms as cdt import sequence_viewer as sv import slider as sl # ---------------------------------------------------------------------------------------------------------------------- # <editor-fold desc = "FOLDERS NAMES" date = 1 binary_data_filename = join(const_rat.base_save_folder, const_rat.rat_folder, const_rat.date_folders[date], 'Analysis', 'Denoised', 'Data', 'Amplifier_APs_Denoised.bin') analysis_folder = join(const_rat.base_save_folder, const_rat.rat_folder, const_rat.date_folders[date], 'Analysis', 'NeuropixelSimulations', 'Sparce') kilosort_folder = join(analysis_folder, 'Kilosort') data_folder = join(const_rat.base_save_folder, const_rat.rat_folder, const_rat.date_folders[date], 'Data') events_folder = join(data_folder, "events") event_dataframes = ns_funcs.load_events_dataframes(events_folder, sync_funcs.event_types) results_folder = join(analysis_folder, 'Results') events_definitions_folder = join(results_folder, 'EventsDefinitions') sampling_freq = const_com.SAMPLING_FREQUENCY # </editor-fold> # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # STEP 1: RUN KILOSORT ON THE DATA # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # <editor-fold desc = "STEP 2: CLEAN SPIKESORT (RIGHT AFTER KILOSORT)" # a) Create average of templates: # To create averages of templates use cmd (because the create_data_cubes doesn't work when called from a REPL): # Go to where the create_data_cubes.py is (in spikesort_tsne_guis/spikesort_tsen_guis) and run the following python command # (you can use either the raw or the denoised data to create the average) # python E:\Software\Develop\Source\Repos\spikesorting_tsne_guis\spikesorting_tsne_guis\create_data_cubes.py # original # "D:\\AK_33.1\2018_04_30-11_38\Analysis\NeuropixelSimulations\Sparce\Kilosort" # "D:\\AK_33.1\2018_04_30-11_38\Analysis\Denoised\Data\Amplifier_APs_Denoised.bin" # 1368 # 50 # (Use single space between parameters, not Enter like here) # (Change the folders as appropriate for where the data is) # b) Clean: clean.cleanup_kilosorted_data(kilosort_folder, number_of_channels_in_binary_file=const_com.NUMBER_OF_AP_CHANNELS_IN_BINARY_FILE, binary_data_filename=binary_data_filename, prb_file=const_com.prb_file, type_of_binary=const_com.BINARY_FILE_ENCODING, order_of_binary='F', sampling_frequency=20000, num_of_shanks_for_vis=5) # c) Remove some types template_marking = np.load(join(kilosort_folder, 'template_marking.npy')) print(len(np.argwhere(template_marking == 0))) print(len(np.argwhere(template_marking == 1))) print(len(np.argwhere(template_marking == 2))) print(len(np.argwhere(template_marking == 3))) print(len(np.argwhere(template_marking == 4))) print(len(np.argwhere(template_marking == 5))) print(len(np.argwhere(template_marking == 6))) print(len(np.argwhere(template_marking == 7))) template_marking[np.argwhere(template_marking == 5)] = 0 template_marking[np.argwhere(template_marking == 6)] = 0 np.save(join(kilosort_folder, 'template_marking.npy'), template_marking) # </editor-fold> # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # <editor-fold desc = "STEP 3: CREATE TEMPLATE INFO OF ALL THE CLEANED TEMPLATES" # a) Create the positions of the templates on the probe (and have a look) _ = spp.generate_probe_positions_of_templates(kilosort_folder) bad_channel_positions = spp.get_y_spread_regions_of_bad_channel_groups(kilosort_folder, const_rat.bad_channels) spp.view_grouped_templates_positions(kilosort_folder, const_rat.BRAIN_REGIONS, const_com.PROBE_DIMENSIONS, const_com.POSITION_MULT) # b) Create the template_info.df dataframe (or load it if you already have it) # template_info = preproc_kilo.generate_template_info_after_cleaning(kilosort_folder, sampling_freq) template_info = np.load(join(kilosort_folder, 'template_info.df'), allow_pickle=True) # c) Make the spike info from the initial, cleaned, kilosort results # spike_info = preproc_kilo.generate_spike_info_after_cleaning(kilosort_folder) spike_info = np.load(join(kilosort_folder, 'spike_info_after_cleaning.df'), allow_pickle=True) spp.view_grouped_templates_positions(kilosort_folder, const_rat.BRAIN_REGIONS, const_com.PROBE_DIMENSIONS, const_com.POSITION_MULT, template_info=template_info) # </editor-fold> # ---------------------------------------------------------------------------------------------------------------------- # ---------------------------------------------------------------------------------------------------------------------- # <editor-fold desc = "CALCULATE SPIKING RATES"> # Make the spike rates using each frame as a binning window # Load the pre generated DataFrames for the event CSVs event_dataframes = ns_funcs.load_events_dataframes(events_folder, sync_funcs.event_types) file_to_save_to = join(kilosort_folder, 'firing_rate_with_video_frame_window.npy') template_info = pd.read_pickle(join(kilosort_folder, 'template_info.df')) spike_info = pd.read_pickle(join(kilosort_folder, 'spike_info_after_cleaning.df')) spike_rates = binning.spike_count_per_frame(template_info, spike_info, event_dataframes['ev_video'], sampling_freq, file_to_save_to=file_to_save_to) # Using the frame based spikes rates do a rolling window to average a bit more num_of_frames_to_average = 0.25/(1/120) spike_rates_0p25 = [] for n in np.arange(spike_rates.shape[0]): spike_rates_0p25.append(binning.rolling_window_with_step(spike_rates[n, :], np.mean, num_of_frames_to_average, num_of_frames_to_average)) spike_rates_0p25 = np.array(spike_rates_0p25) np.save(join(kilosort_folder, 'firing_rate_with_0p25s_window.npy'), spike_rates_0p25) # </editor-fold> # ---------------------------------------------------------------------------------------------------------------------- # ------------------------------------------------- # <editor-fold desc="GET TIMES AND FRAMES OF SUCCESSFUL TRIALS"> video_frame_spike_rates_filename = join(kilosort_folder, 'firing_rate_with_video_frame_window.npy') spike_rates = np.load(video_frame_spike_rates_filename) camera_pulses, beam_breaks, sounds = \ sync_funcs.get_time_points_of_events_in_sync_file(data_folder, clean=True, cam_ttl_pulse_period= const_com.CAMERA_TTL_PULSES_TIMEPOINT_PERIOD) sounds_dur = sounds[:, 1] - sounds[:, 0] reward_sounds = sounds[sounds_dur < 4000] # Using the trialend csv file to generate events # succesful_trials = event_dataframes['ev_trial_end'][event_dataframes['ev_trial_end']['Result'] == 'Food'] # succesful_trials = succesful_trials['AmpTimePoints'].values # Using the start of the reward tone to generate events # There is a difference of 78.6 frames (+-2) between the reward tone and the csv file event (about 700ms) succesful_trials = reward_sounds[:, 0] # Get the average firing rates of all neurons a few seconds around the successful pokes time_around_beam_break = 8 avg_firing_rate_around_suc_trials = fr_funcs.get_avg_firing_rates_around_events(spike_rates=spike_rates, event_time_points=succesful_trials, ev_video_df=event_dataframes['ev_video'], time_around_event=time_around_beam_break) events_random = np.random.choice(np.arange(succesful_trials.min(), succesful_trials.max(), 100), len(succesful_trials), replace=False) avg_firing_rate_around_random_times = fr_funcs.get_avg_firing_rates_around_events(spike_rates=spike_rates, event_time_points=events_random, ev_video_df=event_dataframes['ev_video'], time_around_event=time_around_beam_break) # </editor-fold> # ---------------------------------------------------------------------------------------------------------------------- # <editor-fold desc="LOOK AT ALL THE NEURONS AROUND THE POKE EVENT"> smooth_time = 0.5 smooth_frames = smooth_time * 120 t = binning.rolling_window_with_step(avg_firing_rate_around_random_times, np.mean, smooth_frames, int(smooth_frames / 3)) tn = preproc.normalize(t, norm='l1', axis=0) tn = np.asarray(t) for i in np.arange(len(t)): tn[i, :] = binning.scale(t[i], 0, 1) y_positions = template_info['position Y'].values position_sorted_indices = np.argsort(y_positions) regions_pos = list(const_rat.BRAIN_REGIONS.values()) region_lines = [] for rp in regions_pos: region_lines.append(sync_funcs.find_nearest(y_positions[position_sorted_indices] * const_com.POSITION_MULT, rp)[0]) region_lines = np.array(region_lines) tns = tn[position_sorted_indices] plt.imshow(np.flipud(tns), aspect='auto') plt.hlines(y=len(t) - region_lines, xmin=0, xmax=len(tns[0])-1, linewidth=3, color='w') plt.vlines(x=int(len(tns[0]) / 2), ymin=0, ymax=len(tns) - 1) plt.imshow(np.flipud(tns), aspect='auto', extent=[-8, 8, len(tns), 0]) plt.hlines(y=len(t) - region_lines, xmin=-8, xmax=8, linewidth=2, color='w') plt.vlines(x=0, ymin=0, ymax=len(tns) - 1) i = 0 sv.graph_pane(globals(), 'i', 'tn') time_around_beam_break = 8 index = 0 fig1 = plt.figure(1) fig2 = plt.figure(2) output = None all_indices = np.arange(len(avg_firing_rate_around_suc_trials)) frames_around_beam_break = 120 *time_around_beam_break args = [all_indices, avg_firing_rate_around_suc_trials, template_info, spike_info, succesful_trials, frames_around_beam_break, fig1, fig2] show_rasters_decrease = fr_funcs.show_rasters_for_live_update sl.connect_repl_var(globals(), 'index', 'output', 'show_rasters_decrease', 'args', slider_limits=[0, len(avg_firing_rate_around_suc_trials) - 1]) # </editor-fold> # ----------------------------------------------------------------------------------------------------------------------
edc117b558873902ee1d38b226f7af11cebc80c9
58df99d96af6a688852993e38da89b75fea1d0dc
/exps/NATS-Bench/draw-correlations.py
6afac3b804703bc53660e618d2c2a6e820974d3e
[ "MIT" ]
permissive
yuezhixiong/AutoDL-Projects
0f24ed98389b70f452a79c8ef825d5e563ac5d8c
0d3c63bdbe2d648c2119ffe8d0491f8a07cf85cb
refs/heads/master
2023-03-22T17:15:37.013837
2021-03-02T05:13:51
2021-03-02T05:13:51
315,518,182
0
1
MIT
2021-02-26T06:36:34
2020-11-24T04:28:29
Python
UTF-8
Python
false
false
3,860
py
############################################################### # NATS-Bench (arxiv.org/pdf/2009.00437.pdf), IEEE TPAMI 2021 # ############################################################### # Copyright (c) Xuanyi Dong [GitHub D-X-Y], 2020.06 # ############################################################### # Usage: python exps/NATS-Bench/draw-correlations.py # ############################################################### import os, gc, sys, time, scipy, torch, argparse import numpy as np from typing import List, Text, Dict, Any from shutil import copyfile from collections import defaultdict, OrderedDict from copy import deepcopy from pathlib import Path import matplotlib import seaborn as sns matplotlib.use('agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker lib_dir = (Path(__file__).parent / '..' / '..' / 'lib').resolve() if str(lib_dir) not in sys.path: sys.path.insert(0, str(lib_dir)) from config_utils import dict2config, load_config from nats_bench import create from log_utils import time_string def get_valid_test_acc(api, arch, dataset): is_size_space = api.search_space_name == 'size' if dataset == 'cifar10': xinfo = api.get_more_info(arch, dataset=dataset, hp=90 if is_size_space else 200, is_random=False) test_acc = xinfo['test-accuracy'] xinfo = api.get_more_info(arch, dataset='cifar10-valid', hp=90 if is_size_space else 200, is_random=False) valid_acc = xinfo['valid-accuracy'] else: xinfo = api.get_more_info(arch, dataset=dataset, hp=90 if is_size_space else 200, is_random=False) valid_acc = xinfo['valid-accuracy'] test_acc = xinfo['test-accuracy'] return valid_acc, test_acc, 'validation = {:.2f}, test = {:.2f}\n'.format(valid_acc, test_acc) def compute_kendalltau(vectori, vectorj): # indexes = list(range(len(vectori))) # rank_1 = sorted(indexes, key=lambda i: vectori[i]) # rank_2 = sorted(indexes, key=lambda i: vectorj[i]) # import pdb; pdb.set_trace() coef, p = scipy.stats.kendalltau(vectori, vectorj) return coef def compute_spearmanr(vectori, vectorj): coef, p = scipy.stats.spearmanr(vectori, vectorj) return coef if __name__ == '__main__': parser = argparse.ArgumentParser(description='NATS-Bench: Benchmarking NAS Algorithms for Architecture Topology and Size', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--save_dir', type=str, default='output/vis-nas-bench/nas-algos', help='Folder to save checkpoints and log.') parser.add_argument('--search_space', type=str, choices=['tss', 'sss'], help='Choose the search space.') args = parser.parse_args() save_dir = Path(args.save_dir) api = create(None, 'tss', fast_mode=True, verbose=False) indexes = list(range(1, 10000, 300)) scores_1 = [] scores_2 = [] for index in indexes: valid_acc, test_acc, _ = get_valid_test_acc(api, index, 'cifar10') scores_1.append(valid_acc) scores_2.append(test_acc) correlation = compute_kendalltau(scores_1, scores_2) print('The kendall tau correlation of {:} samples : {:}'.format(len(indexes), correlation)) correlation = compute_spearmanr(scores_1, scores_2) print('The spearmanr correlation of {:} samples : {:}'.format(len(indexes), correlation)) # scores_1 = ['{:.2f}'.format(x) for x in scores_1] # scores_2 = ['{:.2f}'.format(x) for x in scores_2] # print(', '.join(scores_1)) # print(', '.join(scores_2)) dpi, width, height = 250, 1000, 1000 figsize = width / float(dpi), height / float(dpi) LabelSize, LegendFontsize = 14, 14 fig, ax = plt.subplots(1, 1, figsize=figsize) ax.scatter(scores_1, scores_2 , marker='^', s=0.5, c='tab:green', alpha=0.8) save_path = '/Users/xuanyidong/Desktop/test-temp-rank.png' fig.savefig(save_path, dpi=dpi, bbox_inches='tight', format='png') plt.close('all')
becb97ab51bd113a00a2a0c169559e348ee0f82c
a46b14b44c87adb0288224a0e7e31d9bed30223f
/guest_project/apps/guest_app/models.py
f6db55f42203f80a0a458a0b4a83ca4f50478693
[]
no_license
JeffLawrence1/Python-Django-Intermediate
0b663e5d706dc6b35ff2785ae38d7bf0f2f3b651
d1efc3e6385286ab25bae36042987a85ae94e359
refs/heads/master
2020-03-09T03:42:47.348420
2018-04-07T21:42:04
2018-04-07T21:42:04
128,570,954
0
0
null
null
null
null
UTF-8
Python
false
false
191
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class User(models.Model): name = models.CharField(max_length=255)
592cca932c6d29898437e2362af88c8d578e9466
a735cc0b04b3227720bfd97c74ef13bda5bdf571
/python/documentation/doc/conf.py
87be3541d59a67e9c9cc135f03e7e0690fa181a4
[ "MIT" ]
permissive
abstractfactory/labs
beed0aab27cd3028c67ece87ef91d18b55114eb1
f0791fb92686456d4cef3a11f699590a949fd6a9
refs/heads/master
2021-01-23T20:50:07.613682
2014-11-18T10:30:29
2014-11-18T10:30:29
20,175,862
1
3
null
null
null
null
UTF-8
Python
false
false
8,179
py
# -*- coding: utf-8 -*- # # Labs documentation build configuration file, created by # sphinx-quickstart on Tue Jun 24 15:49:19 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Labs' copyright = u'2014, Marcus Ottosson' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'Labsdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'Labs.tex', u'Labs Documentation', u'Marcus Ottosson', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'labs', u'Labs Documentation', [u'Marcus Ottosson'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'Labs', u'Labs Documentation', u'Marcus Ottosson', 'Labs', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
5242f6f122ece46875d63baf451df2044a5956d8
ce083128fa87ca86c65059893aa8882d088461f5
/python/pytest-labs/.venv/lib/python3.6/site-packages/facebook_business/adobjects/adcampaignfrequencycontrolspecs.py
d0005352b87cf20f8700d3c56dda97efc9a99ee6
[]
no_license
marcosptf/fedora
581a446e7f81d8ae9a260eafb92814bc486ee077
359db63ff1fa79696b7bc803bcfa0042bff8ab44
refs/heads/master
2023-04-06T14:53:40.378260
2023-03-26T00:47:52
2023-03-26T00:47:52
26,059,824
6
5
null
2022-12-08T00:43:21
2014-11-01T18:48:56
null
UTF-8
Python
false
false
1,973
py
# Copyright 2014 Facebook, Inc. # You are hereby granted a non-exclusive, worldwide, royalty-free license to # use, copy, modify, and distribute this software in source code or binary # form for use in connection with the web services and APIs provided by # Facebook. # As with any software that integrates with the Facebook platform, your use # of this software is subject to the Facebook Developer Principles and # Policies [http://developers.facebook.com/policy/]. This copyright notice # shall be included in all copies or substantial portions of the software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from facebook_business.adobjects.abstractobject import AbstractObject """ This class is auto-generated. For any issues or feature requests related to this class, please let us know on github and we'll fix in our codegen framework. We'll not be able to accept pull request for this class. """ class AdCampaignFrequencyControlSpecs( AbstractObject, ): def __init__(self, api=None): super(AdCampaignFrequencyControlSpecs, self).__init__() self._isAdCampaignFrequencyControlSpecs = True self._api = api class Field(AbstractObject.Field): event = 'event' interval_days = 'interval_days' max_frequency = 'max_frequency' _field_types = { 'event': 'string', 'interval_days': 'unsigned int', 'max_frequency': 'unsigned int', } @classmethod def _get_field_enum_info(cls): field_enum_info = {} return field_enum_info
824fe2517075df54beda8ff30d6a67ef447af8ae
7a7bbdaab3cedcd9b89d9245d67fe7cc472fc288
/1_dimention/2577.py
057b91d168293a509f38fbb985532bb1d9aba21b
[]
no_license
rheehot/baekjun
cd213c6903e69a8e48b4942c950048c1c3e03c34
44792c6d125af7d9b0739c571e7918c802f73c01
refs/heads/master
2023-02-12T08:42:47.578842
2020-12-21T00:40:35
2020-12-21T00:40:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
123
py
a = int(input()) b = int(input()) c = int(input()) mul = str(a * b * c) for i in range(10): print(mul.count(str(i)))
254e98217498dea904c67279827063013f34b5fb
e6421de3f06af8be4234e9901d71f86b31c6c3a7
/pdenv/bin/easy_install-3.5
5e6b880f3fb8150f6afd21b014f591583dfa7719
[ "MIT" ]
permissive
Elmartin913/PanDjango
bdb5446ee18ee297c23199cd3f9dd59cae555135
3b1eb52d53c87365f3d2fa5bd7ef72843ed5af32
refs/heads/master
2022-12-11T04:44:05.229530
2018-05-11T10:16:07
2018-05-11T10:16:07
128,903,323
0
0
MIT
2022-12-08T00:57:53
2018-04-10T08:54:10
CSS
UTF-8
Python
false
false
276
5
#!/home/elmartin913/workspace/app/PanDjango/pdenv/bin/python3 # -*- coding: utf-8 -*- import re import sys from setuptools.command.easy_install import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())
e57aebb6fb7ca69bcb5a28998f4b3016e5559651
47366be5cbee9d7e086291c20f97f10ab2bf74fe
/cluster/cluster_create_inequalities_subset_kdd.py
a030a3765bc70ab81a1b6e0dfd314582797a9901
[]
no_license
nipunbatra/journal
3d44eed05c95970606649d17402da54fc0a415ff
94a8b88589e8f60e6f0314f8c5a374f22336b3e9
refs/heads/master
2021-01-09T20:40:45.844121
2016-07-27T15:16:29
2016-07-27T15:16:29
62,874,718
0
0
null
null
null
null
UTF-8
Python
false
false
4,042
py
import time import pandas as pd import pickle import os import numpy as np SLURM_OUT = "../slurm_out" from subprocess import Popen import time print "a" out_overall = pickle.load(open('../data/input/all_regions.pkl','r')) num_trials=25 print "b" K = 3 for train_region in ["SanDiego"]: if train_region=="Austin": NUM_HOMES_MAX = 45 elif train_region=="SanDiego": NUM_HOMES_MAX = len(out_overall['SanDiego']) else: NUM_HOMES_MAX = len(out_overall['Boulder']) NUM_HOMES_MAX=20 for test_region in ["Austin"]: if train_region!=test_region: TRANSFORMATIONS = ["None","DD","DD-percentage","median-aggregate-percentage", "median-aggregate",'regional','regional-percentage'] else: TRANSFORMATIONS = ["None"] train_df = out_overall[train_region] test_df = out_overall[test_region] test_df=test_df[(test_df.full_agg_available==1)&(test_df.md_available==1)] NUM_HOMES_MIN=4 for num_homes in range(NUM_HOMES_MIN, NUM_HOMES_MAX, 2): for transform in TRANSFORMATIONS: #for transform in ["None","DD","DD-percentage"]: #for transform in ["median-aggregate-percentage"]: print transform print "*"*40 count = 0 #for appliance in ["dw",'hvac','fridge','wm','mw','ec','wh','oven']: for appliance in ["hvac"]: if appliance=="hvac": month_min, month_max = 5, 11 else: month_min, month_max = 1, 13 count+= 1 #for appliance in ["hvac","fridge","dr","wm"]: test_df = test_df.ix[test_df[['%s_%d' %(appliance,month) for month in range(month_min, month_max)]].dropna().index] for test_home in test_df.index: #for appliance in ["mw"]: if len(test_df.ix[test_home][['%s_%d' %(appliance, m) for m in range(month_min, month_max)]].dropna())==0: # Appliance data not present for this homes..let's save some time continue print appliance, test_home, count, len(test_df.index), K, transform, train_region, test_region OFILE = "%s/%d_%s_%s_%d_%s_%s.out" % (SLURM_OUT, num_homes, train_region[0], test_region[0], test_home, appliance[0], transform[0] ) EFILE = "%s/%d_%s_%s_%d_%s_%s.err" % (SLURM_OUT, num_homes, train_region[0], test_region[0], test_home, appliance, transform ) SLURM_SCRIPT = "%d_%s_%s_%d_%s_%s.pbs" % (num_homes, train_region[0], test_region[0], test_home, appliance[:2], transform) CMD = 'python ../new_experiments/create_inequalities_subset_kdd.py %s %s %d %s %s %d %d %d' % (train_region, test_region, test_home, appliance, transform, K, num_homes, num_trials) lines = [] lines.append("#!/bin/sh\n") lines.append('#SBATCH --time=0-05:0:00\n') lines.append('#SBATCH --mem=16\n') lines.append('#SBATCH -o '+'"' +OFILE+'"\n') lines.append('#SBATCH -e '+'"' +EFILE+'"\n') lines.append(CMD+'\n') with open(SLURM_SCRIPT, 'w') as f: f.writelines(lines) command = ['sbatch', SLURM_SCRIPT] Popen(command) #os.remove(SLURM_SCRIPT) print "Now sleeping.." import time time.sleep(40) time.sleep(400) time.sleep(1200)
05f02000e82ea0aa84a9665a9401fad1feec02b2
03587c34370995706871e45320264c2636d795f0
/app/views/loja/AvaliacaoView.py
a391584f99994610a29e9c4c605cadf597837918
[]
no_license
caiomarinhodev/fastdelivery
29d1f95dc7204369806e6b99298c9aaafab5ea9f
6ad45aa596e204b793ba47f7a0c1b918a2e0890a
refs/heads/master
2020-03-12T03:18:04.507010
2018-04-20T23:49:13
2018-04-20T23:49:13
130,421,809
0
0
null
null
null
null
UTF-8
Python
false
false
1,139
py
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect from django.views.generic import DetailView from app.models import Request, Avaliacao class AvaliacaoView(LoginRequiredMixin, DetailView): template_name = 'loja/avaliacao_cliente.html' login_url = '/define/login/' model = Request context_object_name = 'pedido_obj' def get(self, request, *args, **kwargs): return super(AvaliacaoView, self).get(request, *args, **kwargs) def add_avaliacao(request): data = request.POST pedido = Request.objects.get(id=data['pedido']) if 'comentario' and 'nota' in data: aval = Avaliacao(cliente=pedido.cliente, estabelecimento=pedido.estabelecimento, nota=data['nota'], comentario=data['comentario']) aval.save() else: messages.error(request, 'Insira uma nota e um comentario') return redirect('/avaliacao/pedido/' + str(data['pedido'])) messages.success(request, 'Avaliacao Realizada com Sucesso') return redirect('/acompanhar-pedido/' + str(data['pedido']))
368438d6bd6eb2e764a63f7c2983f6a8380944e8
80775c192c7084171a0371b0fe14330b8cd89f0f
/stickerizer/emojis.py
7070fbc525378011ade618d9b44d039bdcc88f9a
[ "MIT" ]
permissive
vanyakosmos/face2sticker
5435ddbbc123c782a6501a78f6142e1ce88f9bc7
7b82eb12dd3e4c54c5033caee77f57b751f637b8
refs/heads/master
2021-09-13T07:40:51.156215
2018-04-26T17:16:24
2018-04-26T17:16:24
105,321,918
3
0
null
null
null
null
UTF-8
Python
false
false
1,318
py
import numpy as np from emotion_clf.emotion import load_clf, vectorize, emotions clf = load_clf('emotion_clf/clf2.pkl') def associate_emojis(face_landmarks): emotions_probs = predict_probabilities(face_landmarks) emoji = map_emoji(emotions_probs) return emoji def predict_probabilities(face_landmarks: dict): landmarks = [] for points in face_landmarks.values(): landmarks.extend(points) vector = vectorize(landmarks) data = np.array([vector]) res = clf.predict_proba(data)[0] probs = {} for i, e in enumerate(emotions): probs[e] = res[i] return probs def map_emoji(emotions_prob: dict): emojis = { '😡': { 'anger': 10, }, '😒': { 'contempt': 10, }, '😣': { 'disgust': 10, }, '😱': { 'fear': 10, }, '😀': { 'happiness': 10, }, '😢': { 'sadness': 10, }, '😮': { 'surprise': 10, }, } max_s = None result = '🌚' for emoji, ems in emojis.items(): s = sum([ems.get(e, 1) * emotions_prob[e] for e in emotions]) if not max_s or s > max_s: max_s = s result = emoji return result
8f7d2e670202fe46834fd31c9e7eaf218bed9b04
ca3d6e6683f4736792fc93352424c6e6d216ab4d
/chapter9/chapter9_app_external_api_test.py
ccdbb3f2d629abb50083ae1be6495e4b66566be2
[ "MIT" ]
permissive
msg4rajesh/Building-Data-Science-Applications-with-FastAPI
11ac071583002b15bc955fc3bc72ab86d2800222
99b472d8295a57c5a74a63d8184ac053dc4012f2
refs/heads/main
2023-07-16T09:48:48.536002
2021-08-26T05:02:39
2021-08-26T05:02:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,297
py
import asyncio from typing import Any, Dict import httpx import pytest from asgi_lifespan import LifespanManager from fastapi import status from chapter9.chapter9_app_external_api import app, external_api class MockExternalAPI: mock_data = { "data": [ { "employee_age": 61, "employee_name": "Tiger Nixon", "employee_salary": 320800, "id": 1, "profile_image": "", } ], "status": "success", "message": "Success", } async def __call__(self) -> Dict[str, Any]: return MockExternalAPI.mock_data @pytest.fixture(scope="session") def event_loop(): loop = asyncio.get_event_loop() yield loop loop.close() @pytest.fixture async def test_client(): app.dependency_overrides[external_api] = MockExternalAPI() async with LifespanManager(app): async with httpx.AsyncClient(app=app, base_url="http://app.io") as test_client: yield test_client @pytest.mark.asyncio async def test_get_employees(test_client: httpx.AsyncClient): response = await test_client.get("/employees") assert response.status_code == status.HTTP_200_OK json = response.json() assert json == MockExternalAPI.mock_data
ff7e5353de2674b363d6503c65205bd258975026
dfff7fef4d49266db475856d4c0afef8ca672e00
/tests/cantfit.py
54f692c8b57158768e4561a4098cae020b3eafbe
[ "MIT" ]
permissive
funilrys/black
70a5a251338ab67fed0771ab6ec97cca03aa378b
b4cee97c99d5513ef81fdf2bff1809721662f87d
refs/heads/master
2020-03-17T14:41:13.259870
2018-05-16T05:15:28
2018-05-16T05:15:28
133,682,656
1
0
null
2018-05-16T14:57:35
2018-05-16T14:57:35
null
UTF-8
Python
false
false
2,983
py
# long variable name this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 0 this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = 1 # with a comment this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ 1, 2, 3 ] this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function() this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( arg1, arg2, arg3 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long function name normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( arg1, arg2, arg3 ) normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long arguments normal_name = normal_function_name( "but with super long string arguments that on their own exceed the line limit so there's no way it can ever fit", "eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs", this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, ) # output # long variable name this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( 0 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( 1 ) # with a comment this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = [ 1, 2, 3 ] this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = ( function() ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( arg1, arg2, arg3 ) this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it = function( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long function name normal_name = ( but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying() ) normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( arg1, arg2, arg3 ) normal_name = but_the_function_name_is_now_ridiculously_long_and_it_is_still_super_annoying( [1, 2, 3], arg1, [1, 2, 3], arg2, [1, 2, 3], arg3 ) # long arguments normal_name = normal_function_name( "but with super long string arguments that on their own exceed the line limit so there's no way it can ever fit", "eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs with spam and eggs and spam with eggs", this_is_a_ridiculously_long_name_and_nobody_in_their_right_mind_would_use_one_like_it=0, )
6ec673beb0c506a5c90bb8c68908c0c73c13587c
3a74ac2e7db63069945e5bc620342b4b89b8b201
/python/dgl/distributed/rpc_server.py
ad47de7104c4d92fc64b87b7cdc82f26fefd6a38
[ "Apache-2.0" ]
permissive
vishalbelsare/dgl
5d17ba82f720d742e1274c5d48dac64eca234504
512a80b00d2cd35607a542eb5544fa1f1c93a6f6
refs/heads/master
2023-08-17T15:09:55.082014
2022-01-22T04:25:14
2022-01-22T04:25:14
167,955,673
0
0
Apache-2.0
2022-01-23T13:57:57
2019-01-28T12:05:37
Python
UTF-8
Python
false
false
4,476
py
"""Functions used by server.""" import time from . import rpc from .constants import MAX_QUEUE_SIZE def start_server(server_id, ip_config, num_servers, num_clients, server_state, \ max_queue_size=MAX_QUEUE_SIZE, net_type='socket'): """Start DGL server, which will be shared with all the rpc services. This is a blocking function -- it returns only when the server shutdown. Parameters ---------- server_id : int Current server ID (starts from 0). ip_config : str Path of IP configuration file. num_servers : int Server count on each machine. num_clients : int Total number of clients that will be connected to the server. Note that, we do not support dynamic connection for now. It means that when all the clients connect to server, no client will can be added to the cluster. server_state : ServerSate object Store in main data used by server. max_queue_size : int Maximal size (bytes) of server queue buffer (~20 GB on default). Note that the 20 GB is just an upper-bound because DGL uses zero-copy and it will not allocate 20GB memory at once. net_type : str Networking type. Current options are: 'socket'. """ assert server_id >= 0, 'server_id (%d) cannot be a negative number.' % server_id assert num_servers > 0, 'num_servers (%d) must be a positive number.' % num_servers assert num_clients >= 0, 'num_client (%d) cannot be a negative number.' % num_clients assert max_queue_size > 0, 'queue_size (%d) cannot be a negative number.' % max_queue_size assert net_type in ('socket'), 'net_type (%s) can only be \'socket\'' % net_type # Register signal handler. rpc.register_sig_handler() # Register some basic services rpc.register_service(rpc.CLIENT_REGISTER, rpc.ClientRegisterRequest, rpc.ClientRegisterResponse) rpc.register_service(rpc.SHUT_DOWN_SERVER, rpc.ShutDownRequest, None) rpc.register_service(rpc.GET_NUM_CLIENT, rpc.GetNumberClientsRequest, rpc.GetNumberClientsResponse) rpc.register_service(rpc.CLIENT_BARRIER, rpc.ClientBarrierRequest, rpc.ClientBarrierResponse) rpc.set_rank(server_id) server_namebook = rpc.read_ip_config(ip_config, num_servers) machine_id = server_namebook[server_id][0] rpc.set_machine_id(machine_id) ip_addr = server_namebook[server_id][1] port = server_namebook[server_id][2] rpc.create_sender(max_queue_size, net_type) rpc.create_receiver(max_queue_size, net_type) # wait all the senders connect to server. # Once all the senders connect to server, server will not # accept new sender's connection print("Wait connections non-blockingly...") rpc.receiver_wait(ip_addr, port, num_clients, blocking=False) rpc.set_num_client(num_clients) # Recv all the client's IP and assign ID to clients addr_list = [] client_namebook = {} for _ in range(num_clients): # blocked until request is received req, _ = rpc.recv_request() assert isinstance(req, rpc.ClientRegisterRequest) addr_list.append(req.ip_addr) addr_list.sort() for client_id, addr in enumerate(addr_list): client_namebook[client_id] = addr for client_id, addr in client_namebook.items(): client_ip, client_port = addr.split(':') # TODO[Rhett]: server should not be blocked endlessly. while not rpc.connect_receiver(client_ip, client_port, client_id): time.sleep(1) if rpc.get_rank() == 0: # server_0 send all the IDs for client_id, _ in client_namebook.items(): register_res = rpc.ClientRegisterResponse(client_id) rpc.send_response(client_id, register_res) # main service loop while True: req, client_id = rpc.recv_request() res = req.process_request(server_state) if res is not None: if isinstance(res, list): for response in res: target_id, res_data = response rpc.send_response(target_id, res_data) elif isinstance(res, str) and res == 'exit': break # break the loop and exit server else: rpc.send_response(client_id, res)
8a16b83756f3b6f2cc7e3bf1f7c8a50c5bc43058
f171072a6390997ea4cf398f32ff3c7b7680af3a
/bumerang/apps/video/albums/migrations/0005_auto__add_field_videoalbum_created.py
598fadaa544415799e09f3de533bda105c00bcce
[]
no_license
onewaterdrop/bumerang
f1ab153d033072c49de2edb976fa761bd4293bba
0466c8b37ad1073d7ba4fc4dc00a5c6debb343a7
refs/heads/master
2021-01-15T23:41:23.379010
2014-06-23T07:57:48
2014-06-23T07:57:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
13,622
py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'VideoAlbum.created' db.add_column('albums_videoalbum', 'created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'VideoAlbum.created' db.delete_column('albums_videoalbum', 'created') models = { 'albums.photoalbum': { 'Meta': {'object_name': 'PhotoAlbum'}, 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['albums.PhotoCategory']", 'null': 'True', 'blank': 'True'}), 'cover': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['photo.Photo']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'published_in_archive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'albums.photocategory': { 'Meta': {'ordering': "('sort_order', 'title')", 'object_name': 'PhotoCategory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'albums.videoalbum': { 'Meta': {'object_name': 'VideoAlbum'}, 'cover': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['video.Video']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'photo.photo': { 'Meta': {'ordering': "('-id',)", 'object_name': 'Photo'}, 'access': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'blank': 'True'}), 'agency': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'album': ('django.db.models.fields.related.ForeignKey', [], {'max_length': '255', 'to': "orm['albums.PhotoAlbum']", 'null': 'True', 'blank': 'True'}), 'authors': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'festivals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'genre': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['photo.PhotoGenre']", 'null': 'True', 'blank': 'True'}), 'icon': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'manager': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'original_file': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'published_in_archive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}), 'teachers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'views_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'year': ('django.db.models.fields.IntegerField', [], {'default': '2011', 'null': 'True', 'blank': 'True'}) }, 'photo.photogenre': { 'Meta': {'ordering': "('sort_order', 'title')", 'object_name': 'PhotoGenre'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'video.video': { 'Meta': {'ordering': "('-id',)", 'object_name': 'Video'}, 'access': ('django.db.models.fields.IntegerField', [], {'default': '1', 'null': 'True', 'blank': 'True'}), 'agency': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'album': ('django.db.models.fields.related.ForeignKey', [], {'max_length': '255', 'to': "orm['albums.VideoAlbum']", 'null': 'True', 'blank': 'True'}), 'authors': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['video.VideoCategory']", 'null': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'country': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'duration': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'festivals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'genre': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['video.VideoGenre']", 'null': 'True', 'blank': 'True'}), 'hq_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_in_broadcast_lists': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'manager': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'original_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'published_in_archive': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'rating_score': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}), 'rating_votes': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '12', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'teachers': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'views_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}), 'year': ('django.db.models.fields.IntegerField', [], {'default': '2012', 'null': 'True', 'blank': 'True'}) }, 'video.videocategory': { 'Meta': {'ordering': "('sort_order', 'title')", 'object_name': 'VideoCategory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'video.videogenre': { 'Meta': {'ordering': "('sort_order', 'title')", 'object_name': 'VideoGenre'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'sort_order': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}) } } complete_apps = ['albums']
f2ed1999ab2fe5b10597c440649a3b93645b82d3
c1e305171afcd18fdd66a46cbcf81d8dbcc3fd0c
/PyTorch/Py09_dropout.py
447dd6e594089cf2812c287b60aa6a968b1ae24c
[]
no_license
ANRhine/PyTorch_Tutorial
2f0d9fcc94dfec37a352b5dcb37fc66738abc37d
378d03d2f2cfa08ff2040096218078a2e3cd659a
refs/heads/master
2021-04-07T06:24:28.608860
2018-03-16T14:43:03
2018-03-16T14:43:03
125,291,327
1
0
null
null
null
null
UTF-8
Python
false
false
3,116
py
#! /usr/bin/env python # -*- coding:utf-8 -*- """ ------------------------------------- File name: Py09_dropout.py Author: Ruonan Yu Date: 18-1-30 ------------------------------------- """ import torch import matplotlib.pyplot as plt from torch.autograd import Variable import torch.nn as nn torch.manual_seed(1) N_SAMPLES = 20 N_HIDDEN = 300 LR = 0.001 # fake data # training data x = torch.unsqueeze(torch.linspace(-1, 1, N_SAMPLES), 1) y = x + 0.3 * torch.normal(torch.zeros(N_SAMPLES, 1), torch.ones(N_SAMPLES, 1)) x, y = Variable(x), Variable(y) # test data test_x = torch.unsqueeze(torch.linspace(-1, 1, N_SAMPLES), 1) test_y = test_x + 0.3 * torch.normal(torch.zeros(N_SAMPLES, 1), torch.ones(N_SAMPLES, 1)) test_x, test_y = Variable(test_x, volatile=True), Variable(test_y, volatile=True) # overfitting network net_overfitting = nn.Sequential( nn.Linear(1, N_HIDDEN), nn.ReLU(), nn.Linear(N_HIDDEN, N_HIDDEN), nn.ReLU(), nn.Linear(N_HIDDEN, 1) ) # dropout network net_dropouted = nn.Sequential( nn.Linear(1, N_HIDDEN), nn.Dropout(0.5), # drop 50% of neuron nn.ReLU(), nn.Linear(N_HIDDEN, N_HIDDEN), nn.Dropout(0.5), # drop 50% of neuron nn.ReLU(), nn.Linear(N_HIDDEN, 1) ) print(net_overfitting) print(net_dropouted) # training optimizer_ofit = torch.optim.Adam(net_overfitting.parameters(), lr=LR) optimizer_drop = torch.optim.Adam(net_dropouted.parameters(), lr=LR) loss_func = nn.MSELoss() plt.ion() for t in range(500): pred_ofit = net_overfitting(x) pred_drop = net_dropouted(x) loss_ofit = loss_func(pred_ofit, y) loss_drop = loss_func(pred_drop, y) optimizer_ofit.zero_grad() optimizer_drop.zero_grad() loss_ofit.backward() loss_drop.backward() optimizer_ofit.step() optimizer_drop.step() if t % 10 == 0: # 每10步画一次图 # 将神经网络转换test形式,画好图之后改回训练形式 net_overfitting.eval() net_dropouted.eval() # 因为drop网络在train的时候和test的时候参数不一样 plt.cla() test_pred_ofit = net_overfitting(test_x) test_pred_drop = net_dropouted(test_x) plt.scatter(x.data.numpy(), y.data.numpy(), c='magenta', alpha=0.5, label='train') plt.scatter(test_x.data.numpy(), test_y.data.numpy(), c='cyan', s=50, alpha=0.5, label='test') plt.plot(test_x.data.numpy(), test_pred_ofit.data.numpy(), 'r-', lw=3, label='overfitting') plt.plot(test_x.data.numpy(), test_pred_drop.data.numpy(), 'b--', lw=3, label='dropout(50%)') plt.text(0, -1.2, r'$overfitting loss=%.4f$' % loss_func(test_pred_ofit, test_y).data[0], fontdict={'size': 10, 'color': 'red'}) plt.text(0, -1.5, r'$dropout loss=%.4f$' % loss_func(test_pred_drop, test_y).data[0], fontdict={'size': 10, 'color': 'red'}) plt.legend(loc='upper left') plt.ylim((-2.5, 2.5)) plt.pause(0.1) # 将两个网络改回train形式 net_overfitting.train() net_dropouted.train() plt.ioff() plt.show()
c44a67a3eaabc76d6e5635f62a79a69aa80faa77
e5a511e346f5be8a82fe9cb2edf457aa7e82859c
/PythonNEW/Practice/StringRemoveExistingIdentitaion.py
f66992651f064d1098bc0a3e95b04ea1ee0ff896
[]
no_license
nekapoor7/Python-and-Django
8397561c78e599abc8755887cbed39ebef8d27dc
8fa4d15f4fa964634ad6a89bd4d8588aa045e24f
refs/heads/master
2022-10-10T20:23:02.673600
2020-06-11T09:06:42
2020-06-11T09:06:42
257,163,996
0
0
null
null
null
null
UTF-8
Python
false
false
482
py
""" Write a Python program to remove existing indentation from all of the lines in a given text.""" import textwrap sample_text = ''' Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. ''' text = textwrap.dedent(sample_text) print(text)
9393d21961b0043d35b932fd166c21ca22c72e0c
e456cdf76c1419413931d218317d44ea4b7c3fb7
/demo/django/pokedex/admin.py
fd91861f03cd25790e7dec41cc349aba98f35f27
[ "MIT" ]
permissive
Nekmo/angular-django
cbbd8bb0c6baeea6e788c5623fb98102b443f1e9
0464747806ce4e79571d3a72db0f04e15f0c6e5e
refs/heads/master
2023-08-27T16:03:10.006482
2021-11-08T23:15:14
2021-11-08T23:15:14
298,419,330
14
6
null
null
null
null
UTF-8
Python
false
false
169
py
from django.contrib import admin # Register your models here. from pokedex.models import Specie @admin.register(Specie) class SpecieAdmin(admin.ModelAdmin): pass
cc175ac74f032d57d8641a106ebead8e8f7f8a10
7c9707f0f1cb8e633ac605934f3dbd8036790868
/projet/rpi_manager/migrations/0002_ph.py
71da2a49b682367bb47761ea2e6341addf2a5fc5
[]
no_license
ometeore/hydropo
891e1abd4c1b8ccd0a3b27a043abf894b70ceb5b
324076d4b7ddbd14e718c424eb24d129c2a2243c
refs/heads/master
2023-06-14T08:35:55.838469
2021-07-04T16:28:09
2021-07-04T16:28:09
290,198,666
0
0
null
null
null
null
UTF-8
Python
false
false
991
py
# Generated by Django 3.1 on 2020-08-25 13:49 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("rpi_manager", "0001_initial"), ] operations = [ migrations.CreateModel( name="Ph", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ("date", models.DateTimeField()), ("value", models.FloatField()), ( "rpi", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="rpi_manager.rpi", ), ), ], ), ]
89e026a18c52f389d46597ba589fee07cc32a352
d44d33899aaab3d2a8b693b648701d49810aca12
/cip5-multiprofile-wave.py
e001a331576902efdc7df62b78d3e40a59f81237
[]
no_license
izham-sugita/CIP
208eee2e108a910abd3a137083638244b8f60303
a0cd77531a34ad32a0cebeb6069123e89aceb0b5
refs/heads/master
2021-06-27T14:51:45.696969
2021-01-07T11:44:04
2021-01-07T11:44:04
204,810,048
0
1
null
null
null
null
UTF-8
Python
false
false
5,796
py
import numpy as np import matplotlib.pyplot as plt #Changing the default size #fig_size = plt.rcParams["figure.figsize"] #fig_size[0] = 20 #fig_size[1] = 16 #plt.rcParams["figure.figsize"] = fig_size imax = 2001 imax = int( input("Enter imax ") ) length = 2.0 #-1<=x<=1 dx = length/(imax-1) u = np.ndarray((imax),dtype=np.float64) un = np.ndarray((imax),dtype=np.float64) ud1 = np.zeros_like(u) ud1n = np.zeros_like(u) ud2 = np.zeros_like(u) ud2n = np.zeros_like(u) x = np.ndarray((imax),dtype=np.float64) ''' for i in range(imax): x[i] = i*dx u[i] = 0.0 un[i] =0.0 if x[i] >= 4.0 and x[i] <= 6.0: u[i] = 1.0 un[i]=1.0 ''' u[:] = 0.0 un[:] = 0.0 #multiple wave profile for i in range(imax): x[i] = -1.0 + i*dx if x[i] >=-0.8 and x[i] <=-0.6: u[i] = np.exp( -np.log(2.0)*(x[i]+0.7)**2 / 0.0009 ) un[i] = u[i] elif x[i] >=-0.5 and x[i] <=-0.2: u[i] = 1.0 un[i] = u[i] elif x[i] >=0.0 and x[i] <=0.2: u[i] = 1.0 - abs(10.0*x[i] - 1.0) un[i] = u[i] elif x[i] >=0.4 and x[i] <=0.6: u[i] = np.sqrt( 1.0 - 100.0*(x[i] - 0.5)**2 ) un[i] = u[i] #Initiate derivatives value for i in range( 1, imax-1 ): ud1[i] = 0.5*(u[i+1] - u[i-1])/dx for i in range( 1, imax-1 ): ud2[i] = 0.5*(ud1[i+1] - ud1[i-1])/dx dt = np.float64(input("Enter dt, dx=%s\n "%dx )) elapsed = 10.0 itermax = int( elapsed/dt )-int(elapsed/2.0) #adjusted timestep; don't know why print("Maximum iteration: ", itermax) c = 1.0 c = float(input("Enter c, +1.0 or -1.0 ")) alpha = c*dt/dx eps = 1.0e-6 uexact = np.zeros_like(u) ''' #calculating exact solution for i in range(imax): r1 = itermax*dt + 4.0 r2 = r1 + (6.0 - 4.0) #did this on purpose, a reminder if x[i] >=r1 and x[i] <= r2: uexact[i] = 1.0 ''' uexact[:] = u[:] #matrix A up = -np.sign(c) A = np.array( [ [ (up*dx)**5, (up*dx)**4, (up*dx)**3], [5.0*(up*dx)**4, 4.0*(up*dx)**3, 3.0*(up*dx)**2], [20.0*(up*dx)**3, 12.0*(up*dx)**2, 6.0*up*dx] ] ) coef = np.array( [0.0, 0.0, 0.0] ) b = np.array( [0.0, 0.0, 0.0] ) xx = -c*dt steps = 1 eps = 1.0e-8 phi = np.zeros_like(u) for iter in range(itermax): for i in range(1,imax-1): up = -np.sign(c) iup = i + int(up) xx = -c*dt b[0] = ( u[iup] - u[i] ) -0.5*ud2[i]*dx*dx - ud1[i]*up*dx b[1] = ( ud1[iup] - ud1[i] ) - ud2[i]*up*dx b[2] = ud2[iup] - ud2[i] coef = np.linalg.solve(A, b) a0 = coef[0] a1 = coef[1] a2 = coef[2] a3 = ud2[i]*0.5 a4 = ud1[i] #limiter udif = ( u[iup] - u[i] )/dx*up #minmod limiter ratio = (u[i] - u[i-1]) / (u[i+1] - u[i] + eps) phi0 = min(10.0*dx, ratio) #default is 1.0 phi[iup] = max(0.0, phi0) #phi[iup] = 0.0 #van Leer (continuous function) #very diffusive #ratio = (u[i] - u[i-1]) / (u[i+1] - u[i] + eps) #phi[iup] = (ratio + abs(ratio)) / (1.0 + ratio) #un[i] = a0*xx**5 + a1*xx**4 + a2*xx**3 + a3*xx**2 + a4*xx + u[i] un[i] = u[i] + (1.0-phi[iup])*(a4*xx + a3*xx**2 + a2*xx**3 + a1*xx**4 + a0*xx**5) \ + phi[iup]*(udif*xx) ud1n[i] = (1.0 - phi[iup])*( 5.0*a0*xx**4 + 4.0*a1*xx**3 + 3.0*a2*xx**2 + 2.0*a3*xx \ + ud1[i] ) + phi[iup]*udif # weight 0.98, 0.01 is the least diffusive #putting weight only on the first derivative #un[i] = u[i] + (1.0 - phi[iup])*(a4*xx) + a3*xx**2 + a2*xx**3 + a1*xx**4 + a0*xx**5 \ # + phi[iup]*(udif*xx) #ud1n[i] = 5.0*a0*xx**4 + 4.0*a1*xx**3 + 3.0*a2*xx**2 + 2.0*a3*xx \ # + (1.0 - phi[iup])*ud1[i] + phi[iup]*udif #the second derivative is not affected ud2n[i] = 20.0*a0*xx**3 + 12.0*a1*xx**2 + 6.0*a2*xx + ud2[i] #update periodic BC u[0] = un[imax-2] ud1[0] = ud1n[imax-2] ud2[0] = ud2n[imax-2] u[imax-1] = un[imax-2] ud1[imax-1] = ud1n[imax-2] ud2[imax-1] = ud2n[imax-2] for i in range(1, imax-1): u[i] = un[i] ud1[i] = ud1n[i] ud2[i] = ud2n[i] #update periodic BC #u[imax-1] = un[imax-2] #ud1[imax-1] = ud1n[imax-2] #ud2[imax-1] = ud2n[imax-2] #u[0] = un[imax-2] #ud1[0] = ud1n[imax-2] #ud2[0] = ud2n[imax-2] ''' #update u[:] = un[:] ud1[:] = ud1n[:] ud2[:] = ud2n[:] ''' #if iter%steps == 0: # num = str(iter) # filename = "./data1D/f"+num.zfill(5)+".csv" # fp = open(filename, "w") # fp.write("x, u\n") # for i in range(imax): # str1 = str(x[i]) # str2 = str(u[i]) # comma = "," # nextline = "\n" # strall = str1+comma+str2+nextline # fp.write(strall) # fp.close() current = iter*dt + dt display = "t = %.4f"%(current) phi[:] = 0.0 current = iter*dt + dt display = "t = %.4f"%(current) #plt.axis([0.0, 10.0, -0.5, 1.5 ] ) plt.axis([-2.0, 2.0, -0.5, 1.5 ] ) plt.title(display) plt.ylabel("U") plt.xlabel("x") plt.plot(x,u,'bo-') plt.pause(0.001) plt.clf() #clear drawing filename = "final.png" #plt.axis([0.0, 10.0, -0.5, 1.5 ] ) plt.axis([-2.0, 2.0, -0.5, 1.5 ] ) plt.plot(x,u, 'bo-', x, uexact,'kv-') plt.title(display) plt.ylabel("U") plt.xlabel("x") plt.savefig(filename) plt.show() #plt.show(block=False) #plt.pause(3) #plt.close() filename = "cip5-final.csv" fp = open(filename, "w") fp.write("x, u\n") for i in range(imax): str1 = str(x[i]) str2 = str(u[i]) comma = "," nextline = "\n" strall = str1+comma+str2+nextline fp.write(strall) fp.close()
898a057527760f01aeb95b618322cf09388c1f42
02e23da0431623db86c8138bda350a1d526d4185
/Archivos Python Documentos/Graficas/.history/TRABAJO_SPT_v3_20200224230649.py
0fe0123926d8f3bed47ddd88db91bc709c442b12
[]
no_license
Jaamunozr/Archivos-python
d9996d3d10ff8429cd1b4c2b396016a3a5482889
1f0af9ba08f12ac27e111fcceed49bbcf3b39657
refs/heads/master
2022-08-05T14:49:45.178561
2022-07-13T13:44:39
2022-07-13T13:44:39
244,073,267
0
0
null
null
null
null
UTF-8
Python
false
false
5,848
py
import os import pylab as pl from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter import numpy as np #------------------------------------------------------------------------------ os.system("clear") fig = pl.figure() axx = Axes3D(fig) raiz=np.sqrt ln=np.log puntoX=float(0) puntoY=float(0) #puntoX=float(input("Seleccione la coordenada en X donde desea calcular el potencial: ")) #puntoY=float(input("Seleccione la coordenada en Y donde desea calcular el potencial: ")) print("Calculando ...") #------------------------------------------------------------------------------ Xa = np.arange(-10, 10, 0.1) #Rango de coordenadas de X Ya = np.arange(-10, 10, 0.1) #Rango de coordenadas de Y l = 2 #Longitud del electrodo [m] rho= 100 #Resistividad de terrreno [Ohm/m] Ik=200 #Corriente de falla [A] (Total) Rad=0.01 #Radio del electrodo [m] Electrodos=8 #Número de electrodos Pos1=4 #Posición 1 en Y para analisis de grafica 2D Pos2=0 #Posición 2 en Y para analisis de grafica 2D #------------------------------------------------------------------------------ #Posición de los electrodos #------------------------------------------------------------------------------ P=np.array([ [-4,-4], #Electrodo A [0,-4], #Electrodo B [4,-4], #Electrodo C [-4,0], #Electrodo D [4,0], #Electrodo E [-4,4], #Electrodo F [0,4], #Electrodo G [4,4] #Electrodo H ]) #------------------------------------------------------------------------------ E=Electrodos-1 ik=Ik/Electrodos Vt=np.zeros((np.count_nonzero(Xa),np.count_nonzero(Ya))) m=np.zeros((Electrodos,1)) V=np.zeros((Electrodos,1)) k=0 m2=np.zeros((Electrodos,1)) V2=np.zeros((Electrodos,1)) #------------------------------------------------------------------------------ #Cálculo del punto ingresado #------------------------------------------------------------------------------ i=0 while i<=E: m2[i][0] =round(raiz((((P[i][0])-puntoX)**2)+(((P[i][1])-puntoY)**2)),4) o,u=((P[i][0])-puntoX),((P[i][1])-puntoY) if ((o ==0) and (u==0)) or (m2[i][0]==0): #print("Elementos de matriz",k,t, "x,y",P[i][0],P[i][1],"punto de eje",X,Y ) m2[i][0]=Rad V2[i][0] =ln((l+raiz((m2[i][0])**2+l**2))/(m2[i][0])) i += 1 Vt2=(np.sum(V2)*(rho*ik))/(2*np.pi*l) print("El potencial en el punto (",puntoX,",",puntoY,"), es de",round(Vt2,3),"[V]") #------------------------------------------------------------------------------ #Cálculo de la malla #------------------------------------------------------------------------------ Vxy = [1] * (np.count_nonzero(Ya)) while k<np.count_nonzero(Ya): Y=round(Ya[k],3) t=0 while t<np.count_nonzero(Xa): X=round(Xa[t],3) i=0 while i<=E: m[i][0] =round(raiz((((P[i][0])-X)**2)+(((P[i][1])-Y)**2)),4) o,u=((P[i][0])-X),((P[i][1])-Y) if ((o ==0) and (u==0)) or (m[i][0]==0): #print("Elementos de matriz",k,t, "x,y",P[i][0],P[i][1],"punto de eje",X,Y ) m[i][0]=Rad V[i][0] =ln((l+raiz((m[i][0])**2+l**2))/(m[i][0])) i += 1 Vt[k][t]=np.sum(V) if Y==Pos1: Vxa=Vt[k] if Y==Pos2: Vxb=Vt[k] if (Y==X) and ((X-Y)==0): Vxy[k]=Vt[k][t]*(rho*ik)/(2*np.pi*l) t +=1 k +=1 Vtt=(Vt*(rho*ik))/(2*np.pi*l) Vxa=(Vxa*(rho*ik))/(2*np.pi*l) Vxb=(Vxb*(rho*ik))/(2*np.pi*l) aa=np.where(np.amax(Vtt) == Vtt) print ("Valor máximo de tensión (GPR):",round(Vtt[::].max(),3),"[V], en posición: (",round(Xa[aa[0][0]],2),",",round(Ya[aa[1][0]],2),")") bb=np.where(np.amin(Vtt) == Vtt) print("Valor de Resistencia de puesta a tierra:", (round(Vtt[::].max(),3)/Ik), "[Ohm]") #print ("Valor mínimo de tensión:",round(Vtt[::].min(),3),"[V], en posición: (",round(Xa[bb[0][0]],2),",",round(Ya[bb[1][0]],2),")") print ("Número de elementos de Vt:",np.count_nonzero(Vtt)) #------------------------------------------------------------------------------ # GRAFICAS 3D #------------------------------------------------------------------------------ # Configurar una figura dos veces más alta que ancha #fig = plt.figure(figsize=plt.figaspect(0.2)) #fig = plt.figure(4,figsize=(6,4.5)) #(Ancho, alto) #fig.suptitle('Potencial') fig = plt.figure(figsize=plt.figaspect(2.)) fig.suptitle('A tale of 2 subplots') # Primera imagen a imprimir ax = fig.add_subplot(2, 2, 1, projection='3d') X, Y = np.meshgrid(Xa, Ya) #surf = ax.plot_surface(X, Y, Vtt, cmap = cm.get_cmap("jet"))#, antialiased=False) surf = ax.plot_surface(X, Y, Vtt, rstride=1, cstride=1, linewidth=0, antialiased=False) ax.set_zlim(300, 1800) #fig.colorbar(surf) #------------------------------------------------------------------------------ #Graficas en 2D #------------------------------------------------------------------------------ x1=Xa ax = fig.add_subplot(2, 2, 2) ax.plot(x1, Vxa, color="blue", linewidth=1.0, linestyle="-") ax.title.set_text('Eje X1 vs V') ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) ax.set_ylabel('Grafica 1') ax = fig.add_subplot(2, 2, 3) ax.plot(x1, Vxb, color="red", linewidth=1.0, linestyle="-") ax.title.set_text('Eje X2 vs V') ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) ax.set_ylabel('Grafica 2') ax = fig.add_subplot(2, 2, 4) ax.plot(x1, Vxy, color="green", linewidth=1.0, linestyle="-") ax.title.set_text('Eje X,Y vs V') ax.grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) ax.set_ylabel('Grafica 3') plt.pause(25) pl.savefig('tierras.pdf')
423824d04b9ff1a989d3a18f132c057b03f82f22
4554f8d3ab1a6267b17dad2b4d2c47b0abe8d746
/benchmarking/remote/devices.py
c7cacd80d2eb8e3a4eb17eebb98a6ac45237cf32
[ "Apache-2.0" ]
permissive
jteller/FAI-PEP
44fead3ca26f4844067d455c86ac8c5bfaf79a14
73b8a08815675135e9da7d68375d1218cbd04eaa
refs/heads/master
2020-04-29T06:04:19.197966
2019-03-15T23:32:54
2019-03-15T23:32:54
175,904,011
0
0
Apache-2.0
2019-03-15T23:30:04
2019-03-15T23:30:04
null
UTF-8
Python
false
false
2,484
py
#!/usr/bin/env python ############################################################################## # Copyright 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. ############################################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import os from utils.devices import devices as devices_dict class Devices(object): def __init__(self, filename=None): if filename: # if the user provides filename, we will load it. assert os.path.isfile(filename), \ "Device file {} does not exist".format(filename) with open(filename, "r") as f: self.devices = json.load(f) else: # otherwise read from internal self.devices = devices_dict self._elaborateDevices() def getFullNames(self, devices): names = devices.split(",") new_names = [self.devices[name]["name"] if name in self.devices else name for name in names] return ",".join(new_names) def getAbbrs(self, abbr): if abbr in self.devices: device = self.devices[abbr] if "abbr" in device: return device["abbr"] return None def _elaborateDevices(self): device_abbr = [] for name, _ in self.devices.items(): device = self.devices[name] assert "name" in device, \ "Field name is required in devices" assert device["name"] == name, \ "Device key ({}) and name ({})".format(name, device["name"]) + \ " do not match" if "abbr" in device: assert isinstance(device["abbr"], list), \ "Abbreviations for {} needs to be a list".format(name) for abbr in device["abbr"]: device_abbr.append((device, abbr)) for device_abbr_pair in device_abbr: self._elaborateOneDevice(device_abbr_pair[0], device_abbr_pair[1]) def _elaborateOneDevice(self, device, abbr): assert abbr not in self.devices, "Abbreviation " + \ "{} is already specified in the device list".format(abbr) self.devices[abbr] = device
431a60378e86b4b85d841143ab2f513bb7bbeeff
1b5cc8dc487da59455dfe6749796870d51d5ab87
/src/collective/iptvusp/tests/test_uspvideo.py
72b74796685ac00b3964064bc7a733813671c2c5
[]
no_license
simplesconsultoria/collective.iptvusp
eddcd726a800933127b04959bba90c63210049dc
89b14ee4a01e19ef5cd7198c5bdf808ef555f1f0
refs/heads/master
2021-01-01T18:29:41.272115
2013-03-12T19:01:25
2013-03-12T19:01:25
6,388,881
0
0
null
null
null
null
UTF-8
Python
false
false
1,806
py
# -*- coding: utf-8 -*- import unittest2 as unittest from zope.component import createObject from zope.component import queryUtility from plone.app.testing import TEST_USER_ID from plone.app.testing import setRoles from plone.dexterity.interfaces import IDexterityFTI from plone.app.dexterity.behaviors.exclfromnav import IExcludeFromNavigation from collective.iptvusp.content import IUSPVideo from collective.iptvusp.testing import INTEGRATION_TESTING class CoverIntegrationTestCase(unittest.TestCase): layer = INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] setRoles(self.portal, TEST_USER_ID, ['Manager']) self.portal.invokeFactory('Folder', 'test-folder') setRoles(self.portal, TEST_USER_ID, ['Member']) self.folder = self.portal['test-folder'] self.folder.invokeFactory('iptvusp.uspvideo', 'c1', template_layout='Layout A') self.c1 = self.folder['c1'] def test_adding(self): self.assertTrue(IUSPVideo.providedBy(self.c1)) def test_fti(self): fti = queryUtility(IDexterityFTI, name='iptvusp.uspvideo') self.assertNotEqual(None, fti) def test_schema(self): fti = queryUtility(IDexterityFTI, name='iptvusp.uspvideo') schema = fti.lookupSchema() self.assertEqual(IUSPVideo, schema) def test_factory(self): fti = queryUtility(IDexterityFTI, name='iptvusp.uspvideo') factory = fti.factory new_object = createObject(factory) self.assertTrue(IUSPVideo.providedBy(new_object)) def test_exclude_from_navigation_behavior(self): self.assertTrue(IExcludeFromNavigation.providedBy(self.c1))
6a28e7551bac14d5e50e838a962b64b49a7008ae
057722b227e9f51c78bd77b622859674016f19dc
/homework4/code/p7/trysvm.py
8783e7fd91174a983250421516e6938b0597d778
[]
no_license
walkerning/Homework-pattern_recognition
56508bc66d0932ad8c9899658d8229169d800551
843a79d1f4cc278839ade27a593ae66e603ac4ba
refs/heads/master
2021-03-19T15:30:55.581932
2017-05-31T15:51:22
2017-05-31T15:51:22
84,166,823
0
0
null
null
null
null
UTF-8
Python
false
false
1,740
py
# -*- coding: utf-8 -*- import numpy as np from sklearn import svm samples_w1 = np.array([[-3.0, 0.5, 2.9, -0.1, -4.0, -1.3, -3.4, -4.1, -5.1, 1.9], [-2.9, 8.7, 2.1, 5.2, 2.2, 3.7, 6.2, 3.4, 1.6, 5.1]]).T samples_w2 = np.array([[-2.0, -8.9, -4.2, -8.5, -6.7, -0.5, -5.3, -8.7, -7.1, -8.0], [-8.4, 0.2, -7.7, -3.2, -4.0, -9.2, -6.7, -6.4, -9.7, -6.3]]).T def transform_data(data): # return 1 x1 x2 x1**2 x2**2 x1x2 return np.hstack((np.ones((data.shape[0], 1)), data, data**2, (data[:, 0] * data[:, 1])[:, np.newaxis])) def main(): # set misclassification penalty to a large enough value trans_samples_w1 = transform_data(samples_w1) trans_samples_w2 = transform_data(samples_w2) # data = np.vstack((trans_samples_w1[0, :], trans_samples_w2[0, :])) # labels = [0, 1] # res = svm.SVC(C=1e10, kernel="linear").fit(data, labels) # m = np.sqrt(res.coef_[0].dot(res.coef_[0])) # margin1 = (res.coef_.dot(trans_samples_w1[0,:]) + res.intercept_) / m # margin2 = (res.coef_.dot(trans_samples_w2[0,:]) + res.intercept_) / m # print "margin of w1 {}: {}; margin of w2 {}: {}".format(trans_samples_w1[0, :], margin1, # trans_samples_w2[0, :], margin2) for num in range(1, samples_w1.shape[0]+1): data = np.vstack((trans_samples_w1[:num, :], trans_samples_w2[:num, :])) labels = np.hstack((np.zeros(num), np.ones(num))) res = svm.SVC(C=1e10, kernel="linear").fit(data, labels) print "sample number: {}, coef: {}, b: {}, margin: {}".format(num*2, res.coef_, res.intercept_, np.sqrt(1/(res.coef_[0].dot(res.coef_[0])))) if __name__ == "__main__": main()
f6d6555a8ba6236ab372c46d3874d38c6e764625
db7660d3541c26b418ea84ca08fbf41f9ebd726b
/brax/jumpy.py
7486fd1ac0b8ac9b44e57f3f0ed88c4c3ca5f7a4
[ "Apache-2.0" ]
permissive
proceduralia/brax
8727ada08184fe9f60356d17a15ea671df0906d6
d54dc479a32e5e99641cde921c7988d69cd5bb7b
refs/heads/main
2023-08-27T15:39:44.618414
2021-11-08T21:35:42
2021-11-08T21:37:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,680
py
# Copyright 2021 The Brax Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # pylint:disable=redefined-builtin """Numpy backend for JAX that is called for non-jit/non-jax arrays.""" from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar, Union import jax from jax import core from jax import numpy as jnp import numpy as onp ndarray = Union[onp.ndarray, jnp.ndarray] # pylint:disable=invalid-name tree_map = jax.tree_map # works great with jax or numpy as-is pi = onp.pi inf = onp.inf float32 = onp.float32 int32 = onp.int32 def _in_jit() -> bool: """Returns true if currently inside a jax.jit call.""" return core.cur_sublevel().level > 0 def _which_np(*args): """Returns np or jnp depending on args.""" for a in args: if isinstance(a, jnp.ndarray): return jnp return onp F = TypeVar('F', bound=Callable) def vmap(fun: F, include: Optional[Sequence[bool]] = None) -> F: """Creates a function which maps ``fun`` over argument axes.""" if _in_jit(): in_axes = 0 if include: in_axes = [0 if inc else None for inc in include] return jax.vmap(fun, in_axes=in_axes) def _batched(*args): args_flat, args_treedef = jax.tree_flatten(args) vargs, vargs_idx = [], [] rets = [] if include: for i, (inc, arg) in enumerate(zip(include, args_flat)): if inc: vargs.append(arg) vargs_idx.append(i) else: vargs, vargs_idx = list(args_flat), list(range(len(args_flat))) for zvargs in zip(*vargs): for varg, idx in zip(zvargs, vargs_idx): args_flat[idx] = varg args_unflat = jax.tree_unflatten(args_treedef, args_flat) rets.append(fun(*args_unflat)) return jax.tree_map(lambda *x: onp.stack(x), *rets) return _batched Carry = TypeVar('Carry') X = TypeVar('X') Y = TypeVar('Y') def scan(f: Callable[[Carry, X], Tuple[Carry, Y]], init: Carry, xs: X, length: Optional[int] = None, reverse: bool = False, unroll: int = 1) -> Tuple[Carry, Y]: """Scan a function over leading array axes while carrying along state.""" if _in_jit(): return jax.lax.scan(f, init, xs, length, reverse, unroll) else: xs_flat, xs_tree = jax.tree_flatten(xs) carry = init ys = [] maybe_reversed = reversed if reverse else lambda x: x for i in maybe_reversed(range(length)): xs_slice = [x[i] for x in xs_flat] carry, y = f(carry, jax.tree_unflatten(xs_tree, xs_slice)) ys.append(y) stacked_y = jax.tree_map(lambda *y: onp.vstack(y), *maybe_reversed(ys)) return carry, stacked_y def take(tree: Any, i: Union[ndarray, Sequence[int]], axis: int = 0) -> Any: """Returns tree sliced by i.""" np = _which_np(i) if isinstance(i, list) or isinstance(i, tuple): i = np.array(i, dtype=int) return jax.tree_map(lambda x: np.take(x, i, axis=axis, mode='clip'), tree) def norm(x: ndarray, axis: Optional[Union[Tuple[int, ...], int]] = None) -> ndarray: """Returns the array norm.""" return _which_np(x, axis).linalg.norm(x, axis=axis) def index_update(x: ndarray, idx: ndarray, y: ndarray) -> ndarray: """Pure equivalent of x[idx] = y.""" if _which_np(x) is jnp: return x.at[idx].set(y) x = onp.copy(x) x[idx] = y return x def safe_norm(x: ndarray, axis: Optional[Union[Tuple[int, ...], int]] = None) -> ndarray: """Calculates a linalg.norm(x) that's safe for gradients at x=0. Avoids a poorly defined gradient for jnp.linal.norm(0) see https://github.com/google/jax/issues/3058 for details Args: x: A jnp.array axis: The axis along which to compute the norm Returns: Norm of the array x. """ np = _which_np(x) if np is jnp: is_zero = jnp.allclose(x, 0.) # temporarily swap x with ones if is_zero, then swap back x = jnp.where(is_zero, jnp.ones_like(x), x) n = jnp.linalg.norm(x, axis=axis) n = jnp.where(is_zero, 0., n) else: n = onp.linalg.norm(x, axis=axis) return n def any(a: ndarray, axis: Optional[int] = None) -> ndarray: """Test whether any array element along a given axis evaluates to True.""" return _which_np(a).any(a, axis=axis) def all(a: ndarray, axis: Optional[int] = None) -> ndarray: """Test whether all array elements along a given axis evaluate to True.""" return _which_np(a).all(a, axis=axis) def mean(a: ndarray, axis: Optional[int] = None) -> ndarray: """Compute the arithmetic mean along the specified axis.""" return _which_np(a).mean(a, axis=axis) def arange(start: int, stop: int) -> ndarray: """Return evenly spaced values within a given interval.""" return _which_np().arange(start, stop) def dot(x: ndarray, y: ndarray) -> ndarray: """Returns dot product of two arrays.""" return _which_np(x, y).dot(x, y) def outer(a: ndarray, b: ndarray) -> ndarray: """Compute the outer product of two vectors.""" return _which_np(a, b).outer(a, b) def matmul(x1: ndarray, x2: ndarray) -> ndarray: """Matrix product of two arrays.""" return _which_np(x1, x2).matmul(x1, x2) def inv(a: ndarray) -> ndarray: """Compute the (multiplicative) inverse of a matrix.""" return _which_np(a).linalg.inv(a) def square(x: ndarray) -> ndarray: """Return the element-wise square of the input.""" return _which_np(x).square(x) def repeat(a: ndarray, repeats: Union[int, ndarray]) -> ndarray: """Repeat elements of an array.""" return _which_np(a, repeats).repeat(a, repeats=repeats) def floor(x: ndarray) -> ndarray: """Returns the floor of the input, element-wise..""" return _which_np(x).floor(x) def cross(x: ndarray, y: ndarray) -> ndarray: """Returns cross product of two arrays.""" return _which_np(x, y).cross(x, y) def sin(angle: ndarray) -> ndarray: """Returns trigonometric sine, element-wise.""" return _which_np(angle).sin(angle) def cos(angle: ndarray) -> ndarray: """Returns trigonometric cosine, element-wise.""" return _which_np(angle).cos(angle) def arctan2(x1: ndarray, x2: ndarray) -> ndarray: """Returns element-wise arc tangent of x1/x2 choosing the quadrant correctly.""" return _which_np(x1, x2).arctan2(x1, x2) def arccos(x: ndarray) -> ndarray: """Trigonometric inverse cosine, element-wise.""" return _which_np(x).arccos(x) def logical_not(x: ndarray) -> ndarray: """Returns the truth value of NOT x element-wise.""" return _which_np(x).logical_not(x) def multiply(x1: ndarray, x2: ndarray) -> ndarray: """Multiply arguments element-wise.""" return _which_np(x1, x2).multiply(x1, x2) def minimum(x1: ndarray, x2: ndarray) -> ndarray: """Element-wise minimum of array elements.""" return _which_np(x1, x2).minimum(x1, x2) def amin(x: ndarray) -> ndarray: """Returns the minimum along a given axis.""" return _which_np(x).amin(x) def exp(x: ndarray) -> ndarray: """Returns the exponential of all elements in the input array.""" return _which_np(x).exp(x) def sign(x: ndarray) -> ndarray: """Returns an element-wise indication of the sign of a number.""" return _which_np(x).sign(x) def sum(a: ndarray, axis: Optional[int] = None): """Returns sum of array elements over a given axis.""" return _which_np(a).sum(a, axis=axis) def random_prngkey(seed: int) -> ndarray: """Returns a PRNG key given a seed.""" if _which_np() is jnp: return jax.random.PRNGKey(seed) else: rng = onp.random.default_rng(seed) return rng.integers(low=0, high=2**32, dtype='uint32', size=2) def random_uniform(rng: ndarray, shape: Tuple[int, ...] = (), low: Optional[float] = 0.0, high: Optional[float] = 1.0) -> ndarray: """Sample uniform random values in [low, high) with given shape/dtype.""" if _which_np(rng) is jnp: return jax.random.uniform(rng, shape=shape, minval=low, maxval=high) else: return onp.random.default_rng(rng).uniform(size=shape, low=low, high=high) def random_split(rng: ndarray, num: int = 2) -> ndarray: """Splits a PRNG key into num new keys by adding a leading axis.""" if _which_np(rng) is jnp: return jax.random.split(rng, num=num) else: rng = onp.random.default_rng(rng) return rng.integers(low=0, high=2**32, dtype='uint32', size=(num, 2)) def segment_sum(data: ndarray, segment_ids: ndarray, num_segments: Optional[int] = None) -> ndarray: """Computes the sum within segments of an array.""" if _which_np(data, segment_ids) is jnp: s = jax.ops.segment_sum(data, segment_ids, num_segments) else: if num_segments is None: num_segments = onp.amax(segment_ids) + 1 s = onp.zeros((num_segments,) + data.shape[1:]) onp.add.at(s, segment_ids, data) return s def top_k(operand: ndarray, k: int) -> ndarray: """Returns top k values and their indices along the last axis of operand.""" if _which_np(operand) is jnp: return jax.lax.top_k(operand, k) else: ind = onp.argpartition(operand, -k)[-k:] return operand[ind], ind def stack(x: List[ndarray], axis=0) -> ndarray: """Join a sequence of arrays along a new axis.""" return _which_np(*x).stack(x, axis=axis) def concatenate(x: Sequence[ndarray], axis=0) -> ndarray: """Join a sequence of arrays along an existing axis.""" return _which_np(*x).concatenate(x, axis=axis) def sqrt(x: ndarray) -> ndarray: """Returns the non-negative square-root of an array, element-wise.""" return _which_np(x).sqrt(x) def where(condition: ndarray, x: ndarray, y: ndarray) -> ndarray: """Return elements chosen from `x` or `y` depending on `condition`.""" return _which_np(condition, x, y).where(condition, x, y) def diag(v: ndarray, k: int = 0) -> ndarray: """Extract a diagonal or construct a diagonal array.""" return _which_np(v).diag(v, k) def clip(a: ndarray, a_min: ndarray, a_max: ndarray) -> ndarray: """Clip (limit) the values in an array.""" return _which_np(a, a_min, a_max).clip(a, a_min, a_max) def eye(n: int) -> ndarray: """Return a 2-D array with ones on the diagonal and zeros elsewhere.""" return _which_np().eye(n) def zeros(shape, dtype=float) -> ndarray: """Return a new array of given shape and type, filled with zeros.""" return _which_np().zeros(shape, dtype=dtype) def zeros_like(a: ndarray) -> ndarray: """Return an array of zeros with the same shape and type as a given array.""" return _which_np(a).zeros_like(a) def ones(shape, dtype=float) -> ndarray: """Return a new array of given shape and type, filled with ones.""" return _which_np().ones(shape, dtype=dtype) def ones_like(a: ndarray) -> ndarray: """Return an array of ones with the same shape and type as a given array.""" return _which_np(a).ones_like(a) def reshape(a: ndarray, newshape: Union[Tuple[int, ...], int]) -> ndarray: """Gives a new shape to an array without changing its data.""" return _which_np(a).reshape(a, newshape) def array(object: Any, dtype=None) -> ndarray: """Creates an array given a list.""" try: np = _which_np(*object) except TypeError: np = _which_np(object) # object is not iterable (e.g. primitive type) return np.array(object, dtype)
d2f6e5faa8e1f124af00e0502dca3ad30670785e
b5fabc6c6de064690f8d4ee423001cf9365a3d9f
/flash/image/segmentation/model.py
9296db60cbcff1e6220d5aee051ddb36549a8b1f
[ "Apache-2.0" ]
permissive
dmarx/lightning-flash
021dfd76bde6e30309f14feb5853020b0babe90d
4cda031c1f9c8d8754fd36b5720d2a5a7d866765
refs/heads/master
2023-09-06T06:24:29.856354
2021-11-24T23:38:14
2021-11-24T23:38:14
422,352,910
0
1
null
null
null
null
UTF-8
Python
false
false
7,182
py
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any, Dict, List, Optional, Union import torch from torch import nn from torch.nn import functional as F from torchmetrics import IoU from flash.core.classification import ClassificationTask from flash.core.data.io.input import DataKeys from flash.core.data.io.output_transform import OutputTransform from flash.core.registry import FlashRegistry from flash.core.utilities.imports import _KORNIA_AVAILABLE from flash.core.utilities.isinstance import _isinstance from flash.core.utilities.types import ( LOSS_FN_TYPE, LR_SCHEDULER_TYPE, METRICS_TYPE, OPTIMIZER_TYPE, OUTPUT_TRANSFORM_TYPE, OUTPUT_TYPE, ) from flash.image.segmentation.backbones import SEMANTIC_SEGMENTATION_BACKBONES from flash.image.segmentation.heads import SEMANTIC_SEGMENTATION_HEADS from flash.image.segmentation.output import SegmentationLabels if _KORNIA_AVAILABLE: import kornia as K class SemanticSegmentationOutputTransform(OutputTransform): def per_sample_transform(self, sample: Any) -> Any: resize = K.geometry.Resize(sample[DataKeys.METADATA]["size"][-2:], interpolation="bilinear") sample[DataKeys.PREDS] = resize(sample[DataKeys.PREDS]) sample[DataKeys.INPUT] = resize(sample[DataKeys.INPUT]) return super().per_sample_transform(sample) class SemanticSegmentation(ClassificationTask): """``SemanticSegmentation`` is a :class:`~flash.Task` for semantic segmentation of images. For more details, see :ref:`semantic_segmentation`. Args: num_classes: Number of classes to classify. backbone: A string or model to use to compute image features. backbone_kwargs: Additional arguments for the backbone configuration. head: A string or (model, num_features) tuple to use to compute image features. head_kwargs: Additional arguments for the head configuration. pretrained: Use a pretrained backbone. loss_fn: Loss function for training. optimizer: Optimizer to use for training. lr_scheduler: The LR scheduler to use during training. metrics: Metrics to compute for training and evaluation. Can either be an metric from the `torchmetrics` package, a custom metric inherenting from `torchmetrics.Metric`, a callable function or a list/dict containing a combination of the aforementioned. In all cases, each metric needs to have the signature `metric(preds,target)` and return a single scalar tensor. Defaults to :class:`torchmetrics.IOU`. learning_rate: Learning rate to use for training. multi_label: Whether the targets are multi-label or not. output: The :class:`~flash.core.data.io.output.Output` to use when formatting prediction outputs. output_transform: :class:`~flash.core.data.io.output_transform.OutputTransform` use for post processing samples. """ output_transform_cls = SemanticSegmentationOutputTransform backbones: FlashRegistry = SEMANTIC_SEGMENTATION_BACKBONES heads: FlashRegistry = SEMANTIC_SEGMENTATION_HEADS required_extras: str = "image" def __init__( self, num_classes: int, backbone: Union[str, nn.Module] = "resnet50", backbone_kwargs: Optional[Dict] = None, head: str = "fpn", head_kwargs: Optional[Dict] = None, pretrained: Union[bool, str] = True, loss_fn: LOSS_FN_TYPE = None, optimizer: OPTIMIZER_TYPE = "Adam", lr_scheduler: LR_SCHEDULER_TYPE = None, metrics: METRICS_TYPE = None, learning_rate: float = 1e-3, multi_label: bool = False, output: OUTPUT_TYPE = None, output_transform: OUTPUT_TRANSFORM_TYPE = None, ) -> None: if metrics is None: metrics = IoU(num_classes=num_classes) if loss_fn is None: loss_fn = F.cross_entropy # TODO: need to check for multi_label if multi_label: raise NotImplementedError("Multi-label not supported yet.") super().__init__( model=None, loss_fn=loss_fn, optimizer=optimizer, lr_scheduler=lr_scheduler, metrics=metrics, learning_rate=learning_rate, output=output or SegmentationLabels(), output_transform=output_transform or self.output_transform_cls(), ) self.save_hyperparameters() if not backbone_kwargs: backbone_kwargs = {} if not head_kwargs: head_kwargs = {} if isinstance(backbone, nn.Module): self.backbone = backbone else: self.backbone = self.backbones.get(backbone)(**backbone_kwargs) self.head: nn.Module = self.heads.get(head)( backbone=self.backbone, num_classes=num_classes, pretrained=pretrained, **head_kwargs ) self.backbone = self.head.encoder def training_step(self, batch: Any, batch_idx: int) -> Any: batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET]) return super().training_step(batch, batch_idx) def validation_step(self, batch: Any, batch_idx: int) -> Any: batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET]) return super().validation_step(batch, batch_idx) def test_step(self, batch: Any, batch_idx: int) -> Any: batch = (batch[DataKeys.INPUT], batch[DataKeys.TARGET]) return super().test_step(batch, batch_idx) def predict_step(self, batch: Any, batch_idx: int, dataloader_idx: int = 0) -> Any: batch_input = batch[DataKeys.INPUT] batch[DataKeys.PREDS] = super().predict_step(batch_input, batch_idx, dataloader_idx=dataloader_idx) return batch def forward(self, x) -> torch.Tensor: res = self.head(x) # some frameworks like torchvision return a dict. # In particular, torchvision segmentation models return the output logits # in the key `out`. if _isinstance(res, Dict[str, torch.Tensor]): res = res["out"] return res @classmethod def available_pretrained_weights(cls, backbone: str): result = cls.backbones.get(backbone, with_metadata=True) pretrained_weights = None if "weights_paths" in result["metadata"]: pretrained_weights = list(result["metadata"]["weights_paths"]) return pretrained_weights @staticmethod def _ci_benchmark_fn(history: List[Dict[str, Any]]): """This function is used only for debugging usage with CI.""" assert history[-1]["val_iou"] > 0.2
bf2bb21fe32c046e31ac269a94e444f91dc0217b
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03626/s873858203.py
5c64e4b78d0537220084f2cc138a77120c711579
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
440
py
MOD = 1000000007 n = int(input()) s1 = input() s2 = input() if s1[0] == s2[0]: ans = 3 i = 1 prev = 1 else: ans = 6 i = 2 prev = 2 while i<n: if s1[i] == s2[i]: i += 1 if prev == 1: ans *= 2 else: prev = 1 else: i += 2 if prev == 1: ans *= 2 prev = 2 else: ans *= 3 ans %= MOD print(ans)
deb150440060e0d6c968a2ccf2812970012b495a
27c4e774f053594473da202c1c45dcbf237465be
/Scorm.py
566403fdd0e407806057a4daa6e2727586ed572a
[]
no_license
Gamboua/zope-migration
34e6b27962859352fe08a4277a8215b36b01889c
7a83ed67c5ea561bfa8aa300728390b7220f3633
refs/heads/master
2020-12-25T14:49:22.173420
2017-10-19T20:47:50
2017-10-19T20:47:50
67,830,154
0
1
null
2016-10-20T21:42:09
2016-09-09T20:20:57
PHP
UTF-8
Python
false
false
1,910
py
import paramiko import os from scp import SCPClient from config import * from Command import Command import random, string class Scorm: def __init__(self, scorm, course): self.course = course self.scp = None self.type = 'scorm' self.section = 0 self.folder = self.get_if_exists('folder', scorm) self.title = self.get_if_exists('title', scorm) def get_if_exists(self, parameter, json): return json.get(parameter) if parameter in json else None def scorm_add(self): self.scorm_import_folder() zip_name = self.scorm_zip() Command.command_execute(Command.activity_create_command( options=self.get_scorm_options(zip_name), type=self.type, id=self.course.id )) def get_scorm_options(self, name): params = [] if self.section is not None: params.append('--section %s' % self.section) if self.title: params.append('--name "%s"' % self.title) params.append('--filepath /tmp/%s.zip' % name) return ' '.join(params) def scorm_zip(self): name = ''.join(random.choice(string.ascii_letters) for x in range(8)) os.chdir(self.folder) os.system('zip -r /tmp/%s *' % name) os.chdir(os.path.dirname(os.path.abspath(__file__))) return name def scorm_import_folder(self): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(REMOTE_SCORM_SERVER, REMOTE_SCORM_PORT, REMOTE_SCORM_USER) scp = SCPClient(client.get_transport()) if not os.path.isdir('/opt/zope298/courses'): os.makedirs('/opt/zope298/courses') scp.get( self.folder, '/opt/zope298/courses/', recursive=True ) scp.close()
4a5b7c6844ca194b50ed70323648cba57b6e0b8d
c6e5bbafd810d23e0ee46d69026cba35339d1dbd
/accounts/managers.py
42d3aae755fba1358031994ccd3a06d4ca8dcdd1
[]
no_license
mfonism/django-inqueerstigate
9c8b729848bf3df9fb9ec991ec47391b69ad7b66
af5420bf8adf6aa89533cd1462d9eeed6e8c88db
refs/heads/main
2023-05-26T12:59:55.774989
2021-06-07T11:46:48
2021-06-07T11:46:48
323,681,513
0
0
null
null
null
null
UTF-8
Python
false
false
1,179
py
from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, password, **extra_fields)
847e83de22c9dbcb04f87362a0d956c786584799
caace044baf7a6f2b0bda65ae361eed06bddfc3c
/dailyQuestion/2020/2020-06/06-01/python/solution_items.py
1f7df5de69c465f7a57e918ca5eee350c02c2603
[ "Apache-2.0" ]
permissive
russellgao/algorithm
fd6126e89c40d7d351c53bbd5fde690c9be899ef
ad5e724d20a8492b8eba03fc0f24e4ff5964b3ea
refs/heads/master
2023-03-28T03:00:02.370660
2021-03-28T10:56:38
2021-03-28T10:56:38
259,038,372
3
0
null
null
null
null
UTF-8
Python
false
false
1,550
py
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # 迭代 def sortList(head: ListNode) -> ListNode: head_len = 0 invc = 1 h = head while h : head_len += 1 h = h.next result = ListNode(0) result.next = head while invc <= head_len : pre = result h = result.next while h : h1 ,i = h , invc while i and h : i -= 1 h = h.next if i : break h2, i = h, invc while i and h : i -= 1 h = h.next c1, c2 = invc, invc-i while c1 and c2 : if h1.val > h2.val : pre.next = h2 h2 = h2.next c2 -= 1 else : pre.next = h1 h1 = h1.next c1 -= 1 pre = pre.next pre.next = h1 if c1 else h2 while c1 > 0 or c2 > 0 : pre = pre.next c1 -= 1 c2 -= 1 pre.next = h invc <<= 1 return result.next if __name__ == "__main__" : node = ListNode(4) node.next = ListNode(2) node.next.next = ListNode(1) node.next.next.next = ListNode(3) node.next.next.next.next = ListNode(5) result = sortList(node) while result : print(result.val) result = result.next print()
db0454c4c301f4b509ebb198c08bac7e87c6a3bd
d19d16ddc922b0915aff982568c5c71ee58fb8b9
/dataset/utils.py
f13a627e795ae92c6dca77770e719e98d0542e2e
[]
no_license
zhaoyuzhi/HSGAN
036a6fec722d564f9b203f6032bf47039c1eadd4
f974761ec4a65ef58283ae4ccba618b97e79c4bc
refs/heads/main
2023-08-03T10:06:05.195187
2023-07-27T14:21:54
2023-07-27T14:21:54
337,642,689
6
0
null
null
null
null
UTF-8
Python
false
false
2,688
py
import os import numpy as np # ---------------------------------------- # PATH processing # ---------------------------------------- def check_path(path): if not os.path.exists(path): os.makedirs(path) def get_files(path): # read a folder, return the complete path ret = [] for root, dirs, files in os.walk(path): for filespath in files: ret.append(os.path.join(root, filespath)) return ret def get_jpgs(path): # read a folder, return the image name ret = [] for root, dirs, files in os.walk(path): for filespath in files: ret.append(filespath) return ret def get_mats(path): # read a folder, return the image name ret = [] for root, dirs, files in os.walk(path): for filespath in files: if filespath[-3:] == 'mat': ret.append(os.path.join(root, filespath)) return ret def get_mats_name(path): # read a folder, return the image name ret = [] for root, dirs, files in os.walk(path): for filespath in files: if filespath[-3:] == 'mat': ret.append(filespath.split('.')[0]) return ret def get_bmps(path): # read a folder, return the image name ret = [] for root, dirs, files in os.walk(path): for filespath in files: if filespath[-3:] == 'bmp': ret.append(os.path.join(root, filespath)) return ret def get_pairs_name(path): # read a folder, return the image name ret = [] for root, dirs, files in os.walk(path): for filespath in files: if filespath[-3:] == 'mat': ret.append(filespath.split('.')[0]) return ret # ---------------------------------------- # PATH processing # ---------------------------------------- def text_readlines(filename): # Try to read a txt file and return a list.Return [] if there was a mistake. try: file = open(filename, 'r') except IOError: error = [] return error content = file.readlines() # This for loop deletes the EOF (like \n) for i in range(len(content)): content[i] = content[i][:len(content[i])-1] file.close() return content def text_save(content, filename, mode = 'a'): # save a list to a txt # Try to save a list variable in txt file. file = open(filename, mode) for i in range(len(content)): file.write(str(content[i]) + '\n') file.close() def savetxt(name, loss_log): np_loss_log = np.array(loss_log) np.savetxt(name, np_loss_log)
971930662e9f48b55e5e7268f17b00a473b909c6
4fb5b869f6690b73e32a2d8624f5fc8954540b42
/pypiplot/examples.py
b73f61adfb29a23b32d768d116b50680a0502255
[ "MIT" ]
permissive
erdogant/pypiplot
cc8eb15f9b6855cba270256591ba8b1ec4ae41f6
2016cca3d0b4022cda1806c2c4b8c4eb2d31ee19
refs/heads/master
2023-04-16T03:26:26.935072
2023-02-21T23:46:01
2023-02-21T23:46:01
293,334,020
0
0
null
null
null
null
UTF-8
Python
false
false
3,271
py
import pypiplot # print(pypiplot.__version__) # print(dir(Pypiplot)) from pypiplot import Pypiplot # %% Update all libraries to date. pp = Pypiplot(username='erdogant', repo_type=['owner', 'fork']) pp.update() results = pp.stats() pp.plot_year(vmin=700) pp.plot() pp.plot_year() # %% Top 10 best repos pp = Pypiplot(username='erdogant', savepath='D://REPOS/pypiplot/repo_data/') # Get download statistics pp.stats() # Get top 10 repo=pp.results['data'].sum().sort_values()[-10:].index.values # Get stats for the top10 pp.stats(repo=repo) # Plot pp.plot() # pp.plot_year() # pp.plot_cal() # path = 'D://REPOS/erdogant.github.io/docs/imagesc/pypi/pypi_heatmap_full.html' pp.plot_heatmap(vmin=10, vmax=2000, cmap='interpolateOranges', path=path) # %% Plot # Init pp = Pypiplot(username='erdogant', savepath='D://REPOS/pypiplot/repo_data/') # Get download statistics results = pp.stats() # Store svg on github.io # path = 'D://REPOS/erdogant.github.io/docs/imagesc/pypi/pypi_heatmap.html' path = 'D://REPOS/erdogant.github.io/docs/imagesc/pypi/pypi_heatmap.html' path = 'C://temp/pypi_heatmap.html' pp.plot_year(path=path, vmin=700) # Store all repo info in github.io pp.plot(legend=False) # %% D3blocks pp = Pypiplot(username='d3blocks') pp.update(repo=['d3blocks']) pp.stats(repo='d3blocks') pp.plot() # %% pp = Pypiplot(username='erdogant') pp.stats(repo='distfit') pp.plot_year() pp.plot(vmin=25) # %% Update single repo pp.update(repo=['bnlearn']) pp.update(repo='bnlearn') results = pp.stats(repo=['distfit','pca', 'bnlearn']) pp.plot(legend=True) # %% Get some stats results = pp.stats(repo=['df2onehot','pca','bnlearn','ismember','thompson']) pp.plot(legend=True) # %% pp = Pypiplot(username='erdogant') pp.stats(repo='distfit') pp.plot_year() pp.plot(vmin=25) pp.stats(repo='worldmap') pp.plot_year() pp.stats(repo='hnet') pp.plot_year() pp.stats(repo='ismember') pp.plot_year() pp.stats(repo='flameplot') pp.plot_year() pp.stats(repo='pca') pp.plot_year() pp.stats() pp.stats(repo=['df2onehot','clustimage','bnlearn','distfit','pypickle','clusteval','findpeaks', 'kaplanmeier','pca','colourmap']) pp.results['data'].rolling(window=30).mean().plot(figsize=(15,10)) plt.grid(True) plt.xlabel('Time') plt.ylabel('Average nr. download based on a rolling window of 30 days') # pp.results['data'].cumsum().plot() pp.plot_year(vmin=100) pp.plot(vmin=25) pp.results['data'].cumsum().plot() # %% Plot bnlearn results = pp.stats(repo='bnlearn') pp.plot_year() # %% pp.update() results = pp.stats() pp.plot_year(vmin=700) pp.plot(vmin=25) # %% Plot # Init pp = Pypiplot(username='erdogant', savepath='D://REPOS/pypiplot/repo_data/') # Get download statistics results = pp.stats() # Store svg on github.io path = 'D://REPOS/erdogant.github.io/docs/imagesc/pypi/pypi_heatmap.html' path = 'C://temp/pypi_heatmap.html' pp.plot_year(path=path, vmin=700) # Store all repo info in github.io path = 'D://REPOS/erdogant.github.io/docs/imagesc/pypi/pypi_heatmap_repos.html' pp.plot(path=path, vmin=100) # %% from pypiplot import Pypiplot # results = pp.stats() pp.stats(repo=['df2onehot','clustimage','bnlearn','distfit','pypickle','clusteval','findpeaks', 'kaplanmeier','colourmap']) pp.plot_cal(method='mean', vmin=100) pp.plot(method='mean') # %%
a60ce595e94bd01b6f46c0cb382957eebfd7ab07
576cc83449e10fd3f98281970c46016ea7a5aea2
/Tensorflow/CNN/莫烦python02.py
2e08d2c51048bcd31c14f4a4a131722ae38111f1
[]
no_license
HotView/PycharmProjects
215ab9edd341e3293daebcf86d97537f8cd28d75
61393fe5ba781a8c1216a5cbe7e0d06149a10190
refs/heads/master
2020-06-02T07:41:53.608742
2019-11-13T08:31:57
2019-11-13T08:31:57
191,085,178
3
2
null
null
null
null
UTF-8
Python
false
false
1,519
py
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("data",one_hot=True) def add_layer(inputs,in_size,out_size,activaion_function = None): Weights = tf.Variable(tf.random_normal([in_size,out_size])) biases = tf.Variable(tf.zeros([1,out_size])+0.1) Wx_plus_b = tf.matmul(inputs,Weights)+biases if activaion_function is None: outputs = Wx_plus_b else: outputs =activaion_function(Wx_plus_b) return outputs def compute_accuracy(v_xs,v_ys): global prediction y_pre = sess.run(prediction,feed_dict={xs:v_xs}) correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) result = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys}) return result xs = tf.placeholder(tf.float32,[None,784]) ys = tf.placeholder(tf.float32,[None,10]) # add output layer prediction = add_layer(xs,784,10,activaion_function=tf.nn.softmax) # error crosss_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(crosss_entropy) sess =tf.Session() sess.run(tf.initialize_all_variables()) for i in range(5000): batch_xs,batch_ys = mnist.train.next_batch(100) sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys}) if i%50==0: print(compute_accuracy(mnist.test.images,mnist.test.labels))
6567d0f8b19425ebfd1cd990c73c0e2498f971f2
41294ab88364fbb40ee67fcc643a91cc355c25d5
/solution/accounting.py
368251986f18af4b2806c42760073666909b3c70
[]
no_license
tessajules/underpaid-customers-HB-homework
96e542cc736d03b1476c88c43cd931081b03926d
ec3526debea68ecbf7aed25d041baf26110e40b2
refs/heads/master
2021-05-28T22:11:25.106565
2015-04-10T02:56:36
2015-04-10T02:56:36
null
0
0
null
null
null
null
UTF-8
Python
false
false
969
py
MELON_COST = 1.00 def melon_payment_calculator(payment_data): """Calculate cost of melons and determine who has underpaid.""" payment_data = open(payment_data) for line in payment_data: order = line.split('|') customer_name = order[1] customer_first = customer_name.split(" ")[0] customer_melons = float(order[2]) customer_paid = float(order[3]) customer_expected = customer_melons * MELON_COST if customer_expected < customer_paid: print customer_name, "paid %.2f, expected %.2f" % ( customer_paid, customer_expected) print customer_first, "has overpaid for their melons." elif customer_expected > customer_paid: print customer_name, "paid %.2f, expected %.2f" % ( customer_paid, customer_expected) print customer_first, "has underpaid for their melons." melon_payment_calculator("customer-orders.txt")
ea8bb3f37fef6e37cd9f9274f22db69548ed5b99
1a59a9076c1e9f1eb98e24ff41a4c1c95e2b353e
/xcp2k/classes/_program_run_info36.py
df87e8835f3ba808b0a2fb5f2bbb04a979030521
[]
no_license
Roolthasiva/xcp2k
66b2f30ebeae1a946b81f71d22f97ea4076e11dc
fc3b5885503c6f6dc549efeb4f89f61c8b6b8242
refs/heads/master
2022-12-23T06:03:14.033521
2020-10-07T08:01:48
2020-10-07T08:01:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
695
py
from xcp2k.inputsection import InputSection from xcp2k.classes._each343 import _each343 class _program_run_info36(InputSection): def __init__(self): InputSection.__init__(self) self.Section_parameters = None self.Add_last = None self.Common_iteration_levels = None self.Filename = None self.Log_print_key = None self.EACH = _each343() self._name = "PROGRAM_RUN_INFO" self._keywords = {'Add_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Filename': 'FILENAME', 'Log_print_key': 'LOG_PRINT_KEY'} self._subsections = {'EACH': 'EACH'} self._attributes = ['Section_parameters']
acc4aef5d2a6eb365488380fe43780058d19a3d6
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/pg_1623+386/sdB_PG_1623+386_lc.py
79bf55d3e02753efc2d185b0d3025a46f7a7b55a
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
346
py
from gPhoton.gAperture import gAperture def main(): gAperture(band="NUV", skypos=[246.351292,38.505214], stepsz=30., csvfile="/data2/fleming/GPHOTON_OUTPU/LIGHTCURVES/sdBs/sdB_PG_1623+386 /sdB_PG_1623+386_lc.csv", maxgap=1000., overwrite=True, radius=0.00555556, annulus=[0.005972227,0.0103888972], verbose=3) if __name__ == "__main__": main()