text
stringlengths
0
1.05M
meta
dict
"""Add response table Revision ID: 2527acb7f3eb Revises: 50d3cad50bb8 Create Date: 2013-09-13 20:11:17.840269 """ # revision identifiers, used by Alembic. revision = '2527acb7f3eb' down_revision = '50d3cad50bb8' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('responses', sa.Column('id', sa.Integer(), nullable=False), sa.Column('request_id', sa.Integer(), nullable=False), sa.Column('response_type', sa.Enum(u'documentation', u'interview', u'population sample'), nullable=False), sa.Column('status', sa.Enum(u'Assigned', u'Accepted', u'Completed'), nullable=False), sa.Column('owner_id', sa.Integer(), nullable=True), sa.Column('title', sa.String(length=250), nullable=False), sa.Column('slug', sa.String(length=250), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('modified_by_id', sa.Integer(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('context_id', sa.Integer(), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column('url', sa.String(length=250), nullable=True), sa.Column('population_worksheet', sa.String(length=250), nullable=True), sa.Column('population_count', sa.Integer(), nullable=True), sa.Column('sample_worksheet', sa.String(length=250), nullable=True), sa.Column('sample_count', sa.Integer(), nullable=True), sa.Column('sample_evidence', sa.String(length=250), nullable=True), sa.ForeignKeyConstraint(['context_id'], ['contexts.id'], ), sa.ForeignKeyConstraint(['owner_id'], ['people.id'], ), sa.ForeignKeyConstraint(['request_id'], ['requests.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('evidence', sa.Column('id', sa.Integer(), nullable=False), sa.Column('url', sa.String(length=250), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('modified_by_id', sa.Integer(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('context_id', sa.Integer(), nullable=True), sa.Column('response_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['context_id'], ['contexts.id'], ), sa.ForeignKeyConstraint(['response_id'], ['responses.id'], ), sa.PrimaryKeyConstraint('id') ) def downgrade(): op.drop_table('evidence') op.drop_table('responses')
{ "repo_name": "vladan-m/ggrc-core", "path": "src/ggrc/migrations/versions/20130913201117_2527acb7f3eb_add_response_table.py", "copies": "2", "size": "2422", "license": "apache-2.0", "hash": -4866437537746364000, "line_mean": 42.25, "line_max": 110, "alpha_frac": 0.6754748142, "autogenerated": false, "ratio": 3.3545706371191137, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5030045451319114, "avg_score": null, "num_lines": null }
ADDRESS = '127.0.0.1' PORT = 8700 import os os.environ["SEAMLESS_COMMUNION_ID"] = "jobmaster-service" os.environ["SEAMLESS_COMMUNION_OUTGOING"] = "8600" import seamless seamless.set_ncores(0) from seamless import communion_server communion_server.configure_master( buffer=True, buffer_status=True, transformation_job=True, transformation_status=True, ) from seamless.highlevel import load_graph import sys, json from aiohttp import web import aiohttp_cors seamless.database_cache.connect() async def handler(request): text = await request.text() graph = json.loads(text) ctx = load_graph(graph) await ctx.computation() colored_graph = ctx.get_graph() body = json.dumps(colored_graph, indent=2, sort_keys=True) return web.Response( status=200, body=body, content_type='application/json', ) async def start(): await communion_server._start() app = web.Application() app.add_routes([ web.get('/{tail:.*}', handler), ]) # Configure default CORS settings. cors = aiohttp_cors.setup(app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*", allow_methods=["GET", ] ) }) # Configure CORS on all routes. for route in list(app.router.routes()): cors.add(route) runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, ADDRESS, PORT) await site.start() import asyncio asyncio.ensure_future(start()) loop = asyncio.get_event_loop() if len(sys.argv) > 1: run_time = float(sys.argv[1]) loop.call_later(run_time, sys.exit) loop.run_forever()
{ "repo_name": "sjdv1982/seamless", "path": "scripts/color-graph-service.py", "copies": "1", "size": "1747", "license": "mit", "hash": -2424835789730155000, "line_mean": 23.2638888889, "line_max": 62, "alpha_frac": 0.6433886663, "autogenerated": false, "ratio": 3.385658914728682, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9488981499771618, "avg_score": 0.008013216251412845, "num_lines": 72 }
#Address Book creator #Ask user for whether they are looking up a contact or if they're adding a new contact import time import sys choice = input("Enter 'looking for a contact' to search for a contact or Enter 'New contact' to add a new contact. Enter 'Exit' to exit.\n").lower() while choice not in ["looking for a contact", "new contact","exit"]: print("Input invalid, please enter a correct input.") choice = input("Enter 'looking for a contact' to search for a contact or Enter 'New contact' to add a new contact. Enter 'Exit' to exit.\n").lower() while choice in ["looking for a contact", "new contact","exit"]: #Create and open a text file named Contacts try: contact = open("Contacts.txt", "r+") contact.close() except: contact = open("Contacts.txt", "w") contact.close() finally: if choice == "exit": choice2 = input("Are you sure? This will exit the program\n").lower() while choice2 not in ["yes", "y", "no", "n"]: print("Invalid input") choice2 = input("Are you sure? This will exit the program (Enter yes or no)\n").lower() if choice2 in ["yes", "y"]: try: print("Thank you for using this program made by Vithushan Elangovan. Goodbye!") print("Exiting program in 3 seconds...Press CTRL+C to interrupt exit") time.sleep(1) print("3...Press CTRL+C to interrupt exit") time.sleep(1) print("2...Press CTRL+C to interrupt exit") time.sleep(1) print("1...Press CTRL+C to interrupt exit") time.sleep(1) print("Exit complete") contact.close() sys.exit() quit() except KeyboardInterrupt: print("Keyboard interrupt received. Returning to main menu.") time.sleep(2) choice = input("Enter 'looking for a contact' to search for a contact or Enter 'New contact' to add a new contact. Enter 'Exit' twice to exit program.\n").lower() elif choice2 in ["no", "n"]: choice = input("Enter 'looking for a contact' to search for a contact or Enter 'New contact' to add a new contact. Enter 'Exit' twice to exit program.\n").lower() if choice == "new contact": contact = open("Contacts.txt", "a") fname = input("Please enter the first name:\n") fname = fname[0].upper() + fname[1:].lower() mname = input("Please enter any middle names:\n") lname = input("Please enter the last name:\n") lname = lname[0].upper() + lname[1:].lower() #combines names to a full name name = fname + " " + mname + " " + lname contact.write("\n-------------------------------------------") contact.write("\nName: " + name) #age age = input("Please enter the age of " + fname + ":\n") contact.write("\t Age: " + age) #date of birth d_o_b = input("Please enter the date of birth of " + fname + " in the format ddmmyyyy:\n") #to ensure date of birth is in correct format while len(d_o_b)!=8: print("Please enter the date in the format required") d_o_b = input("Please enter the date of birth of " + fname + " in the format ddmmyyyy:\n") while int(d_o_b[2:4])>12: print("Please enter the date in the format required") d_o_b = input("Please enter the date of birth of " + fname + " in the format ddmmyyyy:\n") while int(d_o_b[0:2])>31: print("Please enter the date in the format required") d_o_b = input("Please enter the date of birth of " + fname + " in the format ddmmyyyy:\n") contact.write("\nD.O.B: " + d_o_b[0:2] + "-" + d_o_b[2:4] + "-" + d_o_b[4:]) #home phone hphone = input("Please enter the home phone number of " + fname + ":\n") contact.write("\nHome Phone: " + hphone) #mobile phone mphone = input("Please enter the mobile phone number of " + fname + ":\n") contact.write("\t Mobile Phone: " + mphone) #address h_no = input("Please enter the house number and/or house name of " + fname + ":\n") street = input("Please enter the street of " + fname + ":\n") town = input("Please enter the town or city where " + fname + " lives in:\n") county = input("Please enter the county or state where " + fname + "lives in:\n") country = input("Please enter the country of residence of " + fname + ":\n") zip_code = input("Please enter the zip/postal code of " + fname + ":\n") address = h_no + " " + street + "\n\t" + town + "\n\t" + county + "\n\t" + country + "\n\t" + zip_code contact.write("\nAddress:\n\t" + address) print("Your contact has been successfully added.") #To carry on to next command choice = input("Would you like to add a new contact? or would you like to look for a contact? Type in 'exit' to close the document\n").lower() elif choice == "looking for a contact": contact = open("Contacts.txt", "r") firname = input("Please enter the first name of the contact you are looking for:\n") lstname = input("Please enter the last name of the contact you are looking for:\n") searchlines = contact.readlines() found = False for i,line in enumerate(searchlines): if (firname[0].upper()+firname[1:].lower()) in searchlines[i] and (lstname[0].upper()+lstname[1:].lower()) in searchlines[i]: for l in searchlines[i:i+10]: print(l), print("") found = True break if not found: print("Contact not found") contact.close() choice = input("Please type in 'New contact' to add a contact or 'looking for a contact' to search your address book (Enter exit to exit the program):\n").lower()
{ "repo_name": "Vite94/pythondepo", "path": "Address _Book.py", "copies": "1", "size": "6490", "license": "mit", "hash": 2833017906339489000, "line_mean": 59.8095238095, "line_max": 182, "alpha_frac": 0.5334360555, "autogenerated": false, "ratio": 4.110196326789107, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008346421774922183, "num_lines": 105 }
"""addressbook URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin import contacts.views urlpatterns =[ url(r'^$', contacts.views.ListContactView.as_view(), name='contacts-list'), url(r'^new$', contacts.views.CreateContactView.as_view(), name='contacts-new'), url(r'^edit/(?P<pk>\d+)/$', contacts.views.UpdateContactView.as_view(), name='contacts-edit',), url(r'^edit/(?P<pk>\d+)/$', contacts.views.UpdateContactView.as_view(), name='contacts-edit-addresses',), url(r'^delete/(?P<pk>\d+)/$', contacts.views.DeleteContactView.as_view(), name='contacts-delete',), url(r'^(?P<pk>\d+)/$', contacts.views.ContactView.as_view(), name='contacts-view',), ]
{ "repo_name": "mauerbac/addressbook", "path": "addressbook/urls.py", "copies": "1", "size": "1347", "license": "mit", "hash": -6591887206096219000, "line_mean": 37.4857142857, "line_max": 83, "alpha_frac": 0.6636971047, "autogenerated": false, "ratio": 3.427480916030534, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4591178020730534, "avg_score": null, "num_lines": null }
"""Address module Address data lives in the 'addresses' table. Several entities link to address via foreign keys. """ from sqlalchemy.dialects.postgresql import ENUM from ..database import db address_type = ENUM('postal', 'physical', 'both', name='address_type', create_type=False) address_use = ENUM('home', 'work', 'temp', 'old', name='address_use', create_type=False) class Address(db.Model): """SQLAlchemy class for `addresses` table""" __tablename__ = 'addresses' id = db.Column(db.Integer(), primary_key=True) use = db.Column('a_use', address_use) type = db.Column('a_type', address_type) line1 = db.Column(db.Text) line2 = db.Column(db.Text) line3 = db.Column(db.Text) city = db.Column(db.Text) district = db.Column(db.Text) state = db.Column(db.Text) postalCode = db.Column(db.Text) country = db.Column(db.Text) @property def lines(self): return '; '.join([el for el in (self.line1, self.line2, self.line3) if el]) def __str__(self): return "Address: {0.use} {0.type} {0.lines} {0.city} {0.district}" \ " {0.state} {0.postalCode} {0.country}".format(self) @classmethod def from_fhir(cls, data): adr = cls() if 'line' in data: for i, line in zip(range(1, len(data['line']) + 1), data['line']): # in case of 4 or more lines, delimit and append to line3 if i > 3: adr.line3 = '; '.join((adr.line3, line)) else: setattr(adr, 'line{}'.format(i), line) for attr in ('use', 'type'): if attr in data: setattr(adr, attr, data[attr].lower()) for attr in ('city', 'district', 'state', 'postalCode', 'country'): if attr in data: setattr(adr, attr, data[attr]) return adr def as_fhir(self): d = {} d['use'] = self.use d['type'] = self.type lines = [] for el in self.line1, self.line2, self.line3: if el: lines.append(el) d['line'] = lines for attr in ('city', 'district', 'state', 'postalCode', 'country'): value = getattr(self, attr, None) if value: d[attr] = value return d
{ "repo_name": "uwcirg/true_nth_usa_portal", "path": "portal/models/address.py", "copies": "1", "size": "2384", "license": "bsd-3-clause", "hash": 2947297204266540000, "line_mean": 31.2162162162, "line_max": 78, "alpha_frac": 0.5318791946, "autogenerated": false, "ratio": 3.495601173020528, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4527480367620528, "avg_score": null, "num_lines": null }
# Address monitor from picshell.engine.util.Format import Format import wx.lib.newevent import wx class UpDownCounter: def __init__(self,ui,address,selectBit,incBit,upDownBit,max,name="",csBar=False): self.address = Format.toNumber(address) self.ui = ui self.selectBit =selectBit self.incBit =incBit self.upDownBit = upDownBit self.max = max self.name=name self.reset() self.type="UpDownCounter" self.oldIncBit = 0 self.csBar = csBar def reset(self): self.cpt = 0 if (self.ui != None): wx.CallAfter(self.UpdateUI, None ) def execute(self,value): select = value & pow(2,self.selectBit) incBit = value & pow(2,self.incBit) upDown = value & pow(2,self.upDownBit) if self.csBar : cs = (select == 0) else : cs = (select > 0) if cs: if incBit > 0 and self.oldIncBit == 0: # up edge if (upDown>0): if self.cpt < self.max : self.cpt += 1 else: if self.cpt > 0: self.cpt -= 1 wx.CallAfter(self.UpdateUI, str(self.cpt) ) self.oldIncBit = incBit def UpdateUI(self,value): self.ui.Clear() if value != None : self.ui.AppendText( value ) def CreateUI(self,parent, psizer ): panel = wx.Panel(parent,-1) sizer = wx.BoxSizer(wx.HORIZONTAL) panel.SetSizer(sizer) label = wx.StaticText(panel,-1," " + self.name) self.ui = wx.TextCtrl(panel) self.ui.SetFont(wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL)) sizer.Add(self.ui,0,0) sizer.Add(label,0,0) psizer.Add(panel,0,0)
{ "repo_name": "sirloon/jaluino", "path": "ide/plugins/JaluinoDebugger/picshell/ui/debug/comp/Counter.py", "copies": "1", "size": "1930", "license": "bsd-3-clause", "hash": -6429332897391366000, "line_mean": 27.2727272727, "line_max": 84, "alpha_frac": 0.5041450777, "autogenerated": false, "ratio": 3.5283363802559413, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45324814579559414, "avg_score": null, "num_lines": null }
# Address monitor import wx import wx.lib.newevent from wx import gizmos from picshell.engine.util.Format import Format class Dual7Seg: def __init__(self,ui,address,razBit,uniteeBit,deciBit,name=""): self.address = Format.toNumber(address) self.ui = ui self.unitee=0; self.deci=0; self.oldIncUnitee = 0 self.oldRaz = 0 self.oldIncDeci = 0 self.razBit = razBit self.uniteeBit = uniteeBit self.deciBit = deciBit self.name = name self.type="Dual7Seg" self.reset() def reset(self): if (self.ui != None): wx.CallAfter(self.UpdateUI, "00" ) def execute(self,value): raz = value & pow(2,self.razBit) incUnitee = value & pow(2,self.uniteeBit) incDeci = value & pow(2,self.deciBit) if raz > 0 and self.oldRaz == 0: self.unitee = 0 self.deci = 0 if incUnitee >0 and self.oldIncUnitee == 0: self.unitee += 1 if (self.unitee > 9): self.unitee = 0 if incDeci >0 and self.oldIncDeci == 0 : self.deci += 1 if (self.deci > 9): self.deci = 0 val = str(self.deci)+str(self.unitee) wx.CallAfter(self.UpdateUI, val ) self.oldRaz = raz self.oldIncUnitee = incUnitee self.oldIncDeci = incDeci def UpdateUI(self, value): self.ui.SetValue(value) def CreateUI(self,parent, psizer ): panel = wx.Panel(parent,-1) sizer = wx.BoxSizer(wx.HORIZONTAL) panel.SetSizer(sizer) label = wx.StaticText(panel,-1," " + self.name) #ui = wx.TextCtrl(panel) #ui.SetFont(wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL)) self.ui = gizmos.LEDNumberCtrl(panel, -1, (25,25), (280, 50)) sizer.Add(self.ui,0,0) sizer.Add(label,0,0) psizer.Add(panel,0,0)
{ "repo_name": "sirloon/jaluino", "path": "ide/plugins/JaluinoDebugger/picshell/ui/debug/comp/Dual7Seg.py", "copies": "1", "size": "2074", "license": "bsd-3-clause", "hash": -3802446014534816300, "line_mean": 27.6285714286, "line_max": 69, "alpha_frac": 0.5226615236, "autogenerated": false, "ratio": 3.261006289308176, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9099802507002119, "avg_score": 0.03677306118121134, "num_lines": 70 }
# Address monitor import wx from picshell.engine.util.Format import Format class Dual7Seg: def __init__(self,ui,address,razBit,uniteeBit,deciBit,name=""): self.address = Format.toNumber(address) self.ui = ui self.unitee=0; self.deci=0; self.oldIncUnitee = 0 self.oldRaz = 0 self.oldIncDeci = 0 self.razBit = razBit self.uniteeBit = uniteeBit self.deciBit = deciBit self.name = name self.type="Dual7Seg" self.reset() def reset(self): if (self.ui != None): wx.CallAfter(self.UpdateUI, "00" ) def execute(self,value): raz = value & pow(2,self.razBit) incUnitee = value & pow(2,self.uniteeBit) incDeci = value & pow(2,self.deciBit) if raz > 0 and self.oldRaz == 0: self.unitee = 0 self.deci = 0 if incUnitee >0 and self.oldIncUnitee == 0: self.unitee += 1 if (self.unitee > 9): self.unitee = 0 if incDeci >0 and self.oldIncDeci == 0 : self.deci += 1 if (self.deci > 9): self.deci = 0 #self.ui.Clear() val = str(self.deci)+str(self.unitee) wx.CallAfter(self.UpdateUI, val ) self.oldRaz = raz self.oldIncUnitee = incUnitee self.oldIncDeci = incDeci
{ "repo_name": "sirloon/jaluino", "path": "ide/plugins/JaluinoDebugger/picshell/ui/debug/comp/SevenSegment.py", "copies": "1", "size": "1457", "license": "bsd-3-clause", "hash": -4541048091560956400, "line_mean": 27.7755102041, "line_max": 66, "alpha_frac": 0.5161290323, "autogenerated": false, "ratio": 3.266816143497758, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4282945175797758, "avg_score": null, "num_lines": null }
# Address monitor from picshell.engine.util.Format import Format from picshell.engine.util import BitUtil import wx.lib.newevent import wx class LCD : # http://www.doc.ic.ac.uk/~ih/doc/lcd/initiali.html # http://www.myke.com/lcd.htm # Taken from bert's lcd jal lib # #clear_display = 0b_0000_0001 #return_home = 0b_0000_0010 #display_onoff = 0b_0000_1000 # #cursor_shift_right = 0b_0001_0100 #cursor_shift_left = 0b_0001_0000 #display_shift_right = 0b_0001_1100 #display_shift_left = 0b_0001_1000 # #set_CGRAM_address = 0b_0100_0000 + 6 bits address #set_DDRAM_address = 0b_1000_0000 + 7 bits address # # HD44780 4 bits, 2x16 impl. # debug = False def __init__(self,name, address,nbChar=16): self.address = Format.toNumber(address) self.ui = None self.name = name self.reset() self.nb_char = nbChar self.type = "LCD" def reset(self): self.isData = False self.oldValue = 0 self.oldClkValue = 0 self.text = [0]*256; for i in range(0,len(self.text)): self.text[i] = " " self.indexText = 0; self.hi = -1; self.initted = False self.cptInitSeq = 0; for i in range(0,len(self.text)): self.text[i]=ord(' ') # let's say that value = None -> clear value wx.CallAfter(self.UpdateUI, None ) def execute(self,value): # # A faire : determiner data ou cmd que lorsque je recois le HI # if self.debug: print "LCD execute %02X" % value if (self.initted): if self.debug: print Format.binf(value)+" - 0x%X" %(value & 0x3F) if (BitUtil.isSet(value,5) ) and BitUtil.isClear(self.oldValue,5): # clock enable if self.debug: print "---------------------------------------Clock" if (self.isData) : # DATA if (self.hi != -1) : ascii = self.hi + (value&0xF) if self.debug: print "----------------->low_data:"+str(value) print chr(ascii), print "offset : "+str(int(self.indexText/0x40)*self.nb_char), print "index : "+str(self.indexText) print "------->ASCII : "+str(ascii) self.text[(self.indexText%0x40)+ int(self.indexText/0x40)*self.nb_char] = ascii out =""; for i in range (0,self.nb_char*4): c = self.text[i]; if (ord(' ')==c): c=ord('-') out = out+""+chr(c); if self.debug: print "------->"+chr(c) if (i%self.nb_char==self.nb_char-1): out += "\n"; wx.CallAfter(self.UpdateUI, out ) self.indexText +=1 # TODO : should depend on config. self.hi = -1; else: # hi data self.isData = BitUtil.isSet(value,4) self.hi = value&0XF; if self.debug: print "----------------->hi_data:"+str(self.hi) self.hi <<=4; else: # COMMAND if (self.hi != -1): if self.debug: print "----------------->low_cmd:"+str(value) whole = self.hi + (value&0xF) self.hi = -1 if (whole == 1): # let's say that value = None -> clear value wx.CallAfter(self.UpdateUI, None ) if ((whole&0x80)>0): # position : self.indexText = whole&0x7F; else: self.hi = value&0XF; self.hi <<=4; self.isData = self.isData = BitUtil.isSet(value,4) if self.debug: print "----------------->hi_cmd:"+str(self.hi) else: # not initted yet if self.debug: print Format.binf(value)+" - 0x%X" %(value & 0x3F) if (BitUtil.isSet(value,5) ) and BitUtil.isClear(self.oldValue,5): if self.debug: print "---------------------------------------Clock (not inited)" if ((value&0x3F) == 0x23): self.cptInitSeq+=1 if self.debug: print "======================Init LCD" else: if self.debug: print " self.cptInitSeq %d" % self.cptInitSeq print " value %02X " % (value&0x3F) if (self.cptInitSeq>=2): if ((value&0x3F) == 0x22): self.initted = True; if self.debug: print "===============LCD INITED" self.oldValue = value def UpdateUI(self,value): if ( self.ui != None ): self.ui.Clear() if value != None : self.ui.AppendText( value ) def CreateUI(self,parent, psizer ): self.ui = wx.TextCtrl(parent,size=(12*int(self.nb_char), 90),style=wx.TE_MULTILINE) self.ui.SetBackgroundColour("black") self.ui.SetForegroundColour("#40C040") self.ui.SetFont(wx.Font(10, wx.MODERN, wx.NORMAL, wx.BOLD)) psizer.Add(self.ui)
{ "repo_name": "sirloon/jaluino", "path": "ide/plugins/JaluinoDebugger/picshell/ui/debug/comp/LCD.py", "copies": "1", "size": "6410", "license": "bsd-3-clause", "hash": -1592823929043019500, "line_mean": 37.5679012346, "line_max": 103, "alpha_frac": 0.388299532, "autogenerated": false, "ratio": 4.140826873385013, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5029126405385013, "avg_score": null, "num_lines": null }
# Address utilities from __future__ import absolute_import import re from .crypto import ( sha3, ) from .encoding import ( encode_hex, ) from .string import ( force_text, coerce_args_to_text, coerce_return_to_text, ) from .types import ( is_string, ) from .formatting import ( add_0x_prefix, remove_0x_prefix, is_prefixed, ) @coerce_args_to_text def is_address(address): """ Checks if the given string is an address """ if not is_string(address): return False if not re.match(r"^(0x)?[0-9a-fA-F]{40}$", address): return False elif re.match(r"^(0x)?[0-9a-f]{40}", address) or re.match(r"(0x)?[0-9A-F]{40}$", address): return True else: return is_checksum_address(address) @coerce_args_to_text def is_checksum_address(address): """ Checks if the given string is a checksummed address """ if not is_string(address): return False checksum_address = to_checksum_address(address) return force_text(address) == force_text(checksum_address) @coerce_args_to_text def is_strict_address(address): """ Checks if the given string is strictly an address """ if not is_string(address): return False return re.match(r"^0x[0-9a-fA-F]{40}$", address) is not None @coerce_args_to_text @coerce_return_to_text def to_checksum_address(address): """ Makes a checksum address """ if not is_string(address): return False address = remove_0x_prefix(address.lower()) addressHash = sha3(address) checksumAddress = "0x" for i in range(len(address)): if int(addressHash[i], 16) > 7: checksumAddress += address[i].upper() else: checksumAddress += address[i] return checksumAddress @coerce_args_to_text @coerce_return_to_text def to_address(address): """ Transforms given string to valid 20 bytes-length addres with 0x prefix """ if is_string(address): if len(address) == 42: return address.lower() elif len(address) == 40: return add_0x_prefix(address.lower()) elif len(address) == 20: return encode_hex(address) elif len(address) in {66, 64}: long_address = remove_0x_prefix(address.lower()) if is_prefixed(long_address, '000000000000000000000000'): return add_0x_prefix(address[-40:]) raise ValueError("Unknown address format") @coerce_args_to_text def is_same_address(addr1, addr2): """ Checks if both addresses are same or not """ if is_address(addr1) & is_address(addr2): return to_checksum_address(addr1) == to_checksum_address(addr2) else: return to_checksum_address(to_address(addr1)) == to_checksum_address(to_address(addr2))
{ "repo_name": "shravan-shandilya/web3.py", "path": "web3/utils/address.py", "copies": "1", "size": "2834", "license": "mit", "hash": -3592311787607494700, "line_mean": 22.2295081967, "line_max": 95, "alpha_frac": 0.6235003529, "autogenerated": false, "ratio": 3.481572481572482, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4605072834472482, "avg_score": null, "num_lines": null }
"""Add restricted theme Revision ID: 1d5d4abfebd1 Revises: 54645a535ad6 Create Date: 2014-11-25 16:51:51.567026 """ # revision identifiers, used by Alembic. revision = '1d5d4abfebd1' down_revision = '54645a535ad6' from alembic import op, context from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Integer, Boolean def upgrade(): schema = context.get_context().config.get_main_option('schema') engine = op.get_bind().engine if op.get_context().dialect.has_table( engine, 'restricted_role_theme', schema=schema ): # pragma: nocover return op.add_column('theme', Column( 'public', Boolean, server_default='t', nullable=False ), schema=schema) op.create_table( 'restricted_role_theme', Column( 'role_id', Integer, ForeignKey(schema + '.role.id'), primary_key=True ), Column( 'theme_id', Integer, ForeignKey(schema + '.theme.id'), primary_key=True ), schema=schema ) def downgrade(): schema = context.get_context().config.get_main_option('schema') op.drop_table('restricted_role_theme', schema=schema) op.drop_column('theme', 'public', schema=schema)
{ "repo_name": "tsauerwein/c2cgeoportal", "path": "c2cgeoportal/scaffolds/update/CONST_alembic/versions/1d5d4abfebd1_add_restricted_theme.py", "copies": "2", "size": "1218", "license": "bsd-2-clause", "hash": 702936470458691300, "line_mean": 25.4782608696, "line_max": 83, "alpha_frac": 0.6543513957, "autogenerated": false, "ratio": 3.5, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.51543513957, "avg_score": null, "num_lines": null }
"""Add resumes. Revision ID: e7410a32fd81 Revises: 4453e9c3a9be Create Date: 2018-01-17 11:49:53.974612 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e7410a32fd81' down_revision = '4453e9c3a9be' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('resume_permissions', sa.Column('id', sa.Integer(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_table('resumes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.Unicode(length=32), nullable=True), sa.Column('hashed', sa.Unicode(length=64), nullable=True), sa.Column('date_created', sa.DateTime(), nullable=True), sa.Column('date_updated', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('resumes') op.drop_table('resume_permissions') # ### end Alembic commands ###
{ "repo_name": "saseumn/website", "path": "migrations/versions/e7410a32fd81_.py", "copies": "1", "size": "1218", "license": "mit", "hash": 9013851385332065000, "line_mean": 28, "line_max": 65, "alpha_frac": 0.6666666667, "autogenerated": false, "ratio": 3.3278688524590163, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4494535519159016, "avg_score": null, "num_lines": null }
"""add reviewRequested to workspace table Revision ID: 98595efd597e Revises: 9bde0801927b Create Date: 2020-04-06 15:31:13.382126 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '98595efd597e' down_revision = '9bde0801927b' branch_labels = None depends_on = None def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('workbench_workspace', sa.Column('review_requested', sa.Boolean(), nullable=True)) op.add_column('workbench_workspace_history', sa.Column('review_requested', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('workbench_workspace_history', 'review_requested') op.drop_column('workbench_workspace', 'review_requested') # ### end Alembic commands ### def upgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def downgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
{ "repo_name": "all-of-us/raw-data-repository", "path": "rdr_service/alembic/versions/98595efd597e_add_reviewrequested_to_workspace_table.py", "copies": "1", "size": "1331", "license": "bsd-3-clause", "hash": 3224335975592063000, "line_mean": 25.0980392157, "line_max": 108, "alpha_frac": 0.6799398948, "autogenerated": false, "ratio": 3.607046070460705, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4786985965260705, "avg_score": null, "num_lines": null }
"""add_roach_temp_table Revision ID: f29adafca107 Revises: 38aa03a7c923 Create Date: 2017-12-09 19:59:50.058296+00:00 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f29adafca107' down_revision = '64bc793c6237' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('roach_temperature', sa.Column('time', sa.BigInteger(), nullable=False), sa.Column('roach', sa.String(), nullable=False), sa.Column('ambient_temp', sa.Float(), nullable=True), sa.Column('inlet_temp', sa.Float(), nullable=True), sa.Column('outlet_temp', sa.Float(), nullable=True), sa.Column('fpga_temp', sa.Float(), nullable=True), sa.Column('ppc_temp', sa.Float(), nullable=True), sa.PrimaryKeyConstraint('time', 'roach') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('roach_temperature') # ### end Alembic commands ###
{ "repo_name": "HERA-Team/Monitor_and_Control", "path": "alembic/versions/f29adafca107_add_roach_temp_table.py", "copies": "2", "size": "1068", "license": "bsd-2-clause", "hash": -2554360161644391400, "line_mean": 27.8648648649, "line_max": 65, "alpha_frac": 0.670411985, "autogenerated": false, "ratio": 3.2363636363636363, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9886736431076526, "avg_score": 0.004007838057422004, "num_lines": 37 }
"""Add role column to groups_tenants_table Revision ID: 7aae863786af Revises: 406821843b55 Create Date: 2017-10-04 11:10:48.227654 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '7aae863786af' down_revision = '406821843b55' branch_labels = None depends_on = None def upgrade(): op.add_column( 'groups_tenants', sa.Column('role_id', sa.Integer()), ) op.create_foreign_key( 'groups_tenants_role_id_fkey', 'groups_tenants', 'roles', ['role_id'], ['id'], ) op.create_primary_key( 'groups_tenants_pkey', 'groups_tenants', ['group_id', 'tenant_id'], ) # Define tables with just the columns needed # to generate the UPDATE sql expression below groups_tenants = sa.table( 'groups_tenants', sa.column('group_id', sa.Integer), sa.column('role_id', sa.Integer), ) roles = sa.table( 'roles', sa.column('id', sa.Integer), sa.column('name', sa.Text), ) # Set 'user' role as the default for every group in a tenant op.execute( groups_tenants.update() .values(role_id=( sa.select([roles.c.id]) .where(roles.c.name == op.inline_literal('user')) )) ) op.alter_column('groups_tenants', 'role_id', nullable=False) def downgrade(): op.drop_constraint( 'groups_tenants_pkey', 'groups_tenants', ) op.drop_constraint( 'groups_tenants_role_id_fkey', 'groups_tenants', ) op.drop_column('groups_tenants', 'role_id')
{ "repo_name": "cloudify-cosmo/cloudify-manager", "path": "resources/rest-service/cloudify/migrations/versions/7aae863786af_add_role_column_groups_tenants_table.py", "copies": "1", "size": "1645", "license": "apache-2.0", "hash": -965583712299888800, "line_mean": 23.1911764706, "line_max": 64, "alpha_frac": 0.5854103343, "autogenerated": false, "ratio": 3.3917525773195876, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44771629116195877, "avg_score": null, "num_lines": null }
"""Add role column to users_tenants table Revision ID: 406821843b55 Revises: 3496c876cd1a Create Date: 2017-10-01 19:37:31.484983 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '406821843b55' down_revision = '4dfd8797fdfa' branch_labels = None depends_on = None # Define tables with just the columns needed # to generate the UPDATE sql expressions below users_roles = sa.table( 'users_roles', sa.column('user_id', sa.Integer), sa.column('role_id', sa.Integer), ) users_tenants = sa.table( 'users_tenants', sa.column('user_id', sa.Integer), sa.column('role_id', sa.Integer), ) roles = sa.table( 'roles', sa.column('id', sa.Integer), sa.column('name', sa.Text), ) OLD_ADMIN_ROLE_ID = 1 OLD_USER_ROLE_ID = 2 def update_system_role(from_role_id, to_role_id): """Helper function to update system role values. Calling this function will update the role for all users whose current role is `from_role_id` and set it to `to_role_id`. """ op.execute( users_roles.update() .where(users_roles.c.role_id == op.inline_literal(from_role_id)) .values(role_id=to_role_id) ) def _get_role_id(role_name): """ Return a SELECT statement that retrieves a role ID from a role name """ return sa.select([roles.c.id]).where( roles.c.name == op.inline_literal(role_name)) def upgrade(): op.add_column( 'users_tenants', sa.Column('role_id', sa.Integer()), ) op.create_foreign_key( 'users_tenants_role_id_fkey', 'users_tenants', 'roles', ['role_id'], ['id'], ) op.create_primary_key( 'users_tenants_pkey', 'users_tenants', ['user_id', 'tenant_id'], ) # Set 'user' role as the default for every user in a tenant op.execute( users_tenants.update() .values(role_id=_get_role_id('user')) ) op.alter_column('users_tenants', 'role_id', nullable=False) # Manually using old role IDs, because they have changed in this version. # Old roles were: # 1 - admin # 2 - user # New roles are: # 1 - sys_admin # 2 - manager # 3 - user # 4 - viewer # 5 - default update_system_role(OLD_USER_ROLE_ID, _get_role_id('default')) update_system_role(OLD_ADMIN_ROLE_ID, _get_role_id('sys_admin')) def downgrade(): update_system_role(_get_role_id('default'), OLD_USER_ROLE_ID) update_system_role(_get_role_id('sys_admin'), OLD_ADMIN_ROLE_ID) op.drop_constraint( 'users_tenants_pkey', 'users_tenants', ) op.drop_constraint( 'users_tenants_role_id_fkey', 'users_tenants', ) op.drop_column('users_tenants', 'role_id')
{ "repo_name": "cloudify-cosmo/cloudify-manager", "path": "resources/rest-service/cloudify/migrations/versions/406821843b55_add_role_column_to_users_tenants_table.py", "copies": "1", "size": "2787", "license": "apache-2.0", "hash": 4767588812979075000, "line_mean": 24.3363636364, "line_max": 79, "alpha_frac": 0.6167922497, "autogenerated": false, "ratio": 3.185142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4301935106842857, "avg_score": null, "num_lines": null }
"""Add roles and role implications for gdrive connectors Revision ID: 24c56d737c18 Revises: 18bf74925b9 Create Date: 2013-11-22 00:10:39.635553 """ # revision identifiers, used by Alembic. revision = '24c56d737c18' down_revision = '18bf74925b9' import sqlalchemy as sa from alembic import op from datetime import datetime from sqlalchemy.sql import table, column, select import json roles_table = table('roles', column('id', sa.Integer), column('name', sa.String), column('permissions_json', sa.String) ) def upgrade(): folder_set = set(["Program", "Audit", "Request"]) connection = op.get_bind() roles = connection.execute(select([roles_table.c.id, roles_table.c.permissions_json])) for role_id, permissions_json in roles: permissions = json.loads(permissions_json) if(permissions is None): continue for ptype in ["read", "create", "delete"]: if(ptype in permissions and any( # filter out "terms" objects set([i if type(i) == str or type(i) == unicode else i["type"] for i in permissions[ptype]]) .intersection(folder_set) ) and "ObjectFolder" not in permissions[ptype]): permissions[ptype].append("ObjectFolder") if(ptype in permissions and "Document" in permissions[ptype] and "ObjectFile" not in permissions[ptype]): permissions[ptype].append("ObjectFile") if(ptype in permissions and "Meeting" in permissions[ptype] and "ObjectEvent" not in permissions[ptype]): permissions[ptype].append("ObjectEvent") op.execute(roles_table.update().values(permissions_json = json.dumps(permissions))\ .where(roles_table.c.id == role_id)) def downgrade(): connection = op.get_bind() roles = connection.execute(select([roles_table.c.id, roles_table.c.permissions_json])) for role_id, permissions_json in roles: permissions = json.loads(permissions_json) if(permissions is None): continue for ptype in ["read", "create", "delete"]: if(ptype in permissions): permissions[ptype] = [i for i in permissions[ptype] \ if i not in ["ObjectFolder", "ObjectFile", "ObjectEvent"]] op.execute(roles_table.update().values(permissions_json = json.dumps(permissions))\ .where(roles_table.c.id == role_id))
{ "repo_name": "uskudnik/ggrc-core", "path": "src/ggrc_basic_permissions/migrations/versions/20131122001039_24c56d737c18_add_roles_and_role_i.py", "copies": "2", "size": "2368", "license": "apache-2.0", "hash": 8949674108140033000, "line_mean": 31.8888888889, "line_max": 103, "alpha_frac": 0.6592060811, "autogenerated": false, "ratio": 3.7767145135566187, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5435920594656619, "avg_score": null, "num_lines": null }
"""Add role seed data for flask-security Revision ID: 7b2d863b105 Revises: 2a3fee7de8d4 Create Date: 2015-07-02 10:48:35.805882 """ # revision identifiers, used by Alembic. revision = '7b2d863b105' down_revision = '2a3fee7de8d4' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### role_table = sa.table('role', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(length=80), nullable=True), sa.Column('description', sa.String(length=255), nullable=True), ) op.bulk_insert(role_table, [ {'id': 2, 'name': 'product_category_view', 'description': 'View product categories'}, {'id': 3, 'name': 'product_category_create', 'description': 'Create product category'}, {'id': 4, 'name': 'product_category_edit', 'description': 'Edit product category'}, {'id': 5, 'name': 'product_category_delete', 'description': 'Delete product category'}, {'id': 6, 'name': 'sales_order_view', 'description': 'View sales orders'}, {'id': 7, 'name': 'sales_order_create', 'description': 'Create sales order'}, {'id': 8, 'name': 'sales_order_edit', 'description': 'Edit sales order'}, {'id': 9, 'name': 'sales_order_delete', 'description': 'Delete sales order'}, {'id': 10, 'name': 'purchase_order_view', 'description': 'View purchase orders'}, {'id': 11, 'name': 'purchase_order_create', 'description': 'Create purchase order'}, {'id': 12, 'name': 'purchase_order_edit', 'description': 'Edit purchase order'}, {'id': 13, 'name': 'purchase_order_delete', 'description': 'Delete purchase order'}, {'id': 14, 'name': 'expense_view', 'description': 'View expenses'}, {'id': 15, 'name': 'expense_create', 'description': 'Create expense'}, {'id': 16, 'name': 'expense_edit', 'description': 'Edit expense'}, {'id': 17, 'name': 'expense_delete', 'description': 'Delete expense'}, {'id': 18, 'name': 'incoming_view', 'description': 'View incoming'}, {'id': 19, 'name': 'incoming_create', 'description': 'Create incoming'}, {'id': 20, 'name': 'incoming_edit', 'description': 'Edit incoming'}, {'id': 21, 'name': 'incoming_delete', 'description': 'Delete incoming'}, {'id': 22, 'name': 'supplier_view', 'description': 'View suppliers'}, {'id': 23, 'name': 'supplier_create', 'description': 'Create supplier'}, {'id': 24, 'name': 'supplier_edit', 'description': 'Edit supplier'}, {'id': 25, 'name': 'supplier_delete', 'description': 'Delete supplier'}, {'id': 26, 'name': 'product_view', 'description': 'View products'}, {'id': 27, 'name': 'product_create', 'description': 'Create product'}, {'id': 28, 'name': 'product_edit', 'description': 'Edit product'}, {'id': 29, 'name': 'product_delete', 'description': 'Delete product'}, {'id': 30, 'name': 'enum_values_view', 'description': 'View enum values'}, {'id': 31, 'name': 'enum_values_create', 'description': 'Create enum value'}, {'id': 32, 'name': 'enum_values_edit', 'description': 'Edit enum value'}, {'id': 33, 'name': 'enum_values_delete', 'description': 'Delete enum value'}, {'id': 34, 'name': 'preference_view', 'description': 'View system preference'}, {'id': 35, 'name': 'preference_edit', 'description': 'Update system preference'}, {'id': 36, 'name': 'user_view', 'description': 'View user'}, {'id': 37, 'name': 'user_create', 'description': 'Create user'}, {'id': 38, 'name': 'user_edit', 'description': 'Edit user'}, {'id': 39, 'name': 'user_delete', 'description': 'Delete user'}, {'id': 40, 'name': 'role_view', 'description': 'View roles'}, {'id': 41, 'name': 'role_create', 'description': 'Create role'}, {'id': 42, 'name': 'role_edit', 'description': 'Edit role'}, {'id': 43, 'name': 'role_delete', 'description': 'Delete role'}, ],multiinsert=False) from sqlalchemy.sql import text op.get_bind().execute(text("ALTER SEQUENCE role_id_seq RESTART WITH 44;")) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### pass ### end Alembic commands ###
{ "repo_name": "betterlife/psi", "path": "psi/migrations/versions/05_7b2d863b105_.py", "copies": "2", "size": "4346", "license": "mit", "hash": -4404478219019477000, "line_mean": 56.1842105263, "line_max": 95, "alpha_frac": 0.5959502991, "autogenerated": false, "ratio": 3.5828524319868094, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5178802731086809, "avg_score": null, "num_lines": null }
"""Add RoleState table. Revision ID: e86b741dc3fc Revises: b68e0d8ed9fe Create Date: 2017-02-04 14:47:51.072291 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'e86b741dc3fc' down_revision = 'b68e0d8ed9fe' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('rolestate', sa.Column('id', sa.Integer(), nullable=False), sa.Column('user_id', sa.BigInteger(), nullable=True), sa.Column('guild_id', sa.BigInteger(), nullable=False), sa.Column('roles', postgresql.ARRAY(sa.Integer()), nullable=True), sa.Column('nick', sa.String(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('rolestate') # ### end Alembic commands ###
{ "repo_name": "MJB47/Jokusoramame", "path": "migrations/versions/e86b741dc3fc_add_rolestate_table.py", "copies": "1", "size": "1036", "license": "mit", "hash": -5190973541077401000, "line_mean": 27.7777777778, "line_max": 70, "alpha_frac": 0.6785714286, "autogenerated": false, "ratio": 3.352750809061489, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9512688367710269, "avg_score": 0.003726773990243888, "num_lines": 36 }
"""add rollouts Revision ID: e9288c901c60 Revises: 3b0eac21d779 Create Date: 2019-05-20 09:54:52.711057 """ # revision identifiers, used by Alembic. revision = 'e9288c901c60' down_revision = '3b0eac21d779' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('rollout_users', sa.Column('userid', sa.String(), nullable=False), sa.Column('features', postgresql.JSONB(astext_type=sa.Text()), nullable=True), sa.Column('env', sa.String(), nullable=True) ) op.create_index(op.f('ix_rollout_users_env'), 'rollout_users', ['env'], unique=False) op.create_index(op.f('ix_rollout_users_features'), 'rollout_users', ['features'], unique=False) op.create_index(op.f('ix_rollout_users_userid'), 'rollout_users', ['userid'], unique=False) op.create_index(op.f('ix_metrics_env'), 'metrics', ['env'], unique=False) op.create_index(op.f('ix_metrics_feature'), 'metrics', ['feature'], unique=False) op.add_column('toggles', sa.Column('schedule', postgresql.JSONB(astext_type=sa.Text()), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('toggles', 'schedule') op.drop_index(op.f('ix_metrics_feature'), table_name='metrics') op.drop_index(op.f('ix_metrics_env'), table_name='metrics') op.drop_index(op.f('ix_rollout_users_userid'), table_name='rollout_users') op.drop_index(op.f('ix_rollout_users_features'), table_name='rollout_users') op.drop_index(op.f('ix_rollout_users_env'), table_name='rollout_users') op.drop_table('rollout_users') # ### end Alembic commands ###
{ "repo_name": "CanopyTax/toggle-meister", "path": "migrations/versions/e9288c901c60_add_rollouts.py", "copies": "1", "size": "1913", "license": "apache-2.0", "hash": 7916422713842947000, "line_mean": 39.7021276596, "line_max": 99, "alpha_frac": 0.645060115, "autogenerated": false, "ratio": 3.236886632825719, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9362279441381571, "avg_score": 0.003933461288829559, "num_lines": 47 }
"""Add room features Revision ID: 7e03b2262e9e Revises: 868c04697dd7 Create Date: 2018-10-26 13:22:27.627996 """ import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = '7e03b2262e9e' down_revision = '868c04697dd7' branch_labels = None depends_on = None def upgrade(): op.create_table( 'features', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False, index=True, unique=True), sa.Column('title', sa.String(), nullable=False), sa.Column('icon', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id'), schema='roombooking' ) op.create_table( 'equipment_features', sa.Column('equipment_id', sa.Integer(), nullable=False, autoincrement=False), sa.Column('feature_id', sa.Integer(), nullable=False, autoincrement=False), sa.ForeignKeyConstraint(['equipment_id'], ['roombooking.equipment_types.id']), sa.ForeignKeyConstraint(['feature_id'], ['roombooking.features.id']), sa.PrimaryKeyConstraint('equipment_id', 'feature_id'), schema='roombooking' ) def downgrade(): op.drop_table('equipment_features', schema='roombooking') op.drop_table('features', schema='roombooking')
{ "repo_name": "indico/indico", "path": "indico/migrations/versions/20181026_1322_7e03b2262e9e_add_room_features.py", "copies": "7", "size": "1299", "license": "mit", "hash": 1842048663026054400, "line_mean": 29.9285714286, "line_max": 86, "alpha_frac": 0.6643571978, "autogenerated": false, "ratio": 3.464, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7628357197799999, "avg_score": null, "num_lines": null }
"""Add Room.notification_emails column Revision ID: fe73a07da0b4 Revises: 3e4a0c08eae6 Create Date: 2019-03-19 17:28:46.354942 """ import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'fe73a07da0b4' down_revision = '3e4a0c08eae6' branch_labels = None depends_on = None def upgrade(): op.add_column('rooms', sa.Column('notification_emails', postgresql.ARRAY(sa.String()), nullable=False, server_default='{}'), schema='roombooking') op.alter_column('rooms', 'notification_emails', server_default=None, schema='roombooking') # import data from attributes op.execute(''' WITH notification_emails AS ( SELECT rav.room_id, string_to_array(lower(replace(rav.value #>> '{}', ' ', '')), ',') AS emails FROM roombooking.room_attribute_values rav WHERE rav.attribute_id = (SELECT id FROM roombooking.room_attributes WHERE name = 'notification-email') ) UPDATE roombooking.rooms r SET notification_emails = ne.emails FROM notification_emails ne WHERE r.id = ne.room_id; ''') def downgrade(): # restore attribute and data op.execute(''' WITH attr AS ( INSERT INTO roombooking.room_attributes (name, title, is_hidden) VALUES ('notification-email', 'Notification Email', true) -- DO NOTHING wouldn't return us the id so we do a no-op update ON CONFLICT (name) DO UPDATE SET name = excluded.name RETURNING id ) INSERT INTO roombooking.room_attribute_values (attribute_id, room_id, value) SELECT attr.id, r.id, to_json(array_to_string(notification_emails, ',')) FROM roombooking.rooms r, attr WHERE r.notification_emails != '{}' ON CONFLICT (attribute_id, room_id) DO UPDATE SET value = excluded.value; ''') op.drop_column('rooms', 'notification_emails', schema='roombooking')
{ "repo_name": "ThiefMaster/indico", "path": "indico/migrations/versions/20190319_1728_fe73a07da0b4_add_room_notification_emails_column.py", "copies": "7", "size": "2039", "license": "mit", "hash": -6440591727876420000, "line_mean": 36.7592592593, "line_max": 115, "alpha_frac": 0.6449239823, "autogenerated": false, "ratio": 3.7344322344322345, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7879356216732234, "avg_score": null, "num_lines": null }
"""Add room principals table Revision ID: cbe630695800 Revises: 252c0015c9a0 Create Date: 2018-12-13 11:10:12.684382 """ from __future__ import print_function import json import sqlalchemy as sa from alembic import context, op from sqlalchemy.dialects import postgresql from indico.core.auth import multipass from indico.core.db.sqlalchemy import PyIntEnum from indico.core.db.sqlalchemy.principals import PrincipalType from indico.core.db.sqlalchemy.protection import ProtectionMode # revision identifiers, used by Alembic. revision = 'cbe630695800' down_revision = '252c0015c9a0' branch_labels = None depends_on = None def _create_acl_entry(conn, room_id, user_id=None, group_id=None, mp_group_provider=None, mp_group_name=None, full_access=False, permissions=()): permissions = list(permissions) if user_id is not None: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, user_id, type, read_access, full_access, permissions) VALUES (%s, %s, %s, false, %s, %s) ''', (room_id, user_id, PrincipalType.user.value, full_access, permissions)) elif group_id is not None: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, local_group_id, type, read_access, full_access, permissions) VALUES (%s, %s, %s, false, %s, %s) ''', (room_id, group_id, PrincipalType.local_group.value, full_access, permissions)) else: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, mp_group_provider, mp_group_name, type, read_access, full_access, permissions) VALUES (%s, %s, %s, %s, false, %s, %s) ''', (room_id, mp_group_provider, mp_group_name, PrincipalType.multipass_group.value, full_access, permissions)) def _get_attr_value(conn, room_id, attr_id): query = 'SELECT value FROM roombooking.room_attribute_values WHERE room_id = %s AND attribute_id = %s' return conn.execute(query, (room_id, attr_id)).scalar() def _group_to_kwargs(group): if multipass.default_group_provider: return {'mp_group_provider': multipass.default_group_provider.name, 'mp_group_name': group} else: try: return {'local_group_id': int(group)} except ValueError: # non-numeric group id return None def _upgrade_permissions(): conn = op.get_bind() booking_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('allowed-booking-group',)).scalar() manager_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('manager-group',)).scalar() query = 'SELECT id, owner_id, reservations_need_confirmation, is_reservable FROM roombooking.rooms' for room_id, owner_id, reservations_need_confirmation, is_reservable in conn.execute(query): booking_group = manager_group = None if booking_group_attr_id is not None: booking_group = _get_attr_value(conn, room_id, booking_group_attr_id) if manager_group_attr_id is not None: manager_group = _get_attr_value(conn, room_id, manager_group_attr_id) if not booking_group and is_reservable: conn.execute('UPDATE roombooking.rooms SET protection_mode = %s WHERE id = %s', (ProtectionMode.public.value, room_id)) if booking_group: group_kwargs = _group_to_kwargs(booking_group) if group_kwargs is None: print('WARNING: Invalid booking group: {}'.format(booking_group)) else: permission = 'prebook' if reservations_need_confirmation else 'book' _create_acl_entry(conn, room_id, permissions={permission}, **group_kwargs) if manager_group: group_kwargs = _group_to_kwargs(manager_group) if group_kwargs is None: print('WARNING: Invalid manager group: {}'.format(manager_group)) else: _create_acl_entry(conn, room_id, full_access=True, **group_kwargs) # is_reservable==false used allow the room owner to book the room, which # isn't the case anymore, so we mark all rooms as reservable. # above we already kept non-reservable rooms as protected conn.execute('UPDATE roombooking.rooms SET is_reservable = true') def _create_attribute(conn, name, title): res = conn.execute(''' INSERT INTO roombooking.room_attributes (name, title, is_hidden) VALUES (%s, %s, false) RETURNING id ''', (name, title)) return res.fetchone()[0] def _set_attribute_value(conn, room_id, attribute_id, value): res = conn.execute('SELECT value FROM roombooking.room_attribute_values WHERE room_id = %s AND attribute_id = %s', (room_id, attribute_id)) if not res.rowcount: conn.execute(''' INSERT INTO roombooking.room_attribute_values (room_id, attribute_id, value) VALUES (%s, %s, %s) ''', (room_id, attribute_id, json.dumps(value))) elif res.scalar() != value: conn.execute(''' UPDATE roombooking.room_attribute_values SET value = %s WHERE room_id = %s AND attribute_id = %s ''', (json.dumps(value), room_id, attribute_id)) def _downgrade_permissions(): conn = op.get_bind() booking_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('allowed-booking-group',)).scalar() manager_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('manager-group',)).scalar() if booking_group_attr_id is None: booking_group_attr_id = _create_attribute(conn, 'allowed-booking-group', 'Allowed Booking Group') if manager_group_attr_id is None: manager_group_attr_id = _create_attribute(conn, 'manager-group', 'Manager Group') query = 'SELECT id, owner_id, protection_mode FROM roombooking.rooms' for room_id, owner_id, protection_mode in conn.execute(query): res = conn.execute('SELECT * FROM roombooking.room_principals WHERE room_id = %s', (room_id,)) if not res.rowcount and protection_mode == ProtectionMode.protected: conn.execute('UPDATE roombooking.rooms SET is_reservable = false WHERE id = %s', (room_id,)) for row in res: if row.type == PrincipalType.user and row.user_id == owner_id: continue if row.type == PrincipalType.local_group and not multipass.default_group_provider: if row.full_access: _set_attribute_value(conn, room_id, manager_group_attr_id, unicode(row.local_group_id)) if 'book' in row.permissions or 'prebook' in row.permissions: _set_attribute_value(conn, room_id, booking_group_attr_id, unicode(row.local_group_id)) elif (row.type == PrincipalType.multipass_group and multipass.default_group_provider and row.mp_group_provider == multipass.default_group_provider.name): if row.full_access: _set_attribute_value(conn, room_id, manager_group_attr_id, row.mp_group_name) if 'book' in row.permissions or 'prebook' in row.permissions: _set_attribute_value(conn, room_id, booking_group_attr_id, row.mp_group_name) def upgrade(): if context.is_offline_mode(): raise Exception('This upgrade is only possible in online mode') op.create_table( 'room_principals', sa.Column('read_access', sa.Boolean(), nullable=False), sa.Column('full_access', sa.Boolean(), nullable=False), sa.Column('permissions', postgresql.ARRAY(sa.String()), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('room_id', sa.Integer(), nullable=False, index=True), sa.Column('local_group_id', sa.Integer(), nullable=True, index=True), sa.Column('mp_group_provider', sa.String(), nullable=True), sa.Column('mp_group_name', sa.String(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True, index=True), sa.Column('type', PyIntEnum(PrincipalType, exclude_values={PrincipalType.email, PrincipalType.network, PrincipalType.event_role}), nullable=False), sa.CheckConstraint('NOT read_access', name='no_read_access'), sa.CheckConstraint('read_access OR full_access OR array_length(permissions, 1) IS NOT NULL', name='has_privs'), sa.CheckConstraint('type != 1 OR (local_group_id IS NULL AND mp_group_name IS NULL AND ' 'mp_group_provider IS NULL AND user_id IS NOT NULL)', name='valid_user'), sa.CheckConstraint('type != 2 OR (mp_group_name IS NULL AND mp_group_provider IS NULL AND user_id IS NULL AND ' 'local_group_id IS NOT NULL)', name='valid_local_group'), sa.CheckConstraint('type != 3 OR (local_group_id IS NULL AND user_id IS NULL AND mp_group_name IS NOT NULL AND ' 'mp_group_provider IS NOT NULL)', name='valid_multipass_group'), sa.ForeignKeyConstraint(['local_group_id'], ['users.groups.id']), sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']), sa.ForeignKeyConstraint(['user_id'], ['users.users.id']), sa.PrimaryKeyConstraint('id'), schema='roombooking' ) op.create_index(None, 'room_principals', ['mp_group_provider', 'mp_group_name'], schema='roombooking') op.create_index('ix_uq_room_principals_user', 'room_principals', ['user_id', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 1')) op.create_index('ix_uq_room_principals_local_group', 'room_principals', ['local_group_id', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 2')) op.create_index('ix_uq_room_principals_mp_group', 'room_principals', ['mp_group_provider', 'mp_group_name', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 3')) op.add_column('rooms', sa.Column('protection_mode', PyIntEnum(ProtectionMode, exclude_values={ProtectionMode.inheriting}), nullable=False, server_default=unicode(ProtectionMode.protected.value)), schema='roombooking') _upgrade_permissions() op.alter_column('rooms', 'protection_mode', server_default=None, schema='roombooking') def downgrade(): if context.is_offline_mode(): raise Exception('This downgrade is only possible in online mode') _downgrade_permissions() op.drop_column('rooms', 'protection_mode', schema='roombooking') op.drop_table('room_principals', schema='roombooking')
{ "repo_name": "OmeGak/indico", "path": "indico/migrations/versions/20181213_1110_cbe630695800_add_room_principals_table.py", "copies": "3", "size": "11259", "license": "mit", "hash": -1735228198831489500, "line_mean": 51.6121495327, "line_max": 120, "alpha_frac": 0.620303757, "autogenerated": false, "ratio": 3.7146156384031674, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5834919395403168, "avg_score": null, "num_lines": null }
"""Add room principals table Revision ID: cbe630695800 Revises: 252c0015c9a0 Create Date: 2018-12-13 11:10:12.684382 """ import json import sqlalchemy as sa from alembic import context, op from sqlalchemy.dialects import postgresql from indico.core.auth import multipass from indico.core.db.sqlalchemy import PyIntEnum from indico.core.db.sqlalchemy.principals import PrincipalType from indico.core.db.sqlalchemy.protection import ProtectionMode # revision identifiers, used by Alembic. revision = 'cbe630695800' down_revision = '252c0015c9a0' branch_labels = None depends_on = None def _create_acl_entry(conn, room_id, user_id=None, group_id=None, mp_group_provider=None, mp_group_name=None, full_access=False, permissions=()): permissions = list(permissions) if user_id is not None: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, user_id, type, read_access, full_access, permissions) VALUES (%s, %s, %s, false, %s, %s) ''', (room_id, user_id, PrincipalType.user.value, full_access, permissions)) elif group_id is not None: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, local_group_id, type, read_access, full_access, permissions) VALUES (%s, %s, %s, false, %s, %s) ''', (room_id, group_id, PrincipalType.local_group.value, full_access, permissions)) else: conn.execute(''' INSERT INTO roombooking.room_principals (room_id, mp_group_provider, mp_group_name, type, read_access, full_access, permissions) VALUES (%s, %s, %s, %s, false, %s, %s) ''', (room_id, mp_group_provider, mp_group_name, PrincipalType.multipass_group.value, full_access, permissions)) def _get_attr_value(conn, room_id, attr_id): query = 'SELECT value FROM roombooking.room_attribute_values WHERE room_id = %s AND attribute_id = %s' return conn.execute(query, (room_id, attr_id)).scalar() def _get_default_group_provider(): try: provider = multipass.default_group_provider except AttributeError: xargs = context.get_x_argument(as_dictionary=True) return xargs.get('default_group_provider') else: return provider.name def _group_to_kwargs(group): default_group_provider = _get_default_group_provider() if default_group_provider: return {'mp_group_provider': default_group_provider, 'mp_group_name': group} else: try: return {'local_group_id': int(group)} except ValueError: # non-numeric group id return None def _upgrade_permissions(): conn = op.get_bind() booking_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('allowed-booking-group',)).scalar() manager_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('manager-group',)).scalar() query = 'SELECT id, owner_id, reservations_need_confirmation, is_reservable FROM roombooking.rooms' for room_id, owner_id, reservations_need_confirmation, is_reservable in conn.execute(query): booking_group = manager_group = None if booking_group_attr_id is not None: booking_group = _get_attr_value(conn, room_id, booking_group_attr_id) if manager_group_attr_id is not None: manager_group = _get_attr_value(conn, room_id, manager_group_attr_id) if not booking_group and is_reservable: conn.execute('UPDATE roombooking.rooms SET protection_mode = %s WHERE id = %s', (ProtectionMode.public.value, room_id)) if booking_group: group_kwargs = _group_to_kwargs(booking_group) if group_kwargs is None: print(f'WARNING: Invalid booking group: {booking_group}') else: permission = 'prebook' if reservations_need_confirmation else 'book' _create_acl_entry(conn, room_id, permissions={permission}, **group_kwargs) if manager_group: group_kwargs = _group_to_kwargs(manager_group) if group_kwargs is None: print(f'WARNING: Invalid manager group: {manager_group}') else: _create_acl_entry(conn, room_id, full_access=True, **group_kwargs) # is_reservable==false used allow the room owner to book the room, which # isn't the case anymore, so we mark all rooms as reservable. # above we already kept non-reservable rooms as protected conn.execute('UPDATE roombooking.rooms SET is_reservable = true') def _create_attribute(conn, name, title): res = conn.execute(''' INSERT INTO roombooking.room_attributes (name, title, is_hidden) VALUES (%s, %s, false) RETURNING id ''', (name, title)) return res.fetchone()[0] def _set_attribute_value(conn, room_id, attribute_id, value): res = conn.execute('SELECT value FROM roombooking.room_attribute_values WHERE room_id = %s AND attribute_id = %s', (room_id, attribute_id)) if not res.rowcount: conn.execute(''' INSERT INTO roombooking.room_attribute_values (room_id, attribute_id, value) VALUES (%s, %s, %s) ''', (room_id, attribute_id, json.dumps(value))) elif res.scalar() != value: conn.execute(''' UPDATE roombooking.room_attribute_values SET value = %s WHERE room_id = %s AND attribute_id = %s ''', (json.dumps(value), room_id, attribute_id)) def _downgrade_permissions(): default_group_provider = _get_default_group_provider() conn = op.get_bind() booking_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('allowed-booking-group',)).scalar() manager_group_attr_id = conn.execute('SELECT id FROM roombooking.room_attributes WHERE name = %s', ('manager-group',)).scalar() if booking_group_attr_id is None: booking_group_attr_id = _create_attribute(conn, 'allowed-booking-group', 'Allowed Booking Group') if manager_group_attr_id is None: manager_group_attr_id = _create_attribute(conn, 'manager-group', 'Manager Group') query = 'SELECT id, owner_id, protection_mode FROM roombooking.rooms' for room_id, owner_id, protection_mode in conn.execute(query): res = conn.execute('SELECT * FROM roombooking.room_principals WHERE room_id = %s', (room_id,)) if not res.rowcount and protection_mode == ProtectionMode.protected: conn.execute('UPDATE roombooking.rooms SET is_reservable = false WHERE id = %s', (room_id,)) for row in res: if row.type == PrincipalType.user and row.user_id == owner_id: continue if row.type == PrincipalType.local_group and not default_group_provider: if row.full_access: _set_attribute_value(conn, room_id, manager_group_attr_id, str(row.local_group_id)) if 'book' in row.permissions or 'prebook' in row.permissions: _set_attribute_value(conn, room_id, booking_group_attr_id, str(row.local_group_id)) elif (row.type == PrincipalType.multipass_group and default_group_provider and row.mp_group_provider == default_group_provider.name): if row.full_access: _set_attribute_value(conn, room_id, manager_group_attr_id, row.mp_group_name) if 'book' in row.permissions or 'prebook' in row.permissions: _set_attribute_value(conn, room_id, booking_group_attr_id, row.mp_group_name) def upgrade(): if context.is_offline_mode(): raise Exception('This upgrade is only possible in online mode') op.create_table( 'room_principals', sa.Column('read_access', sa.Boolean(), nullable=False), sa.Column('full_access', sa.Boolean(), nullable=False), sa.Column('permissions', postgresql.ARRAY(sa.String()), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('room_id', sa.Integer(), nullable=False, index=True), sa.Column('local_group_id', sa.Integer(), nullable=True, index=True), sa.Column('mp_group_provider', sa.String(), nullable=True), sa.Column('mp_group_name', sa.String(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True, index=True), sa.Column('type', PyIntEnum(PrincipalType, exclude_values={PrincipalType.email, PrincipalType.network, PrincipalType.event_role}), nullable=False), sa.CheckConstraint('NOT read_access', name='no_read_access'), sa.CheckConstraint('read_access OR full_access OR array_length(permissions, 1) IS NOT NULL', name='has_privs'), sa.CheckConstraint('type != 1 OR (local_group_id IS NULL AND mp_group_name IS NULL AND ' 'mp_group_provider IS NULL AND user_id IS NOT NULL)', name='valid_user'), sa.CheckConstraint('type != 2 OR (mp_group_name IS NULL AND mp_group_provider IS NULL AND user_id IS NULL AND ' 'local_group_id IS NOT NULL)', name='valid_local_group'), sa.CheckConstraint('type != 3 OR (local_group_id IS NULL AND user_id IS NULL AND mp_group_name IS NOT NULL AND ' 'mp_group_provider IS NOT NULL)', name='valid_multipass_group'), sa.ForeignKeyConstraint(['local_group_id'], ['users.groups.id']), sa.ForeignKeyConstraint(['room_id'], ['roombooking.rooms.id']), sa.ForeignKeyConstraint(['user_id'], ['users.users.id']), sa.PrimaryKeyConstraint('id'), schema='roombooking' ) op.create_index(None, 'room_principals', ['mp_group_provider', 'mp_group_name'], schema='roombooking') op.create_index('ix_uq_room_principals_user', 'room_principals', ['user_id', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 1')) op.create_index('ix_uq_room_principals_local_group', 'room_principals', ['local_group_id', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 2')) op.create_index('ix_uq_room_principals_mp_group', 'room_principals', ['mp_group_provider', 'mp_group_name', 'room_id'], unique=True, schema='roombooking', postgresql_where=sa.text('type = 3')) op.add_column('rooms', sa.Column('protection_mode', PyIntEnum(ProtectionMode, exclude_values={ProtectionMode.inheriting}), nullable=False, server_default=str(ProtectionMode.protected.value)), schema='roombooking') _upgrade_permissions() op.alter_column('rooms', 'protection_mode', server_default=None, schema='roombooking') def downgrade(): if context.is_offline_mode(): raise Exception('This downgrade is only possible in online mode') _downgrade_permissions() op.drop_column('rooms', 'protection_mode', schema='roombooking') op.drop_table('room_principals', schema='roombooking')
{ "repo_name": "indico/indico", "path": "indico/migrations/versions/20181213_1110_cbe630695800_add_room_principals_table.py", "copies": "4", "size": "11530", "license": "mit", "hash": 6371399686940524000, "line_mean": 50.2444444444, "line_max": 120, "alpha_frac": 0.6202948829, "autogenerated": false, "ratio": 3.713365539452496, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6333660422352496, "avg_score": null, "num_lines": null }
"""Add rss bits! Revision ID: 34f427187628 Revises: b88c4e0d8ed4 Create Date: 2017-02-27 02:45:31.776790 """ # revision identifiers, used by Alembic. revision = '34f427187628' down_revision = 'b88c4e0d8ed4' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy_utils.types import TSVectorType from sqlalchemy_searchable import make_searchable import sqlalchemy_utils # Patch in knowledge of the citext type, so it reflects properly. from sqlalchemy.dialects.postgresql.base import ischema_names import citext import queue import datetime from sqlalchemy.dialects.postgresql import ENUM from sqlalchemy.dialects.postgresql import JSON from sqlalchemy.dialects.postgresql import TSVECTOR ischema_names['citext'] = citext.CIText from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('rss_parser_feed_name_lut_version', sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False), sa.Column('feed_netloc', sa.Text(), autoincrement=False, nullable=True), sa.Column('feed_name', sa.Text(), autoincrement=False, nullable=True), sa.Column('transaction_id', sa.BigInteger(), autoincrement=False, nullable=False), sa.Column('end_transaction_id', sa.BigInteger(), nullable=True), sa.Column('operation_type', sa.SmallInteger(), nullable=False), sa.PrimaryKeyConstraint('id', 'transaction_id') ) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_end_transaction_id'), 'rss_parser_feed_name_lut_version', ['end_transaction_id'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_feed_name'), 'rss_parser_feed_name_lut_version', ['feed_name'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_feed_netloc'), 'rss_parser_feed_name_lut_version', ['feed_netloc'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_id'), 'rss_parser_feed_name_lut_version', ['id'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_operation_type'), 'rss_parser_feed_name_lut_version', ['operation_type'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_version_transaction_id'), 'rss_parser_feed_name_lut_version', ['transaction_id'], unique=False) op.create_table('rss_parser_funcs', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('version', sa.Integer(), nullable=True), sa.Column('feed_name', sa.Text(), nullable=False), sa.Column('enabled', sa.Boolean(), nullable=True), sa.Column('func', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_rss_parser_funcs_feed_name'), 'rss_parser_funcs', ['feed_name'], unique=True) op.create_index(op.f('ix_rss_parser_funcs_id'), 'rss_parser_funcs', ['id'], unique=False) op.create_table('rss_parser_funcs_version', sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False), sa.Column('version', sa.Integer(), autoincrement=False, nullable=True), sa.Column('feed_name', sa.Text(), autoincrement=False, nullable=True), sa.Column('enabled', sa.Boolean(), autoincrement=False, nullable=True), sa.Column('func', sa.Text(), autoincrement=False, nullable=True), sa.Column('transaction_id', sa.BigInteger(), autoincrement=False, nullable=False), sa.Column('end_transaction_id', sa.BigInteger(), nullable=True), sa.Column('operation_type', sa.SmallInteger(), nullable=False), sa.PrimaryKeyConstraint('id', 'transaction_id') ) op.create_index(op.f('ix_rss_parser_funcs_version_end_transaction_id'), 'rss_parser_funcs_version', ['end_transaction_id'], unique=False) op.create_index(op.f('ix_rss_parser_funcs_version_feed_name'), 'rss_parser_funcs_version', ['feed_name'], unique=False) op.create_index(op.f('ix_rss_parser_funcs_version_id'), 'rss_parser_funcs_version', ['id'], unique=False) op.create_index(op.f('ix_rss_parser_funcs_version_operation_type'), 'rss_parser_funcs_version', ['operation_type'], unique=False) op.create_index(op.f('ix_rss_parser_funcs_version_transaction_id'), 'rss_parser_funcs_version', ['transaction_id'], unique=False) op.create_table('rss_parser_feed_name_lut', sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('feed_netloc', sa.Text(), nullable=False), sa.Column('feed_name', sa.Text(), nullable=False), sa.ForeignKeyConstraint(['feed_name'], ['rss_parser_funcs.feed_name'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('feed_netloc', 'feed_name') ) op.create_index(op.f('ix_rss_parser_feed_name_lut_feed_name'), 'rss_parser_feed_name_lut', ['feed_name'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_feed_netloc'), 'rss_parser_feed_name_lut', ['feed_netloc'], unique=False) op.create_index(op.f('ix_rss_parser_feed_name_lut_id'), 'rss_parser_feed_name_lut', ['id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_rss_parser_feed_name_lut_id'), table_name='rss_parser_feed_name_lut') op.drop_index(op.f('ix_rss_parser_feed_name_lut_feed_netloc'), table_name='rss_parser_feed_name_lut') op.drop_index(op.f('ix_rss_parser_feed_name_lut_feed_name'), table_name='rss_parser_feed_name_lut') op.drop_table('rss_parser_feed_name_lut') op.drop_index(op.f('ix_rss_parser_funcs_version_transaction_id'), table_name='rss_parser_funcs_version') op.drop_index(op.f('ix_rss_parser_funcs_version_operation_type'), table_name='rss_parser_funcs_version') op.drop_index(op.f('ix_rss_parser_funcs_version_id'), table_name='rss_parser_funcs_version') op.drop_index(op.f('ix_rss_parser_funcs_version_feed_name'), table_name='rss_parser_funcs_version') op.drop_index(op.f('ix_rss_parser_funcs_version_end_transaction_id'), table_name='rss_parser_funcs_version') op.drop_table('rss_parser_funcs_version') op.drop_index(op.f('ix_rss_parser_funcs_id'), table_name='rss_parser_funcs') op.drop_index(op.f('ix_rss_parser_funcs_feed_name'), table_name='rss_parser_funcs') op.drop_table('rss_parser_funcs') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_transaction_id'), table_name='rss_parser_feed_name_lut_version') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_operation_type'), table_name='rss_parser_feed_name_lut_version') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_id'), table_name='rss_parser_feed_name_lut_version') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_feed_netloc'), table_name='rss_parser_feed_name_lut_version') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_feed_name'), table_name='rss_parser_feed_name_lut_version') op.drop_index(op.f('ix_rss_parser_feed_name_lut_version_end_transaction_id'), table_name='rss_parser_feed_name_lut_version') op.drop_table('rss_parser_feed_name_lut_version') ### end Alembic commands ###
{ "repo_name": "fake-name/ReadableWebProxy", "path": "alembic/versions/00026_34f427187628_add_rss_bits.py", "copies": "1", "size": "7058", "license": "bsd-3-clause", "hash": -3768902020650808000, "line_mean": 59.8448275862, "line_max": 157, "alpha_frac": 0.7111079626, "autogenerated": false, "ratio": 3.0820960698689954, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4293204032468995, "avg_score": null, "num_lines": null }
"""Add RTPLaunchRecord table Revision ID: bad90ab035ba Revises: 77c082c87844 Create Date: 2021-03-08 19:16:44.611253+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "bad90ab035ba" down_revision = "77c082c87844" branch_labels = None depends_on = None def upgrade(): op.create_table( "rtp_launch_record", sa.Column("obsid", sa.BigInteger(), nullable=False), sa.Column("submitted_time", sa.BigInteger(), nullable=True), sa.Column("rtp_attempts", sa.BigInteger(), nullable=False), sa.Column("jd", sa.BigInteger(), nullable=False), sa.Column("obs_tag", sa.String(length=128), nullable=False), sa.Column("filename", sa.String(length=128), nullable=False), sa.Column("prefix", sa.String(length=128), nullable=False), sa.ForeignKeyConstraint( ["obsid"], ["hera_obs.obsid"], ), sa.PrimaryKeyConstraint("obsid"), ) def downgrade(): op.drop_table("rtp_launch_record")
{ "repo_name": "HERA-Team/hera_mc", "path": "alembic/versions/bad90ab035ba_add_rtplaunchrecord_table.py", "copies": "1", "size": "1092", "license": "bsd-2-clause", "hash": 3032425211695831600, "line_mean": 27.7368421053, "line_max": 69, "alpha_frac": 0.6575091575, "autogenerated": false, "ratio": 3.3808049535603715, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9538314111060371, "avg_score": 0, "num_lines": 38 }
"""Add rtp_task_resource_record table Revision ID: 3d3c72ecbc0d Revises: c9a1ff35c6ed Create Date: 2018-01-20 21:35:16.716477+00:00 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3d3c72ecbc0d' down_revision = 'c9a1ff35c6ed' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('rtp_task_resource_record', sa.Column('obsid', sa.BigInteger(), nullable=False), sa.Column('task_name', sa.Text(), nullable=False), sa.Column('start_time', sa.BigInteger(), nullable=False), sa.Column('stop_time', sa.BigInteger(), nullable=False), sa.Column('max_memory', sa.Float(), nullable=True), sa.Column('avg_cpu_load', sa.Float(), nullable=True), sa.ForeignKeyConstraint(['obsid'], ['hera_obs.obsid'], ), sa.PrimaryKeyConstraint('obsid', 'task_name') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('rtp_task_resource_record') # ### end Alembic commands ###
{ "repo_name": "HERA-Team/Monitor_and_Control", "path": "alembic/versions/3d3c72ecbc0d_add_rtp_task_resource_record_table.py", "copies": "2", "size": "1123", "license": "bsd-2-clause", "hash": -7458420873891244000, "line_mean": 29.3513513514, "line_max": 65, "alpha_frac": 0.6758682102, "autogenerated": false, "ratio": 3.154494382022472, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48303625922224724, "avg_score": null, "num_lines": null }
"""add_rtp_tracking_tables Revision ID: bb6db4d3fee6 Revises: 77c082c87844 Create Date: 2021-02-18 21:10:33.076138+00:00 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = 'bb6db4d3fee6' down_revision = 'bad90ab035ba' branch_labels = None depends_on = None def upgrade(): op.create_table( 'rtp_task_jobid', sa.Column('obsid', sa.BigInteger(), nullable=False), sa.Column('task_name', sa.Text(), nullable=False), sa.Column('start_time', sa.BigInteger(), nullable=False), sa.Column('job_id', sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint(['obsid'], ['hera_obs.obsid'], ), sa.PrimaryKeyConstraint('obsid', 'task_name', 'start_time') ) op.create_table( 'rtp_task_multiple_jobid', sa.Column('obsid_start', sa.BigInteger(), nullable=False), sa.Column('task_name', sa.Text(), nullable=False), sa.Column('start_time', sa.BigInteger(), nullable=False), sa.Column('job_id', sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint(['obsid_start'], ['hera_obs.obsid'], ), sa.PrimaryKeyConstraint('obsid_start', 'task_name', 'start_time') ) op.create_table( 'rtp_task_multiple_resource_record', sa.Column('obsid_start', sa.BigInteger(), nullable=False), sa.Column('task_name', sa.Text(), nullable=False), sa.Column('start_time', sa.BigInteger(), nullable=False), sa.Column('stop_time', sa.BigInteger(), nullable=False), sa.Column('max_memory', sa.Float(), nullable=True), sa.Column('avg_cpu_load', sa.Float(), nullable=True), sa.ForeignKeyConstraint(['obsid_start'], ['hera_obs.obsid'], ), sa.PrimaryKeyConstraint('obsid_start', 'task_name') ) op.create_table( 'rtp_task_multiple_track', sa.Column('obsid_start', sa.BigInteger(), nullable=False), sa.Column('task_name', sa.Text(), nullable=False), sa.Column('obsid', sa.BigInteger(), nullable=False), sa.ForeignKeyConstraint(['obsid'], ['hera_obs.obsid'], ), sa.ForeignKeyConstraint(['obsid_start'], ['hera_obs.obsid'], ), sa.PrimaryKeyConstraint('obsid_start', 'task_name', 'obsid') ) def downgrade(): op.drop_table('rtp_task_multiple_track') op.drop_table('rtp_task_multiple_resource_record') op.drop_table('rtp_task_multiple_jobid') op.drop_table('rtp_task_jobid')
{ "repo_name": "HERA-Team/hera_mc", "path": "alembic/versions/bb6db4d3fee6_add_rtp_tracking_tables.py", "copies": "1", "size": "2508", "license": "bsd-2-clause", "hash": 6300514259796285000, "line_mean": 38.1875, "line_max": 73, "alpha_frac": 0.6403508772, "autogenerated": false, "ratio": 3.282722513089005, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9423073390289005, "avg_score": 0, "num_lines": 64 }
"""Add rule table to configure rules and alerts. Revision ID: fd28e46e46a6 Revises: d2b00dd93241 Create Date: 2016-05-02 17:46:46.658227 """ # revision identifiers, used by Alembic. revision = 'fd28e46e46a6' down_revision = 'd2b00dd93241' from alembic import op import sqlalchemy as sa import doorman.database from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('rule', sa.Column('id', sa.Integer(), nullable=False), sa.Column('type', sa.String(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('action', sa.Enum('added', 'removed', 'both', name='rule_actions'), nullable=False), sa.Column('alerters', postgresql.ARRAY(sa.String()), nullable=False), sa.Column('config', postgresql.JSONB(), nullable=True), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('rule') ### end Alembic commands ### postgresql.ENUM(name='rule_actions').drop(op.get_bind(), checkfirst=False)
{ "repo_name": "mwielgoszewski/doorman", "path": "migrations/versions/fd28e46e46a6_.py", "copies": "1", "size": "1147", "license": "mit", "hash": 5240756503258983000, "line_mean": 30.8611111111, "line_max": 98, "alpha_frac": 0.6904969486, "autogenerated": false, "ratio": 3.4444444444444446, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46349413930444444, "avg_score": null, "num_lines": null }
"""addRuleTiming Revision ID: e4d26a4b740e Revises: 77ce67003a95 Create Date: 2016-03-24 14:24:55.778000 """ # revision identifiers, used by Alembic. revision = 'e4d26a4b740e' down_revision = '77ce67003a95' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_validation(): ### commands auto generated by Alembic - please adjust! ### op.create_table('rule_timing', sa.Column('rule_timing_id', sa.Integer(), nullable=False), sa.Column('name', sa.Text(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('rule_timing_id') ) op.add_column(u'rule', sa.Column('rule_timing_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'rule', 'rule_timing', ['rule_timing_id'], ['rule_timing_id']) ### end Alembic commands ### def downgrade_validation(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'rule', type_='foreignkey') op.drop_column(u'rule', 'rule_timing_id') op.drop_table('rule_timing') ### end Alembic commands ###
{ "repo_name": "fedspendingtransparency/data-act-validator", "path": "dataactvalidator/migrations/versions/e4d26a4b740e_addruletiming.py", "copies": "1", "size": "1269", "license": "cc0-1.0", "hash": 2777950557507053600, "line_mean": 27.8409090909, "line_max": 94, "alpha_frac": 0.6753349094, "autogenerated": false, "ratio": 3.253846153846154, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9393623159356088, "avg_score": 0.007111580778013155, "num_lines": 44 }
"""Adds a backend for storing documents as flat files. To use add this to settings.local: NORMALIZED_PROCESSING = ['storage'] RAW_PROCESSING = ['storage'] """ import os import copy import json from scrapi.processing.base import BaseProcessor class StorageProcessor(BaseProcessor): NAME = 'storage' def process_raw(self, raw): filename = 'archive/{}/{}/raw.{}'.format(raw['source'], raw['docID'], raw['filetype']) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) new_attrs = copy.deepcopy(raw.attributes) if new_attrs.get('versions'): new_attrs['versions'] = map(str, new_attrs['versions']) with open(filename, 'w') as f: f.write(json.dumps(new_attrs, indent=4)) def process_normalized(self, raw, normalized): filename = 'archive/{}/{}/normalized.json'.format(raw['source'], raw['docID'], raw['filetype']) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'w') as f: f.write(json.dumps(normalized.attributes, indent=4))
{ "repo_name": "icereval/scrapi", "path": "scrapi/processing/storage.py", "copies": "1", "size": "1173", "license": "apache-2.0", "hash": -2513332523352699400, "line_mean": 30.7027027027, "line_max": 103, "alpha_frac": 0.6359761296, "autogenerated": false, "ratio": 3.723809523809524, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48597856534095235, "avg_score": null, "num_lines": null }
"""Adds a backend for storing documents as flat files. To use add this to settings.local: NORMALIZED_PROCESSING = ['storage'] RAW_PROCESSING = ['storage'] """ import os import json from scrapi.util import json_without_bytes from scrapi.processing.base import BaseProcessor from .postgres import HarvesterResponseModel, DatabaseManager as StubManager class StorageProcessor(BaseProcessor): NAME = 'storage' manager = StubManager() def process_raw(self, raw): self.write(raw['source'], raw['docID'], 'raw', raw.attributes) def process_normalized(self, raw, normalized): self.write(raw['source'], raw['docID'], 'normalized', normalized.attributes) def write(self, source, doc_id, filename, content): filepath = 'archive/{}/{}/{}.json'.format(source, doc_id, filename) if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) with open(filepath, 'w') as f: f.write(json.dumps(json_without_bytes(content), indent=4)) def documents(self, *sources): raise NotImplementedError def get_versions(self, source, docID): raise NotImplementedError @property def HarvesterResponseModel(self): return HarvesterResponseModel
{ "repo_name": "CenterForOpenScience/scrapi", "path": "scrapi/processing/storage.py", "copies": "1", "size": "1287", "license": "apache-2.0", "hash": -1998086297258879700, "line_mean": 27.6, "line_max": 84, "alpha_frac": 0.6837606838, "autogenerated": false, "ratio": 3.9722222222222223, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.000261437908496732, "num_lines": 45 }
"""Adds account to a project""" from baseCmd import * from baseResponse import * class addAccountToProjectCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """ID of the project to add the account to""" """Required""" self.projectid = None self.typeInfo['projectid'] = 'uuid' """name of the account to be added to the project""" self.account = None self.typeInfo['account'] = 'string' """email to which invitation to the project is going to be sent""" self.email = None self.typeInfo['email'] = 'string' self.required = ["projectid", ] class addAccountToProjectResponse (baseResponse): typeInfo = {} def __init__(self): """any text associated with the success or failure""" self.displaytext = None self.typeInfo['displaytext'] = 'string' """true if operation is executed successfully""" self.success = None self.typeInfo['success'] = 'boolean'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addAccountToProject.py", "copies": "1", "size": "1031", "license": "apache-2.0", "hash": 6376106598097270000, "line_mean": 29.3235294118, "line_max": 74, "alpha_frac": 0.6023278371, "autogenerated": false, "ratio": 4.191056910569106, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.029411764705882353, "num_lines": 34 }
"""Adds a chook to a git repository. Usage: chooks add [--stdin | --argument] [--once | --filter=FILTER...] [--global] [--fatal] [--hook=NAME...] [--name=NAME] [--disabled] [--] <command> [<args>...] Options: --stdin Supply input files to this chook via stdin. --filter=<filter> Only execute this chook for files who names match the given filter. --global Execute this chook for all repositories. --hook=<name> Name of the git hooks this chook will be executed for (if not specified, default to all git hooks). --fatal Return a nonzero status to the git hook if this chook returns a nonzero status. --once If specified, this chook is only applied once for the git hook. If not specified, this chook is applied against all files echoed by 'git status' (excluding ignored/untracked) --name=<name> Custom hook name (defaults to the command name). --disabled Default the hook to a disabled state. """ from chooks import constants from chooks import git # TODO interactive mode? def run(args): full_cmd = '%s %s' % (args['<command>'], ' '.join(args['<args>'])) filters = args.get('--filter') and ','.join(args['--filter']) # TODO validate hook names, making sure they're actually git hooks hooks = args.get('--hook') and ','.join(args['--hook']) values = { constants.KEY_COMMAND: full_cmd, constants.KEY_STDIN: args.get('--stdin'), constants.KEY_FILTERS: filters, constants.KEY_HOOKS: hooks, constants.KEY_FATAL: args.get('--fatal'), constants.KEY_DISABLED: args.get('--disabled'), } hook_name = args.get('--name') or args['<command>'] is_global = args.get('--global', False) if git.set_hook_values(hook_name, values, is_global=is_global): return 0 return 1
{ "repo_name": "thegedge/chooks", "path": "chooks/commands/add.py", "copies": "1", "size": "1970", "license": "mit", "hash": -4633034512226892000, "line_mean": 38.4, "line_max": 79, "alpha_frac": 0.5934010152, "autogenerated": false, "ratio": 3.995943204868154, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5089344220068154, "avg_score": null, "num_lines": null }
"""Adds a directory to sys.path, permanently. """ import sys import os import site HEADER = """\ # .pth file created by the pypath script. # edit at your own risk """ SITEDIR = site.getusersitepackages() PATH = os.path.join(SITEDIR, "pypath.pth") if not os.path.exists(SITEDIR): os.mkdirs(SITEDIR) def add(path, pth_file=None): path = path.strip() pth_file = pth_file or PATH if not os.path.exists(path): raise ValueError("doesn't exist: {}".format(path)) with open(pth_file, "r") as f: for line in f: if line.strip(os.linesep) == path: # already added return empty = not f.tell() with open(pth_file, "a") as f: if empty: f.write(HEADER) f.write(os.linesep + path) def remove(path, pth_file=None): pth_file = pth_file or PATH try: with open(pth_file, "r") as f: lines = f.read().splitlines()[2:] except IOError: raise ValueError("not found: {}".format(path)) try: lines.remove(path) except ValueError: raise ValueError("not found: {}".format(path)) lines.insert(0, HEADER) with open(pth_file, "w") as f: f.write(os.linesep.join(lines)) def show(pth_file=None): pth_file = pth_file or PATH print("current paths ({}):".format(pth_file)) try: f = open(pth_file, "r") except IOError: return with f: lines = f.read() if not lines.startswith(HEADER): raise ValueError(".pth file is invalid: {}".format(pth_file)) for line in lines.splitlines()[2:]: if not line.strip(): continue print(line) if __name__ == "__main__": import argparse EPILOG = "If no args are passed, the current contents are shown." parser = argparse.ArgumentParser(epilog=EPILOG) group = parser.add_mutually_exclusive_group() group.add_argument("-a", "--add", metavar="PATH") group.add_argument("-r", "--remove", metavar="PATH") parser.add_argument("-f", "--file", metavar="<path to .pth file>") args = parser.parse_args() if args.add: add(args.add, args.file) elif args.remove: remove(args.remove, args.file) else: show(args.file)
{ "repo_name": "ActiveState/code", "path": "recipes/Python/578043_Script_that_Adds_Directory_syspath/recipe-578043.py", "copies": "1", "size": "2290", "license": "mit", "hash": -7103668853676106000, "line_mean": 25.0227272727, "line_max": 73, "alpha_frac": 0.5794759825, "autogenerated": false, "ratio": 3.4855403348554033, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9565016317355404, "avg_score": 0, "num_lines": 88 }
"""Adds a distinct vulnerbility table column for keeping track of the initial review_feedback reviewer. Revision ID: c10e1faccb1c Revises: fb11cb6a2398 Create Date: 2020-10-03 09:50:58.363062 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "c10e1faccb1c" down_revision = "fb11cb6a2398" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "vulnerability", sa.Column("feedback_reviewer_id", sa.Integer(), nullable=True) ) op.create_foreign_key( "fk_feedback_reviewer_id", "vulnerability", "user", ["feedback_reviewer_id"], ["id"], ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint("fk_feedback_reviewer_id", "vulnerability", type_="foreignkey") op.drop_column("vulnerability", "feedback_reviewer_id") # ### end Alembic commands ###
{ "repo_name": "google/vulncode-db", "path": "migrations/versions/c10e1faccb1c_adds_a_distinct_vulnerbility_table_.py", "copies": "1", "size": "1041", "license": "apache-2.0", "hash": 1216071739682578200, "line_mean": 26.3947368421, "line_max": 103, "alpha_frac": 0.6666666667, "autogenerated": false, "ratio": 3.4932885906040267, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9655682458112897, "avg_score": 0.0008545598382258999, "num_lines": 38 }
"""Adds a empty protocols column to `base_result` and wavefunction to `result` Revision ID: c194a8ef6acf Revises: cc54842bb6ba Create Date: 2019-09-30 10:31:23.552722 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "c194a8ef6acf" down_revision = "cc54842bb6ba" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column("base_result", sa.Column("protocols", postgresql.JSONB(astext_type=sa.Text()), nullable=True)) op.execute("UPDATE base_result SET protocols='{}'::json") op.alter_column("base_result", "protocols", nullable=False) op.add_column("result", sa.Column("wavefunction", postgresql.JSONB(astext_type=sa.Text()), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("base_result", "protocols") op.drop_column("result", "wavefunction") # ### end Alembic commands ###
{ "repo_name": "psi4/DatenQM", "path": "qcfractal/alembic/versions/c194a8ef6acf_protocols.py", "copies": "2", "size": "1081", "license": "bsd-3-clause", "hash": 5937581573691617000, "line_mean": 32.78125, "line_max": 112, "alpha_frac": 0.7058279371, "autogenerated": false, "ratio": 3.420886075949367, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5126714013049367, "avg_score": null, "num_lines": null }
"""Adds a few finishing touches to the IPHAS DR2 binary FITS catalogues. It will add TDISP keywords, sanitise TUNIT keywords, add checksums, and add origin information. """ import numpy as np from astropy.io import fits from astropy import log def augment(filename_origin, filename_target): log.info('Opening {0}'.format(filename_origin)) f = fits.open(filename_origin) for i in np.arange(1, f[1].header['TFIELDS']+1, 1): # Loop over all columns name = f[1].header['TTYPE{0}'.format(i)] # Set an appropriate TDISP keyword for floating points if name in ['ra', 'dec', 'l', 'b']: f[1].header['TDISP{0}'.format(i)] = 'F9.5' if name in ['posErr', 'pStar', 'pGalaxy', 'pNoise', 'pSaturated', 'rGauSig', 'rEll', 'rSeeing', 'iGauSig', 'iEll', 'iSeeing', 'haGauSig', 'haEll', 'haSeeing', 'seeing']: f[1].header['TDISP{0}'.format(i)] = 'F4.2' if name in ['mergedClassStat', 'rmi', 'rmha', 'r', 'rErr', 'rPeakMag', 'rPeakMagErr', 'rAperMag1', 'rAperMag1Err', 'rAperMag3', 'rAperMag3Err', 'rClassStat', 'i', 'iErr', 'iPeakMag', 'iPeakMagErr', 'iAperMag1', 'iAperMag1Err', 'iAperMag3', 'iAperMag3Err', 'iClassStat', 'iXi', 'iEta', 'ha', 'haErr', 'haPeakMag', 'haPeakMagErr', 'haAperMag1', 'haAperMag1Err', 'haAperMag3', 'haAperMag3Err', 'haClassStat', 'haXi', 'haEta', 'r2', 'rErr2', 'i2', 'iErr2', 'ha2', 'haErr2']: f[1].header['TDISP{0}'.format(i)] = 'F5.2' if name in ['rPa', 'iPa', 'haPa']: f[1].header['TDISP{0}'.format(i)] = 'F5.1' if name in ['rMJD', 'iMJD', 'haMJD']: f[1].header['TDISP{0}'.format(i)] = 'F11.5' if name in ['rX', 'rY', 'iX', 'iY', 'haX', 'haY']: f[1].header['TDISP{0}'.format(i)] = 'F7.2' # Bring unit definitions in line with the FITS standard try: unit = f[1].header['TUNIT{0}'.format(i)] if unit == 'degrees': f[1].header['TUNIT{0}'.format(i)] = 'deg' if unit == 'Magnitude': f[1].header['TUNIT{0}'.format(i)] = 'mag' if unit == 'Pixels': f[1].header['TUNIT{0}'.format(i)] = 'pixel' if unit == 'Arcsec': f[1].header['TUNIT{0}'.format(i)] = 'arcsec' if unit in ['Sigma', 'Number', 'Flag', 'N-sigma', 'bitmask', 'Julian days', 'String']: del f[1].header['TUNIT{0}'.format(i)] except KeyError: pass # Make the header more informative f[1].header['EXTNAME'] = 'CATALOG' f[1].header['ORIGIN'] = 'IPHAS' f[1].header['PHOTSYS'] = 'VEGA' f[1].header['REFERENC'] = 'Barentsen et al (2014)' f[1].header['PRODCATG'] = 'SCIENCE.CATALOGTILE' f[1].header['COMMENT'] = ' _____ _____ _ _ _____ ' f[1].header['COMMENT'] = '|_ _| __ \| | | | /\ / ____|' f[1].header['COMMENT'] = ' | | | |__) | |__| | / \ | (___ ' f[1].header['COMMENT'] = ' | | | ___/| __ | / /\ \ \___ \ ' f[1].header['COMMENT'] = ' _| |_| | | | | |/ ____ \ ____) |' f[1].header['COMMENT'] = '|_____|_| |_| |_/_/ \_\_____/ ' f[1].header['COMMENT'] = '' f[1].header['COMMENT'] = 'This catalogue is part of IPHAS DR2.' f[1].header['COMMENT'] = 'For more information, visit http://www.iphas.org.' log.info('Writing {0}'.format(filename_target)) f.writeto(filename_target, checksum=True, clobber=True) if __name__ == '__main__': DR2 = '/car-data/gb/iphas-dr2-rc6/concatenated' ##for l in [215]: for l in np.arange(25, 220, 5): for part in ['a', 'b']: origin = DR2+'/full-compressed/iphas-dr2-{0}{1}.fits.gz'.format(l, part) target = DR2+'/full-augmented/iphas-dr2-{0}{1}.fits.gz'.format(l, part) augment(origin, target) origin = DR2+'/light-compressed/iphas-dr2-{0}{1}-light.fits.gz'.format(l, part) target = DR2+'/light-augmented/iphas-dr2-{0}{1}-light.fits.gz'.format(l, part) augment(origin, target)
{ "repo_name": "barentsen/iphas-dr2", "path": "scripts/release-preparation/augment-catalogue.py", "copies": "1", "size": "4349", "license": "mit", "hash": 1715670377547698000, "line_mean": 43.3775510204, "line_max": 91, "alpha_frac": 0.4899977006, "autogenerated": false, "ratio": 2.922715053763441, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3912712754363441, "avg_score": null, "num_lines": null }
# Adds a fourth 'name' column to the accessionid_to_taxonid.tsv table. import argparse, csv def get_accession_to_taxon(accessionfilename): accession_to_taxon = {} with open(accessionfilename, 'r') as afile: i = 0 for line in afile: fields = line.split('\t') ncbi_id = fields[1].strip() if ncbi_id != '*': genbank_id = fields[0].strip() if len(fields) >= 3 and fields[2] != '': strain = fields[2].strip() else: strain = None accession_to_taxon[genbank_id] = (ncbi_id, strain) i += 1 if i % 100000 == 0: print genbank_id, ncbi_id, strain print i, 'accessions' return accession_to_taxon def get_ncbi_to_name(taxonomyfilename): ncbi_to_name = {} i = 0 with open(taxonomyfilename, 'r') as nfile: reader = csv.reader(nfile, delimiter='\t') header = reader.next() uidx = header.index('uid') namex = header.index('name') for row in reader: # id, parentid, name, rank id = row[uidx] if id != 'uid': name = row[namex] # ?? if name != None: ncbi_to_name[id] = name i += 1 if i % 200000 == 0: print i, id, name, row return ncbi_to_name if __name__ == '__main__': parser = argparse.ArgumentParser(description='NCBI ids and names') parser.add_argument('ncbi', help='taxonomy.tsv for NCBI taxonomy in open tree format') parser.add_argument('mappings', help='genbank accession id to NCBI taxon mapping') parser.add_argument('out', help='where to write the output file') args = parser.parse_args() print 'reading', args.mappings accession_to_taxon = get_accession_to_taxon(args.mappings) print 'reading', args.ncbi ncbi_to_name = get_ncbi_to_name(args.ncbi) print 'writing', args.out with open(args.out, 'w') as outfile: i = 0 writer = csv.writer(outfile, delimiter='\t') for gid in accession_to_taxon: (ncbi_id, strain) = accession_to_taxon[gid] name = ncbi_to_name.get(ncbi_id) row = writer.writerow((gid, ncbi_id, strain, name)) i += 1 if i % 500000 == 0: print gid, ncbi_id, strain, name
{ "repo_name": "OpenTreeOfLife/reference-taxonomy", "path": "import_scripts/silva/get_taxon_names.py", "copies": "1", "size": "2420", "license": "bsd-2-clause", "hash": -7662449143392651000, "line_mean": 35.6666666667, "line_max": 90, "alpha_frac": 0.5404958678, "autogenerated": false, "ratio": 3.3333333333333335, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43738292011333335, "avg_score": null, "num_lines": null }
"""Adds a guest OS name to hypervisor OS name mapping""" from baseCmd import * from baseResponse import * class addGuestOsMappingCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """Hypervisor type. One of : XenServer, KVM""" """Required""" self.hypervisor = None self.typeInfo['hypervisor'] = 'string' """Hypervisor version to create the mapping for. Use 'default' for default versions""" """Required""" self.hypervisorversion = None self.typeInfo['hypervisorversion'] = 'string' """OS name specific to the hypervisor""" """Required""" self.osnameforhypervisor = None self.typeInfo['osnameforhypervisor'] = 'string' """Display Name of Guest OS standard type. Either Display Name or UUID must be passed""" self.osdisplayname = None self.typeInfo['osdisplayname'] = 'string' """UUID of Guest OS type. Either the UUID or Display Name must be passed""" self.ostypeid = None self.typeInfo['ostypeid'] = 'uuid' self.required = ["hypervisor", "hypervisorversion", "osnameforhypervisor", ] class addGuestOsMappingResponse (baseResponse): typeInfo = {} def __init__(self): """the ID of the Guest OS mapping""" self.id = None self.typeInfo['id'] = 'string' """the hypervisor""" self.hypervisor = None self.typeInfo['hypervisor'] = 'string' """version of the hypervisor for mapping""" self.hypervisorversion = None self.typeInfo['hypervisorversion'] = 'string' """is the mapping user defined""" self.isuserdefined = None self.typeInfo['isuserdefined'] = 'string' """standard display name for the Guest OS""" self.osdisplayname = None self.typeInfo['osdisplayname'] = 'string' """hypervisor specific name for the Guest OS""" self.osnameforhypervisor = None self.typeInfo['osnameforhypervisor'] = 'string' """the ID of the Guest OS type""" self.ostypeid = None self.typeInfo['ostypeid'] = 'string'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addGuestOsMapping.py", "copies": "1", "size": "2158", "license": "apache-2.0", "hash": -3090484583819889700, "line_mean": 36.8596491228, "line_max": 96, "alpha_frac": 0.6139944393, "autogenerated": false, "ratio": 4.2066276803118905, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.018324650209247437, "num_lines": 57 }
"""Adds a help webpage and query functions for commands.""" import collections import io from plumeria.command import commands from plumeria.message import Response, MemoryAttachment from plumeria.core.webserver import app, render_template @commands.create('help', 'commands', category='Utility') async def help(message): """ Get a listing of commands. """ if not message.channel.is_private: server = message.channel.server.id else: server = "private" return Response(await app.get_base_url() + "/help/{}".format(server)) @commands.create('commands dump', category='Utility') async def dump_commands(message): """ Get a listing of commands in Markdown as a text file. """ server = message.channel.server.id categories = set() by_category = collections.defaultdict(lambda: []) mappings = sorted(await commands.get_mappings(server), key=lambda m: m.command.category or "") for mapping in mappings: categories.add(mapping.command.category) by_category[mapping.command.category].append(mapping) categories = sorted(categories) buf = io.StringIO() for category in categories: buf.write("\n\n**{}**\n".format(category)) for mapping in by_category[category]: buf.write("\n* {}".format(mapping.aliases[0])) return Response("See attachment", attachments=[ MemoryAttachment(io.BytesIO(buf.getvalue().strip().encode("utf-8")), "commands.txt", "text/plain") ]) @app.route('/help/{server}') async def handle(request): server_id = request.match_info['server'] if server_id == "private": server_id = None categories = set() by_category = collections.defaultdict(lambda: []) mappings = sorted(await commands.get_mappings(server_id), key=lambda m: m.command.category or "") for mapping in mappings: categories.add(mapping.command.category) by_category[mapping.command.category].append(mapping) categories = sorted(categories) return render_template("help.html", commands=mappings, by_category=by_category, categories=categories) def setup(): commands.add(help) commands.add(dump_commands) app.add(handle)
{ "repo_name": "sk89q/Plumeria", "path": "plumeria/core/help.py", "copies": "1", "size": "2211", "license": "mit", "hash": 4285825018072487000, "line_mean": 33.0153846154, "line_max": 106, "alpha_frac": 0.6824966079, "autogenerated": false, "ratio": 3.976618705035971, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5159115312935971, "avg_score": null, "num_lines": null }
"""Adds a list of files into the META-INF directory of the passed deploy jar. """ import argparse from itertools import izip import shutil import zipfile # Set to Jan 1 1980, the earliest date supported by zipfile ZIP_DATE = (1980, 1, 1, 0, 0, 0) parser = argparse.ArgumentParser() parser.add_argument( "--deploy_jar", required=True, help="The deploy jar to modify.",) parser.add_argument( "--output", required=True, help="The output file.",) parser.add_argument( "meta_inf_files", nargs="+", help="Sequence of input file, final file name pairs",) def pairwise(t): it = iter(t) return izip(it, it) def main(): args = parser.parse_args() shutil.copyfile(args.deploy_jar, args.output) output_jar = zipfile.ZipFile(args.output, "a") for meta_inf_file, name in pairwise(args.meta_inf_files): with file(meta_inf_file) as f: zip_info = zipfile.ZipInfo("META-INF/" + name, ZIP_DATE) output_jar.writestr(zip_info, f.read()) if __name__ == "__main__": main()
{ "repo_name": "brendandouglas/intellij", "path": "build_defs/package_meta_inf_files.py", "copies": "1", "size": "1026", "license": "apache-2.0", "hash": -78276815953253660, "line_mean": 22.3181818182, "line_max": 77, "alpha_frac": 0.6608187135, "autogenerated": false, "ratio": 3.257142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9373612431044771, "avg_score": 0.008869827919617148, "num_lines": 44 }
"""add_saliva_code Revision ID: f098d2c51614 Revises: e26ea978c345 Create Date: 2018-04-10 11:55:36.406746 """ import model.utils import sqlalchemy as sa from alembic import op from rdr_service.participant_enums import OrderStatus, SampleStatus # revision identifiers, used by Alembic. revision = "f098d2c51614" down_revision = "e26ea978c345" branch_labels = None depends_on = None def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "participant_summary", sa.Column("sample_order_status_1sal2", model.utils.Enum(OrderStatus), nullable=True) ) op.add_column( "participant_summary", sa.Column("sample_order_status_1sal2_time", model.utils.UTCDateTime(), nullable=True) ) op.add_column( "participant_summary", sa.Column("sample_status_1sal2", model.utils.Enum(SampleStatus), nullable=True) ) op.add_column( "participant_summary", sa.Column("sample_status_1sal2_time", model.utils.UTCDateTime(), nullable=True) ) # ### end Alembic commands ### def downgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("participant_summary", "sample_status_1sal2_time") op.drop_column("participant_summary", "sample_status_1sal2") op.drop_column("participant_summary", "sample_order_status_1sal2_time") op.drop_column("participant_summary", "sample_order_status_1sal2") # ### end Alembic commands ### def upgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def downgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
{ "repo_name": "all-of-us/raw-data-repository", "path": "rdr_service/alembic/versions/f098d2c51614_add_saliva_code.py", "copies": "1", "size": "1889", "license": "bsd-3-clause", "hash": 7622167912451686000, "line_mean": 28.515625, "line_max": 116, "alpha_frac": 0.6829010058, "autogenerated": false, "ratio": 3.4345454545454546, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9614697576265752, "avg_score": 0.0005497768159406091, "num_lines": 64 }
"""Adds all Sphinx "objects" to the table of contents.""" from typing import Optional import docutils.nodes import sphinx.addnodes import sphinx.application import sphinx.environment.collectors.toctree def _monkey_patch_toc_tree_process_doc(app: sphinx.application.Sphinx): """Enables support for also finding Sphinx domain objects. Args: app: Sphinx application. """ TocTreeCollector = sphinx.environment.collectors.toctree.TocTreeCollector # Apply the monkey pach orig_process_doc = TocTreeCollector.process_doc def _make_section_from_desc(source: sphinx.addnodes.desc) -> Optional[docutils.nodes.section]: signature: sphinx.addnodes.desc_signature for child in source._traverse(): if not isinstance(child, sphinx.addnodes.desc_signature): continue signature = child break else: # No signature found return None ids = signature['ids'] if not ids: # Not indexed. return None section = docutils.nodes.section() section['ids'] = ids # Extract title from signature title = '' for child in signature._traverse(): if isinstance(child, (sphinx.addnodes.desc_name, sphinx.addnodes.desc_addname)): title += child.astext() if not title: # No name found return None # Sphinx uses the first child of the section node as the title. titlenode = docutils.nodes.comment(title, title) section += titlenode return section def _make_section_from_field( source: docutils.nodes.field) -> Optional[docutils.nodes.section]: fieldname = source[0] fieldbody = source[1] ids = fieldname['ids'] if not ids: # Not indexed return None section = docutils.nodes.section() section['ids'] = ids title = fieldname.astext() # Sphinx uses the first child of the section node as the title. titlenode = docutils.nodes.comment(title, title) section += titlenode return section def _make_section_from_parameter( source: docutils.nodes.term) -> Optional[docutils.nodes.section]: ids = source['ids'] if not ids: # Not indexed return None section = docutils.nodes.section() section['ids'] = ids paramname = source['paramname'] titlenode = docutils.nodes.comment(paramname, paramname) section += titlenode return section def _patched_process_doc( self: sphinx.environment.collectors.toctree.TocTreeCollector, app: sphinx.application.Sphinx, doctree: docutils.nodes.document) -> None: new_document = doctree.copy() # Shallow copy def _collect(source: docutils.nodes.Node, target: docutils.nodes.Element) -> None: if not isinstance(source, docutils.nodes.Element): return children = iter(source.children) if isinstance(source, docutils.nodes.section): new_node = source.copy() # Also copy first child, which sphinx interprets as the title new_node += next(children).deepcopy() target += new_node target = new_node elif isinstance(source, sphinx.addnodes.only): # Retain "only" nodes since they affect toc generation. new_node = source.copy() target += new_node target = new_node elif isinstance(source, sphinx.addnodes.toctree): # Deep copy entire toctree new_node = source.deepcopy() target += new_node return elif isinstance(source, sphinx.addnodes.desc): # Object description. Try to create synthetic section. new_node = _make_section_from_desc(source) if new_node is not None: target += new_node target = new_node elif isinstance(source, docutils.nodes.field): # Field. Try to create synthetic section. new_node = _make_section_from_field(source) if new_node is not None: target += new_node target = new_node elif isinstance(source, docutils.nodes.term) and source.get('paramname'): # Parameter within object description. Try to create synthetic section. new_node = _make_section_from_parameter(source) if new_node is not None: target += new_node # Parameters cannot contain sub-sections return for child in children: _collect(child, target) _collect(doctree, new_document) return orig_process_doc(self, app, new_document) TocTreeCollector.process_doc = _patched_process_doc # TocTreeCollector is registered before our extension is. In order for the # monkey patching to take effect, we need to unregister it and re-register it. for read_listener in app.events.listeners['doctree-read']: obj = getattr(read_listener.handler, '__self__', None) if obj is not None and isinstance(obj, TocTreeCollector): obj.disable(app) app.add_env_collector(TocTreeCollector) break def setup(app: sphinx.application.Sphinx) -> None: _monkey_patch_toc_tree_process_doc(app) return { "parallel_read_safe": True, "parallel_write_safe": True, }
{ "repo_name": "google/tensorstore", "path": "docs/tensorstore_sphinx_material/sphinx_material/object_toc.py", "copies": "1", "size": "5767", "license": "apache-2.0", "hash": -5586200962627016000, "line_mean": 37.7046979866, "line_max": 98, "alpha_frac": 0.5867868909, "autogenerated": false, "ratio": 4.52668759811617, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5613474489016169, "avg_score": null, "num_lines": null }
"""Add same_tool and tool_id Revision ID: 16f121110a0f Revises: 2c58f1b857f1 Create Date: 2015-11-09 12:28:43.019410 """ # revision identifiers, used by Alembic. revision = '16f121110a0f' down_revision = '2c58f1b857f1' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('ActiveTranslationMessages', sa.Column('same_tool', sa.Boolean(), nullable=True)) op.add_column('ActiveTranslationMessages', sa.Column('tool_id', sa.Unicode(length=255), nullable=True)) op.create_index(u'ix_ActiveTranslationMessages_same_tool', 'ActiveTranslationMessages', ['same_tool'], unique=False) op.create_index(u'ix_ActiveTranslationMessages_tool_id', 'ActiveTranslationMessages', ['tool_id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(u'ix_ActiveTranslationMessages_tool_id', table_name='ActiveTranslationMessages') op.drop_index(u'ix_ActiveTranslationMessages_same_tool', table_name='ActiveTranslationMessages') op.drop_column('ActiveTranslationMessages', 'tool_id') op.drop_column('ActiveTranslationMessages', 'same_tool') ### end Alembic commands ###
{ "repo_name": "go-lab/appcomposer", "path": "alembic/versions/16f121110a0f_add_same_tool_and_tool_id.py", "copies": "3", "size": "1266", "license": "bsd-2-clause", "hash": 657974739117903600, "line_mean": 38.5625, "line_max": 120, "alpha_frac": 0.7353870458, "autogenerated": false, "ratio": 3.4216216216216218, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5657008667421621, "avg_score": null, "num_lines": null }
"""add sample and identifier history Revision ID: b4f6eb55d503 Revises: 4aa79d5ac86e Create Date: 2018-08-31 13:26:22.482944 """ import model.utils import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision = "b4f6eb55d503" down_revision = "4aa79d5ac86e" branch_labels = None depends_on = None def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "biobank_order_identifier_history", sa.Column("system", sa.String(length=80), nullable=False), sa.Column("value", sa.String(length=80), nullable=False), sa.Column("version", sa.Integer(), nullable=False), sa.Column("biobank_order_id", sa.String(length=80), nullable=False), sa.ForeignKeyConstraint(["biobank_order_id"], ["biobank_order.biobank_order_id"]), sa.PrimaryKeyConstraint("system", "value", "version"), ) op.create_table( "biobank_ordered_sample_history", sa.Column("test", sa.String(length=80), nullable=False), sa.Column("description", sa.UnicodeText(), nullable=False), sa.Column("processing_required", sa.Boolean(), nullable=False), sa.Column("collected", model.utils.UTCDateTime(), nullable=True), sa.Column("processed", model.utils.UTCDateTime(), nullable=True), sa.Column("finalized", model.utils.UTCDateTime(), nullable=True), sa.Column("version", sa.Integer(), nullable=False), sa.Column("order_id", sa.String(length=80), nullable=False), sa.ForeignKeyConstraint(["order_id"], ["biobank_order.biobank_order_id"]), sa.PrimaryKeyConstraint("order_id", "test", "version"), ) # ### end Alembic commands ### def downgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("biobank_ordered_sample_history") op.drop_table("biobank_order_identifier_history") # ### end Alembic commands ### def upgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def downgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
{ "repo_name": "all-of-us/raw-data-repository", "path": "rdr_service/alembic/versions/b4f6eb55d503_add_sample_and_identifier_history.py", "copies": "1", "size": "2374", "license": "bsd-3-clause", "hash": -604238389329764400, "line_mean": 32.9142857143, "line_max": 90, "alpha_frac": 0.6575400168, "autogenerated": false, "ratio": 3.6189024390243905, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9774796941270099, "avg_score": 0.0003291029108585047, "num_lines": 70 }
"""Add sample groups Revision ID: 1c15bafd311a Revises: 52c2d8ff8e6f Create Date: 2015-08-12 17:58:22.640975 """ # revision identifiers, used by Alembic. revision = '1c15bafd311a' down_revision = '52c2d8ff8e6f' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('group', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=200), nullable=True), sa.PrimaryKeyConstraint('id'), mysql_charset='utf8', mysql_engine='InnoDB' ) op.create_table('group_membership', sa.Column('sample_id', sa.Integer(), nullable=False), sa.Column('group_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['group_id'], ['group.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['sample_id'], ['sample.id'], ondelete='CASCADE') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('group_membership') op.drop_table('group') ### end Alembic commands ###
{ "repo_name": "varda/varda", "path": "alembic/versions/1c15bafd311a_add_sample_groups.py", "copies": "1", "size": "1107", "license": "mit", "hash": 7748948407039880000, "line_mean": 27.3846153846, "line_max": 77, "alpha_frac": 0.6684733514, "autogenerated": false, "ratio": 3.3545454545454545, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45230188059454546, "avg_score": null, "num_lines": null }
"""add_sample_prep Revision ID: 4e1a5a724f61 Revises: df29b42d614 Create Date: 2016-05-11 13:16:30.339670 """ # revision identifiers, used by Alembic. revision = '4e1a5a724f61' down_revision = 'df29b42d614' import sqlalchemy as sa from alembic import op def upgrade(): op.create_table('SamplePrepWorkerTbl', sa.Column('name', sa.VARCHAR(32), primary_key=True), sa.Column('fullname', sa.VARCHAR(45)), sa.Column('email', sa.VARCHAR(45)), sa.Column('phone', sa.VARCHAR(45)), sa.Column('comment', sa.VARCHAR(140))) op.create_table('SamplePrepSessionTbl', sa.Column('id', sa.INT, primary_key=True), sa.Column('name', sa.VARCHAR(32)), sa.Column('comment', sa.VARCHAR(140)), sa.Column('worker_name', sa.String(32), sa.ForeignKey('SamplePrepWorkerTbl.name')), sa.Column('start_date', sa.DATE), sa.Column('end_date', sa.DATE)) op.create_table('SamplePrepStepTbl', sa.Column('id', sa.INT, primary_key=True), sa.Column('sampleID', sa.INT, sa.ForeignKey('SampleTbl.id')), sa.Column('sessionID', sa.INT, sa.ForeignKey('SamplePrepSessionTbl.id')), sa.Column('crush', sa.VARCHAR(140)), sa.Column('wash', sa.VARCHAR(140)), sa.Column('sieve', sa.VARCHAR(140)), sa.Column('frantz', sa.VARCHAR(140)), sa.Column('acid', sa.VARCHAR(140)), sa.Column('heavy_liquid', sa.VARCHAR(140)), sa.Column('pick', sa.VARCHAR(140)), sa.Column('status', sa.VARCHAR(32)), sa.Column('comment', sa.VARCHAR(300)), sa.Column('timestamp', sa.DATETIME), sa.Column('added', sa.Boolean)) op.create_table('SamplePrepImageTbl', sa.Column('id', sa.INT, primary_key=True), sa.Column('stepID', sa.INT, sa.ForeignKey('SamplePrepStepTbl.id')), sa.Column('host', sa.VARCHAR(45)), sa.Column('path', sa.VARCHAR(45)), sa.Column('timestamp', sa.DATETIME)) def downgrade(): op.drop_table('SamplePrepImageTbl') op.drop_table('SamplePrepStepTbl') op.drop_table('SamplePrepSessionTbl') op.drop_table('SamplePrepWorkerTbl')
{ "repo_name": "UManPychron/pychron", "path": "alembic_dvc/versions/4e1a5a724f61_add_sample_prep.py", "copies": "3", "size": "2505", "license": "apache-2.0", "hash": -8451233955739186000, "line_mean": 40.0655737705, "line_max": 103, "alpha_frac": 0.5385229541, "autogenerated": false, "ratio": 3.722139673105498, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002114055218669062, "num_lines": 61 }
"""Adds an attachment to an existing ticket.""" # :license: MIT, see LICENSE for more details. import os import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions from SoftLayer.CLI import helpers @click.command() @click.argument('identifier') @click.option('--path', help="The path of the attachment to be uploaded") @click.option('--name', help="The name of the attachment shown in the ticket") @environment.pass_env def cli(env, identifier, path, name): """Adds an attachment to an existing ticket.""" mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if path is None: raise exceptions.ArgumentError("Missing argument --path") if not os.path.exists(path): raise exceptions.ArgumentError("%s not exist" % path) if name is None: name = os.path.basename(path) attached_file = mgr.upload_attachment(ticket_id=ticket_id, file_path=path, file_name=name) env.fout("File attached: \n%s" % attached_file)
{ "repo_name": "kyubifire/softlayer-python", "path": "SoftLayer/CLI/ticket/upload.py", "copies": "5", "size": "1158", "license": "mit", "hash": 7784721970717351000, "line_mean": 30.2972972973, "line_max": 78, "alpha_frac": 0.6614853195, "autogenerated": false, "ratio": 4.034843205574913, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7196328525074913, "avg_score": null, "num_lines": null }
"""Adds a network serviceProvider to a physical network""" from baseCmd import * from baseResponse import * class addNetworkServiceProviderCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """the name for the physical network service provider""" """Required""" self.name = None self.typeInfo['name'] = 'string' """the Physical Network ID to add the provider to""" """Required""" self.physicalnetworkid = None self.typeInfo['physicalnetworkid'] = 'uuid' """the destination Physical Network ID to bridge to""" self.destinationphysicalnetworkid = None self.typeInfo['destinationphysicalnetworkid'] = 'uuid' """the list of services to be enabled for this physical network service provider""" self.servicelist = [] self.typeInfo['servicelist'] = 'list' self.required = ["name", "physicalnetworkid", ] class addNetworkServiceProviderResponse (baseResponse): typeInfo = {} def __init__(self): """uuid of the network provider""" self.id = None self.typeInfo['id'] = 'string' """true if individual services can be enabled/disabled""" self.canenableindividualservice = None self.typeInfo['canenableindividualservice'] = 'boolean' """the destination physical network""" self.destinationphysicalnetworkid = None self.typeInfo['destinationphysicalnetworkid'] = 'string' """the provider name""" self.name = None self.typeInfo['name'] = 'string' """the physical network this belongs to""" self.physicalnetworkid = None self.typeInfo['physicalnetworkid'] = 'string' """services for this provider""" self.servicelist = None self.typeInfo['servicelist'] = 'list' """state of the network provider""" self.state = None self.typeInfo['state'] = 'string'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addNetworkServiceProvider.py", "copies": "1", "size": "1973", "license": "apache-2.0", "hash": 8173339617989073000, "line_mean": 36.2264150943, "line_max": 91, "alpha_frac": 0.6259503294, "autogenerated": false, "ratio": 4.525229357798165, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5651179687198166, "avg_score": null, "num_lines": null }
"""Adds a new cluster""" from baseCmd import * from baseResponse import * class addClusterCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """the cluster name""" """Required""" self.clustername = None self.typeInfo['clustername'] = 'string' """type of the cluster: CloudManaged, ExternalManaged""" """Required""" self.clustertype = None self.typeInfo['clustertype'] = 'string' """hypervisor type of the cluster: XenServer,KVM""" """Required""" self.hypervisor = None self.typeInfo['hypervisor'] = 'string' """the Pod ID for the host""" """Required""" self.podid = None self.typeInfo['podid'] = 'uuid' """the Zone ID for the cluster""" """Required""" self.zoneid = None self.typeInfo['zoneid'] = 'uuid' """Allocation state of this cluster for allocation of new resources""" self.allocationstate = None self.typeInfo['allocationstate'] = 'string' """the password for the host""" self.password = None self.typeInfo['password'] = 'string' """the URL""" self.url = None self.typeInfo['url'] = 'string' """the username for the cluster""" self.username = None self.typeInfo['username'] = 'string' self.required = ["clustername", "clustertype", "hypervisor", "podid", "zoneid", ] class addClusterResponse (baseResponse): typeInfo = {} def __init__(self): """the cluster ID""" self.id = None self.typeInfo['id'] = 'string' """the allocation state of the cluster""" self.allocationstate = None self.typeInfo['allocationstate'] = 'string' """the type of the cluster""" self.clustertype = None self.typeInfo['clustertype'] = 'string' """The cpu overcommit ratio of the cluster""" self.cpuovercommitratio = None self.typeInfo['cpuovercommitratio'] = 'string' """the hypervisor type of the cluster""" self.hypervisortype = None self.typeInfo['hypervisortype'] = 'string' """whether this cluster is managed by cloudstack""" self.managedstate = None self.typeInfo['managedstate'] = 'string' """The memory overcommit ratio of the cluster""" self.memoryovercommitratio = None self.typeInfo['memoryovercommitratio'] = 'string' """the cluster name""" self.name = None self.typeInfo['name'] = 'string' """the Pod ID of the cluster""" self.podid = None self.typeInfo['podid'] = 'string' """the Pod name of the cluster""" self.podname = None self.typeInfo['podname'] = 'string' """the Zone ID of the cluster""" self.zoneid = None self.typeInfo['zoneid'] = 'string' """the Zone name of the cluster""" self.zonename = None self.typeInfo['zonename'] = 'string' """the capacity of the Cluster""" self.capacity = [] class capacity: def __init__(self): """"the total capacity available""" self.capacitytotal = None """"the capacity currently in use""" self.capacityused = None """"the Cluster ID""" self.clusterid = None """"the Cluster name""" self.clustername = None """"the percentage of capacity currently in use""" self.percentused = None """"the Pod ID""" self.podid = None """"the Pod name""" self.podname = None """"the capacity type""" self.type = None """"the Zone ID""" self.zoneid = None """"the Zone name""" self.zonename = None
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addCluster.py", "copies": "1", "size": "3800", "license": "apache-2.0", "hash": -400041690979819100, "line_mean": 33.2342342342, "line_max": 89, "alpha_frac": 0.5618421053, "autogenerated": false, "ratio": 4.18041804180418, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009672172172172172, "num_lines": 111 }
"""Adds a new host.""" from baseCmd import * from baseResponse import * class addHostCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """hypervisor type of the host""" """Required""" self.hypervisor = None self.typeInfo['hypervisor'] = 'string' """the password for the host""" """Required""" self.password = None self.typeInfo['password'] = 'string' """the Pod ID for the host""" """Required""" self.podid = None self.typeInfo['podid'] = 'uuid' """the host URL""" """Required""" self.url = None self.typeInfo['url'] = 'string' """the username for the host""" """Required""" self.username = None self.typeInfo['username'] = 'string' """the Zone ID for the host""" """Required""" self.zoneid = None self.typeInfo['zoneid'] = 'uuid' """Allocation state of this Host for allocation of new resources""" self.allocationstate = None self.typeInfo['allocationstate'] = 'string' """the cluster ID for the host""" self.clusterid = None self.typeInfo['clusterid'] = 'uuid' """the cluster name for the host""" self.clustername = None self.typeInfo['clustername'] = 'string' """list of tags to be added to the host""" self.hosttags = [] self.typeInfo['hosttags'] = 'list' self.required = ["hypervisor", "password", "podid", "url", "username", "zoneid", ] class addHostResponse (baseResponse): typeInfo = {} def __init__(self): """the ID of the host""" self.id = None self.typeInfo['id'] = 'string' """the cpu average load on the host""" self.averageload = None self.typeInfo['averageload'] = 'long' """capabilities of the host""" self.capabilities = None self.typeInfo['capabilities'] = 'string' """the cluster ID of the host""" self.clusterid = None self.typeInfo['clusterid'] = 'string' """the cluster name of the host""" self.clustername = None self.typeInfo['clustername'] = 'string' """the cluster type of the cluster that host belongs to""" self.clustertype = None self.typeInfo['clustertype'] = 'string' """the amount of the host's CPU currently allocated""" self.cpuallocated = None self.typeInfo['cpuallocated'] = 'string' """the CPU number of the host""" self.cpunumber = None self.typeInfo['cpunumber'] = 'integer' """the number of CPU sockets on the host""" self.cpusockets = None self.typeInfo['cpusockets'] = 'integer' """the CPU speed of the host""" self.cpuspeed = None self.typeInfo['cpuspeed'] = 'long' """the amount of the host's CPU currently used""" self.cpuused = None self.typeInfo['cpuused'] = 'string' """the amount of the host's CPU after applying the cpu.overprovisioning.factor""" self.cpuwithoverprovisioning = None self.typeInfo['cpuwithoverprovisioning'] = 'string' """the date and time the host was created""" self.created = None self.typeInfo['created'] = 'date' """Host details in key/value pairs.""" self.details = None self.typeInfo['details'] = 'map' """true if the host is disconnected. False otherwise.""" self.disconnected = None self.typeInfo['disconnected'] = 'date' """the host's currently allocated disk size""" self.disksizeallocated = None self.typeInfo['disksizeallocated'] = 'long' """the total disk size of the host""" self.disksizetotal = None self.typeInfo['disksizetotal'] = 'long' """events available for the host""" self.events = None self.typeInfo['events'] = 'string' """true if the host is Ha host (dedicated to vms started by HA process; false otherwise""" self.hahost = None self.typeInfo['hahost'] = 'boolean' """true if this host has enough CPU and RAM capacity to migrate a VM to it, false otherwise""" self.hasenoughcapacity = None self.typeInfo['hasenoughcapacity'] = 'boolean' """comma-separated list of tags for the host""" self.hosttags = None self.typeInfo['hosttags'] = 'string' """the host hypervisor""" self.hypervisor = None self.typeInfo['hypervisor'] = 'hypervisortype' """the hypervisor version""" self.hypervisorversion = None self.typeInfo['hypervisorversion'] = 'string' """the IP address of the host""" self.ipaddress = None self.typeInfo['ipaddress'] = 'string' """true if local storage is active, false otherwise""" self.islocalstorageactive = None self.typeInfo['islocalstorageactive'] = 'boolean' """the date and time the host was last pinged""" self.lastpinged = None self.typeInfo['lastpinged'] = 'date' """the management server ID of the host""" self.managementserverid = None self.typeInfo['managementserverid'] = 'long' """the amount of the host's memory currently allocated""" self.memoryallocated = None self.typeInfo['memoryallocated'] = 'long' """the memory total of the host""" self.memorytotal = None self.typeInfo['memorytotal'] = 'long' """the amount of the host's memory currently used""" self.memoryused = None self.typeInfo['memoryused'] = 'long' """the name of the host""" self.name = None self.typeInfo['name'] = 'string' """the incoming network traffic on the host""" self.networkkbsread = None self.typeInfo['networkkbsread'] = 'long' """the outgoing network traffic on the host""" self.networkkbswrite = None self.typeInfo['networkkbswrite'] = 'long' """the OS category ID of the host""" self.oscategoryid = None self.typeInfo['oscategoryid'] = 'string' """the OS category name of the host""" self.oscategoryname = None self.typeInfo['oscategoryname'] = 'string' """the Pod ID of the host""" self.podid = None self.typeInfo['podid'] = 'string' """the Pod name of the host""" self.podname = None self.typeInfo['podname'] = 'string' """the date and time the host was removed""" self.removed = None self.typeInfo['removed'] = 'date' """the resource state of the host""" self.resourcestate = None self.typeInfo['resourcestate'] = 'string' """the state of the host""" self.state = None self.typeInfo['state'] = 'status' """true if this host is suitable(has enough capacity and satisfies all conditions like hosttags, max guests vm limit etc) to migrate a VM to it , false otherwise""" self.suitableformigration = None self.typeInfo['suitableformigration'] = 'boolean' """the host type""" self.type = None self.typeInfo['type'] = 'type' """the host version""" self.version = None self.typeInfo['version'] = 'string' """the Zone ID of the host""" self.zoneid = None self.typeInfo['zoneid'] = 'string' """the Zone name of the host""" self.zonename = None self.typeInfo['zonename'] = 'string' """GPU cards present in the host""" self.gpugroup = [] """the ID of the latest async job acting on this object""" self.jobid = None self.typeInfo['jobid'] = '' """the current status of the latest async job acting on this object""" self.jobstatus = None self.typeInfo['jobstatus'] = '' class vgpu: def __init__(self): """"Maximum vgpu can be created with this vgpu type on the given gpu group""" self.maxcapacity = None """"Maximum displays per user""" self.maxheads = None """"Maximum X resolution per display""" self.maxresolutionx = None """"Maximum Y resolution per display""" self.maxresolutiony = None """"Maximum no. of vgpu per gpu card (pgpu)""" self.maxvgpuperpgpu = None """"Remaining capacity in terms of no. of more VMs that can be deployped with this vGPU type""" self.remainingcapacity = None """"Model Name of vGPU""" self.vgputype = None """"Video RAM for this vGPU type""" self.videoram = None class gpugroup: def __init__(self): """"GPU cards present in the host""" self.gpugroupname = None """"the list of enabled vGPUs""" self.vgpu = [] """"Maximum vgpu can be created with this vgpu type on the given gpu group""" self.maxcapacity = None """"Maximum displays per user""" self.maxheads = None """"Maximum X resolution per display""" self.maxresolutionx = None """"Maximum Y resolution per display""" self.maxresolutiony = None """"Maximum no. of vgpu per gpu card (pgpu)""" self.maxvgpuperpgpu = None """"Remaining capacity in terms of no. of more VMs that can be deployped with this vGPU type""" self.remainingcapacity = None """"Model Name of vGPU""" self.vgputype = None """"Video RAM for this vGPU type""" self.videoram = None
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addHost.py", "copies": "1", "size": "9618", "license": "apache-2.0", "hash": -2644649808279163000, "line_mean": 39.2426778243, "line_max": 172, "alpha_frac": 0.5829694323, "autogenerated": false, "ratio": 4.136774193548387, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5219743625848386, "avg_score": null, "num_lines": null }
"""Adds a new HTTPS handler to urllib2, which uses the SSL library from Python 2.6.""" import logging log = logging.getLogger('sslurllib') import sys # We only need this wrapper for Python versions < 2.6 # sys.hexversion is guaranteed to always increment if sys.hexversion >= 0x020600F0: runningPython26 = True else: runningPython26 = False try: import ssl _sane = True except: log.warning('ssl is not installed, please install it from http://pypi.python.org/pypi/ssl/') _sane = False if _sane and not runningPython26: import httplib, socket, urllib2 __all__ = ['HTTPSv2Connection', 'HTTPSv2Handler'] log.debug('Installing SSLv2 HTTPS Methods into urllib2') class HTTPSv2Connection(httplib.HTTPConnection): """This class allows communication via SSLv2.""" default_port = httplib.HTTPS_PORT def __init__(self, host, port=None, key_file=None, cert_file=None, strict=None): httplib.HTTPConnection.__init__(self, host, port, strict) self.key_file = key_file self.cert_file = cert_file def connect(self): "Connect to a host on a given (SSL) port." log.debug('HTTPSv2 connecting to %s:%s', self.host, self.port) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_sock = ssl.wrap_socket(sock, ca_certs=self.cert_file) ssl_sock.connect((self.host, self.port)) self.sock = ssl_sock class HTTPSv2Handler(urllib2.HTTPSHandler): """Overrides the base urllib2 HTTPSHandler.""" def https_open(self, req): return self.do_open(HTTPSv2Connection, req) # now instantiate the HTTPSv2Handler and install it. v2handler = HTTPSv2Handler() opener = urllib2.build_opener(v2handler) # this will make our new subclassed HTTPSHandler be used for all HTTPSConnections urllib2.install_opener(opener)
{ "repo_name": "jordotech/satchmofork", "path": "satchmo/apps/satchmo_utils/sslurllib.py", "copies": "13", "size": "2035", "license": "bsd-3-clause", "hash": -6917595699230877000, "line_mean": 32.3606557377, "line_max": 96, "alpha_frac": 0.6314496314, "autogenerated": false, "ratio": 3.9668615984405458, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03012166233581811, "num_lines": 61 }
"""Adds a new load_balancer service.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import loadbal @click.command() @click.argument('identifier') @click.option('--allocation', required=True, type=click.INT, help="The allocated percent of connections") @click.option('--port', required=True, help="The port number", type=click.INT) @click.option('--routing-type', required=True, help="The port routing type") @click.option('--routing-method', required=True, help="The routing method") @environment.pass_env def cli(env, identifier, allocation, port, routing_type, routing_method): """Adds a new load_balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) mgr.add_service_group(loadbal_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group is being added!')
{ "repo_name": "nanjj/softlayer-python", "path": "SoftLayer/CLI/loadbal/group_add.py", "copies": "5", "size": "1257", "license": "mit", "hash": -6613113585282953000, "line_mean": 29.6585365854, "line_max": 73, "alpha_frac": 0.599840891, "autogenerated": false, "ratio": 4.395104895104895, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7494945786104895, "avg_score": null, "num_lines": null }
"""Adds a new load balancer service.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import loadbal @click.command() @click.argument('identifier') @click.option('--enabled / --disabled', required=True, help="Create the service as enabled or disabled") @click.option('--port', required=True, help="The port number for the service", type=click.INT) @click.option('--weight', required=True, type=click.INT, help="The weight of the service") @click.option('--healthcheck-type', required=True, help="The health check type") @click.option('--ip-address', required=True, help="The IP address of the service") @environment.pass_env def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Adds a new load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
{ "repo_name": "skraghu/softlayer-python", "path": "SoftLayer/CLI/loadbal/service_add.py", "copies": "4", "size": "1702", "license": "mit", "hash": -5545226448736186000, "line_mean": 31.1132075472, "line_max": 78, "alpha_frac": 0.5904817861, "autogenerated": false, "ratio": 4.121065375302663, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6711547161402663, "avg_score": null, "num_lines": null }
"""Adds a new load_balancer service.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import loadbal import click @click.command() @click.argument('identifier') @click.option('--allocation', required=True, type=click.INT, help="The allocated percent of connections") @click.option('--port', required=True, help="The port number", type=click.INT) @click.option('--routing-type', required=True, help="The port routing type") @click.option('--routing-method', required=True, help="The routing method") @environment.pass_env def cli(env, identifier, allocation, port, routing_type, routing_method): """Adds a new load_balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) _, loadbal_id = loadbal.parse_id(identifier) mgr.add_service_group(loadbal_id, allocation=allocation, port=port, routing_type=routing_type, routing_method=routing_method) env.fout('Load balancer service group is being added!')
{ "repo_name": "iftekeriba/softlayer-python", "path": "SoftLayer/CLI/loadbal/group_add.py", "copies": "2", "size": "1257", "license": "mit", "hash": -8290777336085122000, "line_mean": 29.6585365854, "line_max": 73, "alpha_frac": 0.599840891, "autogenerated": false, "ratio": 4.395104895104895, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5994945786104895, "avg_score": null, "num_lines": null }
"""Adds a new load balancer service.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import loadbal import click @click.command() @click.argument('identifier') @click.option('--enabled / --disabled', required=True, help="Create the service as enable or disabled") @click.option('--port', required=True, help="The port number for the service", type=click.INT) @click.option('--weight', required=True, type=click.INT, help="The weight of the service") @click.option('--healthcheck-type', required=True, help="The health check type") @click.option('--ip-address', required=True, help="The IP address of the service") @environment.pass_env def cli(env, identifier, enabled, port, weight, healthcheck_type, ip_address): """Adds a new load balancer service.""" mgr = SoftLayer.LoadBalancerManager(env.client) loadbal_id, group_id = loadbal.parse_id(identifier) # check if the IP is valid ip_address_id = None if ip_address: ip_service = env.client['Network_Subnet_IpAddress'] ip_record = ip_service.getByIpAddress(ip_address) if len(ip_record) > 0: ip_address_id = ip_record['id'] mgr.add_service(loadbal_id, group_id, ip_address_id=ip_address_id, enabled=enabled, port=port, weight=weight, hc_type=healthcheck_type) env.fout('Load balancer service is being added!')
{ "repo_name": "iftekeriba/softlayer-python", "path": "SoftLayer/CLI/loadbal/service_add.py", "copies": "2", "size": "1701", "license": "mit", "hash": -5702753782360820000, "line_mean": 31.0943396226, "line_max": 78, "alpha_frac": 0.5902410347, "autogenerated": false, "ratio": 4.11864406779661, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5708885102496609, "avg_score": null, "num_lines": null }
"""Adds a new transaction summary table to reduce all time calculation times Revision ID: 2b3b1f654b5 Revises: 53dcf1daebec Create Date: 2014-07-07 19:25:17.114450 """ # revision identifiers, used by Alembic. revision = '2b3b1f654b5' down_revision = '53dcf1daebec' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('transaction_summary', sa.Column('transaction_id', sa.String(), nullable=False), sa.Column('user', sa.String(), nullable=False), sa.Column('amount', sa.BigInteger(), nullable=True), sa.Column('count', sa.SmallInteger(), nullable=True), sa.ForeignKeyConstraint(['transaction_id'], ['transaction.txid'], ), sa.PrimaryKeyConstraint('transaction_id', 'user') ) op.create_index('summary_user_idx', 'transaction_summary', ['user'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index('summary_user_idx', table_name='transaction_summary') op.drop_table('transaction_summary') ### end Alembic commands ###
{ "repo_name": "simplecrypto/simplecoin", "path": "migrations/versions/2b3b1f654b5_adds_a_new_transaction_summary_table_to_.py", "copies": "1", "size": "1151", "license": "mit", "hash": 8355419743709821000, "line_mean": 31.8857142857, "line_max": 86, "alpha_frac": 0.6959165943, "autogenerated": false, "ratio": 3.5415384615384617, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47374550558384615, "avg_score": null, "num_lines": null }
"""Adds a Nicira NVP device""" from baseCmd import * from baseResponse import * class addNiciraNvpDeviceCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """Hostname of ip address of the Nicira NVP Controller.""" """Required""" self.hostname = None self.typeInfo['hostname'] = 'string' """Credentials to access the Nicira Controller API""" """Required""" self.password = None self.typeInfo['password'] = 'string' """the Physical Network ID""" """Required""" self.physicalnetworkid = None self.typeInfo['physicalnetworkid'] = 'uuid' """The Transportzone UUID configured on the Nicira Controller""" """Required""" self.transportzoneuuid = None self.typeInfo['transportzoneuuid'] = 'string' """Credentials to access the Nicira Controller API""" """Required""" self.username = None self.typeInfo['username'] = 'string' """The L3 Gateway Service UUID configured on the Nicira Controller""" self.l3gatewayserviceuuid = None self.typeInfo['l3gatewayserviceuuid'] = 'string' self.required = ["hostname", "password", "physicalnetworkid", "transportzoneuuid", "username", ] class addNiciraNvpDeviceResponse (baseResponse): typeInfo = {} def __init__(self): """the controller Ip address""" self.hostname = None self.typeInfo['hostname'] = 'string' """this L3 gateway service Uuid""" self.l3gatewayserviceuuid = None self.typeInfo['l3gatewayserviceuuid'] = 'string' """device name""" self.niciradevicename = None self.typeInfo['niciradevicename'] = 'string' """device id of the Nicire Nvp""" self.nvpdeviceid = None self.typeInfo['nvpdeviceid'] = 'string' """the physical network to which this Nirica Nvp belongs to""" self.physicalnetworkid = None self.typeInfo['physicalnetworkid'] = 'string' """name of the provider""" self.provider = None self.typeInfo['provider'] = 'string' """the transport zone Uuid""" self.transportzoneuuid = None self.typeInfo['transportzoneuuid'] = 'string'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addNiciraNvpDevice.py", "copies": "1", "size": "2286", "license": "apache-2.0", "hash": 3363061833845239000, "line_mean": 35.8709677419, "line_max": 104, "alpha_frac": 0.6106736658, "autogenerated": false, "ratio": 4.141304347826087, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5251978013626086, "avg_score": null, "num_lines": null }
"""Add sanity check to tas Revision ID: 9dded6e6bf79 Revises: 180c6e439a69 Create Date: 2016-11-02 17:34:03.314917 """ # revision identifiers, used by Alembic. revision = '9dded6e6bf79' down_revision = '180c6e439a69' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_data_broker(): ### commands auto generated by Alembic - please adjust! ### op.create_unique_constraint('tas_lookup_sanity_check', 'tas_lookup', ['account_num', 'allocation_transfer_agency', 'agency_identifier', 'beginning_period_of_availability', 'ending_period_of_availability', 'availability_type_code', 'main_account_code', 'sub_account_code']) ### end Alembic commands ### def downgrade_data_broker(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('tas_lookup_sanity_check', 'tas_lookup', type_='unique') ### end Alembic commands ###
{ "repo_name": "fedspendingtransparency/data-act-broker-backend", "path": "dataactcore/migrations/versions/9dded6e6bf79_add_sanity_check_to_tas.py", "copies": "1", "size": "1070", "license": "cc0-1.0", "hash": -6024681441434611000, "line_mean": 25.75, "line_max": 276, "alpha_frac": 0.7028037383, "autogenerated": false, "ratio": 3.34375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9394347721614678, "avg_score": 0.03044120333706446, "num_lines": 40 }
"""Adds an update to an existing ticket.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import helpers from SoftLayer.CLI import ticket @click.command() @click.argument('identifier') @click.option('--body', help="Text to add to the ticket. STDIN or the default text editor will be used otherwise.") @environment.pass_env def cli(env, identifier, body): """Adds an update to an existing ticket. Will update the ticket with `Some text`.:: slcli ticket update 123456 --body="Some text" Will update the ticket with text from STDIN:: cat sometfile.txt | slcli ticket update 123456 Will open the default text editor, and once closed, use that text to update the ticket:: slcli ticket update 123456 """ mgr = SoftLayer.TicketManager(env.client) ticket_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'ticket') if body is None: stdin = click.get_text_stream('stdin') # Means there is text on the STDIN buffer, read it and add to the ticket if not stdin.isatty(): body = stdin.read() # This is an interactive terminal, open a text editor else: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) mgr.update_ticket(ticket_id=ticket_id, body=body) env.fout("Ticket Updated!")
{ "repo_name": "allmightyspiff/softlayer-python", "path": "SoftLayer/CLI/ticket/update.py", "copies": "2", "size": "1383", "license": "mit", "hash": -2641012299453345000, "line_mean": 31.1627906977, "line_max": 115, "alpha_frac": 0.6876355748, "autogenerated": false, "ratio": 3.8739495798319328, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007488912493883226, "num_lines": 43 }
"""adds a range of portable public IP's to a region""" from baseCmd import * from baseResponse import * class createPortableIpRangeCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """the ending IP address in the portable IP range""" """Required""" self.endip = None self.typeInfo['endip'] = 'string' """the gateway for the portable IP range""" """Required""" self.gateway = None self.typeInfo['gateway'] = 'string' """the netmask of the portable IP range""" """Required""" self.netmask = None self.typeInfo['netmask'] = 'string' """Id of the Region""" """Required""" self.regionid = None self.typeInfo['regionid'] = 'integer' """the beginning IP address in the portable IP range""" """Required""" self.startip = None self.typeInfo['startip'] = 'string' """VLAN id, if not specified defaulted to untagged""" self.vlan = None self.typeInfo['vlan'] = 'string' self.required = ["endip", "gateway", "netmask", "regionid", "startip", ] class createPortableIpRangeResponse (baseResponse): typeInfo = {} def __init__(self): """portable IP range ID""" self.id = None self.typeInfo['id'] = 'string' """the end ip of the portable IP range""" self.endip = None self.typeInfo['endip'] = 'string' """the gateway of the VLAN IP range""" self.gateway = None self.typeInfo['gateway'] = 'string' """the netmask of the VLAN IP range""" self.netmask = None self.typeInfo['netmask'] = 'string' """Region Id in which portable ip range is provisioned""" self.regionid = None self.typeInfo['regionid'] = 'integer' """the start ip of the portable IP range""" self.startip = None self.typeInfo['startip'] = 'string' """the ID or VID of the VLAN.""" self.vlan = None self.typeInfo['vlan'] = 'string' """List of portable IP and association with zone/network/vpc details that are part of GSLB rule""" self.portableipaddress = [] class portableipaddress: def __init__(self): """"the account ID the portable IP address is associated with""" self.accountid = None """"date the portal IP address was acquired""" self.allocated = None """"the domain ID the portable IP address is associated with""" self.domainid = None """"public IP address""" self.ipaddress = None """"the ID of the Network where ip belongs to""" self.networkid = None """"the physical network this belongs to""" self.physicalnetworkid = None """"Region Id in which global load balancer is created""" self.regionid = None """"State of the ip address. Can be: Allocatin, Allocated and Releasing""" self.state = None """"VPC the ip belongs to""" self.vpcid = None """"the ID of the zone the public IP address belongs to""" self.zoneid = None
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/createPortableIpRange.py", "copies": "1", "size": "3169", "license": "apache-2.0", "hash": -2304959834246790400, "line_mean": 35.4252873563, "line_max": 106, "alpha_frac": 0.5777847902, "autogenerated": false, "ratio": 4.1049222797927465, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.012341835243401761, "num_lines": 87 }
"""Adds a Region""" from baseCmd import * from baseResponse import * class addRegionCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """Id of the Region""" """Required""" self.id = None self.typeInfo['id'] = 'integer' """Region service endpoint""" """Required""" self.endpoint = None self.typeInfo['endpoint'] = 'string' """Name of the region""" """Required""" self.name = None self.typeInfo['name'] = 'string' self.required = ["id", "endpoint", "name", ] class addRegionResponse (baseResponse): typeInfo = {} def __init__(self): """the ID of the region""" self.id = None self.typeInfo['id'] = 'integer' """the end point of the region""" self.endpoint = None self.typeInfo['endpoint'] = 'string' """true if GSLB service is enabled in the region, false otherwise""" self.gslbserviceenabled = None self.typeInfo['gslbserviceenabled'] = 'boolean' """the name of the region""" self.name = None self.typeInfo['name'] = 'string' """true if security groups support is enabled, false otherwise""" self.portableipserviceenabled = None self.typeInfo['portableipserviceenabled'] = 'boolean'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addRegion.py", "copies": "1", "size": "1358", "license": "apache-2.0", "hash": -6288617407236292000, "line_mean": 29.1777777778, "line_max": 76, "alpha_frac": 0.5670103093, "autogenerated": false, "ratio": 4.127659574468085, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5194669883768085, "avg_score": null, "num_lines": null }
"""Adds a simulated sensor.""" from datetime import datetime import logging import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) CONF_AMP = "amplitude" CONF_FWHM = "spread" CONF_MEAN = "mean" CONF_PERIOD = "period" CONF_PHASE = "phase" CONF_SEED = "seed" CONF_UNIT = "unit" CONF_RELATIVE_TO_EPOCH = "relative_to_epoch" DEFAULT_AMP = 1 DEFAULT_FWHM = 0 DEFAULT_MEAN = 0 DEFAULT_NAME = "simulated" DEFAULT_PERIOD = 60 DEFAULT_PHASE = 0 DEFAULT_SEED = 999 DEFAULT_UNIT = "value" DEFAULT_RELATIVE_TO_EPOCH = True ICON = "mdi:chart-line" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_AMP, default=DEFAULT_AMP): vol.Coerce(float), vol.Optional(CONF_FWHM, default=DEFAULT_FWHM): vol.Coerce(float), vol.Optional(CONF_MEAN, default=DEFAULT_MEAN): vol.Coerce(float), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PERIOD, default=DEFAULT_PERIOD): cv.positive_int, vol.Optional(CONF_PHASE, default=DEFAULT_PHASE): vol.Coerce(float), vol.Optional(CONF_SEED, default=DEFAULT_SEED): cv.positive_int, vol.Optional(CONF_UNIT, default=DEFAULT_UNIT): cv.string, vol.Optional( CONF_RELATIVE_TO_EPOCH, default=DEFAULT_RELATIVE_TO_EPOCH ): cv.boolean, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the simulated sensor.""" name = config.get(CONF_NAME) unit = config.get(CONF_UNIT) amp = config.get(CONF_AMP) mean = config.get(CONF_MEAN) period = config.get(CONF_PERIOD) phase = config.get(CONF_PHASE) fwhm = config.get(CONF_FWHM) seed = config.get(CONF_SEED) relative_to_epoch = config.get(CONF_RELATIVE_TO_EPOCH) sensor = SimulatedSensor( name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ) add_entities([sensor], True) class SimulatedSensor(Entity): """Class for simulated sensor.""" def __init__( self, name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ): """Init the class.""" self._name = name self._unit = unit self._amp = amp self._mean = mean self._period = period self._phase = phase # phase in degrees self._fwhm = fwhm self._seed = seed self._random = Random(seed) # A local seeded Random self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None def time_delta(self): """Return the time delta.""" dt0 = self._start_time dt1 = dt_util.utcnow() return dt1 - dt0 def signal_calc(self): """Calculate the signal.""" mean = self._mean amp = self._amp time_delta = self.time_delta().total_seconds() * 1e6 # to milliseconds period = self._period * 1e6 # to milliseconds fwhm = self._fwhm / 2 phase = math.radians(self._phase) if period == 0: periodic = 0 else: periodic = amp * (math.sin((2 * math.pi * time_delta / period) + phase)) noise = self._random.gauss(mu=0, sigma=fwhm) return round(mean + periodic + noise, 3) async def async_update(self): """Update the sensor.""" self._state = self.signal_calc() @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" return ICON @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit @property def device_state_attributes(self): """Return other details about the sensor state.""" attr = { "amplitude": self._amp, "mean": self._mean, "period": self._period, "phase": self._phase, "spread": self._fwhm, "seed": self._seed, "relative_to_epoch": self._relative_to_epoch, } return attr
{ "repo_name": "nkgilley/home-assistant", "path": "homeassistant/components/simulated/sensor.py", "copies": "10", "size": "4609", "license": "apache-2.0", "hash": 2035162879398523400, "line_mean": 28.9285714286, "line_max": 84, "alpha_frac": 0.6107615535, "autogenerated": false, "ratio": 3.60641627543036, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.921717782893036, "avg_score": null, "num_lines": null }
"""Adds a simulated sensor.""" from datetime import datetime import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util CONF_AMP = "amplitude" CONF_FWHM = "spread" CONF_MEAN = "mean" CONF_PERIOD = "period" CONF_PHASE = "phase" CONF_SEED = "seed" CONF_UNIT = "unit" CONF_RELATIVE_TO_EPOCH = "relative_to_epoch" DEFAULT_AMP = 1 DEFAULT_FWHM = 0 DEFAULT_MEAN = 0 DEFAULT_NAME = "simulated" DEFAULT_PERIOD = 60 DEFAULT_PHASE = 0 DEFAULT_SEED = 999 DEFAULT_UNIT = "value" DEFAULT_RELATIVE_TO_EPOCH = True ICON = "mdi:chart-line" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_AMP, default=DEFAULT_AMP): vol.Coerce(float), vol.Optional(CONF_FWHM, default=DEFAULT_FWHM): vol.Coerce(float), vol.Optional(CONF_MEAN, default=DEFAULT_MEAN): vol.Coerce(float), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PERIOD, default=DEFAULT_PERIOD): cv.positive_int, vol.Optional(CONF_PHASE, default=DEFAULT_PHASE): vol.Coerce(float), vol.Optional(CONF_SEED, default=DEFAULT_SEED): cv.positive_int, vol.Optional(CONF_UNIT, default=DEFAULT_UNIT): cv.string, vol.Optional( CONF_RELATIVE_TO_EPOCH, default=DEFAULT_RELATIVE_TO_EPOCH ): cv.boolean, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the simulated sensor.""" name = config.get(CONF_NAME) unit = config.get(CONF_UNIT) amp = config.get(CONF_AMP) mean = config.get(CONF_MEAN) period = config.get(CONF_PERIOD) phase = config.get(CONF_PHASE) fwhm = config.get(CONF_FWHM) seed = config.get(CONF_SEED) relative_to_epoch = config.get(CONF_RELATIVE_TO_EPOCH) sensor = SimulatedSensor( name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ) add_entities([sensor], True) class SimulatedSensor(Entity): """Class for simulated sensor.""" def __init__( self, name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ): """Init the class.""" self._name = name self._unit = unit self._amp = amp self._mean = mean self._period = period self._phase = phase # phase in degrees self._fwhm = fwhm self._seed = seed self._random = Random(seed) # A local seeded Random self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None def time_delta(self): """Return the time delta.""" dt0 = self._start_time dt1 = dt_util.utcnow() return dt1 - dt0 def signal_calc(self): """Calculate the signal.""" mean = self._mean amp = self._amp time_delta = self.time_delta().total_seconds() * 1e6 # to milliseconds period = self._period * 1e6 # to milliseconds fwhm = self._fwhm / 2 phase = math.radians(self._phase) if period == 0: periodic = 0 else: periodic = amp * (math.sin((2 * math.pi * time_delta / period) + phase)) noise = self._random.gauss(mu=0, sigma=fwhm) return round(mean + periodic + noise, 3) async def async_update(self): """Update the sensor.""" self._state = self.signal_calc() @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" return ICON @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit @property def device_state_attributes(self): """Return other details about the sensor state.""" return { "amplitude": self._amp, "mean": self._mean, "period": self._period, "phase": self._phase, "spread": self._fwhm, "seed": self._seed, "relative_to_epoch": self._relative_to_epoch, }
{ "repo_name": "mezz64/home-assistant", "path": "homeassistant/components/simulated/sensor.py", "copies": "9", "size": "4535", "license": "apache-2.0", "hash": -8189537015309690000, "line_mean": 29.2333333333, "line_max": 84, "alpha_frac": 0.6103638368, "autogenerated": false, "ratio": 3.5992063492063493, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8709570186006349, "avg_score": null, "num_lines": null }
"""Adds a simulated sensor.""" from datetime import datetime import math from random import Random import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util CONF_AMP = "amplitude" CONF_FWHM = "spread" CONF_MEAN = "mean" CONF_PERIOD = "period" CONF_PHASE = "phase" CONF_SEED = "seed" CONF_UNIT = "unit" CONF_RELATIVE_TO_EPOCH = "relative_to_epoch" DEFAULT_AMP = 1 DEFAULT_FWHM = 0 DEFAULT_MEAN = 0 DEFAULT_NAME = "simulated" DEFAULT_PERIOD = 60 DEFAULT_PHASE = 0 DEFAULT_SEED = 999 DEFAULT_UNIT = "value" DEFAULT_RELATIVE_TO_EPOCH = True ICON = "mdi:chart-line" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_AMP, default=DEFAULT_AMP): vol.Coerce(float), vol.Optional(CONF_FWHM, default=DEFAULT_FWHM): vol.Coerce(float), vol.Optional(CONF_MEAN, default=DEFAULT_MEAN): vol.Coerce(float), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PERIOD, default=DEFAULT_PERIOD): cv.positive_int, vol.Optional(CONF_PHASE, default=DEFAULT_PHASE): vol.Coerce(float), vol.Optional(CONF_SEED, default=DEFAULT_SEED): cv.positive_int, vol.Optional(CONF_UNIT, default=DEFAULT_UNIT): cv.string, vol.Optional( CONF_RELATIVE_TO_EPOCH, default=DEFAULT_RELATIVE_TO_EPOCH ): cv.boolean, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the simulated sensor.""" name = config.get(CONF_NAME) unit = config.get(CONF_UNIT) amp = config.get(CONF_AMP) mean = config.get(CONF_MEAN) period = config.get(CONF_PERIOD) phase = config.get(CONF_PHASE) fwhm = config.get(CONF_FWHM) seed = config.get(CONF_SEED) relative_to_epoch = config.get(CONF_RELATIVE_TO_EPOCH) sensor = SimulatedSensor( name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ) add_entities([sensor], True) class SimulatedSensor(SensorEntity): """Class for simulated sensor.""" def __init__( self, name, unit, amp, mean, period, phase, fwhm, seed, relative_to_epoch ): """Init the class.""" self._name = name self._unit = unit self._amp = amp self._mean = mean self._period = period self._phase = phase # phase in degrees self._fwhm = fwhm self._seed = seed self._random = Random(seed) # A local seeded Random self._start_time = ( datetime(1970, 1, 1, tzinfo=dt_util.UTC) if relative_to_epoch else dt_util.utcnow() ) self._relative_to_epoch = relative_to_epoch self._state = None def time_delta(self): """Return the time delta.""" dt0 = self._start_time dt1 = dt_util.utcnow() return dt1 - dt0 def signal_calc(self): """Calculate the signal.""" mean = self._mean amp = self._amp time_delta = self.time_delta().total_seconds() * 1e6 # to milliseconds period = self._period * 1e6 # to milliseconds fwhm = self._fwhm / 2 phase = math.radians(self._phase) if period == 0: periodic = 0 else: periodic = amp * (math.sin((2 * math.pi * time_delta / period) + phase)) noise = self._random.gauss(mu=0, sigma=fwhm) return round(mean + periodic + noise, 3) async def async_update(self): """Update the sensor.""" self._state = self.signal_calc() @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" return ICON @property def unit_of_measurement(self): """Return the unit this state is expressed in.""" return self._unit @property def extra_state_attributes(self): """Return other details about the sensor state.""" return { "amplitude": self._amp, "mean": self._mean, "period": self._period, "phase": self._phase, "spread": self._fwhm, "seed": self._seed, "relative_to_epoch": self._relative_to_epoch, }
{ "repo_name": "kennedyshead/home-assistant", "path": "homeassistant/components/simulated/sensor.py", "copies": "5", "size": "4506", "license": "apache-2.0", "hash": 8812218134252604000, "line_mean": 29.2416107383, "line_max": 84, "alpha_frac": 0.608743897, "autogenerated": false, "ratio": 3.590438247011952, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6699182144011953, "avg_score": null, "num_lines": null }
"""Adds async capabilities to the base product object""" import asyncio import aiohttp from domaintools.base_results import Results from domaintools.exceptions import ServiceUnavailableException, ServiceException class _AIter(object): """A wrapper to wrap an AsyncResults as an async iterable""" __slots__ = ('results', 'iterator', ) def __init__(self, results): self.results = results self.iterator = None def __aiter__(self): return self async def __anext__(self): if self.iterator is None: await self.results self.iterator = self.results._items().__iter__() try: return self.iterator.__next__() except StopIteration: raise StopAsyncIteration class AsyncResults(Results): """The base (abstract) DomainTools' product definition with Async capabilities built in""" def __await__(self): return self.__awaitable__().__await__() async def _make_async_request(self, session): async with session.get(self.url, params=self.kwargs, **self.api.extra_aiohttp_params) as results: self.setStatus(results.status, results) if self.kwargs.get('format', 'json') == 'json': self._data = await results.json() else: self._data = await results.text() limit_exceeded, message = self.check_limit_exceeded() if limit_exceeded: self._limit_exceeded = True self._limit_exceeded_message = message async def __awaitable__(self): if self._data is None: async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(verify_ssl=self.api.verify_ssl)) as session: wait_time = self._wait_time() if wait_time is None and self.api: try: await self._make_async_request(session) except ServiceUnavailableException: await asyncio.sleep(60) self._wait_time() await self._make_async_request(session) else: await asyncio.sleep(wait_time) await self._make_async_request(session) return self def __aiter__(self): return _AIter(self) async def __aenter__(self): return await self async def __aexit__(self, *args): return
{ "repo_name": "DomainTools/python_api", "path": "domaintools_async/__init__.py", "copies": "1", "size": "2457", "license": "mit", "hash": 2357463837164870700, "line_mean": 32.2027027027, "line_max": 120, "alpha_frac": 0.5767195767, "autogenerated": false, "ratio": 4.541589648798522, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5618309225498522, "avg_score": null, "num_lines": null }
"""adds autohandler functionality to Mako templates. requires that the TemplateLookup class is used with templates. usage: <%! from mako.ext.autohandler import autohandler %> <%inherit file="${autohandler(template, context)}"/> or with custom autohandler filename: <%! from mako.ext.autohandler import autohandler %> <%inherit file="${autohandler(template, context, name='somefilename')}"/> """ import posixpath, os, re def autohandler(template, context, name='autohandler'): lookup = context.lookup _template_uri = template.module._template_uri if not lookup.filesystem_checks: try: return lookup._uri_cache[(autohandler, _template_uri, name)] except KeyError: pass tokens = re.findall(r'([^/]+)', posixpath.dirname(_template_uri)) + [name] while len(tokens): path = '/' + '/'.join(tokens) if path != _template_uri and _file_exists(lookup, path): if not lookup.filesystem_checks: return lookup._uri_cache.setdefault((autohandler, _template_uri, name), path) else: return path if len(tokens) == 1: break tokens[-2:] = [name] if not lookup.filesystem_checks: return lookup._uri_cache.setdefault((autohandler, _template_uri, name), None) else: return None def _file_exists(lookup, path): psub = re.sub(r'^/', '',path) for d in lookup.directories: if os.access(d + '/' + psub, os.F_OK): return True else: return False
{ "repo_name": "tebeka/pythonwise", "path": "tagcloud/mako/ext/autohandler.py", "copies": "2", "size": "1565", "license": "bsd-3-clause", "hash": 1150788806840755300, "line_mean": 26.4736842105, "line_max": 93, "alpha_frac": 0.6146964856, "autogenerated": false, "ratio": 3.8641975308641974, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014580504738720558, "num_lines": 57 }
"""Adds backup image store.""" from baseCmd import * from baseResponse import * class addImageStoreCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "false" """the image store provider name""" """Required""" self.provider = None self.typeInfo['provider'] = 'string' """the details for the image store. Example: details[0].key=accesskey&details[0].value=s389ddssaa&details[1].key=secretkey&details[1].value=8dshfsss""" self.details = [] self.typeInfo['details'] = 'map' """the name for the image store""" self.name = None self.typeInfo['name'] = 'string' """the URL for the image store""" self.url = None self.typeInfo['url'] = 'string' """the Zone ID for the image store""" self.zoneid = None self.typeInfo['zoneid'] = 'uuid' self.required = ["provider", ] class addImageStoreResponse (baseResponse): typeInfo = {} def __init__(self): """the ID of the image store""" self.id = None self.typeInfo['id'] = 'string' """the details of the image store""" self.details = None self.typeInfo['details'] = 'set' """the name of the image store""" self.name = None self.typeInfo['name'] = 'string' """the protocol of the image store""" self.protocol = None self.typeInfo['protocol'] = 'string' """the provider name of the image store""" self.providername = None self.typeInfo['providername'] = 'string' """the scope of the image store""" self.scope = None self.typeInfo['scope'] = 'scopetype' """the url of the image store""" self.url = None self.typeInfo['url'] = 'string' """the Zone ID of the image store""" self.zoneid = None self.typeInfo['zoneid'] = 'string' """the Zone name of the image store""" self.zonename = None self.typeInfo['zonename'] = 'string'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addImageStore.py", "copies": "1", "size": "2048", "license": "apache-2.0", "hash": -2132041095111330800, "line_mean": 32.5737704918, "line_max": 159, "alpha_frac": 0.5649414062, "autogenerated": false, "ratio": 3.9233716475095783, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4988313053709578, "avg_score": null, "num_lines": null }
"""Adds boolean merged mined column for payouts and blocks, along with a table for merge mining address associations Revision ID: 450b99a485f8 Revises: 322f0244224f Create Date: 2014-05-03 02:47:32.704020 """ # revision identifiers, used by Alembic. revision = '450b99a485f8' down_revision = '322f0244224f' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('merge_address', sa.Column('user', sa.String(), nullable=False), sa.Column('merge_address', sa.String(), nullable=True), sa.PrimaryKeyConstraint('user') ) op.add_column(u'block', sa.Column('merged', sa.Boolean(), nullable=True, server_default="FALSE")) op.add_column(u'bonus_payout', sa.Column('merged', sa.Boolean(), nullable=True, server_default="FALSE")) op.add_column(u'payout', sa.Column('merged', sa.Boolean(), nullable=True, server_default="FALSE")) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column(u'payout', 'merged') op.drop_column(u'bonus_payout', 'merged') op.drop_column(u'block', 'merged') op.drop_table('merge_address') ### end Alembic commands ###
{ "repo_name": "simplecrypto/simplecoin", "path": "migrations/versions/450b99a485f8_adds_boolean_merged_mined_column_for_.py", "copies": "1", "size": "1253", "license": "mit", "hash": 2782317533599447600, "line_mean": 33.8055555556, "line_max": 116, "alpha_frac": 0.691141261, "autogenerated": false, "ratio": 3.323607427055703, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45147486880557025, "avg_score": null, "num_lines": null }
"""Adds capacities table for users. Revision ID: 58c968a5c213 Revises: a2c99320aae4 Create Date: 2017-12-29 18:53:26.489653 """ # revision identifiers, used by Alembic. revision = '58c968a5c213' down_revision = 'a2c99320aae4' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('capacities', sa.Column('id', sa.Integer(), nullable=False), sa.Column('male_max', sa.Integer(), nullable=True), sa.Column('female_max', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.add_column(u'users', sa.Column('capacity_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'users', 'capacities', ['capacity_id'], ['id']) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'users', type_='foreignkey') op.drop_column(u'users', 'capacity_id') op.drop_table('capacities') # ### end Alembic commands ###
{ "repo_name": "Rdbaker/WPI-IFC", "path": "migrations/versions/58c968a5c213_.py", "copies": "1", "size": "1051", "license": "bsd-3-clause", "hash": 7303802393144287000, "line_mean": 29.0285714286, "line_max": 82, "alpha_frac": 0.6669838249, "autogenerated": false, "ratio": 3.233846153846154, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44008299787461536, "avg_score": null, "num_lines": null }
"""Adds challenge types and uses keys table Revision ID: 87733981ca0e Revises: cb3cfcc47e2f Create Date: 2017-02-04 14:50:16.999303 """ from CTFd.models import db, Challenges, Keys from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text, table, column from sqlalchemy.orm import sessionmaker import json # revision identifiers, used by Alembic. revision = '87733981ca0e' down_revision = 'cb3cfcc47e2f' branch_labels = None depends_on = None keys_table = table('keys', column('id', db.Integer), column('chal', db.Integer), column('key_type', db.Integer), column('flag', db.Text) ) def upgrade(): # ### commands auto generated by Alembic - please adjust! ### ## Copy over flags data to Keys table print("Getting bind...") conn = op.get_bind() print("Executing: SELECT id, flags from challenges") res = conn.execute(text("SELECT id, flags from challenges")) results = res.fetchall() print("There are {} results".format(len(results))) new_keys = [] print("Processing existing flags") for r in results: if r[1]: ## Check if flags are NULL data = json.loads(r[1]) for old_keys in data: new_keys.append({'chal':r[0], 'flag':old_keys.get('flag'), 'key_type':old_keys.get('type')}) if new_keys: ## Base CTFd databases actually already insert into Keys but the database does not make use of them ## This prevents duplicate entries of keys print("Executing: TRUNCATE keys") conn.execute(text("TRUNCATE `keys`")) print("Bulk inserting the keys") op.bulk_insert(keys_table, new_keys) ## Add type column to challenges print("Adding type column to challenges") op.add_column('challenges', sa.Column('type', sa.Integer(), nullable=True, default=0)) ## Set all NULLs to 0 print("Setting all NULLs to 0") conn.execute("UPDATE challenges set type=0 WHERE type IS NULL") ## Drop flags from challenges print("Dropping flags column from challenges") op.drop_column('challenges', 'flags') print("Finished") # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### print("Getting bind...") conn = op.get_bind() print("Adding flags column back to challenges table") op.add_column('challenges', sa.Column('flags', sa.TEXT(), nullable=True)) print("Dropping type column from challenges table") op.drop_column('challenges', 'type') print("Executing: SELECT id, flags from challenges") res = conn.execute("SELECT id, flags from challenges") results = res.fetchall() print("There are {} results".format(len(results))) for chal_id in results: new_keys = Keys.query.filter_by(chal=chal_id[0]).all() old_flags = [] for new_key in new_keys: flag_dict = {'flag': new_key.flag, 'type': new_key.key_type} old_flags.append(flag_dict) old_flags =json.dumps(old_flags) print("Updating challenge {} to insert {}".format(chal_id[0], flag_dict)) conn.execute(text('UPDATE challenges SET flags=:flags WHERE id=:id'), id=chal_id[0], flags=old_flags) print("Finished") # ### end Alembic commands ###
{ "repo_name": "mschwager/CTFd", "path": "migrations/versions/87733981ca0e_adds_challenge_types_and_uses_keys_table.py", "copies": "2", "size": "3283", "license": "apache-2.0", "hash": -2769333597934081000, "line_mean": 31.83, "line_max": 109, "alpha_frac": 0.6491014316, "autogenerated": false, "ratio": 3.623620309050773, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5272721740650773, "avg_score": null, "num_lines": null }
"""Add Scheduler info to the database Revision ID: 4b8e6be32ada Revises: 54e60d31349a Create Date: 2013-12-27 19:54:24.832911 """ # revision identifiers, used by Alembic. revision = '4b8e6be32ada' down_revision = '54e60d31349a' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('Scheduler', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('summary', sa.String(length=255), nullable=False), sa.Column('scheduler_type', sa.String(length=255), nullable=False), sa.Column('config', sa.String(length=4096), nullable=False), sa.Column('is_external', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name'), mysql_engine='InnoDB' ) op.create_table('SchedulerResource', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('scheduler_id', sa.Integer(), nullable=False), sa.Column('slots', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['scheduler_id'], ['Scheduler.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name','scheduler_id'), mysql_engine='InnoDB' ) op.create_table('ExperimentInstance', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('min_slot', sa.Integer(), nullable=False), sa.Column('max_slot', sa.Integer(), nullable=False), sa.Column('scheduler_resource_id', sa.Integer(), nullable=False), sa.Column('experiment_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['experiment_id'], ['Experiment.id'], ), sa.ForeignKeyConstraint(['scheduler_resource_id'], ['SchedulerResource.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name','scheduler_resource_id'), mysql_engine='InnoDB' ) op.create_table('ExperimentExternalScheduler', sa.Column('experiment_id', sa.Integer(), nullable=False), sa.Column('scheduler_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['experiment_id'], ['Experiment.id'], ), sa.ForeignKeyConstraint(['scheduler_id'], ['Scheduler.id'], ), sa.PrimaryKeyConstraint('experiment_id', 'scheduler_id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('ExperimentExternalScheduler') op.drop_table('ExperimentInstance') op.drop_table('SchedulerResource') op.drop_table('Scheduler') ### end Alembic commands ###
{ "repo_name": "zstars/weblabdeusto", "path": "server/src/weblab/db/upgrade/regular/versions/4b8e6be32ada_add_scheduler_info_t.py", "copies": "1", "size": "2682", "license": "bsd-2-clause", "hash": 2405706887533656000, "line_mean": 37.8695652174, "line_max": 83, "alpha_frac": 0.6808351976, "autogenerated": false, "ratio": 3.6292286874154263, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4810063885015426, "avg_score": null, "num_lines": null }
"""add scheduler related tables Revision ID: 20d2e65b1fd2 Revises: fefa06dd93cc Create Date: 2021-04-09 11:21:19.103241 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '20d2e65b1fd2' down_revision = 'fefa06dd93cc' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('optimistic_lock_v2', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False, comment='id'), sa.Column('name', sa.String(length=255), nullable=False, comment='lock name'), sa.Column('version', sa.BIGINT(), nullable=False, comment='lock version'), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='created at'), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='updated at'), sa.Column('deleted_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='deleted at'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name', name='uniq_name'), comment='optimistic lock', mysql_charset='utf8mb4', mysql_engine='innodb' ) op.create_table('scheduler_item_v2', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False, comment='id'), sa.Column('name', sa.String(length=255), nullable=False, comment='item name'), sa.Column('pipeline', sa.Text(), nullable=False, comment='pipeline'), sa.Column('status', sa.Integer(), nullable=False, comment='item status'), sa.Column('interval', sa.Integer(), nullable=False, comment='item run interval in second'), sa.Column('last_run_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='last runner time'), sa.Column('retry_cnt', sa.Integer(), nullable=False, comment='retry count when item is failed'), sa.Column('extra', sa.Text(), nullable=True, comment='extra info'), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='created at'), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='updated at'), sa.Column('deleted_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='deleted at'), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name', name='uniq_name'), comment='scheduler items', mysql_charset='utf8mb4', mysql_engine='innodb' ) op.create_table('scheduler_runner_v2', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False, comment='id'), sa.Column('item_id', sa.Integer(), nullable=False, comment='item id'), sa.Column('status', sa.Integer(), nullable=False, comment='runner status'), sa.Column('start_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='runner start time'), sa.Column('end_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='runner end time'), sa.Column('pipeline', sa.Text(), nullable=False, comment='pipeline from scheduler item'), sa.Column('output', sa.Text(), nullable=False, comment='output'), sa.Column('context', sa.Text(), nullable=False, comment='context'), sa.Column('extra', sa.Text(), nullable=True, comment='extra info'), sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='created at'), sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='updated at'), sa.Column('deleted_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=True, comment='deleted at'), sa.PrimaryKeyConstraint('id'), comment='scheduler runners', mysql_charset='utf8mb4', mysql_engine='innodb' ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('scheduler_runner_v2') op.drop_table('scheduler_item_v2') op.drop_table('optimistic_lock_v2') # ### end Alembic commands ###
{ "repo_name": "bytedance/fedlearner", "path": "web_console_v2/api/migrations/versions/20d2e65b1fd2_add_scheduler_related_tables.py", "copies": "1", "size": "4202", "license": "apache-2.0", "hash": 1728592682392433200, "line_mean": 52.8717948718, "line_max": 133, "alpha_frac": 0.6861018563, "autogenerated": false, "ratio": 3.5192629815745393, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9645910537974314, "avg_score": 0.011890859980044995, "num_lines": 78 }
"""add schema hash Revision ID: c37d49853d1b Revises: 6eae0fb73bcc Create Date: 2020-06-05 13:04:48.192373 """ from alembic import op import sqlalchemy as sa import rdr_service.model.utils from sqlalchemy.dialects import mysql from rdr_service.participant_enums import PhysicalMeasurementsStatus, QuestionnaireStatus, OrderStatus from rdr_service.participant_enums import WithdrawalStatus, WithdrawalReason, SuspensionStatus, QuestionnaireDefinitionStatus from rdr_service.participant_enums import EnrollmentStatus, Race, SampleStatus, OrganizationType, BiobankOrderStatus from rdr_service.participant_enums import OrderShipmentTrackingStatus, OrderShipmentStatus from rdr_service.participant_enums import MetricSetType, MetricsKey, GenderIdentity from rdr_service.model.base import add_table_history_table, drop_table_history_table from rdr_service.model.code import CodeType from rdr_service.model.site_enums import SiteStatus, EnrollingStatus, DigitalSchedulingStatus, ObsoleteStatus # revision identifiers, used by Alembic. revision = 'c37d49853d1b' down_revision = '6eae0fb73bcc' branch_labels = None depends_on = None def upgrade(engine_name): globals()["upgrade_%s" % engine_name]() def downgrade(engine_name): globals()["downgrade_%s" % engine_name]() def upgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('resource_schema', sa.Column('schema_hash', sa.String(length=64), nullable=False)) op.create_index('ix_res_type_schema_hash', 'resource_schema', ['resource_type_id', 'schema_hash'], unique=False) op.add_column('resource_type', sa.Column('type_name', sa.String(length=80), nullable=False)) op.add_column('resource_type', sa.Column('type_uid', sa.SmallInteger(), nullable=False)) op.create_unique_constraint(None, 'resource_type', ['type_uid', 'type_name']) op.drop_column('resource_type', 'resource_key_id') op.drop_column('resource_type', 'resource_Key') op.drop_column('resource_data', 'resource_pk') op.add_column('resource_type', sa.Column('resource_pk_field', sa.String(length=65), nullable=False)) op.execute('ALTER TABLE resource_data ADD uri varchar(80) null AFTER resource_schema_id') op.create_unique_constraint(None, 'resource_data', ['uri']) # ### end Alembic commands ### def downgrade_rdr(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'resource_data', type_='unique') op.drop_column('resource_data', 'uri') op.drop_column('resource_type', 'resource_pk_field') op.add_column('resource_data', sa.Column('resource_pk', mysql.VARCHAR(length=65), nullable=True)) op.add_column('resource_type', sa.Column('resource_Key', mysql.VARCHAR(length=80), nullable=False)) op.add_column('resource_type', sa.Column('resource_key_id', mysql.SMALLINT(display_width=6), autoincrement=False, nullable=False)) op.drop_constraint(None, 'resource_type', type_='unique') op.drop_column('resource_type', 'type_uid') op.drop_column('resource_type', 'type_name') op.drop_index('ix_res_type_schema_hash', table_name='resource_schema') op.drop_column('resource_schema', 'schema_hash') # ### end Alembic commands ### def upgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ### def downgrade_metrics(): # ### commands auto generated by Alembic - please adjust! ### pass # ### end Alembic commands ###
{ "repo_name": "all-of-us/raw-data-repository", "path": "rdr_service/alembic/versions/c37d49853d1b_add_schema_hash.py", "copies": "1", "size": "3515", "license": "bsd-3-clause", "hash": 5063834024226617000, "line_mean": 42.3950617284, "line_max": 125, "alpha_frac": 0.7240398293, "autogenerated": false, "ratio": 3.4630541871921183, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9611641282039456, "avg_score": 0.015090546890532623, "num_lines": 81 }
"""Add school information using Excel spread sheets. This is mostly used at startup to add the teachers, subjects, and social skills. """ import openpyxl from errors.core import (InvalidExcelSheetFormatException, NoExcelSheetRowsException) import core.excel.excel_utilities as excel_utils import utils.helpers as helpers def process_school_info(excel_file_path): """Process and return the school's information contained in Excel Spreadsheet. This is necessary at first program launch. The Excel workbook would contain three sheets: teachers, subjects, and social_skills. Args: excel_file_path: The absolute path to the excel workbook file. Returns: (dict) key-value mapping of various school information, e.g., staff, subjects, and social_skills. """ required_sheet_names = ('staffs', 'subjects', 'social_skills') document = openpyxl.load_workbook(excel_file_path) if not excel_utils.workbook_has_required_sheets(document, required_sheet_names): raise InvalidExcelSheetFormatException( 'School information workbook missing required sheets. ' + 'Expects {} sheets.'.format(', '.join(required_sheet_names))) info = dict(subjects=None, staffs=None, social_skills=None) info['subjects'] = \ process_subjects_sheet(document.get_sheet_by_name('subjects')) info['staffs'] = process_staffs_sheet(document.get_sheet_by_name('staffs')) info['social_skills'] = \ process_socials_sheet(document.get_sheet_by_name('social_skills')) return info def process_socials_sheet(sheet): """Process and return the social skills information for the school. Args: sheet: openpyxl.sheet: Excel spreadsheet containing teachers data. Returns: A list of social skills. Each list item is a dictionary describing various aspect of the social skill. E.g. dict(name="punctuality"), etc. """ required_header_names = ('name',) all_rows = list(sheet.rows)[:] if len(all_rows) < 2: raise NoExcelSheetRowsException( 'Social Excel sheet must have a header and at least one data row.') header, rows = all_rows[0], all_rows[1:] if not excel_utils.sheet_has_required_headers(header, required_header_names): raise InvalidExcelSheetFormatException( 'Social Excel sheet does not have the required header names. ' + 'Expects {}'.format(', '.join(required_header_names))) return list(excel_utils.map_rows_to_header(rows, header)) def process_subjects_sheet(sheet): """Processes the excel sheet containing subjects information. Args: sheet: openpyxl.sheet: Excel spreadsheet containing subjects data. Returns: A list of subjects. Each list item is a dictionary describing various aspects of the subjects. E.g dict(name='Social Science') """ required_header_names = ('name',) all_rows = list(sheet.rows)[:] if len(all_rows) < 2: raise NoExcelSheetRowsException( 'Student Excel sheet must have a header and at least one data row.') header, rows = all_rows[0], all_rows[1:] if not excel_utils.sheet_has_required_headers(header, required_header_names): raise InvalidExcelSheetFormatException( 'Student Excel sheet does not have the required header names. ' + 'Expects {}'.format(', '.join(required_header_names))) return list(excel_utils.map_rows_to_header(rows, header)) def process_staffs_sheet(sheet): """Process and return the staff information for the school.. Args: sheet: openpyxl.sheet: Excel spreadsheet containing teachers data. Returns: A list of staffs. Each list item is a dictionary describing various aspects of the staff. E.g dict(fname='Sule', lname='ChukwuEmeka') """ required_header_names = ('name',) staffs = [] all_rows = list(sheet.rows)[:] if len(all_rows) < 2: raise NoExcelSheetRowsException( 'Staff excel sheet must have a header and at least one data row.') header, rows = all_rows[0], all_rows[1:] if not excel_utils.sheet_has_required_headers(header, required_header_names): raise InvalidExcelSheetFormatException( 'Staff Excel sheet does not have the required header names. ' + 'Expects {}'.format(', '.join(required_header_names))) for staff in excel_utils.map_rows_to_header(rows, header): staff_name = helpers.get_human_name_parts(staff['name']) staffs.append( dict( fname=staff_name.first, lname=staff_name.last, mname=staff_name.middle)) return staffs
{ "repo_name": "cantell/silos", "path": "silos/core/excel/school_info.py", "copies": "1", "size": "4873", "license": "mit", "hash": -4342890307913788000, "line_mean": 38.6178861789, "line_max": 82, "alpha_frac": 0.6519597784, "autogenerated": false, "ratio": 3.9812091503267975, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5133168928726798, "avg_score": null, "num_lines": null }
"""Adds config flow for AccuWeather.""" from __future__ import annotations import asyncio from typing import Any from accuweather import AccuWeather, ApiError, InvalidApiKeyError, RequestsExceededError from aiohttp import ClientError from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import callback from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from .const import CONF_FORECAST, DOMAIN class AccuWeatherFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for AccuWeather.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle a flow initialized by the user.""" # Under the terms of use of the API, one user can use one free API key. Due to # the small number of requests allowed, we only allow one integration instance. if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") errors = {} if user_input is not None: websession = async_get_clientsession(self.hass) try: async with timeout(10): accuweather = AccuWeather( user_input[CONF_API_KEY], websession, latitude=user_input[CONF_LATITUDE], longitude=user_input[CONF_LONGITUDE], ) await accuweather.async_get_location() except (ApiError, ClientConnectorError, asyncio.TimeoutError, ClientError): errors["base"] = "cannot_connect" except InvalidApiKeyError: errors[CONF_API_KEY] = "invalid_api_key" except RequestsExceededError: errors[CONF_API_KEY] = "requests_exceeded" else: await self.async_set_unique_id( accuweather.location_key, raise_on_progress=False ) return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional( CONF_NAME, default=self.hass.config.location_name ): str, } ), errors=errors, ) @staticmethod @callback def async_get_options_flow( config_entry: ConfigEntry, ) -> AccuWeatherOptionsFlowHandler: """Options callback for AccuWeather.""" return AccuWeatherOptionsFlowHandler(config_entry) class AccuWeatherOptionsFlowHandler(config_entries.OptionsFlow): """Config flow options for AccuWeather.""" def __init__(self, entry: ConfigEntry) -> None: """Initialize AccuWeather options flow.""" self.config_entry = entry async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Manage the options.""" return await self.async_step_user() async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle a flow initialized by the user.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional( CONF_FORECAST, default=self.config_entry.options.get(CONF_FORECAST, False), ): bool } ), )
{ "repo_name": "kennedyshead/home-assistant", "path": "homeassistant/components/accuweather/config_flow.py", "copies": "2", "size": "4474", "license": "apache-2.0", "hash": -5284807563277703000, "line_mean": 35.0806451613, "line_max": 88, "alpha_frac": 0.5847116674, "autogenerated": false, "ratio": 4.469530469530469, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6054242136930469, "avg_score": null, "num_lines": null }
"""Adds config flow for AccuWeather.""" import asyncio from accuweather import AccuWeather, ApiError, InvalidApiKeyError, RequestsExceededError from aiohttp import ClientError from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from .const import CONF_FORECAST, DOMAIN # pylint:disable=unused-import class AccuWeatherFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for AccuWeather.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" # Under the terms of use of the API, one user can use one free API key. Due to # the small number of requests allowed, we only allow one integration instance. if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") errors = {} if user_input is not None: websession = async_get_clientsession(self.hass) try: async with timeout(10): accuweather = AccuWeather( user_input[CONF_API_KEY], websession, latitude=user_input[CONF_LATITUDE], longitude=user_input[CONF_LONGITUDE], ) await accuweather.async_get_location() except (ApiError, ClientConnectorError, asyncio.TimeoutError, ClientError): errors["base"] = "cannot_connect" except InvalidApiKeyError: errors[CONF_API_KEY] = "invalid_api_key" except RequestsExceededError: errors[CONF_API_KEY] = "requests_exceeded" else: await self.async_set_unique_id( accuweather.location_key, raise_on_progress=False ) return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional( CONF_NAME, default=self.hass.config.location_name ): str, } ), errors=errors, ) @staticmethod @callback def async_get_options_flow(config_entry): """Options callback for AccuWeather.""" return AccuWeatherOptionsFlowHandler(config_entry) class AccuWeatherOptionsFlowHandler(config_entries.OptionsFlow): """Config flow options for AccuWeather.""" def __init__(self, config_entry): """Initialize AccuWeather options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage the options.""" return await self.async_step_user() async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional( CONF_FORECAST, default=self.config_entry.options.get(CONF_FORECAST, False), ): bool } ), )
{ "repo_name": "mezz64/home-assistant", "path": "homeassistant/components/accuweather/config_flow.py", "copies": "11", "size": "4174", "license": "apache-2.0", "hash": 5717172662766872000, "line_mean": 36.2678571429, "line_max": 88, "alpha_frac": 0.5828941064, "autogenerated": false, "ratio": 4.497844827586207, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
"""Adds config flow for Airly.""" from airly import Airly from airly.exceptions import AirlyError import async_timeout import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from .const import DEFAULT_NAME, DOMAIN, NO_AIRLY_SENSORS @callback def configured_instances(hass): """Return a set of configured Airly instances.""" return set( entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN) ) class AirlyFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for Airly.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def __init__(self): """Initialize.""" self._errors = {} async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" self._errors = {} websession = async_get_clientsession(self.hass) if user_input is not None: if user_input[CONF_NAME] in configured_instances(self.hass): self._errors[CONF_NAME] = "name_exists" api_key_valid = await self._test_api_key(websession, user_input["api_key"]) if not api_key_valid: self._errors["base"] = "auth" else: location_valid = await self._test_location( websession, user_input["api_key"], user_input["latitude"], user_input["longitude"], ) if not location_valid: self._errors["base"] = "wrong_location" if not self._errors: return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self._show_config_form( name=DEFAULT_NAME, api_key="", latitude=self.hass.config.latitude, longitude=self.hass.config.longitude, ) def _show_config_form(self, name=None, api_key=None, latitude=None, longitude=None): """Show the configuration form to edit data.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY, default=api_key): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional(CONF_NAME, default=name): str, } ), errors=self._errors, ) async def _test_api_key(self, client, api_key): """Return true if api_key is valid.""" with async_timeout.timeout(10): airly = Airly(api_key, client) measurements = airly.create_measurements_session_point( latitude=52.24131, longitude=20.99101 ) try: await measurements.update() except AirlyError: return False return True async def _test_location(self, client, api_key, latitude, longitude): """Return true if location is valid.""" with async_timeout.timeout(10): airly = Airly(api_key, client) measurements = airly.create_measurements_session_point( latitude=latitude, longitude=longitude ) await measurements.update() current = measurements.current if current["indexes"][0]["description"] == NO_AIRLY_SENSORS: return False return True
{ "repo_name": "leppa/home-assistant", "path": "homeassistant/components/airly/config_flow.py", "copies": "1", "size": "3976", "license": "apache-2.0", "hash": -1002484137566711400, "line_mean": 33.8771929825, "line_max": 88, "alpha_frac": 0.5716800805, "autogenerated": false, "ratio": 4.374037403740374, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004022679839976518, "num_lines": 114 }
"""Adds config flow for Airly.""" import async_timeout import voluptuous as vol from airly import Airly from airly.exceptions import AirlyError import homeassistant.helpers.config_validation as cv from homeassistant import config_entries from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DEFAULT_NAME, DOMAIN, NO_AIRLY_SENSORS @callback def configured_instances(hass): """Return a set of configured Airly instances.""" return set( entry.data[CONF_NAME] for entry in hass.config_entries.async_entries(DOMAIN) ) class AirlyFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for Airly.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def __init__(self): """Initialize.""" self._errors = {} async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" self._errors = {} websession = async_get_clientsession(self.hass) if user_input is not None: if user_input[CONF_NAME] in configured_instances(self.hass): self._errors[CONF_NAME] = "name_exists" api_key_valid = await self._test_api_key(websession, user_input["api_key"]) if not api_key_valid: self._errors["base"] = "auth" else: location_valid = await self._test_location( websession, user_input["api_key"], user_input["latitude"], user_input["longitude"], ) if not location_valid: self._errors["base"] = "wrong_location" if not self._errors: return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self._show_config_form( name=DEFAULT_NAME, api_key="", latitude=self.hass.config.latitude, longitude=self.hass.config.longitude, ) def _show_config_form(self, name=None, api_key=None, latitude=None, longitude=None): """Show the configuration form to edit data.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_API_KEY, default=api_key): str, vol.Optional( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Optional( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, vol.Optional(CONF_NAME, default=name): str, } ), errors=self._errors, ) async def _test_api_key(self, client, api_key): """Return true if api_key is valid.""" with async_timeout.timeout(10): airly = Airly(api_key, client) measurements = airly.create_measurements_session_point( latitude=52.24131, longitude=20.99101 ) try: await measurements.update() except AirlyError: return False return True async def _test_location(self, client, api_key, latitude, longitude): """Return true if location is valid.""" with async_timeout.timeout(10): airly = Airly(api_key, client) measurements = airly.create_measurements_session_point( latitude=latitude, longitude=longitude ) await measurements.update() current = measurements.current if current["indexes"][0]["description"] == NO_AIRLY_SENSORS: return False return True
{ "repo_name": "qedi-r/home-assistant", "path": "homeassistant/components/airly/config_flow.py", "copies": "2", "size": "3976", "license": "apache-2.0", "hash": -597709820204643000, "line_mean": 33.8771929825, "line_max": 88, "alpha_frac": 0.5716800805, "autogenerated": false, "ratio": 4.374037403740374, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004022679839976518, "num_lines": 114 }
"""Adds config flow for Bravia TV integration.""" import ipaddress import logging import re from bravia_tv import BraviaRC from bravia_tv.braviarc import NoIPControl import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from .const import ( # pylint:disable=unused-import ATTR_CID, ATTR_MAC, ATTR_MODEL, BRAVIARC, CLIENTID_PREFIX, CONF_IGNORED_SOURCES, DOMAIN, NICKNAME, ) _LOGGER = logging.getLogger(__name__) def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: disallowed = re.compile(r"[^a-zA-Z\d\-]") return all(x and not disallowed.search(x) for x in host.split(".")) class BraviaTVConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for BraviaTV integration.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize.""" self.braviarc = None self.host = None self.title = None self.mac = None async def init_device(self, pin): """Initialize Bravia TV device.""" await self.hass.async_add_executor_job( self.braviarc.connect, pin, CLIENTID_PREFIX, NICKNAME ) if not self.braviarc.is_connected(): raise CannotConnect() system_info = await self.hass.async_add_executor_job( self.braviarc.get_system_info ) if not system_info: raise ModelNotSupported() await self.async_set_unique_id(system_info[ATTR_CID].lower()) self._abort_if_unique_id_configured() self.title = system_info[ATTR_MODEL] self.mac = system_info[ATTR_MAC] @staticmethod @callback def async_get_options_flow(config_entry): """Bravia TV options callback.""" return BraviaTVOptionsFlowHandler(config_entry) async def async_step_import(self, user_input=None): """Handle configuration by yaml file.""" self.host = user_input[CONF_HOST] self.braviarc = BraviaRC(self.host) try: await self.init_device(user_input[CONF_PIN]) except CannotConnect: _LOGGER.error("Import aborted, cannot connect to %s", self.host) return self.async_abort(reason="cannot_connect") except NoIPControl: _LOGGER.error("IP Control is disabled in the TV settings") return self.async_abort(reason="no_ip_control") except ModelNotSupported: _LOGGER.error("Import aborted, your TV is not supported") return self.async_abort(reason="unsupported_model") user_input[CONF_MAC] = self.mac return self.async_create_entry(title=self.title, data=user_input) async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: if host_valid(user_input[CONF_HOST]): self.host = user_input[CONF_HOST] self.braviarc = BraviaRC(self.host) return await self.async_step_authorize() errors[CONF_HOST] = "invalid_host" return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST, default=""): str}), errors=errors, ) async def async_step_authorize(self, user_input=None): """Get PIN from the Bravia TV device.""" errors = {} if user_input is not None: try: await self.init_device(user_input[CONF_PIN]) except CannotConnect: errors["base"] = "cannot_connect" except ModelNotSupported: errors["base"] = "unsupported_model" else: user_input[CONF_HOST] = self.host user_input[CONF_MAC] = self.mac return self.async_create_entry(title=self.title, data=user_input) # Connecting with th PIN "0000" to start the pairing process on the TV. try: await self.hass.async_add_executor_job( self.braviarc.connect, "0000", CLIENTID_PREFIX, NICKNAME ) except NoIPControl: return self.async_abort(reason="no_ip_control") return self.async_show_form( step_id="authorize", data_schema=vol.Schema({vol.Required(CONF_PIN, default=""): str}), errors=errors, ) class BraviaTVOptionsFlowHandler(config_entries.OptionsFlow): """Config flow options for Bravia TV.""" def __init__(self, config_entry): """Initialize Bravia TV options flow.""" self.braviarc = None self.config_entry = config_entry self.pin = config_entry.data[CONF_PIN] self.ignored_sources = config_entry.options.get(CONF_IGNORED_SOURCES) self.source_list = [] async def async_step_init(self, user_input=None): """Manage the options.""" self.braviarc = self.hass.data[DOMAIN][self.config_entry.entry_id][BRAVIARC] if not self.braviarc.is_connected(): await self.hass.async_add_executor_job( self.braviarc.connect, self.pin, CLIENTID_PREFIX, NICKNAME ) content_mapping = await self.hass.async_add_executor_job( self.braviarc.load_source_list ) self.source_list = [*content_mapping] return await self.async_step_user() async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional( CONF_IGNORED_SOURCES, default=self.ignored_sources ): cv.multi_select(self.source_list) } ), ) class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class ModelNotSupported(exceptions.HomeAssistantError): """Error to indicate not supported model."""
{ "repo_name": "robbiet480/home-assistant", "path": "homeassistant/components/braviatv/config_flow.py", "copies": "2", "size": "6488", "license": "apache-2.0", "hash": -8750293057679700000, "line_mean": 31.9340101523, "line_max": 84, "alpha_frac": 0.607891492, "autogenerated": false, "ratio": 3.965770171149144, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5573661663149144, "avg_score": null, "num_lines": null }
"""Adds config flow for Brother Printer.""" import ipaddress import re from brother import Brother, SnmpError, UnsupportedModel import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_HOST, CONF_TYPE from .const import DOMAIN, PRINTER_TYPES from .utils import get_snmp_engine DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST, default=""): str, vol.Optional(CONF_TYPE, default="laser"): vol.In(PRINTER_TYPES), } ) def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: disallowed = re.compile(r"[^a-zA-Z\d\-]") return all(x and not disallowed.search(x) for x in host.split(".")) class BrotherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Brother Printer.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize.""" self.brother = None self.host = None async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: if not host_valid(user_input[CONF_HOST]): raise InvalidHost() snmp_engine = get_snmp_engine(self.hass) brother = Brother(user_input[CONF_HOST], snmp_engine=snmp_engine) await brother.async_update() await self.async_set_unique_id(brother.serial.lower()) self._abort_if_unique_id_configured() title = f"{brother.model} {brother.serial}" return self.async_create_entry(title=title, data=user_input) except InvalidHost: errors[CONF_HOST] = "wrong_host" except ConnectionError: errors["base"] = "cannot_connect" except SnmpError: errors["base"] = "snmp_error" except UnsupportedModel: return self.async_abort(reason="unsupported_model") return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) async def async_step_zeroconf(self, discovery_info): """Handle zeroconf discovery.""" if discovery_info is None: return self.async_abort(reason="cannot_connect") if not discovery_info.get("name") or not discovery_info["name"].startswith( "Brother" ): return self.async_abort(reason="not_brother_printer") # Hostname is format: brother.local. self.host = discovery_info["hostname"].rstrip(".") snmp_engine = get_snmp_engine(self.hass) self.brother = Brother(self.host, snmp_engine=snmp_engine) try: await self.brother.async_update() except (ConnectionError, SnmpError, UnsupportedModel): return self.async_abort(reason="cannot_connect") # Check if already configured await self.async_set_unique_id(self.brother.serial.lower()) self._abort_if_unique_id_configured() self.context.update( { "title_placeholders": { "serial_number": self.brother.serial, "model": self.brother.model, } } ) return await self.async_step_zeroconf_confirm() async def async_step_zeroconf_confirm(self, user_input=None): """Handle a flow initiated by zeroconf.""" if user_input is not None: title = f"{self.brother.model} {self.brother.serial}" return self.async_create_entry( title=title, data={CONF_HOST: self.host, CONF_TYPE: user_input[CONF_TYPE]}, ) return self.async_show_form( step_id="zeroconf_confirm", data_schema=vol.Schema( {vol.Optional(CONF_TYPE, default="laser"): vol.In(PRINTER_TYPES)} ), description_placeholders={ "serial_number": self.brother.serial, "model": self.brother.model, }, ) class InvalidHost(exceptions.HomeAssistantError): """Error to indicate that hostname/IP address is invalid."""
{ "repo_name": "adrienbrault/home-assistant", "path": "homeassistant/components/brother/config_flow.py", "copies": "3", "size": "4407", "license": "mit", "hash": 3360446324924501000, "line_mean": 32.641221374, "line_max": 83, "alpha_frac": 0.5888359428, "autogenerated": false, "ratio": 4.046831955922865, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0002770611130320682, "num_lines": 131 }
"""Adds config flow for Dune HD integration.""" from __future__ import annotations import ipaddress import logging import re from typing import Any, Final from pdunehd import DuneHDPlayer import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_HOST from homeassistant.data_entry_flow import FlowResult from .const import DOMAIN _LOGGER: Final = logging.getLogger(__name__) def host_valid(host: str) -> bool: """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version in [4, 6]: return True except ValueError: pass if len(host) > 253: return False allowed = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return all(allowed.match(x) for x in host.split(".")) class DuneHDConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Dune HD integration.""" VERSION = 1 async def init_device(self, host: str) -> None: """Initialize Dune HD player.""" player = DuneHDPlayer(host) state = await self.hass.async_add_executor_job(player.update_state) if not state: raise CannotConnect() async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle the initial step.""" errors = {} if user_input is not None: if host_valid(user_input[CONF_HOST]): host: str = user_input[CONF_HOST] try: if self.host_already_configured(host): raise AlreadyConfigured() await self.init_device(host) except CannotConnect: errors[CONF_HOST] = "cannot_connect" except AlreadyConfigured: errors[CONF_HOST] = "already_configured" else: return self.async_create_entry(title=host, data=user_input) else: errors[CONF_HOST] = "invalid_host" return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST, default=""): str}), errors=errors, ) async def async_step_import( self, user_input: dict[str, str] | None = None ) -> FlowResult: """Handle configuration by yaml file.""" assert user_input is not None host: str = user_input[CONF_HOST] self._async_abort_entries_match({CONF_HOST: host}) try: await self.init_device(host) except CannotConnect: _LOGGER.error("Import aborted, cannot connect to %s", host) return self.async_abort(reason="cannot_connect") else: return self.async_create_entry(title=host, data=user_input) def host_already_configured(self, host: str) -> bool: """See if we already have a dunehd entry matching user input configured.""" existing_hosts = { entry.data[CONF_HOST] for entry in self._async_current_entries() } return host in existing_hosts class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class AlreadyConfigured(exceptions.HomeAssistantError): """Error to indicate device is already configured."""
{ "repo_name": "home-assistant/home-assistant", "path": "homeassistant/components/dunehd/config_flow.py", "copies": "2", "size": "3388", "license": "apache-2.0", "hash": -364915577055524100, "line_mean": 31.2666666667, "line_max": 83, "alpha_frac": 0.6071428571, "autogenerated": false, "ratio": 4.1468788249694, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00011337868480725623, "num_lines": 105 }
"""Adds config flow for Dune HD integration.""" import ipaddress import logging import re from pdunehd import DuneHDPlayer import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_HOST from .const import DOMAIN _LOGGER = logging.getLogger(__name__) def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: if len(host) > 253: return False allowed = re.compile(r"(?!-)[A-Z\d\-\_]{1,63}(?<!-)$", re.IGNORECASE) return all(allowed.match(x) for x in host.split(".")) class DuneHDConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Dune HD integration.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize.""" self.host = None async def init_device(self, host): """Initialize Dune HD player.""" player = DuneHDPlayer(host) state = await self.hass.async_add_executor_job(player.update_state) if not state: raise CannotConnect() async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: if host_valid(user_input[CONF_HOST]): self.host = user_input[CONF_HOST] try: if self.host_already_configured(self.host): raise AlreadyConfigured() await self.init_device(self.host) except CannotConnect: errors[CONF_HOST] = "cannot_connect" except AlreadyConfigured: errors[CONF_HOST] = "already_configured" else: return self.async_create_entry(title=self.host, data=user_input) else: errors[CONF_HOST] = "invalid_host" return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST, default=""): str}), errors=errors, ) async def async_step_import(self, user_input=None): """Handle configuration by yaml file.""" self.host = user_input[CONF_HOST] if self.host_already_configured(self.host): return self.async_abort(reason="already_configured") try: await self.init_device(self.host) except CannotConnect: _LOGGER.error("Import aborted, cannot connect to %s", self.host) return self.async_abort(reason="cannot_connect") else: return self.async_create_entry(title=self.host, data=user_input) def host_already_configured(self, host): """See if we already have a dunehd entry matching user input configured.""" existing_hosts = { entry.data[CONF_HOST] for entry in self._async_current_entries() } return host in existing_hosts class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect.""" class AlreadyConfigured(exceptions.HomeAssistantError): """Error to indicate device is already configured."""
{ "repo_name": "sander76/home-assistant", "path": "homeassistant/components/dunehd/config_flow.py", "copies": "3", "size": "3308", "license": "apache-2.0", "hash": -2486452650846179000, "line_mean": 31.7524752475, "line_max": 84, "alpha_frac": 0.6055018138, "autogenerated": false, "ratio": 4.192648922686946, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00023435116620905788, "num_lines": 101 }
"""Adds config flow for GIOS.""" import asyncio from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout from gios import ApiError, Gios, InvalidSensorsData, NoStationError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import CONF_STATION_ID, DEFAULT_NAME, DOMAIN # pylint:disable=unused-import DATA_SCHEMA = vol.Schema( { vol.Required(CONF_STATION_ID): int, vol.Optional(CONF_NAME, default=DEFAULT_NAME): str, } ) class GiosFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for GIOS.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" errors = {} if user_input is not None: try: await self.async_set_unique_id( user_input[CONF_STATION_ID], raise_on_progress=False ) self._abort_if_unique_id_configured() websession = async_get_clientsession(self.hass) with timeout(30): gios = Gios(user_input[CONF_STATION_ID], websession) await gios.update() return self.async_create_entry( title=user_input[CONF_STATION_ID], data=user_input, ) except (ApiError, ClientConnectorError, asyncio.TimeoutError): errors["base"] = "cannot_connect" except NoStationError: errors[CONF_STATION_ID] = "wrong_station_id" except InvalidSensorsData: errors[CONF_STATION_ID] = "invalid_sensors_data" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
{ "repo_name": "mKeRix/home-assistant", "path": "homeassistant/components/gios/config_flow.py", "copies": "6", "size": "1969", "license": "mit", "hash": 8669842686844972000, "line_mean": 32.9482758621, "line_max": 88, "alpha_frac": 0.6272219401, "autogenerated": false, "ratio": 4.068181818181818, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7695403758281818, "avg_score": null, "num_lines": null }
"""Adds config flow for GIOS.""" import asyncio from aiohttp.client_exceptions import ClientConnectorError from async_timeout import timeout from gios import ApiError, Gios, NoStationError import voluptuous as vol from homeassistant import config_entries, exceptions from homeassistant.const import CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import CONF_STATION_ID, DEFAULT_NAME, DOMAIN # pylint:disable=unused-import DATA_SCHEMA = vol.Schema( { vol.Required(CONF_STATION_ID): int, vol.Optional(CONF_NAME, default=DEFAULT_NAME): str, } ) class GiosFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for GIOS.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" errors = {} if user_input is not None: try: await self.async_set_unique_id( user_input[CONF_STATION_ID], raise_on_progress=False ) self._abort_if_unique_id_configured() websession = async_get_clientsession(self.hass) with timeout(30): gios = Gios(user_input[CONF_STATION_ID], websession) await gios.update() if not gios.available: raise InvalidSensorsData() return self.async_create_entry( title=user_input[CONF_STATION_ID], data=user_input, ) except (ApiError, ClientConnectorError, asyncio.TimeoutError): errors["base"] = "cannot_connect" except NoStationError: errors[CONF_STATION_ID] = "wrong_station_id" except InvalidSensorsData: errors[CONF_STATION_ID] = "invalid_sensors_data" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) class InvalidSensorsData(exceptions.HomeAssistantError): """Error to indicate invalid sensors data."""
{ "repo_name": "postlund/home-assistant", "path": "homeassistant/components/gios/config_flow.py", "copies": "2", "size": "2157", "license": "apache-2.0", "hash": -622666431586207200, "line_mean": 32.1846153846, "line_max": 88, "alpha_frac": 0.6267964766, "autogenerated": false, "ratio": 4.15606936416185, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00017286084701815038, "num_lines": 65 }
"""Adds config flow for Mill integration.""" import logging from mill import Mill import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN # pylint:disable=unused-import _LOGGER = logging.getLogger(__name__) DATA_SCHEMA = vol.Schema( {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str} ) class MillConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Mill integration.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_user(self, user_input=None): """Handle the initial step.""" if user_input is None: return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors={}, ) username = user_input[CONF_USERNAME].replace(" ", "") password = user_input[CONF_PASSWORD].replace(" ", "") mill_data_connection = Mill( username, password, websession=async_get_clientsession(self.hass), ) errors = {} if not await mill_data_connection.connect(): errors["connection_error"] = "connection_error" return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors, ) unique_id = username await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=unique_id, data={CONF_USERNAME: username, CONF_PASSWORD: password}, )
{ "repo_name": "pschmitt/home-assistant", "path": "homeassistant/components/mill/config_flow.py", "copies": "6", "size": "1706", "license": "apache-2.0", "hash": -7888228120362871000, "line_mean": 30.0181818182, "line_max": 85, "alpha_frac": 0.6494724502, "autogenerated": false, "ratio": 3.9953161592505855, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.7644788609450586, "avg_score": null, "num_lines": null }
"""Adds config flow for Nettigo Air Monitor.""" from __future__ import annotations import asyncio import logging from typing import Any, cast from aiohttp.client_exceptions import ClientConnectorError import async_timeout from nettigo_air_monitor import ApiError, CannotGetMac, NettigoAirMonitor import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ATTR_NAME, CONF_HOST from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.typing import DiscoveryInfoType from .const import DOMAIN _LOGGER = logging.getLogger(__name__) class NAMFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Config flow for Nettigo Air Monitor.""" VERSION = 1 def __init__(self) -> None: """Initialize flow.""" self.host: str | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle a flow initialized by the user.""" errors = {} if user_input is not None: self.host = user_input[CONF_HOST] try: mac = await self._async_get_mac(cast(str, self.host)) except (ApiError, ClientConnectorError, asyncio.TimeoutError): errors["base"] = "cannot_connect" except CannotGetMac: return self.async_abort(reason="device_unsupported") except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(format_mac(mac)) self._abort_if_unique_id_configured({CONF_HOST: self.host}) return self.async_create_entry( title=cast(str, self.host), data=user_input, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_HOST, default=""): str, } ), errors=errors, ) async def async_step_zeroconf( self, discovery_info: DiscoveryInfoType ) -> FlowResult: """Handle zeroconf discovery.""" self.host = discovery_info[CONF_HOST] try: mac = await self._async_get_mac(cast(str, self.host)) except (ApiError, ClientConnectorError, asyncio.TimeoutError): return self.async_abort(reason="cannot_connect") except CannotGetMac: return self.async_abort(reason="device_unsupported") await self.async_set_unique_id(format_mac(mac)) self._abort_if_unique_id_configured({CONF_HOST: self.host}) self.context["title_placeholders"] = { ATTR_NAME: discovery_info[ATTR_NAME].split(".")[0] } return await self.async_step_confirm_discovery() async def async_step_confirm_discovery( self, user_input: dict[str, Any] | None = None ) -> FlowResult: """Handle discovery confirm.""" errors: dict = {} if user_input is not None: return self.async_create_entry( title=cast(str, self.host), data={CONF_HOST: self.host}, ) self._set_confirm_only() return self.async_show_form( step_id="confirm_discovery", description_placeholders={CONF_HOST: self.host}, errors=errors, ) async def _async_get_mac(self, host: str) -> str: """Get device MAC address.""" websession = async_get_clientsession(self.hass) nam = NettigoAirMonitor(websession, host) # Device firmware uses synchronous code and doesn't respond to http queries # when reading data from sensors. The nettigo-air-monitor library tries to get # the data 4 times, so we use a longer than usual timeout here. with async_timeout.timeout(30): return cast(str, await nam.async_get_mac_address())
{ "repo_name": "kennedyshead/home-assistant", "path": "homeassistant/components/nam/config_flow.py", "copies": "2", "size": "4193", "license": "apache-2.0", "hash": 5386702381332036000, "line_mean": 33.652892562, "line_max": 86, "alpha_frac": 0.6119723348, "autogenerated": false, "ratio": 4.226814516129032, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5838786850929032, "avg_score": null, "num_lines": null }
"""Adds config flow for Tibber integration.""" import asyncio import aiohttp import tibber import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN DATA_SCHEMA = vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str}) class TibberConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Tibber integration.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL async def async_step_import(self, import_info): """Set the config entry up from yaml.""" return await self.async_step_user(import_info) async def async_step_user(self, user_input=None): """Handle the initial step.""" if self._async_current_entries(): return self.async_abort(reason="already_configured") if user_input is not None: access_token = user_input[CONF_ACCESS_TOKEN].replace(" ", "") tibber_connection = tibber.Tibber( access_token=access_token, websession=async_get_clientsession(self.hass), ) errors = {} try: await tibber_connection.update_info() except asyncio.TimeoutError: errors[CONF_ACCESS_TOKEN] = "timeout" except aiohttp.ClientError: errors[CONF_ACCESS_TOKEN] = "cannot_connect" except tibber.InvalidLogin: errors[CONF_ACCESS_TOKEN] = "invalid_access_token" if errors: return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors, ) unique_id = tibber_connection.user_id await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=tibber_connection.name, data={CONF_ACCESS_TOKEN: access_token}, ) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors={}, )
{ "repo_name": "sander76/home-assistant", "path": "homeassistant/components/tibber/config_flow.py", "copies": "3", "size": "2267", "license": "apache-2.0", "hash": -4784417641404741000, "line_mean": 30.4861111111, "line_max": 73, "alpha_frac": 0.5955006617, "autogenerated": false, "ratio": 4.245318352059925, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6340819013759925, "avg_score": null, "num_lines": null }
import asyncio from discord.ext import commands def decToHex(dec: int): """Converts a decimal integer to a hex string.""" hexDigits = "0123456789ABCDEF" conversion = '' # (Re-)initiate string # dec referenced as division # special case if dec is already 0 if dec == 0: return "00" while dec != 0: remainder = dec % 16 dec = dec // 16 conversion += hexDigits[remainder] conversion = reverseString(conversion) return conversion def reverseString(string: str): """Reverses a string.""" return string[::-1] def calcDeltaHex(n: float, rate: float): # n = semitone difference, rate = the initial samplerate of your sample in Hz """Deflemask SegaPCM Delta command calculator. n = semitone difference, rate = the initial samplerate of your sample in Hz""" a = 2**(1/12) # a = 12-tones in an octave (see 'Frequency Table formula' for the 'equal tempered scale') fn = rate * (a**n) # Calculates the freq of the note, in 'n' semitones away from original pitch delta = fn / (31250/255) # 255 is FF in hex; the max value of 20xx delta = int(round(delta, 0)) # Rounds the delta value to 0 decimals return decToHex(delta) # Converts delta value from decimal to hex class Bulbautils: """Ivysalt's utility commands. Useful for chiptune stuff mostly.""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=False, description='Note: rounds speed and tempo if given tempo results in a non-integer speed.') @asyncio.coroutine def amkspeed(self, tempo: float): """Calculates AddMusicK speed, given tempo in BPM.""" try: if (tempo <= 0): raise ValueError("Error: Tempo must be positive.") amkspeed = tempo * 256 / 625 amkspeedtest = amkspeed % 1 if (amkspeedtest != 0): yield from self.bot.say("The AMK speed is about {:.0f}. The yielded tempo is {:g} BPM.".format(int(round(amkspeed)), round(amkspeed) * 625 / 256)) else: yield from self.bot.say("The AMK speed is {:.0f}.".format(amkspeed)) except ValueError as err: # Display error message to channel yield from self.bot.say("{} Type ``?help amkspeed`` for proper usage.".format(err)) @commands.command(pass_context=False, description='Calculates clock speed based on first the desired tempo and then the tick speed.') @asyncio.coroutine def clockspeed(self, tempo: float, speed: float): """Calculates clock rate, given tempo in BPM and speed in ticks per row/unit.""" try: if (tempo <= 0): raise ValueError("Error: Tempo must be positive.") if (speed <= 0): raise ValueError("Error: Tick speed must be positive.") clockspeed = tempo * speed / 15 yield from self.bot.say("The clock speed is {:g} Hz.".format(clockspeed)) except ValueError as err: # Display error message to channel yield from self.bot.say("{} Type ``?help clockspeed`` for proper usage.".format(err)) @commands.command(pass_context=False, description='Calculates tick speed based on first the desired tempo and then the clock speed.') @asyncio.coroutine def tickspeed(self, tempo: float, clock: float): """Calculates tick speed, given tempo in BPM and clock rate in Hz.""" try: if (tempo <= 0): raise ValueError("Error: Tempo must be positive.") if (tempo <= 0): raise ValueError("Error: Clock speed must be positive.") tickspeed = 15 * clock / tempo # if the tickspeed is non-int it'll print past the period yield from self.bot.say("The tick speed is {:g}.".format(tickspeed)) except ValueError as err: # Display error message to channel yield from self.bot.say("{} Type ``?help tickspeed`` for proper usage.".format(err)) @commands.command(pass_context=True, no_pm=False) @asyncio.coroutine def deltapcm(self, ctx, semitone_change: float=0, rate: float=31250.0): """Deflemask SegaPCM Delta command calculator. Written by DeltaRazero. semitone_change = semitone difference, rate = the initial samplerate of your sample in Hz""" if (semitone_change == 0 and rate == 31250.0): yield from self.bot.say("Type ``?help deltapcm`` to get usage information.") return elif (rate <= 0 or rate > 31250): yield from self.bot.say("Sample rate needs to be between 1 Hz and 31250 Hz... Type ``?help deltapcm`` to get usage information.") return try: convertedHex = calcDeltaHex(semitone_change, rate) except OverflowError as err: yield from self.bot.say("{} Type ``?help deltapcm`` for proper usage.".format(err)) if (convertedHex == ""): # Check if hex value smaller than 00 or over FF and report to user yield from self.bot.say("ERROR: Underflow ! Type ``?help deltapcm`` to get usage information.") elif (len(convertedHex) > 2): yield from self.bot.say("ERROR: Overflow ! Type ``?help deltapcm`` to get usage information.") else: if (len(convertedHex) == 1): # Check if value not less than 10 (in hex) and add 0 if so convertedHex = "0" + convertedHex yield from self.bot.say("Your delta command is: ``20{}``".format(convertedHex)) def setup(bot): bot.add_cog(Bulbautils(bot))
{ "repo_name": "retrodpc/Bulbaspot-Cogs", "path": "bulbautils/bulbautils.py", "copies": "1", "size": "5991", "license": "apache-2.0", "hash": 314027902224836030, "line_mean": 44.1, "line_max": 162, "alpha_frac": 0.6105825405, "autogenerated": false, "ratio": 3.9860279441117763, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5096610484611777, "avg_score": null, "num_lines": null }
#Adds day of week def day_of_week(): import pandas as pd days=pd.DataFrame([[0,1,2,3,4,5,6],["Sun","Mon","Tue","Wed","Thr","Fri","Sat"]]).transpose() days.columns=['indx','dayOfWeek'] return days #joins dataset and day of week def set_day_of_week(df,days): df=df.merge(days,how='left',left_on='weekday',right_on='indx') df.drop('weekday',axis=1,inplace=True) return df #Sets days in the dataset def set_days(df): import pandas as pd df['days']=pd.Series(range(df.shape[0]))/24 df['days']=df['days'].astype('int') return df import pandas as pd data=pd.read_csv("dbike.csv") df=pd.DataFrame(data) #df['atemp'] del(df['atemp'],df['casual'],df['registered'],df['instant'],df['dteday']) num_cols=["temp","hum","windspeed","hr"] def bike_scatter(df,cols): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import statsmodels.nonparametric.smoothers_lowess as lw print('Columns='+str(df.columns)) print('cols='+str(cols)) for col in cols: print(col) los=lw.lowess(df['cnt'],df[col], frac=0.3) fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df.plot(kind='scatter',x=col,y='cnt',ax=ax) plt.plot(los[:,0],los[:,1],axes=ax,color='r') ax.set_xlabel(col) ax.set_ylabel('No. of Bikes') ax.set_title('No. of bikes vs. '+col) fig.savefig('scatter_'+col+'.png') return 'DONE' box_cols=['season','yr','mnth','hr','holiday','workingday','weathersit','dayOfWeek'] def bike_box(df,cols): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for col in cols: fig =plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df.boxplot(column='cnt',by=col,ax=ax) ax.set_xlabel(col) ax.set_ylabel('No of bikes') ax.set_title('Number of bikes vs'+col) fig.savefig('box_'+col+'.png') return 'DONE' plt_times=[6,8,10,12,14,16,18,20] def bike_series(df,tms): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt lims=(min(df.cnt),max(df.cnt)) for t in tms: fig =plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df[df.hr==t].plot(kind='line',x='days',y='cnt',ylim=lims,ax=ax) plt.xlabel("Days from start ") plt.ylabel("Bikes rented") plt.title("Bikes rented by day for hour="+str(t)) fig.savefig('series_'+str(t)+'.png') return 'DONE' hist_cols=["cnt","temp","hum","windspeed"] def bike_hist(df,cols): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for col in cols: fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df[col].hist(bins=30,ax=ax) ax.set_xlabel(col) ax.set_ylabel('Density of '+col) ax.set_ylabel('Density of '+col) fig.savefig('hist_'+col+'.png') return 'DONE' #Display histograms by hrs def bike_hist_cond(df,col,by): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt fig,ax=plt.subplots(nrows=len(by),ncols=1,figsize=(8,6)) for i,t in enumerate(by): temp=df.ix[df.hr==t,col] ax[i].hist(temp.as_matrix(),bins=30) ax[i].set_title('Bikes rented at time = '+str(t)) fig.savefig('hist_') #displaying bikes rented with time series def ts_bikes(df,times): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for tm in times: fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df[df.hr == tm].plot(kind='line',x='days',y='cnt',ax=ax) df[df.hr == tm].plot(kind='line',x='days',y='prediction',color='red',ax=ax) plt.xlabel("Days from start") plt.ylabel("Number of bikes rented") plt.title("Bikes rented for hour="+str(tm)) fig.savefig('ts_'+str(tm)+'.png') return 'DONE' #Calculating residuals def residuals(df): df['resids']=df.prediction - df.cnt return df #Displaying residuals def box_residuals(df): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt df=residuals(df) fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df.boxplot(column=['resids'],by=['hr'],ax=ax) plt.xlabel('') plt.ylabel('Residuals') plt.title("Boxplot grouped by hr") fig.savefig('boxes'+'.png') return 'DONE' #Displaying residuals with time series def ts_resids_hist(df,times): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for tm in times: fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() temp=df.ix[df.hr==tm,'resids'] ax.hist(temp.as_matrix(),bins=30) plt.xlabel('Residuals') plt.ylabel('Density') plt.title("Residuals for hour="+str(tm)) fig.savefig('hist_'+str(tm)+'.png') return 'DONE' days=day_of_week() df1=set_day_of_week(df,days) df2=set_days(df1) #Part 1 (Without separating working hours and non working hours) train_data=df2.head(12165) test_data=df2.tail(5214) test_data1=df2.tail(5214) train_labels=train_data['cnt'] del(train_data['cnt'],train_data['dayOfWeek']) train_features=train_data from sklearn import datasets, linear_model #Linear Regression model reg=linear_model.LinearRegression() reg.fit(train_features,train_labels) del(test_data1['cnt'],test_data1['dayOfWeek']) import numpy as np prediction=[] for i in np.arange(len(test_data)): pred_val=test_data1.iloc[[i]] #Predicting on testing data l=reg.predict(pred_val) l=' '.join(map(str,l)) coef=reg.coef_ prediction.append(l) test_data['prediction']=prediction test_data['prediction']=pd.to_numeric(test_data['prediction'],errors='coerce') times=[6,8,10,12,14,16,18,20,22] ts_bikes(test_data,times) residuals(test_data) box_residuals(test_data) ts_resids_hist(test_data,times) #Part 2 (Separating working hours and non working hours) #Spliting working hours and non working hours def is_Working(df): import numpy as np work_day=df['workingday'].as_matrix() holiday=df['holiday'].as_matrix() df['isWorking']=np.where(np.logical_and(work_day==1, holiday==0),1,0) df['monthCount']=12*df.yr+df.mnth isWorking=df['isWorking'].as_matrix() df['workHr']=np.where(isWorking,df.hr,df.hr+24.0) df=df.drop(['workingday','holiday','hr'], axis=1) return df def lower_quantile(df): import pandas as pd out=df.groupby(['monthCount','workHr']).cnt.quantile(q=0.2) out=pd.DataFrame(out) out.reset_index(inplace=True) out.columns=['monthCount','workHr','quantile'] return out def quantile_2(df,quantile): import pandas as pd #Save original names of dataframe in_names=list(df) df=pd.merge(df,quantile,left_on=['monthCount','workHr'],right_on=['monthCount','workHr'],how='inner') #Filter rows df=df.ix[df['cnt']>df['quantile']] #Remove unwanted cols df.drop('quantile',axis=1,inplace=True) df.columns=in_names #Sort data based on dayCount df.sort(['days','workHr'], axis=0,inplace=True) return df #refer ts_bikes() def ts_bikes1(df,times): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for tm in times: fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df[df.workHr == tm].plot(kind='line',x='days',y='cnt',ax=ax) df[df.workHr == tm].plot(kind='line',x='days',y='prediction',color='red',ax=ax) plt.xlabel("Days from start") plt.ylabel("Number of bikes rented") plt.title("Bikes rented for hour="+str(tm)) fig.savefig('ts1_'+str(tm)+'.png') return 'DONE' #refer box_residuals() def box_residuals1(df): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt df=residuals(df) fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() df.boxplot(column=['resids'],by=['workHr'],ax=ax) plt.xlabel('') plt.ylabel('Residuals') plt.title("Boxplot grouped by workingHr") fig.savefig('boxes1'+'.png') return 'DONE' #refer ts_resids_hist() def ts_resids_hist1(df,times): import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt for tm in times: fig=plt.figure(figsize=(8,6)) fig.clf() ax=fig.gca() temp=df.ix[df.workHr==tm,'resids'] ax.hist(temp.as_matrix(),bins=30) plt.xlabel('Residuals') plt.ylabel('Density') plt.title("Residuals for workHour="+str(tm)) fig.savefig('hist1_'+str(tm)+'.png') return 'DONE' #Calculating working day df3=is_Working(df2) #Calculating quantile where quantile=0.2 quantile=lower_quantile(df3) #merging df3 and quantile df4=quantile_2(df3,quantile) #Spliting the data train_features1=df4.head(9287) test_data3=df4.tail(3980) test_data2=df4.tail(3980) train_labels1=train_features1['cnt'] del(train_features1['cnt'],train_features1['dayOfWeek']) #train #Linear Regression model reg1=linear_model.LinearRegression() reg1.fit(train_features1,train_labels1) del(test_data2['cnt'],test_data2['dayOfWeek']) import numpy as np prediction1=[] for i in np.arange(len(test_data2)): pred_val1=test_data2.iloc[[i]] #Predicting on testing data l1=reg1.predict(pred_val1) l1=' '.join(map(str,l1)) coef=reg1.coef_ prediction1.append(l1) test_data3['prediction']=prediction1 test_data3['prediction']=pd.to_numeric(test_data3['prediction'],errors='coerce') times1=[6,8,10,12,14,16,18,20,22,30,32,34,36,38,40] ts_bikes1(test_data3,times1) residuals(test_data3) box_residuals1(test_data3) ts_resids_hist1(test_data3,times1)
{ "repo_name": "Achilles107/BikeRental", "path": "bikeRental.py", "copies": "1", "size": "9995", "license": "mit", "hash": -5644749837821821000, "line_mean": 31.2059800664, "line_max": 105, "alpha_frac": 0.6203101551, "autogenerated": false, "ratio": 2.9844729770080622, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.41047831321080624, "avg_score": null, "num_lines": null }
"""Adds default (bad) framework lifecycle event datetimes where those fields are currently null, so that we can set them as non-nullable in the next migration. This migration will run against preview/staging/production, but we have already manually populated all of the frameworks there, so it will take no effect. The primary purpose of this migration is to populate framework dates for API unit tests. Revision ID: 1150 Revises: 1140 Create Date: 2018-05-08 09:53:43.699711 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.sql import table, column, and_ # revision identifiers, used by Alembic. revision = '1150' down_revision = '1140' def upgrade(): frameworks = table('frameworks', column('applications_close_at_utc', sa.DateTime()), column('clarifications_close_at_utc', sa.DateTime()), column('clarifications_publish_at_utc', sa.DateTime()), column('framework_expires_at_utc', sa.DateTime()), column('framework_live_at_utc', sa.DateTime()), column('intention_to_award_at_utc', sa.DateTime())) op.execute( frameworks.update().where( and_( frameworks.c.applications_close_at_utc == None, # noqa frameworks.c.clarifications_close_at_utc == None, # noqa frameworks.c.clarifications_publish_at_utc == None, # noqa frameworks.c.framework_expires_at_utc == None, # noqa frameworks.c.framework_live_at_utc == None, # noqa frameworks.c.intention_to_award_at_utc == None, # noqa ) ).values( applications_close_at_utc='1970-01-01T00:00:00.000000Z', clarifications_close_at_utc='1970-01-01T00:00:00.000000Z', clarifications_publish_at_utc='1970-01-01T00:00:00.000000Z', framework_expires_at_utc='1970-01-01T00:00:00.000000Z', framework_live_at_utc='1970-01-01T00:00:00.000000Z', intention_to_award_at_utc='1970-01-01T00:00:00.000000Z', ) ) def downgrade(): pass
{ "repo_name": "alphagov/digitalmarketplace-api", "path": "migrations/versions/1150_add_dates_to_empty_frameworks_for_tests.py", "copies": "1", "size": "2201", "license": "mit", "hash": -6360806096910406000, "line_mean": 41.3269230769, "line_max": 120, "alpha_frac": 0.6288050886, "autogenerated": false, "ratio": 3.6622296173044924, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4791034705904492, "avg_score": null, "num_lines": null }
"""Adds detail for the Resource.""" from baseCmd import * from baseResponse import * class addResourceDetailCmd (baseCmd): typeInfo = {} def __init__(self): self.isAsync = "true" """Map of (key/value pairs)""" """Required""" self.details = [] self.typeInfo['details'] = 'map' """resource id to create the details for""" """Required""" self.resourceid = None self.typeInfo['resourceid'] = 'string' """type of the resource""" """Required""" self.resourcetype = None self.typeInfo['resourcetype'] = 'string' """pass false if you want this detail to be disabled for the regular user. True by default""" self.fordisplay = None self.typeInfo['fordisplay'] = 'boolean' self.required = ["details", "resourceid", "resourcetype", ] class addResourceDetailResponse (baseResponse): typeInfo = {} def __init__(self): """any text associated with the success or failure""" self.displaytext = None self.typeInfo['displaytext'] = 'string' """true if operation is executed successfully""" self.success = None self.typeInfo['success'] = 'boolean'
{ "repo_name": "MissionCriticalCloud/marvin", "path": "marvin/cloudstackAPI/addResourceDetail.py", "copies": "1", "size": "1235", "license": "apache-2.0", "hash": 3843862349573584400, "line_mean": 30.6666666667, "line_max": 101, "alpha_frac": 0.5935222672, "autogenerated": false, "ratio": 4.288194444444445, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02589240824534942, "num_lines": 39 }
"""Adds docstrings to functions defined in the torch._C""" import re import torch._C from torch._C import _add_docstr as add_docstr def parse_kwargs(desc): """Maps a description of args to a dictionary of {argname: description}. Input: (' weight (Tensor): a weight tensor\n' + ' Some optional description') Output: { 'weight': \ 'weight (Tensor): a weight tensor\n Some optional description' } """ # Split on exactly 4 spaces after a newline regx = re.compile(r"\n\s{4}(?!\s)") kwargs = [section.strip() for section in regx.split(desc)] kwargs = [section for section in kwargs if len(section) > 0] return {desc.split(' ')[0]: desc for desc in kwargs} reduceops_common_args = parse_kwargs(""" dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. If specified, the input tensor is casted to :attr:`dtype` before the operation is performed. This is useful for preventing data type overflows. Default: None. """) factory_common_args = parse_kwargs(""" out (Tensor, optional): the output tensor dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: if ``None``, uses a global default (see :func:`torch.set_default_tensor_type`). layout (:class:`torch.layout`, optional): the desired layout of returned Tensor. Default: ``torch.strided``. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if ``None``, uses the current device for the default tensor type (see :func:`torch.set_default_tensor_type`). :attr:`device` will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: ``False``. """) factory_like_common_args = parse_kwargs(""" input (Tensor): the size of :attr:`input` will determine size of the output tensor layout (:class:`torch.layout`, optional): the desired layout of returned tensor. Default: if ``None``, defaults to the layout of :attr:`input`. dtype (:class:`torch.dtype`, optional): the desired data type of returned Tensor. Default: if ``None``, defaults to the dtype of :attr:`input`. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if ``None``, defaults to the device of :attr:`input`. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: ``False``. """) factory_data_common_args = parse_kwargs(""" data (array_like): Initial data for the tensor. Can be a list, tuple, NumPy ``ndarray``, scalar, and other types. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: if ``None``, infers data type from :attr:`data`. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if ``None``, uses the current device for the default tensor type (see :func:`torch.set_default_tensor_type`). :attr:`device` will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: ``False``. """) add_docstr(torch.abs, r""" abs(input, out=None) -> Tensor Computes the element-wise absolute value of the given :attr:`input` tensor. .. math:: \text{out}_{i} = |\text{input}_{i}| Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.abs(torch.tensor([-1, -2, 3])) tensor([ 1, 2, 3]) """) add_docstr(torch.acos, r""" acos(input, out=None) -> Tensor Returns a new tensor with the arccosine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \cos^{-1}(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.3348, -0.5889, 0.2005, -0.1584]) >>> torch.acos(a) tensor([ 1.2294, 2.2004, 1.3690, 1.7298]) """) add_docstr(torch.add, r""" .. function:: add(input, value, out=None) Adds the scalar :attr:`value` to each element of the input :attr:`input` and returns a new resulting tensor. .. math:: \text{out} = \text{input} + \text{value} If :attr:`input` is of type FloatTensor or DoubleTensor, :attr:`value` must be a real number, otherwise it should be an integer. Args: input (Tensor): the input tensor value (Number): the number to be added to each element of :attr:`input` Keyword arguments: out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.0202, 1.0985, 1.3506, -0.6056]) >>> torch.add(a, 20) tensor([ 20.0202, 21.0985, 21.3506, 19.3944]) .. function:: add(input, value=1, other, out=None) Each element of the tensor :attr:`other` is multiplied by the scalar :attr:`value` and added to each element of the tensor :attr:`input`. The resulting tensor is returned. The shapes of :attr:`input` and :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`. .. math:: \text{out} = \text{input} + \text{value} \times \text{other} If :attr:`other` is of type FloatTensor or DoubleTensor, :attr:`value` must be a real number, otherwise it should be an integer. Args: input (Tensor): the first input tensor value (Number): the scalar multiplier for :attr:`other` other (Tensor): the second input tensor Keyword arguments: out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.9732, -0.3497, 0.6245, 0.4022]) >>> b = torch.randn(4, 1) >>> b tensor([[ 0.3743], [-1.7724], [-0.5811], [-0.8017]]) >>> torch.add(a, 10, b) tensor([[ 2.7695, 3.3930, 4.3672, 4.1450], [-18.6971, -18.0736, -17.0994, -17.3216], [ -6.7845, -6.1610, -5.1868, -5.4090], [ -8.9902, -8.3667, -7.3925, -7.6147]]) """) add_docstr(torch.addbmm, r""" addbmm(beta=1, mat, alpha=1, batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices stored in :attr:`batch1` and :attr:`batch2`, with a reduced add step (all matrix multiplications get accumulated along the first dimension). :attr:`mat` is added to the final result. :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same number of matrices. If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a :math:`(b \times m \times p)` tensor, :attr:`mat` must be :ref:`broadcastable <broadcasting-semantics>` with a :math:`(n \times p)` tensor and :attr:`out` will be a :math:`(n \times p)` tensor. .. math:: out = \beta\ \text{mat} + \alpha\ (\sum_{i=0}^{b} \text{batch1}_i \mathbin{@} \text{batch2}_i) For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers. Args: beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) mat (Tensor): matrix to be added alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`) batch1 (Tensor): the first batch of matrices to be multiplied batch2 (Tensor): the second batch of matrices to be multiplied out (Tensor, optional): the output tensor Example:: >>> M = torch.randn(3, 5) >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> torch.addbmm(M, batch1, batch2) tensor([[ 6.6311, 0.0503, 6.9768, -12.0362, -2.1653], [ -4.8185, -1.4255, -6.6760, 8.9453, 2.5743], [ -3.8202, 4.3691, 1.0943, -1.1109, 5.4730]]) """) add_docstr(torch.addcdiv, r""" addcdiv(tensor, value=1, tensor1, tensor2, out=None) -> Tensor Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, multiply the result by the scalar :attr:`value` and add it to :attr:`tensor`. .. math:: \text{out}_i = \text{tensor}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i} The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be :ref:`broadcastable <broadcasting-semantics>`. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be a real number, otherwise an integer. Args: tensor (Tensor): the tensor to be added value (Number, optional): multiplier for :math:`\text{tensor1} / \text{tensor2}` tensor1 (Tensor): the numerator tensor tensor2 (Tensor): the denominator tensor out (Tensor, optional): the output tensor Example:: >>> t = torch.randn(1, 3) >>> t1 = torch.randn(3, 1) >>> t2 = torch.randn(1, 3) >>> torch.addcdiv(t, 0.1, t1, t2) tensor([[-0.2312, -3.6496, 0.1312], [-1.0428, 3.4292, -0.1030], [-0.5369, -0.9829, 0.0430]]) """) add_docstr(torch.addcmul, r""" addcmul(tensor, value=1, tensor1, tensor2, out=None) -> Tensor Performs the element-wise multiplication of :attr:`tensor1` by :attr:`tensor2`, multiply the result by the scalar :attr:`value` and add it to :attr:`tensor`. .. math:: \text{out}_i = \text{tensor}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i The shapes of :attr:`tensor`, :attr:`tensor1`, and :attr:`tensor2` must be :ref:`broadcastable <broadcasting-semantics>`. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be a real number, otherwise an integer. Args: tensor (Tensor): the tensor to be added value (Number, optional): multiplier for :math:`tensor1 .* tensor2` tensor1 (Tensor): the tensor to be multiplied tensor2 (Tensor): the tensor to be multiplied out (Tensor, optional): the output tensor Example:: >>> t = torch.randn(1, 3) >>> t1 = torch.randn(3, 1) >>> t2 = torch.randn(1, 3) >>> torch.addcmul(t, 0.1, t1, t2) tensor([[-0.8635, -0.6391, 1.6174], [-0.7617, -0.5879, 1.7388], [-0.8353, -0.6249, 1.6511]]) """) add_docstr(torch.addmm, r""" addmm(beta=1, mat, alpha=1, mat1, mat2, out=None) -> Tensor Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. The matrix :attr:`mat` is added to the final result. If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a :math:`(m \times p)` tensor, then :attr:`mat` must be :ref:`broadcastable <broadcasting-semantics>` with a :math:`(n \times p)` tensor and :attr:`out` will be a :math:`(n \times p)` tensor. :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between :attr:`mat1` and :attr`mat2` and the added matrix :attr:`mat` respectively. .. math:: \text{out} = \beta\ \text{mat} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i) For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers. Args: beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) mat (Tensor): matrix to be added alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`) mat1 (Tensor): the first matrix to be multiplied mat2 (Tensor): the second matrix to be multiplied out (Tensor, optional): the output tensor Example:: >>> M = torch.randn(2, 3) >>> mat1 = torch.randn(2, 3) >>> mat2 = torch.randn(3, 3) >>> torch.addmm(M, mat1, mat2) tensor([[-4.8716, 1.4671, -1.3746], [ 0.7573, -3.9555, -2.8681]]) """) add_docstr(torch.addmv, r""" addmv(beta=1, tensor, alpha=1, mat, vec, out=None) -> Tensor Performs a matrix-vector product of the matrix :attr:`mat` and the vector :attr:`vec`. The vector :attr:`tensor` is added to the final result. If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of size `m`, then :attr:`tensor` must be :ref:`broadcastable <broadcasting-semantics>` with a 1-D tensor of size `n` and :attr:`out` will be 1-D tensor of size `n`. :attr:`alpha` and :attr:`beta` are scaling factors on matrix-vector product between :attr:`mat` and :attr:`vec` and the added tensor :attr:`tensor` respectively. .. math:: \text{out} = \beta\ \text{tensor} + \alpha\ (\text{mat} \mathbin{@} \text{vec}) For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`tensor` (:math:`\beta`) tensor (Tensor): vector to be added alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`) mat (Tensor): matrix to be multiplied vec (Tensor): vector to be multiplied out (Tensor, optional): the output tensor Example:: >>> M = torch.randn(2) >>> mat = torch.randn(2, 3) >>> vec = torch.randn(3) >>> torch.addmv(M, mat, vec) tensor([-0.3768, -5.5565]) """) add_docstr(torch.addr, r""" addr(beta=1, mat, alpha=1, vec1, vec2, out=None) -> Tensor Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` and adds it to the matrix :attr:`mat`. Optional values :attr:`beta` and :attr:`alpha` are scaling factors on the outer product between :attr:`vec1` and :attr:`vec2` and the added matrix :attr:`mat` respectively. .. math:: \text{out} = \beta\ \text{mat} + \alpha\ (\text{vec1} \otimes \text{vec2}) If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector of size `m`, then :attr:`mat` must be :ref:`broadcastable <broadcasting-semantics>` with a matrix of size :math:`(n \times m)` and :attr:`out` will be a matrix of size :math:`(n \times m)`. For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) mat (Tensor): matrix to be added alpha (Number, optional): multiplier for :math:`\text{vec1} \otimes \text{vec2}` (:math:`\alpha`) vec1 (Tensor): the first vector of the outer product vec2 (Tensor): the second vector of the outer product out (Tensor, optional): the output tensor Example:: >>> vec1 = torch.arange(1., 4.) >>> vec2 = torch.arange(1., 3.) >>> M = torch.zeros(3, 2) >>> torch.addr(M, vec1, vec2) tensor([[ 1., 2.], [ 2., 4.], [ 3., 6.]]) """) add_docstr(torch.allclose, r""" allclose(self, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> bool This function checks if all :attr:`self` and :attr:`other` satisfy the condition: .. math:: \lvert \text{self} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert elementwise, for all elements of :attr:`self` and :attr:`other`. The behaviour of this function is analogous to `numpy.allclose <https://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html>`_ Args: self (Tensor): first tensor to compare other (Tensor): second tensor to compare atol (float, optional): absolute tolerance. Default: 1e-08 rtol (float, optional): relative tolerance. Default: 1e-05 equal_nan (float, optional): if ``True``, then two ``NaN`` s will be compared as equal. Default: ``False`` Example:: >>> torch.allclose(torch.tensor([10000., 1e-07]), torch.tensor([10000.1, 1e-08])) False >>> torch.allclose(torch.tensor([10000., 1e-08]), torch.tensor([10000.1, 1e-09])) True >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')])) False >>> torch.allclose(torch.tensor([1.0, float('nan')]), torch.tensor([1.0, float('nan')]), equal_nan=True) True """) add_docstr(torch.as_tensor, r""" as_tensor(data, dtype=None, device=None) -> Tensor Convert the data into a `torch.Tensor`. If the data is already a `Tensor` with the same `dtype` and `device`, no copy will be performed, otherwise a new `Tensor` will be returned with computational graph retained if data `Tensor` has ``requires_grad=True``. Similarly, if the data is an ``ndarray`` of the corresponding `dtype` and the `device` is the cpu, no copy will be performed. Args: {data} {dtype} {device} Example:: >>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) >>> a = numpy.array([1, 2, 3]) >>> t = torch.as_tensor(a, device=torch.device('cuda')) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([1, 2, 3]) """.format(**factory_data_common_args)) add_docstr(torch.asin, r""" asin(input, out=None) -> Tensor Returns a new tensor with the arcsine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \sin^{-1}(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.5962, 1.4985, -0.4396, 1.4525]) >>> torch.asin(a) tensor([-0.6387, nan, -0.4552, nan]) """) add_docstr(torch.atan, r""" atan(input, out=None) -> Tensor Returns a new tensor with the arctangent of the elements of :attr:`input`. .. math:: \text{out}_{i} = \tan^{-1}(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.2341, 0.2539, -0.6256, -0.6448]) >>> torch.atan(a) tensor([ 0.2299, 0.2487, -0.5591, -0.5727]) """) add_docstr(torch.atan2, r""" atan2(input1, input2, out=None) -> Tensor Returns a new tensor with the arctangent of the elements of :attr:`input1` and :attr:`input2`. The shapes of :attr:`input1` and :attr:`input2` must be :ref:`broadcastable <broadcasting-semantics>`. Args: input1 (Tensor): the first input tensor input2 (Tensor): the second input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.9041, 0.0196, -0.3108, -2.4423]) >>> torch.atan2(a, torch.randn(4)) tensor([ 0.9833, 0.0811, -1.9743, -1.4151]) """) add_docstr(torch.baddbmm, r""" baddbmm(beta=1, mat, alpha=1, batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices in :attr:`batch1` and :attr:`batch2`. :attr:`mat` is added to the final result. :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same number of matrices. If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a :math:`(b \times m \times p)` tensor, then :attr:`mat` must be :ref:`broadcastable <broadcasting-semantics>` with a :math:`(b \times n \times p)` tensor and :attr:`out` will be a :math:`(b \times n \times p)` tensor. Both :attr:`alpha` and :attr:`beta` mean the same as the scaling factors used in :meth:`torch.addbmm`. .. math:: \text{out}_i = \beta\ \text{mat}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i) For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers. Args: beta (Number, optional): multiplier for :attr:`mat` (:math:`\beta`) mat (Tensor): the tensor to be added alpha (Number, optional): multiplier for :math:`\text{batch1} \mathbin{@} \text{batch2}` (:math:`\alpha`) batch1 (Tensor): the first batch of matrices to be multiplied batch2 (Tensor): the second batch of matrices to be multiplied out (Tensor, optional): the output tensor Example:: >>> M = torch.randn(10, 3, 5) >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> torch.baddbmm(M, batch1, batch2).size() torch.Size([10, 3, 5]) """) add_docstr(torch.bernoulli, r""" bernoulli(input, *, generator=None, out=None) -> Tensor Draws binary random numbers (0 or 1) from a Bernoulli distribution. The :attr:`input` tensor should be a tensor containing probabilities to be used for drawing the binary random number. Hence, all values in :attr:`input` have to be in the range: :math:`0 \leq \text{input}_i \leq 1`. The :math:`\text{i}^{th}` element of the output tensor will draw a value :math:`1` according to the :math:`\text{i}^{th}` probability value given in :attr:`input`. .. math:: \text{out}_{i} \sim \mathrm{Bernoulli}(p = \text{input}_{i}) The returned :attr:`out` tensor only has values 0 or 1 and is of the same shape as :attr:`input`. :attr:`out` can have integral ``dtype``, but :attr`input` must have floating point ``dtype``. Args: input (Tensor): the input tensor of probability values for the Bernoulli distribution out (Tensor, optional): the output tensor Example:: >>> a = torch.empty(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] >>> a tensor([[ 0.1737, 0.0950, 0.3609], [ 0.7148, 0.0289, 0.2676], [ 0.9456, 0.8937, 0.7202]]) >>> torch.bernoulli(a) tensor([[ 1., 0., 0.], [ 0., 0., 0.], [ 1., 1., 1.]]) >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 >>> torch.bernoulli(a) tensor([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]]) >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 >>> torch.bernoulli(a) tensor([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]]) """) add_docstr(torch.bincount, r""" bincount(self, weights=None, minlength=0) -> Tensor Count the frequency of each value in an array of non-negative ints. The number of bins (size 1) is one larger than the largest value in :attr:`input` unless :attr:`input` is empty, in which case the result is a tensor of size 0. If :attr:`minlength` is specified, the number of bins is at least :attr:`minlength` and if :attr:`input` is empty, then the result is tensor of size :attr:`minlength` filled with zeros. If ``n`` is the value at position ``i``, ``out[n] += weights[i]`` if :attr:`weights` is specified else ``out[n] += 1``. .. include:: cuda_deterministic.rst Arguments: input (Tensor): 1-d int tensor weights (Tensor): optional, weight for each value in the input tensor. Should be of same size as input tensor. minlength (int): optional, minimum number of bins. Should be non-negative. Returns: output (Tensor): a tensor of shape ``Size([max(input) + 1])`` if :attr:`input` is non-empty, else ``Size(0)`` Example:: >>> input = torch.randint(0, 8, (5,), dtype=torch.int64) >>> weights = torch.linspace(0, 1, steps=5) >>> input, weights (tensor([4, 3, 6, 3, 4]), tensor([ 0.0000, 0.2500, 0.5000, 0.7500, 1.0000]) >>> torch.bincount(input) tensor([0, 0, 0, 2, 2, 0, 1]) >>> input.bincount(weights) tensor([0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 0.0000, 0.5000]) """) add_docstr(torch.bmm, r""" bmm(batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices stored in :attr:`batch1` and :attr:`batch2`. :attr:`batch1` and :attr:`batch2` must be 3-D tensors each containing the same number of matrices. If :attr:`batch1` is a :math:`(b \times n \times m)` tensor, :attr:`batch2` is a :math:`(b \times m \times p)` tensor, :attr:`out` will be a :math:`(b \times n \times p)` tensor. .. math:: \text{out}_i = \text{batch1}_i \mathbin{@} \text{batch2}_i .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`. For broadcasting matrix products, see :func:`torch.matmul`. Args: batch1 (Tensor): the first batch of matrices to be multiplied batch2 (Tensor): the second batch of matrices to be multiplied out (Tensor, optional): the output tensor Example:: >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> res = torch.bmm(batch1, batch2) >>> res.size() torch.Size([10, 3, 5]) """) add_docstr(torch.stack, r""" stack(seq, dim=0, out=None) -> Tensor Concatenates sequence of tensors along a new dimension. All tensors need to be of the same size. Arguments: seq (sequence of Tensors): sequence of tensors to concatenate dim (int): dimension to insert. Has to be between 0 and the number of dimensions of concatenated tensors (inclusive) out (Tensor, optional): the output tensor """) add_docstr(torch.chunk, r""" chunk(tensor, chunks, dim=0) -> List of Tensors Splits a tensor into a specific number of chunks. Last chunk will be smaller if the tensor size along the given dimension :attr:`dim` is not divisible by :attr:`chunks`. Arguments: tensor (Tensor): the tensor to split chunks (int): number of chunks to return dim (int): dimension along which to split the tensor """) add_docstr(torch.cat, r""" cat(tensors, dim=0, out=None) -> Tensor Concatenates the given sequence of :attr:`seq` tensors in the given dimension. All tensors must either have the same shape (except in the concatenating dimension) or be empty. :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` and :func:`torch.chunk`. :func:`torch.cat` can be best understood via examples. Args: tensors (sequence of Tensors): any python sequence of tensors of the same type. Non-empty tensors provided must have the same shape, except in the cat dimension. dim (int, optional): the dimension over which the tensors are concatenated out (Tensor, optional): the output tensor Example:: >>> x = torch.randn(2, 3) >>> x tensor([[ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497]]) >>> torch.cat((x, x, x), 0) tensor([[ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497], [ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497], [ 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497]]) >>> torch.cat((x, x, x), 1) tensor([[ 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614, 0.6580, -1.0969, -0.4614], [-0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497, -0.1034, -0.5790, 0.1497]]) """) add_docstr(torch.ceil, r""" ceil(input, out=None) -> Tensor Returns a new tensor with the ceil of the elements of :attr:`input`, the smallest integer greater than or equal to each element. .. math:: \text{out}_{i} = \left\lceil \text{input}_{i} \right\rceil = \left\lfloor \text{input}_{i} \right\rfloor + 1 Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.6341, -1.4208, -1.0900, 0.5826]) >>> torch.ceil(a) tensor([-0., -1., -1., 1.]) """) add_docstr(torch.reciprocal, r""" reciprocal(input, out=None) -> Tensor Returns a new tensor with the reciprocal of the elements of :attr:`input` .. math:: \text{out}_{i} = \frac{1}{\text{input}_{i}} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.4595, -2.1219, -1.4314, 0.7298]) >>> torch.reciprocal(a) tensor([-2.1763, -0.4713, -0.6986, 1.3702]) """) add_docstr(torch.cholesky, r""" cholesky(A, upper=False, out=None) -> Tensor Computes the Cholesky decomposition of a symmetric positive-definite matrix :math:`A` or for batches of symmetric positive-definite matrices. If :attr:`upper` is ``True``, the returned matrix `U` is upper-triangular, and the decomposition has the form: .. math:: A = U^TU If :attr:`upper` is ``False``, the returned matrix `L` is lower-triangular, and the decomposition has the form: .. math:: A = LL^T If :attr:`upper` is ``True``, and :attr:`A` is a batch of symmetric positive-definite matrices, then the returned tensor will be composed of upper-triangular Cholesky factors of each of the individual matrices. Similarly, when :attr:`upper` is ``False``, the returned tensor will be composed of lower-triangular Cholesky factors of each of the individual matrices. Args: a (Tensor): the input tensor of size (*, n, n) where `*` is zero or more batch dimensions consisting of symmetric positive-definite matrices. upper (bool, optional): flag that indicates whether to return a upper or lower triangular matrix. Default: ``False`` out (Tensor, optional): the output matrix Example:: >>> a = torch.randn(3, 3) >>> a = torch.mm(a, a.t()) # make symmetric positive-definite >>> l = torch.cholesky(a) >>> a tensor([[ 2.4112, -0.7486, 1.4551], [-0.7486, 1.3544, 0.1294], [ 1.4551, 0.1294, 1.6724]]) >>> l tensor([[ 1.5528, 0.0000, 0.0000], [-0.4821, 1.0592, 0.0000], [ 0.9371, 0.5487, 0.7023]]) >>> torch.mm(l, l.t()) tensor([[ 2.4112, -0.7486, 1.4551], [-0.7486, 1.3544, 0.1294], [ 1.4551, 0.1294, 1.6724]]) >>> a = torch.randn(3, 2, 2) >>> a = torch.matmul(a, a.transpose(-1, -2)) + 1e-03 # make symmetric positive-definite >>> l = torch.cholesky(a) >>> z = torch.matmul(l, l.transpose(-1, -2)) >>> torch.max(torch.abs(z - a)) # Max non-zero tensor(2.3842e-07) """) add_docstr(torch.clamp, r""" clamp(input, min, max, out=None) -> Tensor Clamp all elements in :attr:`input` into the range `[` :attr:`min`, :attr:`max` `]` and return a resulting tensor: .. math:: y_i = \begin{cases} \text{min} & \text{if } x_i < \text{min} \\ x_i & \text{if } \text{min} \leq x_i \leq \text{max} \\ \text{max} & \text{if } x_i > \text{max} \end{cases} If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, args :attr:`min` and :attr:`max` must be real numbers, otherwise they should be integers. Args: input (Tensor): the input tensor min (Number): lower-bound of the range to be clamped to max (Number): upper-bound of the range to be clamped to out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-1.7120, 0.1734, -0.0478, -0.0922]) >>> torch.clamp(a, min=-0.5, max=0.5) tensor([-0.5000, 0.1734, -0.0478, -0.0922]) .. function:: clamp(input, *, min, out=None) -> Tensor Clamps all elements in :attr:`input` to be larger or equal :attr:`min`. If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer. Args: input (Tensor): the input tensor value (Number): minimal value of each element in the output out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.0299, -2.3184, 2.1593, -0.8883]) >>> torch.clamp(a, min=0.5) tensor([ 0.5000, 0.5000, 2.1593, 0.5000]) .. function:: clamp(input, *, max, out=None) -> Tensor Clamps all elements in :attr:`input` to be smaller or equal :attr:`max`. If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer. Args: input (Tensor): the input tensor value (Number): maximal value of each element in the output out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.7753, -0.4702, -0.4599, 1.1899]) >>> torch.clamp(a, max=0.5) tensor([ 0.5000, -0.4702, -0.4599, 0.5000]) """) add_docstr(torch.cos, r""" cos(input, out=None) -> Tensor Returns a new tensor with the cosine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \cos(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 1.4309, 1.2706, -0.8562, 0.9796]) >>> torch.cos(a) tensor([ 0.1395, 0.2957, 0.6553, 0.5574]) """) add_docstr(torch.cosh, r""" cosh(input, out=None) -> Tensor Returns a new tensor with the hyperbolic cosine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \cosh(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.1632, 1.1835, -0.6979, -0.7325]) >>> torch.cosh(a) tensor([ 1.0133, 1.7860, 1.2536, 1.2805]) """) add_docstr(torch.cross, r""" cross(input, other, dim=-1, out=None) -> Tensor Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` and :attr:`other`. :attr:`input` and :attr:`other` must have the same size, and the size of their :attr:`dim` dimension should be 3. If :attr:`dim` is not given, it defaults to the first dimension found with the size 3. Args: input (Tensor): the input tensor other (Tensor): the second input tensor dim (int, optional): the dimension to take the cross-product in. out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 3) >>> a tensor([[-0.3956, 1.1455, 1.6895], [-0.5849, 1.3672, 0.3599], [-1.1626, 0.7180, -0.0521], [-0.1339, 0.9902, -2.0225]]) >>> b = torch.randn(4, 3) >>> b tensor([[-0.0257, -1.4725, -1.2251], [-1.1479, -0.7005, -1.9757], [-1.3904, 0.3726, -1.1836], [-0.9688, -0.7153, 0.2159]]) >>> torch.cross(a, b, dim=1) tensor([[ 1.0844, -0.5281, 0.6120], [-2.4490, -1.5687, 1.9792], [-0.8304, -1.3037, 0.5650], [-1.2329, 1.9883, 1.0551]]) >>> torch.cross(a, b) tensor([[ 1.0844, -0.5281, 0.6120], [-2.4490, -1.5687, 1.9792], [-0.8304, -1.3037, 0.5650], [-1.2329, 1.9883, 1.0551]]) """) add_docstr(torch.cumprod, r""" cumprod(input, dim, dtype=None) -> Tensor Returns the cumulative product of elements of :attr:`input` in the dimension :attr:`dim`. For example, if :attr:`input` is a vector of size N, the result will also be a vector of size N, with elements. .. math:: y_i = x_1 \times x_2\times x_3\times \dots \times x_i Args: input (Tensor): the input tensor dim (int): the dimension to do the operation over {dtype} Example:: >>> a = torch.randn(10) >>> a tensor([ 0.6001, 0.2069, -0.1919, 0.9792, 0.6727, 1.0062, 0.4126, -0.2129, -0.4206, 0.1968]) >>> torch.cumprod(a, dim=0) tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0158, -0.0065, 0.0014, -0.0006, -0.0001]) >>> a[5] = 0.0 >>> torch.cumprod(a, dim=0) tensor([ 0.6001, 0.1241, -0.0238, -0.0233, -0.0157, -0.0000, -0.0000, 0.0000, -0.0000, -0.0000]) """.format(**reduceops_common_args)) add_docstr(torch.cumsum, r""" cumsum(input, dim, out=None, dtype=None) -> Tensor Returns the cumulative sum of elements of :attr:`input` in the dimension :attr:`dim`. For example, if :attr:`input` is a vector of size N, the result will also be a vector of size N, with elements. .. math:: y_i = x_1 + x_2 + x_3 + \dots + x_i Args: input (Tensor): the input tensor dim (int): the dimension to do the operation over {dtype} Example:: >>> a = torch.randn(10) >>> a tensor([-0.8286, -0.4890, 0.5155, 0.8443, 0.1865, -0.1752, -2.0595, 0.1850, -1.1571, -0.4243]) >>> torch.cumsum(a, dim=0) tensor([-0.8286, -1.3175, -0.8020, 0.0423, 0.2289, 0.0537, -2.0058, -1.8209, -2.9780, -3.4022]) """.format(**reduceops_common_args)) add_docstr(torch.diag, r""" diag(input, diagonal=0, out=None) -> Tensor - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor with the elements of :attr:`input` as the diagonal. - If :attr:`input` is a matrix (2-D tensor), then returns a 1-D tensor with the diagonal elements of :attr:`input`. The argument :attr:`diagonal` controls which diagonal to consider: - If :attr:`diagonal` = 0, it is the main diagonal. - If :attr:`diagonal` > 0, it is above the main diagonal. - If :attr:`diagonal` < 0, it is below the main diagonal. Args: input (Tensor): the input tensor diagonal (int, optional): the diagonal to consider out (Tensor, optional): the output tensor .. seealso:: :func:`torch.diagonal` always returns the diagonal of its input. :func:`torch.diagflat` always constructs a tensor with diagonal elements specified by the input. Examples: Get the square matrix where the input vector is the diagonal:: >>> a = torch.randn(3) >>> a tensor([ 0.5950,-0.0872, 2.3298]) >>> torch.diag(a) tensor([[ 0.5950, 0.0000, 0.0000], [ 0.0000,-0.0872, 0.0000], [ 0.0000, 0.0000, 2.3298]]) >>> torch.diag(a, 1) tensor([[ 0.0000, 0.5950, 0.0000, 0.0000], [ 0.0000, 0.0000,-0.0872, 0.0000], [ 0.0000, 0.0000, 0.0000, 2.3298], [ 0.0000, 0.0000, 0.0000, 0.0000]]) Get the k-th diagonal of a given matrix:: >>> a = torch.randn(3, 3) >>> a tensor([[-0.4264, 0.0255,-0.1064], [ 0.8795,-0.2429, 0.1374], [ 0.1029,-0.6482,-1.6300]]) >>> torch.diag(a, 0) tensor([-0.4264,-0.2429,-1.6300]) >>> torch.diag(a, 1) tensor([ 0.0255, 0.1374]) """) add_docstr(torch.diag_embed, r""" diag_embed(input, offset=0, dim1=-2, dim2=-1) -> Tensor Creates a tensor whose diagonals of certain 2D planes (specified by :attr:`dim1` and :attr:`dim2`) are filled by :attr:`input`. To facilitate creating batched diagonal matrices, the 2D planes formed by the last two dimensions of the returned tensor are chosen by default. The argument :attr:`offset` controls which diagonal to consider: - If :attr:`offset` = 0, it is the main diagonal. - If :attr:`offset` > 0, it is above the main diagonal. - If :attr:`offset` < 0, it is below the main diagonal. The size of the new matrix will be calculated to make the specified diagonal of the size of the last input dimension. Note that for :attr:`offset` other than :math:`0`, the order of :attr:`dim1` and :attr:`dim2` matters. Exchanging them is equivalent to changing the sign of :attr:`offset`. Applying :meth:`torch.diagonal` to the output of this function with the same arguments yields a matrix identical to input. However, :meth:`torch.diagonal` has different default dimensions, so those need to be explicitly specified. Args: input (Tensor): the input tensor. Must be at least 1-dimensional. offset (int, optional): which diagonal to consider. Default: 0 (main diagonal). dim1 (int, optional): first dimension with respect to which to take diagonal. Default: -2. dim2 (int, optional): second dimension with respect to which to take diagonal. Default: -1. Example:: >>> a = torch.randn(2, 3) >>> torch.diag_embed(a) tensor([[[ 1.5410, 0.0000, 0.0000], [ 0.0000, -0.2934, 0.0000], [ 0.0000, 0.0000, -2.1788]], [[ 0.5684, 0.0000, 0.0000], [ 0.0000, -1.0845, 0.0000], [ 0.0000, 0.0000, -1.3986]]]) >>> torch.diag_embed(a, offset=1, dim1=0, dim2=2) tensor([[[ 0.0000, 1.5410, 0.0000, 0.0000], [ 0.0000, 0.5684, 0.0000, 0.0000]], [[ 0.0000, 0.0000, -0.2934, 0.0000], [ 0.0000, 0.0000, -1.0845, 0.0000]], [[ 0.0000, 0.0000, 0.0000, -2.1788], [ 0.0000, 0.0000, 0.0000, -1.3986]], [[ 0.0000, 0.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000, 0.0000]]]) """) add_docstr(torch.diagflat, r""" diagflat(input, diagonal=0) -> Tensor - If :attr:`input` is a vector (1-D tensor), then returns a 2-D square tensor with the elements of :attr:`input` as the diagonal. - If :attr:`input` is a tensor with more than one dimension, then returns a 2-D tensor with diagonal elements equal to a flattened :attr:`input`. The argument :attr:`offset` controls which diagonal to consider: - If :attr:`offset` = 0, it is the main diagonal. - If :attr:`offset` > 0, it is above the main diagonal. - If :attr:`offset` < 0, it is below the main diagonal. Args: input (Tensor): the input tensor offset (int, optional): the diagonal to consider. Default: 0 (main diagonal). Examples:: >>> a = torch.randn(3) >>> a tensor([-0.2956, -0.9068, 0.1695]) >>> torch.diagflat(a) tensor([[-0.2956, 0.0000, 0.0000], [ 0.0000, -0.9068, 0.0000], [ 0.0000, 0.0000, 0.1695]]) >>> torch.diagflat(a, 1) tensor([[ 0.0000, -0.2956, 0.0000, 0.0000], [ 0.0000, 0.0000, -0.9068, 0.0000], [ 0.0000, 0.0000, 0.0000, 0.1695], [ 0.0000, 0.0000, 0.0000, 0.0000]]) >>> a = torch.randn(2, 2) >>> a tensor([[ 0.2094, -0.3018], [-0.1516, 1.9342]]) >>> torch.diagflat(a) tensor([[ 0.2094, 0.0000, 0.0000, 0.0000], [ 0.0000, -0.3018, 0.0000, 0.0000], [ 0.0000, 0.0000, -0.1516, 0.0000], [ 0.0000, 0.0000, 0.0000, 1.9342]]) """) add_docstr(torch.diagonal, r""" diagonal(input, offset=0, dim1=0, dim2=1) -> Tensor Returns a partial view of :attr:`input` with the its diagonal elements with respect to :attr:`dim1` and :attr:`dim2` appended as a dimension at the end of the shape. The argument :attr:`offset` controls which diagonal to consider: - If :attr:`offset` = 0, it is the main diagonal. - If :attr:`offset` > 0, it is above the main diagonal. - If :attr:`offset` < 0, it is below the main diagonal. Applying :meth:`torch.diag_embed` to the output of this function with the same arguments yields a diagonal matrix with the diagonal entries of the input. However, :meth:`torch.diag_embed` has different default dimensions, so those need to be explicitly specified. Args: input (Tensor): the input tensor. Must be at least 2-dimensional. offset (int, optional): which diagonal to consider. Default: 0 (main diagonal). dim1 (int, optional): first dimension with respect to which to take diagonal. Default: 0. dim2 (int, optional): second dimension with respect to which to take diagonal. Default: 1. .. note:: To take a batch diagonal, pass in dim1=-2, dim2=-1. Examples:: >>> a = torch.randn(3, 3) >>> a tensor([[-1.0854, 1.1431, -0.1752], [ 0.8536, -0.0905, 0.0360], [ 0.6927, -0.3735, -0.4945]]) >>> torch.diagonal(a, 0) tensor([-1.0854, -0.0905, -0.4945]) >>> torch.diagonal(a, 1) tensor([ 1.1431, 0.0360]) >>> x = torch.randn(2, 5, 4, 2) >>> torch.diagonal(x, offset=-1, dim1=1, dim2=2) tensor([[[-1.2631, 0.3755, -1.5977, -1.8172], [-1.1065, 1.0401, -0.2235, -0.7938]], [[-1.7325, -0.3081, 0.6166, 0.2335], [ 1.0500, 0.7336, -0.3836, -1.1015]]]) """) add_docstr(torch.digamma, r""" digamma(input, out=None) -> Tensor Computes the logarithmic derivative of the gamma function on `input`. .. math:: \psi(x) = \frac{d}{dx} \ln\left(\Gamma\left(x\right)\right) = \frac{\Gamma'(x)}{\Gamma(x)} Args: input (Tensor): the tensor to compute the digamma function on Example:: >>> a = torch.tensor([1, 0.5]) >>> torch.digamma(a) tensor([-0.5772, -1.9635]) """) add_docstr(torch.dist, r""" dist(input, other, p=2) -> Tensor Returns the p-norm of (:attr:`input` - :attr:`other`) The shapes of :attr:`input` and :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`. Args: input (Tensor): the input tensor other (Tensor): the Right-hand-side input tensor p (float, optional): the norm to be computed Example:: >>> x = torch.randn(4) >>> x tensor([-1.5393, -0.8675, 0.5916, 1.6321]) >>> y = torch.randn(4) >>> y tensor([ 0.0967, -1.0511, 0.6295, 0.8360]) >>> torch.dist(x, y, 3.5) tensor(1.6727) >>> torch.dist(x, y, 3) tensor(1.6973) >>> torch.dist(x, y, 0) tensor(inf) >>> torch.dist(x, y, 1) tensor(2.6537) """) add_docstr(torch.div, r""" .. function:: div(input, value, out=None) -> Tensor Divides each element of the input :attr:`input` with the scalar :attr:`value` and returns a new resulting tensor. .. math:: \text{out}_i = \frac{\text{input}_i}{\text{value}} If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input tensor value (Number): the number to be divided to each element of :attr:`input` out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(5) >>> a tensor([ 0.3810, 1.2774, -0.2972, -0.3719, 0.4637]) >>> torch.div(a, 0.5) tensor([ 0.7620, 2.5548, -0.5944, -0.7439, 0.9275]) .. function:: div(input, other, out=None) -> Tensor Each element of the tensor :attr:`input` is divided by each element of the tensor :attr:`other`. The resulting tensor is returned. The shapes of :attr:`input` and :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`. .. math:: \text{out}_i = \frac{\text{input}_i}{\text{other}_i} Args: input (Tensor): the numerator tensor other (Tensor): the denominator tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 4) >>> a tensor([[-0.3711, -1.9353, -0.4605, -0.2917], [ 0.1815, -1.0111, 0.9805, -1.5923], [ 0.1062, 1.4581, 0.7759, -1.2344], [-0.1830, -0.0313, 1.1908, -1.4757]]) >>> b = torch.randn(4) >>> b tensor([ 0.8032, 0.2930, -0.8113, -0.2308]) >>> torch.div(a, b) tensor([[-0.4620, -6.6051, 0.5676, 1.2637], [ 0.2260, -3.4507, -1.2086, 6.8988], [ 0.1322, 4.9764, -0.9564, 5.3480], [-0.2278, -0.1068, -1.4678, 6.3936]]) """) add_docstr(torch.dot, r""" dot(tensor1, tensor2) -> Tensor Computes the dot product (inner product) of two tensors. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`. Example:: >>> torch.dot(torch.tensor([2, 3]), torch.tensor([2, 1])) tensor(7) """) add_docstr(torch.eig, r""" eig(a, eigenvectors=False, out=None) -> (Tensor, Tensor) Computes the eigenvalues and eigenvectors of a real square matrix. Args: a (Tensor): the square matrix of shape :math:`(n \times n)` for which the eigenvalues and eigenvectors will be computed eigenvectors (bool): ``True`` to compute both eigenvalues and eigenvectors; otherwise, only eigenvalues will be computed out (tuple, optional): the output tensors Returns: (Tensor, Tensor): A tuple containing - **e** (*Tensor*): Shape :math:`(n \times 2)`. Each row is an eigenvalue of ``a``, where the first element is the real part and the second element is the imaginary part. The eigenvalues are not necessarily ordered. - **v** (*Tensor*): If ``eigenvectors=False``, it's an empty tensor. Otherwise, this tensor of shape :math:`(n \times n)` can be used to compute normalized (unit length) eigenvectors of corresponding eigenvalues ``e`` as follows. If the corresponding e[j] is a real number, column v[:, j] is the eigenvector corresponding to eigenvalue e[j]. If the corresponding e[j] and e[j + 1] eigenvalues form a complex conjugate pair, then the true eigenvectors can be computed as :math:`\text{eigenvector}[j] = v[:, j] + i \times v[:, j + 1]`, :math:`\text{eigenvector}[j + 1] = v[:, j] - i \times v[:, j + 1]`. """) add_docstr(torch.eq, r""" eq(input, other, out=None) -> Tensor Computes element-wise equality The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor. Must be a `ByteTensor` Returns: Tensor: A ``torch.ByteTensor`` containing a 1 at each location where comparison is true Example:: >>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 1, 0], [ 0, 1]], dtype=torch.uint8) """) add_docstr(torch.equal, r""" equal(tensor1, tensor2) -> bool ``True`` if two tensors have the same size and elements, ``False`` otherwise. Example:: >>> torch.equal(torch.tensor([1, 2]), torch.tensor([1, 2])) True """) add_docstr(torch.erf, r""" erf(tensor, out=None) -> Tensor Computes the error function of each element. The error function is defined as follows: .. math:: \mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_{0}^{x} e^{-t^2} dt Args: tensor (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.erf(torch.tensor([0, -1., 10.])) tensor([ 0.0000, -0.8427, 1.0000]) """) add_docstr(torch.erfc, r""" erfc(input, out=None) -> Tensor Computes the complementary error function of each element of :attr:`input`. The complementary error function is defined as follows: .. math:: \mathrm{erfc}(x) = 1 - \frac{2}{\sqrt{\pi}} \int_{0}^{x} e^{-t^2} dt Args: tensor (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.erfc(torch.tensor([0, -1., 10.])) tensor([ 1.0000, 1.8427, 0.0000]) """) add_docstr(torch.erfinv, r""" erfinv(input, out=None) -> Tensor Computes the inverse error function of each element of :attr:`input`. The inverse error function is defined in the range :math:`(-1, 1)` as: .. math:: \mathrm{erfinv}(\mathrm{erf}(x)) = x Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.erfinv(torch.tensor([0, 0.5, -1.])) tensor([ 0.0000, 0.4769, -inf]) """) add_docstr(torch.exp, r""" exp(input, out=None) -> Tensor Returns a new tensor with the exponential of the elements of the input tensor :attr:`input`. .. math:: y_{i} = e^{x_{i}} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.exp(torch.tensor([0, math.log(2.)])) tensor([ 1., 2.]) """) add_docstr(torch.expm1, r""" expm1(input, out=None) -> Tensor Returns a new tensor with the exponential of the elements minus 1 of :attr:`input`. .. math:: y_{i} = e^{x_{i}} - 1 Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> torch.expm1(torch.tensor([0, math.log(2.)])) tensor([ 0., 1.]) """) add_docstr(torch.eye, r""" eye(n, m=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. Args: n (int): the number of rows m (int, optional): the number of columns with default being :attr:`n` {out} {dtype} {layout} {device} {requires_grad} Returns: Tensor: A 2-D tensor with ones on the diagonal and zeros elsewhere Example:: >>> torch.eye(3) tensor([[ 1., 0., 0.], [ 0., 1., 0.], [ 0., 0., 1.]]) """.format(**factory_common_args)) add_docstr(torch.floor, r""" floor(input, out=None) -> Tensor Returns a new tensor with the floor of the elements of :attr:`input`, the largest integer less than or equal to each element. .. math:: \text{out}_{i} = \left\lfloor \text{input}_{i} \right\rfloor Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.8166, 1.5308, -0.2530, -0.2091]) >>> torch.floor(a) tensor([-1., 1., -1., -1.]) """) add_docstr(torch.fmod, r""" fmod(input, divisor, out=None) -> Tensor Computes the element-wise remainder of division. The dividend and divisor may contain both for integer and floating point numbers. The remainder has the same sign as the dividend :attr:`input`. When :attr:`divisor` is a tensor, the shapes of :attr:`input` and :attr:`divisor` must be :ref:`broadcastable <broadcasting-semantics>`. Args: input (Tensor): the dividend divisor (Tensor or float): the divisor, which may be either a number or a tensor of the same shape as the dividend out (Tensor, optional): the output tensor Example:: >>> torch.fmod(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) tensor([-1., -0., -1., 1., 0., 1.]) >>> torch.fmod(torch.tensor([1., 2, 3, 4, 5]), 1.5) tensor([ 1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) """) add_docstr(torch.frac, r""" frac(input, out=None) -> Tensor Computes the fractional portion of each element in :attr:`input`. .. math:: \text{out}_{i} = \text{input}_{i} - \left\lfloor \text{input}_{i} \right\rfloor Example:: >>> torch.frac(torch.tensor([1, 2.5, -3.2])) tensor([ 0.0000, 0.5000, -0.2000]) """) add_docstr(torch.from_numpy, r""" from_numpy(ndarray) -> Tensor Creates a :class:`Tensor` from a :class:`numpy.ndarray`. The returned tensor and :attr:`ndarray` share the same memory. Modifications to the tensor will be reflected in the :attr:`ndarray` and vice versa. The returned tensor is not resizable. Example:: >>> a = numpy.array([1, 2, 3]) >>> t = torch.from_numpy(a) >>> t tensor([ 1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) """) add_docstr(torch.flatten, r""" flatten(input, start_dim=0, end_dim=-1) -> Tensor Flattens a contiguous range of dims in a tensor. Args: input (Tensor): the input tensor start_dim (int): the first dim to flatten end_dim (int): the last dim to flatten Example:: >>> t = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) >>> torch.flatten(t) tensor([1, 2, 3, 4, 5, 6, 7, 8]) >>> torch.flatten(t, start_dim=1) tensor([[1, 2, 3, 4], [5, 6, 7, 8]]) """) add_docstr(torch.gather, r""" gather(input, dim, index, out=None) -> Tensor Gathers values along an axis specified by `dim`. For a 3-D tensor the output is specified by:: out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 If :attr:`input` is an n-dimensional tensor with size :math:`(x_0, x_1..., x_{i-1}, x_i, x_{i+1}, ..., x_{n-1})` and ``dim = i``, then :attr:`index` must be an :math:`n`-dimensional tensor with size :math:`(x_0, x_1, ..., x_{i-1}, y, x_{i+1}, ..., x_{n-1})` where :math:`y \geq 1` and :attr:`out` will have the same size as :attr:`index`. Args: input (Tensor): the source tensor dim (int): the axis along which to index index (LongTensor): the indices of elements to gather out (Tensor, optional): the destination tensor Example:: >>> t = torch.tensor([[1,2],[3,4]]) >>> torch.gather(t, 1, torch.tensor([[0,0],[1,0]])) tensor([[ 1, 1], [ 4, 3]]) """) add_docstr(torch.ge, r""" ge(input, other, out=None) -> Tensor Computes :math:`\text{input} \geq \text{other}` element-wise. The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor that must be a `ByteTensor` Returns: Tensor: A ``torch.ByteTensor`` containing a 1 at each location where comparison is true Example:: >>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 1, 1], [ 0, 1]], dtype=torch.uint8) """) add_docstr(torch.gels, r""" gels(B, A, out=None) -> Tensor Computes the solution to the least squares and least norm problems for a full rank matrix :math:`A` of size :math:`(m \times n)` and a matrix :math:`B` of size :math:`(m \times k)`. If :math:`m \geq n`, :func:`gels` solves the least-squares problem: .. math:: \begin{array}{ll} \min_X & \|AX-B\|_2. \end{array} If :math:`m < n`, :func:`gels` solves the least-norm problem: .. math:: \begin{array}{ll} \min_X & \|X\|_2 & \text{subject to} & AX = B. \end{array} Returned tensor :math:`X` has shape :math:`(\max(m, n) \times k)`. The first :math:`n` rows of :math:`X` contains the solution. If :math:`m \geq n`, the residual sum of squares for the solution in each column is given by the sum of squares of elements in the remaining :math:`m - n` rows of that column. Args: B (Tensor): the matrix :math:`B` A (Tensor): the :math:`m` by :math:`n` matrix :math:`A` out (tuple, optional): the optional destination tensor Returns: (Tensor, Tensor): A tuple containing: - **X** (*Tensor*): the least squares solution - **qr** (*Tensor*): the details of the QR factorization .. note:: The returned matrices will always be transposed, irrespective of the strides of the input matrices. That is, they will have stride `(1, m)` instead of `(m, 1)`. Example:: >>> A = torch.tensor([[1., 1, 1], [2, 3, 4], [3, 5, 2], [4, 2, 5], [5, 4, 3]]) >>> B = torch.tensor([[-10., -3], [ 12, 14], [ 14, 12], [ 16, 16], [ 18, 16]]) >>> X, _ = torch.gels(B, A) >>> X tensor([[ 2.0000, 1.0000], [ 1.0000, 1.0000], [ 1.0000, 2.0000], [ 10.9635, 4.8501], [ 8.9332, 5.2418]]) """) add_docstr(torch.geqrf, r""" geqrf(input, out=None) -> (Tensor, Tensor) This is a low-level function for calling LAPACK directly. You'll generally want to use :func:`torch.qr` instead. Computes a QR decomposition of :attr:`input`, but without constructing :math:`Q` and :math:`R` as explicit separate matrices. Rather, this directly calls the underlying LAPACK function `?geqrf` which produces a sequence of 'elementary reflectors'. See `LAPACK documentation for geqrf`_ for further details. Args: input (Tensor): the input matrix out (tuple, optional): the output tuple of (Tensor, Tensor) .. _LAPACK documentation for geqrf: https://software.intel.com/en-us/node/521004 """) add_docstr(torch.ger, r""" ger(vec1, vec2, out=None) -> Tensor Outer product of :attr:`vec1` and :attr:`vec2`. If :attr:`vec1` is a vector of size :math:`n` and :attr:`vec2` is a vector of size :math:`m`, then :attr:`out` must be a matrix of size :math:`(n \times m)`. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`. Args: vec1 (Tensor): 1-D input vector vec2 (Tensor): 1-D input vector out (Tensor, optional): optional output matrix Example:: >>> v1 = torch.arange(1., 5.) >>> v2 = torch.arange(1., 4.) >>> torch.ger(v1, v2) tensor([[ 1., 2., 3.], [ 2., 4., 6.], [ 3., 6., 9.], [ 4., 8., 12.]]) """) add_docstr(torch.gesv, r""" torch.gesv(B, A) -> (Tensor, Tensor) This function returns the solution to the system of linear equations represented by :math:`AX = B` and the LU factorization of A, in order as a tuple `X, LU`. `LU` contains `L` and `U` factors for LU factorization of `A`. `torch.gesv(B, A)` can take in 2D inputs `B, A` or inputs that are batches of 2D matrices. If the inputs are batches, then returns batched outputs `X, LU`. .. note:: The :attr:`out` keyword only supports 2D matrix inputs, that is, `B, A` must be 2D matrices. .. note:: Irrespective of the original strides, the returned matrices `X` and `LU` will be transposed, i.e. with strides like `B.contiguous().transpose(-1, -2).strides()` and `A.contiguous().transpose(-1, -2).strides()` respectively. Args: B (Tensor): input matrix of size :math:`(*, m, k)` , where :math:`*` is zero or more batch dimensions. A (Tensor): input square matrix of size :math:`(*, m, m)`, where :math:`*` is zero or more batch dimensions. out ((Tensor, Tensor), optional): optional output tuple. Example:: >>> A = torch.tensor([[6.80, -2.11, 5.66, 5.97, 8.23], [-6.05, -3.30, 5.36, -4.44, 1.08], [-0.45, 2.58, -2.70, 0.27, 9.04], [8.32, 2.71, 4.35, -7.17, 2.14], [-9.67, -5.14, -7.26, 6.08, -6.87]]).t() >>> B = torch.tensor([[4.02, 6.19, -8.22, -7.57, -3.03], [-1.56, 4.00, -8.67, 1.75, 2.86], [9.81, -4.09, -4.57, -8.61, 8.99]]).t() >>> X, LU = torch.gesv(B, A) >>> torch.dist(B, torch.mm(A, X)) tensor(1.00000e-06 * 7.0977) >>> # Batched solver example >>> A = torch.randn(2, 3, 1, 4, 4) >>> B = torch.randn(2, 3, 1, 4, 6) >>> X, LU = torch.gesv(B, A) >>> torch.dist(B, A.matmul(X)) tensor(1.00000e-06 * 3.6386) """) add_docstr(torch.get_default_dtype, r""" get_default_dtype() -> torch.dtype Get the current default floating point :class:`torch.dtype`. Example:: >>> torch.get_default_dtype() # initial default for floating point is torch.float32 torch.float32 >>> torch.set_default_dtype(torch.float64) >>> torch.get_default_dtype() # default is now changed to torch.float64 torch.float64 >>> torch.set_default_tensor_type(torch.FloatTensor) # setting tensor type also affects this >>> torch.get_default_dtype() # changed to torch.float32, the dtype for torch.FloatTensor torch.float32 """) add_docstr(torch.get_num_threads, r""" get_num_threads() -> int Gets the number of OpenMP threads used for parallelizing CPU operations """) add_docstr(torch.gt, r""" gt(input, other, out=None) -> Tensor Computes :math:`\text{input} > \text{other}` element-wise. The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor that must be a `ByteTensor` Returns: Tensor: A ``torch.ByteTensor`` containing a 1 at each location where comparison is true Example:: >>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 0, 1], [ 0, 0]], dtype=torch.uint8) """) add_docstr(torch.histc, r""" histc(input, bins=100, min=0, max=0, out=None) -> Tensor Computes the histogram of a tensor. The elements are sorted into equal width bins between :attr:`min` and :attr:`max`. If :attr:`min` and :attr:`max` are both zero, the minimum and maximum values of the data are used. Args: input (Tensor): the input tensor bins (int): number of histogram bins min (int): lower end of the range (inclusive) max (int): upper end of the range (inclusive) out (Tensor, optional): the output tensor Returns: Tensor: Histogram represented as a tensor Example:: >>> torch.histc(torch.tensor([1., 2, 1]), bins=4, min=0, max=3) tensor([ 0., 2., 1., 0.]) """) add_docstr(torch.index_select, r""" index_select(input, dim, index, out=None) -> Tensor Returns a new tensor which indexes the :attr:`input` tensor along dimension :attr:`dim` using the entries in :attr:`index` which is a `LongTensor`. The returned tensor has the same number of dimensions as the original tensor (:attr:`input`). The :attr:`dim`\ th dimension has the same size as the length of :attr:`index`; other dimensions have the same size as in the original tensor. .. note:: The returned tensor does **not** use the same storage as the original tensor. If :attr:`out` has a different shape than expected, we silently change it to the correct shape, reallocating the underlying storage if necessary. Args: input (Tensor): the input tensor dim (int): the dimension in which we index index (LongTensor): the 1-D tensor containing the indices to index out (Tensor, optional): the output tensor Example:: >>> x = torch.randn(3, 4) >>> x tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], [-0.4664, 0.2647, -0.1228, -1.1068], [-1.1734, -0.6571, 0.7230, -0.6004]]) >>> indices = torch.tensor([0, 2]) >>> torch.index_select(x, 0, indices) tensor([[ 0.1427, 0.0231, -0.5414, -1.0009], [-1.1734, -0.6571, 0.7230, -0.6004]]) >>> torch.index_select(x, 1, indices) tensor([[ 0.1427, -0.5414], [-0.4664, -0.1228], [-1.1734, 0.7230]]) """) add_docstr(torch.inverse, r""" inverse(input, out=None) -> Tensor Takes the inverse of the square matrix :attr:`input`. :attr:`input` can be batches of 2D square tensors, in which case this function would return a tensor composed of individual inverses. .. note:: Irrespective of the original strides, the returned tensors will be transposed, i.e. with strides like `input.contiguous().transpose(-2, -1).strides()` Args: input (Tensor): the input tensor of size (*, n, n) where `*` is zero or more batch dimensions out (Tensor, optional): the optional output tensor Example:: >>> x = torch.rand(4, 4) >>> y = torch.inverse(x) >>> z = torch.mm(x, y) >>> z tensor([[ 1.0000, -0.0000, -0.0000, 0.0000], [ 0.0000, 1.0000, 0.0000, 0.0000], [ 0.0000, 0.0000, 1.0000, 0.0000], [ 0.0000, -0.0000, -0.0000, 1.0000]]) >>> torch.max(torch.abs(z - torch.eye(4))) # Max non-zero tensor(1.1921e-07) >>> # Batched inverse example >>> x = torch.randn(2, 3, 4, 4) >>> y = torch.inverse(x) >>> z = torch.matmul(x, y) >>> torch.max(torch.abs(z - torch.eye(4).expand_as(x))) # Max non-zero tensor(1.9073e-06) """) add_docstr(torch.kthvalue, r""" kthvalue(input, k, dim=None, keepdim=False, out=None) -> (Tensor, LongTensor) Returns the :attr:`k` th smallest element of the given :attr:`input` tensor along a given dimension. If :attr:`dim` is not given, the last dimension of the `input` is chosen. A tuple of `(values, indices)` is returned, where the `indices` is the indices of the kth-smallest element in the original `input` tensor in dimension `dim`. If :attr:`keepdim` is ``True``, both the :attr:`values` and :attr:`indices` tensors are the same size as :attr:`input`, except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in both the :attr:`values` and :attr:`indices` tensors having 1 fewer dimension than the :attr:`input` tensor. Args: input (Tensor): the input tensor k (int): k for the k-th smallest element dim (int, optional): the dimension to find the kth value along keepdim (bool): whether the output tensors have :attr:`dim` retained or not out (tuple, optional): the output tuple of (Tensor, LongTensor) can be optionally given to be used as output buffers Example:: >>> x = torch.arange(1., 6.) >>> x tensor([ 1., 2., 3., 4., 5.]) >>> torch.kthvalue(x, 4) (tensor(4.), tensor(3)) >>> x=torch.arange(1.,7.).resize_(2,3) >>> x tensor([[ 1., 2., 3.], [ 4., 5., 6.]]) >>> torch.kthvalue(x,2,0,True) (tensor([[ 4., 5., 6.]]), tensor([[ 1, 1, 1]])) """) add_docstr(torch.le, r""" le(input, other, out=None) -> Tensor Computes :math:`\text{input} \leq \text{other}` element-wise. The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor that must be a `ByteTensor` Returns: Tensor: A ``torch.ByteTensor`` containing a 1 at each location where comparison is true Example:: >>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 1, 0], [ 1, 1]], dtype=torch.uint8) """) add_docstr(torch.lerp, r""" lerp(start, end, weight, out=None) Does a linear interpolation of two tensors :attr:`start` and :attr:`end` based on a scalar :attr:`weight` and returns the resulting :attr:`out` tensor. .. math:: \text{out}_i = \text{start}_i + \text{weight} \times (\text{end}_i - \text{start}_i) The shapes of :attr:`start` and :attr:`end` must be :ref:`broadcastable <broadcasting-semantics>`. Args: start (Tensor): the tensor with the starting points end (Tensor): the tensor with the ending points weight (float): the weight for the interpolation formula out (Tensor, optional): the output tensor Example:: >>> start = torch.arange(1., 5.) >>> end = torch.empty(4).fill_(10) >>> start tensor([ 1., 2., 3., 4.]) >>> end tensor([ 10., 10., 10., 10.]) >>> torch.lerp(start, end, 0.5) tensor([ 5.5000, 6.0000, 6.5000, 7.0000]) """) add_docstr(torch.linspace, r""" linspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a one-dimensional tensor of :attr:`steps` equally spaced points between :attr:`start` and :attr:`end`. The output tensor is 1-D of size :attr:`steps`. Args: start (float): the starting value for the set of points end (float): the ending value for the set of points steps (int): number of points to sample between :attr:`start` and :attr:`end`. Default: ``100``. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.linspace(3, 10, steps=5) tensor([ 3.0000, 4.7500, 6.5000, 8.2500, 10.0000]) >>> torch.linspace(-10, 10, steps=5) tensor([-10., -5., 0., 5., 10.]) >>> torch.linspace(start=-10, end=10, steps=5) tensor([-10., -5., 0., 5., 10.]) """.format(**factory_common_args)) add_docstr(torch.log, r""" log(input, out=None) -> Tensor Returns a new tensor with the natural logarithm of the elements of :attr:`input`. .. math:: y_{i} = \log_{e} (x_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(5) >>> a tensor([-0.7168, -0.5471, -0.8933, -1.4428, -0.1190]) >>> torch.log(a) tensor([ nan, nan, nan, nan, nan]) """) add_docstr(torch.log10, r""" log10(input, out=None) -> Tensor Returns a new tensor with the logarithm to the base 10 of the elements of :attr:`input`. .. math:: y_{i} = \log_{10} (x_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.rand(5) >>> a tensor([ 0.5224, 0.9354, 0.7257, 0.1301, 0.2251]) >>> torch.log10(a) tensor([-0.2820, -0.0290, -0.1392, -0.8857, -0.6476]) """) add_docstr(torch.log1p, r""" log1p(input, out=None) -> Tensor Returns a new tensor with the natural logarithm of (1 + :attr:`input`). .. math:: y_i = \log_{e} (x_i + 1) .. note:: This function is more accurate than :func:`torch.log` for small values of :attr:`input` Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(5) >>> a tensor([-1.0090, -0.9923, 1.0249, -0.5372, 0.2492]) >>> torch.log1p(a) tensor([ nan, -4.8653, 0.7055, -0.7705, 0.2225]) """) add_docstr(torch.log2, r""" log2(input, out=None) -> Tensor Returns a new tensor with the logarithm to the base 2 of the elements of :attr:`input`. .. math:: y_{i} = \log_{2} (x_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.rand(5) >>> a tensor([ 0.8419, 0.8003, 0.9971, 0.5287, 0.0490]) >>> torch.log2(a) tensor([-0.2483, -0.3213, -0.0042, -0.9196, -4.3504]) """) add_docstr(torch.logspace, r""" logspace(start, end, steps=100, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a one-dimensional tensor of :attr:`steps` points logarithmically spaced between :math:`10^{{\text{{start}}}}` and :math:`10^{{\text{{end}}}}`. The output tensor is 1-D of size :attr:`steps`. Args: start (float): the starting value for the set of points end (float): the ending value for the set of points steps (int): number of points to sample between :attr:`start` and :attr:`end`. Default: ``100``. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.logspace(start=-10, end=10, steps=5) tensor([ 1.0000e-10, 1.0000e-05, 1.0000e+00, 1.0000e+05, 1.0000e+10]) >>> torch.logspace(start=0.1, end=1.0, steps=5) tensor([ 1.2589, 2.1135, 3.5481, 5.9566, 10.0000]) """.format(**factory_common_args)) add_docstr(torch.logsumexp, r""" logsumexp(input, dim, keepdim=False, out=None) Returns the log of summed exponentials of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. The computation is numerically stabilized. For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is .. math:: \text{logsumexp}(x)_{i} = \log \sum_j \exp(x_{ij}) If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 fewer dimension than :attr:`input`. Args: input (Tensor): the input tensor dim (int or tuple of ints): the dimension or dimensions to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(3, 3) >>> torch.logsumexp(a, 1) tensor([ 0.8442, 1.4322, 0.8711]) """) add_docstr(torch.lt, r""" lt(input, other, out=None) -> Tensor Computes :math:`\text{input} < \text{other}` element-wise. The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor that must be a `ByteTensor` Returns: Tensor: A `torch.ByteTensor` containing a 1 at each location where comparison is true Example:: >>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 0, 0], [ 1, 0]], dtype=torch.uint8) """) add_docstr(torch.masked_select, r""" masked_select(input, mask, out=None) -> Tensor Returns a new 1-D tensor which indexes the :attr:`input` tensor according to the binary mask :attr:`mask` which is a `ByteTensor`. The shapes of the :attr:`mask` tensor and the :attr:`input` tensor don't need to match, but they must be :ref:`broadcastable <broadcasting-semantics>`. .. note:: The returned tensor does **not** use the same storage as the original tensor Args: input (Tensor): the input data mask (ByteTensor): the tensor containing the binary mask to index with out (Tensor, optional): the output tensor Example:: >>> x = torch.randn(3, 4) >>> x tensor([[ 0.3552, -2.3825, -0.8297, 0.3477], [-1.2035, 1.2252, 0.5002, 0.6248], [ 0.1307, -2.0608, 0.1244, 2.0139]]) >>> mask = x.ge(0.5) >>> mask tensor([[ 0, 0, 0, 0], [ 0, 1, 1, 1], [ 0, 0, 0, 1]], dtype=torch.uint8) >>> torch.masked_select(x, mask) tensor([ 1.2252, 0.5002, 0.6248, 2.0139]) """) add_docstr(torch.matrix_rank, r""" matrix_rank(input, tol=None, bool symmetric=False) -> Tensor Returns the numerical rank of a 2-D tensor. The method to compute the matrix rank is done using SVD by default. If :attr:`symmetric` is ``True``, then :attr:`input` is assumed to be symmetric, and the computation of the rank is done by obtaining the eigenvalues. :attr:`tol` is the threshold below which the singular values (or the eigenvalues when :attr:`symmetric` is ``True``) are considered to be 0. If :attr:`tol` is not specified, :attr:`tol` is set to ``S.max() * max(S.size()) * eps`` where `S` is the singular values (or the eigenvalues when :attr:`symmetric` is ``True``), and ``eps`` is the epsilon value for the datatype of :attr:`input`. Args: input (Tensor): the input 2-D tensor tol (float, optional): the tolerance value. Default: ``None`` symmetric(bool, optional): indicates whether :attr:`input` is symmetric. Default: ``False`` Example:: >>> a = torch.eye(10) >>> torch.matrix_rank(a) tensor(10) >>> b = torch.eye(10) >>> b[0, 0] = 0 >>> torch.matrix_rank(b) tensor(9) """) add_docstr(torch.matrix_power, r""" matrix_power(input, n) -> Tensor Returns the matrix raised to the power :attr:`n` for square matrices. For batch of matrices, each individual matrix is raised to the power :attr:`n`. If :attr:`n` is negative, then the inverse of the matrix (if invertible) is raised to the power :attr:`n`. For a batch of matrices, the batched inverse (if invertible) is raised to the power :attr:`n`. If :attr:`n` is 0, then an identity matrix is returned. Args: input (Tensor): the input tensor n (int): the power to raise the matrix to Example:: >>> a = torch.randn(2, 2, 2) >>> a tensor([[[-1.9975, -1.9610], [ 0.9592, -2.3364]], [[-1.2534, -1.3429], [ 0.4153, -1.4664]]]) >>> torch.matrix_power(a, 3) tensor([[[ 3.9392, -23.9916], [ 11.7357, -0.2070]], [[ 0.2468, -6.7168], [ 2.0774, -0.8187]]]) """) add_docstr(torch.max, r""" .. function:: max(input) -> Tensor Returns the maximum value of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor Example:: >>> a = torch.randn(1, 3) >>> a tensor([[ 0.6763, 0.7445, -2.2369]]) >>> torch.max(a) tensor(0.7445) .. function:: max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor) Returns the maximum value of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. The second return value is the index location of each maximum value found (argmax). If :attr:`keepdim` is ``True``, the output tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensors having 1 fewer dimension than :attr:`input`. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensors have :attr:`dim` retained or not out (tuple, optional): the result tuple of two output tensors (max, max_indices) Example:: >>> a = torch.randn(4, 4) >>> a tensor([[-1.2360, -0.2942, -0.1222, 0.8475], [ 1.1949, -1.1127, -2.2379, -0.6702], [ 1.5717, -0.9207, 0.1297, -1.8768], [-0.6172, 1.0036, -0.6060, -0.2432]]) >>> torch.max(a, 1) (tensor([ 0.8475, 1.1949, 1.5717, 1.0036]), tensor([ 3, 0, 0, 1])) .. function:: max(input, other, out=None) -> Tensor Each element of the tensor :attr:`input` is compared with the corresponding element of the tensor :attr:`other` and an element-wise maximum is taken. The shapes of :attr:`input` and :attr:`other` don't need to match, but they must be :ref:`broadcastable <broadcasting-semantics>`. .. math:: \text{out}_i = \max(\text{tensor}_i, \text{other}_i) .. note:: When the shapes do not match, the shape of the returned output tensor follows the :ref:`broadcasting rules <broadcasting-semantics>`. Args: input (Tensor): the input tensor other (Tensor): the second input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.2942, -0.7416, 0.2653, -0.1584]) >>> b = torch.randn(4) >>> b tensor([ 0.8722, -1.7421, -0.4141, -0.5055]) >>> torch.max(a, b) tensor([ 0.8722, -0.7416, 0.2653, -0.1584]) """) add_docstr(torch.mean, r""" .. function:: mean(input) -> Tensor Returns the mean value of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor Example:: >>> a = torch.randn(1, 3) >>> a tensor([[ 0.2294, -0.5481, 1.3288]]) >>> torch.mean(a) tensor(0.3367) .. function:: mean(input, dim, keepdim=False, out=None) -> Tensor Returns the mean value of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, reduce over all of them. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 (or ``len(dim)``) fewer dimension(s). Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool, optional): whether the output tensor has :attr:`dim` retained or not out (Tensor): the output tensor Example:: >>> a = torch.randn(4, 4) >>> a tensor([[-0.3841, 0.6320, 0.4254, -0.7384], [-0.9644, 1.0131, -0.6549, -1.4279], [-0.2951, -1.3350, -0.7694, 0.5600], [ 1.0842, -0.9580, 0.3623, 0.2343]]) >>> torch.mean(a, 1) tensor([-0.0163, -0.5085, -0.4599, 0.1807]) >>> torch.mean(a, 1, True) tensor([[-0.0163], [-0.5085], [-0.4599], [ 0.1807]]) """) add_docstr(torch.median, r""" .. function:: median(input) -> Tensor Returns the median value of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor Example:: >>> a = torch.randn(1, 3) >>> a tensor([[ 1.5219, -1.5212, 0.2202]]) >>> torch.median(a) tensor(0.2202) .. function:: median(input, dim=-1, keepdim=False, values=None, indices=None) -> (Tensor, LongTensor) Returns the median value of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. Also returns the index location of the median value as a `LongTensor`. By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. If :attr:`keepdim` is ``True``, the output tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the outputs tensor having 1 fewer dimension than :attr:`input`. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensors have :attr:`dim` retained or not values (Tensor, optional): the output tensor indices (Tensor, optional): the output index tensor Example:: >>> a = torch.randn(4, 5) >>> a tensor([[ 0.2505, -0.3982, -0.9948, 0.3518, -1.3131], [ 0.3180, -0.6993, 1.0436, 0.0438, 0.2270], [-0.2751, 0.7303, 0.2192, 0.3321, 0.2488], [ 1.0778, -1.9510, 0.7048, 0.4742, -0.7125]]) >>> torch.median(a, 1) (tensor([-0.3982, 0.2270, 0.2488, 0.4742]), tensor([ 1, 4, 4, 3])) """) add_docstr(torch.min, r""" .. function:: min(input) -> Tensor Returns the minimum value of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor Example:: >>> a = torch.randn(1, 3) >>> a tensor([[ 0.6750, 1.0857, 1.7197]]) >>> torch.min(a) tensor(0.6750) .. function:: min(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor) Returns the minimum value of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. The second return value is the index location of each minimum value found (argmin). If :attr:`keepdim` is ``True``, the output tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensors having 1 fewer dimension than :attr:`input`. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensors have :attr:`dim` retained or not out (tuple, optional): the tuple of two output tensors (min, min_indices) Example:: >>> a = torch.randn(4, 4) >>> a tensor([[-0.6248, 1.1334, -1.1899, -0.2803], [-1.4644, -0.2635, -0.3651, 0.6134], [ 0.2457, 0.0384, 1.0128, 0.7015], [-0.1153, 2.9849, 2.1458, 0.5788]]) >>> torch.min(a, 1) (tensor([-1.1899, -1.4644, 0.0384, -0.1153]), tensor([ 2, 0, 1, 0])) .. function:: min(input, other, out=None) -> Tensor Each element of the tensor :attr:`input` is compared with the corresponding element of the tensor :attr:`other` and an element-wise minimum is taken. The resulting tensor is returned. The shapes of :attr:`input` and :attr:`other` don't need to match, but they must be :ref:`broadcastable <broadcasting-semantics>`. .. math:: \text{out}_i = \min(\text{tensor}_i, \text{other}_i) .. note:: When the shapes do not match, the shape of the returned output tensor follows the :ref:`broadcasting rules <broadcasting-semantics>`. Args: input (Tensor): the input tensor other (Tensor): the second input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.8137, -1.1740, -0.6460, 0.6308]) >>> b = torch.randn(4) >>> b tensor([-0.1369, 0.1555, 0.4019, -0.1929]) >>> torch.min(a, b) tensor([-0.1369, -1.1740, -0.6460, -0.1929]) """) add_docstr(torch.mm, r""" mm(mat1, mat2, out=None) -> Tensor Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. If :attr:`mat1` is a :math:`(n \times m)` tensor, :attr:`mat2` is a :math:`(m \times p)` tensor, :attr:`out` will be a :math:`(n \times p)` tensor. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`. For broadcasting matrix products, see :func:`torch.matmul`. Args: mat1 (Tensor): the first matrix to be multiplied mat2 (Tensor): the second matrix to be multiplied out (Tensor, optional): the output tensor Example:: >>> mat1 = torch.randn(2, 3) >>> mat2 = torch.randn(3, 3) >>> torch.mm(mat1, mat2) tensor([[ 0.4851, 0.5037, -0.3633], [-0.0760, -3.6705, 2.4784]]) """) add_docstr(torch.matmul, r""" matmul(tensor1, tensor2, out=None) -> Tensor Matrix product of two tensors. The behavior depends on the dimensionality of the tensors as follows: - If both tensors are 1-dimensional, the dot product (scalar) is returned. - If both arguments are 2-dimensional, the matrix-matrix product is returned. - If the first argument is 1-dimensional and the second argument is 2-dimensional, a 1 is prepended to its dimension for the purpose of the matrix multiply. After the matrix multiply, the prepended dimension is removed. - If the first argument is 2-dimensional and the second argument is 1-dimensional, the matrix-vector product is returned. - If both arguments are at least 1-dimensional and at least one argument is N-dimensional (where N > 2), then a batched matrix multiply is returned. If the first argument is 1-dimensional, a 1 is prepended to its dimension for the purpose of the batched matrix multiply and removed after. If the second argument is 1-dimensional, a 1 is appended to its dimension for the purpose of the batched matrix multiple and removed after. The non-matrix (i.e. batch) dimensions are :ref:`broadcasted <broadcasting-semantics>` (and thus must be broadcastable). For example, if :attr:`tensor1` is a :math:`(j \times 1 \times n \times m)` tensor and :attr:`tensor2` is a :math:`(k \times m \times p)` tensor, :attr:`out` will be an :math:`(j \times k \times n \times p)` tensor. .. note:: The 1-dimensional dot product version of this function does not support an :attr:`out` parameter. Arguments: tensor1 (Tensor): the first tensor to be multiplied tensor2 (Tensor): the second tensor to be multiplied out (Tensor, optional): the output tensor Example:: >>> # vector x vector >>> tensor1 = torch.randn(3) >>> tensor2 = torch.randn(3) >>> torch.matmul(tensor1, tensor2).size() torch.Size([]) >>> # matrix x vector >>> tensor1 = torch.randn(3, 4) >>> tensor2 = torch.randn(4) >>> torch.matmul(tensor1, tensor2).size() torch.Size([3]) >>> # batched matrix x broadcasted vector >>> tensor1 = torch.randn(10, 3, 4) >>> tensor2 = torch.randn(4) >>> torch.matmul(tensor1, tensor2).size() torch.Size([10, 3]) >>> # batched matrix x batched matrix >>> tensor1 = torch.randn(10, 3, 4) >>> tensor2 = torch.randn(10, 4, 5) >>> torch.matmul(tensor1, tensor2).size() torch.Size([10, 3, 5]) >>> # batched matrix x broadcasted matrix >>> tensor1 = torch.randn(10, 3, 4) >>> tensor2 = torch.randn(4, 5) >>> torch.matmul(tensor1, tensor2).size() torch.Size([10, 3, 5]) """) add_docstr(torch.mode, r""" mode(input, dim=-1, keepdim=False, values=None, indices=None) -> (Tensor, LongTensor) Returns the mode value of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. Also returns the index location of the mode value as a `LongTensor`. By default, :attr:`dim` is the last dimension of the :attr:`input` tensor. If :attr:`keepdim` is ``True``, the output tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensors having 1 fewer dimension than :attr:`input`. .. note:: This function is not defined for ``torch.cuda.Tensor`` yet. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensors have :attr:`dim` retained or not values (Tensor, optional): the output tensor indices (Tensor, optional): the output index tensor Example:: >>> a = torch.randn(4, 5) >>> a tensor([[-1.2808, -1.0966, -1.5946, -0.1148, 0.3631], [ 1.1395, 1.1452, -0.6383, 0.3667, 0.4545], [-0.4061, -0.3074, 0.4579, -1.3514, 1.2729], [-1.0130, 0.3546, -1.4689, -0.1254, 0.0473]]) >>> torch.mode(a, 1) (tensor([-1.5946, -0.6383, -1.3514, -1.4689]), tensor([ 2, 2, 3, 2])) """) add_docstr(torch.mul, r""" .. function:: mul(input, value, out=None) Multiplies each element of the input :attr:`input` with the scalar :attr:`value` and returns a new resulting tensor. .. math:: \text{out}_i = \text{value} \times \text{input}_i If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input tensor value (Number): the number to be multiplied to each element of :attr:`input` out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(3) >>> a tensor([ 0.2015, -0.4255, 2.6087]) >>> torch.mul(a, 100) tensor([ 20.1494, -42.5491, 260.8663]) .. function:: mul(input, other, out=None) Each element of the tensor :attr:`input` is multiplied by each element of the Tensor :attr:`other`. The resulting tensor is returned. The shapes of :attr:`input` and :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`. .. math:: \text{out}_i = \text{input}_i \times \text{other}_i Args: input (Tensor): the first multiplicand tensor other (Tensor): the second multiplicand tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 1) >>> a tensor([[ 1.1207], [-0.3137], [ 0.0700], [ 0.8378]]) >>> b = torch.randn(1, 4) >>> b tensor([[ 0.5146, 0.1216, -0.5244, 2.2382]]) >>> torch.mul(a, b) tensor([[ 0.5767, 0.1363, -0.5877, 2.5083], [-0.1614, -0.0382, 0.1645, -0.7021], [ 0.0360, 0.0085, -0.0367, 0.1567], [ 0.4312, 0.1019, -0.4394, 1.8753]]) """) add_docstr(torch.multinomial, r""" multinomial(input, num_samples, replacement=False, out=None) -> LongTensor Returns a tensor where each row contains :attr:`num_samples` indices sampled from the multinomial probability distribution located in the corresponding row of tensor :attr:`input`. .. note:: The rows of :attr:`input` do not need to sum to one (in which case we use the values as weights), but must be non-negative, finite and have a non-zero sum. Indices are ordered from left to right according to when each was sampled (first samples are placed in first column). If :attr:`input` is a vector, :attr:`out` is a vector of size :attr:`num_samples`. If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape :math:`(m \times \text{num\_samples})`. If replacement is ``True``, samples are drawn with replacement. If not, they are drawn without replacement, which means that when a sample index is drawn for a row, it cannot be drawn again for that row. This implies the constraint that :attr:`num_samples` must be lower than :attr:`input` length (or number of columns of :attr:`input` if it is a matrix). Args: input (Tensor): the input tensor containing probabilities num_samples (int): number of samples to draw replacement (bool, optional): whether to draw with replacement or not out (Tensor, optional): the output tensor Example:: >>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights >>> torch.multinomial(weights, 4) tensor([ 1, 2, 0, 0]) >>> torch.multinomial(weights, 4, replacement=True) tensor([ 2, 1, 1, 1]) """) add_docstr(torch.mv, r""" mv(mat, vec, out=None) -> Tensor Performs a matrix-vector product of the matrix :attr:`mat` and the vector :attr:`vec`. If :attr:`mat` is a :math:`(n \times m)` tensor, :attr:`vec` is a 1-D tensor of size :math:`m`, :attr:`out` will be 1-D of size :math:`n`. .. note:: This function does not :ref:`broadcast <broadcasting-semantics>`. Args: mat (Tensor): matrix to be multiplied vec (Tensor): vector to be multiplied out (Tensor, optional): the output tensor Example:: >>> mat = torch.randn(2, 3) >>> vec = torch.randn(3) >>> torch.mv(mat, vec) tensor([ 1.0404, -0.6361]) """) add_docstr(torch.mvlgamma, r""" mvlgamma(input, p) -> Tensor Computes the multivariate log-gamma function with dimension :math:`p` element-wise, given by .. math:: \log(\Gamma_{p}(a)) = C + \displaystyle \sum_{i=1}^{p} \log\left(\Gamma\left(a - \frac{i - 1}{2}\right)\right) where :math:`C = \log(\pi) \times \frac{p (p - 1)}{2}` and :math:`\Gamma(\cdot)` is the Gamma function. If any of the elements are less than or equal to :math:`\frac{p - 1}{2}`, then an error is thrown. Args: input (Tensor): the tensor to compute the multivariate log-gamma function p (int): the number of dimensions Example:: >>> a = torch.empty(2, 3).uniform_(1, 2) >>> a tensor([[1.6835, 1.8474, 1.1929], [1.0475, 1.7162, 1.4180]]) >>> torch.mvlgamma(a, 2) tensor([[0.3928, 0.4007, 0.7586], [1.0311, 0.3901, 0.5049]]) """) add_docstr(torch.narrow, r""" narrow(input, dimension, start, length) -> Tensor Returns a new tensor that is a narrowed version of :attr:`input` tensor. The dimension :attr:`dim` is input from :attr:`start` to :attr:`start + length`. The returned tensor and :attr:`input` tensor share the same underlying storage. Args: input (Tensor): the tensor to narrow dimension (int): the dimension along which to narrow start (int): the starting dimension length (int): the distance to the ending dimension Example:: >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> torch.narrow(x, 0, 0, 2) tensor([[ 1, 2, 3], [ 4, 5, 6]]) >>> torch.narrow(x, 1, 1, 2) tensor([[ 2, 3], [ 5, 6], [ 8, 9]]) """) add_docstr(torch.ne, r""" ne(input, other, out=None) -> Tensor Computes :math:`input \neq other` element-wise. The second argument can be a number or a tensor whose shape is :ref:`broadcastable <broadcasting-semantics>` with the first argument. Args: input (Tensor): the tensor to compare other (Tensor or float): the tensor or value to compare out (Tensor, optional): the output tensor that must be a `ByteTensor` Returns: Tensor: A ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[ 0, 1], [ 1, 0]], dtype=torch.uint8) """) add_docstr(torch.neg, r""" neg(input, out=None) -> Tensor Returns a new tensor with the negative of the elements of :attr:`input`. .. math:: \text{out} = -1 \times \text{input} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(5) >>> a tensor([ 0.0090, -0.2262, -0.0682, -0.2866, 0.3940]) >>> torch.neg(a) tensor([-0.0090, 0.2262, 0.0682, 0.2866, -0.3940]) """) add_docstr(torch.nonzero, r""" nonzero(input, out=None) -> LongTensor Returns a tensor containing the indices of all non-zero elements of :attr:`input`. Each row in the result contains the indices of a non-zero element in :attr:`input`. If :attr:`input` has `n` dimensions, then the resulting indices tensor :attr:`out` is of size :math:`(z \times n)`, where :math:`z` is the total number of non-zero elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor out (LongTensor, optional): the output tensor containing indices Example:: >>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1])) tensor([[ 0], [ 1], [ 2], [ 4]]) >>> torch.nonzero(torch.tensor([[0.6, 0.0, 0.0, 0.0], [0.0, 0.4, 0.0, 0.0], [0.0, 0.0, 1.2, 0.0], [0.0, 0.0, 0.0,-0.4]])) tensor([[ 0, 0], [ 1, 1], [ 2, 2], [ 3, 3]]) """) add_docstr(torch.normal, r""" .. function:: normal(mean, std, out=None) -> Tensor Returns a tensor of random numbers drawn from separate normal distributions whose mean and standard deviation are given. The :attr:`mean` is a tensor with the mean of each output element's normal distribution The :attr:`std` is a tensor with the standard deviation of each output element's normal distribution The shapes of :attr:`mean` and :attr:`std` don't need to match, but the total number of elements in each tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`mean` is used as the shape for the returned output tensor Args: mean (Tensor): the tensor of per-element means std (Tensor): the tensor of per-element standard deviations out (Tensor, optional): the output tensor Example:: >>> torch.normal(mean=torch.arange(1., 11.), std=torch.arange(1, 0, -0.1)) tensor([ 1.0425, 3.5672, 2.7969, 4.2925, 4.7229, 6.2134, 8.0505, 8.1408, 9.0563, 10.0566]) .. function:: normal(mean=0.0, std, out=None) -> Tensor Similar to the function above, but the means are shared among all drawn elements. Args: mean (float, optional): the mean for all distributions std (Tensor): the tensor of per-element standard deviations out (Tensor, optional): the output tensor Example:: >>> torch.normal(mean=0.5, std=torch.arange(1., 6.)) tensor([-1.2793, -1.0732, -2.0687, 5.1177, -1.2303]) .. function:: normal(mean, std=1.0, out=None) -> Tensor Similar to the function above, but the standard-deviations are shared among all drawn elements. Args: mean (Tensor): the tensor of per-element means std (float, optional): the standard deviation for all distributions out (Tensor, optional): the output tensor Example:: >>> torch.normal(mean=torch.arange(1., 6.)) tensor([ 1.1552, 2.6148, 2.6535, 5.8318, 4.2361]) """) add_docstr(torch.numel, r""" numel(input) -> int Returns the total number of elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor Example:: >>> a = torch.randn(1, 2, 3, 4, 5) >>> torch.numel(a) 120 >>> a = torch.zeros(4,4) >>> torch.numel(a) 16 """) add_docstr(torch.ones, r""" ones(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with the scalar value `1`, with the shape defined by the variable argument :attr:`sizes`. Args: sizes (int...): a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.ones(2, 3) tensor([[ 1., 1., 1.], [ 1., 1., 1.]]) >>> torch.ones(5) tensor([ 1., 1., 1., 1., 1.]) """.format(**factory_common_args)) add_docstr(torch.ones_like, r""" ones_like(input, dtype=None, layout=None, device=None, requires_grad=False) -> Tensor Returns a tensor filled with the scalar value `1`, with the same size as :attr:`input`. ``torch.ones_like(input)`` is equivalent to ``torch.ones(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. .. warning:: As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, the old ``torch.ones_like(input, out=output)`` is equivalent to ``torch.ones(input.size(), out=output)``. Args: {input} {dtype} {layout} {device} {requires_grad} Example:: >>> input = torch.empty(2, 3) >>> torch.ones_like(input) tensor([[ 1., 1., 1.], [ 1., 1., 1.]]) """.format(**factory_like_common_args)) add_docstr(torch.orgqr, r""" orgqr(a, tau) -> Tensor Computes the orthogonal matrix `Q` of a QR factorization, from the `(a, tau)` tuple returned by :func:`torch.geqrf`. This directly calls the underlying LAPACK function `?orgqr`. See `LAPACK documentation for orgqr`_ for further details. Args: a (Tensor): the `a` from :func:`torch.geqrf`. tau (Tensor): the `tau` from :func:`torch.geqrf`. .. _LAPACK documentation for orgqr: https://software.intel.com/en-us/mkl-developer-reference-c-orgqr """) add_docstr(torch.ormqr, r""" ormqr(a, tau, mat, left=True, transpose=False) -> (Tensor, Tensor) Multiplies `mat` by the orthogonal `Q` matrix of the QR factorization formed by :func:`torch.geqrf` that is represented by `(a, tau)`. This directly calls the underlying LAPACK function `?ormqr`. See `LAPACK documentation for ormqr`_ for further details. Args: a (Tensor): the `a` from :func:`torch.geqrf`. tau (Tensor): the `tau` from :func:`torch.geqrf`. mat (Tensor): the matrix to be multiplied. .. _LAPACK documentation for ormqr: https://software.intel.com/en-us/mkl-developer-reference-c-ormqr """) add_docstr(torch.potri, r""" potri(u, upper=True, out=None) -> Tensor Computes the inverse of a positive semidefinite matrix given its Cholesky factor :attr:`u`: returns matrix `inv` If :attr:`upper` is ``True`` or not provided, :attr:`u` is upper triangular such that the returned tensor is .. math:: inv = (u^T u)^{-1} If :attr:`upper` is ``False``, :attr:`u` is lower triangular such that the returned tensor is .. math:: inv = (uu^{T})^{-1} Args: u (Tensor): the input 2-D tensor, a upper or lower triangular Cholesky factor upper (bool, optional): whether to return a upper (default) or lower triangular matrix out (Tensor, optional): the output tensor for `inv` Example:: >>> a = torch.randn(3, 3) >>> a = torch.mm(a, a.t()) # make symmetric positive definite >>> u = torch.cholesky(a) >>> a tensor([[ 0.9935, -0.6353, 1.5806], [ -0.6353, 0.8769, -1.7183], [ 1.5806, -1.7183, 10.6618]]) >>> torch.potri(u) tensor([[ 1.9314, 1.2251, -0.0889], [ 1.2251, 2.4439, 0.2122], [-0.0889, 0.2122, 0.1412]]) >>> a.inverse() tensor([[ 1.9314, 1.2251, -0.0889], [ 1.2251, 2.4439, 0.2122], [-0.0889, 0.2122, 0.1412]]) """) add_docstr(torch.potrs, r""" potrs(b, u, upper=True, out=None) -> Tensor Solves a linear system of equations with a positive semidefinite matrix to be inverted given its Cholesky factor matrix :attr:`u`. If :attr:`upper` is ``True`` or not provided, :attr:`u` is upper triangular and `c` is returned such that: .. math:: c = (u^T u)^{-1} b If :attr:`upper` is ``False``, :attr:`u` is and lower triangular and `c` is returned such that: .. math:: c = (u u^T)^{-1} b `torch.potrs(b, u)` can take in 2D inputs `b, u` or inputs that are batches of 2D matrices. If the inputs are batches, then returns batched outputs `c` .. note:: The :attr:`out` keyword only supports 2D matrix inputs, that is, `b, u` must be 2D matrices. Args: b (Tensor): input matrix of size :math:`(*, m, k)`, where :math:`*` is zero or more batch dimensions u (Tensor): input matrix of size :math:`(*, m, m)`, where :math:`*` is zero of more batch dimensions composed of upper or lower triangular Cholesky factor upper (bool, optional): whether to return a upper (default) or lower triangular matrix out (Tensor, optional): the output tensor for `c` Example:: >>> a = torch.randn(3, 3) >>> a = torch.mm(a, a.t()) # make symmetric positive definite >>> u = torch.cholesky(a) >>> a tensor([[ 0.7747, -1.9549, 1.3086], [-1.9549, 6.7546, -5.4114], [ 1.3086, -5.4114, 4.8733]]) >>> b = torch.randn(3, 2) >>> b tensor([[-0.6355, 0.9891], [ 0.1974, 1.4706], [-0.4115, -0.6225]]) >>> torch.potrs(b,u) tensor([[ -8.1625, 19.6097], [ -5.8398, 14.2387], [ -4.3771, 10.4173]]) >>> torch.mm(a.inverse(),b) tensor([[ -8.1626, 19.6097], [ -5.8398, 14.2387], [ -4.3771, 10.4173]]) """) add_docstr(torch.pow, r""" .. function:: pow(input, exponent, out=None) -> Tensor Takes the power of each element in :attr:`input` with :attr:`exponent` and returns a tensor with the result. :attr:`exponent` can be either a single ``float`` number or a `Tensor` with the same number of elements as :attr:`input`. When :attr:`exponent` is a scalar value, the operation applied is: .. math:: \text{out}_i = x_i ^ \text{exponent} When :attr:`exponent` is a tensor, the operation applied is: .. math:: \text{out}_i = x_i ^ {\text{exponent}_i} When :attr:`exponent` is a tensor, the shapes of :attr:`input` and :attr:`exponent` must be :ref:`broadcastable <broadcasting-semantics>`. Args: input (Tensor): the input tensor exponent (float or tensor): the exponent value out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.4331, 1.2475, 0.6834, -0.2791]) >>> torch.pow(a, 2) tensor([ 0.1875, 1.5561, 0.4670, 0.0779]) >>> exp = torch.arange(1., 5.) >>> a = torch.arange(1., 5.) >>> a tensor([ 1., 2., 3., 4.]) >>> exp tensor([ 1., 2., 3., 4.]) >>> torch.pow(a, exp) tensor([ 1., 4., 27., 256.]) .. function:: pow(base, input, out=None) -> Tensor :attr:`base` is a scalar ``float`` value, and :attr:`input` is a tensor. The returned tensor :attr:`out` is of the same shape as :attr:`input` The operation applied is: .. math:: out_i = base ^ {input_i} Args: base (float): the scalar base value for the power operation input (Tensor): the exponent tensor out (Tensor, optional): the output tensor Example:: >>> exp = torch.arange(1., 5.) >>> base = 2 >>> torch.pow(base, exp) tensor([ 2., 4., 8., 16.]) """) add_docstr(torch.prod, r""" .. function:: prod(input, dtype=None) -> Tensor Returns the product of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor {dtype} Example:: >>> a = torch.randn(1, 3) >>> a tensor([[-0.8020, 0.5428, -1.5854]]) >>> torch.prod(a) tensor(0.6902) .. function:: prod(input, dim, keepdim=False, dtype=None) -> Tensor Returns the product of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 fewer dimension than :attr:`input`. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not {dtype} Example:: >>> a = torch.randn(4, 2) >>> a tensor([[ 0.5261, -0.3837], [ 1.1857, -0.2498], [-1.1646, 0.0705], [ 1.1131, -1.0629]]) >>> torch.prod(a, 1) tensor([-0.2018, -0.2962, -0.0821, -1.1831]) """.format(**reduceops_common_args)) add_docstr(torch.pstrf, r""" pstrf(a, upper=True, out=None) -> (Tensor, Tensor) Computes the pivoted Cholesky decomposition of a positive semidefinite matrix :attr:`a`. returns matrices `u` and `piv`. If :attr:`upper` is ``True`` or not provided, `u` is upper triangular such that :math:`a = p^T u^T u p`, with `p` the permutation given by `piv`. If :attr:`upper` is ``False``, `u` is lower triangular such that :math:`a = p^T u u^T p`. Args: a (Tensor): the input 2-D tensor upper (bool, optional): whether to return a upper (default) or lower triangular matrix out (tuple, optional): tuple of `u` and `piv` tensors Example:: >>> a = torch.randn(3, 3) >>> a = torch.mm(a, a.t()) # make symmetric positive definite >>> a tensor([[ 3.5405, -0.4577, 0.8342], [-0.4577, 1.8244, -0.1996], [ 0.8342, -0.1996, 3.7493]]) >>> u,piv = torch.pstrf(a) >>> u tensor([[ 1.9363, 0.4308, -0.1031], [ 0.0000, 1.8316, -0.2256], [ 0.0000, 0.0000, 1.3277]]) >>> piv tensor([ 2, 0, 1], dtype=torch.int32) >>> p = torch.eye(3).index_select(0,piv.long()).index_select(0,piv.long()).t() # make pivot permutation >>> torch.mm(torch.mm(p.t(),torch.mm(u.t(),u)),p) # reconstruct tensor([[ 3.5405, -0.4577, 0.8342], [-0.4577, 1.8244, -0.1996], [ 0.8342, -0.1996, 3.7493]]) """) add_docstr(torch.qr, r""" qr(input, out=None) -> (Tensor, Tensor) Computes the QR decomposition of a matrix :attr:`input`, and returns matrices `Q` and `R` such that :math:`\text{input} = Q R`, with :math:`Q` being an orthogonal matrix and :math:`R` being an upper triangular matrix. This returns the thin (reduced) QR factorization. .. note:: precision may be lost if the magnitudes of the elements of :attr:`input` are large .. note:: While it should always give you a valid decomposition, it may not give you the same one across platforms - it will depend on your LAPACK implementation. .. note:: Irrespective of the original strides, the returned matrix :math:`Q` will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)`. Args: input (Tensor): the input 2-D tensor out (tuple, optional): tuple of `Q` and `R` tensors Example:: >>> a = torch.tensor([[12., -51, 4], [6, 167, -68], [-4, 24, -41]]) >>> q, r = torch.qr(a) >>> q tensor([[-0.8571, 0.3943, 0.3314], [-0.4286, -0.9029, -0.0343], [ 0.2857, -0.1714, 0.9429]]) >>> r tensor([[ -14.0000, -21.0000, 14.0000], [ 0.0000, -175.0000, 70.0000], [ 0.0000, 0.0000, -35.0000]]) >>> torch.mm(q, r).round() tensor([[ 12., -51., 4.], [ 6., 167., -68.], [ -4., 24., -41.]]) >>> torch.mm(q.t(), q).round() tensor([[ 1., 0., 0.], [ 0., 1., -0.], [ 0., -0., 1.]]) """) add_docstr(torch.rand, r""" rand(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with random numbers from a uniform distribution on the interval :math:`[0, 1)` The shape of the tensor is defined by the variable argument :attr:`sizes`. Args: sizes (int...): a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.rand(4) tensor([ 0.5204, 0.2503, 0.3525, 0.5673]) >>> torch.rand(2, 3) tensor([[ 0.8237, 0.5781, 0.6879], [ 0.3816, 0.7249, 0.0998]]) """.format(**factory_common_args)) add_docstr(torch.rand_like, r""" rand_like(input, dtype=None, layout=None, device=None, requires_grad=False) -> Tensor Returns a tensor with the same size as :attr:`input` that is filled with random numbers from a uniform distribution on the interval :math:`[0, 1)`. ``torch.rand_like(input)`` is equivalent to ``torch.rand(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. Args: {input} {dtype} {layout} {device} {requires_grad} """.format(**factory_like_common_args)) add_docstr(torch.randint, r""" randint(low=0, high, size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with random integers generated uniformly between :attr:`low` (inclusive) and :attr:`high` (exclusive). The shape of the tensor is defined by the variable argument :attr:`size`. .. note: With the global dtype default (`torch.float32`), this function returns a tensor with dtype `torch.int64`. Args: low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. high (int): One above the highest integer to be drawn from the distribution. size (tuple): a tuple defining the shape of the output tensor. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.randint(3, 5, (3,)) tensor([4, 3, 4]) >>> torch.randint(10, (2, 2)) tensor([[0, 2], [5, 5]]) >>> torch.randint(3, 10, (2, 2)) tensor([[4, 5], [6, 7]]) """.format(**factory_common_args)) add_docstr(torch.randint_like, r""" randint_like(input, low=0, high, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor with the same shape as Tensor :attr:`input` filled with random integers generated uniformly between :attr:`low` (inclusive) and :attr:`high` (exclusive). .. note: With the global dtype default (`torch.float32`), this function returns a tensor with dtype `torch.int64`. Args: {input} low (int, optional): Lowest integer to be drawn from the distribution. Default: 0. high (int): One above the highest integer to be drawn from the distribution. {dtype} {layout} {device} {requires_grad} """.format(**factory_like_common_args)) add_docstr(torch.randn, r""" randn(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with random numbers from a normal distribution with mean `0` and variance `1` (also called the standard normal distribution). .. math:: \text{{out}}_{{i}} \sim \mathcal{{N}}(0, 1) The shape of the tensor is defined by the variable argument :attr:`sizes`. Args: sizes (int...): a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.randn(4) tensor([-2.1436, 0.9966, 2.3426, -0.6366]) >>> torch.randn(2, 3) tensor([[ 1.5954, 2.8929, -1.0923], [ 1.1719, -0.4709, -0.1996]]) """.format(**factory_common_args)) add_docstr(torch.randn_like, r""" randn_like(input, dtype=None, layout=None, device=None, requires_grad=False) -> Tensor Returns a tensor with the same size as :attr:`input` that is filled with random numbers from a normal distribution with mean 0 and variance 1. ``torch.randn_like(input)`` is equivalent to ``torch.randn(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. Args: {input} {dtype} {layout} {device} {requires_grad} """.format(**factory_like_common_args)) add_docstr(torch.randperm, r""" randperm(n, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False) -> LongTensor Returns a random permutation of integers from ``0`` to ``n - 1``. Args: n (int): the upper bound (exclusive) {out} dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: ``torch.int64``. {layout} {device} {requires_grad} Example:: >>> torch.randperm(4) tensor([2, 1, 0, 3]) """.format(**factory_common_args)) add_docstr(torch.tensor, r""" tensor(data, dtype=None, device=None, requires_grad=False) -> Tensor Constructs a tensor with :attr:`data`. .. warning:: :func:`torch.tensor` always copies :attr:`data`. If you have a Tensor ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` or :func:`torch.Tensor.detach`. If you have a NumPy ``ndarray`` and want to avoid a copy, use :func:`torch.from_numpy`. .. warning:: When data is a tensor `x`, :func:`torch.tensor` reads out 'the data' from whatever it is passed, and constructs a leaf variable. Therefore ``torch.tensor(x)`` is equivalent to ``x.clone().detach()`` and ``torch.tensor(x, requires_grad=True)`` is equivalent to ``x.clone().detach().requires_grad_(True)``. The equivalents using ``clone()`` and ``detach()`` are recommended. Args: {data} {dtype} {device} {requires_grad} Example:: >>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]]) tensor([[ 0.1000, 1.2000], [ 2.2000, 3.1000], [ 4.9000, 5.2000]]) >>> torch.tensor([0, 1]) # Type inference on data tensor([ 0, 1]) >>> torch.tensor([[0.11111, 0.222222, 0.3333333]], dtype=torch.float64, device=torch.device('cuda:0')) # creates a torch.cuda.DoubleTensor tensor([[ 0.1111, 0.2222, 0.3333]], dtype=torch.float64, device='cuda:0') >>> torch.tensor(3.14159) # Create a scalar (zero-dimensional tensor) tensor(3.1416) >>> torch.tensor([]) # Create an empty tensor (of size (0,)) tensor([]) """.format(**factory_data_common_args)) add_docstr(torch.range, r""" range(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor + 1` with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is the gap between two values in the tensor. .. math:: \text{out}_{i+1} = \text{out}_i + \text{step}. """ + r""" .. warning:: This function is deprecated in favor of :func:`torch.arange`. Args: start (float): the starting value for the set of points. Default: ``0``. end (float): the ending value for the set of points step (float): the gap between each pair of adjacent points. Default: ``1``. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.range(1, 4) tensor([ 1., 2., 3., 4.]) >>> torch.range(1, 4, 0.5) tensor([ 1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000, 4.0000]) """.format(**factory_common_args)) add_docstr(torch.arange, r""" arange(start=0, end, step=1, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a 1-D tensor of size :math:`\left\lfloor \frac{\text{end} - \text{start}}{\text{step}} \right\rfloor` with values from the interval ``[start, end)`` taken with common difference :attr:`step` beginning from `start`. Note that non-integer :attr:`step` is subject to floating point rounding errors when comparing against :attr:`end`; to avoid inconsistency, we advise adding a small epsilon to :attr:`end` in such cases. .. math:: \text{out}_{{i+1}} = \text{out}_{i} + \text{step} """ + r""" Args: start (Number): the starting value for the set of points. Default: ``0``. end (Number): the ending value for the set of points step (Number): the gap between each pair of adjacent points. Default: ``1``. {out} {dtype} If `dtype` is not given, infer the data type from the other input arguments. If any of `start`, `end`, or `stop` are floating-point, the `dtype` is inferred to be the default dtype, see :meth:`~torch.get_default_dtype`. Otherwise, the `dtype` is inferred to be `torch.int64`. {layout} {device} {requires_grad} Example:: >>> torch.arange(5) tensor([ 0, 1, 2, 3, 4]) >>> torch.arange(1, 4) tensor([ 1, 2, 3]) >>> torch.arange(1, 2.5, 0.5) tensor([ 1.0000, 1.5000, 2.0000]) """.format(**factory_common_args)) add_docstr(torch.remainder, r""" remainder(input, divisor, out=None) -> Tensor Computes the element-wise remainder of division. The divisor and dividend may contain both for integer and floating point numbers. The remainder has the same sign as the divisor. When :attr:`divisor` is a tensor, the shapes of :attr:`input` and :attr:`divisor` must be :ref:`broadcastable <broadcasting-semantics>`. Args: input (Tensor): the dividend divisor (Tensor or float): the divisor that may be either a number or a Tensor of the same shape as the dividend out (Tensor, optional): the output tensor Example:: >>> torch.remainder(torch.tensor([-3., -2, -1, 1, 2, 3]), 2) tensor([ 1., 0., 1., 1., 0., 1.]) >>> torch.remainder(torch.tensor([1., 2, 3, 4, 5]), 1.5) tensor([ 1.0000, 0.5000, 0.0000, 1.0000, 0.5000]) .. seealso:: :func:`torch.fmod`, which computes the element-wise remainder of division equivalently to the C library function ``fmod()``. """) add_docstr(torch.renorm, r""" renorm(input, p, dim, maxnorm, out=None) -> Tensor Returns a tensor where each sub-tensor of :attr:`input` along dimension :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower than the value :attr:`maxnorm` .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged Args: input (Tensor): the input tensor p (float): the power for the norm computation dim (int): the dimension to slice over to get the sub-tensors maxnorm (float): the maximum norm to keep each sub-tensor under out (Tensor, optional): the output tensor Example:: >>> x = torch.ones(3, 3) >>> x[1].fill_(2) tensor([ 2., 2., 2.]) >>> x[2].fill_(3) tensor([ 3., 3., 3.]) >>> x tensor([[ 1., 1., 1.], [ 2., 2., 2.], [ 3., 3., 3.]]) >>> torch.renorm(x, 1, 0, 5) tensor([[ 1.0000, 1.0000, 1.0000], [ 1.6667, 1.6667, 1.6667], [ 1.6667, 1.6667, 1.6667]]) """) add_docstr(torch.reshape, r""" reshape(input, shape) -> Tensor Returns a tensor with the same data and number of elements as :attr:`input`, but with the specified shape. When possible, the returned tensor will be a view of :attr:`input`. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior. See :meth:`torch.Tensor.view` on when it is possible to return a view. A single dimension may be -1, in which case it's inferred from the remaining dimensions and the number of elements in :attr:`input`. Args: input (Tensor): the tensor to be reshaped shape (tuple of ints): the new shape Example:: >>> a = torch.arange(4.) >>> torch.reshape(a, (2, 2)) tensor([[ 0., 1.], [ 2., 3.]]) >>> b = torch.tensor([[0, 1], [2, 3]]) >>> torch.reshape(b, (-1,)) tensor([ 0, 1, 2, 3]) """) add_docstr(torch.round, r""" round(input, out=None) -> Tensor Returns a new tensor with each of the elements of :attr:`input` rounded to the closest integer. Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.9920, 0.6077, 0.9734, -1.0362]) >>> torch.round(a) tensor([ 1., 1., 1., -1.]) """) add_docstr(torch.rsqrt, r""" rsqrt(input, out=None) -> Tensor Returns a new tensor with the reciprocal of the square-root of each of the elements of :attr:`input`. .. math:: \text{out}_{i} = \frac{1}{\sqrt{\text{input}_{i}}} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.0370, 0.2970, 1.5420, -0.9105]) >>> torch.rsqrt(a) tensor([ nan, 1.8351, 0.8053, nan]) """) add_docstr(torch.set_flush_denormal, r""" set_flush_denormal(mode) -> bool Disables denormal floating numbers on CPU. Returns ``True`` if your system supports flushing denormal numbers and it successfully configures flush denormal mode. :meth:`~torch.set_flush_denormal` is only supported on x86 architectures supporting SSE3. Args: mode (bool): Controls whether to enable flush denormal mode or not Example:: >>> torch.set_flush_denormal(True) True >>> torch.tensor([1e-323], dtype=torch.float64) tensor([ 0.], dtype=torch.float64) >>> torch.set_flush_denormal(False) True >>> torch.tensor([1e-323], dtype=torch.float64) tensor(9.88131e-324 * [ 1.0000], dtype=torch.float64) """) add_docstr(torch.set_num_threads, r""" set_num_threads(int) Sets the number of OpenMP threads used for parallelizing CPU operations """) add_docstr(torch.sigmoid, r""" sigmoid(input, out=None) -> Tensor Returns a new tensor with the sigmoid of the elements of :attr:`input`. .. math:: \text{out}_{i} = \frac{1}{1 + e^{-\text{input}_{i}}} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.9213, 1.0887, -0.8858, -1.7683]) >>> torch.sigmoid(a) tensor([ 0.7153, 0.7481, 0.2920, 0.1458]) """) add_docstr(torch.sign, r""" sign(input, out=None) -> Tensor Returns a new tensor with the sign of the elements of :attr:`input`. Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.tensor([0.7, -1.2, 0., 2.3]) >>> a tensor([ 0.7000, -1.2000, 0.0000, 2.3000]) >>> torch.sign(a) tensor([ 1., -1., 0., 1.]) """) add_docstr(torch.sin, r""" sin(input, out=None) -> Tensor Returns a new tensor with the sine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \sin(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-0.5461, 0.1347, -2.7266, -0.2746]) >>> torch.sin(a) tensor([-0.5194, 0.1343, -0.4032, -0.2711]) """) add_docstr(torch.sinh, r""" sinh(input, out=None) -> Tensor Returns a new tensor with the hyperbolic sine of the elements of :attr:`input`. .. math:: \text{out}_{i} = \sinh(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.5380, -0.8632, -0.1265, 0.9399]) >>> torch.sinh(a) tensor([ 0.5644, -0.9744, -0.1268, 1.0845]) """) add_docstr(torch.sort, r""" sort(input, dim=None, descending=False, out=None) -> (Tensor, LongTensor) Sorts the elements of the :attr:`input` tensor along a given dimension in ascending order by value. If :attr:`dim` is not given, the last dimension of the `input` is chosen. If :attr:`descending` is ``True`` then the elements are sorted in descending order by value. A tuple of (sorted_tensor, sorted_indices) is returned, where the sorted_indices are the indices of the elements in the original `input` tensor. Args: input (Tensor): the input tensor dim (int, optional): the dimension to sort along descending (bool, optional): controls the sorting order (ascending or descending) out (tuple, optional): the output tuple of (`Tensor`, `LongTensor`) that can be optionally given to be used as output buffers Example:: >>> x = torch.randn(3, 4) >>> sorted, indices = torch.sort(x) >>> sorted tensor([[-0.2162, 0.0608, 0.6719, 2.3332], [-0.5793, 0.0061, 0.6058, 0.9497], [-0.5071, 0.3343, 0.9553, 1.0960]]) >>> indices tensor([[ 1, 0, 2, 3], [ 3, 1, 0, 2], [ 0, 3, 1, 2]]) >>> sorted, indices = torch.sort(x, 0) >>> sorted tensor([[-0.5071, -0.2162, 0.6719, -0.5793], [ 0.0608, 0.0061, 0.9497, 0.3343], [ 0.6058, 0.9553, 1.0960, 2.3332]]) >>> indices tensor([[ 2, 0, 0, 1], [ 0, 1, 1, 2], [ 1, 2, 2, 0]]) """) add_docstr(torch.sparse_coo_tensor, r""" sparse_coo_tensor(indices, values, size=None, dtype=None, device=None, requires_grad=False) -> Tensor Constructs a sparse tensors in COO(rdinate) format with non-zero elements at the given :attr:`indices` with the given :attr:`values`. A sparse tensor can be `uncoalesced`, in that case, there are duplicate coordinates in the indices, and the value at that index is the sum of all duplicate value entries: `torch.sparse`_. Args: indices (array_like): Initial data for the tensor. Can be a list, tuple, NumPy ``ndarray``, scalar, and other types. Will be cast to a :class:`torch.LongTensor` internally. The indices are the coordinates of the non-zero values in the matrix, and thus should be two-dimensional where the first dimension is the number of tensor dimensions and the second dimension is the number of non-zero values. values (array_like): Initial values for the tensor. Can be a list, tuple, NumPy ``ndarray``, scalar, and other types. size (list, tuple, or :class:`torch.Size`, optional): Size of the sparse tensor. If not provided the size will be inferred as the minimum size big enough to hold all non-zero elements. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor. Default: if None, infers data type from :attr:`values`. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see :func:`torch.set_default_tensor_type`). :attr:`device` will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: ``False``. Example:: >>> i = torch.tensor([[0, 1, 1], [2, 0, 2]]) >>> v = torch.tensor([3, 4, 5], dtype=torch.float32) >>> torch.sparse_coo_tensor(i, v, [2, 4]) tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), size=(2, 4), nnz=3, layout=torch.sparse_coo) >>> torch.sparse_coo_tensor(i, v) # Shape inference tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), size=(2, 3), nnz=3, layout=torch.sparse_coo) >>> torch.sparse_coo_tensor(i, v, [2, 4], dtype=torch.float64, device=torch.device('cuda:0')) tensor(indices=tensor([[0, 1, 1], [2, 0, 2]]), values=tensor([3., 4., 5.]), device='cuda:0', size=(2, 4), nnz=3, dtype=torch.float64, layout=torch.sparse_coo) # Create an empty sparse tensor with the following invariants: # 1. sparse_dim + dense_dim = len(SparseTensor.shape) # 2. SparseTensor._indices().shape = (sparse_dim, nnz) # 3. SparseTensor._values().shape = (nnz, SparseTensor.shape[sparse_dim:]) # # For instance, to create an empty sparse tensor with nnz = 0, dense_dim = 0 and # sparse_dim = 1 (hence indices is a 2D tensor of shape = (1, 0)) >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), [], [1]) tensor(indices=tensor([], size=(1, 0)), values=tensor([], size=(0,)), size=(1,), nnz=0, layout=torch.sparse_coo) # and to create an empty sparse tensor with nnz = 0, dense_dim = 1 and # sparse_dim = 1 >>> S = torch.sparse_coo_tensor(torch.empty([1, 0]), torch.empty([0, 2]), [1, 2]) tensor(indices=tensor([], size=(1, 0)), values=tensor([], size=(0, 2)), size=(1, 2), nnz=0, layout=torch.sparse_coo) .. _torch.sparse: https://pytorch.org/docs/stable/sparse.html """) add_docstr(torch.sqrt, r""" sqrt(input, out=None) -> Tensor Returns a new tensor with the square-root of the elements of :attr:`input`. .. math:: \text{out}_{i} = \sqrt{\text{input}_{i}} Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-2.0755, 1.0226, 0.0831, 0.4806]) >>> torch.sqrt(a) tensor([ nan, 1.0112, 0.2883, 0.6933]) """) add_docstr(torch.squeeze, r""" squeeze(input, dim=None, out=None) -> Tensor Returns a tensor with all the dimensions of :attr:`input` of size `1` removed. For example, if `input` is of shape: :math:`(A \times 1 \times B \times C \times 1 \times D)` then the `out` tensor will be of shape: :math:`(A \times B \times C \times D)`. When :attr:`dim` is given, a squeeze operation is done only in the given dimension. If `input` is of shape: :math:`(A \times 1 \times B)`, ``squeeze(input, 0)`` leaves the tensor unchanged, but ``squeeze(input, 1)`` will squeeze the tensor to the shape :math:`(A \times B)`. .. note:: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other. Args: input (Tensor): the input tensor dim (int, optional): if given, the input will be squeezed only in this dimension out (Tensor, optional): the output tensor Example:: >>> x = torch.zeros(2, 1, 2, 1, 2) >>> x.size() torch.Size([2, 1, 2, 1, 2]) >>> y = torch.squeeze(x) >>> y.size() torch.Size([2, 2, 2]) >>> y = torch.squeeze(x, 0) >>> y.size() torch.Size([2, 1, 2, 1, 2]) >>> y = torch.squeeze(x, 1) >>> y.size() torch.Size([2, 2, 1, 2]) """) add_docstr(torch.std, r""" .. function:: std(input, unbiased=True) -> Tensor Returns the standard-deviation of all elements in the :attr:`input` tensor. If :attr:`unbiased` is ``False``, then the standard-deviation will be calculated via the biased estimator. Otherwise, Bessel's correction will be used. Args: input (Tensor): the input tensor unbiased (bool): whether to use the unbiased estimation or not Example:: >>> a = torch.randn(1, 3) >>> a tensor([[-0.8166, -1.3802, -0.3560]]) >>> torch.std(a) tensor(0.5130) .. function:: std(input, dim, keepdim=False, unbiased=True, out=None) -> Tensor Returns the standard-deviation of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 fewer dimension than :attr:`input`. If :attr:`unbiased` is ``False``, then the standard-deviation will be calculated via the biased estimator. Otherwise, Bessel's correction will be used. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not unbiased (bool): whether to use the unbiased estimation or not out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 4) >>> a tensor([[ 0.2035, 1.2959, 1.8101, -0.4644], [ 1.5027, -0.3270, 0.5905, 0.6538], [-1.5745, 1.3330, -0.5596, -0.6548], [ 0.1264, -0.5080, 1.6420, 0.1992]]) >>> torch.std(a, dim=1) tensor([ 1.0311, 0.7477, 1.2204, 0.9087]) """) add_docstr(torch.sum, r""" .. function:: sum(input, dtype=None) -> Tensor Returns the sum of all elements in the :attr:`input` tensor. Args: input (Tensor): the input tensor {dtype} Example:: >>> a = torch.randn(1, 3) >>> a tensor([[ 0.1133, -0.9567, 0.2958]]) >>> torch.sum(a) tensor(-0.5475) .. function:: sum(input, dim, keepdim=False, dtype=None) -> Tensor Returns the sum of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. If :attr:`dim` is a list of dimensions, reduce over all of them. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension(s) :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 (or ``len(dim)``) fewer dimension(s). Args: input (Tensor): the input tensor dim (int or tuple of ints): the dimension or dimensions to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not {dtype} Example:: >>> a = torch.randn(4, 4) >>> a tensor([[ 0.0569, -0.2475, 0.0737, -0.3429], [-0.2993, 0.9138, 0.9337, -1.6864], [ 0.1132, 0.7892, -0.1003, 0.5688], [ 0.3637, -0.9906, -0.4752, -1.5197]]) >>> torch.sum(a, 1) tensor([-0.4598, -0.1381, 1.3708, -2.6217]) >>> b = torch.arange(4 * 5 * 6).view(4, 5, 6) >>> torch.sum(b, (2, 1)) tensor([ 435., 1335., 2235., 3135.]) """.format(**reduceops_common_args)) add_docstr(torch.svd, r""" svd(input, some=True, compute_uv=True, out=None) -> (Tensor, Tensor, Tensor) `U, S, V = torch.svd(A)` returns the singular value decomposition of a real matrix `A` of size `(n x m)` such that :math:`A = USV^T`. `U` is of shape :math:`(n \times n)`. `S` is a diagonal matrix of shape :math:`(n \times m)`, represented as a vector of size :math:`\min(n, m)` containing the non-negative diagonal entries. `V` is of shape :math:`(m \times m)`. If :attr:`some` is ``True`` (default), the returned `U` and `V` matrices will contain only :math:`min(n, m)` orthonormal columns. If :attr:`compute_uv` is ``False``, the returned `U` and `V` matrices will be zero matrices of shape :math:`(n \times n)` and :math:`(m \times m)` respectively. :attr:`some` will be ignored here. .. note:: The implementation of SVD on CPU uses the LAPACK routine `?gesdd` (a divide-and-conquer algorithm) instead of `?gesvd` for speed. Analogously, the SVD on GPU uses the MAGMA routine `gesdd` as well. .. note:: Irrespective of the original strides, the returned matrix `U` will be transposed, i.e. with strides `(1, n)` instead of `(n, 1)`. .. note:: Extra care needs to be taken when backward through `U` and `V` outputs. Such operation is really only stable when :attr:`input` is full rank with all distinct singular values. Otherwise, ``NaN`` can appear as the gradients are not properly defined. Also, notice that double backward will usually do an additional backward through `U` and `V` even if the original backward is only on `S`. .. note:: When :attr:`some` = ``False``, the gradients on ``U[:, min(n, m):]`` and ``V[:, min(n, m):]`` will be ignored in backward as those vectors can be arbitrary bases of the subspaces. .. note:: When :attr:`compute_uv` = ``False``, backward cannot be performed since ``U`` and ``V`` from the forward pass is required for the backward operation. Args: input (Tensor): the input 2-D tensor some (bool, optional): controls the shape of returned `U` and `V` out (tuple, optional): the output tuple of tensors Example:: >>> a = torch.tensor([[8.79, 6.11, -9.15, 9.57, -3.49, 9.84], [9.93, 6.91, -7.93, 1.64, 4.02, 0.15], [9.83, 5.04, 4.86, 8.83, 9.80, -8.99], [5.45, -0.27, 4.85, 0.74, 10.00, -6.02], [3.16, 7.98, 3.01, 5.80, 4.27, -5.31]]).t() >>> u, s, v = torch.svd(a) >>> u tensor([[-0.5911, 0.2632, 0.3554, 0.3143, 0.2299], [-0.3976, 0.2438, -0.2224, -0.7535, -0.3636], [-0.0335, -0.6003, -0.4508, 0.2334, -0.3055], [-0.4297, 0.2362, -0.6859, 0.3319, 0.1649], [-0.4697, -0.3509, 0.3874, 0.1587, -0.5183], [ 0.2934, 0.5763, -0.0209, 0.3791, -0.6526]]) >>> s tensor([ 27.4687, 22.6432, 8.5584, 5.9857, 2.0149]) >>> v tensor([[-0.2514, 0.8148, -0.2606, 0.3967, -0.2180], [-0.3968, 0.3587, 0.7008, -0.4507, 0.1402], [-0.6922, -0.2489, -0.2208, 0.2513, 0.5891], [-0.3662, -0.3686, 0.3859, 0.4342, -0.6265], [-0.4076, -0.0980, -0.4933, -0.6227, -0.4396]]) >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) tensor(1.00000e-06 * 9.3738) """) add_docstr(torch.symeig, r""" symeig(input, eigenvectors=False, upper=True, out=None) -> (Tensor, Tensor) This function returns eigenvalues and eigenvectors of a real symmetric matrix :attr:`input`, represented by a tuple :math:`(e, V)`. :attr:`input` and :math:`V` are :math:`(m \times m)` matrices and :math:`e` is a :math:`m` dimensional vector. This function calculates all eigenvalues (and vectors) of :attr:`input` such that :math:`\text{input} = V \text{diag}(e) V^T`. The boolean argument :attr:`eigenvectors` defines computation of eigenvectors or eigenvalues only. If it is ``False``, only eigenvalues are computed. If it is ``True``, both eigenvalues and eigenvectors are computed. Since the input matrix :attr:`input` is supposed to be symmetric, only the upper triangular portion is used by default. If :attr:`upper` is ``False``, then lower triangular portion is used. Note: Irrespective of the original strides, the returned matrix `V` will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)`. Args: input (Tensor): the input symmetric matrix eigenvectors(boolean, optional): controls whether eigenvectors have to be computed upper(boolean, optional): controls whether to consider upper-triangular or lower-triangular region out (tuple, optional): the output tuple of (Tensor, Tensor) Returns: (Tensor, Tensor): A tuple containing - **e** (*Tensor*): Shape :math:`(m)`. Each element is an eigenvalue of ``input``, The eigenvalues are in ascending order. - **V** (*Tensor*): Shape :math:`(m \times m)`. If ``eigenvectors=False``, it's a tensor filled with zeros. Otherwise, this tensor contains the orthonormal eigenvectors of the ``input``. Examples:: >>> a = torch.tensor([[ 1.96, 0.00, 0.00, 0.00, 0.00], [-6.49, 3.80, 0.00, 0.00, 0.00], [-0.47, -6.39, 4.17, 0.00, 0.00], [-7.20, 1.50, -1.51, 5.70, 0.00], [-0.65, -6.34, 2.67, 1.80, -7.10]]).t() >>> e, v = torch.symeig(a, eigenvectors=True) >>> e tensor([-11.0656, -6.2287, 0.8640, 8.8655, 16.0948]) >>> v tensor([[-0.2981, -0.6075, 0.4026, -0.3745, 0.4896], [-0.5078, -0.2880, -0.4066, -0.3572, -0.6053], [-0.0816, -0.3843, -0.6600, 0.5008, 0.3991], [-0.0036, -0.4467, 0.4553, 0.6204, -0.4564], [-0.8041, 0.4480, 0.1725, 0.3108, 0.1622]]) """) add_docstr(torch.t, r""" t(input) -> Tensor Expects :attr:`input` to be a matrix (2-D tensor) and transposes dimensions 0 and 1. Can be seen as a short-hand function for ``transpose(input, 0, 1)``. Args: input (Tensor): the input tensor Example:: >>> x = torch.randn(2, 3) >>> x tensor([[ 0.4875, 0.9158, -0.5872], [ 0.3938, -0.6929, 0.6932]]) >>> torch.t(x) tensor([[ 0.4875, 0.3938], [ 0.9158, -0.6929], [-0.5872, 0.6932]]) """) add_docstr(torch.flip, r""" flip(input, dims) -> Tensor Reverse the order of a n-D tensor along given axis in dims. Args: input (Tensor): the input tensor dims (a list or tuple): axis to flip on Example:: >>> x = torch.arange(8).view(2, 2, 2) >>> x tensor([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]]]) >>> torch.flip(x, [0, 1]) tensor([[[ 6, 7], [ 4, 5]], [[ 2, 3], [ 0, 1]]]) """) add_docstr(torch.roll, r""" roll(input, shifts, dims=None) -> Tensor Roll the tensor along the given dimension(s). Elements that are shifted beyond the last position are re-introduced at the first position. If a dimension is not specified, the tensor will be flattened before rolling and then restored to the original shape. Args: input (Tensor): the input tensor shifts (int or tuple of ints): The number of places by which the elements of the tensor are shifted. If shifts is a tuple, dims must be a tuple of the same size, and each dimension will be rolled by the corresponding value dims (int or tuple of ints): Axis along which to roll Example:: >>> x = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]).view(4, 2) >>> x tensor([[1, 2], [3, 4], [5, 6], [7, 8]]) >>> torch.roll(x, 1, 0) tensor([[7, 8], [1, 2], [3, 4], [5, 6]]) >>> torch.roll(x, -1, 0) tensor([[3, 4], [5, 6], [7, 8], [1, 2]]) >>> torch.roll(x, shifts=(2, 1), dims=(0, 1)) tensor([[6, 5], [8, 7], [2, 1], [4, 3]]) """) add_docstr(torch.rot90, r""" rot90(input, k, dims) -> Tensor Rotate a n-D tensor by 90 degrees in the plane specified by dims axis. Rotation direction is from the first towards the second axis if k > 0, and from the second towards the first for k < 0. Args: input (Tensor): the input tensor k (int): number of times to rotate dims (a list or tuple): axis to rotate Example:: >>> x = torch.arange(4).view(2, 2) >>> x tensor([[0, 1], [2, 3]]) >>> torch.rot90(x, 1, [0, 1]) tensor([[1, 3], [0, 2]]) >>> x = torch.arange(8).view(2, 2, 2) >>> x tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) >>> torch.rot90(x, 1, [1, 2]) tensor([[[1, 3], [0, 2]], [[5, 7], [4, 6]]]) """) add_docstr(torch.take, r""" take(input, indices) -> Tensor Returns a new tensor with the elements of :attr:`input` at the given indices. The input tensor is treated as if it were viewed as a 1-D tensor. The result takes the same shape as the indices. Args: input (Tensor): the input tensor indices (LongTensor): the indices into tensor Example:: >>> src = torch.tensor([[4, 3, 5], [6, 7, 8]]) >>> torch.take(src, torch.tensor([0, 2, 5])) tensor([ 4, 5, 8]) """) add_docstr(torch.tan, r""" tan(input, out=None) -> Tensor Returns a new tensor with the tangent of the elements of :attr:`input`. .. math:: \text{out}_{i} = \tan(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([-1.2027, -1.7687, 0.4412, -1.3856]) >>> torch.tan(a) tensor([-2.5930, 4.9859, 0.4722, -5.3366]) """) add_docstr(torch.tanh, r""" tanh(input, out=None) -> Tensor Returns a new tensor with the hyperbolic tangent of the elements of :attr:`input`. .. math:: \text{out}_{i} = \tanh(\text{input}_{i}) Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 0.8986, -0.7279, 1.1745, 0.2611]) >>> torch.tanh(a) tensor([ 0.7156, -0.6218, 0.8257, 0.2553]) """) add_docstr(torch.topk, r""" topk(input, k, dim=None, largest=True, sorted=True, out=None) -> (Tensor, LongTensor) Returns the :attr:`k` largest elements of the given :attr:`input` tensor along a given dimension. If :attr:`dim` is not given, the last dimension of the `input` is chosen. If :attr:`largest` is ``False`` then the `k` smallest elements are returned. A tuple of `(values, indices)` is returned, where the `indices` are the indices of the elements in the original `input` tensor. The boolean option :attr:`sorted` if ``True``, will make sure that the returned `k` elements are themselves sorted Args: input (Tensor): the input tensor k (int): the k in "top-k" dim (int, optional): the dimension to sort along largest (bool, optional): controls whether to return largest or smallest elements sorted (bool, optional): controls whether to return the elements in sorted order out (tuple, optional): the output tuple of (Tensor, LongTensor) that can be optionally given to be used as output buffers Example:: >>> x = torch.arange(1., 6.) >>> x tensor([ 1., 2., 3., 4., 5.]) >>> torch.topk(x, 3) (tensor([ 5., 4., 3.]), tensor([ 4, 3, 2])) """) add_docstr(torch.trace, r""" trace(input) -> Tensor Returns the sum of the elements of the diagonal of the input 2-D matrix. Example:: >>> x = torch.arange(1., 10.).view(3, 3) >>> x tensor([[ 1., 2., 3.], [ 4., 5., 6.], [ 7., 8., 9.]]) >>> torch.trace(x) tensor(15.) """) add_docstr(torch.transpose, r""" transpose(input, dim0, dim1) -> Tensor Returns a tensor that is a transposed version of :attr:`input`. The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. The resulting :attr:`out` tensor shares it's underlying storage with the :attr:`input` tensor, so changing the content of one would change the content of the other. Args: input (Tensor): the input tensor dim0 (int): the first dimension to be transposed dim1 (int): the second dimension to be transposed Example:: >>> x = torch.randn(2, 3) >>> x tensor([[ 1.0028, -0.9893, 0.5809], [-0.1669, 0.7299, 0.4942]]) >>> torch.transpose(x, 0, 1) tensor([[ 1.0028, -0.1669], [-0.9893, 0.7299], [ 0.5809, 0.4942]]) """) add_docstr(torch.tril, r""" tril(input, diagonal=0, out=None) -> Tensor Returns the lower triangular part of the matrix (2-D tensor) or batch of matrices :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. The lower triangular part of the matrix is defined as the elements on and below the diagonal. The argument :attr:`diagonal` controls which diagonal to consider. If :attr:`diagonal` = 0, all elements on and below the main diagonal are retained. A positive value includes just as many diagonals above the main diagonal, and similarly a negative value excludes just as many diagonals below the main diagonal. The main diagonal are the set of indices :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where :math:`d_{1}, d_{2}` are the dimensions of the matrix. Args: input (Tensor): the input tensor diagonal (int, optional): the diagonal to consider out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(3, 3) >>> a tensor([[-1.0813, -0.8619, 0.7105], [ 0.0935, 0.1380, 2.2112], [-0.3409, -0.9828, 0.0289]]) >>> torch.tril(a) tensor([[-1.0813, 0.0000, 0.0000], [ 0.0935, 0.1380, 0.0000], [-0.3409, -0.9828, 0.0289]]) >>> b = torch.randn(4, 6) >>> b tensor([[ 1.2219, 0.5653, -0.2521, -0.2345, 1.2544, 0.3461], [ 0.4785, -0.4477, 0.6049, 0.6368, 0.8775, 0.7145], [ 1.1502, 3.2716, -1.1243, -0.5413, 0.3615, 0.6864], [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0978]]) >>> torch.tril(b, diagonal=1) tensor([[ 1.2219, 0.5653, 0.0000, 0.0000, 0.0000, 0.0000], [ 0.4785, -0.4477, 0.6049, 0.0000, 0.0000, 0.0000], [ 1.1502, 3.2716, -1.1243, -0.5413, 0.0000, 0.0000], [-0.0614, -0.7344, -1.3164, -0.7648, -1.4024, 0.0000]]) >>> torch.tril(b, diagonal=-1) tensor([[ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [ 0.4785, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [ 1.1502, 3.2716, 0.0000, 0.0000, 0.0000, 0.0000], [-0.0614, -0.7344, -1.3164, 0.0000, 0.0000, 0.0000]]) """) add_docstr(torch.triu, r""" triu(input, diagonal=0, out=None) -> Tensor Returns the upper triangular part of a matrix (2-D tensor) or batch of matrices :attr:`input`, the other elements of the result tensor :attr:`out` are set to 0. The upper triangular part of the matrix is defined as the elements on and above the diagonal. The argument :attr:`diagonal` controls which diagonal to consider. If :attr:`diagonal` = 0, all elements on and below the main diagonal are retained. A positive value excludes just as many diagonals above the main diagonal, and similarly a negative value includes just as many diagonals below the main diagonal. The main diagonal are the set of indices :math:`\lbrace (i, i) \rbrace` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where :math:`d_{1}, d_{2}` are the dimensions of the matrix. Args: input (Tensor): the input tensor diagonal (int, optional): the diagonal to consider out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(3, 3) >>> a tensor([[ 0.2309, 0.5207, 2.0049], [ 0.2072, -1.0680, 0.6602], [ 0.3480, -0.5211, -0.4573]]) >>> torch.triu(a) tensor([[ 0.2309, 0.5207, 2.0049], [ 0.0000, -1.0680, 0.6602], [ 0.0000, 0.0000, -0.4573]]) >>> torch.triu(a, diagonal=1) tensor([[ 0.0000, 0.5207, 2.0049], [ 0.0000, 0.0000, 0.6602], [ 0.0000, 0.0000, 0.0000]]) >>> torch.triu(a, diagonal=-1) tensor([[ 0.2309, 0.5207, 2.0049], [ 0.2072, -1.0680, 0.6602], [ 0.0000, -0.5211, -0.4573]]) >>> b = torch.randn(4, 6) >>> b tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], [ 0.4333, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], [-0.9888, 1.0679, -1.3337, -1.6556, 0.4798, 0.2830]]) >>> torch.triu(b, diagonal=1) tensor([[ 0.0000, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], [ 0.0000, 0.0000, -1.2919, 1.3378, -0.1768, -1.0857], [ 0.0000, 0.0000, 0.0000, -1.0432, 0.9348, -0.4410], [ 0.0000, 0.0000, 0.0000, 0.0000, 0.4798, 0.2830]]) >>> torch.triu(b, diagonal=-1) tensor([[ 0.5876, -0.0794, -1.8373, 0.6654, 0.2604, 1.5235], [-0.2447, 0.9556, -1.2919, 1.3378, -0.1768, -1.0857], [ 0.0000, 0.3146, 0.6576, -1.0432, 0.9348, -0.4410], [ 0.0000, 0.0000, -1.3337, -1.6556, 0.4798, 0.2830]]) """) add_docstr(torch.trtrs, r""" trtrs(b, A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) Solves a system of equations with a triangular coefficient matrix :math:`A` and multiple right-hand sides :attr:`b`. In particular, solves :math:`AX = b` and assumes :math:`A` is upper-triangular with the default keyword arguments. Args: A (Tensor): the input triangular coefficient matrix b (Tensor): multiple right-hand sides. Each column of :math:`b` is a right-hand side for the system of equations. upper (bool, optional): whether to solve the upper-triangular system of equations (default) or the lower-triangular system of equations. Default: True. transpose (bool, optional): whether :math:`A` should be transposed before being sent into the solver. Default: False. unitriangular (bool, optional): whether :math:`A` is unit triangular. If True, the diagonal elements of :math:`A` are assumed to be 1 and not referenced from :math:`A`. Default: False. Returns: A tuple :math:`(X, M)` where :math:`M` is a clone of :math:`A` and :math:`X` is the solution to :math:`AX = b` (or whatever variant of the system of equations, depending on the keyword arguments.) Shape: - A: :math:`(N, N)` - b: :math:`(N, C)` - output[0]: :math:`(N, C)` - output[1]: :math:`(N, N)` Examples:: >>> A = torch.randn(2, 2).triu() >>> A tensor([[ 1.1527, -1.0753], [ 0.0000, 0.7986]]) >>> b = torch.randn(2, 3) >>> b tensor([[-0.0210, 2.3513, -1.5492], [ 1.5429, 0.7403, -1.0243]]) >>> torch.trtrs(b, A) (tensor([[ 1.7840, 2.9045, -2.5405], [ 1.9319, 0.9269, -1.2826]]), tensor([[ 1.1527, -1.0753], [ 0.0000, 0.7986]])) """) add_docstr(torch.trunc, r""" trunc(input, out=None) -> Tensor Returns a new tensor with the truncated integer values of the elements of :attr:`input`. Args: input (Tensor): the input tensor out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4) >>> a tensor([ 3.4742, 0.5466, -0.8008, -0.9079]) >>> torch.trunc(a) tensor([ 3., 0., -0., -0.]) """) add_docstr(torch.unsqueeze, r""" unsqueeze(input, dim, out=None) -> Tensor Returns a new tensor with a dimension of size one inserted at the specified position. The returned tensor shares the same underlying data with this tensor. A :attr:`dim` value within the range ``[-input.dim() - 1, input.dim() + 1)`` can be used. Negative :attr:`dim` will correspond to :meth:`unsqueeze` applied at :attr:`dim` = ``dim + input.dim() + 1``. Args: input (Tensor): the input tensor dim (int): the index at which to insert the singleton dimension out (Tensor, optional): the output tensor Example:: >>> x = torch.tensor([1, 2, 3, 4]) >>> torch.unsqueeze(x, 0) tensor([[ 1, 2, 3, 4]]) >>> torch.unsqueeze(x, 1) tensor([[ 1], [ 2], [ 3], [ 4]]) """) add_docstr(torch.var, r""" .. function:: var(input, unbiased=True) -> Tensor Returns the variance of all elements in the :attr:`input` tensor. If :attr:`unbiased` is ``False``, then the variance will be calculated via the biased estimator. Otherwise, Bessel's correction will be used. Args: input (Tensor): the input tensor unbiased (bool): whether to use the unbiased estimation or not Example:: >>> a = torch.randn(1, 3) >>> a tensor([[-0.3425, -1.2636, -0.4864]]) >>> torch.var(a) tensor(0.2455) .. function:: var(input, dim, keepdim=False, unbiased=True, out=None) -> Tensor Returns the variance of each row of the :attr:`input` tensor in the given dimension :attr:`dim`. If :attr:`keepdim` is ``True``, the output tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the outputs tensor having 1 fewer dimension than :attr:`input`. If :attr:`unbiased` is ``False``, then the variance will be calculated via the biased estimator. Otherwise, Bessel's correction will be used. Args: input (Tensor): the input tensor dim (int): the dimension to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not unbiased (bool): whether to use the unbiased estimation or not out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 4) >>> a tensor([[-0.3567, 1.7385, -1.3042, 0.7423], [ 1.3436, -0.1015, -0.9834, -0.8438], [ 0.6056, 0.1089, -0.3112, -1.4085], [-0.7700, 0.6074, -0.1469, 0.7777]]) >>> torch.var(a, 1) tensor([ 1.7444, 1.1363, 0.7356, 0.5112]) """) add_docstr(torch.zeros, r""" zeros(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with the scalar value `0`, with the shape defined by the variable argument :attr:`sizes`. Args: sizes (int...): a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.zeros(2, 3) tensor([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> torch.zeros(5) tensor([ 0., 0., 0., 0., 0.]) """.format(**factory_common_args)) add_docstr(torch.zeros_like, r""" zeros_like(input, dtype=None, layout=None, device=None, requires_grad=False) -> Tensor Returns a tensor filled with the scalar value `0`, with the same size as :attr:`input`. ``torch.zeros_like(input)`` is equivalent to ``torch.zeros(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. .. warning:: As of 0.4, this function does not support an :attr:`out` keyword. As an alternative, the old ``torch.zeros_like(input, out=output)`` is equivalent to ``torch.zeros(input.size(), out=output)``. Args: {input} {dtype} {layout} {device} {requires_grad} Example:: >>> input = torch.empty(2, 3) >>> torch.zeros_like(input) tensor([[ 0., 0., 0.], [ 0., 0., 0.]]) """.format(**factory_like_common_args)) add_docstr(torch.btrifact_with_info, r""" btrifact_with_info(A, pivot=True) -> (Tensor, IntTensor, IntTensor) Batch LU factorization with additional error information. This is a version of :meth:`torch.btrifact` that always creates an info `IntTensor`, and returns it as the third return value. Arguments: A (Tensor): the tensor to factor pivot (bool, optional): controls whether pivoting is done Returns: A tuple containing factorization, pivots, and an `IntTensor` where non-zero values indicate whether factorization for each minibatch sample succeeds. Example:: >>> A = torch.randn(2, 3, 3) >>> A_LU, pivots, info = A.btrifact_with_info() >>> if info.nonzero().size(0) == 0: >>> print('LU factorization succeeded for all samples!') LU factorization succeeded for all samples! """) add_docstr(torch.btrisolve, r""" btrisolve(b, LU_data, LU_pivots) -> Tensor Batch LU solve. Returns the LU solve of the linear system :math:`Ax = b`. Arguments: b (Tensor): the RHS tensor LU_data (Tensor): the pivoted LU factorization of A from :meth:`btrifact`. LU_pivots (IntTensor): the pivots of the LU factorization Example:: >>> A = torch.randn(2, 3, 3) >>> b = torch.randn(2, 3) >>> A_LU = torch.btrifact(A) >>> x = torch.btrisolve(b, *A_LU) >>> torch.norm(torch.bmm(A, x.unsqueeze(2)) - b.unsqueeze(2)) tensor(1.00000e-07 * 2.8312) """) add_docstr(torch.empty, r""" empty(*sizes, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor filled with uninitialized data. The shape of the tensor is defined by the variable argument :attr:`sizes`. Args: sizes (int...): a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.empty(2, 3) tensor(1.00000e-08 * [[ 6.3984, 0.0000, 0.0000], [ 0.0000, 0.0000, 0.0000]]) """.format(**factory_common_args)) add_docstr(torch.empty_like, r""" empty_like(input, dtype=None, layout=None, device=None, requires_grad=False) -> Tensor Returns an uninitialized tensor with the same size as :attr:`input`. ``torch.empty_like(input)`` is equivalent to ``torch.empty(input.size(), dtype=input.dtype, layout=input.layout, device=input.device)``. Args: {input} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.empty((2,3), dtype=torch.int64) tensor([[ 9.4064e+13, 2.8000e+01, 9.3493e+13], [ 7.5751e+18, 7.1428e+18, 7.5955e+18]]) """.format(**factory_like_common_args)) add_docstr(torch.full, r""" full(size, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor of size :attr:`size` filled with :attr:`fill_value`. Args: size (int...): a list, tuple, or :class:`torch.Size` of integers defining the shape of the output tensor. fill_value: the number to fill the output tensor with. {out} {dtype} {layout} {device} {requires_grad} Example:: >>> torch.full((2, 3), 3.141592) tensor([[ 3.1416, 3.1416, 3.1416], [ 3.1416, 3.1416, 3.1416]]) """.format(**factory_common_args)) add_docstr(torch.full_like, r""" full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor Returns a tensor with the same size as :attr:`input` filled with :attr:`fill_value`. ``torch.full_like(input, fill_value)`` is equivalent to ``torch.full_like(input.size(), fill_value, dtype=input.dtype, layout=input.layout, device=input.device)``. Args: {input} fill_value: the number to fill the output tensor with. {dtype} {layout} {device} {requires_grad} """.format(**factory_like_common_args)) add_docstr(torch.det, r""" det(A) -> Tensor Calculates determinant of a 2D square tensor. .. note:: Backward through :meth:`det` internally uses SVD results when :attr:`A` is not invertible. In this case, double backward through :meth:`det` will be unstable in when :attr:`A` doesn't have distinct singular values. See :meth:`~torch.svd` for details. Arguments: A (Tensor): The input 2D square tensor Example:: >>> A = torch.randn(3, 3) >>> torch.det(A) tensor(3.7641) """) add_docstr(torch.where, r""" where(condition, x, y) -> Tensor Return a tensor of elements selected from either :attr:`x` or :attr:`y`, depending on :attr:`condition`. The operation is defined as: .. math:: out_i = \begin{cases} x_i & \text{if } \text{condition}_i \\ y_i & \text{otherwise} \\ \end{cases} .. note:: The tensors :attr:`condition`, :attr:`x`, :attr:`y` must be :ref:`broadcastable <broadcasting-semantics>`. Arguments: condition (ByteTensor): When True (nonzero), yield x, otherwise yield y x (Tensor): values selected at indices where :attr:`condition` is ``True`` y (Tensor): values selected at indices where :attr:`condition` is ``False`` Returns: Tensor: A tensor of shape equal to the broadcasted shape of :attr:`condition`, :attr:`x`, :attr:`y` Example:: >>> x = torch.randn(3, 2) >>> y = torch.ones(3, 2) >>> x tensor([[-0.4620, 0.3139], [ 0.3898, -0.7197], [ 0.0478, -0.1657]]) >>> torch.where(x > 0, x, y) tensor([[ 1.0000, 0.3139], [ 0.3898, 1.0000], [ 0.0478, 1.0000]]) """) add_docstr(torch.logdet, r""" logdet(A) -> Tensor Calculates log determinant of a 2D square tensor. .. note:: Result is ``-inf`` if :attr:`A` has zero log determinant, and is ``nan`` if :attr:`A` has negative determinant. .. note:: Backward through :meth:`logdet` internally uses SVD results when :attr:`A` is not invertible. In this case, double backward through :meth:`logdet` will be unstable in when :attr:`A` doesn't have distinct singular values. See :meth:`~torch.svd` for details. Arguments: A (Tensor): The input 2D square tensor Example:: >>> A = torch.randn(3, 3) >>> torch.det(A) tensor(0.2611) >>> torch.logdet(A) tensor(-1.3430) """) add_docstr(torch.slogdet, r""" slogdet(A) -> (Tensor, Tensor) Calculates the sign and log value of a 2D square tensor's determinant. .. note:: If ``A`` has zero determinant, this returns ``(0, -inf)``. .. note:: Backward through :meth:`slogdet` internally uses SVD results when :attr:`A` is not invertible. In this case, double backward through :meth:`slogdet` will be unstable in when :attr:`A` doesn't have distinct singular values. See :meth:`~torch.svd` for details. Arguments: A (Tensor): The input 2D square tensor Returns: A tuple containing the sign of the determinant, and the log value of the absolute determinant. Example:: >>> A = torch.randn(3, 3) >>> torch.det(A) tensor(-4.8215) >>> torch.logdet(A) tensor(nan) >>> torch.slogdet(A) (tensor(-1.), tensor(1.5731)) """) add_docstr(torch.pinverse, r""" pinverse(input, rcond=1e-15) -> Tensor Calculates the pseudo-inverse (also known as the Moore-Penrose inverse) of a 2D tensor. Please look at `Moore-Penrose inverse`_ for more details .. note:: This method is implemented using the Singular Value Decomposition. .. note:: The pseudo-inverse is not necessarily a continuous function in the elements of the matrix `[1]`_. Therefore, derivatives are not always existent, and exist for a constant rank only `[2]`_. However, this method is backprop-able due to the implementation by using SVD results, and could be unstable. Double-backward will also be unstable due to the usage of SVD internally. See :meth:`~torch.svd` for more details. Arguments: input (Tensor): The input 2D tensor of dimensions :math:`m \times n` rcond (float): A floating point value to determine the cutoff for small singular values. Default: 1e-15 Returns: The pseudo-inverse of :attr:`input` of dimensions :math:`n \times m` Example:: >>> input = torch.randn(3, 5) >>> input tensor([[ 0.5495, 0.0979, -1.4092, -0.1128, 0.4132], [-1.1143, -0.3662, 0.3042, 1.6374, -0.9294], [-0.3269, -0.5745, -0.0382, -0.5922, -0.6759]]) >>> torch.pinverse(input) tensor([[ 0.0600, -0.1933, -0.2090], [-0.0903, -0.0817, -0.4752], [-0.7124, -0.1631, -0.2272], [ 0.1356, 0.3933, -0.5023], [-0.0308, -0.1725, -0.5216]]) .. _Moore-Penrose inverse: https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse .. _[1]: https://epubs.siam.org/doi/10.1137/0117004 .. _[2]: https://www.jstor.org/stable/2156365 """) add_docstr(torch.fft, r""" fft(input, signal_ndim, normalized=False) -> Tensor Complex-to-complex Discrete Fourier Transform This method computes the complex-to-complex discrete Fourier transform. Ignoring the batch dimensions, it computes the following expression: .. math:: X[\omega_1, \dots, \omega_d] = \sum_{n_1=0}^{N_1} \dots \sum_{n_d=0}^{N_d} x[n_1, \dots, n_d] e^{-j\ 2 \pi \sum_{i=0}^d \frac{\omega_i n_i}{N_i}}, where :math:`d` = :attr:`signal_ndim` is number of dimensions for the signal, and :math:`N_i` is the size of signal dimension :math:`i`. This method supports 1D, 2D and 3D complex-to-complex transforms, indicated by :attr:`signal_ndim`. :attr:`input` must be a tensor with last dimension of size 2, representing the real and imaginary components of complex numbers, and should have at least ``signal_ndim + 1`` dimensions with optionally arbitrary number of leading batch dimensions. If :attr:`normalized` is set to ``True``, this normalizes the result by dividing it with :math:`\sqrt{\prod_{i=1}^K N_i}` so that the operator is unitary. Returns the real and the imaginary parts together as one tensor of the same shape of :attr:`input`. The inverse of this function is :func:`~torch.ifft`. .. note:: For CUDA tensors, an LRU cache is used for cuFFT plans to speed up repeatedly running FFT methods on tensors of same geometry with same same configuration. Changing ``torch.backends.cuda.cufft_plan_cache.max_size`` (default is 4096 on CUDA 10 and newer, and 1023 on older CUDA versions) controls the capacity of this cache. Some cuFFT plans may allocate GPU memory. You can use ``torch.backends.cuda.cufft_plan_cache.size`` to query the number of plans currently in cache, and ``torch.backends.cuda.cufft_plan_cache.clear()`` to clear the cache. .. warning:: For CPU tensors, this method is currently only available with MKL. Use :func:`torch.backends.mkl.is_available` to check if MKL is installed. Arguments: input (Tensor): the input tensor of at least :attr:`signal_ndim` ``+ 1`` dimensions signal_ndim (int): the number of dimensions in each signal. :attr:`signal_ndim` can only be 1, 2 or 3 normalized (bool, optional): controls whether to return normalized results. Default: ``False`` Returns: Tensor: A tensor containing the complex-to-complex Fourier transform result Example:: >>> # unbatched 2D FFT >>> x = torch.randn(4, 3, 2) >>> torch.fft(x, 2) tensor([[[-0.0876, 1.7835], [-2.0399, -2.9754], [ 4.4773, -5.0119]], [[-1.5716, 2.7631], [-3.8846, 5.2652], [ 0.2046, -0.7088]], [[ 1.9938, -0.5901], [ 6.5637, 6.4556], [ 2.9865, 4.9318]], [[ 7.0193, 1.1742], [-1.3717, -2.1084], [ 2.0289, 2.9357]]]) >>> # batched 1D FFT >>> torch.fft(x, 1) tensor([[[ 1.8385, 1.2827], [-0.1831, 1.6593], [ 2.4243, 0.5367]], [[-0.9176, -1.5543], [-3.9943, -2.9860], [ 1.2838, -2.9420]], [[-0.8854, -0.6860], [ 2.4450, 0.0808], [ 1.3076, -0.5768]], [[-0.1231, 2.7411], [-0.3075, -1.7295], [-0.5384, -2.0299]]]) >>> # arbitrary number of batch dimensions, 2D FFT >>> x = torch.randn(3, 3, 5, 5, 2) >>> y = torch.fft(x, 2) >>> y.shape torch.Size([3, 3, 5, 5, 2]) """) add_docstr(torch.ifft, r""" ifft(input, signal_ndim, normalized=False) -> Tensor Complex-to-complex Inverse Discrete Fourier Transform This method computes the complex-to-complex inverse discrete Fourier transform. Ignoring the batch dimensions, it computes the following expression: .. math:: X[\omega_1, \dots, \omega_d] = \frac{1}{\prod_{i=1}^d N_i} \sum_{n_1=0}^{N_1} \dots \sum_{n_d=0}^{N_d} x[n_1, \dots, n_d] e^{\ j\ 2 \pi \sum_{i=0}^d \frac{\omega_i n_i}{N_i}}, where :math:`d` = :attr:`signal_ndim` is number of dimensions for the signal, and :math:`N_i` is the size of signal dimension :math:`i`. The argument specifications are almost identical with :func:`~torch.fft`. However, if :attr:`normalized` is set to ``True``, this instead returns the results multiplied by :math:`\sqrt{\prod_{i=1}^d N_i}`, to become a unitary operator. Therefore, to invert a :func:`~torch.fft`, the :attr:`normalized` argument should be set identically for :func:`~torch.fft`. Returns the real and the imaginary parts together as one tensor of the same shape of :attr:`input`. The inverse of this function is :func:`~torch.fft`. .. note:: For CUDA tensors, an LRU cache is used for cuFFT plans to speed up repeatedly running FFT methods on tensors of same geometry with same same configuration. Changing ``torch.backends.cuda.cufft_plan_cache.max_size`` (default is 4096 on CUDA 10 and newer, and 1023 on older CUDA versions) controls the capacity of this cache. Some cuFFT plans may allocate GPU memory. You can use ``torch.backends.cuda.cufft_plan_cache.size`` to query the number of plans currently in cache, and ``torch.backends.cuda.cufft_plan_cache.clear()`` to clear the cache. .. warning:: For CPU tensors, this method is currently only available with MKL. Use :func:`torch.backends.mkl.is_available` to check if MKL is installed. Arguments: input (Tensor): the input tensor of at least :attr:`signal_ndim` ``+ 1`` dimensions signal_ndim (int): the number of dimensions in each signal. :attr:`signal_ndim` can only be 1, 2 or 3 normalized (bool, optional): controls whether to return normalized results. Default: ``False`` Returns: Tensor: A tensor containing the complex-to-complex inverse Fourier transform result Example:: >>> x = torch.randn(3, 3, 2) >>> x tensor([[[ 1.2766, 1.3680], [-0.8337, 2.0251], [ 0.9465, -1.4390]], [[-0.1890, 1.6010], [ 1.1034, -1.9230], [-0.9482, 1.0775]], [[-0.7708, -0.8176], [-0.1843, -0.2287], [-1.9034, -0.2196]]]) >>> y = torch.fft(x, 2) >>> torch.ifft(y, 2) # recover x tensor([[[ 1.2766, 1.3680], [-0.8337, 2.0251], [ 0.9465, -1.4390]], [[-0.1890, 1.6010], [ 1.1034, -1.9230], [-0.9482, 1.0775]], [[-0.7708, -0.8176], [-0.1843, -0.2287], [-1.9034, -0.2196]]]) """) add_docstr(torch.rfft, r""" rfft(input, signal_ndim, normalized=False, onesided=True) -> Tensor Real-to-complex Discrete Fourier Transform This method computes the real-to-complex discrete Fourier transform. It is mathematically equivalent with :func:`~torch.fft` with differences only in formats of the input and output. This method supports 1D, 2D and 3D real-to-complex transforms, indicated by :attr:`signal_ndim`. :attr:`input` must be a tensor with at least ``signal_ndim`` dimensions with optionally arbitrary number of leading batch dimensions. If :attr:`normalized` is set to ``True``, this normalizes the result by dividing it with :math:`\sqrt{\prod_{i=1}^K N_i}` so that the operator is unitary, where :math:`N_i` is the size of signal dimension :math:`i`. The real-to-complex Fourier transform results follow conjugate symmetry: .. math:: X[\omega_1, \dots, \omega_d] = X^*[N_1 - \omega_1, \dots, N_d - \omega_d], where the index arithmetic is computed modulus the size of the corresponding dimension, :math:`\ ^*` is the conjugate operator, and :math:`d` = :attr:`signal_ndim`. :attr:`onesided` flag controls whether to avoid redundancy in the output results. If set to ``True`` (default), the output will not be full complex result of shape :math:`(*, 2)`, where :math:`*` is the shape of :attr:`input`, but instead the last dimension will be halfed as of size :math:`\lfloor \frac{N_d}{2} \rfloor + 1`. The inverse of this function is :func:`~torch.irfft`. .. note:: For CUDA tensors, an LRU cache is used for cuFFT plans to speed up repeatedly running FFT methods on tensors of same geometry with same same configuration. Changing ``torch.backends.cuda.cufft_plan_cache.max_size`` (default is 4096 on CUDA 10 and newer, and 1023 on older CUDA versions) controls the capacity of this cache. Some cuFFT plans may allocate GPU memory. You can use ``torch.backends.cuda.cufft_plan_cache.size`` to query the number of plans currently in cache, and ``torch.backends.cuda.cufft_plan_cache.clear()`` to clear the cache. .. warning:: For CPU tensors, this method is currently only available with MKL. Use :func:`torch.backends.mkl.is_available` to check if MKL is installed. Arguments: input (Tensor): the input tensor of at least :attr:`signal_ndim` dimensions signal_ndim (int): the number of dimensions in each signal. :attr:`signal_ndim` can only be 1, 2 or 3 normalized (bool, optional): controls whether to return normalized results. Default: ``False`` onesided (bool, optional): controls whether to return half of results to avoid redundancy. Default: ``True`` Returns: Tensor: A tensor containing the real-to-complex Fourier transform result Example:: >>> x = torch.randn(5, 5) >>> torch.rfft(x, 2).shape torch.Size([5, 3, 2]) >>> torch.rfft(x, 2, onesided=False).shape torch.Size([5, 5, 2]) """) add_docstr(torch.irfft, r""" irfft(input, signal_ndim, normalized=False, onesided=True, signal_sizes=None) -> Tensor Complex-to-real Inverse Discrete Fourier Transform This method computes the complex-to-real inverse discrete Fourier transform. It is mathematically equivalent with :func:`ifft` with differences only in formats of the input and output. The argument specifications are almost identical with :func:`~torch.ifft`. Similar to :func:`~torch.ifft`, if :attr:`normalized` is set to ``True``, this normalizes the result by multiplying it with :math:`\sqrt{\prod_{i=1}^K N_i}` so that the operator is unitary, where :math:`N_i` is the size of signal dimension :math:`i`. Due to the conjugate symmetry, :attr:`input` do not need to contain the full complex frequency values. Roughly half of the values will be sufficient, as is the case when :attr:`input` is given by :func:`~torch.rfft` with ``rfft(signal, onesided=True)``. In such case, set the :attr:`onesided` argument of this method to ``True``. Moreover, the original signal shape information can sometimes be lost, optionally set :attr:`signal_sizes` to be the size of the original signal (without the batch dimensions if in batched mode) to recover it with correct shape. Therefore, to invert an :func:`~torch.rfft`, the :attr:`normalized` and :attr:`onesided` arguments should be set identically for :func:`~torch.irfft`, and preferrably a :attr:`signal_sizes` is given to avoid size mismatch. See the example below for a case of size mismatch. See :func:`~torch.rfft` for details on conjugate symmetry. The inverse of this function is :func:`~torch.rfft`. .. warning:: Generally speaking, the input of this function should contain values following conjugate symmetry. Note that even if :attr:`onesided` is ``True``, often symmetry on some part is still needed. When this requirement is not satisfied, the behavior of :func:`~torch.irfft` is undefined. Since :func:`torch.autograd.gradcheck` estimates numerical Jacobian with point perturbations, :func:`~torch.irfft` will almost certainly fail the check. .. note:: For CUDA tensors, an LRU cache is used for cuFFT plans to speed up repeatedly running FFT methods on tensors of same geometry with same same configuration. Changing ``torch.backends.cuda.cufft_plan_cache.max_size`` (default is 4096 on CUDA 10 and newer, and 1023 on older CUDA versions) controls the capacity of this cache. Some cuFFT plans may allocate GPU memory. You can use ``torch.backends.cuda.cufft_plan_cache.size`` to query the number of plans currently in cache, and ``torch.backends.cuda.cufft_plan_cache.clear()`` to clear the cache. .. warning:: For CPU tensors, this method is currently only available with MKL. Use :func:`torch.backends.mkl.is_available` to check if MKL is installed. Arguments: input (Tensor): the input tensor of at least :attr:`signal_ndim` ``+ 1`` dimensions signal_ndim (int): the number of dimensions in each signal. :attr:`signal_ndim` can only be 1, 2 or 3 normalized (bool, optional): controls whether to return normalized results. Default: ``False`` onesided (bool, optional): controls whether :attr:`input` was halfed to avoid redundancy, e.g., by :func:`rfft`. Default: ``True`` signal_sizes (list or :class:`torch.Size`, optional): the size of the original signal (without batch dimension). Default: ``None`` Returns: Tensor: A tensor containing the complex-to-real inverse Fourier transform result Example:: >>> x = torch.randn(4, 4) >>> torch.rfft(x, 2, onesided=True).shape torch.Size([4, 3, 2]) >>> >>> # notice that with onesided=True, output size does not determine the original signal size >>> x = torch.randn(4, 5) >>> torch.rfft(x, 2, onesided=True).shape torch.Size([4, 3, 2]) >>> >>> # now we use the original shape to recover x >>> x tensor([[-0.8992, 0.6117, -1.6091, -0.4155, -0.8346], [-2.1596, -0.0853, 0.7232, 0.1941, -0.0789], [-2.0329, 1.1031, 0.6869, -0.5042, 0.9895], [-0.1884, 0.2858, -1.5831, 0.9917, -0.8356]]) >>> y = torch.rfft(x, 2, onesided=True) >>> torch.irfft(y, 2, onesided=True, signal_sizes=x.shape) # recover x tensor([[-0.8992, 0.6117, -1.6091, -0.4155, -0.8346], [-2.1596, -0.0853, 0.7232, 0.1941, -0.0789], [-2.0329, 1.1031, 0.6869, -0.5042, 0.9895], [-0.1884, 0.2858, -1.5831, 0.9917, -0.8356]]) """) add_docstr(torch.hann_window, """ hann_window(window_length, periodic=True, dtype=None, \ layout=torch.strided, device=None, requires_grad=False) -> Tensor """ + r""" Hann window function. .. math:: w[n] = \frac{1}{2}\ \left[1 - \cos \left( \frac{2 \pi n}{N - 1} \right)\right] = \sin^2 \left( \frac{\pi n}{N - 1} \right), where :math:`N` is the full window size. The input :attr:`window_length` is a positive integer controlling the returned window size. :attr:`periodic` flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have ``torch.hann_window(L, periodic=True)`` equal to ``torch.hann_window(L + 1, periodic=False)[:-1])``. .. note:: If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. """ + r""" Arguments: window_length (int): the size of returned window periodic (bool, optional): If True, returns a window to be used as periodic function. If False, return a symmetric window. {dtype} Only floating point types are supported. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only ``torch.strided`` (dense layout) is supported. {device} {requires_grad} Returns: Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window """.format(**factory_common_args)) add_docstr(torch.hamming_window, """ hamming_window(window_length, periodic=True, alpha=0.54, beta=0.46, dtype=None, \ layout=torch.strided, device=None, requires_grad=False) -> Tensor """ + r""" Hamming window function. .. math:: w[n] = \alpha - \beta\ \cos \left( \frac{2 \pi n}{N - 1} \right), where :math:`N` is the full window size. The input :attr:`window_length` is a positive integer controlling the returned window size. :attr:`periodic` flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have ``torch.hamming_window(L, periodic=True)`` equal to ``torch.hamming_window(L + 1, periodic=False)[:-1])``. .. note:: If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. .. note:: This is a generalized version of :meth:`torch.hann_window`. """ + r""" Arguments: window_length (int): the size of returned window periodic (bool, optional): If True, returns a window to be used as periodic function. If False, return a symmetric window. {dtype} Only floating point types are supported. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only ``torch.strided`` (dense layout) is supported. {device} {requires_grad} Returns: Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window """.format(**factory_common_args)) add_docstr(torch.bartlett_window, """ bartlett_window(window_length, periodic=True, dtype=None, \ layout=torch.strided, device=None, requires_grad=False) -> Tensor """ + r""" Bartlett window function. .. math:: w[n] = 1 - \left| \frac{2n}{N-1} - 1 \right| = \begin{cases} \frac{2n}{N - 1} & \text{if } 0 \leq n \leq \frac{N - 1}{2} \\ 2 - \frac{2n}{N - 1} & \text{if } \frac{N - 1}{2} < n < N \\ \end{cases}, where :math:`N` is the full window size. The input :attr:`window_length` is a positive integer controlling the returned window size. :attr:`periodic` flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have ``torch.bartlett_window(L, periodic=True)`` equal to ``torch.bartlett_window(L + 1, periodic=False)[:-1])``. .. note:: If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. """ + r""" Arguments: window_length (int): the size of returned window periodic (bool, optional): If True, returns a window to be used as periodic function. If False, return a symmetric window. {dtype} Only floating point types are supported. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only ``torch.strided`` (dense layout) is supported. {device} {requires_grad} Returns: Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window """.format(**factory_common_args)) add_docstr(torch.blackman_window, """ blackman_window(window_length, periodic=True, dtype=None, \ layout=torch.strided, device=None, requires_grad=False) -> Tensor """ + r""" Blackman window function. .. math:: w[n] = 0.42 - 0.5 \cos \left( \frac{2 \pi n}{N - 1} \right) + 0.08 \cos \left( \frac{4 \pi n}{N - 1} \right) where :math:`N` is the full window size. The input :attr:`window_length` is a positive integer controlling the returned window size. :attr:`periodic` flag determines whether the returned window trims off the last duplicate value from the symmetric window and is ready to be used as a periodic window with functions like :meth:`torch.stft`. Therefore, if :attr:`periodic` is true, the :math:`N` in above formula is in fact :math:`\text{window\_length} + 1`. Also, we always have ``torch.blackman_window(L, periodic=True)`` equal to ``torch.blackman_window(L + 1, periodic=False)[:-1])``. .. note:: If :attr:`window_length` :math:`=1`, the returned window contains a single value 1. """ + r""" Arguments: window_length (int): the size of returned window periodic (bool, optional): If True, returns a window to be used as periodic function. If False, return a symmetric window. {dtype} Only floating point types are supported. layout (:class:`torch.layout`, optional): the desired layout of returned window tensor. Only ``torch.strided`` (dense layout) is supported. {device} {requires_grad} Returns: Tensor: A 1-D tensor of size :math:`(\text{{window\_length}},)` containing the window """.format(**factory_common_args)) add_docstr(torch.unbind, r""" unbind(tensor, dim=0) -> seq Removes a tensor dimension. Returns a tuple of all slices along a given dimension, already without it. Arguments: tensor (Tensor): the tensor to unbind dim (int): dimension to remove Example:: >>> torch.unbind(torch.tensor([[1, 2, 3], >>> [4, 5, 6], >>> [7, 8, 9]])) (tensor([1, 2, 3]), tensor([4, 5, 6]), tensor([7, 8, 9])) """)
{ "repo_name": "ryfeus/lambda-packs", "path": "pytorch/source/torch/_torch_docs.py", "copies": "1", "size": "194542", "license": "mit", "hash": -6973738704708488000, "line_mean": 30.855575569, "line_max": 119, "alpha_frac": 0.61419128, "autogenerated": false, "ratio": 3.117760184621302, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4231951464621302, "avg_score": null, "num_lines": null }
"""Adds docstrings to functions defined in the torch._C""" import torch._C from torch._C import _add_docstr as add_docstr add_docstr(torch._C.abs, """abs(input, out=None) -> Tensor Computes the element-wise absolute value of the given :attr:`input` a tensor. Example:: >>> torch.abs(torch.FloatTensor([-1, -2, 3])) FloatTensor([1, 2, 3]) """) add_docstr(torch._C.acos, """ acos(input, out=None) -> Tensor Returns a new `Tensor` with the arccosine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.acos(a) 2.2608 1.2956 1.1075 nan [torch.FloatTensor of size 4] """) add_docstr(torch._C.add, """ .. function:: add(input, value, out=None) Adds the scalar :attr:`value` to each element of the input :attr:`input` and returns a new resulting tensor. :math:`out = tensor + value` If :attr:`input` is of type FloatTensor or DoubleTensor, :attr:`value` must be a real number, otherwise it should be an integer Args: input (Tensor): the input `Tensor` value (Number): the number to be added to each element of :attr:`input` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 0.4050 -1.2227 1.8688 -0.4185 [torch.FloatTensor of size 4] >>> torch.add(a, 20) 20.4050 18.7773 21.8688 19.5815 [torch.FloatTensor of size 4] .. function:: add(input, value=1, other, out=None) Each element of the Tensor :attr:`other` is multiplied by the scalar :attr:`value` and added to each element of the Tensor :attr:`input`. The resulting Tensor is returned. The shapes of :attr:`input` and :attr:`other` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`input` is used as the shape for the returned output Tensor :math:`out = input + (other * value)` If :attr:`other` is of type FloatTensor or DoubleTensor, :attr:`value` must be a real number, otherwise it should be an integer Args: input (Tensor): the first input `Tensor` value (Number): the scalar multiplier for :attr:`other` other (Tensor): the second input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> import torch >>> a = torch.randn(4) >>> a -0.9310 2.0330 0.0852 -0.2941 [torch.FloatTensor of size 4] >>> b = torch.randn(2, 2) >>> b 1.0663 0.2544 -0.1513 0.0749 [torch.FloatTensor of size 2x2] >>> torch.add(a, 10, b) 9.7322 4.5770 -1.4279 0.4552 [torch.FloatTensor of size 4] """) add_docstr(torch._C.addbmm, """ addbmm(beta=1, mat, alpha=1, batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices stored in :attr:`batch1` and :attr:`batch2`, with a reduced add step (all matrix multiplications get accumulated along the first dimension). :attr:`mat` is added to the final result. :attr:`batch1` and :attr:`batch2` must be 3D Tensors each containing the same number of matrices. If :attr:`batch1` is a `b x n x m` Tensor, :attr:`batch2` is a `b x m x p` Tensor, :attr:`out` and :attr:`mat` will be `n x p` Tensors. In other words, :math:`res = (beta * M) + (alpha * sum(batch1_i @ batch2_i, i = 0, b))` For inputs of type `FloatTensor` or `DoubleTensor`, args `beta` and `alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`mat` mat (Tensor): matrix to be added alpha (Number, optional): multiplier for `batch1 @ batch2` batch1 (Tensor): First batch of matrices to be multiplied batch2 (Tensor): Second batch of matrices to be multiplied out (Tensor, optional): Output tensor Example:: >>> M = torch.randn(3, 5) >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> torch.addbmm(M, batch1, batch2) -3.1162 11.0071 7.3102 0.1824 -7.6892 1.8265 6.0739 0.4589 -0.5641 -5.4283 -9.3387 -0.1794 -1.2318 -6.8841 -4.7239 [torch.FloatTensor of size 3x5] """) add_docstr(torch._C.addcdiv, """ addcdiv(tensor, value=1, tensor1, tensor2, out=None) -> Tensor Performs the element-wise division of :attr:`tensor1` by :attr:`tensor2`, multiply the result by the scalar :attr:`value` and add it to :attr:`tensor`. The number of elements must match, but sizes do not matter. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be a real number, otherwise an integer Args: tensor (Tensor): the tensor to be added value (Number, optional): multiplier for `tensor1 ./ tensor2` tensor1 (Tensor): Numerator tensor tensor2 (Tensor): Denominator tensor out (Tensor, optional): Output tensor Example:: >>> t = torch.randn(2, 3) >>> t1 = torch.randn(1, 6) >>> t2 = torch.randn(6, 1) >>> torch.addcdiv(t, 0.1, t1, t2) 0.0122 -0.0188 -0.2354 0.7396 -1.5721 1.2878 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.addcmul, """ addcmul(tensor, value=1, tensor1, tensor2, out=None) -> Tensor Performs the element-wise multiplication of :attr:`tensor1` by :attr:`tensor2`, multiply the result by the scalar :attr:`value` and add it to :attr:`tensor`. The number of elements must match, but sizes do not matter. For inputs of type `FloatTensor` or `DoubleTensor`, :attr:`value` must be a real number, otherwise an integer Args: tensor (Tensor): the tensor to be added value (Number, optional): multiplier for `tensor1 .* tensor2` tensor1 (Tensor): tensor to be multiplied tensor2 (Tensor): tensor to be multiplied out (Tensor, optional): Output tensor Example:: >>> t = torch.randn(2, 3) >>> t1 = torch.randn(1, 6) >>> t2 = torch.randn(6, 1) >>> torch.addcmul(t, 0.1, t1, t2) 0.0122 -0.0188 -0.2354 0.7396 -1.5721 1.2878 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.addmm, """ addmm(beta=1, mat, alpha=1, mat1, mat2, out=None) -> Tensor Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. The matrix :attr:`mat` is added to the final result. If :attr:`mat1` is a `n x m` Tensor, :attr:`mat2` is a `m x p` Tensor, :attr:`out` and :attr:`mat` will be `n x p` Tensors. `alpha` and `beta` are scaling factors on `mat1 @ mat2` and `mat` respectively. In other words, :math:`out = (beta * M) + (alpha * mat1 @ mat2)` For inputs of type `FloatTensor` or `DoubleTensor`, args :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`mat` mat (Tensor): matrix to be added alpha (Number, optional): multiplier for `mat1 @ mat2` mat1 (Tensor): First matrix to be multiplied mat2 (Tensor): Second matrix to be multiplied out (Tensor, optional): Output tensor Example:: >>> M = torch.randn(2, 3) >>> mat1 = torch.randn(2, 3) >>> mat2 = torch.randn(3, 3) >>> torch.addmm(M, mat1, mat2) -0.4095 -1.9703 1.3561 5.7674 -4.9760 2.7378 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.addmv, """ addmv(beta=1, tensor, alpha=1, mat, vec, out=None) -> Tensor Performs a matrix-vector product of the matrix :attr:`mat` and the vector :attr:`vec`. The vector :attr:`tensor` is added to the final result. If :attr:`mat` is a `n x m` Tensor, :attr:`vec` is a 1D Tensor of size `m`, :attr:`out` and :attr:`tensor` will be 1D of size `n`. `alpha` and `beta` are scaling factors on `mat * vec` and `tensor` respectively. In other words: :math:`out = (beta * tensor) + (alpha * (mat @ vec2))` For inputs of type `FloatTensor` or `DoubleTensor`, args :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`tensor` tensor (Tensor): vector to be added alpha (Number, optional): multiplier for `mat @ vec` mat (Tensor): matrix to be multiplied vec (Tensor): vector to be multiplied out (Tensor, optional): Output tensor Example:: >>> M = torch.randn(2) >>> mat = torch.randn(2, 3) >>> vec = torch.randn(3) >>> torch.addmv(M, mat, vec) -2.0939 -2.2950 [torch.FloatTensor of size 2] """) add_docstr(torch._C.addr, r""" addr(beta=1, mat, alpha=1, vec1, vec2, out=None) -> Tensor Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2` and adds it to the matrix :attr:`mat`. Optional values :attr:`beta` and :attr:`alpha` are scalars that multiply :attr:`mat` and :math:`(vec1 \otimes vec2)` respectively In other words, :math:`out = (beta * mat) + (alpha * vec1 \otimes vec2)` If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector of size `m`, then :attr:`mat` must be a matrix of size `n x m` For inputs of type `FloatTensor` or `DoubleTensor`, args :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): Multiplier for :attr:`mat` mat (Tensor): Matrix to be added alpha (Number, optional): Multiplier for outer product of for :attr:`vec1` and :attr:`vec2` vec1 (Tensor): First vector of the outer product vec2 (Tensor): Second vector of the outer product out (Tensor, optional): Output tensor Example:: >>> vec1 = torch.range(1, 3) >>> vec2 = torch.range(1, 2) >>> M = torch.zeros(3, 2) >>> torch.addr(M, vec1, vec2) 1 2 2 4 3 6 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.asin, """ asin(input, out=None) -> Tensor Returns a new `Tensor` with the arcsine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.asin(a) -0.6900 0.2752 0.4633 nan [torch.FloatTensor of size 4] """) add_docstr(torch._C.atan, """ atan(input, out=None) -> Tensor Returns a new `Tensor` with the arctangent of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.atan(a) -0.5669 0.2653 0.4203 0.9196 [torch.FloatTensor of size 4] """) add_docstr(torch._C.atan2, """ atan2(input1, input2, out=None) -> Tensor Returns a new `Tensor` with the arctangent of the elements of :attr:`input1` and :attr:`input2`. Args: input1 (Tensor): the first input `Tensor` input2 (Tensor): the second input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.atan2(a, torch.randn(4)) -2.4167 2.9755 0.9363 1.6613 [torch.FloatTensor of size 4] """) add_docstr(torch._C.baddbmm, r""" baddbmm(beta=1, mat, alpha=1, batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices in :attr:`batch1` and :attr:`batch2`. :attr:`mat` is added to the final result. :attr:`batch1` and :attr:`batch2` must be 3D Tensors each containing the same number of matrices. If :attr:`batch1` is a `b x n x m` Tensor, :attr:`batch2` is a `b x m x p` Tensor, :attr:`out` and :attr:`mat` will be `b x n x p` Tensors. In other words, :math:`res_i = (beta * M_i) + (alpha * batch1_i \times batch2_i)` For inputs of type `FloatTensor` or `DoubleTensor`, args :attr:`beta` and :attr:`alpha` must be real numbers, otherwise they should be integers Args: beta (Number, optional): multiplier for :attr:`mat` mat (Tensor): tensor to be added alpha (Number, optional): multiplier for `batch1 @ batch2` batch1 (Tensor): First batch of matrices to be multiplied batch2 (Tensor): Second batch of matrices to be multiplied out (Tensor, optional): Output tensor Example:: >>> M = torch.randn(10, 3, 5) >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> torch.baddbmm(M, batch1, batch2).size() torch.Size([10, 3, 5]) """) add_docstr(torch._C.bernoulli, """ bernoulli(input, out=None) -> Tensor Draws binary random numbers (0 or 1) from a bernoulli distribution. The :attr:`input` Tensor should be a tensor containing probabilities to be used for drawing the binary random number. Hence, all values in :attr:`input` have to be in the range: :math:`0 <= input_i <= 1` The `i-th` element of the output tensor will draw a value `1` according to the `i-th` probability value given in :attr:`input`. The returned :attr:`out` Tensor only has values 0 or 1 and is of the same shape as :attr:`input` Args: input (Tensor): Probability values for the bernoulli distribution out (Tensor, optional): Output tensor Example:: >>> a = torch.Tensor(3, 3).uniform_(0, 1) # generate a uniform random matrix with range [0, 1] >>> a 0.7544 0.8140 0.9842 0.5282 0.0595 0.6445 0.1925 0.9553 0.9732 [torch.FloatTensor of size 3x3] >>> torch.bernoulli(a) 1 1 1 0 0 1 0 1 1 [torch.FloatTensor of size 3x3] >>> a = torch.ones(3, 3) # probability of drawing "1" is 1 >>> torch.bernoulli(a) 1 1 1 1 1 1 1 1 1 [torch.FloatTensor of size 3x3] >>> a = torch.zeros(3, 3) # probability of drawing "1" is 0 >>> torch.bernoulli(a) 0 0 0 0 0 0 0 0 0 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.bmm, """ bmm(batch1, batch2, out=None) -> Tensor Performs a batch matrix-matrix product of matrices stored in :attr:`batch1` and :attr:`batch2`. :attr:`batch1` and :attr:`batch2` must be 3D Tensors each containing the same number of matrices. If :attr:`batch1` is a `b x n x m` Tensor, :attr:`batch2` is a `b x m x p` Tensor, :attr:`out` will be a `b x n x p` Tensor. Args: batch1 (Tensor): First batch of matrices to be multiplied batch2 (Tensor): Second batch of matrices to be multiplied out (Tensor, optional): Output tensor Example:: >>> batch1 = torch.randn(10, 3, 4) >>> batch2 = torch.randn(10, 4, 5) >>> res = torch.bmm(batch1, batch2) >>> res.size() torch.Size([10, 3, 5]) """) add_docstr(torch._C.cat, """ cat(inputs, dimension=0) -> Tensor Concatenates the given sequence of :attr:`inputs` Tensors in the given dimension. :func:`torch.cat` can be seen as an inverse operation for :func:`torch.split` and :func:`torch.chunk` :func:`cat` can be best understood via examples. Args: inputs (sequence of Tensors): Can be any python sequence of `Tensor` of the same type. dimension (int, optional): The dimension over which the tensors are concatenated Example:: >>> x = torch.randn(2, 3) >>> x 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 [torch.FloatTensor of size 2x3] >>> torch.cat((x, x, x), 0) 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 [torch.FloatTensor of size 6x3] >>> torch.cat((x, x, x), 1) 0.5983 -0.0341 2.4918 0.5983 -0.0341 2.4918 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 1.5981 -0.5265 -0.8735 1.5981 -0.5265 -0.8735 [torch.FloatTensor of size 2x9] """) add_docstr(torch._C.ceil, """ ceil(input, out=None) -> Tensor Returns a new `Tensor` with the ceil of the elements of :attr:`input`, the smallest integer greater than or equal to each element. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.ceil(a) 2 1 -0 -0 [torch.FloatTensor of size 4] """) add_docstr(torch._C.reciprocal, """ reciprocal(input, out=None) -> Tensor Returns a new `Tensor` with the reciprocal of the elements of :attr:`input`, i.e. :math:`1.0 / x` Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.reciprocal(a) 0.7210 2.5565 -1.1583 -1.8289 [torch.FloatTensor of size 4] """) add_docstr(torch._C.clamp, """ clamp(input, min, max, out=None) -> Tensor Clamp all elements in :attr:`input` into the range `[min, max]` and return a resulting Tensor. :: | min, if x_i < min y_i = | x_i, if min <= x_i <= max | max, if x_i > max If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, args :attr:`min` and :attr:`max` must be real numbers, otherwise they should be integers Args: input (Tensor): the input `Tensor` min (Number): lower-bound of the range to be clamped to max (Number): upper-bound of the range to be clamped to out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.clamp(a, min=-0.5, max=0.5) 0.5000 0.3912 -0.5000 -0.5000 [torch.FloatTensor of size 4] .. function:: clamp(input, *, min, out=None) -> Tensor Clamps all elements in :attr:`input` to be larger or equal :attr:`min`. If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input `Tensor` value (Number): minimal value of each element in the output out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.clamp(a, min=0.5) 1.3869 0.5000 0.5000 0.5000 [torch.FloatTensor of size 4] .. function:: clamp(input, *, max, out=None) -> Tensor Clamps all elements in :attr:`input` to be smaller or equal :attr:`max`. If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input `Tensor` value (Number): maximal value of each element in the output out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.clamp(a, max=0.5) 0.5000 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] """) add_docstr(torch._C.cos, """ cos(input, out=None) -> Tensor Returns a new `Tensor` with the cosine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.cos(a) 0.8041 0.9633 0.9018 0.2557 [torch.FloatTensor of size 4] """) add_docstr(torch._C.cosh, """ cosh(input, out=None) -> Tensor Returns a new `Tensor` with the hyperbolic cosine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.cosh(a) 1.2095 1.0372 1.1015 1.9917 [torch.FloatTensor of size 4] """) add_docstr(torch._C.cross, """ cross(input, other, dim=-1, out=None) -> Tensor Returns the cross product of vectors in dimension :attr:`dim` of :attr:`input` and :attr:`other`. :attr:`input` and :attr:`other` must have the same size, and the size of their :attr:`dim` dimension should be 3. If :attr:`dim` is not given, it defaults to the first dimension found with the size 3. Args: input (Tensor): the input `Tensor` other (Tensor): the second input `Tensor` dim (int, optional): the dimension to take the cross-product in. out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4, 3) >>> a -0.6652 -1.0116 -0.6857 0.2286 0.4446 -0.5272 0.0476 0.2321 1.9991 0.6199 1.1924 -0.9397 [torch.FloatTensor of size 4x3] >>> b = torch.randn(4, 3) >>> b -0.1042 -1.1156 0.1947 0.9947 0.1149 0.4701 -1.0108 0.8319 -0.0750 0.9045 -1.3754 1.0976 [torch.FloatTensor of size 4x3] >>> torch.cross(a, b, dim=1) -0.9619 0.2009 0.6367 0.2696 -0.6318 -0.4160 -1.6805 -2.0171 0.2741 0.0163 -1.5304 -1.9311 [torch.FloatTensor of size 4x3] >>> torch.cross(a, b) -0.9619 0.2009 0.6367 0.2696 -0.6318 -0.4160 -1.6805 -2.0171 0.2741 0.0163 -1.5304 -1.9311 [torch.FloatTensor of size 4x3] """) add_docstr(torch._C.cumprod, """ cumprod(input, dim, out=None) -> Tensor Returns the cumulative product of elements of :attr:`input` in the dimension :attr:`dim`. For example, if :attr:`input` is a vector of size N, the result will also be a vector of size N, with elements: :math:`y_i = x_1 * x_2 * x_3 * ... * x_i` Args: input (Tensor): the input `Tensor` dim (int): the dimension to do the operation over out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(10) >>> a 1.1148 1.8423 1.4143 -0.4403 1.2859 -1.2514 -0.4748 1.1735 -1.6332 -0.4272 [torch.FloatTensor of size 10] >>> torch.cumprod(a, dim=0) 1.1148 2.0537 2.9045 -1.2788 -1.6444 2.0578 -0.9770 -1.1466 1.8726 -0.8000 [torch.FloatTensor of size 10] >>> a[5] = 0.0 >>> torch.cumprod(a, dim=0) 1.1148 2.0537 2.9045 -1.2788 -1.6444 -0.0000 0.0000 0.0000 -0.0000 0.0000 [torch.FloatTensor of size 10] """) add_docstr(torch._C.cumsum, """ cumsum(input, dim, out=None) -> Tensor Returns the cumulative sum of elements of :attr:`input` in the dimension :attr:`dim`. For example, if :attr:`input` is a vector of size N, the result will also be a vector of size N, with elements: :math:`y_i = x_1 + x_2 + x_3 + ... + x_i` Args: input (Tensor): the input `Tensor` dim (int): the dimension to do the operation over out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(10) >>> a -0.6039 -0.2214 -0.3705 -0.0169 1.3415 -0.1230 0.9719 0.6081 -0.1286 1.0947 [torch.FloatTensor of size 10] >>> torch.cumsum(a, dim=0) -0.6039 -0.8253 -1.1958 -1.2127 0.1288 0.0058 0.9777 1.5858 1.4572 2.5519 [torch.FloatTensor of size 10] """) add_docstr(torch._C.diag, """ diag(input, diagonal=0, out=None) -> Tensor - If :attr:`input` is a vector (1D Tensor), then returns a 2D square Tensor with the elements of :attr:`input` as the diagonal. - If :attr:`input` is a matrix (2D Tensor), then returns a 1D Tensor with the diagonal elements of :attr:`input`. The argument :attr:`diagonal` controls which diagonal to consider. - :attr:`diagonal` = 0, is the main diagonal. - :attr:`diagonal` > 0, is above the main diagonal. - :attr:`diagonal` < 0, is below the main diagonal. Args: input (Tensor): the input `Tensor` diagonal (int, optional): the diagonal to consider out (Tensor, optional): The result `Tensor` Example: Get the square matrix where the input vector is the diagonal:: >>> a = torch.randn(3) >>> a 1.0480 -2.3405 -1.1138 [torch.FloatTensor of size 3] >>> torch.diag(a) 1.0480 0.0000 0.0000 0.0000 -2.3405 0.0000 0.0000 0.0000 -1.1138 [torch.FloatTensor of size 3x3] >>> torch.diag(a, 1) 0.0000 1.0480 0.0000 0.0000 0.0000 0.0000 -2.3405 0.0000 0.0000 0.0000 0.0000 -1.1138 0.0000 0.0000 0.0000 0.0000 [torch.FloatTensor of size 4x4] Get the k-th diagonal of a given matrix:: >>> a = torch.randn(3, 3) >>> a -1.5328 -1.3210 -1.5204 0.8596 0.0471 -0.2239 -0.6617 0.0146 -1.0817 [torch.FloatTensor of size 3x3] >>> torch.diag(a, 0) -1.5328 0.0471 -1.0817 [torch.FloatTensor of size 3] >>> torch.diag(a, 1) -1.3210 -0.2239 [torch.FloatTensor of size 2] """) add_docstr(torch._C.dist, """ dist(input, other, p=2, out=None) -> Tensor Returns the p-norm of (:attr:`input` - :attr:`other`) Args: input (Tensor): the input `Tensor` other (Tensor): the Right-hand-side input `Tensor` p (float, optional): The norm to be computed. out (Tensor, optional): The result `Tensor` Example:: >>> x = torch.randn(4) >>> x 0.2505 -0.4571 -0.3733 0.7807 [torch.FloatTensor of size 4] >>> y = torch.randn(4) >>> y 0.7782 -0.5185 1.4106 -2.4063 [torch.FloatTensor of size 4] >>> torch.dist(x, y, 3.5) 3.302832063224223 >>> torch.dist(x, y, 3) 3.3677282206393286 >>> torch.dist(x, y, 0) inf >>> torch.dist(x, y, 1) 5.560028076171875 """) add_docstr(torch._C.div, """ .. function:: div(input, value, out=None) Divides each element of the input :attr:`input` with the scalar :attr:`value` and returns a new resulting tensor. :math:`out = tensor / value` If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input `Tensor` value (Number): the number to be divided to each element of :attr:`input` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(5) >>> a -0.6147 -1.1237 -0.1604 -0.6853 0.1063 [torch.FloatTensor of size 5] >>> torch.div(a, 0.5) -1.2294 -2.2474 -0.3208 -1.3706 0.2126 [torch.FloatTensor of size 5] .. function:: div(input, other, out=None) Each element of the Tensor :attr:`input` is divided by each element of the Tensor :attr:`other`. The resulting Tensor is returned. The shapes of :attr:`input` and :attr:`other` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`input` is used as the shape for the returned output Tensor :math:`out_i = input_i / other_i` Args: input (Tensor): the numerator `Tensor` other (Tensor): the denominator `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4,4) >>> a -0.1810 0.4017 0.2863 -0.1013 0.6183 2.0696 0.9012 -1.5933 0.5679 0.4743 -0.0117 -0.1266 -0.1213 0.9629 0.2682 1.5968 [torch.FloatTensor of size 4x4] >>> b = torch.randn(8, 2) >>> b 0.8774 0.7650 0.8866 1.4805 -0.6490 1.1172 1.4259 -0.8146 1.4633 -0.1228 0.4643 -0.6029 0.3492 1.5270 1.6103 -0.6291 [torch.FloatTensor of size 8x2] >>> torch.div(a, b) -0.2062 0.5251 0.3229 -0.0684 -0.9528 1.8525 0.6320 1.9559 0.3881 -3.8625 -0.0253 0.2099 -0.3473 0.6306 0.1666 -2.5381 [torch.FloatTensor of size 4x4] """) add_docstr(torch._C.dot, """ dot(tensor1, tensor2) -> float Computes the dot product (inner product) of two tensors. Both tensors are treated as 1-D vectors. Example:: >>> torch.dot(torch.Tensor([2, 3]), torch.Tensor([2, 1])) 7.0 """) add_docstr(torch._C.eig, """ eig(a, eigenvectors=False, out=None) -> (Tensor, Tensor) Computes the eigenvalues and eigenvectors of a real square matrix. Args: a (Tensor): A square matrix for which the eigenvalues and eigenvectors will be computed eigenvectors (bool): `True` to compute both eigenvalues and eigenvectors. Otherwise, only eigenvalues will be computed. out (tuple, optional): Output tensors Returns: (Tensor, Tensor): tuple containing - **e** (*Tensor*): the right eigenvalues of ``a`` - **v** (*Tensor*): the eigenvectors of ``a`` if ``eigenvectors` is ``True``; otherwise an empty tensor """) add_docstr(torch._C.eq, """ eq(input, other, out=None) -> Tensor Computes element-wise equality The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where the tensors are equal and a 0 at every other location Example:: >>> torch.eq(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 1 0 0 1 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.equal, """ equal(tensor1, tensor2) -> bool True if two tensors have the same size and elements, False otherwise. Example:: >>> torch.equal(torch.Tensor([1, 2]), torch.Tensor([1, 2])) True """) add_docstr(torch._C.exp, """ exp(tensor, out=None) -> Tensor Computes the exponential of each element. Example:: >>> torch.exp(torch.Tensor([0, math.log(2)])) torch.FloatTensor([1, 2]) """) add_docstr(torch._C.eye, """ eye(n, m=None, out=None) Returns a 2-D tensor with ones on the diagonal and zeros elsewhere. Args: n (int): Number of rows m (int, optional): Number of columns. If None, defaults to `n` out (Tensor, optional): Output tensor Returns: Tensor: a 2-D tensor with ones on the diagonal and zeros elsewhere Example:: >>> torch.eye(3) 1 0 0 0 1 0 0 0 1 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.floor, """ floor(input, out=None) -> Tensor Returns a new `Tensor` with the floor of the elements of :attr:`input`, the largest integer less than or equal to each element. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> torch.floor(a) 1 0 -1 -1 [torch.FloatTensor of size 4] """) add_docstr(torch._C.fmod, """ fmod(input, divisor, out=None) -> Tensor Computes the element-wise remainder of division. The dividend and divisor may contain both for integer and floating point numbers. The remainder has the same sign as the dividend `tensor`. Args: input (Tensor): The dividend divisor (Tensor or float): The divisor. This may be either a number or a tensor of the same shape as the dividend. out (Tensor, optional): Output tensor Example:: >>> torch.fmod(torch.Tensor([-3, -2, -1, 1, 2, 3]), 2) torch.FloatTensor([-1, -0, -1, 1, 0, 1]) >>> torch.fmod(torch.Tensor([1, 2, 3, 4, 5]), 1.5) torch.FloatTensor([1.0, 0.5, 0.0, 1.0, 0.5]) .. seealso:: :func:`torch.remainder`, which computes the element-wise remainder of division equivalently to Python's `%` operator """) add_docstr(torch._C.frac, """ frac(tensor, out=None) -> Tensor Computes the fractional portion of each element in `tensor`. Example:: >>> torch.frac(torch.Tensor([1, 2.5, -3.2]) torch.FloatTensor([0, 0.5, -0.2]) """) add_docstr(torch._C.from_numpy, """ from_numpy(ndarray) -> Tensor Creates a :class:`Tensor` from a :class:`numpy.ndarray`. The returned tensor and `ndarray` share the same memory. Modifications to the tensor will be reflected in the `ndarray` and vice versa. The returned tensor is not resizable. Example:: >>> a = numpy.array([1, 2, 3]) >>> t = torch.from_numpy(a) >>> t torch.LongTensor([1, 2, 3]) >>> t[0] = -1 >>> a array([-1, 2, 3]) """) add_docstr(torch._C.gather, """ gather(input, dim, index, out=None) -> Tensor Gathers values along an axis specified by `dim`. For a 3-D tensor the output is specified by:: out[i][j][k] = tensor[index[i][j][k]][j][k] # dim=0 out[i][j][k] = tensor[i][index[i][j][k]][k] # dim=1 out[i][j][k] = tensor[i][j][index[i][j][k]] # dim=3 Args: input (Tensor): The source tensor dim (int): The axis along which to index index (LongTensor): The indices of elements to gather out (Tensor, optional): Destination tensor Example:: >>> t = torch.Tensor([[1,2],[3,4]]) >>> torch.gather(t, 1, torch.LongTensor([[0,0],[1,0]])) 1 1 4 3 [torch.FloatTensor of size 2x2] """) add_docstr(torch._C.ge, """ ge(input, other, out=None) -> Tensor Computes `tensor >= other` element-wise. The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.ge(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 1 1 0 1 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.gels, r""" gels(B, A, out=None) -> Tensor Computes the solution to the least squares and least norm problems for a full rank :math:`m` by :math:`n` matrix :math:`A`. If :math:`m >= n`, :func:`gels` solves the least-squares problem: .. math:: \begin{array}{ll} \mbox{minimize} & \|AX-B\|_F. \end{array} If :math:`m < n`, :func:`gels` solves the least-norm problem: .. math:: \begin{array}{ll} \mbox{minimize} & \|X\|_F & \mbox{subject to} & AX = B. \end{array} The first :math:`n` rows of the returned matrix :math:`X` contains the solution. The remaining rows contain residual information: the euclidean norm of each column starting at row :math:`n` is the residual for the corresponding column. Args: B (Tensor): The matrix :math:`B` A (Tensor): The :math:`m` by :math:`n` matrix :math:`A` out (tuple, optional): Optional destination tensor Returns: (Tensor, Tensor): tuple containing: - **X** (*Tensor*): the least squares solution - **qr** (*Tensor*): the details of the QR factorization .. note:: The returned matrices will always be tranposed, irrespective of the strides of the input matrices. That is, they will have stride `(1, m)` instead of `(m, 1)`. Example:: >>> A = torch.Tensor([[1, 1, 1], ... [2, 3, 4], ... [3, 5, 2], ... [4, 2, 5], ... [5, 4, 3]]) >>> B = torch.Tensor([[-10, -3], [ 12, 14], [ 14, 12], [ 16, 16], [ 18, 16]]) >>> X, _ = torch.gels(B, A) >>> X 2.0000 1.0000 1.0000 1.0000 1.0000 2.0000 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.geqrf, r""" geqrf(input, out=None) -> (Tensor, Tensor) This is a low-level function for calling LAPACK directly. You'll generally want to use :func:`torch.qr` instead. Computes a QR decomposition of :attr:`input`, but without constructing `Q` and `R` as explicit separate matrices. Rather, this directly calls the underlying LAPACK function `?geqrf` which produces a sequence of 'elementary reflectors'. See `LAPACK documentation`_ for further details. Args: input (Tensor): the input matrix out (tuple, optional): The result tuple of (Tensor, Tensor) .. _LAPACK documentation: https://software.intel.com/en-us/node/521004 """) add_docstr(torch._C.ger, """ ger(vec1, vec2, out=None) -> Tensor Outer product of :attr:`vec1` and :attr:`vec2`. If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector of size `m`, then :attr:`out` must be a matrix of size `n x m`. Args: vec1 (Tensor): 1D input vector vec2 (Tensor): 1D input vector out (Tensor, optional): optional output matrix Example:: >>> v1 = torch.range(1, 4) >>> v2 = torch.range(1, 3) >>> torch.ger(v1, v2) 1 2 3 2 4 6 3 6 9 4 8 12 [torch.FloatTensor of size 4x3] """) add_docstr(torch._C.gesv, """ gesv(B, A, out=None) -> (Tensor, Tensor) `X, LU = torch.gesv(B, A)` returns the solution to the system of linear equations represented by :math:`AX = B` `LU` contains `L` and `U` factors for LU factorization of `A`. :attr:`A` has to be a square and non-singular matrix (2D Tensor). If `A` is an `m x m` matrix and `B` is `m x k`, the result `LU` is `m x m` and `X` is `m x k` . .. note:: Irrespective of the original strides, the returned matrices `X` and `LU` will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)`. Args: B (Tensor): input matrix of `m x k` dimensions A (Tensor): input square matrix of `m x m` dimensions out (Tensor, optional): optional output matrix Example:: >>> A = torch.Tensor([[6.80, -2.11, 5.66, 5.97, 8.23], ... [-6.05, -3.30, 5.36, -4.44, 1.08], ... [-0.45, 2.58, -2.70, 0.27, 9.04], ... [8.32, 2.71, 4.35, -7.17, 2.14], ... [-9.67, -5.14, -7.26, 6.08, -6.87]]).t() >>> B = torch.Tensor([[4.02, 6.19, -8.22, -7.57, -3.03], ... [-1.56, 4.00, -8.67, 1.75, 2.86], ... [9.81, -4.09, -4.57, -8.61, 8.99]]).t() >>> X, LU = torch.gesv(B, A) >>> torch.dist(B, torch.mm(A, X)) 9.250057093890353e-06 """) add_docstr(torch._C.get_num_threads, """ get_num_threads() -> int Gets the number of OpenMP threads used for parallelizing CPU operations """) add_docstr(torch._C.gt, """ gt(input, other, out=None) -> Tensor Computes `tensor > other` element-wise. The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.gt(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 0 1 0 0 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.histc, """ histc(input, bins=100, min=0, max=0, out=None) -> Tensor Computes the histogram of a tensor. The elements are sorted into equal width bins between `min` and `max`. If `min` and `max` are both zero, the minimum and maximum values of the data are used. Args: input (Tensor): Input data bins (int): Number of histogram bins min (int): Lower end of the range (inclusive) max (int): Upper end of the range (inclusive) out (Tensor, optional): Output argument Returns: Tensor: the histogram Example:: >>> torch.histc(torch.FloatTensor([1, 2, 1]), bins=4, min=0, max=3) FloatTensor([0, 2, 1, 0]) """) add_docstr(torch._C.index_select, """ index_select(input, dim, index, out=None) -> Tensor Returns a new `Tensor` which indexes the :attr:`input` `Tensor` along dimension :attr:`dim` using the entries in :attr:`index` which is a `LongTensor`. The returned `Tensor` has the same number of dimensions as the original `Tensor`. .. note:: The returned `Tensor` does **not** use the same storage as the original `Tensor` Args: input (Tensor): Input data dim (int): the dimension in which we index index (LongTensor): the 1D tensor containing the indices to index out (Tensor, optional): Output argument Example:: >>> x = torch.randn(3, 4) >>> x 1.2045 2.4084 0.4001 1.1372 0.5596 1.5677 0.6219 -0.7954 1.3635 -1.2313 -0.5414 -1.8478 [torch.FloatTensor of size 3x4] >>> indices = torch.LongTensor([0, 2]) >>> torch.index_select(x, 0, indices) 1.2045 2.4084 0.4001 1.1372 1.3635 -1.2313 -0.5414 -1.8478 [torch.FloatTensor of size 2x4] >>> torch.index_select(x, 1, indices) 1.2045 0.4001 0.5596 0.6219 1.3635 -0.5414 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.inverse, """ inverse(input, out=None) -> Tensor Takes the inverse of the square matrix :attr:`input`. .. note:: Irrespective of the original strides, the returned matrix will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)` Args: input (Tensor): the input 2D square `Tensor` out (Tensor, optional): the optional output `Tensor` Example:: >>> x = torch.rand(10, 10) >>> x 0.7800 0.2267 0.7855 0.9479 0.5914 0.7119 0.4437 0.9131 0.1289 0.1982 0.0045 0.0425 0.2229 0.4626 0.6210 0.0207 0.6338 0.7067 0.6381 0.8196 0.8350 0.7810 0.8526 0.9364 0.7504 0.2737 0.0694 0.5899 0.8516 0.3883 0.6280 0.6016 0.5357 0.2936 0.7827 0.2772 0.0744 0.2627 0.6326 0.9153 0.7897 0.0226 0.3102 0.0198 0.9415 0.9896 0.3528 0.9397 0.2074 0.6980 0.5235 0.6119 0.6522 0.3399 0.3205 0.5555 0.8454 0.3792 0.4927 0.6086 0.1048 0.0328 0.5734 0.6318 0.9802 0.4458 0.0979 0.3320 0.3701 0.0909 0.2616 0.3485 0.4370 0.5620 0.5291 0.8295 0.7693 0.1807 0.0650 0.8497 0.1655 0.2192 0.6913 0.0093 0.0178 0.3064 0.6715 0.5101 0.2561 0.3396 0.4370 0.4695 0.8333 0.1180 0.4266 0.4161 0.0699 0.4263 0.8865 0.2578 [torch.FloatTensor of size 10x10] >>> x = torch.rand(10, 10) >>> y = torch.inverse(x) >>> z = torch.mm(x, y) >>> z 1.0000 0.0000 0.0000 -0.0000 0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 0.0000 1.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0000 -0.0000 0.0000 0.0000 1.0000 -0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 0.0000 0.0000 0.0000 1.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 1.0000 0.0000 0.0000 -0.0000 -0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 0.0000 1.0000 -0.0000 -0.0000 -0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 0.0000 0.0000 1.0000 0.0000 -0.0000 0.0000 0.0000 0.0000 -0.0000 -0.0000 0.0000 0.0000 -0.0000 1.0000 -0.0000 0.0000 -0.0000 0.0000 -0.0000 -0.0000 0.0000 0.0000 -0.0000 -0.0000 1.0000 -0.0000 -0.0000 0.0000 -0.0000 -0.0000 -0.0000 0.0000 -0.0000 -0.0000 0.0000 1.0000 [torch.FloatTensor of size 10x10] >>> torch.max(torch.abs(z - torch.eye(10))) # Max nonzero 5.096662789583206e-07 """) add_docstr(torch._C.kthvalue, """ kthvalue(input, k, dim=None, out=None) -> (Tensor, LongTensor) Returns the :attr:`k`th smallest element of the given :attr:`input` Tensor along a given dimension. If :attr:`dim` is not given, the last dimension of the `input` is chosen. A tuple of `(values, indices)` is returned, where the `indices` is the indices of the kth-smallest element in the original `input` Tensor in dimention `dim`. Args: input (Tensor): the input `Tensor` k (int): k for the k-th smallest element dim (int, optional): The dimension to sort along out (tuple, optional): The output tuple of (Tensor, LongTensor) can be optionally given to be used as output buffers Example:: >>> x = torch.range(1, 5) >>> x 1 2 3 4 5 [torch.FloatTensor of size 5] >>> torch.kthvalue(x, 4) ( 4 [torch.FloatTensor of size 1] , 3 [torch.LongTensor of size 1] ) """) add_docstr(torch._C.le, """ le(input, other, out=None) -> Tensor Computes `tensor <= other` element-wise. The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.le(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 1 0 1 1 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.lerp, """ lerp(start, end, weight, out=None) Does a linear interpolation of two tensors :attr:`start` and :attr:`end` based on a scalar :attr:`weight`: and returns the resulting :attr:`out` Tensor. :math:`out_i = start_i + weight * (end_i - start_i)` Args: start (Tensor): the `Tensor` with the starting points end (Tensor): the `Tensor` with the ending points weight (float): the weight for the interpolation formula out (Tensor, optional): The result `Tensor` Example:: >>> start = torch.range(1, 4) >>> end = torch.Tensor(4).fill_(10) >>> start 1 2 3 4 [torch.FloatTensor of size 4] >>> end 10 10 10 10 [torch.FloatTensor of size 4] >>> torch.lerp(start, end, 0.5) 5.5000 6.0000 6.5000 7.0000 [torch.FloatTensor of size 4] """) add_docstr(torch._C.linspace, """ linspace(start, end, steps=100, out=None) -> Tensor Returns a one-dimensional Tensor of :attr:`steps` equally spaced points between :attr:`start` and :attr:`end` The output tensor is 1D of size :attr:`steps` Args: start (float): The starting value for the set of points end (float): The ending value for the set of points steps (int): Number of points to sample between :attr:`start` and :attr:`end` out (Tensor, optional): The result `Tensor` Example:: >>> torch.linspace(3, 10, steps=5) 3.0000 4.7500 6.5000 8.2500 10.0000 [torch.FloatTensor of size 5] >>> torch.linspace(-10, 10, steps=5) -10 -5 0 5 10 [torch.FloatTensor of size 5] >>> torch.linspace(start=-10, end=10, steps=5) -10 -5 0 5 10 [torch.FloatTensor of size 5] """) add_docstr(torch._C.log, """ log(input, out=None) -> Tensor Returns a new `Tensor` with the natural logarithm of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(5) >>> a -0.4183 0.3722 -0.3091 0.4149 0.5857 [torch.FloatTensor of size 5] >>> torch.log(a) nan -0.9883 nan -0.8797 -0.5349 [torch.FloatTensor of size 5] """) add_docstr(torch._C.log1p, """ log1p(input, out=None) -> Tensor Returns a new `Tensor` with the natural logarithm of (1 + :attr:`input`). :math:`y_i = log(x_i + 1)` .. note:: This function is more accurate than :func:`torch.log` for small values of :attr:`input` Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(5) >>> a -0.4183 0.3722 -0.3091 0.4149 0.5857 [torch.FloatTensor of size 5] >>> torch.log1p(a) -0.5418 0.3164 -0.3697 0.3471 0.4611 [torch.FloatTensor of size 5] """) add_docstr(torch._C.logspace, """ logspace(start, end, steps=100, out=None) -> Tensor Returns a one-dimensional Tensor of :attr:`steps` points logarithmically spaced between :math:`10^{start}` and :math:`10^{end}` The output is a 1D tensor of size :attr:`steps` Args: start (float): The starting value for the set of points end (float): The ending value for the set of points steps (int): Number of points to sample between :attr:`start` and :attr:`end` out (Tensor, optional): The result `Tensor` Example:: >>> torch.logspace(start=-10, end=10, steps=5) 1.0000e-10 1.0000e-05 1.0000e+00 1.0000e+05 1.0000e+10 [torch.FloatTensor of size 5] >>> torch.logspace(start=0.1, end=1.0, steps=5) 1.2589 2.1135 3.5481 5.9566 10.0000 [torch.FloatTensor of size 5] """) add_docstr(torch._C.lt, """ lt(input, other, out=None) -> Tensor Computes `tensor < other` element-wise. The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.lt(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 0 0 1 0 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.masked_select, """ masked_select(input, mask, out=None) -> Tensor Returns a new 1D `Tensor` which indexes the :attr:`input` `Tensor` according to the binary mask :attr:`mask` which is a `ByteTensor`. The :attr:`mask` tensor needs to have the same number of elements as :attr:`input`, but it's shape or dimensionality are irrelevant. .. note:: The returned `Tensor` does **not** use the same storage as the original `Tensor` Args: input (Tensor): Input data mask (ByteTensor): the tensor containing the binary mask to index with out (Tensor, optional): Output argument Example:: >>> x = torch.randn(3, 4) >>> x 1.2045 2.4084 0.4001 1.1372 0.5596 1.5677 0.6219 -0.7954 1.3635 -1.2313 -0.5414 -1.8478 [torch.FloatTensor of size 3x4] >>> mask = x.ge(0.5) >>> mask 1 1 0 1 1 1 1 0 1 0 0 0 [torch.ByteTensor of size 3x4] >>> torch.masked_select(x, mask) 1.2045 2.4084 1.1372 0.5596 1.5677 0.6219 1.3635 [torch.FloatTensor of size 7] """) add_docstr(torch._C.max, """ .. function:: max(input) -> float Returns the maximum value of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a 0.4729 -0.2266 -0.2085 [torch.FloatTensor of size 1x3] >>> torch.max(a) 0.4729 .. function:: max(input, dim, max=None, max_indices=None) -> (Tensor, LongTensor) Returns the maximum value of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. Also returns the index location of each maximum value found. The output Tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce max (Tensor, optional): the result Tensor with maximum values in dimension :attr:`dim` max_indices (LongTensor, optional): the result Tensor with the index locations of the maximum values in dimension :attr:`dim` Example:: >> a = torch.randn(4, 4) >> a 0.0692 0.3142 1.2513 -0.5428 0.9288 0.8552 -0.2073 0.6409 1.0695 -0.0101 -2.4507 -1.2230 0.7426 -0.7666 0.4862 -0.6628 torch.FloatTensor of size 4x4] >>> torch.max(a, 1) ( 1.2513 0.9288 1.0695 0.7426 [torch.FloatTensor of size 4x1] , 2 0 0 0 [torch.LongTensor of size 4x1] ) .. function:: max(input, other, out=None) -> Tensor Each element of the Tensor :attr:`input` is compared with the corresponding element of the Tensor :attr:`other` and an element-wise `max` is taken. The shapes of :attr:`input` and :attr:`other` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`input` is used as the shape for the returned output Tensor :math:`out_i = max(tensor_i, other_i)` Args: input (Tensor): the input `Tensor` other (Tensor): the second input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> b = torch.randn(4) >>> b 1.0067 -0.8010 0.6258 0.3627 [torch.FloatTensor of size 4] >>> torch.max(a, b) 1.3869 0.3912 0.6258 0.3627 [torch.FloatTensor of size 4] """) add_docstr(torch._C.mean, """ .. function:: mean(input) -> float Returns the mean value of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a -0.2946 -0.9143 2.1809 [torch.FloatTensor of size 1x3] >>> torch.mean(a) 0.32398951053619385 .. function:: mean(input, dim, out=None) -> Tensor Returns the mean value of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 4) >>> a -1.2738 -0.3058 0.1230 -1.9615 0.8771 -0.5430 -0.9233 0.9879 1.4107 0.0317 -0.6823 0.2255 -1.3854 0.4953 -0.2160 0.2435 [torch.FloatTensor of size 4x4] >>> torch.mean(a, 1) -0.8545 0.0997 0.2464 -0.2157 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.median, """ median(input, dim=-1, values=None, indices=None) -> (Tensor, LongTensor) Returns the median value of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. Also returns the index location of the median value as a `LongTensor`. By default, :attr:`dim` is the last dimension of the :attr:`input` Tensor. The output Tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. .. note:: This function is not defined for ``torch.cuda.Tensor`` yet. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce values (Tensor, optional): the result Tensor indices (Tensor, optional): the result index Tensor Example:: >>> a -0.6891 -0.6662 0.2697 0.7412 0.5254 -0.7402 0.5528 -0.2399 [torch.FloatTensor of size 4x2] >>> a = torch.randn(4, 5) >>> a 0.4056 -0.3372 1.0973 -2.4884 0.4334 2.1336 0.3841 0.1404 -0.1821 -0.7646 -0.2403 1.3975 -2.0068 0.1298 0.0212 -1.5371 -0.7257 -0.4871 -0.2359 -1.1724 [torch.FloatTensor of size 4x5] >>> torch.median(a, 1) ( 0.4056 0.1404 0.0212 -0.7257 [torch.FloatTensor of size 4x1] , 0 2 4 1 [torch.LongTensor of size 4x1] ) """) add_docstr(torch._C.min, """ .. function:: min(input) -> float Returns the minimum value of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a 0.4729 -0.2266 -0.2085 [torch.FloatTensor of size 1x3] >>> torch.min(a) -0.22663167119026184 .. function:: min(input, dim, min=None, min_indices=None) -> (Tensor, LongTensor) Returns the minimum value of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. Also returns the index location of each minimum value found. The output Tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where they are of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce min (Tensor, optional): the result Tensor with minimum values in dimension :attr:`dim` min_indices (LongTensor, optional): the result Tensor with the index locations of the minimum values in dimension :attr:`dim` Example:: >> a = torch.randn(4, 4) >> a 0.0692 0.3142 1.2513 -0.5428 0.9288 0.8552 -0.2073 0.6409 1.0695 -0.0101 -2.4507 -1.2230 0.7426 -0.7666 0.4862 -0.6628 torch.FloatTensor of size 4x4] >> torch.min(a, 1) 0.5428 0.2073 2.4507 0.7666 torch.FloatTensor of size 4x1] 3 2 2 1 torch.LongTensor of size 4x1] .. function:: min(input, other, out=None) -> Tensor Each element of the Tensor :attr:`input` is compared with the corresponding element of the Tensor :attr:`other` and an element-wise `min` is taken. The resulting Tensor is returned. The shapes of :attr:`input` and :attr:`other` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`input` is used as the shape for the returned output Tensor :math:`out_i = min(tensor_i, other_i)` Args: input (Tensor): the input `Tensor` other (Tensor): the second input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.3869 0.3912 -0.8634 -0.5468 [torch.FloatTensor of size 4] >>> b = torch.randn(4) >>> b 1.0067 -0.8010 0.6258 0.3627 [torch.FloatTensor of size 4] >>> torch.min(a, b) 1.0067 -0.8010 -0.8634 -0.5468 [torch.FloatTensor of size 4] """) add_docstr(torch._C.mm, """ mm(mat1, mat2, out=None) -> Tensor Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`. If :attr:`mat1` is a `n x m` Tensor, :attr:`mat2` is a `m x p` Tensor, :attr:`out` will be a `n x p` Tensor. Args: mat1 (Tensor): First matrix to be multiplied mat2 (Tensor): Second matrix to be multiplied out (Tensor, optional): Output tensor Example:: >>> mat1 = torch.randn(2, 3) >>> mat2 = torch.randn(3, 3) >>> torch.mm(mat1, mat2) 0.0519 -0.3304 1.2232 4.3910 -5.1498 2.7571 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.mode, """ mode(input, dim=-1, values=None, indices=None) -> (Tensor, LongTensor) Returns the mode value of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. Also returns the index location of the mode value as a `LongTensor`. By default, :attr:`dim` is the last dimension of the :attr:`input` Tensor. The output Tensors are of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. .. note:: This function is not defined for ``torch.cuda.Tensor`` yet. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce values (Tensor, optional): the result Tensor indices (Tensor, optional): the result index Tensor Example:: >>> a -0.6891 -0.6662 0.2697 0.7412 0.5254 -0.7402 0.5528 -0.2399 [torch.FloatTensor of size 4x2] >>> a = torch.randn(4, 5) >>> a 0.4056 -0.3372 1.0973 -2.4884 0.4334 2.1336 0.3841 0.1404 -0.1821 -0.7646 -0.2403 1.3975 -2.0068 0.1298 0.0212 -1.5371 -0.7257 -0.4871 -0.2359 -1.1724 [torch.FloatTensor of size 4x5] >>> torch.mode(a, 1) ( -2.4884 -0.7646 -2.0068 -1.5371 [torch.FloatTensor of size 4x1] , 3 4 2 0 [torch.LongTensor of size 4x1] ) """) add_docstr(torch._C.mul, """ .. function:: mul(input, value, out=None) Multiplies each element of the input :attr:`input` with the scalar :attr:`value` and returns a new resulting tensor. :math:`out = tensor * value` If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`value` should be a real number, otherwise it should be an integer Args: input (Tensor): the input `Tensor` value (Number): the number to be multiplied to each element of :attr:`input` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(3) >>> a -0.9374 -0.5254 -0.6069 [torch.FloatTensor of size 3] >>> torch.mul(a, 100) -93.7411 -52.5374 -60.6908 [torch.FloatTensor of size 3] .. function:: mul(input, other, out=None) Each element of the Tensor :attr:`input` is multiplied by each element of the Tensor :attr:`other`. The resulting Tensor is returned. The shapes of :attr:`input` and :attr:`other` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`input` is used as the shape for the returned output Tensor :math:`out_i = input_i * other_i` Args: input (Tensor): the first multiplicand `Tensor` other (Tensor): the second multiplicand `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4,4) >>> a -0.7280 0.0598 -1.4327 -0.5825 -0.1427 -0.0690 0.0821 -0.3270 -0.9241 0.5110 0.4070 -1.1188 -0.8308 0.7426 -0.6240 -1.1582 [torch.FloatTensor of size 4x4] >>> b = torch.randn(2, 8) >>> b 0.0430 -1.0775 0.6015 1.1647 -0.6549 0.0308 -0.1670 1.0742 -1.2593 0.0292 -0.0849 0.4530 1.2404 -0.4659 -0.1840 0.5974 [torch.FloatTensor of size 2x8] >>> torch.mul(a, b) -0.0313 -0.0645 -0.8618 -0.6784 0.0934 -0.0021 -0.0137 -0.3513 1.1638 0.0149 -0.0346 -0.5068 -1.0304 -0.3460 0.1148 -0.6919 [torch.FloatTensor of size 4x4] """) add_docstr(torch._C.multinomial, u""" multinomial(input, num_samples, replacement=False, out=None) -> LongTensor Returns a Tensor where each row contains :attr:`num_samples` indices sampled from the multinomial probability distribution located in the corresponding row of Tensor :attr:`input`. .. note:: The rows of :attr:`input` do not need to sum to one (in which case we use the values as weights), but must be non-negative and have a non-zero sum. Indices are ordered from left to right according to when each was sampled (first samples are placed in first column). If :attr:`input` is a vector, :attr:`out` is a vector of size `num_samples`. If :attr:`input` is a matrix with `m` rows, :attr:`out` is an matrix of shape `m \u00D7 n`. If replacement is `True`, samples are drawn with replacement. If not, they are drawn without replacement, which means that when a sample index is drawn for a row, it cannot be drawn again for that row. This implies the constraint that :attr:`num_samples` must be lower than :attr:`input` length (or number of columns of :attr:`input` if it is a matrix). Args: input (Tensor): Tensor containing probabilities num_samples (int): number of samples to draw replacement (bool, optional): Whether to draw with replacement or not out (Tensor, optional): The result `Tensor` Example:: >>> weights = torch.Tensor([0, 10, 3, 0]) # create a Tensor of weights >>> torch.multinomial(weights, 4) 1 2 0 0 [torch.LongTensor of size 4] >>> torch.multinomial(weights, 4, replacement=True) 1 2 1 2 [torch.LongTensor of size 4] """) add_docstr(torch._C.mv, """ mv(mat, vec, out=None) -> Tensor Performs a matrix-vector product of the matrix :attr:`mat` and the vector :attr:`vec`. If :attr:`mat` is a `n x m` Tensor, :attr:`vec` is a 1D Tensor of size `m`, :attr:`out` will be 1D of size `n`. Args: mat (Tensor): matrix to be multiplied vec (Tensor): vector to be multiplied out (Tensor, optional): Output tensor Example:: >>> mat = torch.randn(2, 3) >>> vec = torch.randn(3) >>> torch.mv(mat, vec) -2.0939 -2.2950 [torch.FloatTensor of size 2] """) add_docstr(torch._C.ne, """ ne(input, other, out=None) -> Tensor Computes `tensor != other` element-wise. The second argument can be a number or a tensor of the same shape and type as the first argument. Args: input (Tensor): Tensor to compare other (Tensor or float): Tensor or value to compare out (Tensor, optional): Output tensor. Must be a `ByteTensor` or the same type as `tensor`. Returns: Tensor: a ``torch.ByteTensor`` containing a 1 at each location where comparison is true. Example:: >>> torch.ne(torch.Tensor([[1, 2], [3, 4]]), torch.Tensor([[1, 1], [4, 4]])) 0 1 1 0 [torch.ByteTensor of size 2x2] """) add_docstr(torch._C.neg, """ neg(input, out=None) -> Tensor Returns a new `Tensor` with the negative of the elements of :attr:`input`. :math:`out = -1 * input` Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(5) >>> a -0.4430 1.1690 -0.8836 -0.4565 0.2968 [torch.FloatTensor of size 5] >>> torch.neg(a) 0.4430 -1.1690 0.8836 0.4565 -0.2968 [torch.FloatTensor of size 5] """) add_docstr(torch._C.nonzero, """ nonzero(input, out=None) -> LongTensor Returns a tensor containing the indices of all non-zero elements of :attr:`input`. Each row in the result contains the indices of a non-zero element in :attr:`input`. If :attr:`input` has `n` dimensions, then the resulting indices Tensor :attr:`out` is of size `z x n`, where `z` is the total number of non-zero elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` out (LongTensor, optional): The result `Tensor` containing indices Example:: >>> torch.nonzero(torch.Tensor([1, 1, 1, 0, 1])) 0 1 2 4 [torch.LongTensor of size 4x1] >>> torch.nonzero(torch.Tensor([[0.6, 0.0, 0.0, 0.0], ... [0.0, 0.4, 0.0, 0.0], ... [0.0, 0.0, 1.2, 0.0], ... [0.0, 0.0, 0.0,-0.4]])) 0 0 1 1 2 2 3 3 [torch.LongTensor of size 4x2] """) add_docstr(torch._C.norm, """ .. function:: norm(input, p=2) -> float Returns the p-norm of the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` p (float, optional): the exponent value in the norm formulation Example:: >>> a = torch.randn(1, 3) >>> a -0.4376 -0.5328 0.9547 [torch.FloatTensor of size 1x3] >>> torch.norm(a, 3) 1.0338925067372466 .. function:: norm(input, p, dim, out=None) -> Tensor Returns the p-norm of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` p (float): the exponent value in the norm formulation dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 2) >>> a -0.6891 -0.6662 0.2697 0.7412 0.5254 -0.7402 0.5528 -0.2399 [torch.FloatTensor of size 4x2] >>> torch.norm(a, 2, 1) 0.9585 0.7888 0.9077 0.6026 [torch.FloatTensor of size 4x1] >>> torch.norm(a, 0, 1) 2 2 2 2 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.normal, """ .. function:: normal(means, std, out=None) Returns a Tensor of random numbers drawn from separate normal distributions who's mean and standard deviation are given. The :attr:`means` is a Tensor with the mean of each output element's normal distribution The :attr:`std` is a Tensor with the standard deviation of each output element's normal distribution The shapes of :attr:`means` and :attr:`std` don't need to match. The total number of elements in each Tensor need to be the same. .. note:: When the shapes do not match, the shape of :attr:`means` is used as the shape for the returned output Tensor Args: means (Tensor): the Tensor of per-element means std (Tensor): the Tensor of per-element standard deviations out (Tensor): the optional result Tensor Example:: torch.normal(means=torch.range(1, 10), std=torch.range(1, 0.1, -0.1)) 1.5104 1.6955 2.4895 4.9185 4.9895 6.9155 7.3683 8.1836 8.7164 9.8916 [torch.FloatTensor of size 10] .. function:: normal(mean=0.0, std, out=None) Similar to the function above, but the means are shared among all drawn elements. Args: means (float, optional): the mean for all distributions std (Tensor): the Tensor of per-element standard deviations out (Tensor): the optional result Tensor Example:: >>> torch.normal(mean=0.5, std=torch.range(1, 5)) 0.5723 0.0871 -0.3783 -2.5689 10.7893 [torch.FloatTensor of size 5] .. function:: normal(means, std=1.0, out=None) Similar to the function above, but the standard-deviations are shared among all drawn elements. Args: means (Tensor): the Tensor of per-element means std (float, optional): the standard deviation for all distributions out (Tensor): the optional result Tensor Example:: >>> torch.normal(means=torch.range(1, 5)) 1.1681 2.8884 3.7718 2.5616 4.2500 [torch.FloatTensor of size 5] """) add_docstr(torch._C.numel, """ numel(input) -> int Returns the total number of elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1,2,3,4,5) >>> torch.numel(a) 120 >>> a = torch.zeros(4,4) >>> torch.numel(a) 16 """) add_docstr(torch._C.ones, """ ones(*sizes, out=None) -> Tensor Returns a Tensor filled with the scalar value `1`, with the shape defined by the varargs :attr:`sizes`. Args: sizes (int...): a set of ints defining the shape of the output Tensor. out (Tensor, optional): the result Tensor Example:: >>> torch.ones(2, 3) 1 1 1 1 1 1 [torch.FloatTensor of size 2x3] >>> torch.ones(5) 1 1 1 1 1 [torch.FloatTensor of size 5] """) # TODO # add_docstr(torch._C.orgqr, # """ # """) # add_docstr(torch._C.ormqr, # """ # """) # add_docstr(torch._C.potrf, # """ # """) # add_docstr(torch._C.potri, # """ # """) # add_docstr(torch._C.potrs, # """ # """) add_docstr(torch._C.pow, """ .. function:: pow(input, exponent, out=None) Takes the power of each element in :attr:`input` with :attr:`exponent` and returns a Tensor with the result. :attr:`exponent` can be either a single ``float`` number or a ``Tensor`` with the same number of elements as :attr:`input`. When :attr:`exponent` is a scalar value, the operation applied is: :math:`out_i = x_i ^ {exponent}` When :attr:`exponent` is a Tensor, the operation applied is: :math:`out_i = x_i ^ {exponent_i}` Args: input (Tensor): the input `Tensor` exponent (float or Tensor): the exponent value out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.5274 -0.8232 -2.1128 1.7558 [torch.FloatTensor of size 4] >>> torch.pow(a, 2) 0.2781 0.6776 4.4640 3.0829 [torch.FloatTensor of size 4] >>> exp = torch.range(1, 4) >>> a = torch.range(1, 4) >>> a 1 2 3 4 [torch.FloatTensor of size 4] >>> exp 1 2 3 4 [torch.FloatTensor of size 4] >>> torch.pow(a, exp) 1 4 27 256 [torch.FloatTensor of size 4] .. function:: pow(base, input, out=None) :attr:`base` is a scalar ``float`` value, and :attr:`input` is a Tensor. The returned Tensor :attr:`out` is of the same shape as :attr:`input` The operation applied is: :math:`out_i = base ^ {input_i}` Args: base (float): the scalar base value for the power operation input (Tensor): the exponent `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> exp = torch.range(1, 4) >>> base = 2 >>> torch.pow(base, exp) 2 4 8 16 [torch.FloatTensor of size 4] """) add_docstr(torch._C.prod, """ .. function:: prod(input) -> float Returns the product of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a 0.6170 0.3546 0.0253 [torch.FloatTensor of size 1x3] >>> torch.prod(a) 0.005537458061418483 .. function:: prod(input, dim, out=None) -> Tensor Returns the product of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 2) >>> a 0.1598 -0.6884 -0.1831 -0.4412 -0.9925 -0.6244 -0.2416 -0.8080 [torch.FloatTensor of size 4x2] >>> torch.prod(a, 1) -0.1100 0.0808 0.6197 0.1952 [torch.FloatTensor of size 4x1] """) # TODO # add_docstr(torch._C.pstrf, # """ # """) add_docstr(torch._C.qr, """ qr(input, out=None) -> (Tensor, Tensor) Computes the QR decomposition of a matrix :attr:`input`: returns matrices `q` and `r` such that :math:`x = q * r`, with `q` being an orthogonal matrix and `r` being an upper triangular matrix. This returns the thin (reduced) QR factorization. .. note:: precision may be lost if the magnitudes of the elements of `input` are large .. note:: while it should always give you a valid decomposition, it may not give you the same one across platforms - it will depend on your LAPACK implementation. .. note:: Irrespective of the original strides, the returned matrix `q` will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)`. Args: input (Tensor): the input 2D `Tensor` out (tuple, optional): A tuple of Q and R Tensors Example:: >>> a = torch.Tensor([[12, -51, 4], [6, 167, -68], [-4, 24, -41]]) >>> q, r = torch.qr(a) >>> q -0.8571 0.3943 0.3314 -0.4286 -0.9029 -0.0343 0.2857 -0.1714 0.9429 [torch.FloatTensor of size 3x3] >>> r -14.0000 -21.0000 14.0000 0.0000 -175.0000 70.0000 0.0000 0.0000 -35.0000 [torch.FloatTensor of size 3x3] >>> torch.mm(q, r).round() 12 -51 4 6 167 -68 -4 24 -41 [torch.FloatTensor of size 3x3] >>> torch.mm(q.t(), q).round() 1 -0 0 -0 1 0 0 0 1 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.rand, """ rand(*sizes, out=None) -> Tensor Returns a Tensor filled with random numbers from a uniform distribution on the interval :math:`[0, 1)` The shape of the Tensor is defined by the varargs :attr:`sizes`. Args: sizes (int...): a set of ints defining the shape of the output Tensor. out (Tensor, optional): the result Tensor Example:: >>> torch.rand(4) 0.9193 0.3347 0.3232 0.7715 [torch.FloatTensor of size 4] >>> torch.rand(2, 3) 0.5010 0.5140 0.0719 0.1435 0.5636 0.0538 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.randn, """ randn(*sizes, out=None) -> Tensor Returns a Tensor filled with random numbers from a normal distribution with zero mean and variance of one. The shape of the Tensor is defined by the varargs :attr:`sizes`. Args: sizes (int...): a set of ints defining the shape of the output Tensor. out (Tensor, optional): the result Tensor Example:: >>> torch.randn(4) -0.1145 0.0094 -1.1717 0.9846 [torch.FloatTensor of size 4] >>> torch.randn(2, 3) 1.4339 0.3351 -1.0999 1.5458 -0.9643 -0.3558 [torch.FloatTensor of size 2x3] """) add_docstr(torch._C.randperm, """ randperm(n, out=None) -> LongTensor Returns a random permutation of integers from ``0`` to ``n - 1``. Args: n (int): the upper bound (exclusive) Example:: >>> torch.randperm(4) 2 1 3 0 [torch.LongTensor of size 4] """) add_docstr(torch._C.range, """ range(start, end, step=1, out=None) -> Tensor returns a 1D Tensor of size :math:`floor((end - start) / step) + 1` with values from :attr:`start` to :attr:`end` with step :attr:`step`. Step is the gap between two values in the tensor. :math:`x_{i+1} = x_i + step` Args: start (float): The starting value for the set of points end (float): The ending value for the set of points step (float): The gap between each pair of adjacent points out (Tensor, optional): The result `Tensor` Example:: >>> torch.range(1, 4) 1 2 3 4 [torch.FloatTensor of size 4] >>> torch.range(1, 4, 0.5) 1.0000 1.5000 2.0000 2.5000 3.0000 3.5000 4.0000 [torch.FloatTensor of size 7] """) add_docstr(torch._C.remainder, """ remainder(input, divisor, out=None) -> Tensor Computes the element-wise remainder of division. The divisor and dividend may contain both for integer and floating point numbers. The remainder has the same sign as the divisor. Args: input (Tensor): The dividend divisor (Tensor or float): The divisor. This may be either a number or a tensor of the same shape as the dividend. out (Tensor, optional): Output tensor Example:: >>> torch.remainder(torch.Tensor([-3, -2, -1, 1, 2, 3]), 2) torch.FloatTensor([1, 0, 1, 1, 0, 1]) >>> torch.remainder(torch.Tensor([1, 2, 3, 4, 5]), 1.5) torch.FloatTensor([1.0, 0.5, 0.0, 1.0, 0.5]) .. seealso:: :func:`torch.fmod`, which computes the element-wise remainder of division equivalently to the C library function ``fmod()`` """) add_docstr(torch._C.renorm, """ renorm(input, p, dim, maxnorm, out=None) -> Tensor Returns a Tensor where each sub-tensor of :attr:`input` along dimension :attr:`dim` is normalized such that the `p`-norm of the sub-tensor is lower than the value :attr:`maxnorm` .. note:: If the norm of a row is lower than `maxnorm`, the row is unchanged Args: input (Tensor): The input Tensor p (float): The power for the norm computation dim (int): The dimension to slice over to get the sub-tensors maxnorm (float): The maximum norm to keep each sub-tensor under out (Tensor, optional): Output tensor Example:: >>> x = torch.ones(3, 3) >>> x[1].fill_(2) >>> x[2].fill_(3) >>> x 1 1 1 2 2 2 3 3 3 [torch.FloatTensor of size 3x3] >>> torch.renorm(x, 1, 0, 5) 1.0000 1.0000 1.0000 1.6667 1.6667 1.6667 1.6667 1.6667 1.6667 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.round, """ round(input, out=None) -> Tensor Returns a new `Tensor` with each of the elements of :attr:`input` rounded to the closest integer. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.2290 1.3409 -0.5662 -0.0899 [torch.FloatTensor of size 4] >>> torch.round(a) 1 1 -1 -0 [torch.FloatTensor of size 4] """) add_docstr(torch._C.rsqrt, """ rsqrt(input, out=None) -> Tensor Returns a new `Tensor` with the reciprocal of the square-root of each of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.2290 1.3409 -0.5662 -0.0899 [torch.FloatTensor of size 4] >>> torch.rsqrt(a) 0.9020 0.8636 nan nan [torch.FloatTensor of size 4] """) add_docstr(torch._C.set_num_threads, """ set_num_threads(int) Sets the number of OpenMP threads used for parallelizing CPU operations """) add_docstr(torch._C.sigmoid, """ sigmoid(input, out=None) -> Tensor Returns a new `Tensor` with the sigmoid of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.4972 1.3512 0.1056 -0.2650 [torch.FloatTensor of size 4] >>> torch.sigmoid(a) 0.3782 0.7943 0.5264 0.4341 [torch.FloatTensor of size 4] """) add_docstr(torch._C.sign, """ sign(input, out=None) -> Tensor Returns a new `Tensor` with the sign of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.sign(a) -1 1 1 1 [torch.FloatTensor of size 4] """) add_docstr(torch._C.sin, """ sin(input, out=None) -> Tensor Returns a new `Tensor` with the sine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.sin(a) -0.5944 0.2684 0.4322 0.9667 [torch.FloatTensor of size 4] """) add_docstr(torch._C.sinh, """ sinh(input, out=None) -> Tensor Returns a new `Tensor` with the hyperbolic sine of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.sinh(a) -0.6804 0.2751 0.4619 1.7225 [torch.FloatTensor of size 4] """) add_docstr(torch._C.sort, """ sort(input, dim=None, descending=False, out=None) -> (Tensor, LongTensor) Sorts the elements of the :attr:`input` Tensor along a given dimension in ascending order by value. If :attr:`dim` is not given, the last dimension of the `input` is chosen. If :attr:`descending` is `True` then the elements are sorted in descending order by value. A tuple of (sorted_tensor, sorted_indices) is returned, where the sorted_indices are the indices of the elements in the original `input` Tensor. Args: input (Tensor): the input `Tensor` dim (int, optional): The dimension to sort along descending (bool, optional): Controls the sorting order (ascending or descending) out (tuple, optional): The output tuple of (Tensor, LongTensor) can be optionally given to be used as output buffers Example:: >>> x = torch.randn(3, 4) >>> sorted, indices = torch.sort(x) >>> sorted -1.6747 0.0610 0.1190 1.4137 -1.4782 0.7159 1.0341 1.3678 -0.3324 -0.0782 0.3518 0.4763 [torch.FloatTensor of size 3x4] >>> indices 0 1 3 2 2 1 0 3 3 1 0 2 [torch.LongTensor of size 3x4] >>> sorted, indices = torch.sort(x, 0) >>> sorted -1.6747 -0.0782 -1.4782 -0.3324 0.3518 0.0610 0.4763 0.1190 1.0341 0.7159 1.4137 1.3678 [torch.FloatTensor of size 3x4] >>> indices 0 2 1 2 2 0 2 0 1 1 0 1 [torch.LongTensor of size 3x4] """) add_docstr(torch._C.sqrt, """ sqrt(input, out=None) -> Tensor Returns a new `Tensor` with the square-root of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a 1.2290 1.3409 -0.5662 -0.0899 [torch.FloatTensor of size 4] >>> torch.sqrt(a) 1.1086 1.1580 nan nan [torch.FloatTensor of size 4] """) add_docstr(torch._C.squeeze, """ squeeze(input, dim=None, out=None) Returns a `Tensor` with all the dimensions of :attr:`input` of size `1` removed. If `input` is of shape: :math:`(A x 1 x B x C x 1 x D)` then the `out` Tensor will be of shape: :math:`(A x B x C x D)` When :attr:`dim` is given, a squeeze operation is done only in the given dimension. If `input` is of shape: :math:`(A x 1 x B)`, `squeeze(input, 0)` leaves the Tensor unchanged, but `squeeze(input, 1)` will squeeze the tensor to the shape :math:`(A x B)`. .. note:: The returned Tensor shares the storage with the input Tensor, so changing the contents of one will change the contents of the other. Args: input (Tensor): the input `Tensor` dim (int, optional): if given, the input will be squeezed only in this dimension out (Tensor, optional): The result `Tensor` Example:: >>> x = torch.zeros(2,1,2,1,2) >>> x.size() (2L, 1L, 2L, 1L, 2L) >>> y = torch.squeeze(x) >>> y.size() (2L, 2L, 2L) >>> y = torch.squeeze(x, 0) >>> y.size() (2L, 1L, 2L, 1L, 2L) >>> y = torch.squeeze(x, 1) >>> y.size() (2L, 2L, 1L, 2L) """) add_docstr(torch._C.std, """ .. function:: std(input) -> float Returns the standard-deviation of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a -1.3063 1.4182 -0.3061 [torch.FloatTensor of size 1x3] >>> torch.std(a) 1.3782334731508061 .. function:: std(input, dim, out=None) -> Tensor Returns the standard-deviation of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 4) >>> a 0.1889 -2.4856 0.0043 1.8169 -0.7701 -0.4682 -2.2410 0.4098 0.1919 -1.1856 -1.0361 0.9085 0.0173 1.0662 0.2143 -0.5576 [torch.FloatTensor of size 4x4] >>> torch.std(a, dim=1) 1.7756 1.1025 1.0045 0.6725 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.sum, """ .. function:: sum(input) -> float Returns the sum of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a 0.6170 0.3546 0.0253 [torch.FloatTensor of size 1x3] >>> torch.sum(a) 0.9969287421554327 .. function:: sum(input, dim, out=None) -> Tensor Returns the sum of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 4) >>> a -0.4640 0.0609 0.1122 0.4784 -1.3063 1.6443 0.4714 -0.7396 -1.3561 -0.1959 1.0609 -1.9855 2.6833 0.5746 -0.5709 -0.4430 [torch.FloatTensor of size 4x4] >>> torch.sum(a, 1) 0.1874 0.0698 -2.4767 2.2440 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.svd, """ svd(input, some=True, out=None) -> (Tensor, Tensor, Tensor) `U, S, V = torch.svd(A)` returns the singular value decomposition of a real matrix `A` of size `(n x m)` such that :math:`A = USV'*`. `U` is of shape `n x n` `S` is of shape `n x m` `V` is of shape `m x m`. :attr:`some` represents the number of singular values to be computed. If `some=True`, it computes some and `some=False` computes all. .. note:: Irrespective of the original strides, the returned matrix `U` will be transposed, i.e. with strides `(1, n)` instead of `(n, 1)`. Args: input (Tensor): the input 2D Tensor some (bool, optional): controls the number of singular values to be computed out (tuple, optional): the result tuple Example:: >>> a = torch.Tensor([[8.79, 6.11, -9.15, 9.57, -3.49, 9.84], ... [9.93, 6.91, -7.93, 1.64, 4.02, 0.15], ... [9.83, 5.04, 4.86, 8.83, 9.80, -8.99], ... [5.45, -0.27, 4.85, 0.74, 10.00, -6.02], ... [3.16, 7.98, 3.01, 5.80, 4.27, -5.31]]).t() >>> a 8.7900 9.9300 9.8300 5.4500 3.1600 6.1100 6.9100 5.0400 -0.2700 7.9800 -9.1500 -7.9300 4.8600 4.8500 3.0100 9.5700 1.6400 8.8300 0.7400 5.8000 -3.4900 4.0200 9.8000 10.0000 4.2700 9.8400 0.1500 -8.9900 -6.0200 -5.3100 [torch.FloatTensor of size 6x5] >>> u, s, v = torch.svd(a) >>> u -0.5911 0.2632 0.3554 0.3143 0.2299 -0.3976 0.2438 -0.2224 -0.7535 -0.3636 -0.0335 -0.6003 -0.4508 0.2334 -0.3055 -0.4297 0.2362 -0.6859 0.3319 0.1649 -0.4697 -0.3509 0.3874 0.1587 -0.5183 0.2934 0.5763 -0.0209 0.3791 -0.6526 [torch.FloatTensor of size 6x5] >>> s 27.4687 22.6432 8.5584 5.9857 2.0149 [torch.FloatTensor of size 5] >>> v -0.2514 0.8148 -0.2606 0.3967 -0.2180 -0.3968 0.3587 0.7008 -0.4507 0.1402 -0.6922 -0.2489 -0.2208 0.2513 0.5891 -0.3662 -0.3686 0.3859 0.4342 -0.6265 -0.4076 -0.0980 -0.4932 -0.6227 -0.4396 [torch.FloatTensor of size 5x5] >>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t())) 8.934150226306685e-06 """) add_docstr(torch._C.symeig, """ symeig(input, eigenvectors=False, upper=True, out=None) -> (Tensor, Tensor) `e, V = torch.symeig(input)` returns eigenvalues and eigenvectors of a symmetric real matrix :attr:`input`. `input` and `V` are `m x m` matrices and `e` is a `m` dimensional vector. This function calculates all eigenvalues (and vectors) of `input` such that `input = V diag(e) V'` The boolean argument :attr:`eigenvectors` defines computation of eigenvectors or eigenvalues only. If it is `False`, only eigenvalues are computed. If it is `True`, both eigenvalues and eigenvectors are computed. Since the input matrix `input` is supposed to be symmetric, only the upper triangular portion is used by default. If :attr:`upper` is `False`, then lower triangular portion is used. Note: Irrespective of the original strides, the returned matrix `V` will be transposed, i.e. with strides `(1, m)` instead of `(m, 1)`. Args: input (Tensor): the input symmetric matrix eigenvectors(boolean, optional): controls whether eigenvectors have to be computed upper(boolean, optional): controls whether to consider upper-triangular or lower-triangular region out (tuple, optional): The result tuple of (Tensor, Tensor) Examples:: >>> a = torch.Tensor([[ 1.96, 0.00, 0.00, 0.00, 0.00], ... [-6.49, 3.80, 0.00, 0.00, 0.00], ... [-0.47, -6.39, 4.17, 0.00, 0.00], ... [-7.20, 1.50, -1.51, 5.70, 0.00], ... [-0.65, -6.34, 2.67, 1.80, -7.10]]).t() >>> e, v = torch.symeig(a, eigenvectors=True) >>> e -11.0656 -6.2287 0.8640 8.8655 16.0948 [torch.FloatTensor of size 5] >>> v -0.2981 -0.6075 0.4026 -0.3745 0.4896 -0.5078 -0.2880 -0.4066 -0.3572 -0.6053 -0.0816 -0.3843 -0.6600 0.5008 0.3991 -0.0036 -0.4467 0.4553 0.6204 -0.4564 -0.8041 0.4480 0.1725 0.3108 0.1622 [torch.FloatTensor of size 5x5] """) add_docstr(torch._C.t, """ t(input, out=None) -> Tensor Expects :attr:`input` to be a matrix (2D Tensor) and transposes dimensions 0 and 1. Can be seen as a short-hand function for `transpose(input, 0, 1)` Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> x = torch.randn(2, 3) >>> x 0.4834 0.6907 1.3417 -0.1300 0.5295 0.2321 [torch.FloatTensor of size 2x3] >>> torch.t(x) 0.4834 -0.1300 0.6907 0.5295 1.3417 0.2321 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.tan, """ tan(input, out=None) -> Tensor Returns a new `Tensor` with the tangent of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.tan(a) -0.7392 0.2786 0.4792 3.7801 [torch.FloatTensor of size 4] """) add_docstr(torch._C.tanh, """ tanh(input, out=None) -> Tensor Returns a new `Tensor` with the hyperbolic tangent of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.6366 0.2718 0.4469 1.3122 [torch.FloatTensor of size 4] >>> torch.tanh(a) -0.5625 0.2653 0.4193 0.8648 [torch.FloatTensor of size 4] """) add_docstr(torch._C.topk, """ topk(input, k, dim=None, largest=True, sorted=True, out=None) -> (Tensor, LongTensor) Returns the :attr:`k` largest elements of the given :attr:`input` Tensor along a given dimension. If :attr:`dim` is not given, the last dimension of the `input` is chosen. If :attr:`largest` is `False` then the `k` smallest elements are returned. A tuple of `(values, indices)` is returned, where the `indices` are the indices of the elements in the original `input` Tensor. The boolean option :attr:`sorted` if `True`, will make sure that the returned `k` elements are themselves sorted Args: input (Tensor): the input `Tensor` k (int): the k in "top-k" dim (int, optional): The dimension to sort along largest (bool, optional): Controls whether to return largest or smallest elements sorted (bool, optional): Controls whether to return the elements in sorted order out (tuple, optional): The output tuple of (Tensor, LongTensor) can be optionally given to be used as output buffers Example:: >>> x = torch.range(1, 5) >>> x 1 2 3 4 5 [torch.FloatTensor of size 5] >>> torch.topk(x, 3) ( 5 4 3 [torch.FloatTensor of size 3] , 4 3 2 [torch.LongTensor of size 3] ) >>> torch.topk(x, 3, 0, largest=False) ( 1 2 3 [torch.FloatTensor of size 3] , 0 1 2 [torch.LongTensor of size 3] ) """) add_docstr(torch._C.trace, """ trace(input) -> float Returns the sum of the elements of the diagonal of the input 2D matrix. Example:: >>> x = torch.range(1, 9).view(3, 3) >>> x 1 2 3 4 5 6 7 8 9 [torch.FloatTensor of size 3x3] >>> torch.trace(x) 15.0 """) add_docstr(torch._C.transpose, """ transpose(input, dim0, dim1, out=None) -> Tensor Returns a `Tensor` that is a transposed version of :attr:`input`. The given dimensions :attr:`dim0` and :attr:`dim1` are swapped. The resulting :attr:`out` Tensor shares it's underlying storage with the :attr:`input` Tensor, so changing the content of one would change the content of the other. Args: input (Tensor): the input `Tensor` dim0 (int): The first dimension to be transposed dim1 (int): The second dimension to be transposed Example:: >>> x = torch.randn(2, 3) >>> x 0.5983 -0.0341 2.4918 1.5981 -0.5265 -0.8735 [torch.FloatTensor of size 2x3] >>> torch.transpose(x, 0, 1) 0.5983 1.5981 -0.0341 -0.5265 2.4918 -0.8735 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.tril, """ tril(input, k=0, out=None) -> Tensor Returns the lower triangular part of the matrix (2D Tensor) :attr:`input`, the other elements of the result Tensor :attr:`out` are set to 0. The lower triangular part of the matrix is defined as the elements on and below the diagonal. The argument :attr:`k` controls which diagonal to consider. - :attr:`k` = 0, is the main diagonal. - :attr:`k` > 0, is above the main diagonal. - :attr:`k` < 0, is below the main diagonal. Args: input (Tensor): the input `Tensor` k (int, optional): the diagonal to consider out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(3,3) >>> a 1.3225 1.7304 1.4573 -0.3052 -0.3111 -0.1809 1.2469 0.0064 -1.6250 [torch.FloatTensor of size 3x3] >>> torch.tril(a) 1.3225 0.0000 0.0000 -0.3052 -0.3111 0.0000 1.2469 0.0064 -1.6250 [torch.FloatTensor of size 3x3] >>> torch.tril(a, k=1) 1.3225 1.7304 0.0000 -0.3052 -0.3111 -0.1809 1.2469 0.0064 -1.6250 [torch.FloatTensor of size 3x3] >>> torch.tril(a, k=-1) 0.0000 0.0000 0.0000 -0.3052 0.0000 0.0000 1.2469 0.0064 0.0000 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.triu, """ triu(input, k=0, out=None) -> Tensor Returns the upper triangular part of the matrix (2D Tensor) :attr:`input`, the other elements of the result Tensor :attr:`out` are set to 0. The upper triangular part of the matrix is defined as the elements on and above the diagonal. The argument :attr:`k` controls which diagonal to consider. - :attr:`k` = 0, is the main diagonal. - :attr:`k` > 0, is above the main diagonal. - :attr:`k` < 0, is below the main diagonal. Args: input (Tensor): the input `Tensor` k (int, optional): the diagonal to consider out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(3,3) >>> a 1.3225 1.7304 1.4573 -0.3052 -0.3111 -0.1809 1.2469 0.0064 -1.6250 [torch.FloatTensor of size 3x3] >>> torch.triu(a) 1.3225 1.7304 1.4573 0.0000 -0.3111 -0.1809 0.0000 0.0000 -1.6250 [torch.FloatTensor of size 3x3] >>> torch.triu(a, k=1) 0.0000 1.7304 1.4573 0.0000 0.0000 -0.1809 0.0000 0.0000 0.0000 [torch.FloatTensor of size 3x3] >>> torch.triu(a, k=-1) 1.3225 1.7304 1.4573 -0.3052 -0.3111 -0.1809 0.0000 0.0064 -1.6250 [torch.FloatTensor of size 3x3] """) # TODO # add_docstr(torch._C.trtrs, # """ # """) add_docstr(torch._C.trunc, """ trunc(input, out=None) -> Tensor Returns a new `Tensor` with the truncated integer values of the elements of :attr:`input`. Args: input (Tensor): the input `Tensor` out (Tensor, optional): The result `Tensor` Example:: >>> a = torch.randn(4) >>> a -0.4972 1.3512 0.1056 -0.2650 [torch.FloatTensor of size 4] >>> torch.trunc(a) -0 1 0 -0 [torch.FloatTensor of size 4] """) add_docstr(torch._C.unsqueeze, """ unsqueeze(input, dim, out=None) Returns a new tensor with a dimension of size one inserted at the specified position. The returned tensor shares the same underlying data with this tensor. Args: input (Tensor): the input `Tensor` dim (int): The index at which to insert the singleton dimension out (Tensor, optional): The result `Tensor` Example: >>> x = torch.Tensor([1, 2, 3, 4]) >>> torch.unsqueeze(x, 0) 1 2 3 4 [torch.FloatTensor of size 1x4] >>> torch.unsqueeze(x, 1) 1 2 3 4 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.var, """ .. function:: var(input) -> float Returns the variance of all elements in the :attr:`input` Tensor. Args: input (Tensor): the input `Tensor` Example:: >>> a = torch.randn(1, 3) >>> a -1.3063 1.4182 -0.3061 [torch.FloatTensor of size 1x3] >>> torch.var(a) 1.899527506513334 .. function:: var(input, dim, out=None) -> Tensor Returns the variance of each row of the :attr:`input` Tensor in the given dimension :attr:`dim`. The output Tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Args: input (Tensor): the input `Tensor` dim (int): the dimension to reduce out (Tensor, optional): the result Tensor Example:: >>> a = torch.randn(4, 4) >>> a -1.2738 -0.3058 0.1230 -1.9615 0.8771 -0.5430 -0.9233 0.9879 1.4107 0.0317 -0.6823 0.2255 -1.3854 0.4953 -0.2160 0.2435 [torch.FloatTensor of size 4x4] >>> torch.var(a, 1) 0.8859 0.9509 0.7548 0.6949 [torch.FloatTensor of size 4x1] """) add_docstr(torch._C.zeros, """ zeros(*sizes, out=None) -> Tensor Returns a Tensor filled with the scalar value `0`, with the shape defined by the varargs :attr:`sizes`. Args: sizes (int...): a set of ints defining the shape of the output Tensor. out (Tensor, optional): the result Tensor Example:: >>> torch.zeros(2, 3) 0 0 0 0 0 0 [torch.FloatTensor of size 2x3] >>> torch.zeros(5) 0 0 0 0 0 [torch.FloatTensor of size 5] """) add_docstr(torch._C.btrifact, """ btrifact(A, info=None) -> Tensor, IntTensor Batch LU factorization. Returns a tuple containing the LU factorization and pivots. The optional argument `info` provides information if the factorization succeeded for each minibatch example. The info values are from dgetrf and a non-zero value indicates an error occurred. The specific values are from cublas if cuda is being used, otherwise LAPACK. Arguments: A (Tensor): tensor to factor. Example:: >>> A = torch.randn(2, 3, 3) >>> A_LU = A.btrifact() """) add_docstr(torch._C.btrisolve, """ btrisolve(b, LU_data, LU_pivots) -> Tensor Batch LU solve. Returns the LU solve of the linear system Ax = b. Arguments: b (Tensor): RHS tensor. LU_data (Tensor): Pivoted LU factorization of A from btrifact. LU_pivots (IntTensor): Pivots of the LU factorization. Example:: >>> A = torch.randn(2, 3, 3) >>> b = torch.randn(2, 3) >>> A_LU_data, A_LU_pivots, info = torch.btrifact(A) >>> x = b.trisolve(A_LU_data, A_LU_pivots) >>> torch.norm(A.bmm(x.unsqueeze(2)) - b) 6.664001874625056e-08 """)
{ "repo_name": "RPGOne/Skynet", "path": "pytorch-master/torch/_torch_docs.py", "copies": "1", "size": "103053", "license": "bsd-3-clause", "hash": 42147154166949410, "line_mean": 22.3627295398, "line_max": 119, "alpha_frac": 0.6090555345, "autogenerated": false, "ratio": 3.0017476915906904, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.411080322609069, "avg_score": null, "num_lines": null }
"""Adds docstrings to Tensor functions""" import torch._C from torch._C import _add_docstr as add_docstr from ._torch_docs import parse_kwargs def add_docstr_all(method, docstr): add_docstr(getattr(torch._C._TensorBase, method), docstr) new_common_args = parse_kwargs(""" size (int...): a list, tuple, or :class:`torch.Size` of integers defining the shape of the output tensor. dtype (:class:`torch.dtype`, optional): the desired type of returned tensor. Default: if None, same :class:`torch.dtype` as this tensor. device (:class:`torch.device`, optional): the desired device of returned tensor. Default: if None, same :class:`torch.device` as this tensor. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: ``False``. """) add_docstr_all('new_tensor', r""" new_tensor(data, dtype=None, device=None, requires_grad=False) -> Tensor Returns a new Tensor with :attr:`data` as the tensor data. By default, the returned Tensor has the same :class:`torch.dtype` and :class:`torch.device` as this tensor. .. warning:: :func:`new_tensor` always copies :attr:`data`. If you have a Tensor ``data`` and want to avoid a copy, use :func:`torch.Tensor.requires_grad_` or :func:`torch.Tensor.detach`. If you have a numpy array and want to avoid a copy, use :func:`torch.from_numpy`. .. warning:: When data is a tensor `x`, :func:`new_tensor()` reads out 'the data' from whatever it is passed, and constructs a leaf variable. Therefore ``tensor.new_tensor(x)`` is equivalent to ``x.clone().detach()`` and ``tensor.new_tensor(x, requires_grad=True)`` is equivalent to ``x.clone().detach().requires_grad_(True)``. The equivalents using ``clone()`` and ``detach()`` are recommended. Args: data (array_like): The returned Tensor copies :attr:`data`. {dtype} {device} {requires_grad} Example:: >>> tensor = torch.ones((2,), dtype=torch.int8) >>> data = [[0, 1], [2, 3]] >>> tensor.new_tensor(data) tensor([[ 0, 1], [ 2, 3]], dtype=torch.int8) """.format(**new_common_args)) add_docstr_all('new_full', r""" new_full(size, fill_value, dtype=None, device=None, requires_grad=False) -> Tensor Returns a Tensor of size :attr:`size` filled with :attr:`fill_value`. By default, the returned Tensor has the same :class:`torch.dtype` and :class:`torch.device` as this tensor. Args: fill_value (scalar): the number to fill the output tensor with. {dtype} {device} {requires_grad} Example:: >>> tensor = torch.ones((2,), dtype=torch.float64) >>> tensor.new_full((3, 4), 3.141592) tensor([[ 3.1416, 3.1416, 3.1416, 3.1416], [ 3.1416, 3.1416, 3.1416, 3.1416], [ 3.1416, 3.1416, 3.1416, 3.1416]], dtype=torch.float64) """.format(**new_common_args)) add_docstr_all('new_empty', r""" new_empty(size, dtype=None, device=None, requires_grad=False) -> Tensor Returns a Tensor of size :attr:`size` filled with uninitialized data. By default, the returned Tensor has the same :class:`torch.dtype` and :class:`torch.device` as this tensor. Args: {dtype} {device} {requires_grad} Example:: >>> tensor = torch.ones(()) >>> tensor.new_empty((2, 3)) tensor([[ 5.8182e-18, 4.5765e-41, -1.0545e+30], [ 3.0949e-41, 4.4842e-44, 0.0000e+00]]) """.format(**new_common_args)) add_docstr_all('new_ones', r""" new_ones(size, dtype=None, device=None, requires_grad=False) -> Tensor Returns a Tensor of size :attr:`size` filled with ``1``. By default, the returned Tensor has the same :class:`torch.dtype` and :class:`torch.device` as this tensor. Args: size (int...): a list, tuple, or :class:`torch.Size` of integers defining the shape of the output tensor. {dtype} {device} {requires_grad} Example:: >>> tensor = torch.tensor((), dtype=torch.int32) >>> tensor.new_ones((2, 3)) tensor([[ 1, 1, 1], [ 1, 1, 1]], dtype=torch.int32) """.format(**new_common_args)) add_docstr_all('new_zeros', r""" new_zeros(size, dtype=None, device=None, requires_grad=False) -> Tensor Returns a Tensor of size :attr:`size` filled with ``0``. By default, the returned Tensor has the same :class:`torch.dtype` and :class:`torch.device` as this tensor. Args: size (int...): a list, tuple, or :class:`torch.Size` of integers defining the shape of the output tensor. {dtype} {device} {requires_grad} Example:: >>> tensor = torch.tensor((), dtype=torch.float64) >>> tensor.new_zeros((2, 3)) tensor([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=torch.float64) """.format(**new_common_args)) add_docstr_all('abs', r""" abs() -> Tensor See :func:`torch.abs` """) add_docstr_all('abs_', r""" abs_() -> Tensor In-place version of :meth:`~Tensor.abs` """) add_docstr_all('acos', r""" acos() -> Tensor See :func:`torch.acos` """) add_docstr_all('acos_', r""" acos_() -> Tensor In-place version of :meth:`~Tensor.acos` """) add_docstr_all('add', r""" add(value) -> Tensor add(value=1, other) -> Tensor See :func:`torch.add` """) add_docstr_all('add_', r""" add_(value) -> Tensor add_(value=1, other) -> Tensor In-place version of :meth:`~Tensor.add` """) add_docstr_all('addbmm', r""" addbmm(beta=1, mat, alpha=1, batch1, batch2) -> Tensor See :func:`torch.addbmm` """) add_docstr_all('addbmm_', r""" addbmm_(beta=1, mat, alpha=1, batch1, batch2) -> Tensor In-place version of :meth:`~Tensor.addbmm` """) add_docstr_all('addcdiv', r""" addcdiv(value=1, tensor1, tensor2) -> Tensor See :func:`torch.addcdiv` """) add_docstr_all('addcdiv_', r""" addcdiv_(value=1, tensor1, tensor2) -> Tensor In-place version of :meth:`~Tensor.addcdiv` """) add_docstr_all('addcmul', r""" addcmul(value=1, tensor1, tensor2) -> Tensor See :func:`torch.addcmul` """) add_docstr_all('addcmul_', r""" addcmul_(value=1, tensor1, tensor2) -> Tensor In-place version of :meth:`~Tensor.addcmul` """) add_docstr_all('addmm', r""" addmm(beta=1, mat, alpha=1, mat1, mat2) -> Tensor See :func:`torch.addmm` """) add_docstr_all('addmm_', r""" addmm_(beta=1, mat, alpha=1, mat1, mat2) -> Tensor In-place version of :meth:`~Tensor.addmm` """) add_docstr_all('addmv', r""" addmv(beta=1, tensor, alpha=1, mat, vec) -> Tensor See :func:`torch.addmv` """) add_docstr_all('addmv_', r""" addmv_(beta=1, tensor, alpha=1, mat, vec) -> Tensor In-place version of :meth:`~Tensor.addmv` """) add_docstr_all('addr', r""" addr(beta=1, alpha=1, vec1, vec2) -> Tensor See :func:`torch.addr` """) add_docstr_all('addr_', r""" addr_(beta=1, alpha=1, vec1, vec2) -> Tensor In-place version of :meth:`~Tensor.addr` """) add_docstr_all('all', r""" .. function:: all() -> bool Returns True if all elements in the tensor are non-zero, False otherwise. Example:: >>> a = torch.randn(1, 3).byte() % 2 >>> a tensor([[1, 0, 0]], dtype=torch.uint8) >>> a.all() tensor(0, dtype=torch.uint8) .. function:: all(dim, keepdim=False, out=None) -> Tensor Returns True if all elements in each row of the tensor in the given dimension :attr:`dim` are non-zero, False otherwise. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 fewer dimension than :attr:`input`. Args: dim (int): the dimension to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 2).byte() % 2 >>> a tensor([[0, 0], [0, 0], [0, 1], [1, 1]], dtype=torch.uint8) >>> a.all(dim=1) tensor([0, 0, 0, 1], dtype=torch.uint8) """) add_docstr_all('allclose', r""" allclose(other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor See :func:`torch.allclose` """) add_docstr_all('any', r""" .. function:: any() -> bool Returns True if any elements in the tensor are non-zero, False otherwise. Example:: >>> a = torch.randn(1, 3).byte() % 2 >>> a tensor([[0, 0, 1]], dtype=torch.uint8) >>> a.any() tensor(1, dtype=torch.uint8) .. function:: any(dim, keepdim=False, out=None) -> Tensor Returns True if any elements in each row of the tensor in the given dimension :attr:`dim` are non-zero, False otherwise. If :attr:`keepdim` is ``True``, the output tensor is of the same size as :attr:`input` except in the dimension :attr:`dim` where it is of size 1. Otherwise, :attr:`dim` is squeezed (see :func:`torch.squeeze`), resulting in the output tensor having 1 fewer dimension than :attr:`input`. Args: dim (int): the dimension to reduce keepdim (bool): whether the output tensor has :attr:`dim` retained or not out (Tensor, optional): the output tensor Example:: >>> a = torch.randn(4, 2).byte() % 2 >>> a tensor([[1, 0], [0, 0], [0, 1], [0, 0]], dtype=torch.uint8) >>> a.any(dim=1) tensor([1, 0, 1, 0], dtype=torch.uint8) """) add_docstr_all('apply_', r""" apply_(callable) -> Tensor Applies the function :attr:`callable` to each element in the tensor, replacing each element with the value returned by :attr:`callable`. .. note:: This function only works with CPU tensors and should not be used in code sections that require high performance. """) add_docstr_all('asin', r""" asin() -> Tensor See :func:`torch.asin` """) add_docstr_all('asin_', r""" asin_() -> Tensor In-place version of :meth:`~Tensor.asin` """) add_docstr_all('atan', r""" atan() -> Tensor See :func:`torch.atan` """) add_docstr_all('atan2', r""" atan2(other) -> Tensor See :func:`torch.atan2` """) add_docstr_all('atan2_', r""" atan2_(other) -> Tensor In-place version of :meth:`~Tensor.atan2` """) add_docstr_all('atan_', r""" atan_() -> Tensor In-place version of :meth:`~Tensor.atan` """) add_docstr_all('baddbmm', r""" baddbmm(beta=1, alpha=1, batch1, batch2) -> Tensor See :func:`torch.baddbmm` """) add_docstr_all('baddbmm_', r""" baddbmm_(beta=1, alpha=1, batch1, batch2) -> Tensor In-place version of :meth:`~Tensor.baddbmm` """) add_docstr_all('bernoulli', r""" bernoulli(*, generator=None) -> Tensor Returns a result tensor where each :math:`\texttt{result[i]}` is independently sampled from :math:`\text{Bernoulli}(\texttt{self[i]})`. :attr:`self` must have floating point ``dtype``, and the result will have the same ``dtype``. See :func:`torch.bernoulli` """) add_docstr_all('bernoulli_', r""" .. function:: bernoulli_(p=0.5, *, generator=None) -> Tensor Fills each location of :attr:`self` with an independent sample from :math:`\text{Bernoulli}(\texttt{p})`. :attr:`self` can have integral ``dtype``. .. function:: bernoulli_(p_tensor, *, generator=None) -> Tensor :attr:`p_tensor` should be a tensor containing probabilities to be used for drawing the binary random number. The :math:`\text{i}^{th}` element of :attr:`self` tensor will be set to a value sampled from :math:`\text{Bernoulli}(\texttt{p\_tensor[i]})`. :attr:`self` can have integral ``dtype``, but :attr`p_tensor` must have floating point ``dtype``. See also :meth:`~Tensor.bernoulli` and :func:`torch.bernoulli` """) add_docstr_all('bincount', r""" bincount(weights=None, minlength=0) -> Tensor See :func:`torch.bincount` """) add_docstr_all('bmm', r""" bmm(batch2) -> Tensor See :func:`torch.bmm` """) add_docstr_all('btrifact_with_info', r""" btrifact_with_info(pivot=True) -> (Tensor, Tensor, Tensor) See :func:`torch.btrifact_with_info` """) add_docstr_all('btrisolve', r""" btrisolve(LU_data, LU_pivots) -> Tensor See :func:`torch.btrisolve` """) add_docstr_all('cauchy_', r""" cauchy_(median=0, sigma=1, *, generator=None) -> Tensor Fills the tensor with numbers drawn from the Cauchy distribution: .. math:: f(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - \text{median})^2 + \sigma^2} """) add_docstr_all('ceil', r""" ceil() -> Tensor See :func:`torch.ceil` """) add_docstr_all('ceil_', r""" ceil_() -> Tensor In-place version of :meth:`~Tensor.ceil` """) add_docstr_all('cholesky', r""" cholesky(upper=False) -> Tensor See :func:`torch.cholesky` """) add_docstr_all('clamp', r""" clamp(min, max) -> Tensor See :func:`torch.clamp` """) add_docstr_all('clamp_', r""" clamp_(min, max) -> Tensor In-place version of :meth:`~Tensor.clamp` """) add_docstr_all('clone', r""" clone() -> Tensor Returns a copy of the :attr:`self` tensor. The copy has the same size and data type as :attr:`self`. .. note:: Unlike `copy_()`, this function is recorded in the computation graph. Gradients propagating to the cloned tensor will propagate to the original tensor. """) add_docstr_all('contiguous', r""" contiguous() -> Tensor Returns a contiguous tensor containing the same data as :attr:`self` tensor. If :attr:`self` tensor is contiguous, this function returns the :attr:`self` tensor. """) add_docstr_all('copy_', r""" copy_(src, non_blocking=False) -> Tensor Copies the elements from :attr:`src` into :attr:`self` tensor and returns :attr:`self`. The :attr:`src` tensor must be :ref:`broadcastable <broadcasting-semantics>` with the :attr:`self` tensor. It may be of a different data type or reside on a different device. Args: src (Tensor): the source tensor to copy from non_blocking (bool): if ``True`` and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect. """) add_docstr_all('cos', r""" cos() -> Tensor See :func:`torch.cos` """) add_docstr_all('cos_', r""" cos_() -> Tensor In-place version of :meth:`~Tensor.cos` """) add_docstr_all('cosh', r""" cosh() -> Tensor See :func:`torch.cosh` """) add_docstr_all('cosh_', r""" cosh_() -> Tensor In-place version of :meth:`~Tensor.cosh` """) add_docstr_all('cpu', r""" cpu() -> Tensor Returns a copy of this object in CPU memory. If this object is already in CPU memory and on the correct device, then no copy is performed and the original object is returned. """) add_docstr_all('cross', r""" cross(other, dim=-1) -> Tensor See :func:`torch.cross` """) add_docstr_all('cuda', r""" cuda(device=None, non_blocking=False) -> Tensor Returns a copy of this object in CUDA memory. If this object is already in CUDA memory and on the correct device, then no copy is performed and the original object is returned. Args: device (:class:`torch.device`): The destination GPU device. Defaults to the current CUDA device. non_blocking (bool): If ``True`` and the source is in pinned memory, the copy will be asynchronous with respect to the host. Otherwise, the argument has no effect. Default: ``False``. """) add_docstr_all('cumprod', r""" cumprod(dim, dtype=None) -> Tensor See :func:`torch.cumprod` """) add_docstr_all('cumsum', r""" cumsum(dim, dtype=None) -> Tensor See :func:`torch.cumsum` """) add_docstr_all('data_ptr', r""" data_ptr() -> int Returns the address of the first element of :attr:`self` tensor. """) add_docstr_all('dense_dim', r""" dense_dim() -> int If :attr:`self` is a sparse COO tensor (i.e., with ``torch.sparse_coo`` layout), this returns a the number of dense dimensions. Otherwise, this throws an error. See also :meth:`Tensor.sparse_dim`. """) add_docstr_all('diag', r""" diag(diagonal=0) -> Tensor See :func:`torch.diag` """) add_docstr_all('diag_embed', r""" diag_embed(offset=0, dim1=-2, dim2=-1) -> Tensor See :func:`torch.diag_embed` """) add_docstr_all('diagflat', r""" diagflat(diagonal=0) -> Tensor See :func:`torch.diagflat` """) add_docstr_all('diagonal', r""" diagonal(offset=0, dim1=0, dim2=1) -> Tensor See :func:`torch.diagonal` """) add_docstr_all('digamma', r""" digamma() -> Tensor See :func:`torch.digamma` """) add_docstr_all('digamma_', r""" digamma_() -> Tensor In-place version of :meth:`~Tensor.digamma` """) add_docstr_all('dim', r""" dim() -> int Returns the number of dimensions of :attr:`self` tensor. """) add_docstr_all('dist', r""" dist(other, p=2) -> Tensor See :func:`torch.dist` """) add_docstr_all('div', r""" div(value) -> Tensor See :func:`torch.div` """) add_docstr_all('div_', r""" div_(value) -> Tensor In-place version of :meth:`~Tensor.div` """) add_docstr_all('dot', r""" dot(tensor2) -> Tensor See :func:`torch.dot` """) add_docstr_all('eig', r""" eig(eigenvectors=False) -> (Tensor, Tensor) See :func:`torch.eig` """) add_docstr_all('element_size', r""" element_size() -> int Returns the size in bytes of an individual element. Example:: >>> torch.tensor([]).element_size() 4 >>> torch.tensor([], dtype=torch.uint8).element_size() 1 """) add_docstr_all('eq', r""" eq(other) -> Tensor See :func:`torch.eq` """) add_docstr_all('eq_', r""" eq_(other) -> Tensor In-place version of :meth:`~Tensor.eq` """) add_docstr_all('equal', r""" equal(other) -> bool See :func:`torch.equal` """) add_docstr_all('erf', r""" erf() -> Tensor See :func:`torch.erf` """) add_docstr_all('erf_', r""" erf_() -> Tensor In-place version of :meth:`~Tensor.erf` """) add_docstr_all('erfc', r""" erfc() -> Tensor See :func:`torch.erfc` """) add_docstr_all('erfc_', r""" erfc_() -> Tensor In-place version of :meth:`~Tensor.erfc` """) add_docstr_all('erfinv', r""" erfinv() -> Tensor See :func:`torch.erfinv` """) add_docstr_all('erfinv_', r""" erfinv_() -> Tensor In-place version of :meth:`~Tensor.erfinv` """) add_docstr_all('exp', r""" exp() -> Tensor See :func:`torch.exp` """) add_docstr_all('exp_', r""" exp_() -> Tensor In-place version of :meth:`~Tensor.exp` """) add_docstr_all('expm1', r""" expm1() -> Tensor See :func:`torch.expm1` """) add_docstr_all('expm1_', r""" expm1_() -> Tensor In-place version of :meth:`~Tensor.expm1` """) add_docstr_all('exponential_', r""" exponential_(lambd=1, *, generator=None) -> Tensor Fills :attr:`self` tensor with elements drawn from the exponential distribution: .. math:: f(x) = \lambda e^{-\lambda x} """) add_docstr_all('fill_', r""" fill_(value) -> Tensor Fills :attr:`self` tensor with the specified value. """) add_docstr_all('floor', r""" floor() -> Tensor See :func:`torch.floor` """) add_docstr_all('flip', r""" flip(dims) -> Tensor See :func:`torch.flip` """) add_docstr_all('roll', r""" roll(shifts, dims) -> Tensor See :func:`torch.roll` """) add_docstr_all('floor_', r""" floor_() -> Tensor In-place version of :meth:`~Tensor.floor` """) add_docstr_all('fmod', r""" fmod(divisor) -> Tensor See :func:`torch.fmod` """) add_docstr_all('fmod_', r""" fmod_(divisor) -> Tensor In-place version of :meth:`~Tensor.fmod` """) add_docstr_all('frac', r""" frac() -> Tensor See :func:`torch.frac` """) add_docstr_all('frac_', r""" frac_() -> Tensor In-place version of :meth:`~Tensor.frac` """) add_docstr_all('flatten', r""" flatten(input, start_dim=0, end_dim=-1) -> Tensor see :func:`torch.flatten` """) add_docstr_all('gather', r""" gather(dim, index) -> Tensor See :func:`torch.gather` """) add_docstr_all('ge', r""" ge(other) -> Tensor See :func:`torch.ge` """) add_docstr_all('ge_', r""" ge_(other) -> Tensor In-place version of :meth:`~Tensor.ge` """) add_docstr_all('gels', r""" gels(A) -> Tensor See :func:`torch.gels` """) add_docstr_all('geometric_', r""" geometric_(p, *, generator=None) -> Tensor Fills :attr:`self` tensor with elements drawn from the geometric distribution: .. math:: f(X=k) = (1 - p)^{k - 1} p """) add_docstr_all('geqrf', r""" geqrf() -> (Tensor, Tensor) See :func:`torch.geqrf` """) add_docstr_all('ger', r""" ger(vec2) -> Tensor See :func:`torch.ger` """) add_docstr_all('gesv', r""" gesv(A) -> Tensor, Tensor See :func:`torch.gesv` """) add_docstr_all('indices', r""" indices() -> Tensor If :attr:`self` is a sparse COO tensor (i.e., with ``torch.sparse_coo`` layout), this returns a view of the contained indices tensor. Otherwise, this throws an error. See also :meth:`Tensor.values`. .. note:: This method can only be called on a coalesced sparse tensor. See :meth:`Tensor.coalesce` for details. """) add_docstr_all('get_device', r""" get_device() -> Device ordinal (Integer) For CUDA tensors, this function returns the device ordinal of the GPU on which the tensor resides. For CPU tensors, an error is thrown. Example:: >>> x = torch.randn(3, 4, 5, device='cuda:0') >>> x.get_device() 0 >>> x.cpu().get_device() # RuntimeError: get_device is not implemented for type torch.FloatTensor """) add_docstr_all('values', r""" values() -> Tensor If :attr:`self` is a sparse COO tensor (i.e., with ``torch.sparse_coo`` layout), this returns a view of the contained values tensor. Otherwise, this throws an error. See also :meth:`Tensor.indices`. .. note:: This method can only be called on a coalesced sparse tensor. See :meth:`Tensor.coalesce` for details. """) add_docstr_all('gt', r""" gt(other) -> Tensor See :func:`torch.gt` """) add_docstr_all('gt_', r""" gt_(other) -> Tensor In-place version of :meth:`~Tensor.gt` """) add_docstr_all('hardshrink', r""" hardshrink(lambd=0.5) -> Tensor See :func:`torch.nn.functional.hardshrink` """) add_docstr_all('histc', r""" histc(bins=100, min=0, max=0) -> Tensor See :func:`torch.histc` """) add_docstr_all('index_add_', r""" index_add_(dim, index, tensor) -> Tensor Accumulate the elements of :attr:`tensor` into the :attr:`self` tensor by adding to the indices in the order given in :attr:`index`. For example, if ``dim == 0`` and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is added to the ``j``\ th row of :attr:`self`. The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the length of :attr:`index` (which must be a vector), and all other dimensions must match :attr:`self`, or an error will be raised. .. include:: cuda_deterministic.rst Args: dim (int): dimension along which to index index (LongTensor): indices of :attr:`tensor` to select from tensor (Tensor): the tensor containing values to add Example:: >>> x = torch.ones(5, 3) >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) >>> index = torch.tensor([0, 4, 2]) >>> x.index_add_(0, index, t) tensor([[ 2., 3., 4.], [ 1., 1., 1.], [ 8., 9., 10.], [ 1., 1., 1.], [ 5., 6., 7.]]) """) add_docstr_all('index_copy_', r""" index_copy_(dim, index, tensor) -> Tensor Copies the elements of :attr:`tensor` into the :attr:`self` tensor by selecting the indices in the order given in :attr:`index`. For example, if ``dim == 0`` and ``index[i] == j``, then the ``i``\ th row of :attr:`tensor` is copied to the ``j``\ th row of :attr:`self`. The :attr:`dim`\ th dimension of :attr:`tensor` must have the same size as the length of :attr:`index` (which must be a vector), and all other dimensions must match :attr:`self`, or an error will be raised. Args: dim (int): dimension along which to index index (LongTensor): indices of :attr:`tensor` to select from tensor (Tensor): the tensor containing values to copy Example:: >>> x = torch.zeros(5, 3) >>> t = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) >>> index = torch.tensor([0, 4, 2]) >>> x.index_copy_(0, index, t) tensor([[ 1., 2., 3.], [ 0., 0., 0.], [ 7., 8., 9.], [ 0., 0., 0.], [ 4., 5., 6.]]) """) add_docstr_all('index_fill_', r""" index_fill_(dim, index, val) -> Tensor Fills the elements of the :attr:`self` tensor with value :attr:`val` by selecting the indices in the order given in :attr:`index`. Args: dim (int): dimension along which to index index (LongTensor): indices of :attr:`self` tensor to fill in val (float): the value to fill with Example:: >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=torch.float) >>> index = torch.tensor([0, 2]) >>> x.index_fill_(1, index, -1) tensor([[-1., 2., -1.], [-1., 5., -1.], [-1., 8., -1.]]) """) add_docstr_all('index_put_', r""" index_put_(indices, value, accumulate=False) -> Tensor Puts values from the tensor :attr:`value` into the tensor :attr:`self` using the indices specified in :attr:`indices` (which is a tuple of Tensors). The expression ``tensor.index_put_(indices, value)`` is equivalent to ``tensor[indices] = value``. Returns :attr:`self`. If :attr:`accumulate` is ``True``, the elements in :attr:`tensor` are added to :attr:`self`. If accumulate is ``False``, the behavior is undefined if indices contain duplicate elements. Args: indices (tuple of LongTensor): tensors used to index into `self`. value (Tensor): tensor of same dtype as `self`. accumulate (bool): whether to accumulate into self """) add_docstr_all('index_select', r""" index_select(dim, index) -> Tensor See :func:`torch.index_select` """) add_docstr_all('sparse_mask', r""" sparse_mask(input, mask) -> Tensor Returns a new SparseTensor with values from Tensor :attr:`input` filtered by indices of :attr:`mask` and values are ignored. :attr:`input` and :attr:`mask` must have the same shape. Args: input (Tensor): an input Tensor mask (SparseTensor): a SparseTensor which we filter :attr:`input` based on its indices Example:: >>> nnz = 5 >>> dims = [5, 5, 2, 2] >>> I = torch.cat([torch.randint(0, dims[0], size=(nnz,)), torch.randint(0, dims[1], size=(nnz,))], 0).reshape(2, nnz) >>> V = torch.randn(nnz, dims[2], dims[3]) >>> size = torch.Size(dims) >>> S = torch.sparse_coo_tensor(I, V, size).coalesce() >>> D = torch.randn(dims) >>> D.sparse_mask(S) tensor(indices=tensor([[0, 0, 0, 2], [0, 1, 4, 3]]), values=tensor([[[ 1.6550, 0.2397], [-0.1611, -0.0779]], [[ 0.2326, -1.0558], [ 1.4711, 1.9678]], [[-0.5138, -0.0411], [ 1.9417, 0.5158]], [[ 0.0793, 0.0036], [-0.2569, -0.1055]]]), size=(5, 5, 2, 2), nnz=4, layout=torch.sparse_coo) """) add_docstr_all('inverse', r""" inverse() -> Tensor See :func:`torch.inverse` """) add_docstr_all('is_contiguous', r""" is_contiguous() -> bool Returns True if :attr:`self` tensor is contiguous in memory in C order. """) add_docstr_all('is_set_to', r""" is_set_to(tensor) -> bool Returns True if this object refers to the same ``THTensor`` object from the Torch C API as the given tensor. """) add_docstr_all('item', r""" item() -> number Returns the value of this tensor as a standard Python number. This only works for tensors with one element. For other cases, see :meth:`~Tensor.tolist`. This operation is not differentiable. Example:: >>> x = torch.tensor([1.0]) >>> x.item() 1.0 """) add_docstr_all('kthvalue', r""" kthvalue(k, dim=None, keepdim=False) -> (Tensor, LongTensor) See :func:`torch.kthvalue` """) add_docstr_all('le', r""" le(other) -> Tensor See :func:`torch.le` """) add_docstr_all('le_', r""" le_(other) -> Tensor In-place version of :meth:`~Tensor.le` """) add_docstr_all('lerp', r""" lerp(start, end, weight) -> Tensor See :func:`torch.lerp` """) add_docstr_all('lerp_', r""" lerp_(start, end, weight) -> Tensor In-place version of :meth:`~Tensor.lerp` """) add_docstr_all('log', r""" log() -> Tensor See :func:`torch.log` """) add_docstr_all('log_', r""" log_() -> Tensor In-place version of :meth:`~Tensor.log` """) add_docstr_all('log10', r""" log10() -> Tensor See :func:`torch.log10` """) add_docstr_all('log10_', r""" log10_() -> Tensor In-place version of :meth:`~Tensor.log10` """) add_docstr_all('log1p', r""" log1p() -> Tensor See :func:`torch.log1p` """) add_docstr_all('log1p_', r""" log1p_() -> Tensor In-place version of :meth:`~Tensor.log1p` """) add_docstr_all('log2', r""" log2() -> Tensor See :func:`torch.log2` """) add_docstr_all('log2_', r""" log2_() -> Tensor In-place version of :meth:`~Tensor.log2` """) add_docstr_all('log_normal_', r""" log_normal_(mean=1, std=2, *, generator=None) Fills :attr:`self` tensor with numbers samples from the log-normal distribution parameterized by the given mean :math:`\mu` and standard deviation :math:`\sigma`. Note that :attr:`mean` and :attr:`std` are the mean and standard deviation of the underlying normal distribution, and not of the returned distribution: .. math:: f(x) = \dfrac{1}{x \sigma \sqrt{2\pi}}\ e^{-\frac{(\ln x - \mu)^2}{2\sigma^2}} """) add_docstr_all('logsumexp', r""" logsumexp(dim, keepdim=False) -> Tensor See :func:`torch.logsumexp` """) add_docstr_all('lt', r""" lt(other) -> Tensor See :func:`torch.lt` """) add_docstr_all('lt_', r""" lt_(other) -> Tensor In-place version of :meth:`~Tensor.lt` """) add_docstr_all('map_', r""" map_(tensor, callable) Applies :attr:`callable` for each element in :attr:`self` tensor and the given :attr:`tensor` and stores the results in :attr:`self` tensor. :attr:`self` tensor and the given :attr:`tensor` must be :ref:`broadcastable <broadcasting-semantics>`. The :attr:`callable` should have the signature:: def callable(a, b) -> number """) add_docstr_all('masked_scatter_', r""" masked_scatter_(mask, source) Copies elements from :attr:`source` into :attr:`self` tensor at positions where the :attr:`mask` is one. The shape of :attr:`mask` must be :ref:`broadcastable <broadcasting-semantics>` with the shape of the underlying tensor. The :attr:`source` should have at least as many elements as the number of ones in :attr:`mask` Args: mask (ByteTensor): the binary mask source (Tensor): the tensor to copy from .. note:: The :attr:`mask` operates on the :attr:`self` tensor, not on the given :attr:`source` tensor. """) add_docstr_all('masked_fill_', r""" masked_fill_(mask, value) Fills elements of :attr:`self` tensor with :attr:`value` where :attr:`mask` is one. The shape of :attr:`mask` must be :ref:`broadcastable <broadcasting-semantics>` with the shape of the underlying tensor. Args: mask (ByteTensor): the binary mask value (float): the value to fill in with """) add_docstr_all('masked_select', r""" masked_select(mask) -> Tensor See :func:`torch.masked_select` """) add_docstr_all('matrix_power', r""" matrix_power(n) -> Tensor See :func:`torch.matrix_power` """) add_docstr_all('max', r""" max(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) See :func:`torch.max` """) add_docstr_all('mean', r""" mean(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) See :func:`torch.mean` """) add_docstr_all('median', r""" median(dim=None, keepdim=False) -> (Tensor, LongTensor) See :func:`torch.median` """) add_docstr_all('min', r""" min(dim=None, keepdim=False) -> Tensor or (Tensor, Tensor) See :func:`torch.min` """) add_docstr_all('mm', r""" mm(mat2) -> Tensor See :func:`torch.mm` """) add_docstr_all('mode', r""" mode(dim=None, keepdim=False) -> (Tensor, LongTensor) See :func:`torch.mode` """) add_docstr_all('mul', r""" mul(value) -> Tensor See :func:`torch.mul` """) add_docstr_all('mul_', r""" mul_(value) In-place version of :meth:`~Tensor.mul` """) add_docstr_all('multinomial', r""" multinomial(num_samples, replacement=False, *, generator=None) -> Tensor See :func:`torch.multinomial` """) add_docstr_all('mv', r""" mv(vec) -> Tensor See :func:`torch.mv` """) add_docstr_all('mvlgamma', r""" mvlgamma(p) -> Tensor See :func:`torch.mvlgamma` """) add_docstr_all('mvlgamma_', r""" mvlgamma_(p) -> Tensor In-place version of :meth:`~Tensor.mvlgamma` """) add_docstr_all('narrow', r""" narrow(dimension, start, length) -> Tensor See :func:`torch.narrow` Example:: >>> x = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> x.narrow(0, 0, 2) tensor([[ 1, 2, 3], [ 4, 5, 6]]) >>> x.narrow(1, 1, 2) tensor([[ 2, 3], [ 5, 6], [ 8, 9]]) """) add_docstr_all('narrow_copy', r""" narrow_copy(dimension, start, length) -> Tensor Same as :meth:`Tensor.narrow` except returning a copy rather than shared storage. This is primarily for sparse tensors, which do not have a shared-storage narrow method. Calling ```narrow_copy`` with ```dimemsion > self.sparse_dim()``` will return a copy with the relevant dense dimension narrowed, and ```self.shape``` updated accordingly. """) add_docstr_all('ndimension', r""" ndimension() -> int Alias for :meth:`~Tensor.dim()` """) add_docstr_all('ne', r""" ne(other) -> Tensor See :func:`torch.ne` """) add_docstr_all('ne_', r""" ne_(other) -> Tensor In-place version of :meth:`~Tensor.ne` """) add_docstr_all('neg', r""" neg() -> Tensor See :func:`torch.neg` """) add_docstr_all('neg_', r""" neg_() -> Tensor In-place version of :meth:`~Tensor.neg` """) add_docstr_all('nelement', r""" nelement() -> int Alias for :meth:`~Tensor.numel` """) add_docstr_all('nonzero', r""" nonzero() -> LongTensor See :func:`torch.nonzero` """) add_docstr_all('norm', r""" norm(p=2, dim=None, keepdim=False) -> Tensor See :func:`torch.norm` """) add_docstr_all('normal_', r""" normal_(mean=0, std=1, *, generator=None) -> Tensor Fills :attr:`self` tensor with elements samples from the normal distribution parameterized by :attr:`mean` and :attr:`std`. """) add_docstr_all('numel', r""" numel() -> int See :func:`torch.numel` """) add_docstr_all('numpy', r""" numpy() -> numpy.ndarray Returns :attr:`self` tensor as a NumPy :class:`ndarray`. This tensor and the returned :class:`ndarray` share the same underlying storage. Changes to :attr:`self` tensor will be reflected in the :class:`ndarray` and vice versa. """) add_docstr_all('orgqr', r""" orgqr(input2) -> Tensor See :func:`torch.orgqr` """) add_docstr_all('ormqr', r""" ormqr(input2, input3, left=True, transpose=False) -> Tensor See :func:`torch.ormqr` """) add_docstr_all('permute', r""" permute(*dims) -> Tensor Permute the dimensions of this tensor. Args: *dims (int...): The desired ordering of dimensions Example: >>> x = torch.randn(2, 3, 5) >>> x.size() torch.Size([2, 3, 5]) >>> x.permute(2, 0, 1).size() torch.Size([5, 2, 3]) """) add_docstr_all('potri', r""" potri(upper=True) -> Tensor See :func:`torch.potri` """) add_docstr_all('potrs', r""" potrs(input2, upper=True) -> Tensor See :func:`torch.potrs` """) add_docstr_all('pow', r""" pow(exponent) -> Tensor See :func:`torch.pow` """) add_docstr_all('pow_', r""" pow_(exponent) -> Tensor In-place version of :meth:`~Tensor.pow` """) add_docstr_all('prod', r""" prod(dim=None, keepdim=False, dtype=None) -> Tensor See :func:`torch.prod` """) add_docstr_all('pstrf', r""" pstrf(upper=True, tol=-1) -> (Tensor, IntTensor) See :func:`torch.pstrf` """) add_docstr_all('put_', r""" put_(indices, tensor, accumulate=False) -> Tensor Copies the elements from :attr:`tensor` into the positions specified by indices. For the purpose of indexing, the :attr:`self` tensor is treated as if it were a 1-D tensor. If :attr:`accumulate` is ``True``, the elements in :attr:`tensor` are added to :attr:`self`. If accumulate is ``False``, the behavior is undefined if indices contain duplicate elements. Args: indices (LongTensor): the indices into self tensor (Tensor): the tensor containing values to copy from accumulate (bool): whether to accumulate into self Example:: >>> src = torch.tensor([[4, 3, 5], [6, 7, 8]]) >>> src.put_(torch.tensor([1, 3]), torch.tensor([9, 10])) tensor([[ 4, 9, 5], [ 10, 7, 8]]) """) add_docstr_all('qr', r""" qr() -> (Tensor, Tensor) See :func:`torch.qr` """) add_docstr_all('random_', r""" random_(from=0, to=None, *, generator=None) -> Tensor Fills :attr:`self` tensor with numbers sampled from the discrete uniform distribution over ``[from, to - 1]``. If not specified, the values are usually only bounded by :attr:`self` tensor's data type. However, for floating point types, if unspecified, range will be ``[0, 2^mantissa]`` to ensure that every value is representable. For example, `torch.tensor(1, dtype=torch.double).random_()` will be uniform in ``[0, 2^53]``. """) add_docstr_all('reciprocal', r""" reciprocal() -> Tensor See :func:`torch.reciprocal` """) add_docstr_all('reciprocal_', r""" reciprocal_() -> Tensor In-place version of :meth:`~Tensor.reciprocal` """) add_docstr_all('remainder', r""" remainder(divisor) -> Tensor See :func:`torch.remainder` """) add_docstr_all('remainder_', r""" remainder_(divisor) -> Tensor In-place version of :meth:`~Tensor.remainder` """) add_docstr_all('renorm', r""" renorm(p, dim, maxnorm) -> Tensor See :func:`torch.renorm` """) add_docstr_all('renorm_', r""" renorm_(p, dim, maxnorm) -> Tensor In-place version of :meth:`~Tensor.renorm` """) add_docstr_all('repeat', r""" repeat(*sizes) -> Tensor Repeats this tensor along the specified dimensions. Unlike :meth:`~Tensor.expand`, this function copies the tensor's data. .. warning:: :func:`torch.repeat` behaves differently from `numpy.repeat <https://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html>`_, but is more similar to `numpy.tile <https://docs.scipy.org/doc/numpy/reference/generated/numpy.tile.html>`_. Args: sizes (torch.Size or int...): The number of times to repeat this tensor along each dimension Example:: >>> x = torch.tensor([1, 2, 3]) >>> x.repeat(4, 2) tensor([[ 1, 2, 3, 1, 2, 3], [ 1, 2, 3, 1, 2, 3], [ 1, 2, 3, 1, 2, 3], [ 1, 2, 3, 1, 2, 3]]) >>> x.repeat(4, 2, 1).size() torch.Size([4, 2, 3]) """) add_docstr_all('requires_grad_', r""" requires_grad_(requires_grad=True) -> Tensor Change if autograd should record operations on this tensor: sets this tensor's :attr:`requires_grad` attribute in-place. Returns this tensor. :func:`require_grad_`'s main use case is to tell autograd to begin recording operations on a Tensor ``tensor``. If ``tensor`` has ``requires_grad=False`` (because it was obtained through a DataLoader, or required preprocessing or initialization), ``tensor.requires_grad_()`` makes it so that autograd will begin to record operations on ``tensor``. Args: requires_grad (bool): If autograd should record operations on this tensor. Default: ``True``. Example:: >>> # Let's say we want to preprocess some saved weights and use >>> # the result as new weights. >>> saved_weights = [0.1, 0.2, 0.3, 0.25] >>> loaded_weights = torch.tensor(saved_weights) >>> weights = preprocess(loaded_weights) # some function >>> weights tensor([-0.5503, 0.4926, -2.1158, -0.8303]) >>> # Now, start to record operations done to weights >>> weights.requires_grad_() >>> out = weights.pow(2).sum() >>> out.backward() >>> weights.grad tensor([-1.1007, 0.9853, -4.2316, -1.6606]) """) add_docstr_all('reshape', r""" reshape(*shape) -> Tensor Returns a tensor with the same data and number of elements as :attr:`self` but with the specified shape. This method returns a view if :attr:`shape` is compatible with the current shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. See :func:`torch.reshape` Args: shape (tuple of ints or int...): the desired shape """) add_docstr_all('reshape_as', r""" reshape_as(other) -> Tensor Returns this tensor as the same shape as :attr:`other`. ``self.reshape_as(other)`` is equivalent to ``self.reshape(other.sizes())``. This method returns a view if ``other.sizes()`` is compatible with the current shape. See :meth:`torch.Tensor.view` on when it is possible to return a view. Please see :meth:`reshape` for more information about ``reshape``. Args: other (:class:`torch.Tensor`): The result tensor has the same shape as :attr:`other`. """) add_docstr_all('resize_', r""" resize_(*sizes) -> Tensor Resizes :attr:`self` tensor to the specified size. If the number of elements is larger than the current storage size, then the underlying storage is resized to fit the new number of elements. If the number of elements is smaller, the underlying storage is not changed. Existing elements are preserved but any new memory is uninitialized. .. warning:: This is a low-level method. The storage is reinterpreted as C-contiguous, ignoring the current strides (unless the target size equals the current size, in which case the tensor is left unchanged). For most purposes, you will instead want to use :meth:`~Tensor.view()`, which checks for contiguity, or :meth:`~Tensor.reshape()`, which copies data if needed. To change the size in-place with custom strides, see :meth:`~Tensor.set_()`. Args: sizes (torch.Size or int...): the desired size Example:: >>> x = torch.tensor([[1, 2], [3, 4], [5, 6]]) >>> x.resize_(2, 2) tensor([[ 1, 2], [ 3, 4]]) """) add_docstr_all('resize_as_', r""" resize_as_(tensor) -> Tensor Resizes the :attr:`self` tensor to be the same size as the specified :attr:`tensor`. This is equivalent to ``self.resize_(tensor.size())``. """) add_docstr_all('rot90', r""" rot90(k, dims) -> Tensor See :func:`torch.rot90` """) add_docstr_all('round', r""" round() -> Tensor See :func:`torch.round` """) add_docstr_all('round_', r""" round_() -> Tensor In-place version of :meth:`~Tensor.round` """) add_docstr_all('rsqrt', r""" rsqrt() -> Tensor See :func:`torch.rsqrt` """) add_docstr_all('rsqrt_', r""" rsqrt_() -> Tensor In-place version of :meth:`~Tensor.rsqrt` """) add_docstr_all('scatter_', r""" scatter_(dim, index, src) -> Tensor Writes all values from the tensor :attr:`src` into :attr:`self` at the indices specified in the :attr:`index` tensor. For each value in :attr:`src`, its output index is specified by its index in :attr:`src` for ``dimension != dim`` and by the corresponding value in :attr:`index` for ``dimension = dim``. For a 3-D tensor, :attr:`self` is updated as:: self[index[i][j][k]][j][k] = src[i][j][k] # if dim == 0 self[i][index[i][j][k]][k] = src[i][j][k] # if dim == 1 self[i][j][index[i][j][k]] = src[i][j][k] # if dim == 2 This is the reverse operation of the manner described in :meth:`~Tensor.gather`. :attr:`self`, :attr:`index` and :attr:`src` (if it is a Tensor) should have same number of dimensions. It is also required that ``index.size(d) <= src.size(d)`` for all dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be between ``0`` and ``self.size(dim) - 1`` inclusive, and all values in a row along the specified dimension :attr:`dim` must be unique. Args: dim (int): the axis along which to index index (LongTensor): the indices of elements to scatter, can be either empty or the same size of src. When empty, the operation returns identity src (Tensor or float): the source element(s) to scatter Example:: >>> x = torch.rand(2, 5) >>> x tensor([[ 0.3992, 0.2908, 0.9044, 0.4850, 0.6004], [ 0.5735, 0.9006, 0.6797, 0.4152, 0.1732]]) >>> torch.zeros(3, 5).scatter_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x) tensor([[ 0.3992, 0.9006, 0.6797, 0.4850, 0.6004], [ 0.0000, 0.2908, 0.0000, 0.4152, 0.0000], [ 0.5735, 0.0000, 0.9044, 0.0000, 0.1732]]) >>> z = torch.zeros(2, 4).scatter_(1, torch.tensor([[2], [3]]), 1.23) >>> z tensor([[ 0.0000, 0.0000, 1.2300, 0.0000], [ 0.0000, 0.0000, 0.0000, 1.2300]]) """) add_docstr_all('scatter_add_', r""" scatter_add_(dim, index, other) -> Tensor Adds all values from the tensor :attr:`other` into :attr:`self` at the indices specified in the :attr:`index` tensor in a similar fashion as :meth:`~torch.Tensor.scatter_`. For each value in :attr:`other`, it is added to an index in :attr:`self` which is specified by its index in :attr:`other` for ``dimension != dim`` and by the corresponding value in :attr:`index` for ``dimension = dim``. For a 3-D tensor, :attr:`self` is updated as:: self[index[i][j][k]][j][k] += other[i][j][k] # if dim == 0 self[i][index[i][j][k]][k] += other[i][j][k] # if dim == 1 self[i][j][index[i][j][k]] += other[i][j][k] # if dim == 2 :attr:`self`, :attr:`index` and :attr:`other` should have same number of dimensions. It is also required that ``index.size(d) <= other.size(d)`` for all dimensions ``d``, and that ``index.size(d) <= self.size(d)`` for all dimensions ``d != dim``. Moreover, as for :meth:`~Tensor.gather`, the values of :attr:`index` must be between ``0`` and ``self.size(dim) - 1`` inclusive, and all values in a row along the specified dimension :attr:`dim` must be unique. .. include:: cuda_deterministic.rst Args: dim (int): the axis along which to index index (LongTensor): the indices of elements to scatter and add, can be either empty or the same size of src. When empty, the operation returns identity. other (Tensor): the source elements to scatter and add Example:: >>> x = torch.rand(2, 5) >>> x tensor([[0.7404, 0.0427, 0.6480, 0.3806, 0.8328], [0.7953, 0.2009, 0.9154, 0.6782, 0.9620]]) >>> torch.ones(3, 5).scatter_add_(0, torch.tensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x) tensor([[1.7404, 1.2009, 1.9154, 1.3806, 1.8328], [1.0000, 1.0427, 1.0000, 1.6782, 1.0000], [1.7953, 1.0000, 1.6480, 1.0000, 1.9620]]) """) add_docstr_all('select', r""" select(dim, index) -> Tensor Slices the :attr:`self` tensor along the selected dimension at the given index. This function returns a tensor with the given dimension removed. Args: dim (int): the dimension to slice index (int): the index to select with .. note:: :meth:`select` is equivalent to slicing. For example, ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. """) add_docstr_all('set_', r""" set_(source=None, storage_offset=0, size=None, stride=None) -> Tensor Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, :attr:`self` tensor will share the same storage and have the same size and strides as :attr:`source`. Changes to elements in one tensor will be reflected in the other. If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying storage, offset, size, and stride. Args: source (Tensor or Storage): the tensor or storage to use storage_offset (int, optional): the offset in the storage size (torch.Size, optional): the desired size. Defaults to the size of the source. stride (tuple, optional): the desired stride. Defaults to C-contiguous strides. """) add_docstr_all('sigmoid', r""" sigmoid() -> Tensor See :func:`torch.sigmoid` """) add_docstr_all('sigmoid_', r""" sigmoid_() -> Tensor In-place version of :meth:`~Tensor.sigmoid` """) add_docstr_all('sign', r""" sign() -> Tensor See :func:`torch.sign` """) add_docstr_all('sign_', r""" sign_() -> Tensor In-place version of :meth:`~Tensor.sign` """) add_docstr_all('sin', r""" sin() -> Tensor See :func:`torch.sin` """) add_docstr_all('sin_', r""" sin_() -> Tensor In-place version of :meth:`~Tensor.sin` """) add_docstr_all('sinh', r""" sinh() -> Tensor See :func:`torch.sinh` """) add_docstr_all('sinh_', r""" sinh_() -> Tensor In-place version of :meth:`~Tensor.sinh` """) add_docstr_all('size', r""" size() -> torch.Size Returns the size of the :attr:`self` tensor. The returned value is a subclass of :class:`tuple`. Example:: >>> torch.empty(3, 4, 5).size() torch.Size([3, 4, 5]) """) add_docstr_all('sort', r""" sort(dim=None, descending=False) -> (Tensor, LongTensor) See :func:`torch.sort` """) add_docstr_all('sparse_dim', r""" sparse_dim() -> int If :attr:`self` is a sparse COO tensor (i.e., with ``torch.sparse_coo`` layout), this returns a the number of sparse dimensions. Otherwise, this throws an error. See also :meth:`Tensor.dense_dim`. """) add_docstr_all('sqrt', r""" sqrt() -> Tensor See :func:`torch.sqrt` """) add_docstr_all('sqrt_', r""" sqrt_() -> Tensor In-place version of :meth:`~Tensor.sqrt` """) add_docstr_all('squeeze', r""" squeeze(dim=None) -> Tensor See :func:`torch.squeeze` """) add_docstr_all('squeeze_', r""" squeeze_(dim=None) -> Tensor In-place version of :meth:`~Tensor.squeeze` """) add_docstr_all('std', r""" std(dim=None, unbiased=True, keepdim=False) -> Tensor See :func:`torch.std` """) add_docstr_all('storage', r""" storage() -> torch.Storage Returns the underlying storage """) add_docstr_all('storage_offset', r""" storage_offset() -> int Returns :attr:`self` tensor's offset in the underlying storage in terms of number of storage elements (not bytes). Example:: >>> x = torch.tensor([1, 2, 3, 4, 5]) >>> x.storage_offset() 0 >>> x[3:].storage_offset() 3 """) add_docstr_all('stride', r""" stride(dim) -> tuple or int Returns the stride of :attr:`self` tensor. Stride is the jump necessary to go from one element to the next one in the specified dimension :attr:`dim`. A tuple of all strides is returned when no argument is passed in. Otherwise, an integer value is returned as the stride in the particular dimension :attr:`dim`. Args: dim (int, optional): the desired dimension in which stride is required Example:: >>> x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) >>> x.stride() (5, 1) >>>x.stride(0) 5 >>> x.stride(-1) 1 """) add_docstr_all('sub', r""" sub(value, other) -> Tensor Subtracts a scalar or tensor from :attr:`self` tensor. If both :attr:`value` and :attr:`other` are specified, each element of :attr:`other` is scaled by :attr:`value` before being used. When :attr:`other` is a tensor, the shape of :attr:`other` must be :ref:`broadcastable <broadcasting-semantics>` with the shape of the underlying tensor. """) add_docstr_all('sub_', r""" sub_(x) -> Tensor In-place version of :meth:`~Tensor.sub` """) add_docstr_all('sum', r""" sum(dim=None, keepdim=False, dtype=None) -> Tensor See :func:`torch.sum` """) add_docstr_all('svd', r""" svd(some=True, compute_uv=True) -> (Tensor, Tensor, Tensor) See :func:`torch.svd` """) add_docstr_all('symeig', r""" symeig(eigenvectors=False, upper=True) -> (Tensor, Tensor) See :func:`torch.symeig` """) add_docstr_all('t', r""" t() -> Tensor See :func:`torch.t` """) add_docstr_all('t_', r""" t_() -> Tensor In-place version of :meth:`~Tensor.t` """) add_docstr_all('to', r""" to(*args, **kwargs) -> Tensor Performs Tensor dtype and/or device conversion. A :class:`torch.dtype` and :class:`torch.device` are inferred from the arguments of ``self.to(*args, **kwargs)``. .. note:: If the ``self`` Tensor already has the correct :class:`torch.dtype` and :class:`torch.device`, then ``self`` is returned. Otherwise, the returned tensor is a copy of ``self`` with the desired :class:`torch.dtype` and :class:`torch.device`. Here are the ways to call ``to``: .. function:: to(dtype, non_blocking=False, copy=False) -> Tensor Returns a Tensor with the specified :attr:`dtype` .. function:: to(device=None, dtype=None, non_blocking=False, copy=False) -> Tensor Returns a Tensor with the specified :attr:`device` and (optional) :attr:`dtype`. If :attr:`dtype` is ``None`` it is inferred to be ``self.dtype``. When :attr:`non_blocking`, tries to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor. When :attr:`copy` is set, a new Tensor is created even when the Tensor already matches the desired conversion. .. function:: to(other, non_blocking=False, copy=False) -> Tensor Returns a Tensor with same :class:`torch.dtype` and :class:`torch.device` as the Tensor :attr:`other`. When :attr:`non_blocking`, tries to convert asynchronously with respect to the host if possible, e.g., converting a CPU Tensor with pinned memory to a CUDA Tensor. When :attr:`copy` is set, a new Tensor is created even when the Tensor already matches the desired conversion. Example:: >>> tensor = torch.randn(2, 2) # Initially dtype=float32, device=cpu >>> tensor.to(torch.float64) tensor([[-0.5044, 0.0005], [ 0.3310, -0.0584]], dtype=torch.float64) >>> cuda0 = torch.device('cuda:0') >>> tensor.to(cuda0) tensor([[-0.5044, 0.0005], [ 0.3310, -0.0584]], device='cuda:0') >>> tensor.to(cuda0, dtype=torch.float64) tensor([[-0.5044, 0.0005], [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') >>> other = torch.randn((), dtype=torch.float64, device=cuda0) >>> tensor.to(other, non_blocking=True) tensor([[-0.5044, 0.0005], [ 0.3310, -0.0584]], dtype=torch.float64, device='cuda:0') """) add_docstr_all('byte', r""" byte() -> Tensor ``self.byte()`` is equivalent to ``self.to(torch.uint8)``. See :func:`to`. """) add_docstr_all('char', r""" char() -> Tensor ``self.char()`` is equivalent to ``self.to(torch.int8)``. See :func:`to`. """) add_docstr_all('double', r""" double() -> Tensor ``self.double()`` is equivalent to ``self.to(torch.float64)``. See :func:`to`. """) add_docstr_all('float', r""" float() -> Tensor ``self.float()`` is equivalent to ``self.to(torch.float32)``. See :func:`to`. """) add_docstr_all('half', r""" half() -> Tensor ``self.half()`` is equivalent to ``self.to(torch.float16)``. See :func:`to`. """) add_docstr_all('int', r""" int() -> Tensor ``self.int()`` is equivalent to ``self.to(torch.int32)``. See :func:`to`. """) add_docstr_all('long', r""" long() -> Tensor ``self.long()`` is equivalent to ``self.to(torch.int64)``. See :func:`to`. """) add_docstr_all('short', r""" short() -> Tensor ``self.short()`` is equivalent to ``self.to(torch.int16)``. See :func:`to`. """) add_docstr_all('take', r""" take(indices) -> Tensor See :func:`torch.take` """) add_docstr_all('tan_', r""" tan_() -> Tensor In-place version of :meth:`~Tensor.tan` """) add_docstr_all('tanh', r""" tanh() -> Tensor See :func:`torch.tanh` """) add_docstr_all('tanh_', r""" tanh_() -> Tensor In-place version of :meth:`~Tensor.tanh` """) add_docstr_all('tolist', r"""" tolist() -> list or number Returns the tensor as a (nested) list. For scalars, a standard Python number is returned, just like with :meth:`~Tensor.item`. Tensors are automatically moved to the CPU first if necessary. This operation is not differentiable. Examples:: >>> a = torch.randn(2, 2) >>> a.tolist() [[0.012766935862600803, 0.5415473580360413], [-0.08909505605697632, 0.7729271650314331]] >>> a[0,0].tolist() 0.012766935862600803 """) add_docstr_all('topk', r""" topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) See :func:`torch.topk` """) add_docstr_all('to_sparse', r""" to_sparse(sparseDims) -> Tensor Returns a sparse copy of the tensor. PyTorch supports sparse tensors in :ref:`coordinate format <sparse-docs>`. Args: sparseDims (int, optional): the number of sparse dimensions to include in the new sparse tensor Example:: >>> d = torch.tensor([[0, 0, 0], [9, 0, 10], [0, 0, 0]]) >>> d tensor([[ 0, 0, 0], [ 9, 0, 10], [ 0, 0, 0]]) >>> d.to_sparse() tensor(indices=tensor([[1, 1], [0, 2]]), values=tensor([ 9, 10]), size=(3, 3), nnz=2, layout=torch.sparse_coo) >>> d.to_sparse(1) tensor(indices=tensor([[1]]), values=tensor([[ 9, 0, 10]]), size=(3, 3), nnz=1, layout=torch.sparse_coo) """) add_docstr_all('trace', r""" trace() -> Tensor See :func:`torch.trace` """) add_docstr_all('transpose', r""" transpose(dim0, dim1) -> Tensor See :func:`torch.transpose` """) add_docstr_all('transpose_', r""" transpose_(dim0, dim1) -> Tensor In-place version of :meth:`~Tensor.transpose` """) add_docstr_all('tril', r""" tril(k=0) -> Tensor See :func:`torch.tril` """) add_docstr_all('tril_', r""" tril_(k=0) -> Tensor In-place version of :meth:`~Tensor.tril` """) add_docstr_all('triu', r""" triu(k=0) -> Tensor See :func:`torch.triu` """) add_docstr_all('triu_', r""" triu_(k=0) -> Tensor In-place version of :meth:`~Tensor.triu` """) add_docstr_all('trtrs', r""" trtrs(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) See :func:`torch.trtrs` """) add_docstr_all('trunc', r""" trunc() -> Tensor See :func:`torch.trunc` """) add_docstr_all('trunc_', r""" trunc_() -> Tensor In-place version of :meth:`~Tensor.trunc` """) add_docstr_all('type', r""" type(dtype=None, non_blocking=False, **kwargs) -> str or Tensor Returns the type if `dtype` is not provided, else casts this object to the specified type. If this is already of the correct type, no copy is performed and the original object is returned. Args: dtype (type or string): The desired type non_blocking (bool): If ``True``, and the source is in pinned memory and destination is on the GPU or vice versa, the copy is performed asynchronously with respect to the host. Otherwise, the argument has no effect. **kwargs: For compatibility, may contain the key ``async`` in place of the ``non_blocking`` argument. The ``async`` arg is deprecated. """) add_docstr_all('type_as', r""" type_as(tensor) -> Tensor Returns this tensor cast to the type of the given tensor. This is a no-op if the tensor is already of the correct type. This is equivalent to:: self.type(tensor.type()) Params: tensor (Tensor): the tensor which has the desired type """) add_docstr_all('unfold', r""" unfold(dim, size, step) -> Tensor Returns a tensor which contains all slices of size :attr:`size` from :attr:`self` tensor in the dimension :attr:`dim`. Step between two slices is given by :attr:`step`. If `sizedim` is the size of dimension dim for :attr:`self`, the size of dimension :attr:`dim` in the returned tensor will be `(sizedim - size) / step + 1`. An additional dimension of size size is appended in the returned tensor. Args: dim (int): dimension in which unfolding happens size (int): the size of each slice that is unfolded step (int): the step between each slice Example:: >>> x = torch.arange(1., 8) >>> x tensor([ 1., 2., 3., 4., 5., 6., 7.]) >>> x.unfold(0, 2, 1) tensor([[ 1., 2.], [ 2., 3.], [ 3., 4.], [ 4., 5.], [ 5., 6.], [ 6., 7.]]) >>> x.unfold(0, 2, 2) tensor([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) """) add_docstr_all('uniform_', r""" uniform_(from=0, to=1) -> Tensor Fills :attr:`self` tensor with numbers sampled from the continuous uniform distribution: .. math:: P(x) = \dfrac{1}{\text{to} - \text{from}} """) add_docstr_all('unsqueeze', r""" unsqueeze(dim) -> Tensor See :func:`torch.unsqueeze` """) add_docstr_all('unsqueeze_', r""" unsqueeze_(dim) -> Tensor In-place version of :meth:`~Tensor.unsqueeze` """) add_docstr_all('var', r""" var(dim=None, unbiased=True, keepdim=False) -> Tensor See :func:`torch.var` """) add_docstr_all('view', r""" view(*shape) -> Tensor Returns a new tensor with the same data as the :attr:`self` tensor but of a different :attr:`shape`. The returned tensor shares the same data and must have the same number of elements, but may have a different size. For a tensor to be viewed, the new view size must be compatible with its original size and stride, i.e., each new view dimension must either be a subspace of an original dimension, or only span across original dimensions :math:`d, d+1, \dots, d+k` that satisfy the following contiguity-like condition that :math:`\forall i = 0, \dots, k-1`, .. math:: \text{stride}[i] = \text{stride}[i+1] \times \text{size}[i+1] Otherwise, :meth:`contiguous` needs to be called before the tensor can be viewed. See also: :meth:`reshape`, which returns a view if the shapes are compatible, and copies (equivalent to calling :meth:`contiguous`) otherwise. Args: shape (torch.Size or int...): the desired size Example:: >>> x = torch.randn(4, 4) >>> x.size() torch.Size([4, 4]) >>> y = x.view(16) >>> y.size() torch.Size([16]) >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions >>> z.size() torch.Size([2, 8]) """) add_docstr_all('view_as', r""" view_as(other) -> Tensor View this tensor as the same size as :attr:`other`. ``self.view_as(other)`` is equivalent to ``self.view(other.size())``. Please see :meth:`~Tensor.view` for more information about ``view``. Args: other (:class:`torch.Tensor`): The result tensor has the same size as :attr:`other`. """) add_docstr_all('expand', r""" expand(*sizes) -> Tensor Returns a new view of the :attr:`self` tensor with singleton dimensions expanded to a larger size. Passing -1 as the size for a dimension means not changing the size of that dimension. Tensor can be also expanded to a larger number of dimensions, and the new ones will be appended at the front. For the new dimensions, the size cannot be set to -1. Expanding a tensor does not allocate new memory, but only creates a new view on the existing tensor where a dimension of size one is expanded to a larger size by setting the ``stride`` to 0. Any dimension of size 1 can be expanded to an arbitrary value without allocating new memory. Args: *sizes (torch.Size or int...): the desired expanded size Example:: >>> x = torch.tensor([[1], [2], [3]]) >>> x.size() torch.Size([3, 1]) >>> x.expand(3, 4) tensor([[ 1, 1, 1, 1], [ 2, 2, 2, 2], [ 3, 3, 3, 3]]) >>> x.expand(-1, 4) # -1 means not changing the size of that dimension tensor([[ 1, 1, 1, 1], [ 2, 2, 2, 2], [ 3, 3, 3, 3]]) """) add_docstr_all('expand_as', r""" expand_as(other) -> Tensor Expand this tensor to the same size as :attr:`other`. ``self.expand_as(other)`` is equivalent to ``self.expand(other.size())``. Please see :meth:`~Tensor.expand` for more information about ``expand``. Args: other (:class:`torch.Tensor`): The result tensor has the same size as :attr:`other`. """) add_docstr_all('zero_', r""" zero_() -> Tensor Fills :attr:`self` tensor with zeros. """) add_docstr_all('matmul', r""" matmul(tensor2) -> Tensor See :func:`torch.matmul` """) add_docstr_all('chunk', r""" chunk(chunks, dim=0) -> List of Tensors See :func:`torch.chunk` """) add_docstr_all('stft', r""" stft(frame_length, hop, fft_size=None, return_onesided=True, window=None, pad_end=0) -> Tensor See :func:`torch.stft` """) add_docstr_all('fft', r""" fft(signal_ndim, normalized=False) -> Tensor See :func:`torch.fft` """) add_docstr_all('ifft', r""" ifft(signal_ndim, normalized=False) -> Tensor See :func:`torch.ifft` """) add_docstr_all('rfft', r""" rfft(signal_ndim, normalized=False, onesided=True) -> Tensor See :func:`torch.rfft` """) add_docstr_all('irfft', r""" irfft(signal_ndim, normalized=False, onesided=True, signal_sizes=None) -> Tensor See :func:`torch.irfft` """) add_docstr_all('det', r""" det() -> Tensor See :func:`torch.det` """) add_docstr_all('where', r""" where(condition, y) -> Tensor ``self.where(condition, y)`` is equivalent to ``torch.where(condition, self, y)``. See :func:`torch.where` """) add_docstr_all('logdet', r""" logdet() -> Tensor See :func:`torch.logdet` """) add_docstr_all('slogdet', r""" slogdet() -> (Tensor, Tensor) See :func:`torch.slogdet` """) add_docstr_all('unbind', r""" unbind(dim=0) -> seq See :func:`torch.unbind` """) add_docstr_all('pinverse', r""" pinverse() -> Tensor See :func:`torch.pinverse` """) add_docstr_all('grad', r""" This attribute is ``None`` by default and becomes a Tensor the first time a call to :func:`backward` computes gradients for ``self``. The attribute will then contain the gradients computed and future calls to :func:`backward` will accumulate (add) gradients into it. """) add_docstr_all('requires_grad', r""" Is ``True`` if gradients need to be computed for this Tensor, ``False`` otherwise. .. note:: The fact that gradients need to be computed for a Tensor do not mean that the :attr:`grad` attribute will be populated, see :attr:`is_leaf` for more details. """) add_docstr_all('is_leaf', r""" All Tensors that have :attr:`requires_grad` which is ``False`` will be leaf Tensors by convention. For Tensors that have :attr:`requires_grad` which is ``True``, they will be leaf Tensors if they were created by the user. This means that they are not the result of an operation and so :attr:`grad_fn` is None. Only leaf Tensors will have their :attr:`grad` populated during a call to :func:`backward`. To get :attr:`grad` populated for non-leaf Tensors, you can use :func:`retain_grad`. Example:: >>> a = torch.rand(10, requires_grad=True) >>> a.is_leaf True >>> b = torch.rand(10, requires_grad=True).cuda() >>> b.is_leaf False # b was created by the operation that cast a cpu Tensor into a cuda Tensor >>> c = torch.rand(10, requires_grad=True) + 2 >>> c.is_leaf False # c was created by the addition operation >>> d = torch.rand(10).cuda() >>> d.is_leaf True # d does not require gradients and so has no operation creating it (that is tracked by the autograd engine) >>> e = torch.rand(10).cuda().requires_grad_() >>> e.is_leaf True # e requires gradients and has no operations creating it >>> f = torch.rand(10, requires_grad=True, device="cuda") >>> f.is_leaf True # f requires grad, has not operation creating it """) add_docstr_all('is_cuda', r""" Is ``True`` if the Tensor is stored on the GPU, ``False`` otherwise. """) add_docstr_all('device', r""" Is the :class:`torch.device` where this Tensor is. """)
{ "repo_name": "ryfeus/lambda-packs", "path": "pytorch/source/torch/_tensor_docs.py", "copies": "1", "size": "70644", "license": "mit", "hash": 8127286000224170000, "line_mean": 22.5951903808, "line_max": 114, "alpha_frac": 0.5967102656, "autogenerated": false, "ratio": 3.1821621621621623, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4278872427762162, "avg_score": null, "num_lines": null }
"""Adds docstrings to Tensor functions""" import torch._C from torch._C import _add_docstr as add_docstr add_docstr(torch._C.FloatTensorBase.abs, """ abs() -> Tensor See :func:`torch.abs` """) add_docstr(torch._C.FloatTensorBase.abs_, """ abs_() -> Tensor In-place version of :meth:`~Tensor.abs` """) add_docstr(torch._C.FloatTensorBase.acos, """ acos() -> Tensor See :func:`torch.acos` """) add_docstr(torch._C.FloatTensorBase.acos_, """ acos_() -> Tensor In-place version of :meth:`~Tensor.acos` """) add_docstr(torch._C.FloatTensorBase.add, """ add(value) See :func:`torch.add` """) add_docstr(torch._C.FloatTensorBase.add_, """ add_(value) In-place version of :meth:`~Tensor.add` """) add_docstr(torch._C.FloatTensorBase.addbmm, """ addbmm(beta=1, mat, alpha=1, batch1, batch2) -> Tensor See :func:`torch.addbmm` """) add_docstr(torch._C.FloatTensorBase.addbmm_, """ addbmm_(beta=1, mat, alpha=1, batch1, batch2) -> Tensor In-place version of :meth:`~Tensor.addbmm` """) add_docstr(torch._C.FloatTensorBase.addcdiv, """ addcdiv(value=1, tensor1, tensor2) -> Tensor See :func:`torch.addcdiv` """) add_docstr(torch._C.FloatTensorBase.addcdiv_, """ addcdiv_(value=1, tensor1, tensor2) -> Tensor In-place version of :meth:`~Tensor.addcdiv` """) add_docstr(torch._C.FloatTensorBase.addcmul, """ addcmul(value=1, tensor1, tensor2) -> Tensor See :func:`torch.addcmul` """) add_docstr(torch._C.FloatTensorBase.addcmul_, """ addcmul_(value=1, tensor1, tensor2) -> Tensor In-place version of :meth:`~Tensor.addcmul` """) add_docstr(torch._C.FloatTensorBase.addmm, """ addmm(beta=1, mat, alpha=1, mat1, mat2) -> Tensor See :func:`torch.addmm` """) add_docstr(torch._C.FloatTensorBase.addmm_, """ addmm_(beta=1, mat, alpha=1, mat1, mat2) -> Tensor In-place version of :meth:`~Tensor.addmm` """) add_docstr(torch._C.FloatTensorBase.addmv, """ addmv(beta=1, tensor, alpha=1, mat, vec) -> Tensor See :func:`torch.addmv` """) add_docstr(torch._C.FloatTensorBase.addmv_, """ addmv_(beta=1, tensor, alpha=1, mat, vec) -> Tensor In-place version of :meth:`~Tensor.addmv` """) add_docstr(torch._C.FloatTensorBase.addr, """ addr(beta=1, alpha=1, vec1, vec2) -> Tensor See :func:`torch.addr` """) add_docstr(torch._C.FloatTensorBase.addr_, """ addr_(beta=1, alpha=1, vec1, vec2) -> Tensor In-place version of :meth:`~Tensor.addr` """) add_docstr(torch._C.FloatTensorBase.apply_, """ apply_(callable) -> Tensor Applies the function :attr:`callable` to each element in the tensor, replacing each element with the value returned by :attr:`callable`. .. note:: This function only works with CPU tensors and should not be used in code sections that require high performance. """) add_docstr(torch._C.FloatTensorBase.asin, """ asin() -> Tensor See :func:`torch.asin` """) add_docstr(torch._C.FloatTensorBase.asin_, """ asin_() -> Tensor In-place version of :meth:`~Tensor.asin` """) add_docstr(torch._C.FloatTensorBase.atan, """ atan() -> Tensor See :func:`torch.atan` """) add_docstr(torch._C.FloatTensorBase.atan2, """ atan2(other) -> Tensor See :func:`torch.atan2` """) add_docstr(torch._C.FloatTensorBase.atan2_, """ atan2_(other) -> Tensor In-place version of :meth:`~Tensor.atan2` """) add_docstr(torch._C.FloatTensorBase.atan_, """ atan_() -> Tensor In-place version of :meth:`~Tensor.atan` """) add_docstr(torch._C.FloatTensorBase.baddbmm, """ baddbmm(beta=1, alpha=1, batch1, batch2) -> Tensor See :func:`torch.baddbmm` """) add_docstr(torch._C.FloatTensorBase.baddbmm_, """ baddbmm_(beta=1, alpha=1, batch1, batch2) -> Tensor In-place version of :meth:`~Tensor.baddbmm` """) add_docstr(torch._C.FloatTensorBase.bernoulli, """ bernoulli() -> Tensor See :func:`torch.bernoulli` """) add_docstr(torch._C.FloatTensorBase.bernoulli_, """ bernoulli_() -> Tensor In-place version of :meth:`~Tensor.bernoulli` """) add_docstr(torch._C.FloatTensorBase.bmm, """ bmm(batch2) -> Tensor See :func:`torch.bmm` """) add_docstr(torch._C.FloatTensorBase.cauchy_, """ cauchy_(median=0, sigma=1, *, generator=None) -> Tensor Fills the tensor with numbers drawn from the Cauchy distribution: .. math:: P(x) = \dfrac{1}{\pi} \dfrac{\sigma}{(x - median)^2 + \sigma^2} """) add_docstr(torch._C.FloatTensorBase.ceil, """ ceil() -> Tensor See :func:`torch.ceil` """) add_docstr(torch._C.FloatTensorBase.ceil_, """ ceil_() -> Tensor In-place version of :meth:`~Tensor.ceil` """) add_docstr(torch._C.FloatTensorBase.clamp, """ clamp(min, max) -> Tensor See :func:`torch.clamp` """) add_docstr(torch._C.FloatTensorBase.clamp_, """ clamp_(min, max) -> Tensor In-place version of :meth:`~Tensor.clamp` """) add_docstr(torch._C.FloatTensorBase.clone, """ clone() -> Tensor Returns a copy of the tensor. The copy has the same size and data type as the original tensor. """) add_docstr(torch._C.FloatTensorBase.contiguous, """ contiguous() -> Tensor Returns a contiguous Tensor containing the same data as this tensor. If this tensor is contiguous, this function returns the original tensor. """) add_docstr(torch._C.FloatTensorBase.copy_, """ copy_(src, async=False) -> Tensor Copies the elements from :attr:`src` into this tensor and returns this tensor. The source tensor should have the same number of elements as this tensor. It may be of a different data type or reside on a different device. Args: src (Tensor): Source tensor to copy async (bool): If True and this copy is between CPU and GPU, then the copy may occur asynchronously with respect to the host. For other copies, this argument has no effect. """) add_docstr(torch._C.FloatTensorBase.cos, """ cos() -> Tensor See :func:`torch.cos` """) add_docstr(torch._C.FloatTensorBase.cos_, """ cos_() -> Tensor In-place version of :meth:`~Tensor.cos` """) add_docstr(torch._C.FloatTensorBase.cosh, """ cosh() -> Tensor See :func:`torch.cosh` """) add_docstr(torch._C.FloatTensorBase.cosh_, """ cosh_() -> Tensor In-place version of :meth:`~Tensor.cosh` """) add_docstr(torch._C.FloatTensorBase.cross, """ cross(other, dim=-1) -> Tensor See :func:`torch.cross` """) add_docstr(torch._C.FloatTensorBase.cumprod, """ cumprod(dim) -> Tensor See :func:`torch.cumprod` """) add_docstr(torch._C.FloatTensorBase.cumsum, """ cumsum(dim) -> Tensor See :func:`torch.cumsum` """) add_docstr(torch._C.FloatTensorBase.data_ptr, """ data_ptr() -> int Returns the address of the first element of this tensor. """) add_docstr(torch._C.FloatTensorBase.diag, """ diag(diagonal=0) -> Tensor See :func:`torch.diag` """) add_docstr(torch._C.FloatTensorBase.dim, """ dim() -> int Returns the number of dimensions of this tensor. """) add_docstr(torch._C.FloatTensorBase.dist, """ dist(other, p=2) -> Tensor See :func:`torch.dist` """) add_docstr(torch._C.FloatTensorBase.div, """ div(value) See :func:`torch.div` """) add_docstr(torch._C.FloatTensorBase.div_, """ div_(value) In-place version of :meth:`~Tensor.div` """) add_docstr(torch._C.FloatTensorBase.dot, """ dot(tensor2) -> float See :func:`torch.dot` """) add_docstr(torch._C.FloatTensorBase.eig, """ eig(eigenvectors=False) -> (Tensor, Tensor) See :func:`torch.eig` """) add_docstr(torch._C.FloatTensorBase.element_size, """ element_size() -> int Returns the size in bytes of an individual element. Example: >>> torch.FloatTensor().element_size() 4 >>> torch.ByteTensor().element_size() 1 """) add_docstr(torch._C.FloatTensorBase.eq, """ eq(other) -> Tensor See :func:`torch.eq` """) add_docstr(torch._C.FloatTensorBase.eq_, """ eq_(other) -> Tensor In-place version of :meth:`~Tensor.eq` """) add_docstr(torch._C.FloatTensorBase.equal, """ equal(other) -> bool See :func:`torch.equal` """) add_docstr(torch._C.FloatTensorBase.exp, """ exp() -> Tensor See :func:`torch.exp` """) add_docstr(torch._C.FloatTensorBase.exp_, """ exp_() -> Tensor In-place version of :meth:`~Tensor.exp` """) add_docstr(torch._C.FloatTensorBase.exponential_, """ exponential_(lambd=1, *, generator=None) -> Tensor Fills this tensor with elements drawn from the exponential distribution: .. math:: P(x) = \lambda e^{-\lambda x} """) add_docstr(torch._C.FloatTensorBase.fill_, """ fill_(value) -> Tensor Fills this tensor with the specified value. """) add_docstr(torch._C.FloatTensorBase.floor, """ floor() -> Tensor See :func:`torch.floor` """) add_docstr(torch._C.FloatTensorBase.floor_, """ floor_() -> Tensor In-place version of :meth:`~Tensor.floor` """) add_docstr(torch._C.FloatTensorBase.fmod, """ fmod(divisor) -> Tensor See :func:`torch.fmod` """) add_docstr(torch._C.FloatTensorBase.fmod_, """ fmod_(divisor) -> Tensor In-place version of :meth:`~Tensor.fmod` """) add_docstr(torch._C.FloatTensorBase.frac, """ frac() -> Tensor See :func:`torch.frac` """) add_docstr(torch._C.FloatTensorBase.frac_, """ frac_() -> Tensor In-place version of :meth:`~Tensor.frac` """) add_docstr(torch._C.FloatTensorBase.gather, """ gather(dim, index) -> Tensor See :func:`torch.gather` """) add_docstr(torch._C.FloatTensorBase.ge, """ ge(other) -> Tensor See :func:`torch.ge` """) add_docstr(torch._C.FloatTensorBase.ge_, """ ge_(other) -> Tensor In-place version of :meth:`~Tensor.ge` """) add_docstr(torch._C.FloatTensorBase.gels, """ gels(A) -> Tensor See :func:`torch.gels` """) add_docstr(torch._C.FloatTensorBase.geometric_, """ geometric_(p, *, generator=None) -> Tensor Fills this tensor with elements drawn from the geometric distribution: .. math:: P(X=k) = (1 - p)^{k - 1} p """) add_docstr(torch._C.FloatTensorBase.geqrf, """ geqrf() -> (Tensor, Tensor) See :func:`torch.geqrf` """) add_docstr(torch._C.FloatTensorBase.ger, """ ger(vec2) -> Tensor See :func:`torch.ger` """) add_docstr(torch._C.FloatTensorBase.gesv, """ gesv(A) -> Tensor, Tensor See :func:`torch.gesv` """) add_docstr(torch._C.FloatTensorBase.gt, """ gt(other) -> Tensor See :func:`torch.gt` """) add_docstr(torch._C.FloatTensorBase.gt_, """ gt_(other) -> Tensor In-place version of :meth:`~Tensor.gt` """) add_docstr(torch._C.FloatTensorBase.histc, """ histc(bins=100, min=0, max=0) -> Tensor See :func:`torch.histc` """) add_docstr(torch._C.FloatTensorBase.index, """ index(m) -> Tensor Selects elements from this tensor using a binary mask or along a given dimension. The expression ``tensor.index(m)`` is equivalent to ``tensor[m]``. Args: m (int or ByteTensor or slice): The dimension or mask used to select elements """) add_docstr(torch._C.FloatTensorBase.index_add_, """ index_add_(dim, index, tensor) -> Tensor Accumulate the elements of tensor into the original tensor by adding to the indices in the order given in index. The shape of tensor must exactly match the elements indexed or an error will be raised. Args: dim (int): Dimension along which to index index (LongTensor): Indices to select from tensor tensor (Tensor): Tensor containing values to add Example: >>> x = torch.Tensor([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) >>> t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> index = torch.LongTensor([0, 2, 1]) >>> x.index_add_(0, index, t) >>> x 2 3 4 8 9 10 5 6 7 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.FloatTensorBase.index_copy_, """ index_copy_(dim, index, tensor) -> Tensor Copies the elements of tensor into the original tensor by selecting the indices in the order given in index. The shape of tensor must exactly match the elements indexed or an error will be raised. Args: dim (int): Dimension along which to index index (LongTensor): Indices to select from tensor tensor (Tensor): Tensor containing values to copy Example: >>> x = torch.Tensor(3, 3) >>> t = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> index = torch.LongTensor([0, 2, 1]) >>> x.index_copy_(0, index, t) >>> x 1 2 3 7 8 9 4 5 6 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.FloatTensorBase.index_fill_, """ index_fill_(dim, index, val) -> Tensor Fills the elements of the original tensor with value :attr:`val` by selecting the indices in the order given in index. Args: dim (int): Dimension along which to index index (LongTensor): Indices val (float): Value to fill Example: >>> x = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> index = torch.LongTensor([0, 2]) >>> x.index_fill_(1, index, -1) >>> x -1 2 -1 -1 5 -1 -1 8 -1 [torch.FloatTensor of size 3x3] """) add_docstr(torch._C.FloatTensorBase.index_select, """ index_select(dim, index) -> Tensor See :func:`torch.index_select` """) add_docstr(torch._C.FloatTensorBase.inverse, """ inverse() -> Tensor See :func:`torch.inverse` """) add_docstr(torch._C.FloatTensorBase.is_contiguous, """ is_contiguous() -> bool Returns True if this tensor is contiguous in memory in C order. """) add_docstr(torch._C.FloatTensorBase.is_set_to, """ is_set_to(tensor) -> bool Returns True if this object refers to the same ``THTensor`` object from the Torch C API as the given tensor. """) add_docstr(torch._C.FloatTensorBase.kthvalue, """ kthvalue(k, dim=None) -> (Tensor, LongTensor) See :func:`torch.kthvalue` """) add_docstr(torch._C.FloatTensorBase.le, """ le(other) -> Tensor See :func:`torch.le` """) add_docstr(torch._C.FloatTensorBase.le_, """ le_(other) -> Tensor In-place version of :meth:`~Tensor.le` """) add_docstr(torch._C.FloatTensorBase.lerp, """ lerp(start, end, weight) See :func:`torch.lerp` """) add_docstr(torch._C.FloatTensorBase.lerp_, """ lerp_(start, end, weight) In-place version of :meth:`~Tensor.lerp` """) add_docstr(torch._C.FloatTensorBase.log, """ log() -> Tensor See :func:`torch.log` """) add_docstr(torch._C.FloatTensorBase.log1p, """ log1p() -> Tensor See :func:`torch.log1p` """) add_docstr(torch._C.FloatTensorBase.log1p_, """ log1p_() -> Tensor In-place version of :meth:`~Tensor.log1p` """) add_docstr(torch._C.FloatTensorBase.log_, """ log_() -> Tensor In-place version of :meth:`~Tensor.log` """) add_docstr(torch._C.FloatTensorBase.log_normal_, u""" log_normal_(mean=1, std=2, *, generator=None) Fills this tensor with numbers samples from the log-normal distribution parameterized by the given mean (\u00B5) and standard deviation (\u03C3). Note that :attr:`mean` and :attr:`stdv` are the mean and standard deviation of the underlying normal distribution, and not of the returned distribution: .. math:: P(x) = \\dfrac{1}{x \\sigma \\sqrt{2\\pi}} e^{-\\dfrac{(\\ln x - \\mu)^2}{2\\sigma^2}} """) add_docstr(torch._C.FloatTensorBase.lt, """ lt(other) -> Tensor See :func:`torch.lt` """) add_docstr(torch._C.FloatTensorBase.lt_, """ lt_(other) -> Tensor In-place version of :meth:`~Tensor.lt` """) add_docstr(torch._C.FloatTensorBase.map_, """ map_(tensor, callable) Applies :attr:`callable` for each element in this tensor and the given tensor and stores the results in this tensor. The :attr:`callable` should have the signature:: def callable(a, b) -> number """) add_docstr(torch._C.FloatTensorBase.masked_copy_, """ masked_copy_(mask, source) Copies elements from :attr:`source` into this tensor at positions where the :attr:`mask` is one. The :attr:`mask` should have the same number of elements as this tensor. The :attr:`source` should have at least as many elements as the number of ones in :attr:`mask` Args: mask (ByteTensor): The binary mask source (Tensor): The tensor to copy from .. note:: The :attr:`mask` operates on the :attr:`self` tensor, not on the given :attr:`source` tensor. """) add_docstr(torch._C.FloatTensorBase.masked_fill_, """ masked_fill_(mask, value) Fills elements of this tensor with :attr:`value` where :attr:`mask` is one. The :attr:`mask` should have the same number of elements as this tensor, but the shape may differ. Args: mask (ByteTensor): The binary mask value (Tensor): The value to fill """) add_docstr(torch._C.FloatTensorBase.masked_select, """ masked_select(mask) -> Tensor See :func:`torch.masked_select` """) add_docstr(torch._C.FloatTensorBase.max, """ max(dim=None) -> float or (Tensor, Tensor) See :func:`torch.max` """) add_docstr(torch._C.FloatTensorBase.mean, """ mean(dim=None) -> float or (Tensor, Tensor) See :func:`torch.mean` """) add_docstr(torch._C.FloatTensorBase.median, """ median(dim=-1, values=None, indices=None) -> (Tensor, LongTensor) See :func:`torch.median` """) add_docstr(torch._C.FloatTensorBase.min, """ min(dim=None) -> float or (Tensor, Tensor) See :func:`torch.min` """) add_docstr(torch._C.FloatTensorBase.mm, """ mm(mat2) -> Tensor See :func:`torch.mm` """) add_docstr(torch._C.FloatTensorBase.mode, """ mode(dim=-1, values=None, indices=None) -> (Tensor, LongTensor) See :func:`torch.mode` """) add_docstr(torch._C.FloatTensorBase.mul, """ mul(value) -> Tensor See :func:`torch.mul` """) add_docstr(torch._C.FloatTensorBase.mul_, """ mul_(value) In-place version of :meth:`~Tensor.mul` """) add_docstr(torch._C.FloatTensorBase.multinomial, """ multinomial(num_samples, replacement=False, *, generator=None) See :func:`torch.multinomial` """) add_docstr(torch._C.FloatTensorBase.mv, """ mv(vec) -> Tensor See :func:`torch.mv` """) add_docstr(torch._C.FloatTensorBase.narrow, """ narrow(dimension, start, length) -> Tensor Returns a new tensor that is a narrowed version of this tensor. The dimension :attr:`dim` is narrowed from :attr:`start` to :attr:`start + length`. The returned tensor and this tensor share the same underlying storage. Args: dimension (int): The dimension along which to narrow start (int): The starting dimension length (int): Example: >>> x = torch.Tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> x.narrow(0, 0, 2) 1 2 3 4 5 6 [torch.FloatTensor of size 2x3] >>> x.narrow(1, 1, 2) 2 3 5 6 8 9 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.FloatTensorBase.ndimension, """ ndimension() -> int Alias for :meth:`~Tensor.dim()` """) add_docstr(torch._C.FloatTensorBase.ne, """ ne(other) -> Tensor See :func:`torch.ne` """) add_docstr(torch._C.FloatTensorBase.ne_, """ ne_(other) -> Tensor In-place version of :meth:`~Tensor.ne` """) add_docstr(torch._C.FloatTensorBase.neg, """ neg() -> Tensor See :func:`torch.neg` """) add_docstr(torch._C.FloatTensorBase.neg_, """ neg_() -> Tensor In-place version of :meth:`~Tensor.neg` """) add_docstr(torch._C.FloatTensorBase.nelement, """ nelement() -> int Alias for :meth:`~Tensor.numel` """) add_docstr(torch._C.FloatTensorBase.nonzero, """ nonzero() -> LongTensor See :func:`torch.nonzero` """) add_docstr(torch._C.FloatTensorBase.norm, """ norm(p=2) -> float See :func:`torch.norm` """) add_docstr(torch._C.FloatTensorBase.normal_, """ normal_(mean=0, std=1, *, generator=None) Fills this tensor with elements samples from the normal distribution parameterized by :attr:`mean` and :attr:`std`. """) add_docstr(torch._C.FloatTensorBase.numel, """ numel() -> int See :func:`torch.numel` """) add_docstr(torch._C.FloatTensorBase.numpy, """ numpy() -> ndarray Returns this tensor as a NumPy :class:`ndarray`. This tensor and the returned :class:`ndarray` share the same underlying storage. Changes to this tensor will be reflected in the :class:`ndarray` and vice versa. """) add_docstr(torch._C.FloatTensorBase.orgqr, """ orgqr(input2) -> Tensor See :func:`torch.orgqr` """) add_docstr(torch._C.FloatTensorBase.ormqr, """ ormqr(input2, input3, left=True, transpose=False) -> Tensor See :func:`torch.ormqr` """) add_docstr(torch._C.FloatTensorBase.potrf, """ potrf(upper=True) -> Tensor See :func:`torch.potrf` """) add_docstr(torch._C.FloatTensorBase.potri, """ potri(upper=True) -> Tensor See :func:`torch.potri` """) add_docstr(torch._C.FloatTensorBase.potrs, """ potrs(input2, upper=True) -> Tensor See :func:`torch.potrs` """) add_docstr(torch._C.FloatTensorBase.pow, """ pow(exponent) See :func:`torch.pow` """) add_docstr(torch._C.FloatTensorBase.pow_, """ pow_(exponent) In-place version of :meth:`~Tensor.pow` """) add_docstr(torch._C.FloatTensorBase.prod, """ prod() -> float See :func:`torch.prod` """) add_docstr(torch._C.FloatTensorBase.pstrf, """ pstrf(upper=True, tol=-1) -> (Tensor, IntTensor) See :func:`torch.pstrf` """) add_docstr(torch._C.FloatTensorBase.qr, """ qr() -> (Tensor, Tensor) See :func:`torch.qr` """) add_docstr(torch._C.FloatTensorBase.random_, """ random_(from=0, to=None, *, generator=None) Fills this tensor with numbers sampled from the uniform distribution or discrete uniform distribution over [from, to - 1]. If not specified, the values are only bounded by this tensor's data type. """) add_docstr(torch._C.FloatTensorBase.reciprocal, """ reciprocal() -> Tensor See :func:`torch.reciprocal` """) add_docstr(torch._C.FloatTensorBase.reciprocal_, """ reciprocal_() -> Tensor In-place version of :meth:`~Tensor.reciprocal` """) add_docstr(torch._C.FloatTensorBase.remainder, """ remainder(divisor) -> Tensor See :func:`torch.remainder` """) add_docstr(torch._C.FloatTensorBase.remainder_, """ remainder_(divisor) -> Tensor In-place version of :meth:`~Tensor.remainder` """) add_docstr(torch._C.FloatTensorBase.renorm, """ renorm(p, dim, maxnorm) -> Tensor See :func:`torch.renorm` """) add_docstr(torch._C.FloatTensorBase.renorm_, """ renorm_(p, dim, maxnorm) -> Tensor In-place version of :meth:`~Tensor.renorm` """) add_docstr(torch._C.FloatTensorBase.resize_, """ resize_(*sizes) Resizes this tensor to the specified size. If the number of elements is larger than the current storage size, then the underlying storage is resized to fit the new number of elements. If the number of elements is smaller, the underlying storage is not changed. Existing elements are preserved but any new memory is uninitialized. Args: sizes (torch.Size or int...): The desired size Example: >>> x = torch.Tensor([[1, 2], [3, 4], [5, 6]]) >>> x.resize_(2, 2) >>> x 1 2 3 4 [torch.FloatTensor of size 2x2] """) add_docstr(torch._C.FloatTensorBase.resize_as_, """ resize_as_(tensor) Resizes the current tensor to be the same size as the specified tensor. This is equivalent to:: self.resize_(tensor.size()) """) add_docstr(torch._C.FloatTensorBase.round, """ round() -> Tensor See :func:`torch.round` """) add_docstr(torch._C.FloatTensorBase.round_, """ round_() -> Tensor In-place version of :meth:`~Tensor.round` """) add_docstr(torch._C.FloatTensorBase.rsqrt, """ rsqrt() -> Tensor See :func:`torch.rsqrt` """) add_docstr(torch._C.FloatTensorBase.rsqrt_, """ rsqrt_() -> Tensor In-place version of :meth:`~Tensor.rsqrt` """) add_docstr(torch._C.FloatTensorBase.scatter_, """ scatter_(input, dim, index, src) -> Tensor Writes all values from the Tensor :attr:`src` into self at the indices specified in the :attr:`index` Tensor. The indices are specified with respect to the given dimension, dim, in the manner described in :meth:`~Tensor.gather`. Note that, as for gather, the values of index must be between `0` and `(self.size(dim) -1)` inclusive and all values in a row along the specified dimension must be unique. Args: input (Tensor): The source tensor dim (int): The axis along which to index index (LongTensor): The indices of elements to scatter src (Tensor or float): The source element(s) to scatter Example:: >>> x = torch.rand(2, 5) >>> x 0.4319 0.6500 0.4080 0.8760 0.2355 0.2609 0.4711 0.8486 0.8573 0.1029 [torch.FloatTensor of size 2x5] >>> torch.zeros(3, 5).scatter_(0, torch.LongTensor([[0, 1, 2, 0, 0], [2, 0, 0, 1, 2]]), x) 0.4319 0.4711 0.8486 0.8760 0.2355 0.0000 0.6500 0.0000 0.8573 0.0000 0.2609 0.0000 0.4080 0.0000 0.1029 [torch.FloatTensor of size 3x5] >>> z = torch.zeros(2, 4).scatter_(1, torch.LongTensor([[2], [3]]), 1.23) >>> z 0.0000 0.0000 1.2300 0.0000 0.0000 0.0000 0.0000 1.2300 [torch.FloatTensor of size 2x4] """) add_docstr(torch._C.FloatTensorBase.select, """ select(dim, index) -> Tensor or number Slices the tensor along the selected dimension at the given index. If this tensor is one dimensional, this function returns a number. Otherwise, it returns a tensor with the given dimension removed. Args: dim (int): Dimension to slice index (int): Index to select .. note:: :meth:`select` is equivalent to slicing. For example, ``tensor.select(0, index)`` is equivalent to ``tensor[index]`` and ``tensor.select(2, index)`` is equivalent to ``tensor[:,:,index]``. """) add_docstr(torch._C.FloatTensorBase.set_, """ set_(source=None, storage_offset=0, size=None, stride=None) Sets the underlying storage, size, and strides. If :attr:`source` is a tensor, this tensor will share the same storage and have the same size and strides as the given tensor. Changes to elements in one tensor will be reflected in the other. If :attr:`source` is a :class:`~torch.Storage`, the method sets the underlying storage, offset, size, and stride. Args: source (Tensor or Storage): The tensor or storage to use storage_offset (int): The offset in the storage size (torch.Size): The desired size. Defaults to the size of the source. stride (tuple): The desired stride. Defaults to C-contiguous strides. """) add_docstr(torch._C.FloatTensorBase.sigmoid, """ sigmoid() -> Tensor See :func:`torch.sigmoid` """) add_docstr(torch._C.FloatTensorBase.sigmoid_, """ sigmoid_() -> Tensor In-place version of :meth:`~Tensor.sigmoid` """) add_docstr(torch._C.FloatTensorBase.sign, """ sign() -> Tensor See :func:`torch.sign` """) add_docstr(torch._C.FloatTensorBase.sign_, """ sign_() -> Tensor In-place version of :meth:`~Tensor.sign` """) add_docstr(torch._C.FloatTensorBase.sin, """ sin() -> Tensor See :func:`torch.sin` """) add_docstr(torch._C.FloatTensorBase.sin_, """ sin_() -> Tensor In-place version of :meth:`~Tensor.sin` """) add_docstr(torch._C.FloatTensorBase.sinh, """ sinh() -> Tensor See :func:`torch.sinh` """) add_docstr(torch._C.FloatTensorBase.sinh_, """ sinh_() -> Tensor In-place version of :meth:`~Tensor.sinh` """) add_docstr(torch._C.FloatTensorBase.size, """ size() -> torch.Size Returns the size of the tensor. The returned value is a subclass of :class:`tuple`. Example: >>> torch.Tensor(3, 4, 5).size() torch.Size([3, 4, 5]) """) add_docstr(torch._C.FloatTensorBase.sort, """ sort(dim=None, descending=False) -> (Tensor, LongTensor) See :func:`torch.sort` """) add_docstr(torch._C.FloatTensorBase.sqrt, """ sqrt() -> Tensor See :func:`torch.sqrt` """) add_docstr(torch._C.FloatTensorBase.sqrt_, """ sqrt_() -> Tensor In-place version of :meth:`~Tensor.sqrt` """) add_docstr(torch._C.FloatTensorBase.squeeze, """ squeeze(dim=None) See :func:`torch.squeeze` """) add_docstr(torch._C.FloatTensorBase.squeeze_, """ squeeze_(dim=None) In-place version of :meth:`~Tensor.squeeze` """) add_docstr(torch._C.FloatTensorBase.std, """ std() -> float See :func:`torch.std` """) add_docstr(torch._C.FloatTensorBase.storage, """ storage() -> torch.Storage Returns the underlying storage """) add_docstr(torch._C.FloatTensorBase.storage_offset, """ storage_offset() -> int Returns this tensor's offset in the underlying storage in terms of number of storage elements (not bytes). Example: >>> x = torch.Tensor([1, 2, 3, 4, 5]) >>> x.storage_offset() 0 >>> x[3:].storage_offset() 3 """) add_docstr(torch._C.FloatTensorBase.stride, """ stride() -> tuple Returns the stride of the tensor. """) add_docstr(torch._C.FloatTensorBase.sub, """ sub(value, other) -> Tensor Subtracts a scalar or tensor from this tensor. If both :attr:`value` and :attr:`other` are specified, each element of :attr:`other` is scaled by :attr:`value` before being used. """) add_docstr(torch._C.FloatTensorBase.sub_, """ sub_(x) -> Tensor In-place version of :meth:`~Tensor.sub` """) add_docstr(torch._C.FloatTensorBase.sum, """ sum(dim=None) -> float See :func:`torch.sum` """) add_docstr(torch._C.FloatTensorBase.svd, """ svd(some=True) -> (Tensor, Tensor, Tensor) See :func:`torch.svd` """) add_docstr(torch._C.FloatTensorBase.symeig, """ symeig(eigenvectors=False, upper=True) -> (Tensor, Tensor) See :func:`torch.symeig` """) add_docstr(torch._C.FloatTensorBase.t, """ t() -> Tensor See :func:`torch.t` """) add_docstr(torch._C.FloatTensorBase.t_, """ t_() -> Tensor In-place version of :meth:`~Tensor.t` """) add_docstr(torch._C.FloatTensorBase.tan, """ tan() -> Tensor See :func:`torch.tan` """) add_docstr(torch._C.FloatTensorBase.tan_, """ tan_() -> Tensor In-place version of :meth:`~Tensor.tan` """) add_docstr(torch._C.FloatTensorBase.tanh, """ tanh() -> Tensor See :func:`torch.tanh` """) add_docstr(torch._C.FloatTensorBase.tanh_, """ tanh_() -> Tensor In-place version of :meth:`~Tensor.tanh` """) add_docstr(torch._C.FloatTensorBase.topk, """ topk(k, dim=None, largest=True, sorted=True) -> (Tensor, LongTensor) See :func:`torch.topk` """) add_docstr(torch._C.FloatTensorBase.trace, """ trace() -> float See :func:`torch.trace` """) add_docstr(torch._C.FloatTensorBase.transpose, """ transpose(dim0, dim1) -> Tensor See :func:`torch.transpose` """) add_docstr(torch._C.FloatTensorBase.transpose_, """ transpose_(dim0, dim1) -> Tensor In-place version of :meth:`~Tensor.transpose` """) add_docstr(torch._C.FloatTensorBase.tril, """ tril(k=0) -> Tensor See :func:`torch.tril` """) add_docstr(torch._C.FloatTensorBase.tril_, """ tril_(k=0) -> Tensor In-place version of :meth:`~Tensor.tril` """) add_docstr(torch._C.FloatTensorBase.triu, """ triu(k=0) -> Tensor See :func:`torch.triu` """) add_docstr(torch._C.FloatTensorBase.triu_, """ triu_(k=0) -> Tensor In-place version of :meth:`~Tensor.triu` """) add_docstr(torch._C.FloatTensorBase.trtrs, """ trtrs(A, upper=True, transpose=False, unitriangular=False) -> (Tensor, Tensor) See :func:`torch.trtrs` """) add_docstr(torch._C.FloatTensorBase.trunc, """ trunc() -> Tensor See :func:`torch.trunc` """) add_docstr(torch._C.FloatTensorBase.trunc_, """ trunc_() -> Tensor In-place version of :meth:`~Tensor.trunc` """) add_docstr(torch._C.FloatTensorBase.unfold, """ unfold(dim, size, step) -> Tensor Returns a tensor which contains all slices of size :attr:`size` in the dimension :attr:`dim`. Step between two slices is given by :attr:`step`. If `sizedim` is the original size of dimension dim, the size of dimension `dim` in the returned tensor will be `(sizedim - size) / step + 1` An additional dimension of size size is appended in the returned tensor. Args: dim (int): dimension in which unfolding happens size (int): size of each slice that is unfolded step (int): the step between each slice Example:: >>> x = torch.range(1, 7) >>> x 1 2 3 4 5 6 7 [torch.FloatTensor of size 7] >>> x.unfold(0, 2, 1) 1 2 2 3 3 4 4 5 5 6 6 7 [torch.FloatTensor of size 6x2] >>> x.unfold(0, 2, 2) 1 2 3 4 5 6 [torch.FloatTensor of size 3x2] """) add_docstr(torch._C.FloatTensorBase.uniform_, """ uniform_(from=0, to=1) -> Tensor Fills this tensor with numbers sampled from the uniform distribution: .. math: P(x) = \dfrac{1}{to - from} """) add_docstr(torch._C.FloatTensorBase.unsqueeze, """ unsqueeze(dim) See :func:`torch.unsqueeze` """) add_docstr(torch._C.FloatTensorBase.unsqueeze_, """ unsqueeze_(dim) In-place version of :meth:`~Tensor.unsqueeze` """) add_docstr(torch._C.FloatTensorBase.var, """ var() -> float See :func:`torch.var` """) add_docstr(torch._C.FloatTensorBase.view, """ view(*args) -> Tensor Returns a new tensor with the same data but different size. The returned tensor shares the same data and must have the same number of elements, but may have a different size. A tensor must be :func:`contiguous` to be viewed. Args: args (torch.Size or int...): Desired size Example: >>> x = torch.randn(4, 4) >>> x.size() torch.Size([4, 4]) >>> y = x.view(16) >>> y.size() torch.Size([16]) >>> z = x.view(-1, 8) # the size -1 is inferred from other dimensions >>> z.size() torch.Size([2, 8]) """) add_docstr(torch._C.FloatTensorBase.zero_, """ zero_() Fills this tensor with zeros. """)
{ "repo_name": "RPGOne/Skynet", "path": "pytorch-master/torch/_tensor_docs.py", "copies": "1", "size": "34576", "license": "bsd-3-clause", "hash": 1831959725932663000, "line_mean": 19.5077105575, "line_max": 94, "alpha_frac": 0.6280657103, "autogenerated": false, "ratio": 3.066063669415625, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9193370702346408, "avg_score": 0.00015173547384328043, "num_lines": 1686 }
"""Add searchtemplate relationship to View model Revision ID: ecf00882f546 Revises: 36e85b266dba Create Date: 2016-09-30 11:42:03.009501 Auto generated code by flask-migrate and Alembic. """ # This code is auto generated. Ignore linter errors. # pylint: skip-file # revision identifiers, used by Alembic. revision = 'ecf00882f546' down_revision = '36e85b266dba' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('view', sa.Column('query_dsl', sa.UnicodeText(), nullable=True)) op.add_column('view', sa.Column('searchtemplate_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'view', 'searchtemplate', ['searchtemplate_id'], ['id']) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'view', type_='foreignkey') op.drop_column('view', 'searchtemplate_id') op.drop_column('view', 'query_dsl') ### end Alembic commands ###
{ "repo_name": "google/timesketch", "path": "timesketch/migrations/versions/ecf00882f546_.py", "copies": "1", "size": "1047", "license": "apache-2.0", "hash": 3557390965745463000, "line_mean": 30.7272727273, "line_max": 88, "alpha_frac": 0.6991404011, "autogenerated": false, "ratio": 3.4215686274509802, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46207090285509805, "avg_score": null, "num_lines": null }
"""Adds edges between family members at the same address.""" import six from . import entity_tools from . import graph_tools from . import utils # Edges between neighbours are added only if the number of entities # at a particular address is at most `MAX_NEIGHBOUR_GROUP_SIZE`: MAX_NEIGHBOUR_GROUP_SIZE = 2 # String to prefix log messages with: LOG_PREFIX = '[post_process_neighbours] ' def _are_surnames_similar(surname1, surname2): """Decides if two surnames are similar enough to be family.""" if (not surname1) or (not surname2): return False # TODO(matejbalog): Consider normalising by removing accents and # capitalisation. if surname1 == surname2: return True # Decide based on the length of the longest common prefix: lcp = utils.longest_common_prefix(surname1, surname2) if (lcp >= 3 and lcp >= len(surname1) - 3 and lcp >= len(surname2) - 1 and surname1[-1] in ['a', '\xe1']): return True if (lcp >= 3 and lcp >= len(surname1) - 1 and lcp >= len(surname2) - 3 and surname2[-1] in ['a', '\xe1']): return True return False def add_family_and_neighbour_edges(db, test_mode): """Adds edges between family members and close neighbours. Creates two new edge types and adds the corresponding edges: (1) "family": Links any two entities at the same address with "sufficiently" similar surnames (as determined by the function `_are_surnames_similar` above). (2) "neighbours": Links any two entities at the same address, as long as there are at most MAX_NEIGHBOUR_GROUP_SIZE entities at that address. """ # Load surnames and academic titles: surnames = entity_tools.get_surnames() titles_parser = entity_tools.get_academic_titles_parser() # Compute mapping from eids to parsed entity names: parsed_name = {} suffix = ' LIMIT 50000;' if test_mode else ';' query = 'SELECT id, name FROM entities' + suffix with db.get_server_side_cursor(query) as cur: for eid, name in cur: parsed = entity_tools.parse_entity_name( name, titles_parser, surnames, verbose=False) if parsed: parsed_name[eid] = parsed # Initialise edges: edges_family = [] edges_neighbours = [] # Iterate through entity groups sharing the same Address: suffix = " LIMIT 50000;" if test_mode else ";" cur = db.get_server_side_cursor(""" SELECT array_agg(id) as eids FROM entities GROUP BY address_id """ + suffix, buffer_size=10000) # Iterate through entity groups sharing the same Address: for row in cur: eids = row[0] # Iterate through distinct pairs of entities in this group: group_size = len(eids) for i in six.moves.range(group_size): # Add family edges: if eids[i] in parsed_name: for j in six.moves.range(i + 1, group_size): if eids[j] in parsed_name: if _are_surnames_similar( parsed_name[eids[i]].surname, parsed_name[eids[j]].surname): edges_family.append((eids[i], eids[j])) edges_family.append((eids[j], eids[i])) # Add neighbour edges: if group_size <= MAX_NEIGHBOUR_GROUP_SIZE: for j in range(i + 1, group_size): edges_neighbours.append((eids[i], eids[j])) edges_neighbours.append((eids[j], eids[i])) cur.close() print('%sAccumulated %d family edges and %d neighbour edges' % (LOG_PREFIX, len(edges_family), len(edges_neighbours))) # Get edge type indices for the new edge types: edge_type_family = graph_tools.add_or_get_edge_type( db, "Zhoda v priezvisku a adrese", LOG_PREFIX) edge_type_neighbour = graph_tools.add_or_get_edge_type( db, "Susedia", LOG_PREFIX) # Remove any existing edges of these edge types: q_data = [edge_type_family, edge_type_neighbour] db.execute(""" DELETE FROM related WHERE stakeholder_type_id=%s OR stakeholder_type_id=%s; """, q_data) print("%sRemoved any existing edges of types %s" % (LOG_PREFIX, q_data)) # Insert the new edges: with db.cursor() as cur: q = """ INSERT INTO related(eid, eid_relation, stakeholder_type_id) VALUES (%s, %s, %s); """ q_data = [(source, target, edge_type_family) for source, target in edges_family] cur.executemany(q, q_data) q_data = [(source, target, edge_type_neighbour) for source, target in edges_neighbours] cur.executemany(q, q_data)
{ "repo_name": "verejnedigital/verejne.digital", "path": "data/prod_generation/post_process_neighbours.py", "copies": "1", "size": "4812", "license": "apache-2.0", "hash": -7172173169473873000, "line_mean": 35.7328244275, "line_max": 122, "alpha_frac": 0.6047381546, "autogenerated": false, "ratio": 3.6289592760180995, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47336974306180996, "avg_score": null, "num_lines": null }
"""add_segment_allocations Revision ID: 1bd7cff90384 Revises: 374c1bdb4480 Create Date: 2016-01-25 19:26:27.899610 """ # revision identifiers, used by Alembic. revision = '1bd7cff90384' down_revision = '374c1bdb4480' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'quark_segment_allocation_ranges', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('segment_id', sa.String(length=36), nullable=True), sa.Column('segment_type', sa.String(length=36), nullable=True), sa.Column('first_id', sa.BigInteger(), nullable=False), sa.Column('last_id', sa.BigInteger(), nullable=False), sa.Column('do_not_use', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('id'), mysql_engine='InnoDB' ) op.create_index(op.f('ix_quark_segment_allocation_ranges_segment_id'), 'quark_segment_allocation_ranges', ['segment_id'], unique=False) op.create_index(op.f('ix_quark_segment_allocation_ranges_segment_type'), 'quark_segment_allocation_ranges', ['segment_type'], unique=False) op.create_table( 'quark_segment_allocations', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False), sa.Column('segment_id', sa.String(length=36), nullable=False), sa.Column('segment_type', sa.String(length=36), nullable=False), sa.Column('segment_allocation_range_id', sa.String(length=36), nullable=True), sa.Column('network_id', sa.String(length=36), nullable=True), sa.Column('deallocated', sa.Boolean(), nullable=True), sa.Column('deallocated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['segment_allocation_range_id'], ['quark_segment_allocation_ranges.id'], ondelete='CASCADE'), sa.PrimaryKeyConstraint('id', 'segment_id', 'segment_type'), mysql_engine='InnoDB' ) op.create_index(op.f('ix_quark_segment_allocations_deallocated'), 'quark_segment_allocations', ['deallocated'], unique=False) op.create_index(op.f('ix_quark_segment_allocations_deallocated_at'), 'quark_segment_allocations', ['deallocated_at'], unique=False) def downgrade(): op.drop_index(op.f('ix_quark_segment_allocations_deallocated_at'), table_name='quark_segment_allocations') op.drop_index(op.f('ix_quark_segment_allocations_deallocated'), table_name='quark_segment_allocations') op.drop_table('quark_segment_allocations') op.drop_index(op.f('ix_quark_segment_allocation_ranges_segment_type'), table_name='quark_segment_allocation_ranges') op.drop_index(op.f('ix_quark_segment_allocation_ranges_segment_id'), table_name='quark_segment_allocation_ranges') op.drop_table('quark_segment_allocation_ranges')
{ "repo_name": "alanquillin/quark", "path": "quark/db/migration/alembic/versions/1bd7cff90384_add_segment_allocations.py", "copies": "4", "size": "3204", "license": "apache-2.0", "hash": 5609530279693270000, "line_mean": 43.5, "line_max": 76, "alpha_frac": 0.6207865169, "autogenerated": false, "ratio": 3.595959595959596, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6216746112859597, "avg_score": null, "num_lines": null }