blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
sequencelengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
65e39f05502ee1e4f16aa0274c7f28f5ee17a0e9 | bf2390ac5b116177acebd424707167c5c22d081a | /include/ClientData.py | e10c43a7a89c916e059cfdba2a21e69ac7991739 | [
"WTFPL"
] | permissive | bigretromike/hydrus | 1cd842129da3e1851a7ad0559790a4895cad6887 | 6da58bc9df51c75fa65173b182166deb3259278e | refs/heads/master | 2021-01-24T20:25:24.164062 | 2015-11-13T09:06:38 | 2015-11-13T09:06:38 | 44,671,599 | 0 | 0 | null | 2015-11-13T09:06:38 | 2015-10-21T11:26:12 | Python | UTF-8 | Python | false | false | 110,042 | py | import ClientConstants as CC
import ClientDefaults
import ClientDownloading
import ClientFiles
import ClientNetworking
import collections
import datetime
import HydrusConstants as HC
import HydrusExceptions
import HydrusSerialisable
import HydrusTags
import threading
import traceback
import os
import random
import shutil
import sqlite3
import stat
import sys
import time
import wx
import yaml
import HydrusData
import HydrusGlobals
import HydrusThreading
def AddPaddingToDimensions( dimensions, padding ):
( x, y ) = dimensions
return ( x + padding, y + padding )
def CatchExceptionClient( etype, value, tb ):
try:
job_key = HydrusThreading.JobKey()
if etype == HydrusExceptions.ShutdownException:
return
elif etype == HydrusExceptions.DBException:
( text, caller_traceback, db_traceback ) = value
job_key.SetVariable( 'popup_title', 'Database Error!' )
job_key.SetVariable( 'popup_text_1', text )
job_key.SetVariable( 'popup_caller_traceback', caller_traceback )
job_key.SetVariable( 'popup_db_traceback', db_traceback )
else:
trace_list = traceback.format_tb( tb )
trace = ''.join( trace_list )
if etype == wx.PyDeadObjectError:
print( 'Got a PyDeadObjectError, which can probably be ignored, but here it is anyway:' )
print( HydrusData.ToUnicode( value ) )
print( trace )
return
try: job_key.SetVariable( 'popup_title', HydrusData.ToUnicode( etype.__name__ ) )
except: job_key.SetVariable( 'popup_title', HydrusData.ToUnicode( etype ) )
job_key.SetVariable( 'popup_text_1', HydrusData.ToUnicode( value ) )
job_key.SetVariable( 'popup_traceback', trace )
text = job_key.ToString()
print( '' )
print( 'The following uncaught exception occured at ' + HydrusData.ConvertTimestampToPrettyTime( HydrusData.GetNow() ) + ':' )
try: print( text )
except: print( repr( text ) )
sys.stdout.flush()
sys.stderr.flush()
HydrusGlobals.client_controller.pub( 'message', job_key )
except:
text = 'Encountered an error I could not parse:'
text += os.linesep
text += HydrusData.ToUnicode( ( etype, value, tb ) )
try: text += traceback.format_exc()
except: pass
HydrusData.ShowText( text )
time.sleep( 1 )
def ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates ):
num_files = 0
actions = set()
locations = set()
extra_words = ''
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
if len( content_updates ) > 0:
name = HydrusGlobals.client_controller.GetServicesManager().GetService( service_key ).GetName()
locations.add( name )
for content_update in content_updates:
( data_type, action, row ) = content_update.ToTuple()
if data_type == HC.CONTENT_TYPE_MAPPINGS: extra_words = ' tags for'
actions.add( HC.content_update_string_lookup[ action ] )
num_files += len( content_update.GetHashes() )
s = ', '.join( locations ) + '->' + ', '.join( actions ) + extra_words + ' ' + HydrusData.ConvertIntToPrettyString( num_files ) + ' files'
return s
def ConvertServiceKeysToTagsToServiceKeysToContentUpdates( hashes, service_keys_to_tags ):
service_keys_to_content_updates = {}
for ( service_key, tags ) in service_keys_to_tags.items():
if service_key == CC.LOCAL_TAG_SERVICE_KEY: action = HC.CONTENT_UPDATE_ADD
else: action = HC.CONTENT_UPDATE_PEND
content_updates = [ HydrusData.ContentUpdate( HC.CONTENT_TYPE_MAPPINGS, action, ( tag, hashes ) ) for tag in tags ]
service_keys_to_content_updates[ service_key ] = content_updates
return service_keys_to_content_updates
def ConvertShortcutToPrettyShortcut( modifier, key ):
if modifier == wx.ACCEL_NORMAL: modifier = ''
elif modifier == wx.ACCEL_ALT: modifier = 'alt'
elif modifier == wx.ACCEL_CTRL: modifier = 'ctrl'
elif modifier == wx.ACCEL_SHIFT: modifier = 'shift'
if key in range( 65, 91 ): key = chr( key + 32 ) # + 32 for converting ascii A -> a
elif key in range( 97, 123 ): key = chr( key )
else: key = CC.wxk_code_string_lookup[ key ]
return ( modifier, key )
def ConvertZoomToPercentage( zoom ):
zoom_percent = zoom * 100
if zoom in CC.ZOOMS:
pretty_zoom = '%i' % zoom_percent + '%'
else:
pretty_zoom = '%.2f' % zoom_percent + '%'
return pretty_zoom
def DeletePath( path ):
if HC.options[ 'delete_to_recycle_bin' ] == True:
HydrusData.RecyclePath( path )
else:
HydrusData.DeletePath( path )
def GetMediasTagCount( pool, tag_service_key = CC.COMBINED_TAG_SERVICE_KEY, collapse_siblings = False ):
siblings_manager = HydrusGlobals.client_controller.GetManager( 'tag_siblings' )
tags_managers = []
for media in pool:
if media.IsCollection():
tags_managers.extend( media.GetSingletonsTagsManagers() )
else:
tags_managers.append( media.GetTagsManager() )
current_tags_to_count = collections.Counter()
deleted_tags_to_count = collections.Counter()
pending_tags_to_count = collections.Counter()
petitioned_tags_to_count = collections.Counter()
for tags_manager in tags_managers:
statuses_to_tags = tags_manager.GetStatusesToTags( tag_service_key )
if collapse_siblings:
statuses_to_tags = siblings_manager.CollapseStatusesToTags( statuses_to_tags )
current_tags_to_count.update( statuses_to_tags[ HC.CURRENT ] )
deleted_tags_to_count.update( statuses_to_tags[ HC.DELETED ] )
pending_tags_to_count.update( statuses_to_tags[ HC.PENDING ] )
petitioned_tags_to_count.update( statuses_to_tags[ HC.PETITIONED ] )
return ( current_tags_to_count, deleted_tags_to_count, pending_tags_to_count, petitioned_tags_to_count )
def ShowExceptionClient( e ):
job_key = HydrusThreading.JobKey()
if isinstance( e, HydrusExceptions.ShutdownException ):
return
elif isinstance( e, HydrusExceptions.DBException ):
( text, caller_traceback, db_traceback ) = e.args
job_key.SetVariable( 'popup_title', 'Database Error!' )
job_key.SetVariable( 'popup_text_1', text )
job_key.SetVariable( 'popup_caller_traceback', caller_traceback )
job_key.SetVariable( 'popup_db_traceback', db_traceback )
else:
( etype, value, tb ) = sys.exc_info()
if etype is None:
etype = type( e )
value = HydrusData.ToUnicode( e )
trace = ''.join( traceback.format_stack() )
else: trace = ''.join( traceback.format_exception( etype, value, tb ) )
if etype == wx.PyDeadObjectError:
print( 'Got a PyDeadObjectError, which can probably be ignored, but here it is anyway:' )
print( HydrusData.ToUnicode( value ) )
print( trace )
return
if hasattr( etype, '__name__' ): title = HydrusData.ToUnicode( etype.__name__ )
else: title = HydrusData.ToUnicode( etype )
job_key.SetVariable( 'popup_title', title )
job_key.SetVariable( 'popup_text_1', HydrusData.ToUnicode( value ) )
job_key.SetVariable( 'popup_traceback', trace )
text = job_key.ToString()
print( '' )
print( 'The following exception occured at ' + HydrusData.ConvertTimestampToPrettyTime( HydrusData.GetNow() ) + ':' )
try: print( text )
except: print( repr( text ) )
sys.stdout.flush()
sys.stderr.flush()
HydrusGlobals.client_controller.pub( 'message', job_key )
time.sleep( 1 )
def ShowTextClient( text ):
job_key = HydrusThreading.JobKey()
job_key.SetVariable( 'popup_text_1', HydrusData.ToUnicode( text ) )
text = job_key.ToString()
try: print( text )
except: print( repr( text ) )
HydrusGlobals.client_controller.pub( 'message', job_key )
class Booru( HydrusData.HydrusYAMLBase ):
yaml_tag = u'!Booru'
def __init__( self, name, search_url, search_separator, advance_by_page_num, thumb_classname, image_id, image_data, tag_classnames_to_namespaces ):
self._name = name
self._search_url = search_url
self._search_separator = search_separator
self._advance_by_page_num = advance_by_page_num
self._thumb_classname = thumb_classname
self._image_id = image_id
self._image_data = image_data
self._tag_classnames_to_namespaces = tag_classnames_to_namespaces
def GetData( self ): return ( self._search_url, self._search_separator, self._advance_by_page_num, self._thumb_classname, self._image_id, self._image_data, self._tag_classnames_to_namespaces )
def GetGalleryParsingInfo( self ): return ( self._search_url, self._advance_by_page_num, self._search_separator, self._thumb_classname )
def GetName( self ): return self._name
def GetNamespaces( self ): return self._tag_classnames_to_namespaces.values()
sqlite3.register_adapter( Booru, yaml.safe_dump )
class ClientOptions( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_CLIENT_OPTIONS
SERIALISABLE_VERSION = 1
def __init__( self ):
HydrusSerialisable.SerialisableBase.__init__( self )
self._dictionary = HydrusSerialisable.SerialisableDictionary()
self._lock = threading.Lock()
self._InitialiseDefaults()
def _GetSerialisableInfo( self ):
with self._lock:
serialisable_info = self._dictionary.GetSerialisableTuple()
return serialisable_info
def _InitialiseDefaults( self ):
self._dictionary[ 'default_import_tag_options' ] = HydrusSerialisable.SerialisableDictionary()
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
self._dictionary = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_info )
def ClearDefaultImportTagOptions( self ):
with self._lock:
self._dictionary[ 'default_import_tag_options' ] = HydrusSerialisable.SerialisableDictionary()
def GetDefaultImportTagOptions( self, gallery_identifier = None ):
with self._lock:
default_import_tag_options = self._dictionary[ 'default_import_tag_options' ]
if gallery_identifier is None:
return default_import_tag_options
else:
if gallery_identifier in default_import_tag_options:
import_tag_options = default_import_tag_options[ gallery_identifier ]
else:
default_booru_gallery_identifier = ClientDownloading.GalleryIdentifier( HC.SITE_TYPE_BOORU )
default_hentai_foundry_gallery_identifier = ClientDownloading.GalleryIdentifier( HC.SITE_TYPE_HENTAI_FOUNDRY )
default_pixiv_gallery_identifier = ClientDownloading.GalleryIdentifier( HC.SITE_TYPE_PIXIV )
default_gallery_identifier = ClientDownloading.GalleryIdentifier( HC.SITE_TYPE_DEFAULT )
guidance_import_tag_options = None
site_type = gallery_identifier.GetSiteType()
if site_type == HC.SITE_TYPE_BOORU and default_booru_gallery_identifier in default_import_tag_options:
guidance_import_tag_options = default_import_tag_options[ default_booru_gallery_identifier ]
elif site_type in ( HC.SITE_TYPE_HENTAI_FOUNDRY_ARTIST, HC.SITE_TYPE_HENTAI_FOUNDRY_TAGS ) and default_hentai_foundry_gallery_identifier in default_import_tag_options:
guidance_import_tag_options = default_import_tag_options[ default_hentai_foundry_gallery_identifier ]
elif site_type in ( HC.SITE_TYPE_PIXIV_ARTIST_ID, HC.SITE_TYPE_PIXIV_TAG ) and default_pixiv_gallery_identifier in default_import_tag_options:
guidance_import_tag_options = default_import_tag_options[ default_pixiv_gallery_identifier ]
elif default_gallery_identifier in default_import_tag_options:
guidance_import_tag_options = default_import_tag_options[ default_gallery_identifier ]
service_keys_to_namespaces = {}
service_keys_to_explicit_tags = {}
if guidance_import_tag_options is not None:
( namespaces, search_value ) = ClientDefaults.GetDefaultNamespacesAndSearchValue( gallery_identifier )
guidance_service_keys_to_namespaces = guidance_import_tag_options.GetServiceKeysToNamespaces()
for ( service_key, guidance_namespaces ) in guidance_service_keys_to_namespaces.items():
if 'all namespaces' in guidance_namespaces:
service_keys_to_namespaces[ service_key ] = namespaces
else:
service_keys_to_namespaces[ service_key ] = [ namespace for namespace in namespaces if namespace in guidance_namespaces ]
service_keys_to_explicit_tags = guidance_import_tag_options.GetServiceKeysToExplicitTags()
import_tag_options = ImportTagOptions( service_keys_to_namespaces = service_keys_to_namespaces, service_keys_to_explicit_tags = service_keys_to_explicit_tags )
return import_tag_options
def SetDefaultImportTagOptions( self, gallery_identifier, import_tag_options ):
with self._lock:
self._dictionary[ 'default_import_tag_options' ][ gallery_identifier ] = import_tag_options
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_CLIENT_OPTIONS ] = ClientOptions
class Credentials( HydrusData.HydrusYAMLBase ):
yaml_tag = u'!Credentials'
def __init__( self, host, port, access_key = None ):
HydrusData.HydrusYAMLBase.__init__( self )
if host == 'localhost': host = '127.0.0.1'
self._host = host
self._port = port
self._access_key = access_key
def __eq__( self, other ): return self.__hash__() == other.__hash__()
def __hash__( self ): return ( self._host, self._port, self._access_key ).__hash__()
def __ne__( self, other ): return self.__hash__() != other.__hash__()
def __repr__( self ): return 'Credentials: ' + HydrusData.ToUnicode( ( self._host, self._port, self._access_key.encode( 'hex' ) ) )
def GetAccessKey( self ): return self._access_key
def GetAddress( self ): return ( self._host, self._port )
def GetConnectionString( self ):
connection_string = ''
if self.HasAccessKey(): connection_string += self._access_key.encode( 'hex' ) + '@'
connection_string += self._host + ':' + str( self._port )
return connection_string
def HasAccessKey( self ): return self._access_key is not None and self._access_key is not ''
def SetAccessKey( self, access_key ): self._access_key = access_key
class FileQueryResult( object ):
def __init__( self, media_results ):
self._hashes_to_media_results = { media_result.GetHash() : media_result for media_result in media_results }
self._hashes_ordered = [ media_result.GetHash() for media_result in media_results ]
self._hashes = set( self._hashes_ordered )
HydrusGlobals.client_controller.sub( self, 'ProcessContentUpdates', 'content_updates_data' )
HydrusGlobals.client_controller.sub( self, 'ProcessServiceUpdates', 'service_updates_data' )
def __iter__( self ):
for hash in self._hashes_ordered: yield self._hashes_to_media_results[ hash ]
def __len__( self ): return len( self._hashes_ordered )
def _Remove( self, hashes ):
for hash in hashes:
if hash in self._hashes_to_media_results:
del self._hashes_to_media_results[ hash ]
self._hashes_ordered.remove( hash )
self._hashes.difference_update( hashes )
def AddMediaResults( self, media_results ):
for media_result in media_results:
hash = media_result.GetHash()
if hash in self._hashes: continue # this is actually important, as sometimes we don't want the media result overwritten
self._hashes_to_media_results[ hash ] = media_result
self._hashes_ordered.append( hash )
self._hashes.add( hash )
def GetHashes( self ): return self._hashes
def GetMediaResult( self, hash ): return self._hashes_to_media_results[ hash ]
def GetMediaResults( self ): return [ self._hashes_to_media_results[ hash ] for hash in self._hashes_ordered ]
def ProcessContentUpdates( self, service_keys_to_content_updates ):
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
for content_update in content_updates:
hashes = content_update.GetHashes()
if len( hashes ) > 0:
for hash in self._hashes.intersection( hashes ):
media_result = self._hashes_to_media_results[ hash ]
media_result.ProcessContentUpdate( service_key, content_update )
def ProcessServiceUpdates( self, service_keys_to_service_updates ):
for ( service_key, service_updates ) in service_keys_to_service_updates.items():
for service_update in service_updates:
( action, row ) = service_update.ToTuple()
if action == HC.SERVICE_UPDATE_DELETE_PENDING:
for media_result in self._hashes_to_media_results.values(): media_result.DeletePending( service_key )
elif action == HC.SERVICE_UPDATE_RESET:
for media_result in self._hashes_to_media_results.values(): media_result.ResetService( service_key )
class FileSearchContext( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEARCH_CONTEXT
SERIALISABLE_VERSION = 1
def __init__( self, file_service_key = CC.COMBINED_FILE_SERVICE_KEY, tag_service_key = CC.COMBINED_TAG_SERVICE_KEY, include_current_tags = True, include_pending_tags = True, predicates = None ):
if predicates is None: predicates = []
self._file_service_key = file_service_key
self._tag_service_key = tag_service_key
self._include_current_tags = include_current_tags
self._include_pending_tags = include_pending_tags
self._predicates = predicates
self._search_complete = False
self._InitialiseTemporaryVariables()
def _GetSerialisableInfo( self ):
serialisable_predicates = [ predicate.GetSerialisableTuple() for predicate in self._predicates ]
return ( self._file_service_key.encode( 'hex' ), self._tag_service_key.encode( 'hex' ), self._include_current_tags, self._include_pending_tags, serialisable_predicates, self._search_complete )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( file_service_key, tag_service_key, self._include_current_tags, self._include_pending_tags, serialisable_predicates, self._search_complete ) = serialisable_info
self._file_service_key = file_service_key.decode( 'hex' )
self._tag_service_key = tag_service_key.decode( 'hex' )
self._predicates = [ HydrusSerialisable.CreateFromSerialisableTuple( pred_tuple ) for pred_tuple in serialisable_predicates ]
self._InitialiseTemporaryVariables()
def _InitialiseTemporaryVariables( self ):
system_predicates = [ predicate for predicate in self._predicates if predicate.GetType() in HC.SYSTEM_PREDICATES ]
self._system_predicates = FileSystemPredicates( system_predicates )
tag_predicates = [ predicate for predicate in self._predicates if predicate.GetType() == HC.PREDICATE_TYPE_TAG ]
self._tags_to_include = []
self._tags_to_exclude = []
for predicate in tag_predicates:
tag = predicate.GetValue()
if predicate.GetInclusive(): self._tags_to_include.append( tag )
else: self._tags_to_exclude.append( tag )
namespace_predicates = [ predicate for predicate in self._predicates if predicate.GetType() == HC.PREDICATE_TYPE_NAMESPACE ]
self._namespaces_to_include = []
self._namespaces_to_exclude = []
for predicate in namespace_predicates:
namespace = predicate.GetValue()
if predicate.GetInclusive(): self._namespaces_to_include.append( namespace )
else: self._namespaces_to_exclude.append( namespace )
wildcard_predicates = [ predicate for predicate in self._predicates if predicate.GetType() == HC.PREDICATE_TYPE_WILDCARD ]
self._wildcards_to_include = []
self._wildcards_to_exclude = []
for predicate in wildcard_predicates:
wildcard = predicate.GetValue()
if predicate.GetInclusive(): self._wildcards_to_include.append( wildcard )
else: self._wildcards_to_exclude.append( wildcard )
def GetFileServiceKey( self ): return self._file_service_key
def GetNamespacesToExclude( self ): return self._namespaces_to_exclude
def GetNamespacesToInclude( self ): return self._namespaces_to_include
def GetPredicates( self ): return self._predicates
def GetSystemPredicates( self ): return self._system_predicates
def GetTagServiceKey( self ): return self._tag_service_key
def GetTagsToExclude( self ): return self._tags_to_exclude
def GetTagsToInclude( self ): return self._tags_to_include
def GetWildcardsToExclude( self ): return self._wildcards_to_exclude
def GetWildcardsToInclude( self ): return self._wildcards_to_include
def IncludeCurrentTags( self ): return self._include_current_tags
def IncludePendingTags( self ): return self._include_pending_tags
def IsComplete( self ): return self._search_complete
def SetComplete( self ): self._search_complete = True
def SetPredicates( self, predicates ):
self._predicates = predicates
self._InitialiseTemporaryVariables()
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEARCH_CONTEXT ] = FileSearchContext
class FileSystemPredicates( object ):
def __init__( self, system_predicates ):
self._inbox = False
self._archive = False
self._local = False
self._not_local = False
self._common_info = {}
self._limit = None
self._similar_to = None
self._file_services_to_include_current = []
self._file_services_to_include_pending = []
self._file_services_to_exclude_current = []
self._file_services_to_exclude_pending = []
self._ratings_predicates = []
for predicate in system_predicates:
predicate_type = predicate.GetType()
value = predicate.GetValue()
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_INBOX: self._inbox = True
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_ARCHIVE: self._archive = True
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_LOCAL: self._local = True
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_NOT_LOCAL: self._not_local = True
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_HASH:
hash = value
self._common_info[ 'hash' ] = hash
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_AGE:
( operator, years, months, days, hours ) = value
age = ( ( ( ( ( ( ( years * 12 ) + months ) * 30 ) + days ) * 24 ) + hours ) * 3600 )
now = HydrusData.GetNow()
# this is backwards because we are talking about age, not timestamp
if operator == '<': self._common_info[ 'min_timestamp' ] = now - age
elif operator == '>': self._common_info[ 'max_timestamp' ] = now - age
elif operator == u'\u2248':
self._common_info[ 'min_timestamp' ] = now - int( age * 1.15 )
self._common_info[ 'max_timestamp' ] = now - int( age * 0.85 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_MIME:
mimes = value
if type( mimes ) == int: mimes = ( mimes, )
self._common_info[ 'mimes' ] = mimes
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_DURATION:
( operator, duration ) = value
if operator == '<': self._common_info[ 'max_duration' ] = duration
elif operator == '>': self._common_info[ 'min_duration' ] = duration
elif operator == '=': self._common_info[ 'duration' ] = duration
elif operator == u'\u2248':
if duration == 0: self._common_info[ 'duration' ] = 0
else:
self._common_info[ 'min_duration' ] = int( duration * 0.85 )
self._common_info[ 'max_duration' ] = int( duration * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_RATING:
( operator, value, service_key ) = value
self._ratings_predicates.append( ( operator, value, service_key ) )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_RATIO:
( operator, ratio_width, ratio_height ) = value
if operator == '=': self._common_info[ 'ratio' ] = ( ratio_width, ratio_height )
elif operator == u'\u2248':
self._common_info[ 'min_ratio' ] = ( ratio_width * 0.85, ratio_height )
self._common_info[ 'max_ratio' ] = ( ratio_width * 1.15, ratio_height )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIZE:
( operator, size, unit ) = value
size = size * unit
if operator == '<': self._common_info[ 'max_size' ] = size
elif operator == '>': self._common_info[ 'min_size' ] = size
elif operator == '=': self._common_info[ 'size' ] = size
elif operator == u'\u2248':
self._common_info[ 'min_size' ] = int( size * 0.85 )
self._common_info[ 'max_size' ] = int( size * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_TAGS:
( operator, num_tags ) = value
if operator == '<': self._common_info[ 'max_num_tags' ] = num_tags
elif operator == '=': self._common_info[ 'num_tags' ] = num_tags
elif operator == '>': self._common_info[ 'min_num_tags' ] = num_tags
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_WIDTH:
( operator, width ) = value
if operator == '<': self._common_info[ 'max_width' ] = width
elif operator == '>': self._common_info[ 'min_width' ] = width
elif operator == '=': self._common_info[ 'width' ] = width
elif operator == u'\u2248':
if width == 0: self._common_info[ 'width' ] = 0
else:
self._common_info[ 'min_width' ] = int( width * 0.85 )
self._common_info[ 'max_width' ] = int( width * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_PIXELS:
( operator, num_pixels, unit ) = value
num_pixels = num_pixels * unit
if operator == '<': self._common_info[ 'max_num_pixels' ] = num_pixels
elif operator == '>': self._common_info[ 'min_num_pixels' ] = num_pixels
elif operator == '=': self._common_info[ 'num_pixels' ] = num_pixels
elif operator == u'\u2248':
self._common_info[ 'min_num_pixels' ] = int( num_pixels * 0.85 )
self._common_info[ 'max_num_pixels' ] = int( num_pixels * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_HEIGHT:
( operator, height ) = value
if operator == '<': self._common_info[ 'max_height' ] = height
elif operator == '>': self._common_info[ 'min_height' ] = height
elif operator == '=': self._common_info[ 'height' ] = height
elif operator == u'\u2248':
if height == 0: self._common_info[ 'height' ] = 0
else:
self._common_info[ 'min_height' ] = int( height * 0.85 )
self._common_info[ 'max_height' ] = int( height * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_WORDS:
( operator, num_words ) = value
if operator == '<': self._common_info[ 'max_num_words' ] = num_words
elif operator == '>': self._common_info[ 'min_num_words' ] = num_words
elif operator == '=': self._common_info[ 'num_words' ] = num_words
elif operator == u'\u2248':
if num_words == 0: self._common_info[ 'num_words' ] = 0
else:
self._common_info[ 'min_num_words' ] = int( num_words * 0.85 )
self._common_info[ 'max_num_words' ] = int( num_words * 1.15 )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_LIMIT:
limit = value
self._limit = limit
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_FILE_SERVICE:
( operator, current_or_pending, service_key ) = value
if operator == True:
if current_or_pending == HC.CURRENT: self._file_services_to_include_current.append( service_key )
else: self._file_services_to_include_pending.append( service_key )
else:
if current_or_pending == HC.CURRENT: self._file_services_to_exclude_current.append( service_key )
else: self._file_services_to_exclude_pending.append( service_key )
if predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
( hash, max_hamming ) = value
self._similar_to = ( hash, max_hamming )
def GetFileServiceInfo( self ): return ( self._file_services_to_include_current, self._file_services_to_include_pending, self._file_services_to_exclude_current, self._file_services_to_exclude_pending )
def GetSimpleInfo( self ): return self._common_info
def GetLimit( self ): return self._limit
def GetRatingsPredicates( self ): return self._ratings_predicates
def GetSimilarTo( self ): return self._similar_to
def HasSimilarTo( self ): return self._similar_to is not None
def MustBeArchive( self ): return self._archive
def MustBeInbox( self ): return self._inbox
def MustBeLocal( self ): return self._local
def MustNotBeLocal( self ): return self._not_local
class Imageboard( HydrusData.HydrusYAMLBase ):
yaml_tag = u'!Imageboard'
def __init__( self, name, post_url, flood_time, form_fields, restrictions ):
self._name = name
self._post_url = post_url
self._flood_time = flood_time
self._form_fields = form_fields
self._restrictions = restrictions
def IsOkToPost( self, media_result ):
( hash, inbox, size, mime, timestamp, width, height, duration, num_frames, num_words, tags_manager, locations_manager, local_ratings, remote_ratings ) = media_result.ToTuple()
if CC.RESTRICTION_MIN_RESOLUTION in self._restrictions:
( min_width, min_height ) = self._restrictions[ CC.RESTRICTION_MIN_RESOLUTION ]
if width < min_width or height < min_height: return False
if CC.RESTRICTION_MAX_RESOLUTION in self._restrictions:
( max_width, max_height ) = self._restrictions[ CC.RESTRICTION_MAX_RESOLUTION ]
if width > max_width or height > max_height: return False
if CC.RESTRICTION_MAX_FILE_SIZE in self._restrictions and size > self._restrictions[ CC.RESTRICTION_MAX_FILE_SIZE ]: return False
if CC.RESTRICTION_ALLOWED_MIMES in self._restrictions and mime not in self._restrictions[ CC.RESTRICTION_ALLOWED_MIMES ]: return False
return True
def GetBoardInfo( self ): return ( self._post_url, self._flood_time, self._form_fields, self._restrictions )
def GetName( self ): return self._name
sqlite3.register_adapter( Imageboard, yaml.safe_dump )
class ImportFileOptions( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_IMPORT_FILE_OPTIONS
SERIALISABLE_VERSION = 1
def __init__( self, automatic_archive = None, exclude_deleted = None, min_size = None, min_resolution = None ):
HydrusSerialisable.SerialisableBase.__init__( self )
self._automatic_archive = automatic_archive
self._exclude_deleted = exclude_deleted
self._min_size = min_size
self._min_resolution = min_resolution
def _GetSerialisableInfo( self ):
return ( self._automatic_archive, self._exclude_deleted, self._min_size, self._min_resolution )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( self._automatic_archive, self._exclude_deleted, self._min_size, self._min_resolution ) = serialisable_info
def FileIsValid( self, size, resolution = None ):
if self._min_size is not None and size < self._min_size:
return False
if resolution is not None and self._min_resolution is not None:
( x, y ) = resolution
( min_x, min_y ) = self._min_resolution
if x < min_x or y < min_y:
return False
return True
def GetAutomaticArchive( self ):
return self._automatic_archive
def GetExcludeDeleted( self ):
return self._exclude_deleted
def ToTuple( self ):
return ( self._automatic_archive, self._exclude_deleted, self._min_size, self._min_resolution )
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_IMPORT_FILE_OPTIONS ] = ImportFileOptions
class ImportTagOptions( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_IMPORT_TAG_OPTIONS
SERIALISABLE_VERSION = 2
def __init__( self, service_keys_to_namespaces = None, service_keys_to_explicit_tags = None ):
HydrusSerialisable.SerialisableBase.__init__( self )
if service_keys_to_namespaces is None:
service_keys_to_namespaces = {}
if service_keys_to_explicit_tags is None:
service_keys_to_explicit_tags = {}
self._service_keys_to_namespaces = service_keys_to_namespaces
self._service_keys_to_explicit_tags = service_keys_to_explicit_tags
def _GetSerialisableInfo( self ):
safe_service_keys_to_namespaces = { service_key.encode( 'hex' ) : list( namespaces ) for ( service_key, namespaces ) in self._service_keys_to_namespaces.items() }
safe_service_keys_to_explicit_tags = { service_key.encode( 'hex' ) : list( tags ) for ( service_key, tags ) in self._service_keys_to_explicit_tags.items() }
return ( safe_service_keys_to_namespaces, safe_service_keys_to_explicit_tags )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( safe_service_keys_to_namespaces, safe_service_keys_to_explicit_tags ) = serialisable_info
self._service_keys_to_namespaces = { service_key.decode( 'hex' ) : set( namespaces ) for ( service_key, namespaces ) in safe_service_keys_to_namespaces.items() }
self._service_keys_to_explicit_tags = { service_key.decode( 'hex' ) : set( tags ) for ( service_key, tags ) in safe_service_keys_to_explicit_tags.items() }
def _UpdateSerialisableInfo( self, version, old_serialisable_info ):
if version == 1:
safe_service_keys_to_namespaces = old_serialisable_info
safe_service_keys_to_explicit_tags = {}
new_serialisable_info = ( safe_service_keys_to_namespaces, safe_service_keys_to_explicit_tags )
return ( 2, new_serialisable_info )
def GetServiceKeysToExplicitTags( self ):
return dict( self._service_keys_to_explicit_tags )
def GetServiceKeysToNamespaces( self ):
return dict( self._service_keys_to_namespaces )
def GetServiceKeysToContentUpdates( self, hash, tags ):
tags = [ tag for tag in tags if tag is not None ]
service_keys_to_tags = collections.defaultdict( set )
siblings_manager = HydrusGlobals.client_controller.GetManager( 'tag_siblings' )
parents_manager = HydrusGlobals.client_controller.GetManager( 'tag_parents' )
for ( service_key, namespaces ) in self._service_keys_to_namespaces.items():
tags_to_add_here = []
if len( namespaces ) > 0:
for namespace in namespaces:
if namespace == '': tags_to_add_here.extend( [ tag for tag in tags if not ':' in tag ] )
else: tags_to_add_here.extend( [ tag for tag in tags if tag.startswith( namespace + ':' ) ] )
tags_to_add_here = HydrusTags.CleanTags( tags_to_add_here )
if len( tags_to_add_here ) > 0:
tags_to_add_here = siblings_manager.CollapseTags( tags_to_add_here )
tags_to_add_here = parents_manager.ExpandTags( service_key, tags_to_add_here )
service_keys_to_tags[ service_key ].update( tags_to_add_here )
for ( service_key, explicit_tags ) in self._service_keys_to_explicit_tags.items():
tags_to_add_here = HydrusTags.CleanTags( explicit_tags )
if len( tags_to_add_here ) > 0:
tags_to_add_here = siblings_manager.CollapseTags( tags_to_add_here )
tags_to_add_here = parents_manager.ExpandTags( service_key, tags_to_add_here )
service_keys_to_tags[ service_key ].update( tags_to_add_here )
service_keys_to_content_updates = ConvertServiceKeysToTagsToServiceKeysToContentUpdates( { hash }, service_keys_to_tags )
return service_keys_to_content_updates
def ShouldFetchTags( self ):
i_am_interested_in_namespaces = len( self._service_keys_to_namespaces ) > 0
return i_am_interested_in_namespaces
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_IMPORT_TAG_OPTIONS ] = ImportTagOptions
class Predicate( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_PREDICATE
SERIALISABLE_VERSION = 1
def __init__( self, predicate_type = None, value = None, inclusive = True, counts = None ):
if counts is None: counts = {}
if type( value ) == list:
value = tuple( value )
self._predicate_type = predicate_type
self._value = value
self._inclusive = inclusive
self._counts = {}
self._counts[ HC.CURRENT ] = 0
self._counts[ HC.PENDING ] = 0
for ( current_or_pending, count ) in counts.items(): self.AddToCount( current_or_pending, count )
def __eq__( self, other ):
return self.__hash__() == other.__hash__()
def __hash__( self ):
return ( self._predicate_type, self._value ).__hash__()
def __ne__( self, other ):
return self.__hash__() != other.__hash__()
def __repr__( self ):
return 'Predicate: ' + HydrusData.ToUnicode( ( self._predicate_type, self._value, self._counts ) )
def _GetSerialisableInfo( self ):
if self._predicate_type in ( HC.PREDICATE_TYPE_SYSTEM_RATING, HC.PREDICATE_TYPE_SYSTEM_FILE_SERVICE ):
( operator, value, service_key ) = self._value
serialisable_value = ( operator, value, service_key.encode( 'hex' ) )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
( hash, max_hamming ) = self._value
serialisable_value = ( hash.encode( 'hex' ), max_hamming )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_HASH:
hash = self._value
serialisable_value = hash.encode( 'hex' )
else:
serialisable_value = self._value
return ( self._predicate_type, serialisable_value, self._inclusive )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( self._predicate_type, serialisable_value, self._inclusive ) = serialisable_info
if self._predicate_type in ( HC.PREDICATE_TYPE_SYSTEM_RATING, HC.PREDICATE_TYPE_SYSTEM_FILE_SERVICE ):
( operator, value, service_key ) = serialisable_value
self._value = ( operator, value, service_key.decode( 'hex' ) )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
( serialisable_hash, max_hamming ) = serialisable_value
self._value = ( serialisable_hash.decode( 'hex' ), max_hamming )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_HASH:
self._value = serialisable_value.decode( 'hex' )
else:
self._value = serialisable_value
if type( self._value ) == list:
self._value = tuple( self._value )
def AddToCount( self, current_or_pending, count ): self._counts[ current_or_pending ] += count
def GetCopy( self ): return Predicate( self._predicate_type, self._value, self._inclusive, self._counts )
def GetCountlessCopy( self ): return Predicate( self._predicate_type, self._value, self._inclusive )
def GetCount( self, current_or_pending = None ):
if current_or_pending is None: return sum( self._counts.values() )
else: return self._counts[ current_or_pending ]
def GetInclusive( self ):
# patch from an upgrade mess-up ~v144
if not hasattr( self, '_inclusive' ):
if self._predicate_type not in HC.SYSTEM_PREDICATES:
( operator, value ) = self._value
self._value = value
self._inclusive = operator == '+'
else: self._inclusive = True
return self._inclusive
def GetInfo( self ): return ( self._predicate_type, self._value, self._inclusive )
def GetType( self ): return self._predicate_type
def GetUnicode( self, with_count = True ):
count_text = u''
if with_count:
if self._counts[ HC.CURRENT ] > 0: count_text += u' (' + HydrusData.ConvertIntToPrettyString( self._counts[ HC.CURRENT ] ) + u')'
if self._counts[ HC.PENDING ] > 0: count_text += u' (+' + HydrusData.ConvertIntToPrettyString( self._counts[ HC.PENDING ] ) + u')'
if self._predicate_type in HC.SYSTEM_PREDICATES:
if self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_EVERYTHING: base = u'system:everything'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_INBOX: base = u'system:inbox'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_ARCHIVE: base = u'system:archive'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_UNTAGGED: base = u'system:untagged'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_LOCAL: base = u'system:local'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_NOT_LOCAL: base = u'system:not local'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_DIMENSIONS: base = u'system:dimensions'
elif self._predicate_type in ( HC.PREDICATE_TYPE_SYSTEM_NUM_TAGS, HC.PREDICATE_TYPE_SYSTEM_WIDTH, HC.PREDICATE_TYPE_SYSTEM_HEIGHT, HC.PREDICATE_TYPE_SYSTEM_DURATION, HC.PREDICATE_TYPE_SYSTEM_NUM_WORDS ):
if self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_TAGS: base = u'system:number of tags'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_WIDTH: base = u'system:width'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_HEIGHT: base = u'system:height'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_DURATION: base = u'system:duration'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_WORDS: base = u'system:number of words'
if self._value is not None:
( operator, value ) = self._value
base += u' ' + operator + u' ' + HydrusData.ConvertIntToPrettyString( value )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_RATIO:
base = u'system:ratio'
if self._value is not None:
( operator, ratio_width, ratio_height ) = self._value
base += u' ' + operator + u' ' + str( ratio_width ) + u':' + str( ratio_height )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIZE:
base = u'system:size'
if self._value is not None:
( operator, size, unit ) = self._value
base += u' ' + operator + u' ' + str( size ) + HydrusData.ConvertIntToUnit( unit )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_LIMIT:
base = u'system:limit'
if self._value is not None:
value = self._value
base += u' is ' + HydrusData.ConvertIntToPrettyString( value )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_AGE:
base = u'system:age'
if self._value is not None:
( operator, years, months, days, hours ) = self._value
base += u' ' + operator + u' ' + str( years ) + u'y' + str( months ) + u'm' + str( days ) + u'd' + str( hours ) + u'h'
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_NUM_PIXELS:
base = u'system:num_pixels'
if self._value is not None:
( operator, num_pixels, unit ) = self._value
base += u' ' + operator + u' ' + str( num_pixels ) + ' ' + HydrusData.ConvertIntToPixels( unit )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_HASH:
base = u'system:hash'
if self._value is not None:
hash = self._value
base += u' is ' + hash.encode( 'hex' )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_MIME:
base = u'system:mime'
if self._value is not None:
mimes = self._value
if set( mimes ) == set( HC.SEARCHABLE_MIMES ):
mime_text = 'anything'
elif set( mimes ) == set( HC.SEARCHABLE_MIMES ).intersection( set( HC.APPLICATIONS ) ):
mime_text = 'application'
elif set( mimes ) == set( HC.SEARCHABLE_MIMES ).intersection( set( HC.AUDIO ) ):
mime_text = 'audio'
elif set( mimes ) == set( HC.SEARCHABLE_MIMES ).intersection( set( HC.IMAGES ) ):
mime_text = 'image'
elif set( mimes ) == set( HC.SEARCHABLE_MIMES ).intersection( set( HC.VIDEO ) ):
mime_text = 'video'
else:
mime_text = ', '.join( [ HC.mime_string_lookup[ mime ] for mime in mimes ] )
base += u' is ' + mime_text
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_RATING:
base = u'system:rating'
if self._value is not None:
( operator, value, service_key ) = self._value
service = HydrusGlobals.client_controller.GetServicesManager().GetService( service_key )
base += u' for ' + service.GetName() + u' ' + operator + u' ' + HydrusData.ToUnicode( value )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_SIMILAR_TO:
base = u'system:similar to'
if self._value is not None:
( hash, max_hamming ) = self._value
base += u' ' + hash.encode( 'hex' ) + u' using max hamming of ' + str( max_hamming )
elif self._predicate_type == HC.PREDICATE_TYPE_SYSTEM_FILE_SERVICE:
base = u'system:'
if self._value is None:
base += 'file service'
else:
( operator, current_or_pending, service_key ) = self._value
if operator == True: base += u'is'
else: base += u'is not'
if current_or_pending == HC.PENDING: base += u' pending to '
else: base += u' currently in '
service = HydrusGlobals.client_controller.GetServicesManager().GetService( service_key )
base += service.GetName()
base += count_text
elif self._predicate_type == HC.PREDICATE_TYPE_TAG:
tag = self._value
if not self._inclusive: base = u'-'
else: base = u''
base += tag
base += count_text
siblings_manager = HydrusGlobals.client_controller.GetManager( 'tag_siblings' )
sibling = siblings_manager.GetSibling( tag )
if sibling is not None: base += u' (will display as ' + sibling + ')'
elif self._predicate_type == HC.PREDICATE_TYPE_PARENT:
base = ' '
tag = self._value
base += tag
base += count_text
elif self._predicate_type == HC.PREDICATE_TYPE_NAMESPACE:
namespace = self._value
if not self._inclusive: base = u'-'
else: base = u''
base += namespace + u':*anything*'
elif self._predicate_type == HC.PREDICATE_TYPE_WILDCARD:
wildcard = self._value
if not self._inclusive: base = u'-'
else: base = u''
base += wildcard
return base
def GetValue( self ): return self._value
def SetInclusive( self, inclusive ): self._inclusive = inclusive
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_PREDICATE ] = Predicate
class Service( HydrusData.HydrusYAMLBase ):
yaml_tag = u'!Service'
def __init__( self, service_key, service_type, name, info ):
HydrusData.HydrusYAMLBase.__init__( self )
self._service_key = service_key
self._service_type = service_type
self._name = name
self._info = info
self._lock = threading.Lock()
HydrusGlobals.client_controller.sub( self, 'ProcessServiceUpdates', 'service_updates_data' )
def __hash__( self ): return self._service_key.__hash__()
def _RecordHydrusBandwidth( self, method, command, data_used ):
if ( self._service_type, method, command ) in HC.BANDWIDTH_CONSUMING_REQUESTS:
HydrusGlobals.client_controller.pub( 'service_updates_delayed', { self._service_key : [ HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_REQUEST_MADE, data_used ) ] } )
def _ReportSyncProcessingError( self, path, error_text ):
text = 'While synchronising ' + self._name + ', the expected update file ' + path + ', ' + error_text + '.'
text += os.linesep * 2
text += 'The service has been indefinitely paused.'
text += os.linesep * 2
text += 'This is a serious error. Unless you know what went wrong, you should contact the developer.'
HydrusData.ShowText( text )
service_updates = [ HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_PAUSE ) ]
service_keys_to_service_updates = { self._service_key : service_updates }
self.ProcessServiceUpdates( service_keys_to_service_updates )
HydrusGlobals.client_controller.Write( 'service_updates', service_keys_to_service_updates )
def CanDownload( self ):
return self._info[ 'account' ].HasPermission( HC.GET_DATA ) and not self.HasRecentError()
def CanDownloadUpdate( self ):
update_due = HydrusData.TimeHasPassed( self._info[ 'next_download_timestamp' ] + HC.UPDATE_DURATION + 1800 )
return self.CanDownload() and update_due and not self.IsPaused()
def CanProcessUpdate( self ):
update_is_downloaded = self._info[ 'next_download_timestamp' ] > self._info[ 'next_processing_timestamp' ]
it_is_time = HydrusData.TimeHasPassed( self._info[ 'next_processing_timestamp' ] + HC.UPDATE_DURATION + HC.options[ 'processing_phase' ] )
return update_is_downloaded and it_is_time and not self.IsPaused()
def CanUpload( self ): return self._info[ 'account' ].HasPermission( HC.POST_DATA ) and not self.HasRecentError()
def GetCredentials( self ):
host = self._info[ 'host' ]
port = self._info[ 'port' ]
if 'access_key' in self._info: access_key = self._info[ 'access_key' ]
else: access_key = None
credentials = Credentials( host, port, access_key )
return credentials
def GetInfo( self, key = None ):
if key is None: return self._info
else: return self._info[ key ]
def GetServiceKey( self ): return self._service_key
def GetName( self ): return self._name
def GetRecentErrorPending( self ):
if 'account' in self._info and self._info[ 'account' ].HasPermission( HC.GENERAL_ADMIN ): return HydrusData.ConvertTimestampToPrettyPending( self._info[ 'last_error' ] + 600 )
else: return HydrusData.ConvertTimestampToPrettyPending( self._info[ 'last_error' ] + 3600 * 4 )
def GetServiceType( self ): return self._service_type
def GetTimestamps( self ): return ( self._info[ 'first_timestamp' ], self._info[ 'next_download_timestamp' ], self._info[ 'next_processing_timestamp' ] )
def GetUpdateStatus( self ):
account = self._info[ 'account' ]
now = HydrusData.GetNow()
first_timestamp = self._info[ 'first_timestamp' ]
next_download_timestamp = self._info[ 'next_download_timestamp' ]
next_processing_timestamp = self._info[ 'next_processing_timestamp' ]
if first_timestamp is None:
num_updates = 0
num_updates_downloaded = 0
num_updates_processed = 0
else:
num_updates = ( now - first_timestamp ) / HC.UPDATE_DURATION
num_updates_downloaded = ( next_download_timestamp - first_timestamp ) / HC.UPDATE_DURATION
num_updates_processed = max( 0, ( next_processing_timestamp - first_timestamp ) / HC.UPDATE_DURATION )
downloaded_text = 'downloaded ' + HydrusData.ConvertValueRangeToPrettyString( num_updates_downloaded, num_updates )
processed_text = 'processed ' + HydrusData.ConvertValueRangeToPrettyString( num_updates_processed, num_updates )
if self.IsPaused() or not self._info[ 'account' ].HasPermission( HC.GET_DATA ): status = 'updates on hold'
else:
if self.CanDownloadUpdate(): status = 'downloaded up to ' + HydrusData.ConvertTimestampToPrettySync( self._info[ 'next_download_timestamp' ] )
elif self.CanProcessUpdate(): status = 'processed up to ' + HydrusData.ConvertTimestampToPrettySync( self._info[ 'next_processing_timestamp' ] )
elif self.HasRecentError(): status = 'due to a previous error, update is delayed - next check ' + self.GetRecentErrorPending()
else:
if HydrusData.TimeHasPassed( self._info[ 'next_download_timestamp' ] + HC.UPDATE_DURATION ):
status = 'next update will be downloaded soon'
else:
status = 'fully synchronised - next update ' + HydrusData.ConvertTimestampToPrettyPending( self._info[ 'next_download_timestamp' ] + HC.UPDATE_DURATION + 1800 )
return downloaded_text + ' - ' + processed_text + ' - ' + status
def HasRecentError( self ):
if 'account' in self._info and self._info[ 'account' ].HasPermission( HC.GENERAL_ADMIN ): return self._info[ 'last_error' ] + 900 > HydrusData.GetNow()
else: return self._info[ 'last_error' ] + 3600 * 4 > HydrusData.GetNow()
def IsInitialised( self ):
if self._service_type == HC.SERVER_ADMIN: return 'access_key' in self._info
else: return True
def IsPaused( self ): return self._info[ 'paused' ]
def ProcessServiceUpdates( self, service_keys_to_service_updates ):
for ( service_key, service_updates ) in service_keys_to_service_updates.items():
for service_update in service_updates:
if service_key == self._service_key:
( action, row ) = service_update.ToTuple()
if action == HC.SERVICE_UPDATE_ERROR: self._info[ 'last_error' ] = HydrusData.GetNow()
elif action == HC.SERVICE_UPDATE_RESET:
self._info[ 'last_error' ] = 0
if 'next_processing_timestamp' in self._info: self._info[ 'next_processing_timestamp' ] = 0
elif action == HC.SERVICE_UPDATE_ACCOUNT:
account = row
self._info[ 'account' ] = account
self._info[ 'last_error' ] = 0
elif action == HC.SERVICE_UPDATE_REQUEST_MADE:
num_bytes = row
if self._service_type == HC.LOCAL_BOORU:
self._info[ 'used_monthly_data' ] += num_bytes
self._info[ 'used_monthly_requests' ] += 1
else: self._info[ 'account' ].RequestMade( num_bytes )
elif action == HC.SERVICE_UPDATE_NEXT_DOWNLOAD_TIMESTAMP:
next_download_timestamp = row
if next_download_timestamp > self._info[ 'next_download_timestamp' ]:
if self._info[ 'first_timestamp' ] is None: self._info[ 'first_timestamp' ] = next_download_timestamp
self._info[ 'next_download_timestamp' ] = next_download_timestamp
elif action == HC.SERVICE_UPDATE_NEXT_PROCESSING_TIMESTAMP:
next_processing_timestamp = row
if next_processing_timestamp > self._info[ 'next_processing_timestamp' ]:
self._info[ 'next_processing_timestamp' ] = next_processing_timestamp
elif action == HC.SERVICE_UPDATE_PAUSE:
self._info[ 'paused' ] = True
def Request( self, method, command, request_args = None, request_headers = None, report_hooks = None, temp_path = None, return_cookies = False ):
if request_args is None: request_args = {}
if request_headers is None: request_headers = {}
if report_hooks is None: report_hooks = []
try:
credentials = self.GetCredentials()
if command in ( 'access_key', 'init', '' ):
pass
elif command in ( 'session_key', 'access_key_verification' ):
ClientNetworking.AddHydrusCredentialsToHeaders( credentials, request_headers )
else:
ClientNetworking.AddHydrusSessionKeyToHeaders( self._service_key, request_headers )
path = '/' + command
if method == HC.GET:
query = ClientNetworking.ConvertHydrusGETArgsToQuery( request_args )
body = ''
elif method == HC.POST:
query = ''
if command == 'file':
content_type = HC.APPLICATION_OCTET_STREAM
body = request_args[ 'file' ]
del request_args[ 'file' ]
else:
if isinstance( request_args, HydrusSerialisable.SerialisableDictionary ):
content_type = HC.APPLICATION_JSON
body = request_args.DumpToNetworkString()
else:
content_type = HC.APPLICATION_YAML
body = yaml.safe_dump( request_args )
request_headers[ 'Content-Type' ] = HC.mime_string_lookup[ content_type ]
if query != '': path_and_query = path + '?' + query
else: path_and_query = path
( host, port ) = credentials.GetAddress()
url = 'http://' + host + ':' + str( port ) + path_and_query
( response, size_of_response, response_headers, cookies ) = HydrusGlobals.client_controller.DoHTTP( method, url, request_headers, body, report_hooks = report_hooks, temp_path = temp_path, return_everything = True )
ClientNetworking.CheckHydrusVersion( self._service_key, self._service_type, response_headers )
if method == HC.GET: data_used = size_of_response
elif method == HC.POST: data_used = len( body )
self._RecordHydrusBandwidth( method, command, data_used )
if return_cookies: return ( response, cookies )
else: return response
except Exception as e:
if not isinstance( e, HydrusExceptions.ServerBusyException ):
if isinstance( e, HydrusExceptions.SessionException ):
session_manager = HydrusGlobals.client_controller.GetManager( 'hydrus_sessions' )
session_manager.DeleteSessionKey( self._service_key )
HydrusGlobals.client_controller.Write( 'service_updates', { self._service_key : [ HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_ERROR, HydrusData.ToUnicode( e ) ) ] } )
if isinstance( e, HydrusExceptions.PermissionException ):
if 'account' in self._info:
account_key = self._info[ 'account' ].GetAccountKey()
unknown_account = HydrusData.GetUnknownAccount( account_key )
else: unknown_account = HydrusData.GetUnknownAccount()
HydrusGlobals.client_controller.Write( 'service_updates', { self._service_key : [ HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_ACCOUNT, unknown_account ) ] } )
raise
def SetCredentials( self, credentials ):
( host, port ) = credentials.GetAddress()
self._info[ 'host' ] = host
self._info[ 'port' ] = port
if credentials.HasAccessKey(): self._info[ 'access_key' ] = credentials.GetAccessKey()
def Sync( self, only_when_idle = False, stop_time = None ):
job_key = HydrusThreading.JobKey( pausable = False, cancellable = True )
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
return
if self._info[ 'paused' ]:
return
if not self.CanDownloadUpdate() and not self.CanProcessUpdate():
return
num_updates_downloaded = 0
num_updates_processed = 0
total_content_weight_processed = 0
try:
options = HydrusGlobals.client_controller.GetOptions()
HydrusGlobals.client_controller.pub( 'splash_set_title_text', self._name )
job_key.SetVariable( 'popup_title', 'repository synchronisation - ' + self._name )
HydrusGlobals.client_controller.pub( 'message', job_key )
try:
while self.CanDownloadUpdate():
if only_when_idle:
if not HydrusGlobals.client_controller.CurrentlyIdle():
break
else:
if stop_time is not None and HydrusData.TimeHasPassed( stop_time ):
break
if options[ 'pause_repo_sync' ]:
break
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
break
if self._info[ 'first_timestamp' ] is None:
gauge_range = None
gauge_value = 0
update_index_string = 'initial update: '
else:
gauge_range = ( ( HydrusData.GetNow() - self._info[ 'first_timestamp' ] ) / HC.UPDATE_DURATION ) + 1
gauge_value = ( ( self._info[ 'next_download_timestamp' ] - self._info[ 'first_timestamp' ] ) / HC.UPDATE_DURATION ) + 1
update_index_string = 'update ' + HydrusData.ConvertValueRangeToPrettyString( gauge_value, gauge_range ) + ': '
subupdate_index_string = 'service update: '
HydrusGlobals.client_controller.pub( 'splash_set_title_text', self._name + ' - ' + update_index_string + subupdate_index_string )
HydrusGlobals.client_controller.pub( 'splash_set_status_text', 'downloading' )
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'downloading and parsing' )
job_key.SetVariable( 'popup_gauge_1', ( gauge_value, gauge_range ) )
service_update_package = self.Request( HC.GET, 'service_update_package', { 'begin' : self._info[ 'next_download_timestamp' ] } )
begin = service_update_package.GetBegin()
subindex_count = service_update_package.GetSubindexCount()
for subindex in range( subindex_count ):
path = ClientFiles.GetExpectedContentUpdatePackagePath( self._service_key, begin, subindex )
if os.path.exists( path ):
info = os.lstat( path )
size = info[6]
if size == 0:
os.remove( path )
if not os.path.exists( path ):
subupdate_index_string = 'content update ' + HydrusData.ConvertValueRangeToPrettyString( subindex + 1, subindex_count ) + ': '
HydrusGlobals.client_controller.pub( 'splash_set_title_text', self._name + ' - ' + update_index_string + subupdate_index_string )
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'downloading and parsing' )
content_update_package = self.Request( HC.GET, 'content_update_package', { 'begin' : begin, 'subindex' : subindex } )
obj_string = content_update_package.DumpToString()
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'saving to disk' )
with open( path, 'wb' ) as f: f.write( obj_string )
job_key.SetVariable( 'popup_text_1', update_index_string + 'committing' )
path = ClientFiles.GetExpectedServiceUpdatePackagePath( self._service_key, begin )
obj_string = service_update_package.DumpToString()
with open( path, 'wb' ) as f: f.write( obj_string )
service_updates = [ HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_NEXT_DOWNLOAD_TIMESTAMP, service_update_package.GetNextBegin() ) ]
service_keys_to_service_updates = { self._service_key : service_updates }
self.ProcessServiceUpdates( service_keys_to_service_updates )
HydrusGlobals.client_controller.Write( 'service_updates', service_keys_to_service_updates )
HydrusGlobals.client_controller.WaitUntilPubSubsEmpty()
num_updates_downloaded += 1
except Exception as e:
if 'Could not connect' in str( e ):
job_key.SetVariable( 'popup_text_1', 'Could not connect to service, will continue with processing.' )
time.sleep( 5 )
else:
raise e
while self.CanProcessUpdate():
if only_when_idle:
if not HydrusGlobals.client_controller.CurrentlyIdle():
break
else:
if stop_time is not None and HydrusData.TimeHasPassed( stop_time ):
break
if options[ 'pause_repo_sync' ]:
break
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
break
gauge_range = ( ( HydrusData.GetNow() - self._info[ 'first_timestamp' ] ) / HC.UPDATE_DURATION ) + 1
gauge_value = ( ( self._info[ 'next_processing_timestamp' ] - self._info[ 'first_timestamp' ] ) / HC.UPDATE_DURATION ) + 1
update_index_string = 'update ' + HydrusData.ConvertValueRangeToPrettyString( gauge_value, gauge_range ) + ': '
subupdate_index_string = 'service update: '
HydrusGlobals.client_controller.pub( 'splash_set_title_text', self._name + ' - ' + update_index_string + subupdate_index_string )
HydrusGlobals.client_controller.pub( 'splash_set_status_text', 'processing' )
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'loading from disk' )
job_key.SetVariable( 'popup_gauge_1', ( gauge_value, gauge_range ) )
path = ClientFiles.GetExpectedServiceUpdatePackagePath( self._service_key, self._info[ 'next_processing_timestamp' ] )
if not os.path.exists( path ):
self._ReportSyncProcessingError( path, 'was missing' )
return
with open( path, 'rb' ) as f: obj_string = f.read()
try:
service_update_package = HydrusSerialisable.CreateFromString( obj_string )
except:
self._ReportSyncProcessingError( path, 'did not parse' )
return
subindex_count = service_update_package.GetSubindexCount()
processing_went_ok = True
for subindex in range( subindex_count ):
if only_when_idle:
if not HydrusGlobals.client_controller.CurrentlyIdle():
break
else:
if stop_time is not None and HydrusData.TimeHasPassed( stop_time ):
break
if options[ 'pause_repo_sync' ]:
break
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
break
subupdate_index_string = 'content update ' + HydrusData.ConvertValueRangeToPrettyString( subindex + 1, subindex_count ) + ': '
path = ClientFiles.GetExpectedContentUpdatePackagePath( self._service_key, self._info[ 'next_processing_timestamp' ], subindex )
if not os.path.exists( path ):
self._ReportSyncProcessingError( path, 'was missing' )
return
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'loading from disk' )
with open( path, 'rb' ) as f: obj_string = f.read()
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'parsing' )
try:
content_update_package = HydrusSerialisable.CreateFromString( obj_string )
except:
self._ReportSyncProcessingError( path, 'did not parse' )
return
HydrusGlobals.client_controller.pub( 'splash_set_title_text', self._name + ' - ' + update_index_string + subupdate_index_string )
job_key.SetVariable( 'popup_text_1', update_index_string + subupdate_index_string + 'processing' )
( did_it_all, c_u_p_weight_processed ) = HydrusGlobals.client_controller.WriteSynchronous( 'content_update_package', self._service_key, content_update_package, job_key, only_when_idle )
total_content_weight_processed += c_u_p_weight_processed
if not did_it_all:
processing_went_ok = False
break
HydrusGlobals.client_controller.WaitUntilPubSubsEmpty()
if options[ 'pause_repo_sync' ]:
break
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
break
if processing_went_ok:
job_key.SetVariable( 'popup_text_2', 'committing service updates' )
service_updates = [ service_update for service_update in service_update_package.IterateServiceUpdates() ]
service_updates.append( HydrusData.ServiceUpdate( HC.SERVICE_UPDATE_NEXT_PROCESSING_TIMESTAMP, service_update_package.GetNextBegin() ) )
service_keys_to_service_updates = { self._service_key : service_updates }
self.ProcessServiceUpdates( service_keys_to_service_updates )
HydrusGlobals.client_controller.Write( 'service_updates', service_keys_to_service_updates )
HydrusGlobals.client_controller.pub( 'notify_new_pending' )
HydrusGlobals.client_controller.WaitUntilPubSubsEmpty()
job_key.SetVariable( 'popup_gauge_2', ( 0, 1 ) )
job_key.SetVariable( 'popup_text_2', '' )
num_updates_processed += 1
time.sleep( 0.1 )
job_key.DeleteVariable( 'popup_gauge_1' )
job_key.DeleteVariable( 'popup_text_2' )
job_key.DeleteVariable( 'popup_gauge_2' )
if self._service_type == HC.FILE_REPOSITORY and self.CanDownload():
HydrusGlobals.client_controller.pub( 'splash_set_status_text', 'reviewing thumbnails' )
job_key.SetVariable( 'popup_text_1', 'reviewing existing thumbnails' )
thumbnail_hashes_i_have = ClientFiles.GetAllThumbnailHashes()
job_key.SetVariable( 'popup_text_1', 'reviewing service thumbnails' )
thumbnail_hashes_i_should_have = HydrusGlobals.client_controller.Read( 'thumbnail_hashes_i_should_have', self._service_key )
thumbnail_hashes_i_need = thumbnail_hashes_i_should_have.difference( thumbnail_hashes_i_have )
if len( thumbnail_hashes_i_need ) > 0:
def SaveThumbnails( batch_of_thumbnails ):
job_key.SetVariable( 'popup_text_1', 'saving thumbnails to database' )
HydrusGlobals.client_controller.WriteSynchronous( 'thumbnails', batch_of_thumbnails )
HydrusGlobals.client_controller.pub( 'add_thumbnail_count', self._service_key, len( batch_of_thumbnails ) )
thumbnails = []
for ( i, hash ) in enumerate( thumbnail_hashes_i_need ):
if options[ 'pause_repo_sync' ]:
break
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
break
job_key.SetVariable( 'popup_text_1', 'downloading thumbnail ' + HydrusData.ConvertValueRangeToPrettyString( i, len( thumbnail_hashes_i_need ) ) )
job_key.SetVariable( 'popup_gauge_1', ( i, len( thumbnail_hashes_i_need ) ) )
request_args = { 'hash' : hash.encode( 'hex' ) }
thumbnail = self.Request( HC.GET, 'thumbnail', request_args = request_args )
thumbnails.append( ( hash, thumbnail ) )
if i % 50 == 0:
SaveThumbnails( thumbnails )
thumbnails = []
HydrusGlobals.client_controller.WaitUntilPubSubsEmpty()
if len( thumbnails ) > 0: SaveThumbnails( thumbnails )
job_key.DeleteVariable( 'popup_gauge_1' )
HydrusGlobals.client_controller.pub( 'splash_set_status_text', '' )
job_key.SetVariable( 'popup_title', 'repository synchronisation - ' + self._name + ' - finished' )
updates_text = HydrusData.ConvertIntToPrettyString( num_updates_downloaded ) + ' updates downloaded, ' + HydrusData.ConvertIntToPrettyString( num_updates_processed ) + ' updates processed'
if self._service_type == HC.TAG_REPOSITORY: content_text = HydrusData.ConvertIntToPrettyString( total_content_weight_processed ) + ' mappings added'
elif self._service_type == HC.FILE_REPOSITORY: content_text = HydrusData.ConvertIntToPrettyString( total_content_weight_processed ) + ' files added'
job_key.SetVariable( 'popup_text_1', updates_text + ', and ' + content_text )
print( job_key.ToString() )
time.sleep( 3 )
job_key.Delete()
except Exception as e:
job_key.Cancel()
print( traceback.format_exc() )
HydrusData.ShowText( 'Failed to update ' + self._name + ':' )
HydrusData.ShowException( e )
time.sleep( 3 )
def ToTuple( self ): return ( self._service_key, self._service_type, self._name, self._info )
class ServicesManager( object ):
def __init__( self ):
self._lock = threading.Lock()
self._keys_to_services = {}
self._services_sorted = []
self.RefreshServices()
HydrusGlobals.client_controller.sub( self, 'RefreshServices', 'notify_new_services_data' )
def GetService( self, service_key ):
with self._lock:
try: return self._keys_to_services[ service_key ]
except KeyError: raise HydrusExceptions.NotFoundException( 'That service was not found!' )
def GetServices( self, types = HC.ALL_SERVICES ):
with self._lock: return [ service for service in self._services_sorted if service.GetServiceType() in types ]
def RefreshServices( self ):
with self._lock:
services = HydrusGlobals.client_controller.Read( 'services' )
self._keys_to_services = { service.GetServiceKey() : service for service in services }
compare_function = lambda a, b: cmp( a.GetName(), b.GetName() )
self._services_sorted = list( services )
self._services_sorted.sort( cmp = compare_function )
class Shortcuts( HydrusSerialisable.SerialisableBaseNamed ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_SHORTCUTS
SERIALISABLE_VERSION = 1
def __init__( self, name ):
HydrusSerialisable.SerialisableBaseNamed.__init__( self, name )
self._mouse_actions = {}
self._keyboard_actions = {}
def _ConvertActionToSerialisableAction( self, action ):
( service_key, data ) = action
if service_key is None:
return [ service_key, data ]
else:
serialisable_service_key = service_key.encode( 'hex' )
return [ serialisable_service_key, data ]
def _ConvertSerialisableActionToAction( self, serialisable_action ):
( serialisable_service_key, data ) = serialisable_action
if serialisable_service_key is None:
return ( serialisable_service_key, data ) # important to return tuple, as serialisable_action is likely a list
else:
service_key = serialisable_service_key.decode( 'hex' )
return ( service_key, data )
def _GetSerialisableInfo( self ):
serialisable_mouse_actions = []
for ( ( modifier, mouse_button ), action ) in self._mouse_actions.items():
serialisable_action = self._ConvertActionToSerialisableAction( action )
serialisable_mouse_actions.append( ( modifier, mouse_button, serialisable_action ) )
serialisable_keyboard_actions = []
for ( ( modifier, key ), action ) in self._keyboard_actions.items():
serialisable_action = self._ConvertActionToSerialisableAction( action )
serialisable_keyboard_actions.append( ( modifier, key, serialisable_action ) )
return ( serialisable_mouse_actions, serialisable_keyboard_actions )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( serialisable_mouse_actions, serialisable_keyboard_actions ) = serialisable_info
self._mouse_actions = {}
for ( modifier, mouse_button, serialisable_action ) in serialisable_mouse_actions:
action = self._ConvertSerialisableActionToAction( serialisable_action )
self._mouse_actions[ ( modifier, mouse_button ) ] = action
self._keyboard_actions = {}
for ( modifier, key, serialisable_action ) in serialisable_keyboard_actions:
action = self._ConvertSerialisableActionToAction( serialisable_action )
self._keyboard_actions[ ( modifier, key ) ] = action
def ClearActions( self ):
self._mouse_actions = {}
self._keyboard_actions = {}
def DeleteKeyboardAction( self, modifier, key ):
if ( modifier, key ) in self._keyboard_actions:
del self._keyboard_actions[ ( modifier, key ) ]
def DeleteMouseAction( self, modifier, mouse_button ):
if ( modifier, mouse_button ) in self._mouse_actions:
del self._mouse_actions[ ( modifier, mouse_button ) ]
def GetKeyboardAction( self, modifier, key ):
if ( modifier, key ) in self._keyboard_actions:
return self._keyboard_actions[ ( modifier, key ) ]
else:
return None
def GetMouseAction( self, modifier, mouse_button ):
if ( modifier, mouse_button ) in self._mouse_actions:
return self._mouse_actions[ ( modifier, mouse_button ) ]
else:
return None
def IterateKeyboardShortcuts( self ):
for ( ( modifier, key ), action ) in self._keyboard_actions.items(): yield ( ( modifier, key ), action )
def IterateMouseShortcuts( self ):
for ( ( modifier, mouse_button ), action ) in self._mouse_actions.items(): yield ( ( modifier, mouse_button ), action )
def SetKeyboardAction( self, modifier, key, action ):
self._keyboard_actions[ ( modifier, key ) ] = action
def SetMouseAction( self, modifier, mouse_button, action ):
self._mouse_actions[ ( modifier, mouse_button ) ] = action
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_SHORTCUTS ] = Shortcuts
class UndoManager( object ):
def __init__( self ):
self._commands = []
self._inverted_commands = []
self._current_index = 0
self._lock = threading.Lock()
HydrusGlobals.client_controller.sub( self, 'Undo', 'undo' )
HydrusGlobals.client_controller.sub( self, 'Redo', 'redo' )
def _FilterServiceKeysToContentUpdates( self, service_keys_to_content_updates ):
filtered_service_keys_to_content_updates = {}
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
filtered_content_updates = []
for content_update in content_updates:
( data_type, action, row ) = content_update.ToTuple()
if data_type == HC.CONTENT_TYPE_FILES:
if action in ( HC.CONTENT_UPDATE_ADD, HC.CONTENT_UPDATE_DELETE, HC.CONTENT_UPDATE_UNDELETE, HC.CONTENT_UPDATE_RESCIND_PETITION ): continue
elif data_type == HC.CONTENT_TYPE_MAPPINGS:
if action in ( HC.CONTENT_UPDATE_RESCIND_PETITION, HC.CONTENT_UPDATE_ADVANCED ): continue
else: continue
filtered_content_update = HydrusData.ContentUpdate( data_type, action, row )
filtered_content_updates.append( filtered_content_update )
if len( filtered_content_updates ) > 0:
filtered_service_keys_to_content_updates[ service_key ] = filtered_content_updates
return filtered_service_keys_to_content_updates
def _InvertServiceKeysToContentUpdates( self, service_keys_to_content_updates ):
inverted_service_keys_to_content_updates = {}
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
inverted_content_updates = []
for content_update in content_updates:
( data_type, action, row ) = content_update.ToTuple()
inverted_row = row
if data_type == HC.CONTENT_TYPE_FILES:
if action == HC.CONTENT_UPDATE_ARCHIVE: inverted_action = HC.CONTENT_UPDATE_INBOX
elif action == HC.CONTENT_UPDATE_INBOX: inverted_action = HC.CONTENT_UPDATE_ARCHIVE
elif action == HC.CONTENT_UPDATE_PEND: inverted_action = HC.CONTENT_UPDATE_RESCIND_PEND
elif action == HC.CONTENT_UPDATE_RESCIND_PEND: inverted_action = HC.CONTENT_UPDATE_PEND
elif action == HC.CONTENT_UPDATE_PETITION:
inverted_action = HC.CONTENT_UPDATE_RESCIND_PETITION
( hashes, reason ) = row
inverted_row = hashes
elif data_type == HC.CONTENT_TYPE_MAPPINGS:
if action == HC.CONTENT_UPDATE_ADD: inverted_action = HC.CONTENT_UPDATE_DELETE
elif action == HC.CONTENT_UPDATE_DELETE: inverted_action = HC.CONTENT_UPDATE_ADD
elif action == HC.CONTENT_UPDATE_PEND: inverted_action = HC.CONTENT_UPDATE_RESCIND_PEND
elif action == HC.CONTENT_UPDATE_RESCIND_PEND: inverted_action = HC.CONTENT_UPDATE_PEND
elif action == HC.CONTENT_UPDATE_PETITION:
inverted_action = HC.CONTENT_UPDATE_RESCIND_PETITION
( tag, hashes, reason ) = row
inverted_row = ( tag, hashes )
inverted_content_update = HydrusData.ContentUpdate( data_type, inverted_action, inverted_row )
inverted_content_updates.append( inverted_content_update )
inverted_service_keys_to_content_updates[ service_key ] = inverted_content_updates
return inverted_service_keys_to_content_updates
def AddCommand( self, action, *args, **kwargs ):
with self._lock:
inverted_action = action
inverted_args = args
inverted_kwargs = kwargs
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
service_keys_to_content_updates = self._FilterServiceKeysToContentUpdates( service_keys_to_content_updates )
if len( service_keys_to_content_updates ) == 0: return
inverted_service_keys_to_content_updates = self._InvertServiceKeysToContentUpdates( service_keys_to_content_updates )
if len( inverted_service_keys_to_content_updates ) == 0: return
inverted_args = ( inverted_service_keys_to_content_updates, )
else: return
self._commands = self._commands[ : self._current_index ]
self._inverted_commands = self._inverted_commands[ : self._current_index ]
self._commands.append( ( action, args, kwargs ) )
self._inverted_commands.append( ( inverted_action, inverted_args, inverted_kwargs ) )
self._current_index += 1
HydrusGlobals.client_controller.pub( 'notify_new_undo' )
def GetUndoRedoStrings( self ):
with self._lock:
( undo_string, redo_string ) = ( None, None )
if self._current_index > 0:
undo_index = self._current_index - 1
( action, args, kwargs ) = self._commands[ undo_index ]
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
undo_string = 'undo ' + ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates )
if len( self._commands ) > 0 and self._current_index < len( self._commands ):
redo_index = self._current_index
( action, args, kwargs ) = self._commands[ redo_index ]
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
redo_string = 'redo ' + ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates )
return ( undo_string, redo_string )
def Undo( self ):
action = None
with self._lock:
if self._current_index > 0:
self._current_index -= 1
( action, args, kwargs ) = self._inverted_commands[ self._current_index ]
if action is not None:
HydrusGlobals.client_controller.WriteSynchronous( action, *args, **kwargs )
HydrusGlobals.client_controller.pub( 'notify_new_undo' )
def Redo( self ):
action = None
with self._lock:
if len( self._commands ) > 0 and self._current_index < len( self._commands ):
( action, args, kwargs ) = self._commands[ self._current_index ]
self._current_index += 1
if action is not None:
HydrusGlobals.client_controller.WriteSynchronous( action, *args, **kwargs )
HydrusGlobals.client_controller.pub( 'notify_new_undo' )
def GetShortcutFromEvent( event ):
modifier = wx.ACCEL_NORMAL
if event.AltDown(): modifier = wx.ACCEL_ALT
elif event.CmdDown(): modifier = wx.ACCEL_CTRL
elif event.ShiftDown(): modifier = wx.ACCEL_SHIFT
key = event.KeyCode
return ( modifier, key )
class ClientServiceIdentifier( HydrusData.HydrusYAMLBase ):
yaml_tag = u'!ClientServiceIdentifier'
def __init__( self, service_key, service_type, name ):
HydrusData.HydrusYAMLBase.__init__( self )
self._service_key = service_key
self._type = service_type
self._name = name
def __eq__( self, other ): return self.__hash__() == other.__hash__()
def __hash__( self ): return self._service_key.__hash__()
def __ne__( self, other ): return self.__hash__() != other.__hash__()
def __repr__( self ): return 'Client Service Identifier: ' + HydrusData.ToUnicode( ( self._name, HC.service_string_lookup[ self._type ] ) )
def GetInfo( self ): return ( self._service_key, self._type, self._name )
def GetName( self ): return self._name
def GetServiceKey( self ): return self._service_key
def GetServiceType( self ): return self._type
| [
"[email protected]"
] | |
8303d30c8032f5f4d4810c52bb87dece4b05a65d | 08a1d871f4be9ea61497751845a5ed9abe2a1012 | /farbox_bucket/utils/cli_color.py | 5819c5e25a1ad977f067ed1c0eba565f31526df8 | [
"MIT",
"LicenseRef-scancode-other-permissive"
] | permissive | itfanr/FarBox | 5bfff706439a6a223f531cfa36100ac21ed4878b | daeda4f5080467f1ddf4b60424b8562f914756bd | refs/heads/master | 2023-04-19T07:23:28.824231 | 2021-05-07T02:29:06 | 2021-05-07T02:29:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,422 | py | #coding: utf8
from __future__ import absolute_import, print_function
#CSI="\x1B["
#RED = CSI+"31;40m"
#GREEN = CSI+'32;40m'
#RESET =CSI+"m"
FLAGS = dict(
RESET = "\x1B[0m",
BOLD = "\x1B[1m",
DIM = "\x1B[2m",
UNDER = "\x1B[4m",
REVERSE = "\x1B[7m",
HIDE = "\x1B[8m",
CLEARSCREEN = "\x1B[2J",
CLEARLINE = "\x1B[2K",
BLACK = "\x1B[30m",
RED = "\x1B[31m",
GREEN = "\x1B[32m",
YELLOW = "\x1B[33m",
BLUE = "\x1B[34m",
MAGENTA = "\x1B[35m",
CYAN = "\x1B[36m",
WHITE = "\x1B[37m",
BBLACK = "\x1B[40m",
BRED = "\x1B[41m",
BGREEN = "\x1B[42m",
BYELLOW = "\x1B[43m",
BBLUE = "\x1B[44m",
BMAGENTA = "\x1B[45m",
BCYAN = "\x1B[46m",
BWHITE = "\x1B[47m",
NEWLINE = "\r\n\x1B[0m",
)
def print_with_color(strings, color='red', end='\r\n'):
color = FLAGS.get(color.upper())
if color:
print(color + strings + FLAGS['RESET'], end=end)
else:
print(strings)
def print_colorful_parts(string_parts, end=''):
for strings, color in string_parts:
print_with_color(strings, color, end)
print(FLAGS['NEWLINE'], end='')
if __name__ == '__main__':
print_with_color('hello', 'green', end=' ')
print_with_color('hello', 'blue')
print_colorful_parts(
[('hello', 'magenta'),
('world', 'yellow'),
('hello', 'red'),
('world', 'cyan')],
end=' '
)
| [
"[email protected]"
] | |
701af4a6dea98585d23863e6340949745d1980e6 | 73758dde83d1a1823c103e1a4ba71e7c95168f71 | /nsd1912/py02/day02/myfunc.py | 684e88105205263137758b3b560f5844088f2eac | [] | no_license | tonggh220/md_5_nsd_notes | 07ffdee7c23963a7a461f2a2340143b0e97bd9e1 | a58a021ad4c7fbdf7df327424dc518f4044c5116 | refs/heads/master | 2023-07-02T01:34:38.798929 | 2021-05-12T08:48:40 | 2021-05-12T08:48:40 | 393,885,415 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 271 | py | def func1(x):
if x == 1:
return 1
return x * func1(x- 1)
# 5 * func1(4)
# 5 * 4 * func1(3)
# 5 * 4 * 3 * func1(2)
# 5 * 4 * 3 * 2 * func1(1)
# 5 * 4 * 3 * 2 * 1
if __name__ == '__main__':
print(func1(5))
| [
"[email protected]"
] | |
2c3ddf59ef5bbc9b91706cc3b505f3e28ba85471 | 1ade02a8e0c6d7e442c9d9041f15518d22da3923 | /w8/mock_phase2/run/core/controllers/generic.py | 4478b8a5012a51fa7a71dcc21a18532f1804d5fc | [] | no_license | fodisi/ByteAcademy-Bootcamp | 7980b80636a36db6da3e0fc0e529fbc6b8e097e0 | d53e3f4864f6cba1b85e806c29b01c48e3c2e81d | refs/heads/master | 2020-03-19T12:55:31.489638 | 2018-07-25T16:19:19 | 2018-07-25T16:19:19 | 136,550,128 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | #!/usr/bin/env python3
from flask import Blueprint, render_template
controller = Blueprint('generic', __name__)
@controller.route('/<product_name>')
def home(product_name):
# obj = model.get_product(product_name)
return render_template('index.html', json_obj=obj.to_json)
| [
"[email protected]"
] | |
8da80ee62fb2a9c9ee57874efa1a8a69dc421479 | 694d57c3e512ce916269411b51adef23532420cd | /leetcode/23merge_k_sorted_lists.py | 76d8e6ea698631516ea4cfdd1e87899d4de8cc45 | [] | no_license | clovery410/mycode | 5541c3a99962d7949832a0859f18819f118edfba | e12025e754547d18d5bb50a9dbe5e725fd03fd9c | refs/heads/master | 2021-05-16T02:46:47.996748 | 2017-05-10T23:43:50 | 2017-05-10T23:43:50 | 39,235,141 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,368 | py | import heapq
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
new_head = None
heap = []
for node in lists:
if node:
heapq.heappush(heap, (node.val, node))
if heap:
new_head = heapq.heappop(heap)[1]
if new_head.next:
heapq.heappush(heap, (new_head.next.val, new_head.next))
pre_node = new_head
while heap:
curr_node = heapq.heappop(heap)[1]
if curr_node.next:
heapq.heappush(heap, (curr_node.next.val, curr_node.next))
pre_node.next = curr_node
pre_node = curr_node
return new_head
if __name__ == '__main__':
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node6 = ListNode(6)
node1.next = node3
node3.next = node5
node2.next = node4
node4.next = node6
sol = Solution()
new_head = sol.mergeKLists([node1, node2])
print new_head.val
print new_head.next.val
print new_head.next.next.val
print new_head.next.next.next.val
print new_head.next.next.next.next.val
print new_head.next.next.next.next.next.val
print sol.mergeKLists([[]])
| [
"[email protected]"
] | |
515c154e112ed44885fb11d8cfbd74d1c10c102d | 1b070c5fabfe7e804eac4c7d706f6ccdf6b29ed0 | /partners/migrations/0005_auto_20200620_0044.py | bfe6abd78feb964304d45149cd068cdcdae946a8 | [
"MIT"
] | permissive | cZachJohnson/My-Business | ef80dae6458c2fb7a08465d29e32f9405e52e43d | 792bb13a5b296260e5de7e03fba6445a13922851 | refs/heads/master | 2023-08-25T06:51:39.330270 | 2021-10-25T01:20:34 | 2021-10-25T01:20:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 687 | py | # Generated by Django 2.2.12 on 2020-06-20 00:44
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("partners", "0004_auto_20200609_0514"),
]
operations = [
migrations.AddField(
model_name="partner",
name="created_at",
field=models.DateTimeField(
auto_now_add=True, default=datetime.datetime(1970, 1, 1, 0, 0)
),
preserve_default=False,
),
migrations.AddField(
model_name="partner",
name="updated_at",
field=models.DateTimeField(auto_now=True),
),
]
| [
"[email protected]"
] | |
6347debad11c0a6b40a7f94a3ab778d780943f36 | 24a88b7dd4d81763fd4212a42c4a73f4c35f8ffc | /apiREST/api/serializers.py | f92010912774eedc0733526c21deca79cd4e444b | [] | no_license | junkluis/leccionMVC | d001c122318dde065ffd9a88aaaad0b7b4533a05 | c311e69f2ae6d102651f9f7e6fc1f9750fc9e4bc | refs/heads/master | 2021-01-15T19:27:48.875724 | 2017-08-14T14:35:29 | 2017-08-14T14:35:29 | 99,823,220 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py | from rest_framework import serializers
from .models import *
class ticketSerializer(serializers.ModelSerializer):
class Meta:
model = ticket
fields = ('fechaEmision', 'Precio', 'Adquiriente', 'Puesto', 'Origen', 'Destino') | [
"[email protected]"
] | |
adf34bdb17df662959d03197aa497d4f9a4eccc1 | 9bbf429d2c2e2f20345d613a719cf01e8f9a0bff | /project/settings.py | 6c1e92b7cc86c64ef10a85cf6336b520a2f2d545 | [] | no_license | sandglasscao/ENU | f78f8a8dfaf3263587885b0622ab6d3182012375 | e3c26fd57f8ef582da576e1cc28b7eb42562c706 | refs/heads/master | 2021-01-23T05:19:03.175439 | 2017-04-14T09:24:22 | 2017-04-14T09:24:22 | 86,297,754 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,673 | py | """
Django settings for project project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import socket
import datetime
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ON_PAAS = 'OPENSHIFT_REPO_DIR' in os.environ
if ON_PAAS:
SECRET_KEY = os.environ['OPENSHIFT_SECRET_TOKEN']
else:
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')_7av^!cy(wfx=k#3*7x+(=j^fzv+ot^1@sh9s9t=8$bu@r(z$'
# SECURITY WARNING: don't run with debug turned on in production!
# adjust to turn off when on Openshift, but allow an environment variable to override on PAAS
DEBUG = not ON_PAAS
DEBUG = DEBUG or os.getenv("debug", "false").lower() == "true"
if ON_PAAS and DEBUG:
print("*** Warning - Debug mode is on ***")
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'crispy_forms',
'userprofile',
'metadata',
'utility',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static',
'django.template.context_processors.i18n',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
if ON_PAAS:
# determine if we are on MySQL or POSTGRESQL
if "OPENSHIFT_POSTGRESQL_DB_USERNAME" in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['OPENSHIFT_APP_NAME'],
'USER': os.environ['OPENSHIFT_POSTGRESQL_DB_USERNAME'],
'PASSWORD': os.environ['OPENSHIFT_POSTGRESQL_DB_PASSWORD'],
'HOST': os.environ['OPENSHIFT_POSTGRESQL_DB_HOST'],
'PORT': os.environ['OPENSHIFT_POSTGRESQL_DB_PORT'],
}
}
elif "OPENSHIFT_MYSQL_DB_USERNAME" in os.environ:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['OPENSHIFT_APP_NAME'],
'USER': os.environ['OPENSHIFT_MYSQL_DB_USERNAME'],
'PASSWORD': os.environ['OPENSHIFT_MYSQL_DB_PASSWORD'],
'HOST': os.environ['OPENSHIFT_MYSQL_DB_HOST'],
'PORT': os.environ['OPENSHIFT_MYSQL_DB_PORT'],
}
}
else:
'''
# stock django, local development.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['OPENSHIFT_APP_NAME'],
'USER': os.environ['OPENSHIFT_MYSQL_DB_USERNAME'],
'PASSWORD': os.environ['OPENSHIFT_MYSQL_DB_PASSWORD'],
'HOST': os.environ['OPENSHIFT_MYSQL_DB_HOST'],
'PORT': os.environ['OPENSHIFT_MYSQL_DB_PORT'],
}
}
'''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ['APP_NAME2'],
'USER': os.environ['MYSQL_DB_USERNAME'],
'PASSWORD': os.environ['MYSQL_DB_PASSWORD'],
'HOST': os.environ['MYSQL_DB_HOST'],
'PORT': os.environ['MYSQL_DB_PORT'],
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
# LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = 'zh-hans'
# TIME_ZONE = 'America/Sao_Paulo'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'wsgi', 'static') # STATIC_ROOT is just for production env to collect all static resources
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(BASE_DIR, "static"),
)
if ON_PAAS:
MEDIA_ROOT = os.path.join(os.environ.get('OPENSHIFT_DATA_DIR'), 'media')
MEDIA_URL = '/static/media/'
else:
#MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
MEDIA_ROOT = os.path.join(BASE_DIR, 'static', 'media')
MEDIA_URL = STATIC_URL + 'media/'
CRISPY_TEMPLATE_PACK = 'bootstrap3'
SITE_ID = 1
LOGIN_REDIRECT_URL = '/'
AUTH_PROFILE_MODULE = 'userprofile.Profile'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
# 'file': {
# 'level': 'INFO',
# 'class': 'logging.FileHandler',
# 'filename': 'bluepage.log',
# 'formatter': 'verbose'
# },
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
'level': 'ERROR',
},
'case': {
'handlers': ['console'],
'level': 'DEBUG',
},
'page': {
'handlers': ['console'],
'level': 'DEBUG',
},
}
}
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
]
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=30000),
}
| [
"root@localhost"
] | root@localhost |
68c11e7899d80a15888e4252296049bf2b4e8843 | 2fd087fbc5faf43940153693823969df6c8ec665 | /pyc_decrypted/latest/dropbox/client/watchdog.py | 6983e510c3bd0826ea5395ce93826e40f4907e9b | [] | no_license | mickeystone/DropBoxLibrarySRC | ed132bbffda7f47df172056845e5f8f6c07fb5de | 2e4a151caa88b48653f31a22cb207fff851b75f8 | refs/heads/master | 2021-05-27T05:02:30.255399 | 2013-08-27T13:16:55 | 2013-08-27T13:16:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 17,772 | py | #Embedded file name: dropbox/client/watchdog.py
import hashlib
import os
import socket
import struct
import threading
import time
from Crypto.Random import random
from trace_report import make_report
from dropbox.build_common import get_build_number
from dropbox.callbacks import Handler
from dropbox.fileutils import safe_remove
from dropbox.globals import dropbox_globals
from dropbox.native_event import AutoResetEvent
from dropbox.native_queue import Queue
from dropbox.platform import platform
from dropbox.sqlite3_helpers import sqlite3_get_memory_statistics
from dropbox.threadutils import StoppableThread
from dropbox.trace import TRACE, unhandled_exc_handler, add_exception_handler, report_bad_assumption
import arch
from dropbox.client.high_trace import sample_process, send_ds_store, send_finder_crashes, send_trace_log
_ONE_WEEK = 604800
class Watchdog2(object):
UNIT_REPORT_INTERVAL = 900
HIGH_CPU_USAGE = 0.3
def __init__(self, status_controller, conn, handler = None):
self.status_controller = status_controller
self.sync_engine = None
self.conn = conn
add_exception_handler(self.handle_exception)
self.clear()
if handler:
handler.add_handler(self.update_counts)
def clear(self):
self.last_times = (time.time(), 0, 0)
self.hung_since = None
self.high_cpu_minutes = 0
self.over_quota = False
self.report_interval = self.UNIT_REPORT_INTERVAL
self.last_cpu_minutes = 0
self.last_dbfseventsd_broken = False
self.last_counts = (0, 0, 0, 0)
self.last_report = 0
self.last_exception_hash = None
self.last_upload_exception_hash = None
self.last_reconstruct_exception_hash = None
self.last_hash_exception_hash = None
self.exc_lock = threading.Lock()
def handle_exception(self, *exc_info, **kw):
with self.exc_lock:
self.last_exception_hash = make_report(exc_info)[1]
thr_name = threading.currentThread().getName()
if thr_name == 'UPLOAD':
self.last_upload_exception_hash = self.last_exception_hash
elif thr_name == 'RECONSTRUCT':
self.last_reconstruct_exception_hash = self.last_exception_hash
elif thr_name == 'HASH':
self.last_hash_exception_hash = self.last_exception_hash
def set_sync_engine(self, sync_engine):
self.sync_engine = sync_engine
self.sync_engine.add_list_callback(self._handle_list)
def _handle_list(self, ret):
try:
self.over_quota = ret['in_use'] > ret['quota']
except KeyError:
pass
def update_counts(self):
if not self.sync_engine:
return
if not self.sync_engine.running:
self.clear()
return
ct = time.time()
elapsed = ct - self.last_times[0]
if elapsed >= 60:
sys_time = ct, utime, stime = self.sync_engine.get_system_time_tuple()
cpu_usage = (stime + utime - (self.last_times[1] + self.last_times[2])) / elapsed
if cpu_usage > self.HIGH_CPU_USAGE:
self.high_cpu_minutes += 1
TRACE('!! Warning: high CPU usage (%d mins total; %.1f%% used)' % (self.high_cpu_minutes, cpu_usage * 100))
self.last_times = sys_time
if ct - self.last_report >= self.report_interval:
queue_stats = self.sync_engine.get_queue_stats()
counts = (queue_stats['hash']['total_count'],
queue_stats['upload']['total_count'],
queue_stats['reconstruct']['total_count'],
queue_stats['conflicted']['total_count'])
is_hung = self.last_counts == counts and sum(counts)
cpu_minutes = self.high_cpu_minutes - self.last_cpu_minutes
dbfseventsd_broken = dropbox_globals.get('dbfseventsd_is_broken', False)
try:
if is_hung or self.last_dbfseventsd_broken != dbfseventsd_broken and dbfseventsd_broken or cpu_minutes >= 5:
TRACE('!! Sync engine appears stalled: %r (%s high cpu mins) dbfseventsd_broken:%r' % (counts, cpu_minutes, dbfseventsd_broken))
if self.hung_since is None:
self.hung_since = time.time()
send_trace_log()
if cpu_minutes >= 5:
sample_process()
current_upload_speed = self.status_controller.upload_status.get_transfer_speed() or 0
current_download_speed = self.status_controller.download_status.get_transfer_speed() or 0
upload_bytecount, upload_hashcount = self.sync_engine.upload_queue_size()
download_bytecount, download_hashcount = self.sync_engine.download_queue_size()
unreconstructable_count = 0
self.conn.report_hang2(dict(is_hung=is_hung, dbfseventsd_broken=dbfseventsd_broken, cpu_minutes=cpu_minutes, cpu_minutesp=float(cpu_minutes) / self.report_interval, hung_for=time.time() - self.hung_since, queue_stats=queue_stats, conflicted_count=queue_stats['conflicted']['total_count'], over_quota=self.over_quota, current_upload_speed=current_upload_speed, current_download_speed=current_download_speed, low_disk_space=self.status_controller.is_true('low_disk_space'), upload_bytecount=upload_bytecount, download_bytecount=download_bytecount, upload_hashcount=upload_hashcount, download_hashcount=download_hashcount, unreconstructable_count=unreconstructable_count, exception_hashes=(self.last_exception_hash,
self.last_hash_exception_hash,
self.last_upload_exception_hash,
self.last_reconstruct_exception_hash)))
elif self.hung_since:
TRACE('!! Sync engine no longer stalled: %r' % (counts,))
self.conn.report_hang2(None)
self.hung_since = None
except Exception as e:
if self.conn.is_transient_error(e):
TRACE('!! Failed to communicate with server: %r%r', type(e), e.args)
else:
unhandled_exc_handler()
self.report_interval += self.UNIT_REPORT_INTERVAL
else:
self.last_counts = counts
self.last_dbfseventsd_broken = dbfseventsd_broken
self.last_cpu_minutes = self.high_cpu_minutes
self.last_report = ct
self.report_interval = self.UNIT_REPORT_INTERVAL
class StatReporter(object):
DEFAULT_INTERVAL = 900
def __init__(self, csr, buildno, status_controller, conn, config, handler = None):
self.csr = csr
self.config = config
self.old_stats = {}
self.last_report = 0
self.buildno = buildno
self.interval = self.DEFAULT_INTERVAL
self.status_controller = status_controller
self.conn = conn
self.sync_engine = None
self.failure_backoff = None
try:
with self.config as config:
try:
last_stats_build = config['stats_build']
except KeyError:
self.next_report_id = config.get('stats_next_report_id', 0)
self.next_report_time = config.get('stats_next_report_time')
self.dont_send_until_upgrade = config.get('stats_dont_send_until_upgrade')
else:
if last_stats_build != get_build_number():
self.next_report_id = 0
self.next_report_time = None
self.dont_send_until_upgrade = False
else:
self.next_report_id = config.get('stats_next_report_id', 0)
self.next_report_time = config.get('stats_next_report_time')
self.dont_send_until_upgrade = config.get('stats_dont_send_until_upgrade')
except Exception:
unhandled_exc_handler()
self.next_report_id = 0
self.next_report_time = None
self.dont_send_until_upgrade = False
if self.next_report_time:
TRACE('Client stats wants us to hit the server again at %s (%s seconds) (local: %s)' % (self.next_report_time, self.next_report_time - time.time(), time.ctime(self.next_report_time)))
if handler:
handler.add_handler(self.run)
def set_reporting_interval(self, interval):
self.interval = interval
def set_sync_engine(self, sync_engine):
self.sync_engine = sync_engine
def report_queryable_stats(self):
us = self.status_controller.upload_status.get_transfer_speed()
if us is not None:
self.csr.report_stat('upload_speed', str(us))
ds = self.status_controller.download_status.get_transfer_speed()
if ds is not None:
self.csr.report_stat('download_speed', str(ds))
if self.sync_engine:
queue_stats = self.sync_engine.get_queue_stats()
self.csr.report_stat('pending_cache_count', str(queue_stats['upload']['total_count']))
self.csr.report_stat('to_hash_cache_count', str(queue_stats['hash']['total_count']))
self.csr.report_stat('updated_cache_count', str(queue_stats['reconstruct']['total_count']))
self.csr.report_stat('conflicted_cache_count', str(queue_stats['conflicted']['total_count']))
self.csr.report_stat('quota_pending_cache_count', str(queue_stats['upload']['failure_counts'].get('quota', 0)))
self.csr.report_stat('invalid_path_pending_cache_count', str(queue_stats['upload']['failure_counts'].get('invalid_path', 0)))
self.csr.report_stat('directory_not_empty_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('directory_not_empty', 0)))
self.csr.report_stat('low_disk_space_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('low_disk_space', 0)))
self.csr.report_stat('permission_denied_updated_cache_count', str(queue_stats['reconstruct']['failure_counts'].get('permission_denied', 0)))
n = int(time.time())
self.csr.report_stat('gui_backoff_factor', str(struct.unpack('<Q', hashlib.md5('Open %s Folder Launch %d Website Apple CarbonEventManager Windows %d' % (self.buildno, n, self.conn.host_int)).digest()[:struct.calcsize('<Q')])[0]), n)
rss = arch.startup.get_rss()
if rss is not None and rss != -1:
self.csr.report_stat('rss', str(rss))
try:
mem_used, highwater = sqlite3_get_memory_statistics()
except Exception:
unhandled_exc_handler()
else:
self.csr.report_stat('sqlite3_memory_used', str(mem_used))
self.csr.report_stat('sqlite3_memory_highwater', str(highwater))
try:
if self.sync_engine and self.sync_engine.p2p_state and self.sync_engine.p2p_state.pool:
peer_dict = self.sync_engine.p2p_state.pool.getPeerAndConnCount()
self.csr.report_stat('peer_count', str(peer_dict['peer_count']))
self.csr.report_stat('peer_connections', str(peer_dict['total_connections']))
except Exception:
unhandled_exc_handler()
def run(self):
if self.dont_send_until_upgrade:
return
if self.failure_backoff:
if time.time() < self.failure_backoff[1]:
return
if self.next_report_time is not None and time.time() < self.next_report_time:
report_bad_assumption('Client-stats backoff was less than our next report time, %s < %s' % (self.next_report_time, self.failure_backoff[1]))
elif self.next_report_time is not None and time.time() < self.next_report_time:
return
self.report_queryable_stats()
self.csr.lock_updates()
try:
total_stats = self.csr.total_stats()
total_events = self.csr.total_events()
report_id = self.next_report_id
divisor = 1
done = False
while not done:
to_pull_from_stats = total_stats / divisor
to_pull_from_events = total_events / divisor
for i in xrange(divisor):
stat_batch = self.csr.iterate_n_stats(to_pull_from_stats)
event_batch = self.csr.iterate_n_events(to_pull_from_events)
stats_to_send = [ (stat, arg, ts) for stat, (arg, ts) in stat_batch ]
try:
event_ids_to_clear, events_to_send = zip(*event_batch)
except ValueError:
event_ids_to_clear, events_to_send = (), ()
if not (stats_to_send or events_to_send):
done = True
break
try:
ret = self.conn.report_stats(time.time(), stats_to_send, events_to_send, self.buildno, report_id)
except Exception as e:
unhandled_exc_handler()
if isinstance(e, socket.error) and e[0] == 32:
break
if self.failure_backoff:
self.failure_backoff = (self.failure_backoff[0] * 2, min(random.uniform(0, self.failure_backoff[0] * 4), _ONE_WEEK) + time.time())
else:
self.failure_backoff = (1, random.uniform(0, 2) + time.time())
TRACE('!! Client Stats failed, backing off until %s for (%s seconds) (local: %s)' % (self.failure_backoff[1], self.failure_backoff[1] - time.time(), time.ctime(self.failure_backoff[1])))
done = True
else:
self.failure_backoff = None
try:
self.dont_send_until_upgrade = ret['dont_send_until_upgrade']
except KeyError:
stats_backoff = float(ret['backoff'])
next_report_id = long(ret['report_id'])
self.next_report_time = stats_backoff + time.time()
self.next_report_id = next_report_id
else:
self.next_report_time = None
self.next_report_id = 0
try:
with self.config as config:
config['stats_dont_send_until_upgrade'] = self.dont_send_until_upgrade
config['stats_next_report_time'] = self.next_report_time
config['stats_next_report_id'] = self.next_report_id
config['stats_build'] = get_build_number()
except Exception:
unhandled_exc_handler()
TRACE('Client stats wants us to hit the server again at %s (%s seconds) (local: %s)', self.next_report_time, stats_backoff, time.ctime(self.next_report_time))
self.csr.clean_reported_stats_and_event_ids(stats_to_send, event_ids_to_clear)
divisor *= 2
finally:
self.csr.unlock_updates()
def maybe_send_explorer_crash():
if arch.util.unreported_explorer_crash():
send_trace_log()
class WatchdogThread(StoppableThread):
def __init__(self, app, *n, **kw):
kw['name'] = 'WATCHDOG'
super(WatchdogThread, self).__init__(*n, **kw)
self.app = app
self.bangp = AutoResetEvent()
self.one_time_q = Queue(100)
self.handler = Handler(handle_exc=unhandled_exc_handler)
self.add_handler(self._one_time_handler)
def set_wakeup_event(self, *n, **kw):
self.bangp.set(*n, **kw)
def add_handler(self, *n, **kw):
self.handler.add_handler(*n, **kw)
def remove_handler(self, *n, **kw):
self.handler.remove_handler(*n, **kw)
def add_one_time_handler(self, cb):
try:
self.one_time_q.put(cb)
except Exception:
unhandled_exc_handler()
def _one_time_handler(self, *n, **kw):
for fn in self.one_time_q.get_all_and_clear():
try:
fn(*n, **kw)
except Exception:
unhandled_exc_handler()
def run(self):
TRACE('Watchdog thread starting.')
if platform == 'mac':
def maybe_send_finder_crashes():
sarch = self.app.sync_engine.arch
if sarch.fschange and sarch.fschange.potential_finder_restart():
send_finder_crashes()
self.add_handler(maybe_send_finder_crashes)
self.add_handler(send_ds_store)
if platform == 'win':
self.add_handler(maybe_send_explorer_crash)
send_finder_crashes()
self.remove_installer_logs()
while not self.stopped():
self.handler.run_handlers()
self.bangp.wait(60)
TRACE('Stopping...')
def remove_installer_logs(self):
if platform != 'win':
return
try:
installer_log_dir = os.path.join(self.app.appdata_path, 'installer', 'l')
if not os.path.exists(installer_log_dir):
return
for x in os.listdir(installer_log_dir):
full_path = os.path.join(installer_log_dir, x)
safe_remove(full_path)
except Exception:
unhandled_exc_handler()
| [
"[email protected]"
] | |
3231911515adfd0365eae0b7ab08f656f1a18ce5 | 134c429df7d5c4d067d9761cb1435992b048adaf | /notes/0431/0431.py | 11bc6ce8611f6db618e1efae727ca798d3c25e41 | [] | no_license | PaulGuo5/Leetcode-notes | 65c6ebb61201d6f16386062e4627291afdf2342d | 431b763bf3019bac7c08619d7ffef37e638940e8 | refs/heads/master | 2021-06-23T09:02:58.143862 | 2021-02-26T01:35:15 | 2021-02-26T01:35:15 | 177,007,645 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,261 | py | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
class Codec:
# Encodes an n-ary tree to a binary tree.
def encode(self, root: 'Node') -> TreeNode:
if not root:
return None
new = TreeNode(root.val)
if not root.children:
return new
new.left = self.encode(root.children[0]) # node's children
node = new.left
for child in root.children[1:]: # node's sibling
node.right = self.encode(child)
node = node.right
return new
# Decodes your binary tree to an n-ary tree.
def decode(self, data: TreeNode) -> 'Node':
if not data:
return None
new = Node(data.val, [])
node = data.left
while node:
new.children.append(self.decode(node))
node = node.right
return new
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))
| [
"[email protected]"
] | |
6ca88a0dbb97f37b2015940e3978efcb9c8a9f0b | bfc25f1ad7bfe061b57cfab82aba9d0af1453491 | /data/external/repositories_2to3/132160/kaggle-ndsb-master/configurations/[email protected] | 15acaee9e4b2e5862cb947b90c641219ff778759 | [
"MIT"
] | permissive | Keesiu/meta-kaggle | 77d134620ebce530d183467202cf45639d9c6ff2 | 87de739aba2399fd31072ee81b391f9b7a63f540 | refs/heads/master | 2020-03-28T00:23:10.584151 | 2018-12-20T19:09:50 | 2018-12-20T19:09:50 | 147,406,338 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 5,904 | py | import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
pre_init_path = "CONVROLL4_MODEL_FILE"
validation_split_path = "splits/bagging_split_27.pkl"
patch_size = (95, 95)
augmentation_params = {
'zoom_range': (1 / 1.6, 1.6),
'rotation_range': (0, 360),
'shear_range': (-20, 20),
'translation_range': (-10, 10),
'do_flip': True,
'allow_stretch': 1.3,
}
batch_size = 128 // 4
chunk_size = 32768 // 4
num_chunks_train = 580
momentum = 0.9
learning_rate_schedule = {
0: 0.003,
420: 0.0003,
540: 0.00003,
}
validate_every = 20
save_every = 20
def estimate_scale(img):
return np.maximum(img.shape[0], img.shape[1]) / 85.0
# augmentation_transforms_test = []
# for flip in [True, False]:
# for zoom in [1/1.3, 1/1.2, 1/1.1, 1.0, 1.1, 1.2, 1.3]:
# for rot in np.linspace(0.0, 360.0, 5, endpoint=False):
# tf = data.build_augmentation_transform(zoom=(zoom, zoom), rotation=rot, flip=flip)
# augmentation_transforms_test.append(tf)
augmentation_transforms_test = tta.build_quasirandom_transforms(70, **{
'zoom_range': (1 / 1.4, 1.4),
'rotation_range': (0, 360),
'shear_range': (-10, 10),
'translation_range': (-8, 8),
'do_flip': True,
'allow_stretch': 1.2,
})
data_loader = load.ZmuvRescaledDataLoader(estimate_scale=estimate_scale, num_chunks_train=num_chunks_train,
patch_size=patch_size, chunk_size=chunk_size, augmentation_params=augmentation_params,
augmentation_transforms_test=augmentation_transforms_test, validation_split_path=validation_split_path)
# Conv2DLayer = nn.layers.cuda_convnet.Conv2DCCLayer
# MaxPool2DLayer = nn.layers.cuda_convnet.MaxPool2DCCLayer
Conv2DLayer = tmp_dnn.Conv2DDNNLayer
MaxPool2DLayer = tmp_dnn.MaxPool2DDNNLayer
def build_model():
l0 = nn.layers.InputLayer((batch_size, 1, patch_size[0], patch_size[1]))
l0c = dihedral.CyclicSliceLayer(l0)
l1a = Conv2DLayer(l0c, num_filters=32, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l1b = Conv2DLayer(l1a, num_filters=16, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l1 = MaxPool2DLayer(l1b, ds=(3, 3), strides=(2, 2))
l1r = dihedral.CyclicConvRollLayer(l1)
l2a = Conv2DLayer(l1r, num_filters=64, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l2b = Conv2DLayer(l2a, num_filters=32, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l2 = MaxPool2DLayer(l2b, ds=(3, 3), strides=(2, 2))
l2r = dihedral.CyclicConvRollLayer(l2)
l3a = Conv2DLayer(l2r, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3b = Conv2DLayer(l3a, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3c = Conv2DLayer(l3b, num_filters=64, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l3 = MaxPool2DLayer(l3c, ds=(3, 3), strides=(2, 2))
l3r = dihedral.CyclicConvRollLayer(l3)
l4a = Conv2DLayer(l3r, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4b = Conv2DLayer(l4a, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4c = Conv2DLayer(l4b, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l4 = MaxPool2DLayer(l4c, ds=(3, 3), strides=(2, 2))
l4r = dihedral.CyclicConvRollLayer(l4)
l5a = Conv2DLayer(l4r, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5b = Conv2DLayer(l5a, num_filters=256, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5c = Conv2DLayer(l5b, num_filters=128, filter_size=(3, 3), border_mode="same", W=nn_plankton.Conv2DOrthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu, untie_biases=True)
l5 = MaxPool2DLayer(l5c, ds=(3, 3), strides=(2, 2))
l5r = dihedral.CyclicConvRollLayer(l5)
l5f = nn.layers.flatten(l5r)
l6 = nn.layers.DenseLayer(nn.layers.dropout(l5f, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l6r = dihedral.CyclicRollLayer(l6)
l7 = nn.layers.DenseLayer(nn.layers.dropout(l6r, p=0.5), num_units=256, W=nn_plankton.Orthogonal(1.0), b=nn.init.Constant(0.1), nonlinearity=nn_plankton.leaky_relu)
l7m = dihedral.CyclicPoolLayer(l7, pool_function=nn_plankton.rms)
l8 = nn.layers.DenseLayer(nn.layers.dropout(l7m, p=0.5), num_units=data.num_classes, nonlinearity=T.nnet.softmax, W=nn_plankton.Orthogonal(1.0))
l_resume = l2
l_exclude = l2
return [l0], l8, l_resume, l_exclude
| [
"[email protected]"
] | |
6ceb9d1a80663a73976e941ebaa5c6143e75a5ce | c7e9ec5ce6627f6f68bab1b86a27a4516595154d | /consentrecords/migrations/0089_auto_20180123_2226.py | 738533784e45a55c62c2542c2229561d9a774b5b | [] | no_license | michaelcrubenstein/consentrecords | 7b79e82c9ad4b5efcfbb44a50ff1d4cadf7180e2 | 992fe78c68d1d5c083f9e2cc0e3e9aa24363b93d | refs/heads/master | 2021-01-23T19:28:13.807809 | 2018-07-03T16:10:34 | 2018-07-03T16:10:34 | 41,223,029 | 1 | 1 | null | 2018-07-03T16:10:35 | 2015-08-22T20:21:26 | JavaScript | UTF-8 | Python | false | false | 700 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2018-01-23 22:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('consentrecords', '0088_auto_20171227_2107'),
]
operations = [
migrations.RemoveField(
model_name='experience',
name='timeframe',
),
migrations.RemoveField(
model_name='experiencehistory',
name='timeframe',
),
migrations.AlterField(
model_name='experience',
name='era',
field=models.IntegerField(db_index=True, null=True),
),
]
| [
"[email protected]"
] | |
0fe411a821c9c8d033e284c43fba39a10774bbb9 | 4a1273f72e7d8a07a3fa67ac9f2709b64ec6bc18 | /retiresmartz/advice_responses.py | 73223c61a7c14be764d3ae4c699eb9fc19d26e8d | [] | no_license | WealthCity/django-project | 6668b92806d8c61ef9e20bd42daec99993cd25b2 | fa31fa82505c3d0fbc54bd8436cfc0e49c896f3e | refs/heads/dev | 2021-01-19T14:10:52.115301 | 2017-04-12T11:23:32 | 2017-04-12T11:23:32 | 88,132,284 | 0 | 1 | null | 2017-04-13T06:26:30 | 2017-04-13T06:26:29 | null | UTF-8 | Python | false | false | 12,283 | py | # -*- coding: utf-8 -*-
from main import constants
from datetime import datetime
import logging
logger = logging.getLogger('api.v1.retiresmartz.advice_responses')
# Retiresmartz Advice feed Logic Calls
# On Track / Off Track
def get_on_track(advice):
return 'If you would like to change any of your retirement details \
you can do so by clicking on the items on this or the previous screen.'
def get_off_track(advice):
return 'I recommend changing some of your retirement details \
by clicking on this or the previous screen. This will help you \
to plan to be on track to a better retirement.'
# Change Retirement Age
def get_decrease_retirement_age_to_62(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 your social \
# security benefit would be estimated to be <estimated SS benefit \
# multiplied by inflator>
return "I see you have decreased your retirement age \
to 62. This will reduce your monthly benefit by 25% compared \
to if you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to retire \
at 66. Social security benefits increase by up to 132% the longer \
you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .25), advice.plan.spendable_income)
def get_decrease_retirement_age_to_63(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 \
# your social security benefit would be estimated to be \
# <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 63. \
This will reduce your monthly benefit by 20% compared to if \
you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .2), advice.plan.spendable_income)
def get_decrease_retirement_age_to_64(advice):
# TODO: Need to insert social security benefit in data\
# By increasing your retirement age to 70 \
# your social security benefit would be estimated to be \
# <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 64. \
This will reduce your monthly benefit by 13% compared to \
if you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .13), advice.plan.spendable_income)
def get_decrease_retirement_age_to_65(advice):
# TODO: Need to insert social security benefit in data
# By increasing your retirement age to 70 \
# your social security benefit would be estimated
# to be <estimated SS benefit multiplied by inflator>
return "I see you have decreased your retirement age to 65. \
This will reduce your monthly benefit by 7% compared to if \
you retired at 66 giving you an estimated social security \
benefit of ${:,.2f} per month instead of ${:,.2f} if you chose to \
retire at 66. Social security benefits increase by up to 132% \
the longer you work.".format(advice.plan.spendable_income - (advice.plan.spendable_income * .07), advice.plan.spendable_income)
def get_increase_retirement_age_to_67(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 67. \
This will increase your monthly benefit by 8% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .08), advice.plan.spendable_income)
def get_increase_retirement_age_to_68(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 68. \
This will increase your monthly benefit by 16% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .16), advice.plan.spendable_income)
def get_increase_retirement_age_to_69(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 69. \
This will increase your monthly benefit by 24% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .24), advice.plan.spendable_income)
def get_increase_retirement_age_to_70(advice):
# TODO: Need to insert social security benefit in data
return "I see you have increased your retirement age to 70. \
This will increase your monthly benefit by 32% of ${:,.2f} per \
month instead of ${:,.2f} if you chose to retire at 66. Increasing \
your retirement age will adjust the amount of social security \
benefits that you are able to obtain. Social security benefits \
increase by up to 132% the longer you work.".format(advice.plan.spendable_income + (advice.plan.spendable_income * .32), advice.plan.spendable_income)
# Life Expectancy
def get_manually_adjusted_age(advice):
return 'Your retirement age has been updated. \
Let us know if anything else changes in your wellbeing \
profile by clicking on the life expectancy bubble.'
def get_smoking_yes(advice):
return 'You could improve your life expectancy score \
by quitting smoking. Do you intend to quit smoking in \
the near future? Yes/No'
def get_quitting_smoking(advice):
# {formula = (Current Age – 18)/42]*7.7 or 7.3 years}
formula = ((advice.plan.client.age - 18) / 42) * 7.7
return "We will add this to your life expectancy. \
Based on your age we will add {} years to your life expectancy.".format(formula)
def get_smoking_no(advice):
return "By not smoking you're already increasing your \
life expectancy by 7 years."
def get_exercise_only(advice):
return "Thanks for telling us about your exercise. Exercise \
does impact your life expectancy. Regular exercise for at \
least 20 minutes each day 5 times a week increases your \
life expectancy by up to 3.2 years."
def get_weight_and_height_only(advice):
return "Thanks for telling us your weight and height. \
These combined details help us better understand your life expectancy."
def get_combination_of_more_than_one_entry_but_not_all(advice):
return "Thanks for providing more wellbeing information. This helps us \
better understand your life expectancy. By completing all of the \
details we can get an even more accurate understanding."
def get_all_wellbeing_entries(advice):
return "Thanks for providing your wellbeing information. This gives us \
the big picture and an accurate understanding of your life expectancy."
# Risk Slider
def get_protective_move(advice):
# TODO: Need to add risk and amounts
"""
This might reduce the returns from your portfolio or increase \
the amount you need to contribute from your paycheck each month \
from <previous amount> to <new amount>
"""
risk = round(advice.plan.recommended_risk, 2)
if risk == 1.0:
risk = 100
elif risk == 0.9:
risk = 90
elif risk == 0.8:
risk = 80
elif risk == 0.7:
risk = 70
elif risk == 0.6:
risk = 60
elif risk == 0.5:
risk == 50
elif risk == 0.4:
risk == 40
elif risk == 0.3:
risk = 30
elif risk == 0.2:
risk = 20
elif risk == 0.1:
risk = 10
else:
risk = str(risk)[2:]
return "I can see you have adjusted your risk profile to be more \
protective. We base your risk profile on the risk questionnaire \
you completed and recommended {}. By adjusting the slider you \
change the asset allocation in your retirement goal.".format(str(risk))
def get_dynamic_move(advice):
# TODO: Need to add risk and amounts
"""
This might increase the returns from your portfolio and decrease the amount \
you need to contribute from your paycheck each month from <previous amount> \
to <new amount>
"""
risk = round(advice.plan.recommended_risk, 2)
if risk == 1.0:
risk = 100
elif risk == 0.9:
risk = 90
elif risk == 0.8:
risk = 80
elif risk == 0.7:
risk = 70
elif risk == 0.6:
risk = 60
elif risk == 0.5:
risk == 50
elif risk == 0.4:
risk == 40
elif risk == 0.3:
risk = 30
elif risk == 0.2:
risk = 20
elif risk == 0.1:
risk = 10
else:
risk = str(risk)[2:]
return "I can see you have adjusted your risk profile to be more dynamic. \
We base your risk profile on the risk questionnaire you completed and \
recommended {}. By adjusting the slider you change the asset allocation \
in your retirement goal.\nYou will be taking more risk.".format(str(risk))
# Contributions / Spending
def get_increase_spending_decrease_contribution(advice, contrib, income):
# TODO: Need to add $X and $Y calculations, max_contributions needs to come in
# if advice.plan.client.account.account_type == constants.ACCOUNT_TYPE_401K or \
# advice.plan.client.account.account_type == constants.ACCOUNT_TYPE_ROTH401K:
# # [If 401K we need to remember here that for a person under 50 the
# # maximum contribution amount is $18,000 per annum and $24,000
# # if they are over 50]
# if advice.plan.client.age < 50:
# max_contribution = 18000
# else:
# max_contribution = 24000
rv = "Hey big spender! I can see you want to spend a bit more. \
If you decreased your spending by ${:,.2f} a week, you could increase your\
retirement income by ${:,.2f} a week.".format(contrib, income)
if advice.plan.client.employment_status == constants.EMPLOYMENT_STATUS_FULL_TIME or \
advice.plan.client.employment_status == constants.EMPLOYMENT_STATUS_PART_TIME:
rv += " Your employer will match these contributions making it easier to reach your goal."
return rv
def get_increase_contribution_decrease_spending(advice, contrib, income):
return "Well done, by increasing your retirement contributions to ${:,.2f} \
a month, you have increased your retirement income by ${:,.2f} a week.".format(contrib, income)
def get_increase_spending_decrease_contribution_again(advice, contrib, income):
# TODO: Need to add $X and $Y calculations
return "Are you sure you need to increase your spending again and reduce your \
retirement contributions? Just think, if your contributions stayed \
at ${:,.2f} a month you would be ${:,.2f} a week better off in retirement.".format(contrib, income)
def get_off_track_item_adjusted_to_on_track(advice):
years = advice.plan.retirement_age - advice.plan.client.age
return "Well done, by adjusting your details your retirement goal is now on track.\n\
We want to make sure our advice keeps you on track so that when you retire \
in {} there are no nasty surprises. If you would like to change or see the \
impact of any of your choices you can make changes to your details on \
this dashboard.".format(datetime.now().date().year + years)
def get_on_track_item_adjusted_to_off_track(advice):
return "Uh oh, you are now off track to achieve your retirement goal. \
We are here to give you’re the advice to ensure you get on track. \
You may want to reconsider the changes you have made to your details \
to get your retirement goal back on track."
| [
"[email protected]"
] | |
1010a87e378223fd5275560d3cf5ea3eb1d65f07 | 017f02454cbb5616a9aa23e3ce76f84832378ec2 | /inferencia/task/pose_estimation/pose_estimation_2d/visualization/pose_estimation_2d_visualizer_factory.py | 451d1b7a92d7c0e6f4d200bafdc3e7bc2a2a02e1 | [
"Apache-2.0"
] | permissive | hampen2929/inferencia | a6e0f0b25abe95c3690ddfc7a225d4a4bdc2cb10 | c83563ff31d47cd441bb8ac3072df32a7fded0ee | refs/heads/main | 2023-08-18T13:53:32.882725 | 2021-09-18T12:15:52 | 2021-09-18T12:15:52 | 379,299,225 | 0 | 2 | Apache-2.0 | 2021-09-18T12:15:53 | 2021-06-22T14:30:36 | Jupyter Notebook | UTF-8 | Python | false | false | 813 | py | from .pose_estimation_2d_visualizer_name import PoseEstimation2DVisualizerName
from ..label.pose_estimation_2d_label_factory import PoseEstimation2DLabelFactory
class PoseEstimation2DVisualizerFactory():
def create(visualizer_name="PoseVisualizer",
label_name="COCOKeyPointLabel"):
if visualizer_name == PoseEstimation2DVisualizerName.pose_visualizer.value:
from .visualization.pose_vilualizer import PoseVilualizer
pose_label = PoseEstimation2DLabelFactory.create(
label_name=label_name)
pose_visualizer = PoseVilualizer(body_edges=pose_label.body_edges)
return pose_visualizer
else:
msg = "{} is not implemented".format(
visualizer_name)
raise NotImplementedError(msg)
| [
"[email protected]"
] | |
f9fade661402627c5a7c12936bed53fbd8d25454 | 50e90ce3870a66395aa2f4abd6a03c7e7de811e6 | /mishamovie/pipeline_steps/combine_frames.py | f92b81a9ca8a11193857ab424569e84310ab838d | [] | no_license | jgc128/mishamovie | c8dd960756d1cef7504d6060d1d7ceca89869c91 | ce8864fb311bff4c0936046a7efe121b5e5f8a3b | refs/heads/main | 2023-06-08T21:28:30.605756 | 2021-07-04T20:59:32 | 2021-07-04T20:59:32 | 361,487,351 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,388 | py | """
This script trains a simple model Cats and Dogs dataset and saves it in the SavedModel format
"""
import argparse
import subprocess
def parse_args():
parser = argparse.ArgumentParser(description='Split video into frames')
parser.add_argument('--input_dir', help='Input dir', required=True)
parser.add_argument('--output_dir', help='Output dir', required=True)
parser.add_argument('--output_filename', help='Output file name', required=True)
parser.add_argument('--input_name_template', default='frame_%5d.png', help='Input name template', required=False)
parser.add_argument('--fps', default=30, type=int, help='Frames per second', required=False)
args = parser.parse_args()
return args
def main():
# TODO: fmpeg -i face_close_aged_long.mp4 -filter "minterpolate='fps=120'" zzzz3.mp4
# https://superuser.com/a/1185430
# https://github.com/dthpham/butterflow
args = parse_args()
print(args)
input_filename = f'{args.input_dir}/{args.input_name_template}'
output_filename = f'{args.output_dir}/{args.output_filename}'
cmd = [
'ffmpeg', '-y', '-framerate', str(args.fps), '-i', input_filename,
'-c:v', 'libx264', '-vf', f'fps={args.fps},pad=ceil(iw/2)*2:ceil(ih/2)*2', '-pix_fmt', 'yuv420p',
output_filename
]
subprocess.run(cmd, check=True)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
9112a8d3de06671acf5e9fded056dc27c0c8b4a3 | 55726b4940cec0e9df9ba90ab69b27b81c283740 | /DjangoBlog/admin_site.py | d90ec5e4ee94b395af46df4d557eb97ac712a51a | [
"MIT"
] | permissive | zlaiyyf/DjangoBlog | fe655c62f74e929cd874d095cc2f8bf48739bd0d | ccb67c9f08a9b6b8ca65828fece34cda89135187 | refs/heads/master | 2022-12-27T05:06:27.578712 | 2020-10-11T07:47:46 | 2020-10-11T07:47:46 | 264,558,604 | 1 | 0 | MIT | 2020-05-17T01:09:08 | 2020-05-17T01:09:07 | null | UTF-8 | Python | false | false | 2,014 | py | #!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: liangliangyy
@license: MIT Licence
@contact: [email protected]
@site: https://www.lylinux.net/
@software: PyCharm
@file: admin_site.py
@time: 2018/1/7 上午2:21
"""
from django.contrib.admin import AdminSite
from DjangoBlog.utils import get_current_site
from django.contrib.sites.admin import SiteAdmin
from django.contrib.admin.models import LogEntry
from django.contrib.sites.models import Site
from DjangoBlog.logentryadmin import LogEntryAdmin
from blog.admin import *
from accounts.admin import *
from oauth.admin import *
from servermanager.admin import *
from comments.admin import *
from owntracks.admin import *
class DjangoBlogAdminSite(AdminSite):
site_header = 'DjangoBlog administration'
site_title = 'DjangoBlog site admin'
def __init__(self, name='admin'):
super().__init__(name)
def has_permission(self, request):
return request.user.is_superuser
# def get_urls(self):
# urls = super().get_urls()
# from django.urls import path
# from blog.views import refresh_memcache
#
# my_urls = [
# path('refresh/', self.admin_view(refresh_memcache), name="refresh"),
# ]
# return urls + my_urls
admin_site = DjangoBlogAdminSite(name='admin')
admin_site.register(Article, ArticlelAdmin)
admin_site.register(Category, CategoryAdmin)
admin_site.register(Tag, TagAdmin)
admin_site.register(Links, LinksAdmin)
admin_site.register(SideBar, SideBarAdmin)
admin_site.register(BlogSettings, BlogSettingsAdmin)
admin_site.register(commands, CommandsAdmin)
admin_site.register(EmailSendLog, EmailSendLogAdmin)
admin_site.register(BlogUser, BlogUserAdmin)
admin_site.register(Comment, CommentAdmin)
admin_site.register(OAuthUser, OAuthUserAdmin)
admin_site.register(OAuthConfig, OAuthConfigAdmin)
admin_site.register(OwnTrackLog, OwnTrackLogsAdmin)
admin_site.register(Site, SiteAdmin)
admin_site.register(LogEntry, LogEntryAdmin)
| [
"[email protected]"
] | |
3ecb1f5f3ec4c2e5ce2a71a98e9fe46cea17d818 | 9130bdbd90b7a70ac4ae491ddd0d6564c1c733e0 | /venv/lib/python3.8/site-packages/cryptography/hazmat/primitives/keywrap.py | 8ca935cafd0f6662b8152910cd075ef54b4b9ba2 | [] | no_license | baruwaa12/Projects | 6ca92561fb440c63eb48c9d1114b3fc8fa43f593 | 0d9a7b833f24729095308332b28c1cde63e9414d | refs/heads/main | 2022-10-21T14:13:47.551218 | 2022-10-09T11:03:49 | 2022-10-09T11:03:49 | 160,078,601 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96 | py | /home/runner/.cache/pip/pool/2f/84/6a/ccb5454b00837ef6351bc65055c9fc4ab3ccb02f3c73ed14ffceb09910 | [
"[email protected]"
] | |
d6ae857b950288a40f300ca27e242e60df1df9a0 | 4f807eb45da63a633f32425908a4acf19462d96f | /python/src/yatzy/YatzyTest.py | 0b2bf06d8f872a60d16e9e5cdc496e24a2794c6a | [] | no_license | mebusw/Test-Driven-Development | 580c3f31ee0f406afa8d7761bf82acd67cfcd166 | 7a49f2615a78a1cedbb909e60e0232e5e1467287 | refs/heads/master | 2021-01-22T06:32:07.448971 | 2017-02-02T04:56:40 | 2017-02-02T04:56:40 | 5,836,643 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,756 | py | """
The game of yatzy is a simple dice game. Each player
rolls five six-sided dice. The player places the roll in
a category, such as ones, twos, fives, pair, two pairs
etc (see below).
If the roll is compatible with the category, the player
gets a score for the roll according to the rules. If the
roll is not compatible with the category, the player scores
zero for the roll.
For example, if a player rolls 5,6,5,5,2 and scores the
dice in the fives category they would score 15 (three fives).
Your task is to score a GIVEN roll in a GIVEN category.
You do NOT have to program the random dice rolling.
You do NOT have to program re-rolls (as in the real game).
You do NOT play by letting the computer choose the highest
scoring category for a given roll.
Yatzy Categories and Scoring Rules
==================================
Chance:
The player scores the sum of all dice,
no matter what they read.
For example,
1,1,3,3,6 placed on "chance" scores 14 (1+1+3+3+6)
4,5,5,6,1 placed on "chance" scores 21 (4+5+5+6+1)
Yatzy:
If all dice have the same number,
the player scores 50 points.
For example,
1,1,1,1,1 placed on "yatzy" scores 50
5,5,5,5,5 placed on "yatzy" scores 50
1,1,1,2,1 placed on "yatzy" scores 0
Ones, Twos, Threes, Fours, Fives, Sixes:
The player scores the sum of the dice that reads one,
two, three, four, five or six, respectively.
For example,
1,1,2,4,4 placed on "fours" scores 8 (4+4)
2,3,2,5,1 placed on "twos" scores 4 (2+2)
3,3,3,4,5 placed on "ones" scores 0
Pair:
If exactly two dice have the same value then
the player scores the sum of the two highest matching dice.
For example, when placed on "pair"
3,3,3,4,4 scores 8 (4+4)
1,1,6,2,6 scores 12 (6+6)
3,3,3,4,1 scores 0
3,3,3,3,1 scores 0
Two pairs:
If exactly two dice have the same value and exactly
two dice have a different value then the
player scores the sum of these four dice.
For example, when placed on "two pairs"
1,1,2,3,3 scores 8 (1+1+3+3)
1,1,2,3,4 scores 0
1,1,2,2,2 scores 0
Three of a kind:
If there are exactly three dice with the same number
then the player scores the sum of these dice.
For example, when placed on "three of a kind"
3,3,3,4,5 scores 9 (3+3+3)
3,3,4,5,6 scores 0
3,3,3,3,1 scores 0
Four of a kind:
If there are exactly four dice with the same number
then the player scores the sum of these dice.
For example, when placed on "four of a kind"
2,2,2,2,5 scores 8 (2+2+2+2)
2,2,2,5,5 scores 0
2,2,2,2,2 scores 0
Small straight:
When placed on "small straight", if the dice read
1,2,3,4,5, the player scores 15 (the sum of all the dice).
Large straight:
When placed on "large straight", if the dice read
2,3,4,5,6, the player scores 20 (the sum of all the dice).
Full house:
If the dice are two of a kind and three of a different kind
then the player scores the sum of all five dice.
For example, when placed on "full house"
1,1,2,2,2 scores 8 (1+1+2+2+2)
2,2,3,3,4 scores 0
4,4,4,4,4 scores 0
"""
import unittest
from itertools import groupby
class Game(object):
@staticmethod
def chance(*dice):
return sum(dice)
@staticmethod
def yatzy(*dice):
return 50 if all(d == dice[0] for d in dice) else 0
@staticmethod
def _single(n):
return lambda *dice: n * dice.count(n)
def __init__(self):
self.sixes = Game._single(6)
self.fives = Game._single(5)
self.fours = Game._single(4)
self.threes = Game._single(3)
self.twos = Game._single(2)
self.ones = Game._single(1)
def pair(self, *dice):
for b in self._buckets(dice):
if b[1] == 2:
return b[0] * 2
return 0
def _buckets(self, dice):
g = groupby(sorted(dice, reverse=True), lambda x: x)
buckets = [(m, len(list(n))) for m, n in g]
buckets = sorted(buckets, key=lambda x: x[1], reverse=True)
return buckets
def three_kind(self, *dice):
b = self._buckets(dice)
if b[0][1] == 3:
return b[0][0] * 3
return 0
def four_kind(self, *dice):
b = self._buckets(dice)
if b[0][1] == 4:
return b[0][0] * 4
return 0
def two_pairs(self, *dice):
b = self._buckets(dice)
if b[0][1] == 2 and b[1][1] == 2:
return b[0][0] * 2 + b[1][0] * 2
return 0
def straight(self, *dice):
if all(z[0] == z[1] + 1 for z in zip(dice[1:], dice[:-1])):
return sum(dice)
return 0
def full_house(self, *dice):
b = self._buckets(dice)
if b[0][1] == 3 and b[1][1] == 2:
return sum(dice)
return 0
class YatzyTest(unittest.TestCase):
def setUp(self):
pass
def test_chance(self):
self.assertEquals(1 + 1 + 3 + 3 + 6, Game.chance(1, 1, 3, 3, 6))
self.assertEquals(4 + 5 + 5 + 6 + 1, Game.chance(4, 5, 5, 6, 1))
def test_yatzy(self):
self.assertEquals(50, Game.yatzy(1, 1, 1, 1, 1))
self.assertEquals(50, Game.yatzy(5, 5, 5, 5, 5))
self.assertEquals(0, Game.yatzy(1, 1, 1, 2, 1))
def test_ones(self):
self.assertEquals(4 + 4, Game().fours(1, 1, 2, 4, 4))
self.assertEquals(2 + 2, Game().twos(2, 3, 2, 5, 1))
self.assertEquals(0, Game().ones(3, 3, 3, 4, 5))
def test_pair(self):
self.assertEquals(4 + 4, Game().pair(3, 3, 3, 4, 4))
self.assertEquals(6 + 6, Game().pair(1, 1, 6, 2, 6))
self.assertEquals(0, Game().pair(3, 3, 3, 4, 1))
self.assertEquals(0, Game().pair(3, 3, 3, 3, 1))
def test_two_pairs(self):
self.assertEquals(1 + 1 + 3 + 3, Game().two_pairs(1, 1, 2, 3, 3))
self.assertEquals(0, Game().two_pairs(1, 1, 2, 3, 4))
self.assertEquals(0, Game().two_pairs(1, 1, 2, 2, 2))
def test_three_of_a_kind(self):
self.assertEquals(3 + 3 + 3, Game().three_kind(3, 3, 3, 4, 5))
self.assertEquals(0, Game().three_kind(3, 3, 4, 5, 6))
self.assertEquals(0, Game().three_kind(3, 3, 3, 3, 1))
def test_four_of_a_kind(self):
self.assertEquals(2 + 2 + 2 + 2, Game().four_kind(2, 2, 2, 2, 5))
self.assertEquals(0, Game().four_kind(2, 2, 2, 5, 5))
self.assertEquals(0, Game().four_kind(2, 2, 2, 2, 2))
def test_straight(self):
self.assertEquals(1 + 2 + 3 + 4 + 5, Game().straight(1, 2, 3, 4, 5))
self.assertEquals(2 + 3 + 4 + 5 + 6, Game().straight(2, 3, 4, 5, 6))
def test_full_house(self):
self.assertEquals(1 + 1 + 2 + 2 + 2, Game().full_house(1, 1, 2, 2, 2))
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testName']
unittest.main()
| [
"[email protected]"
] | |
4c5e15fd9822cbc0c71851e74db43be6f4bfc722 | 1626e16760c9c5b5dc9bd7c345871c716d5ffd99 | /Problems/2400_2499/2475_Number_of_Unequal_Triplets_in_Array/Project_Python3/Number_of_Unequal_Triplets_in_Array.py | 4242af6250379a0c5a304c43d89f7b0342a51492 | [] | no_license | NobuyukiInoue/LeetCode | 94ddb19e63cb8d0775cdc13f311fe90c87a1d718 | 3f0ffd519404165fd1a735441b212c801fd1ad1e | refs/heads/master | 2023-09-01T07:38:50.939942 | 2023-08-23T09:51:17 | 2023-08-23T09:51:17 | 158,100,912 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,432 | py | # coding: utf-8
import collections
import os
import sys
import time
from typing import List, Dict, Tuple
class Solution:
def unequalTriplets(self, nums: List[int]) -> int:
# 35ms - 71ms
trips = pairs = 0
cnts = collections.Counter()
for i, num in enumerate(nums):
trips += pairs - cnts[num] * (i - cnts[num])
pairs += i - cnts[num]
cnts[num] += 1
return trips
def main():
argv = sys.argv
argc = len(argv)
if argc < 2:
print("Usage: python {0} <testdata.txt>".format(argv[0]))
exit(0)
if not os.path.exists(argv[1]):
print("{0} not found...".format(argv[1]))
exit(0)
testDataFile = open(argv[1], "r")
lines = testDataFile.readlines()
for temp in lines:
temp = temp.strip()
if temp == "":
continue
print("args = {0}".format(temp))
loop_main(temp)
# print("Hit Return to continue...")
# input()
def loop_main(temp):
flds = temp.replace("[","").replace("]","").replace(", ",",").rstrip()
nums = [int(n) for n in flds.split(",")]
print("nums = {0}".format(nums))
sl = Solution()
time0 = time.time()
result = sl.unequalTriplets(nums)
time1 = time.time()
print("result = {0:d}".format(result))
print("Execute time ... : {0:f}[s]\n".format(time1 - time0))
if __name__ == "__main__":
main()
| [
"[email protected]"
] | |
d2ffb8597a0d04e3ae245321f7dce967753eb0a2 | 35580ddab92d76862240649bbb91b8e45f330fb0 | /src/srctools/vpk.py | 84789b56fd842cb84326bbf8ea05220628e469d0 | [
"MIT"
] | permissive | TeamSpen210/srctools | 954328566e3ea25e1b88e73c55c93036b133cd76 | 3969e869673e3c76b4bc663d1f73c56a3585f228 | refs/heads/master | 2023-08-28T23:04:28.849165 | 2023-08-26T06:48:44 | 2023-08-26T06:48:44 | 60,130,807 | 44 | 18 | NOASSERTION | 2023-06-18T22:28:05 | 2016-05-31T23:36:26 | Python | UTF-8 | Python | false | false | 25,735 | py | """Classes for reading and writing Valve's VPK format, version 1."""
from typing import IO, Dict, Final, Iterable, Iterator, List, Optional, Tuple, Type, Union
from enum import Enum
from types import TracebackType
import operator
import os
import struct
import attrs
from srctools.binformat import EMPTY_CHECKSUM, checksum, struct_read
__all__ = [
'VPK_SIG', 'DIR_ARCH_INDEX', 'OpenModes',
'script_write', 'get_arch_filename',
'FileInfo', 'VPK',
]
VPK_SIG: Final = 0x55aa1234 #: The first byte of VPK files.
DIR_ARCH_INDEX: Final = 0x7fff #: The file index used for the ``_dir`` file.
FileName = Union[str, Tuple[str, str], Tuple[str, str, str]]
class OpenModes(Enum):
"""Modes for opening VPK files."""
READ = 'r'
WRITE = 'w'
APPEND = 'a'
@property
def writable(self) -> bool:
"""Check if this mode allows modifying the VPK."""
return self.value in 'wa'
def iter_nullstr(file: IO[bytes]) -> Iterator[str]:
"""Read a null-terminated ASCII string from the file.
This continuously yields strings, with empty strings
indicting the end of a section.
"""
chars = bytearray()
while True:
char = file.read(1)
if char == b'\x00':
string = chars.decode('ascii', 'surrogateescape')
chars.clear()
if string == ' ': # Blank strings are saved as ' '
yield ''
elif string == '':
return # Actual blanks end the array.
else:
yield string
elif char == b'':
raise Exception(f'Reached EOF without null-terminator in {bytes(chars)!r}!')
else:
chars.extend(char)
def _write_nullstring(file: IO[bytes], string: str) -> None:
"""Write a null-terminated ASCII string back to the file."""
if string:
file.write(string.encode('ascii', 'surrogateescape') + b'\x00')
else:
# Empty strings are written as a space.
file.write(b' \x00')
def get_arch_filename(prefix: str = 'pak01', index: Optional[int] = None) -> str:
"""Generate the name for a VPK file.
Prefix is the name of the file, usually 'pak01'.
index is the index of the data file, or None for the directory.
"""
if index is None:
return prefix + '_dir.vpk'
else:
return f'{prefix}_{index:>03}.vpk'
def _get_file_parts(value: FileName, relative_to: str = '') -> Tuple[str, str, str]:
"""Get folder, name, ext parts from a string/tuple.
Possible arguments:
'fold/ers/name.ext'
('fold/ers', 'name.ext')
('fold/ers', 'name', 'ext')
"""
path: str
filename: str
ext: str
if isinstance(value, str):
path, filename = os.path.split(value)
ext = ''
elif len(value) == 2:
path, filename = value # type: ignore # len() can't narrow.
ext = ''
else:
path, filename, ext = value # type: ignore # len() can't narrow.
if not ext and '.' in filename:
filename, ext = filename.rsplit('.', 1)
if relative_to:
path = os.path.relpath(path, relative_to)
# Strip '/' off the end, and './' from the beginning.
path = os.path.normpath(path).replace('\\', '/').rstrip('/')
# Special case - empty path gets returned as '.'...
if path == '.':
path = ''
return path, filename, ext
def _join_file_parts(path: str, filename: str, ext: str) -> str:
"""Join together path components to the full path.
Any of the segments can be blank, to skip them.
"""
return f"{path}{'/' if path else ''}{filename}{'.' if ext else ''}{ext}"
def _check_is_ascii(value: str) -> bool:
"""VPK filenames must be ascii, it doesn't store or care about encoding.
Allow the surrogateescape bytes also, so roundtripping existing VPKs is
allowed.
"""
for char in value:
# Do straightforward string comparison, only call ord for the surrogate-escape bytes
# which can't be direct constants.
if char >= '\x80' and not (0xDC80 <= ord(char) <= 0xDCFF):
return False
return True
@attrs.define(eq=False)
class FileInfo:
"""Represents a file stored inside a VPK.
Do not call the constructor, it is only meant for VPK's use.
"""
vpk: 'VPK'
dir: str = attrs.field(on_setattr=attrs.setters.frozen)
_filename: str = attrs.field(on_setattr=attrs.setters.frozen)
ext: str = attrs.field(on_setattr=attrs.setters.frozen)
crc: int
arch_index: Optional[int] # pack_01_000.vpk file to use, or None for _dir.
offset: int # Offset into the archive file, including directory data if in _dir
arch_len: int # Number of bytes in archive files
start_data: bytes # The bytes saved into the directory header
@property
def filename(self) -> str:
"""The full filename for this file."""
return _join_file_parts(self.dir, self._filename, self.ext)
name = filename
def __repr__(self) -> str:
return f'<VPK File: "{_join_file_parts(self.dir, self._filename, self.ext)}">'
@property
def size(self) -> int:
"""The total size of this file."""
return self.arch_len + len(self.start_data)
def read(self) -> bytes:
"""Return the contents for this file."""
if self.arch_len:
if self.arch_index is None:
return self.start_data + self.vpk.footer_data[self.offset: self.offset + self.arch_len]
else:
arch_file = get_arch_filename(self.vpk.file_prefix, self.arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'rb') as data:
data.seek(self.offset)
return self.start_data + data.read(self.arch_len)
else:
return self.start_data
def verify(self) -> bool:
"""Check this file matches the checksum."""
chk = checksum(self.start_data)
if self.arch_len:
if self.arch_index is None:
chk = checksum(
self.vpk.footer_data[self.offset: self.offset + self.arch_len],
chk
)
else:
arch_file = get_arch_filename(self.vpk.file_prefix, self.arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'rb') as data:
data.seek(self.offset)
chk = checksum(
data.read(self.arch_len),
chk,
)
return chk == self.crc
def write(self, data: bytes, arch_index: Optional[int] = None) -> None:
"""Replace this file with the given byte data.
arch_index is the pak_01_000 file to put data into (or None for _dir).
If this file already exists in the VPK, the old data is not removed.
For this reason VPK writes should be done once per file if possible.
"""
if not self.vpk.mode.writable:
raise ValueError(f"VPK mode {self.vpk.mode.name} does not allow writing!")
# Split the file based on a certain limit.
new_checksum = checksum(data)
if new_checksum == self.crc:
return # Same data, don't do anything.
self.crc = new_checksum
self.start_data = data[:self.vpk.dir_limit]
arch_data = data[self.vpk.dir_limit:]
self.arch_len = len(arch_data)
if self.arch_len:
self.arch_index = arch_index
arch_file = get_arch_filename(self.vpk.file_prefix, arch_index)
with open(os.path.join(self.vpk.folder, arch_file), 'ab') as file:
self.offset = file.seek(0, os.SEEK_END)
file.write(arch_data)
else:
# Only stored in the main index
self.arch_index = None
self.offset = 0
class VPK:
"""Represents a VPK file set in a directory."""
folder: str
"""The directory the VPK is located in, used to find the numeric files."""
file_prefix: str
"""The VPK filename, without ``_dir.vpk``."""
# fileinfo[extension][directory][filename]
_fileinfo: Dict[str, Dict[str, Dict[str, FileInfo]]]
mode: OpenModes
"""How the file was opened.
- Read mode, the file will not be modified and it must already exist.
- Write mode will create the directory if needed.
- Append mode will also create the directory, but not wipe the file.
"""
dir_limit: Optional[int]
"""
The maximum amount of data for files saved to the dir file.
- :external:py:data:`None`: No limit.
- ``0``: Save all to a data file.
"""
footer_data: bytes
"""
The block of data after the header, which contains the file data for files stored in the
``_dir`` file, not numeric files.
"""
version: int
"""The VPK version, 1 or 2."""
def __init__(
self,
dir_file: Union[str, 'os.PathLike[str]'],
*,
mode: Union[OpenModes, str] = 'r',
dir_data_limit: Optional[int] = 1024,
version: int = 1,
) -> None:
"""Create a VPK file.
:param dir_file: The path to the directory file. This must end in ``_dir.vpk``.
:param mode: The (r)ead, (w)rite or (a)ppend mode.
:param dir_data_limit: The maximum amount of data to save in the dir file.
:param version: The desired version if the file is not read.
"""
if version not in (1, 2):
raise ValueError(f"Invalid version ({version}) - must be 1 or 2!")
self.folder = self.file_prefix = ''
# Calls the property which sets the above correctly and checks the type.
self.path = dir_file
# fileinfo[extension][directory][filename]
self._fileinfo = {}
self.mode = OpenModes(mode)
self.dir_limit = dir_data_limit
self.footer_data = b''
self.version = version
self.load_dirfile()
def _check_writable(self) -> None:
"""Verify that this is writable."""
if not self.mode.writable:
raise ValueError(f"VPK mode {self.mode.name} does not allow writing!")
@property
def path(self) -> Union[str, 'os.PathLike[str]']: # TODO: Incorrect, Mypy doesn't have 2-type properties.
"""The filename of the directory VPK file.
This can be assigned to set :py:attr:`folder` and :py:attr:`file_prefix`.
"""
return os.path.join(self.folder, self.file_prefix + '_dir.vpk')
@path.setter
def path(self, path: Union[str, 'os.PathLike[str]']) -> None:
"""Set the location and folder from the directory VPK file."""
folder, filename = os.path.split(path)
if not filename.endswith('_dir.vpk'):
raise Exception('Must create with a _dir VPK file!')
self.folder = folder
self.file_prefix = filename[:-8]
def load_dirfile(self) -> None:
"""Read in the directory file to get all filenames. This erases all changes in the file."""
if self.mode is OpenModes.WRITE:
# Erase the directory file, we ignore current contents.
open(self.path, 'wb').close()
self.version = 1
return
try:
dirfile = open(self.path, 'rb')
except FileNotFoundError:
if self.mode is OpenModes.APPEND:
# No directory file - generate a blank file.
open(self.path, 'wb').close()
self.version = 1
return
else:
raise # In read mode, don't overwrite and error when reading.
with dirfile:
vpk_sig, version, tree_length = struct_read('<III', dirfile)
if vpk_sig != VPK_SIG:
raise ValueError('Bad VPK directory signature!')
if version not in (1, 2):
raise ValueError(f"Bad VPK version {self.version}!")
self.version = version
if version >= 2:
(
data_size,
ext_md5_size,
dir_md5_size,
sig_size,
) = struct_read('<4I', dirfile)
header_len = dirfile.tell() + tree_length
self._fileinfo.clear()
entry = struct.Struct('<IHHIIH')
# Read directory contents
# These are in a tree of extension, directory, file. '' terminates a part.
for ext in iter_nullstr(dirfile):
try:
ext_dict = self._fileinfo[ext]
except KeyError:
ext_dict = self._fileinfo[ext] = {}
for directory in iter_nullstr(dirfile):
try:
dir_dict = ext_dict[directory]
except KeyError:
dir_dict = ext_dict[directory] = {}
for file in iter_nullstr(dirfile):
crc, index_len, arch_ind, offset, arch_len, end = entry.unpack(dirfile.read(entry.size))
if arch_ind == DIR_ARCH_INDEX:
arch_ind = None
if arch_len == 0:
offset = 0
if end != 0xffff:
raise Exception(
f'"{_join_file_parts(directory, file, ext)}" has bad terminator! '
f'{(crc, index_len, arch_ind, offset, arch_len, end)}'
)
dir_dict[file] = FileInfo(
self,
directory,
file,
ext,
crc,
arch_ind,
offset,
arch_len,
dirfile.read(index_len),
)
# 1 for the ending b'' section
if dirfile.tell() + 1 == header_len:
dirfile.read(1) # Skip null byte.
break
self.footer_data = dirfile.read()
def write_dirfile(self) -> None:
"""Write the directory file with the changes. This must be performed after writing to the VPK."""
self._check_writable()
if self.version > 1:
raise NotImplementedError("Can't write V2 VPKs!")
# We don't know how big the directory section is, so we first write the directory,
# then come back and overwrite the length value.
with open(self.path, 'wb') as file:
file.write(struct.pack('<III', VPK_SIG, self.version, 0))
header_len = file.tell()
key_getter = operator.itemgetter(0)
# Write in sorted order - not required, but this ensures multiple
# saves are deterministic.
for ext, folders in sorted(self._fileinfo.items(), key=key_getter):
if not folders:
continue
_write_nullstring(file, ext)
for folder, files in sorted(folders.items(), key=key_getter):
if not files:
continue
_write_nullstring(file, folder)
for filename, info in sorted(files.items(), key=key_getter):
_write_nullstring(file, filename)
if info.arch_index is None:
arch_ind = DIR_ARCH_INDEX
else:
arch_ind = info.arch_index
file.write(struct.pack(
'<IHHIIH',
info.crc,
len(info.start_data),
arch_ind,
info.offset,
info.arch_len,
0xffff,
))
file.write(info.start_data)
# Each block is terminated by an empty null-terminated
# string -> one null byte.
file.write(b'\x00')
file.write(b'\x00')
file.write(b'\x00')
# Calculate the length of the header..
dir_len = file.tell() - header_len
file.write(self.footer_data)
# Write the directory size now we know it.
file.seek(struct.calcsize('<II')) # Skip signature and version
file.write(struct.pack('<I', dir_len))
def __enter__(self) -> 'VPK':
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
exc_trace: Optional[TracebackType],
) -> None:
"""When exiting a context sucessfully, the index will be saved."""
if exc_type is None and self.mode.writable:
self.write_dirfile()
def __getitem__(self, item: FileName) -> FileInfo:
"""Get the FileInfo object for a file.
Possible arguments:
vpk['folders/name.ext']
vpk['folders', 'name.ext']
vpk['folders', 'name', 'ext']
"""
path, filename, ext = _get_file_parts(item)
try:
return self._fileinfo[ext][path][filename]
except KeyError:
raise KeyError(
f'No file "{_join_file_parts(path, filename, ext)}"!'
) from None
def __delitem__(self, item: FileName) -> None:
"""Delete a file.
Possible arguments:
del vpk['folders/name.ext']
del vpk['folders', 'name.ext']
del vpk['folders', 'name', 'ext']
"""
self._check_writable()
path, filename, ext = _get_file_parts(item)
try:
folders = self._fileinfo[ext]
files = folders[path]
files.pop(filename)
except KeyError:
raise KeyError(
f'No file "{_join_file_parts(path, filename, ext)}"!'
) from None
if not files:
# Clear this folder.
folders.pop(path)
if not folders:
# Clear extension too.
self._fileinfo.pop(ext)
def __iter__(self) -> Iterator[FileInfo]:
"""Yield all FileInfo objects."""
for folders in self._fileinfo.values():
for files in folders.values():
yield from files.values()
def filenames(self, ext: str = '', folder: str = '') -> Iterator[str]:
"""Yield filenames from this VPK.
If an extension or folder is specified, only files with this extension
or in this folder are returned.
"""
all_folders: Iterable[Dict[str, Dict[str, FileInfo]]]
if ext:
all_folders = [self._fileinfo.get(ext, {})]
else:
all_folders = self._fileinfo.values()
for folders in all_folders:
for subfolder, files in folders.items():
if not subfolder.startswith(folder):
continue
for info in files.values():
yield info.filename
def fileinfos(self, ext: str = '', folder: str = '') -> Iterator[FileInfo]:
"""Yield file info objects from this VPK.
If an extension or folder is specified, only files with this extension
or in this folder are returned.
"""
all_folders: Iterable[Dict[str, Dict[str, FileInfo]]]
if ext:
all_folders = [self._fileinfo.get(ext, {})]
else:
all_folders = self._fileinfo.values()
for folders in all_folders:
for subfolder, files in folders.items():
if not subfolder.startswith(folder):
continue
yield from files.values()
def __len__(self) -> int:
"""Returns the number of files we have."""
count = 0
for folders in self._fileinfo.values():
for files in folders.values():
count += len(files)
return count
def __contains__(self, item: FileName) -> bool:
"""Check if the specified filename is present in the VPK."""
path, filename, ext = _get_file_parts(item)
try:
return filename in self._fileinfo[ext][path]
except KeyError:
return False
def extract_all(self, dest_dir: str) -> None:
"""Extract the contents of this VPK to a directory."""
for folders in self._fileinfo.values():
for folder, files in folders.items():
os.makedirs(os.path.join(dest_dir, folder), exist_ok=True)
for info in files.values():
with open(os.path.join(dest_dir, info.filename), 'wb') as f:
f.write(info.read())
def new_file(self, filename: FileName, root: str = '') -> FileInfo:
"""Create the given file, making it empty by default.
If root is set, files are treated as relative to there,
otherwise the filename must be relative.
FileExistsError will be raised if the file is already present.
"""
self._check_writable()
path, name, ext = _get_file_parts(filename, root)
if not _check_is_ascii(path) or not _check_is_ascii(name) or not _check_is_ascii(ext):
raise ValueError(f'VPK filename {filename!r} must be ASCII format!')
try:
ext_infos = self._fileinfo[ext]
except KeyError:
ext_infos = self._fileinfo[ext] = {}
try:
dir_infos = ext_infos[path]
except KeyError:
dir_infos = ext_infos[path] = {}
if name in dir_infos:
raise FileExistsError(
f'Filename already exists! ({_join_file_parts(path, name, ext)!r})'
)
dir_infos[name] = info = FileInfo(
self,
path,
name,
ext,
EMPTY_CHECKSUM,
None, 0, 0, b'',
)
return info
def add_file(
self,
filename: FileName,
data: bytes,
root: str = '',
arch_index: Optional[int] = 0,
) -> None:
"""Add the given data to the VPK.
If root is set, files are treated as relative to there,
otherwise the filename must be relative.
arch_index is the pak01_xxx file to copy this to, if the length
is larger than self.dir_limit. If None it's written to the _dir file.
FileExistsError will be raised if the file is already present.
"""
self.new_file(filename, root).write(data, arch_index)
def add_folder(self, folder: str, prefix: str = '') -> None:
"""Write all files in a folder to the VPK.
If prefix is set, the folders will be written to that subfolder.
"""
self._check_writable()
if prefix:
prefix = prefix.replace('\\', '/')
for subfolder, _, filenames, in os.walk(folder):
# Prefix + subfolder relative to the folder.
# normpath removes '.' and similar values from the beginning
vpk_path = os.path.normpath(
os.path.join(
prefix,
os.path.relpath(subfolder, folder)
)
)
for filename in filenames:
with open(os.path.join(subfolder, filename), 'rb') as f:
self.add_file((vpk_path, filename), f.read())
def verify_all(self) -> bool:
"""Check all files have a correct checksum."""
return all(file.verify() for file in self)
def script_write(args: List[str]) -> None:
"""Create a VPK archive."""
if len(args) not in (1, 2):
raise ValueError("Usage: make_vpk.py [max_arch_mb] <folder>")
folder = args[-1]
vpk_name_base = folder.rstrip('\\/_dir')
if len(args) > 1:
arch_len = int(args[0]) * 1024 * 1024
else:
arch_len = 100 * 1024 * 1024
current_arch = 1
vpk_folder, vpk_name = os.path.split(vpk_name_base)
for filename in os.listdir(vpk_folder):
if filename.startswith(vpk_name + '_'):
print(f'removing existing "{filename}"')
os.remove(os.path.join(vpk_folder, filename))
with VPK(vpk_name_base + '_dir.vpk', mode='w') as vpk:
arch_filename = get_arch_filename(vpk_name_base, current_arch)
for subfolder, _, filenames, in os.walk(folder):
# normpath removes '.' and similar values from the beginning
vpk_path = os.path.normpath(os.path.relpath(subfolder, folder))
print(vpk_path + '/')
for filename in filenames:
print('\t' + filename)
with open(os.path.join(subfolder, filename), 'rb') as f:
vpk.add_file(
(vpk_path, filename),
f.read(),
arch_index=current_arch,
)
if os.path.exists(arch_filename) and os.stat(arch_filename).st_size > arch_len:
current_arch += 1
arch_filename = get_arch_filename(vpk_name_base, current_arch)
# This function requires accumulating a character at a time, parsing the VPK
# is very slow without a speedup.
_Py_iter_nullstr = _Cy_iter_nullstr = iter_nullstr
try:
from srctools._tokenizer import _VPK_IterNullstr as _Cy_iter_nullstr # type: ignore # noqa
iter_nullstr = _Cy_iter_nullstr
except ImportError:
pass
if __name__ == '__main__':
import sys
script_write(sys.argv[1:])
| [
"[email protected]"
] | |
a0734bf095a97365a24c7c0c3a07de02f71561a0 | a838d4bed14d5df5314000b41f8318c4ebe0974e | /sdk/automanage/azure-mgmt-automanage/azure/mgmt/automanage/models/_models.py | 4a02132654d4953ef71138b04fa109e55841e150 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | scbedd/azure-sdk-for-python | ee7cbd6a8725ddd4a6edfde5f40a2a589808daea | cc8bdfceb23e5ae9f78323edc2a4e66e348bb17a | refs/heads/master | 2023-09-01T08:38:56.188954 | 2021-06-17T22:52:28 | 2021-06-17T22:52:28 | 159,568,218 | 2 | 0 | MIT | 2019-08-11T21:16:01 | 2018-11-28T21:34:49 | Python | UTF-8 | Python | false | false | 26,908 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.core.exceptions import HttpResponseError
import msrest.serialization
class Resource(msrest.serialization.Model):
"""Resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Resource, self).__init__(**kwargs)
self.id = None
self.name = None
self.type = None
class TrackedResource(Resource):
"""The resource model definition for a ARM tracked top level resource.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(TrackedResource, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
self.location = kwargs['location']
class Account(TrackedResource):
"""Definition of the Automanage account.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
:param identity: The identity of the Automanage account.
:type identity: ~automanage_client.models.AccountIdentity
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'AccountIdentity'},
}
def __init__(
self,
**kwargs
):
super(Account, self).__init__(**kwargs)
self.identity = kwargs.get('identity', None)
class AccountIdentity(msrest.serialization.Model):
"""Identity for the Automanage account.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar principal_id: The principal id of Automanage account identity.
:vartype principal_id: str
:ivar tenant_id: The tenant id associated with the Automanage account.
:vartype tenant_id: str
:param type: The type of identity used for the Automanage account. Currently, the only
supported type is 'SystemAssigned', which implicitly creates an identity. Possible values
include: "SystemAssigned", "None".
:type type: str or ~automanage_client.models.ResourceIdentityType
"""
_validation = {
'principal_id': {'readonly': True},
'tenant_id': {'readonly': True},
}
_attribute_map = {
'principal_id': {'key': 'principalId', 'type': 'str'},
'tenant_id': {'key': 'tenantId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(AccountIdentity, self).__init__(**kwargs)
self.principal_id = None
self.tenant_id = None
self.type = kwargs.get('type', None)
class AccountList(msrest.serialization.Model):
"""The response of the list Account operation.
:param value: Result of the list Account operation.
:type value: list[~automanage_client.models.Account]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Account]'},
}
def __init__(
self,
**kwargs
):
super(AccountList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class UpdateResource(msrest.serialization.Model):
"""Represents an update resource.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
}
def __init__(
self,
**kwargs
):
super(UpdateResource, self).__init__(**kwargs)
self.tags = kwargs.get('tags', None)
class AccountUpdate(UpdateResource):
"""Definition of the Automanage account.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
:param identity: The identity of the Automanage account.
:type identity: ~automanage_client.models.AccountIdentity
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
'identity': {'key': 'identity', 'type': 'AccountIdentity'},
}
def __init__(
self,
**kwargs
):
super(AccountUpdate, self).__init__(**kwargs)
self.identity = kwargs.get('identity', None)
class ConfigurationProfileAssignment(Resource):
"""Configuration profile assignment is an association between a VM and automanage profile configuration.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param properties: Properties of the configuration profile assignment.
:type properties: ~automanage_client.models.ConfigurationProfileAssignmentProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfileAssignmentProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignment, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfileAssignmentCompliance(msrest.serialization.Model):
"""The compliance status for the configuration profile assignment.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar update_status: The state of compliance, which only appears in the response. Possible
values include: "Succeeded", "Failed", "Created".
:vartype update_status: str or ~automanage_client.models.UpdateStatus
"""
_validation = {
'update_status': {'readonly': True},
}
_attribute_map = {
'update_status': {'key': 'updateStatus', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentCompliance, self).__init__(**kwargs)
self.update_status = None
class ConfigurationProfileAssignmentList(msrest.serialization.Model):
"""The response of the list configuration profile assignment operation.
:param value: Result of the list configuration profile assignment operation.
:type value: list[~automanage_client.models.ConfigurationProfileAssignment]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConfigurationProfileAssignment]'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConfigurationProfileAssignmentProperties(msrest.serialization.Model):
"""Automanage configuration profile assignment properties.
Variables are only populated by the server, and will be ignored when sending a request.
:param configuration_profile: A value indicating configuration profile. Possible values
include: "Azure virtual machine best practices – Dev/Test", "Azure virtual machine best
practices – Production".
:type configuration_profile: str or ~automanage_client.models.ConfigurationProfile
:param target_id: The target VM resource URI.
:type target_id: str
:param account_id: The Automanage account ARM Resource URI.
:type account_id: str
:param configuration_profile_preference_id: The configuration profile custom preferences ARM
resource URI.
:type configuration_profile_preference_id: str
:ivar provisioning_status: The state of onboarding, which only appears in the response.
Possible values include: "Succeeded", "Failed", "Created".
:vartype provisioning_status: str or ~automanage_client.models.ProvisioningStatus
:param compliance: The configuration setting for the configuration profile.
:type compliance: ~automanage_client.models.ConfigurationProfileAssignmentCompliance
"""
_validation = {
'provisioning_status': {'readonly': True},
}
_attribute_map = {
'configuration_profile': {'key': 'configurationProfile', 'type': 'str'},
'target_id': {'key': 'targetId', 'type': 'str'},
'account_id': {'key': 'accountId', 'type': 'str'},
'configuration_profile_preference_id': {'key': 'configurationProfilePreferenceId', 'type': 'str'},
'provisioning_status': {'key': 'provisioningStatus', 'type': 'str'},
'compliance': {'key': 'compliance', 'type': 'ConfigurationProfileAssignmentCompliance'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfileAssignmentProperties, self).__init__(**kwargs)
self.configuration_profile = kwargs.get('configuration_profile', None)
self.target_id = kwargs.get('target_id', None)
self.account_id = kwargs.get('account_id', None)
self.configuration_profile_preference_id = kwargs.get('configuration_profile_preference_id', None)
self.provisioning_status = None
self.compliance = kwargs.get('compliance', None)
class ConfigurationProfilePreference(TrackedResource):
"""Definition of the configuration profile preference.
Variables are only populated by the server, and will be ignored when sending a request.
All required parameters must be populated in order to send to Azure.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param location: Required. The geo-location where the resource lives.
:type location: str
:param properties: Properties of the configuration profile preference.
:type properties: ~automanage_client.models.ConfigurationProfilePreferenceProperties
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'location': {'required': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'location': {'key': 'location', 'type': 'str'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfilePreferenceProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreference, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfilePreferenceAntiMalware(msrest.serialization.Model):
"""Automanage configuration profile Antimalware preferences.
:param enable_real_time_protection: Enables or disables Real Time Protection. Possible values
include: "True", "False".
:type enable_real_time_protection: str or ~automanage_client.models.EnableRealTimeProtection
:param exclusions: Extensions, Paths and Processes that must be excluded from scan.
:type exclusions: object
:param run_scheduled_scan: Enables or disables a periodic scan for antimalware. Possible values
include: "True", "False".
:type run_scheduled_scan: str or ~automanage_client.models.RunScheduledScan
:param scan_type: Type of scheduled scan. Possible values include: "Quick", "Full".
:type scan_type: str or ~automanage_client.models.ScanType
:param scan_day: Schedule scan settings day.
:type scan_day: str
:param scan_time_in_minutes: Schedule scan settings time.
:type scan_time_in_minutes: str
"""
_attribute_map = {
'enable_real_time_protection': {'key': 'enableRealTimeProtection', 'type': 'str'},
'exclusions': {'key': 'exclusions', 'type': 'object'},
'run_scheduled_scan': {'key': 'runScheduledScan', 'type': 'str'},
'scan_type': {'key': 'scanType', 'type': 'str'},
'scan_day': {'key': 'scanDay', 'type': 'str'},
'scan_time_in_minutes': {'key': 'scanTimeInMinutes', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceAntiMalware, self).__init__(**kwargs)
self.enable_real_time_protection = kwargs.get('enable_real_time_protection', None)
self.exclusions = kwargs.get('exclusions', None)
self.run_scheduled_scan = kwargs.get('run_scheduled_scan', None)
self.scan_type = kwargs.get('scan_type', None)
self.scan_day = kwargs.get('scan_day', None)
self.scan_time_in_minutes = kwargs.get('scan_time_in_minutes', None)
class ConfigurationProfilePreferenceList(msrest.serialization.Model):
"""The response of the list ConfigurationProfilePreference operation.
:param value: Result of the list ConfigurationProfilePreference operation.
:type value: list[~automanage_client.models.ConfigurationProfilePreference]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[ConfigurationProfilePreference]'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ConfigurationProfilePreferenceProperties(msrest.serialization.Model):
"""Automanage configuration profile preference properties.
:param vm_backup: The custom preferences for Azure VM Backup.
:type vm_backup: ~automanage_client.models.ConfigurationProfilePreferenceVmBackup
:param anti_malware: The custom preferences for Azure Antimalware.
:type anti_malware: ~automanage_client.models.ConfigurationProfilePreferenceAntiMalware
"""
_attribute_map = {
'vm_backup': {'key': 'vmBackup', 'type': 'ConfigurationProfilePreferenceVmBackup'},
'anti_malware': {'key': 'antiMalware', 'type': 'ConfigurationProfilePreferenceAntiMalware'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceProperties, self).__init__(**kwargs)
self.vm_backup = kwargs.get('vm_backup', None)
self.anti_malware = kwargs.get('anti_malware', None)
class ConfigurationProfilePreferenceUpdate(UpdateResource):
"""Definition of the configuration profile preference.
:param tags: A set of tags. The tags of the resource.
:type tags: dict[str, str]
:param properties: Properties of the configuration profile preference.
:type properties: ~automanage_client.models.ConfigurationProfilePreferenceProperties
"""
_attribute_map = {
'tags': {'key': 'tags', 'type': '{str}'},
'properties': {'key': 'properties', 'type': 'ConfigurationProfilePreferenceProperties'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceUpdate, self).__init__(**kwargs)
self.properties = kwargs.get('properties', None)
class ConfigurationProfilePreferenceVmBackup(msrest.serialization.Model):
"""Automanage configuration profile VM Backup preferences.
:param time_zone: TimeZone optional input as string. For example: Pacific Standard Time.
:type time_zone: str
:param instant_rp_retention_range_in_days: Instant RP retention policy range in days.
:type instant_rp_retention_range_in_days: int
:param retention_policy: Retention policy with the details on backup copy retention ranges.
:type retention_policy: str
:param schedule_policy: Backup schedule specified as part of backup policy.
:type schedule_policy: str
"""
_attribute_map = {
'time_zone': {'key': 'timeZone', 'type': 'str'},
'instant_rp_retention_range_in_days': {'key': 'instantRpRetentionRangeInDays', 'type': 'int'},
'retention_policy': {'key': 'retentionPolicy', 'type': 'str'},
'schedule_policy': {'key': 'schedulePolicy', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ConfigurationProfilePreferenceVmBackup, self).__init__(**kwargs)
self.time_zone = kwargs.get('time_zone', None)
self.instant_rp_retention_range_in_days = kwargs.get('instant_rp_retention_range_in_days', None)
self.retention_policy = kwargs.get('retention_policy', None)
self.schedule_policy = kwargs.get('schedule_policy', None)
class ErrorAdditionalInfo(msrest.serialization.Model):
"""The resource management error additional info.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar type: The additional info type.
:vartype type: str
:ivar info: The additional info.
:vartype info: object
"""
_validation = {
'type': {'readonly': True},
'info': {'readonly': True},
}
_attribute_map = {
'type': {'key': 'type', 'type': 'str'},
'info': {'key': 'info', 'type': 'object'},
}
def __init__(
self,
**kwargs
):
super(ErrorAdditionalInfo, self).__init__(**kwargs)
self.type = None
self.info = None
class ErrorResponse(msrest.serialization.Model):
"""The resource management error response.
:param error: The error object.
:type error: ~automanage_client.models.ErrorResponseError
"""
_attribute_map = {
'error': {'key': 'error', 'type': 'ErrorResponseError'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponse, self).__init__(**kwargs)
self.error = kwargs.get('error', None)
class ErrorResponseError(msrest.serialization.Model):
"""The error object.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar code: The error code.
:vartype code: str
:ivar message: The error message.
:vartype message: str
:ivar target: The error target.
:vartype target: str
:ivar details: The error details.
:vartype details: list[~automanage_client.models.ErrorResponse]
:ivar additional_info: The error additional info.
:vartype additional_info: list[~automanage_client.models.ErrorAdditionalInfo]
"""
_validation = {
'code': {'readonly': True},
'message': {'readonly': True},
'target': {'readonly': True},
'details': {'readonly': True},
'additional_info': {'readonly': True},
}
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'details': {'key': 'details', 'type': '[ErrorResponse]'},
'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'},
}
def __init__(
self,
**kwargs
):
super(ErrorResponseError, self).__init__(**kwargs)
self.code = None
self.message = None
self.target = None
self.details = None
self.additional_info = None
class Operation(msrest.serialization.Model):
"""Automanage REST API operation.
:param name: Operation name: For ex.
providers/Microsoft.Automanage/configurationProfileAssignments/write or read.
:type name: str
:param is_data_action: Indicates whether the operation is a data action.
:type is_data_action: str
:param display: Provider, Resource, Operation and description values.
:type display: ~automanage_client.models.OperationDisplay
:param status_code: Service provider: Microsoft.Automanage.
:type status_code: str
"""
_attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'is_data_action': {'key': 'isDataAction', 'type': 'str'},
'display': {'key': 'display', 'type': 'OperationDisplay'},
'status_code': {'key': 'properties.statusCode', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(Operation, self).__init__(**kwargs)
self.name = kwargs.get('name', None)
self.is_data_action = kwargs.get('is_data_action', None)
self.display = kwargs.get('display', None)
self.status_code = kwargs.get('status_code', None)
class OperationDisplay(msrest.serialization.Model):
"""Provider, Resource, Operation and description values.
:param provider: Service provider: Microsoft.Automanage.
:type provider: str
:param resource: Resource on which the operation is performed: For ex.
:type resource: str
:param operation: Operation type: Read, write, delete, etc.
:type operation: str
:param description: Description about operation.
:type description: str
"""
_attribute_map = {
'provider': {'key': 'provider', 'type': 'str'},
'resource': {'key': 'resource', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(OperationDisplay, self).__init__(**kwargs)
self.provider = kwargs.get('provider', None)
self.resource = kwargs.get('resource', None)
self.operation = kwargs.get('operation', None)
self.description = kwargs.get('description', None)
class OperationList(msrest.serialization.Model):
"""The response model for the list of Automanage operations.
:param value: List of Automanage operations supported by the Automanage resource provider.
:type value: list[~automanage_client.models.Operation]
"""
_attribute_map = {
'value': {'key': 'value', 'type': '[Operation]'},
}
def __init__(
self,
**kwargs
):
super(OperationList, self).__init__(**kwargs)
self.value = kwargs.get('value', None)
class ProxyResource(Resource):
"""The resource model definition for a ARM proxy resource. It will have everything other than required location and tags.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar id: Fully qualified resource Id for the resource. Ex -
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}.
:vartype id: str
:ivar name: The name of the resource.
:vartype name: str
:ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or
Microsoft.Storage/storageAccounts.
:vartype type: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(
self,
**kwargs
):
super(ProxyResource, self).__init__(**kwargs)
| [
"[email protected]"
] | |
a3a1e64f5807e16bd4520e2cc4130a665ca2d582 | 9c991307e29bdbd573c9d98ecd5c89e2ccaac414 | /bin/vhost_gen.py | ceee30e8546da44219849c8cbb2ea3085806c48c | [
"MIT"
] | permissive | murzindima/vhost-gen | b675e06b31909ca1e2cdbe0a16af33f83d1044f6 | 1835496d0e8694a0eceb1ef0f09d69e264e295f3 | refs/heads/master | 2022-08-28T10:24:47.849638 | 2018-08-04T23:47:24 | 2018-08-04T23:47:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 30,756 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# The MIT License (MIT)
#
# Copyright (c) 2017 cytopia <[email protected]>
"""
vHost creator for Apache 2.2, Apache 2.4 and Nginx.
"""
############################################################
# Imports
############################################################
from __future__ import print_function
import os
import sys
import time
import re
import getopt
import itertools
import yaml
############################################################
# Globals
############################################################
# Default paths
CONFIG_PATH = '/etc/vhost-gen/conf.yml'
TEMPLATE_DIR = '/etc/vhost-gen/templates'
# stdout/stderr log paths
STDOUT_ACCESS = '/tmp/www-access.log'
STDERR_ERROR = '/tmp/www-error.log'
# Default configuration
DEFAULT_CONFIG = {
'server': 'nginx',
'conf_dir': '/etc/nginx/conf.d',
'custom': '',
'vhost': {
'port': '80',
'ssl_port': '443',
'name': {
'prefix': '',
'suffix': ''
},
'docroot': {
'suffix': ''
},
'index': [
'index.php',
'index.html',
'index.htm'
],
'ssl': {
'path_crt': '',
'path_key': '',
'honor_cipher_order': 'on',
'ciphers': 'HIGH:!aNULL:!MD5',
'protocols': 'TLSv1 TLSv1.1 TLSv1.2'
},
'log': {
'access': {
'prefix': '',
'stdout': False
},
'error': {
'prefix': '',
'stderr': False
},
'dir': {
'create': False,
'path': '/var/log/nginx'
}
},
'php_fpm': {
'enable': False,
'address': '',
'port': 9000,
'timeout': 180
},
'alias': [],
'deny': [],
'server_status': {
'enable': False,
'alias': '/server-status'
}
}
}
# Available templates
TEMPLATES = {
'apache22': 'apache22.yml',
'apache24': 'apache24.yml',
'nginx': 'nginx.yml'
}
############################################################
# System Functions
############################################################
def print_help():
"""Show program help."""
print("""
Usage: vhost_gen.py -p|r <str> -n <str> [-l <str> -c <str> -t <str> -o <str> -d -s -v]
vhost_gen.py --help
vhost_gen.py --version
vhost_gen.py will dynamically generate vhost configuration files
for Nginx, Apache 2.2 or Apache 2.4 depending on what you have set
in /etc/vhot-gen/conf.yml
Required arguments:
-p|r <str> You need to choose one of the mutually exclusive arguments.
-p: Path to document root/
-r: http(s)://Host:Port for reverse proxy.
Depening on the choice, it will either generate a document serving
vhost or a reverse proxy vhost.
Note, when using -p, this can also have a suffix directory to be set
in conf.yml
-l <str> Location path when using reverse proxy.
Note, this is not required for normal document root server (-p)
-n <str> Name of vhost
Note, this can also have a prefix and/or suffix to be set in conf.yml
Optional arguments:
-m <str> Vhost generation mode. Possible values are:
-m plain: Only generate http version (default)
-m ssl: Only generate https version
-m both: Generate http and https version
-m redir: Generate https version and make http redirect to https
-c <str> Path to global configuration file.
If not set, the default location is /etc/vhost-gen/conf.yml
If no config is found, a default is used with all features turned off.
-t <str> Path to global vhost template directory.
If not set, the default location is /etc/vhost-gen/templates/
If vhost template files are not found in this directory, the program will
abort.
-o <str> Path to local vhost template directory.
This is used as a secondary template directory and definitions found here
will be merged with the ones found in the global template directory.
Note, definitions in local vhost teplate directory take precedence over
the ones found in the global template directory.
-d Make this vhost the default virtual host.
Note, this will also change the server_name directive of nginx to '_'
as well as discarding any prefix or suffix specified for the name.
Apache does not have any specialities, the first vhost takes precedence.
-s If specified, the generated vhost will be saved in the location found in
conf.yml. If not specified, vhost will be printed to stdout.
-v Be verbose.
Misc arguments:
--help Show this help.
--version Show version.
""")
def print_version():
"""Show program version."""
print('vhost_gen v0.5 (2018-05-02)')
print('cytopia <[email protected]>')
print('https://github.com/devilbox/vhost-gen')
print('The MIT License (MIT)')
############################################################
# Wrapper Functions
############################################################
def str_replace(string, replacer):
"""Generic string replace."""
# Replace all 'keys' with 'values'
for key, val in replacer.items():
string = string.replace(key, val)
return string
def str_indent(text, amount, char=' '):
"""Indent every newline inside str by specified value."""
padding = amount * char
return ''.join(padding+line for line in text.splitlines(True))
def to_str(string):
"""Dummy string retriever."""
if string is None:
return ''
return str(string)
def load_yaml(path):
"""Wrapper to load yaml file safely."""
try:
with open(path, 'r') as stream:
try:
data = yaml.safe_load(stream)
if data is None:
data = dict()
return (True, data, '')
except yaml.YAMLError as err:
return (False, dict(), str(err))
except IOError:
return (False, dict(), 'File does not exist: '+path)
def merge_yaml(yaml1, yaml2):
"""Merge two yaml strings. The secondary takes precedence."""
return dict(itertools.chain(yaml1.items(), yaml2.items()))
def symlink(src, dst, force=False):
"""
Wrapper function to create a symlink with the addition of
being able to overwrite an already existing file.
"""
if os.path.isdir(dst):
return (False, '[ERR] destination is a directory: '+dst)
if force and os.path.exists(dst):
try:
os.remove(dst)
except OSError as err:
return (False, '[ERR] Cannot delete: '+dst+': '+str(err))
try:
os.symlink(src, dst)
except OSError as err:
return (False, '[ERR] Cannot create link: '+str(err))
return (True, None)
############################################################
# Argument Functions
############################################################
def parse_args(argv):
"""Parse command line arguments."""
# Config location, can be overwritten with -c
l_config_path = CONFIG_PATH
l_template_dir = TEMPLATE_DIR
o_template_dir = None
save = None
path = None
name = None
proxy = None
mode = None
location = None
default = False
verbose = False
# Define command line options
try:
opts, argv = getopt.getopt(argv, 'vm:c:p:r:l:n:t:o:ds', ['version', 'help'])
except getopt.GetoptError as err:
print('[ERR]', str(err), file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(2)
# Get command line options
for opt, arg in opts:
if opt == '--version':
print_version()
sys.exit()
elif opt == '--help':
print_help()
sys.exit()
# Verbose
elif opt == '-v':
verbose = True
# Config file overwrite
elif opt == '-c':
l_config_path = arg
# Vhost document root path
elif opt == '-p':
path = arg
# Vhost reverse proxy (ADDR:PORT)
elif opt == '-r':
proxy = arg
# Mode overwrite
elif opt == '-m':
mode = arg
# Location for reverse proxy
elif opt == '-l':
location = arg
# Vhost name
elif opt == '-n':
name = arg
# Global template dir
elif opt == '-t':
l_template_dir = arg
# Local template dir
elif opt == '-o':
o_template_dir = arg
# Save?
elif opt == '-d':
default = True
elif opt == '-s':
save = True
return (
l_config_path, l_template_dir, o_template_dir, path, proxy, mode,
location, name, default, save, verbose
)
def validate_args_req(name, docroot, proxy, mode, location):
"""Validate required arguments."""
# Validate required command line options are set
if docroot is None and proxy is None:
print('[ERR] -p or -r is required', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
if docroot is not None and proxy is not None:
print('[ERR] -p and -r are mutually exclusive', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
# Check proxy string
if proxy is not None:
if location is None:
print('[ERR] When specifying -r, -l is also required.', file=sys.stderr)
sys.exit(1)
# Regex: HOSTNAME/IP:PORT
regex = re.compile('(^http(s)?://[-_.a-zA-Z0-9]+:[0-9]+$)', re.IGNORECASE)
if not regex.match(proxy):
print('[ERR] Invalid proxy argument string: \'%s\', should be: %s or %s.'
% (proxy, 'http(s)://HOST:PORT', 'http(s)://IP:PORT'), file=sys.stderr)
sys.exit(1)
port = int(re.sub('^.*:', '', proxy))
if port < 1 or port > 65535:
print('[ERR] Invalid reverse proxy port range: \'%d\', should between 1 and 65535'
% (port), file=sys.stderr)
sys.exit(1)
# Check mode string
if mode is not None:
if mode not in ('plain', 'ssl', 'both', 'redir'):
print('[ERR] Invalid -m mode string: \'%s\', should be: %s, %s, %s or %s'
% (mode, 'plain', 'ssl', 'both', 'redir'), file=sys.stderr)
sys.exit(1)
# Check normal server settings
if docroot is not None:
if location is not None:
print('[WARN] -l is ignored when using normal vhost (-p)', file=sys.stderr)
if name is None:
print('[ERR] -n is required', file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
regex = re.compile('(^[-_.a-zA-Z0-9]+$)', re.IGNORECASE)
if not regex.match(name):
print('[ERR] Invalid name:', name, file=sys.stderr)
sys.exit(1)
def validate_args_opt(config_path, tpl_dir):
"""Validate optional arguments."""
if not os.path.isfile(config_path):
print('[WARN] Config file not found:', config_path, file=sys.stderr)
if not os.path.isdir(tpl_dir):
print('[ERR] Template path does not exist:', tpl_dir, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
# Validate global templates
tpl_file = os.path.join(tpl_dir, TEMPLATES['apache22'])
if not os.path.isfile(tpl_file):
print('[ERR] Apache 2.2 template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
tpl_file = os.path.join(tpl_dir, TEMPLATES['apache24'])
if not os.path.isfile(tpl_file):
print('[ERR] Apache 2.4 template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
tpl_file = os.path.join(tpl_dir, TEMPLATES['nginx'])
if not os.path.isfile(tpl_file):
print('[ERR] Nginx template file does not exist:', tpl_file, file=sys.stderr)
print('Type --help for help', file=sys.stderr)
sys.exit(1)
############################################################
# Config File Functions
############################################################
def validate_config(config):
"""Validate some important keys in config dict."""
# Validate server type
valid_hosts = list(TEMPLATES.keys())
if config['server'] not in valid_hosts:
print('[ERR] httpd.server must be \'apache22\', \'apache24\' or \'nginx\'', file=sys.stderr)
print('[ERR] Your configuration is:', config['server'], file=sys.stderr)
sys.exit(1)
# # Validate if log dir can be created
# log_dir = config['vhost']['log']['dir']['path']
# if config['vhost']['log']['dir']['create']:
# if not os.path.isdir(log_dir):
# if not os.access(os.path.dirname(log_dir), os.W_OK):
# print('[ERR] log directory does not exist and cannot be created:', log_dir,
# file=sys.stderr)
# sys.exit(1)
############################################################
# Get vHost Skeleton placeholders
############################################################
def vhost_get_port(config, ssl):
"""Get listen port."""
if ssl:
if config['server'] == 'nginx':
return to_str(config['vhost']['ssl_port']) + ' ssl'
return to_str(config['vhost']['ssl_port'])
return to_str(config['vhost']['port'])
def vhost_get_default_server(config, default):
"""
Get vhost default directive which makes it the default vhost.
:param dict config: Configuration dictionary
:param bool default: Default vhost
"""
if default:
if config['server'] == 'nginx':
# The leading space is required here for the template to
# separate it from the port directive left to it.
return ' default_server'
if config['server'] in ('apache22', 'apache24'):
return '_default_'
else:
if config['server'] in ('apache22', 'apache24'):
return '*'
return ''
def vhost_get_server_name(config, server_name, default):
"""Get server name."""
# Nginx uses: "server_name _;" as the default
if default and config['server'] == 'nginx':
return '_'
# Apache does not have any specialities. The first one takes precedence.
# The name will be the same as with every other vhost.
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
return prefix + server_name + suffix
def vhost_get_access_log(config, server_name):
"""Get access log directive."""
if config['vhost']['log']['access']['stdout']:
return STDOUT_ACCESS
prefix = to_str(config['vhost']['log']['access']['prefix'])
name = prefix + server_name + '-access.log'
path = os.path.join(config['vhost']['log']['dir']['path'], name)
return path
def vhost_get_error_log(config, server_name):
"""Get error log directive."""
if config['vhost']['log']['error']['stderr']:
return STDERR_ERROR
prefix = to_str(config['vhost']['log']['error']['prefix'])
name = prefix + server_name + '-error.log'
path = os.path.join(config['vhost']['log']['dir']['path'], name)
return path
############################################################
# Get vHost Type (normal or reverse proxy
############################################################
def vhost_get_vhost_docroot(config, template, docroot, proxy):
"""Get document root directive."""
if proxy is not None:
return ''
return str_replace(template['vhost_type']['docroot'], {
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__INDEX__': vhost_get_index(config)
})
def vhost_get_vhost_rproxy(template, proxy, location):
"""Get reverse proxy definition."""
if proxy is not None:
return str_replace(template['vhost_type']['rproxy'], {
'__LOCATION__': location,
'__PROXY_PROTO__': re.sub('://.*$', '', proxy),
'__PROXY_ADDR__': re.search('^.*://(.+):[0-9]+', proxy).group(1),
'__PROXY_PORT__': re.sub('^.*:', '', proxy)
})
return ''
############################################################
# Get vHost Features
############################################################
def vhost_get_vhost_ssl(config, template, server_name):
"""Get ssl definition."""
return str_replace(template['features']['ssl'], {
'__SSL_PATH_CRT__': to_str(vhost_get_ssl_crt_path(config, server_name)),
'__SSL_PATH_KEY__': to_str(vhost_get_ssl_key_path(config, server_name)),
'__SSL_PROTOCOLS__': to_str(config['vhost']['ssl']['protocols']),
'__SSL_HONOR_CIPHER_ORDER__': to_str(config['vhost']['ssl']['honor_cipher_order']),
'__SSL_CIPHERS__': to_str(config['vhost']['ssl']['ciphers'])
})
def vhost_get_vhost_redir(config, template, server_name):
"""Get redirect to ssl definition."""
return str_replace(template['features']['redirect'], {
'__VHOST_NAME__': server_name,
'__SSL_PORT__': to_str(config['vhost']['ssl_port'])
})
def vhost_get_ssl_crt_path(config, server_name):
"""Get ssl crt path"""
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
name = prefix + server_name + suffix + '.crt'
path = to_str(config['vhost']['ssl']['dir_crt'])
return os.path.join(path, name)
def vhost_get_ssl_key_path(config, server_name):
"""Get ssl key path"""
prefix = to_str(config['vhost']['name']['prefix'])
suffix = to_str(config['vhost']['name']['suffix'])
name = prefix + server_name + suffix + '.key'
path = to_str(config['vhost']['ssl']['dir_crt'])
return os.path.join(path, name)
def vhost_get_docroot_path(config, docroot, proxy):
"""Get path of document root."""
if proxy is not None:
return ''
suffix = to_str(config['vhost']['docroot']['suffix'])
path = os.path.join(docroot, suffix)
return path
def vhost_get_index(config):
"""Get index."""
if 'index' in config['vhost'] and config['vhost']['index']:
elem = config['vhost']['index']
else:
elem = DEFAULT_CONFIG['vhost']['index']
return ' '.join(elem)
def vhost_get_php_fpm(config, template, docroot, proxy):
"""Get PHP FPM directive. If using reverse proxy, PHP-FPM will be disabled."""
if proxy is not None:
return ''
# Get PHP-FPM
php_fpm = ''
if config['vhost']['php_fpm']['enable']:
php_fpm = str_replace(template['features']['php_fpm'], {
'__PHP_ADDR__': to_str(config['vhost']['php_fpm']['address']),
'__PHP_PORT__': to_str(config['vhost']['php_fpm']['port']),
'__PHP_TIMEOUT__': to_str(config['vhost']['php_fpm']['timeout']),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy)
})
return php_fpm
def vhost_get_aliases(config, template):
"""Get virtual host alias directives."""
aliases = []
for item in config['vhost']['alias']:
# Add optional xdomain request if enabled
xdomain_request = ''
if 'xdomain_request' in item:
if item['xdomain_request']['enable']:
xdomain_request = str_replace(template['features']['xdomain_request'], {
'__REGEX__': to_str(item['xdomain_request']['origin'])
})
# Replace everything
aliases.append(str_replace(template['features']['alias'], {
'__ALIAS__': to_str(item['alias']),
'__PATH__': to_str(item['path']),
'__XDOMAIN_REQ__': str_indent(xdomain_request, 4).rstrip()
}))
# Join by OS independent newlines
return os.linesep.join(aliases)
def vhost_get_denies(config, template):
"""Get virtual host deny alias directives."""
denies = []
for item in config['vhost']['deny']:
denies.append(str_replace(template['features']['deny'], {
'__REGEX__': to_str(item['alias'])
}))
# Join by OS independent newlines
return os.linesep.join(denies)
def vhost_get_server_status(config, template):
"""Get virtual host server status directivs."""
status = ''
if config['vhost']['server_status']['enable']:
status = template['features']['server_status']
return str_replace(status, {
'__REGEX__': to_str(config['vhost']['server_status']['alias'])
})
def vhost_get_custom_section(config):
"""Get virtual host custom directives."""
return to_str(config['custom'])
############################################################
# vHost create
############################################################
def get_vhost_plain(config, tpl, docroot, proxy, location, server_name, default):
"""Get plain vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, False),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': str_indent(vhost_get_vhost_docroot(config, tpl, docroot, proxy), 4),
'__VHOST_RPROXY__': str_indent(vhost_get_vhost_rproxy(tpl, proxy, location), 4),
'__REDIRECT__': '',
'__SSL__': '',
'__INDEX__': vhost_get_index(config),
'__ACCESS_LOG__': vhost_get_access_log(config, server_name),
'__ERROR_LOG__': vhost_get_error_log(config, server_name),
'__PHP_FPM__': str_indent(vhost_get_php_fpm(config, tpl, docroot, proxy), 4),
'__ALIASES__': str_indent(vhost_get_aliases(config, tpl), 4),
'__DENIES__': str_indent(vhost_get_denies(config, tpl), 4),
'__SERVER_STATUS__': str_indent(vhost_get_server_status(config, tpl), 4),
'__CUSTOM__': str_indent(vhost_get_custom_section(config), 4)
})
def get_vhost_ssl(config, tpl, docroot, proxy, location, server_name, default):
"""Get ssl vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, True),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': str_indent(vhost_get_vhost_docroot(config, tpl, docroot, proxy), 4),
'__VHOST_RPROXY__': str_indent(vhost_get_vhost_rproxy(tpl, proxy, location), 4),
'__REDIRECT__': '',
'__SSL__': str_indent(vhost_get_vhost_ssl(config, tpl, server_name), 4),
'__INDEX__': vhost_get_index(config),
'__ACCESS_LOG__': vhost_get_access_log(config, server_name + '_ssl'),
'__ERROR_LOG__': vhost_get_error_log(config, server_name + '_ssl'),
'__PHP_FPM__': str_indent(vhost_get_php_fpm(config, tpl, docroot, proxy), 4),
'__ALIASES__': str_indent(vhost_get_aliases(config, tpl), 4),
'__DENIES__': str_indent(vhost_get_denies(config, tpl), 4),
'__SERVER_STATUS__': str_indent(vhost_get_server_status(config, tpl), 4),
'__CUSTOM__': str_indent(vhost_get_custom_section(config), 4)
})
def get_vhost_redir(config, tpl, docroot, proxy, server_name, default):
"""Get redirect to ssl vhost"""
return str_replace(tpl['vhost'], {
'__PORT__': vhost_get_port(config, False),
'__DEFAULT_VHOST__': vhost_get_default_server(config, default),
'__DOCUMENT_ROOT__': vhost_get_docroot_path(config, docroot, proxy),
'__VHOST_NAME__': vhost_get_server_name(config, server_name, default),
'__VHOST_DOCROOT__': '',
'__VHOST_RPROXY__': '',
'__REDIRECT__': str_indent(vhost_get_vhost_redir(config, tpl, server_name), 4),
'__SSL__': '',
'__INDEX__': '',
'__ACCESS_LOG__': vhost_get_access_log(config, server_name),
'__ERROR_LOG__': vhost_get_error_log(config, server_name),
'__PHP_FPM__': '',
'__ALIASES__': '',
'__DENIES__': '',
'__SERVER_STATUS__': '',
'__CUSTOM__': ''
})
def get_vhost(config, tpl, docroot, proxy, mode, location, server_name, default):
"""Create the vhost."""
if mode == 'ssl':
return get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default)
if mode == 'both':
return (
get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default) +
get_vhost_plain(config, tpl, docroot, proxy, location,
server_name, default)
)
if mode == 'redir':
return (
get_vhost_ssl(config, tpl, docroot, proxy, location,
server_name, default) +
get_vhost_redir(config, tpl, docroot, proxy, server_name, default)
)
return get_vhost_plain(config, tpl, docroot, proxy, location,
server_name, default)
############################################################
# Load configs and templates
############################################################
def load_config(config_path):
"""Load config and merge with defaults in case not found or something is missing."""
# Load configuration file
if os.path.isfile(config_path):
succ, config, err = load_yaml(config_path)
if not succ:
return (False, dict(), err)
else:
print('[WARN] config file not found', config_path, file=sys.stderr)
config = dict()
# Merge config settings with program defaults (config takes precedence over defaults)
config = merge_yaml(DEFAULT_CONFIG, config)
return (True, config, '')
def load_template(template_dir, o_template_dir, server):
"""Load global and optional template file and merge them."""
# Load global template file
succ, template, err = load_yaml(os.path.join(template_dir, TEMPLATES[server]))
if not succ:
return (False, dict(), '[ERR] Error loading template' + err)
# Load optional template file (if specified file and merge it)
if o_template_dir is not None:
succ, template2, err = load_yaml(os.path.join(o_template_dir, TEMPLATES[server]))
template = merge_yaml(template, template2)
return (True, template, '')
############################################################
# Post actions
############################################################
def apply_log_settings(config):
"""
This function will apply various settings for the log defines, including
creating the directory itself as well as handling log file output (access
and error) to stderr/stdout.
"""
# Symlink stdout to access logfile
if config['vhost']['log']['access']['stdout']:
succ, err = symlink('/dev/stdout', STDOUT_ACCESS, force=True)
if not succ:
return (False, err)
# Symlink stderr to error logfile
if config['vhost']['log']['error']['stderr']:
succ, err = symlink('/dev/stderr', STDERR_ERROR, force=True)
if not succ:
return (False, err)
# Create log dir
if config['vhost']['log']['dir']['create']:
if not os.path.isdir(config['vhost']['log']['dir']['path']):
try:
os.makedirs(config['vhost']['log']['dir']['path'])
except OSError as err:
return (False, '[ERR] Cannot create directory: '+str(err))
return (True, None)
############################################################
# Main Function
############################################################
def main(argv):
"""Main entrypoint."""
# Get command line arguments
(config_path, tpl_dir, o_tpl_dir, docroot,
proxy, mode, location, name, default, save, verbose) = parse_args(argv)
# Validate command line arguments This will abort the program on error
# This will abort the program on error
validate_args_req(name, docroot, proxy, mode, location)
validate_args_opt(config_path, tpl_dir)
# Load config
succ, config, err = load_config(config_path)
if not succ:
print('[ERR] Error loading config', err, file=sys.stderr)
sys.exit(1)
# Load template
succ, template, err = load_template(tpl_dir, o_tpl_dir, config['server'])
if not succ:
print('[ERR] Error loading template', err, file=sys.stderr)
sys.exit(1)
# Validate configuration file
# This will abort the program on error
validate_config(config)
# Retrieve fully build vhost
vhost = get_vhost(config, template, docroot, proxy, mode, location, name, default)
if verbose:
print('vhostgen: [%s] Adding: %s' %
(time.strftime("%Y-%m-%d %H:%M:%S"),
to_str(config['vhost']['name']['prefix']) + name +
to_str(config['vhost']['name']['suffix'])))
if save:
if not os.path.isdir(config['conf_dir']):
print('[ERR] output conf_dir does not exist:', config['conf_dir'],
file=sys.stderr)
sys.exit(1)
if not os.access(config['conf_dir'], os.W_OK):
print('[ERR] directory does not have write permissions', config['conf_dir'],
file=sys.stderr)
sys.exit(1)
vhost_path = os.path.join(config['conf_dir'], name+'.conf')
with open(vhost_path, 'w') as outfile:
outfile.write(vhost)
# Apply settings for logging (symlinks, mkdir) only in save mode
succ, err = apply_log_settings(config)
if not succ:
print(err, file=sys.stderr)
sys.exit(1)
else:
print(vhost)
############################################################
# Main Entry Point
############################################################
if __name__ == '__main__':
main(sys.argv[1:])
| [
"[email protected]"
] | |
24a7e0e511a2d8d8023e5a267a26f01231db6504 | bc6492a9a30ac7228caad91643d58653b49ab9e3 | /sympy/parsing/autolev/test-examples/pydy-example-repo/chaos_pendulum.py | 37a8673cd2de946f7185811aa561c209c9982994 | [] | no_license | cosmosZhou/sagemath | 2c54ea04868882340c7ef981b7f499fb205095c9 | 0608b946174e86182c6d35d126cd89d819d1d0b8 | refs/heads/master | 2023-01-06T07:31:37.546716 | 2020-11-12T06:39:22 | 2020-11-12T06:39:22 | 311,177,322 | 1 | 0 | null | 2020-11-12T06:09:11 | 2020-11-08T23:42:40 | Python | UTF-8 | Python | false | false | 2,288 | py | import sympy.physics.mechanics as me
import sympy as sm
import math as m
import numpy as np
g, lb, w, h = sm.symbols('g lb w h', real=True)
theta, phi, omega, alpha = me.dynamicsymbols('theta phi omega alpha')
thetad, phid, omegad, alphad = me.dynamicsymbols('theta phi omega alpha', 1)
thetad2, phid2 = me.dynamicsymbols('theta phi', 2)
frame_n = me.ReferenceFrame('n')
body_a_cm = me.Point('a_cm')
body_a_cm.set_vel(frame_n, 0)
body_a_f = me.ReferenceFrame('a_f')
body_a = me.RigidBody('a', body_a_cm, body_a_f, sm.symbols('m'), (me.outer(body_a_f.x,body_a_f.x),body_a_cm))
body_b_cm = me.Point('b_cm')
body_b_cm.set_vel(frame_n, 0)
body_b_f = me.ReferenceFrame('b_f')
body_b = me.RigidBody('b', body_b_cm, body_b_f, sm.symbols('m'), (me.outer(body_b_f.x,body_b_f.x),body_b_cm))
body_a_f.orient(frame_n, 'Axis', [theta, frame_n.y])
body_b_f.orient(body_a_f, 'Axis', [phi, body_a_f.z])
point_o = me.Point('o')
la = (lb-h/2)/2
body_a_cm.set_pos(point_o, la*body_a_f.z)
body_b_cm.set_pos(point_o, lb*body_a_f.z)
body_a_f.set_ang_vel(frame_n, omega*frame_n.y)
body_b_f.set_ang_vel(body_a_f, alpha*body_a_f.z)
point_o.set_vel(frame_n, 0)
body_a_cm.v2pt_theory(point_o,frame_n,body_a_f)
body_b_cm.v2pt_theory(point_o,frame_n,body_a_f)
ma = sm.symbols('ma')
body_a.mass = ma
mb = sm.symbols('mb')
body_b.mass = mb
iaxx = 1/12*ma*(2*la)**2
iayy = iaxx
iazz = 0
ibxx = 1/12*mb*h**2
ibyy = 1/12*mb*(w**2+h**2)
ibzz = 1/12*mb*w**2
body_a.inertia = (me.inertia(body_a_f, iaxx, iayy, iazz, 0, 0, 0), body_a_cm)
body_b.inertia = (me.inertia(body_b_f, ibxx, ibyy, ibzz, 0, 0, 0), body_b_cm)
force_a = body_a.mass*(g*frame_n.z)
force_b = body_b.mass*(g*frame_n.z)
kd_eqs = [thetad - omega, phid - alpha]
forceList = [(body_a.masscenter,body_a.mass*(g*frame_n.z)), (body_b.masscenter,body_b.mass*(g*frame_n.z))]
kane = me.KanesMethod(frame_n, q_ind=[theta,phi], u_ind=[omega, alpha], kd_eqs = kd_eqs)
fr, frstar = kane.kanes_equations([body_a, body_b], forceList)
zero = fr+frstar
from pydy.system import System
sys = System(kane, constants = {g:9.81, lb:0.2, w:0.2, h:0.1, ma:0.01, mb:0.1},
specifieds={},
initial_conditions={theta:np.deg2rad(90), phi:np.deg2rad(0.5), omega:0, alpha:0},
times = np.linspace(0.0, 10, 10/0.02))
y=sys.integrate()
| [
"[email protected]"
] | |
e8903d4f4699625df2cda18ac35f4222d2fd4b28 | 59f8bf58860d021216449b135f486f9b7145f6be | /application/utils/helper.py | b0f149aafc09f1948981c1ab3c93845eb97d3ddc | [] | no_license | JFluo2011/fisher | f5b58e2e151022b2173490b504dda7c704862b19 | d899e2a3dc296cf9d1c2802067d995dde1c3d32e | refs/heads/master | 2022-12-10T12:42:36.376854 | 2018-12-27T07:57:00 | 2018-12-27T07:57:00 | 158,154,663 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 126 | py | def keyword_is_isbn(keyword):
tmp = keyword.strip().replace('-', '')
return (len(tmp) in [10, 13]) and tmp.isdigit()
| [
"[email protected]"
] | |
58c58c2aa06311710749227f4e0405344d093517 | 663d429e1f552ef958d37cfe4a0707354b544a9a | /rimi_linux_mysql/tcp_ip_socket/my_async/asyncsocket_chat/client1.py | 4a9a11ecfbb9b7904ff495bf8814706de43aa992 | [] | no_license | nie000/mylinuxlearn | 72a33024648fc4393442511c85d7c439e169a960 | 813ed75a0018446cd661001e8803f50880d09fff | refs/heads/main | 2023-06-20T07:46:11.842538 | 2021-07-15T13:46:43 | 2021-07-15T13:46:43 | 307,377,665 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 413 | py | import socket
ss_address = ("0.0.0.0",19528)
ss = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('123')
ss.connect(ss_address)
print('456')
while True:
data = input('请输入消息:')
if not data:
break
try:
ss.send(data.encode('utf8'))
print(ss.recv(1024).decode('utf8'))
except BrokenPipeError:
print('连接已经关闭')
break
ss.close()
| [
"[email protected]"
] | |
c7fee91cb539c4e1e261ffa6c3de60b555291813 | 05bf7de1337bc938578accba64416863cec1ed63 | /docs/historical/MSD/MSDTutorial/Post_Processing/common/post_processing_class.py | 493bc56ae42de7f8b5544648a723bab83e78ce4c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
] | permissive | metamorph-inc/openmeta-mms | d0dccae88e7532594f02c5eff8daa74c6c0e4010 | 2644cb7273916e36c3725785fc9a44948d64c343 | refs/heads/master | 2023-04-06T11:09:36.316306 | 2023-03-28T18:17:55 | 2023-03-28T18:17:55 | 70,078,378 | 21 | 8 | NOASSERTION | 2023-01-14T09:31:14 | 2016-10-05T16:29:54 | Python | UTF-8 | Python | false | false | 24,179 | py | import os
import json
import sys
import re
import numpy as np
from py_modelica.mat_file_functions.mat_file_to_dict import MatFile2Dict
# Rescue if the limit-checking should get stuck in an infinite while-loop.
# Which should be impossible to start with, but if I am wrong...
MAX_ITERATIONS = 100000
class PostProcess:
filter = [] # list of all variables/parameter to load from mat-file
# (does not need to include 'time' - loaded by default)
time = None
result = None
def __init__(self, mat_file='', filter=None):
"""
Loads in mat-file, extracts given variables in filter (time always included)
and converts lists of values into numpy arrays.
These are stored in result as:
{{name1: array([values1])}, ..., {nameN: array([valuesN])}}
"""
mat_converter = MatFile2Dict(mat_file, filter, False)
result_lists = mat_converter.get_results()
# convert lists into numpy arrays
self.result = {}
for item in result_lists.iteritems():
self.result.update({item[0]: np.array(item[1])})
self.time = self.result['time']
def data_array(self, name):
"""
Get time-series in numpy array format.
name - name of variable
e.g. data_array('time')
returns with the time.
"""
try:
A = self.result[name]
return A
except KeyError:
print 'ERROR: cannot find [' + name + '] in Modelica results'
return []
def print_data(self, name):
"""
Prints the time-series.
name - name of variable
e.g. data_array('time')
returns with the time.
"""
data = self.data_array(name)
print 'name of data: '
print name
print 'here is the data: (with index)'
print '[',
for i in xrange(data.size - 1):
print str(i) + ':', str(data[i]) + ',',
print str(i + 1) + ':', str(data[i + 1]) + ']'
return data
def time_array(self):
"""
Get time-series of time in numpy array format.
"""
return self.time
def print_time(self):
"""
Prints and returns with time-series of time.
"""
time = self.time
print 'here are time intervals:', time
return time
def short_array(self, name, start=0, end=-1):
"""
Get a truncated, from n1 to n2 array for variable name
name - name of variable
start - start index of interval
end - end index of interval
N.B index goes from 0 to len(array)-1
"""
return self.result[name][start:end]
def plot(self, name):
"""
Returns a tuple, suitable for plotting, of the variable's time-series together with time.
name - name of variable
"""
return self.data_array(name), self.time
def get_data_by_time(self, name, time_val):
"""
Get data based on time value.
name - name of variable to consider
time_val - time point where to extract the value
Returns the data and the index of the data
"""
i = 0
time = self.time
while time[i] < time_val and i in xrange(time.size - 1):
i += 1
data_arr = self.data_array(name)
if time[i - 1] != time_val:
cur = data_arr[i - 1]
next = data_arr[i]
data = time[i - 1] / ((time[i - 1] + time[i]) / 2) * (next - cur) + cur
else:
data = data_arr[i - 1]
return data, i
def get_data_by_index(self, name, index):
return self.data_array(name)[index]
def get_index_from_time(self, time_val):
"""
Get index based on time value.
time_val - time point where to extract the value
Returns index nearest to time_val
"""
i = 0
time = self.time
while time[i] < time_val and i in xrange(time.size-1):
i += 1
return i
def get_time(self, name, value, atol=1e-4, rtol=1e-4, start_index=0, end_index=-1):
"""
Gets the first time point where the variable satisfies either atol or rtol,
if no such point exists - returns with -1.
name - name of variable
atol - absolute tolerance
rtol - relative tolerance
"""
index = -1
# N.B. this is only one of many ways to do this
denominator = 1
if value > rtol:
denominator = value
data = self.data_array(name)[start_index:end_index]
cnt = 0
for x in data:
abs_diff = abs(x - value)
rel_diff = abs_diff / denominator
if abs_diff < atol or rel_diff < rtol:
index = cnt
break
else:
cnt += 1
if index >= 0:
return self.time[start_index + index]
return -1
def last_value(self, name):
"""
Get last value of variable
name - name of variable
"""
return self.data_array(name)[-1]
def global_max(self, name):
"""
Get maximum value of variable
name - name of variable
"""
return self.data_array(name).max()
def global_max_time(self, name):
"""
Get time where max occurs
name - name of variable
returns the time at where the max is
"""
index = self.data_array(name).argmax()
time_at_max = self.time[index]
return time_at_max
def global_min(self, name):
"""
Get minimum value of variable
name - name of variable
"""
return self.data_array(name).min()
def global_min_time(self, name):
"""
Get time where min occurs
name - name of variable
returns the time at where the min is
"""
index = self.data_array(name).argmin()
time_at_min = self.time[index]
return time_at_min
def global_abs_max(self, name):
"""
Get the maximum absolute value of variable
name - name of variable
"""
return np.absolute(self.data_array(name)).max()
def std_dev(self, name):
"""
Returns the standard deviation of variable
name - name of variable
"""
stddev = self.data_array(name).std()
return stddev
def variance(self, name):
"""
Returns the variance of variable
name - name of variable
"""
variance = self.data_array(name).var()
return variance
def sum_value(self, name):
"""
Returns the sum of the time-series for the variable
name - name of variable
"""
result = self.data_array(name).sum()
return result
def mean(self, name):
"""
Returns the mean of the time-series for the variable
name - name of variable
"""
result = np.mean(self.data_array(name), dtype=np.float64)
return result
def integrate(self, name):
"""
Returns the area under the curve of the time-series for the variable
name - name of variable
"""
time = self.time
data = self.data_array(name)
sum = 0
next = data[0]
next_t = time[0]
for i in xrange(data.size):
cur = next
next = data[i]
cur_t = next_t
next_t = time[i]
height = (next + cur) / 2
interval = next_t - cur_t
sum += height * interval
return sum
def minima(self, name):
"""
Returns the minima of time-series of variable
name - name of variable
"""
data = self.data_array(name)
min = []
prev = 0
cur = 0
next = data[0]
for i in xrange(data.size):
if cur < prev and cur <= next:
min.append(cur)
prev = cur
cur = next
next = data[++i]
minimum = np.array(min)
return minimum
def maxima(self, name):
"""
Returns the maxima of time-series of variable
name - name of variable
"""
data = self.data_array(name)
max = []
prev = 0
cur = 0
next = data[0]
for i in xrange(data.size):
if cur >= prev and cur > next:
max.append(cur)
prev = cur
cur = next
next = data[++i]
maximum = np.array(max)
return maximum
def pos_neg(self, name, tol=0.00000015):
"""
Returns time of the roots from positive to negative of time-series of variable
name - name of variable
tol - tolerance
"""
data = self.data_array(name)
time_arr = self.time
time = []
next = -1
for i in xrange(data.size):
cur = next
next = data[i]
if cur > 0 + tol and next <= 0 + tol:
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time.append((cur / (cur + next) / 2) * (next_t - cur_t) + cur_t)
else:
time.append(time_arr[i - 1])
timing = np.array(time)
return timing
def neg_pos(self, name, tol=0.00000015):
"""
Returns time of the roots from negative to positive of time-series of variable
name - name of variable
tol - tolerance
"""
time = []
data = self.data_array(name)
time_arr = self.time
next = 1
for i in xrange(data.size):
cur = next
next = data[i]
if cur <= 0 + tol and next > 0 + tol:
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time.append(cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t)
else:
time.append(time_arr[i - 1])
timing = np.array(time)
return timing
def to_zero(self, name, value_index):
"""
# time from a number to zero
# (use index from print_data() function)
# parameters: data array, time array, index of value
# returns the time of the zero
"""
data = self.data_array(name)
time_arr = self.time
i = value_index + 1
cur = data[value_index]
next = data[i]
tolerance = 0.00000015
if data[value_index] >= 0:
while next >= 0 + tolerance and i in xrange(data.size - 1):
i += 1
cur = next
next = data[i]
if next >= 0 + tolerance:
return -1
else:
while next <= 0 + tolerance and i in xrange(data.size - 1):
i += 1
cur = next
next = data[i]
if next <= 0 + tolerance:
return -1
if cur != 0:
cur_t = time_arr[i - 1]
next_t = time_arr[i]
time = cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t
else:
time = time_arr[i - 1]
return time
def from_zero(self, name, value_index):
"""
# time from a number to zero
# (use index from print_data() function)
# parameters: data array, time array, index of value
# returns the time of the zero
"""
data = self.data_array(name)
time_arr = self.time
i = value_index - 1
cur = data[value_index]
next = data[i]
tolerance = 0.00000015
if data[value_index - 1] >= 0:
while next >= 0 + tolerance and i in xrange(data.size):
i -= 1
cur = next
next = data[i]
if next >= 0 + tolerance:
return -1
else:
while next <= 0 + tolerance and i in xrange(data.size):
i -= 1
cur = next
next = data[i]
if next <= 0 + tolerance:
return -1
if cur != 0:
cur_t = time_arr[i + 1]
next_t = time_arr[i]
time = cur / ((cur + next) / 2) * (next_t - cur_t) + cur_t
else:
time = time_arr[i + 1]
return time
def zeros(self, name):
"""
Find zeros of time-series for variable
name - name of variable
returns the time of the zero
"""
data_array = self.data_array(name)
time = self.time
data = [[], []]
data[0].append(self.pos_neg(data_array, time))
data[1].append(self.neg_pos(data_array, time))
data_arr = np.array(data)
return data_arr
def compare(self, name1, name2):
"""
Compare the time-series of two variables
name1 - name of variable 1
name2 - name of variable 2
returns true if the results are identical
"""
data1 = self.data_array(name1)
data2 = self.data_array(name2)
for i in xrange(data1.size):
if data1[i] != data2[i]:
return False
return True
def time_total(self, val1, val2):
# finding the difference between 2 times
time = abs(val2 - val1)
return time
def delta_t(self, start_index, end_index):
"""
Returns the length of the time-interval between to indices
"""
t1 = self.time[start_index]
t2 = self.time[end_index]
dt = t2 - t1
return dt
def get_local_max(self, name, start_index, end_index):
"""
Returns the value of the maximum between two indices
N.B. including both points
:param name:
:param start_index:
:param end_index:
"""
if end_index == -1:
maximum = self.data_array(name)[start_index:].max()
else:
maximum = self.data_array(name)[start_index:end_index + 1].max()
return maximum
def get_local_min(self, name, start_index, end_index):
"""
Returns the value of the minimum between two indices
N.B. including both points
"""
if end_index == -1:
minimum = self.data_array(name)[start_index:].min()
else:
minimum = self.data_array(name)[start_index:end_index + 1].min()
return minimum
def find_first_max_violation(self, name, value, start_index=0):
"""
Starting from start_index it looks for the first index where the
time-series has a value greater than value.
If it never occurs, it returns -1
"""
time_series = self.data_array(name)[start_index:]
n = len(time_series)
for i in range(n):
if time_series[i] > value:
return i + start_index
return -1
def find_first_min_violation(self, name, value, start_index=0):
"""
Starting from start_index it looks for the first index where the
time-series has a value less than value.
If it never occurs, it returns -1
"""
time_series = self.data_array(name)[start_index:]
n = len(time_series)
for i in range(n):
if time_series[i] < value:
return i + start_index
return -1
def check_max_limit(self, name, value):
actual_value = ''
limit_exceeded = False
start_index = 0
global_max = -np.Inf
cnt = 0
print 'check_max_limit'
while start_index > -1:
index = self.find_first_max_violation(name, value, start_index)
if index > -1:
end_index = self.find_first_min_violation(name, value, index)
d_t = self.delta_t(index, end_index)
print 'Found violation at t={0} lasting : {1}'.format(self.time[index], d_t)
if d_t > 0.5:
limit_exceeded = True
local_max = self.get_local_max(name, index, end_index)
print 'Local maximum : {0}'.format(local_max)
if local_max > global_max:
global_max = local_max
start_index = end_index
else:
break
cnt += 1
if cnt == MAX_ITERATIONS:
print 'Limit checking for variable {0} aborted after {1} iterations' \
.format(name, MAX_ITERATIONS)
sys.exit(1)
if limit_exceeded:
actual_value = global_max
return limit_exceeded, actual_value
def check_min_limit(self, name, value):
actual_value = ''
limit_exceeded = False
start_index = 0
global_min = np.Inf
cnt = 0
print 'check_min_limit'
while start_index > -1:
index = self.find_first_min_violation(name, value, start_index)
if index > -1:
end_index = self.find_first_max_violation(name, value, index)
d_t = self.delta_t(index, end_index)
print 'Found violation at t={0} lasting : {1} s'.format(self.time[index], d_t)
if d_t > 0.5:
limit_exceeded = True
local_min = self.get_local_min(name, index, end_index)
print 'Local minimum : {0}'.format(local_min)
if local_min < global_min:
global_min = local_min
start_index = end_index
else:
break
cnt += 1
if cnt == MAX_ITERATIONS:
print 'Limit checking for variable {0} aborted after {1} iterations' \
.format(name, MAX_ITERATIONS)
sys.exit(1)
if limit_exceeded:
actual_value = global_min
return limit_exceeded, actual_value
#find_zero(self, array1, array2):
def find_zero(self, array1, array2, time_arr):
tolerance = 0.000000015
tol = 0.0001
for i in xrange(array1.size):
if array1[i] <= (array2[i] + tol):
if array1[i] >= (array2[i] - tol):
if array1[i] <= (0 + tolerance):
if array1[i] >= (0 - tolerance):
return time_arr[i];
return -1
def update_metrics_in_report_json(metrics, report_file='summary.testresults.json'):
"""
Metrics should be of the form
:param metrics:
:param report_file:
{'name_of_metric' : {value: (int) or (float), unit: ""}, ...}
"""
if not os.path.exists(report_file):
raise IOError('Report file does not exits : {0}'.format(report_file))
# read current summary report, which contains the metrics
with open(report_file, 'r') as file_in:
result_json = json.load(file_in)
assert isinstance(result_json, dict)
if 'Metrics' in result_json:
for metric in result_json['Metrics']:
if 'Name' in metric and 'Value' in metric:
if metric['Name'] in metrics.keys():
new_value = metrics[metric['Name']]['value']
new_unit = metrics[metric['Name']]['unit']
if new_unit is not None:
metric['Unit'] = new_unit
if new_value is not None:
metric['Value'] = str(new_value)
else:
pass
else:
print 'Metric item : {0} does not have right format'.format(metric)
pass
# update json file with the new values
with open(report_file, 'wb') as file_out:
json.dump(result_json, file_out, indent=4)
else:
print 'Report file {0} does not have any Metrics defined..'
pass
def read_limits():
"""
Reads in limits and modifies the ModelicaUri to the correct one.
Returns:
- the updated limit_dict
- the filter as a list
"""
with open('limits.json', 'r') as f_in:
limit_dict = json.load(f_in)
# use set to avoid checking for duplicates
filter = set()
for limit_item in limit_dict['LimitChecks']:
# drop first part of VariableFullPath update the limit_item
# once the limit.json is generated correctly these two lines can be dropped
modelica_uri = '.'.join(limit_item['VariableFullPath'].split('.')[1:])
modelica_model_rel_uri = limit_item['VariableName']
split_full_path = limit_item['LimitFullPath'].split('/')
modelica_model = split_full_path[-2]
cyphy_relative_uri = '{0}.{1}'.format(modelica_model, modelica_model_rel_uri)
modelica_uri = modelica_uri.replace(modelica_model_rel_uri, cyphy_relative_uri)
limit_item['VariableFullPath'] = modelica_uri
limit_item['ComponentInstanceName'] = split_full_path[-3]
# filter out this variable in the .mat-file
filter.add(modelica_uri)
# Code specific for FANG-I, with no defined VariableName from GME
#limit_var_name = limit_item['VariableName']
limit_var_name = re.sub('\.u(.*)$', '', modelica_uri)
limit_var_name_split = limit_var_name.split('.')
limit_var_name = limit_var_name_split[len(limit_var_name_split)-3] + '=>' + \
limit_var_name_split[len(limit_var_name_split)-1]
limit_item['LimitName'] = limit_var_name
filter = list(filter)
print "Variables for limit-checking : {0}".format(filter)
return limit_dict, filter
def check_limits_and_add_to_report_json(pp, limit_dict):
"""
Check the limits and write out dictionary to summary.report.json
"""
assert isinstance(pp, PostProcess)
for limit_item in limit_dict['LimitChecks']:
modelica_uri = limit_item['VariableFullPath']
limit_value = limit_item['Value']
limit_type = limit_item['Type']
print "--== {0} ==--".format(modelica_uri)
print "Type of Limit : {0}".format(limit_type)
print "Limit : {0} ".format(limit_value)
if limit_type == 'min':
limit_exceeded, actual_value = pp.check_min_limit(modelica_uri, limit_value)
limit_item['LimitExceeded'] = limit_exceeded
limit_item['ActualValue'] = str(actual_value)
elif limit_type == 'max':
limit_exceeded, actual_value = pp.check_max_limit(modelica_uri, limit_value)
limit_item['LimitExceeded'] = limit_exceeded
limit_item['ActualValue'] = str(actual_value)
else:
limit_exceeded_max, actual_max_value = pp.check_max_limit(modelica_uri, limit_value)
limit_exceeded_min, actual_min_value = pp.check_min_limit(modelica_uri, -limit_value)
# determine the actual value depending on which limits were exceeded
if limit_exceeded_max and limit_exceeded_min:
if actual_max_value > abs(actual_min_value):
actual_value = str(actual_max_value)
else:
actual_value = str(abs(actual_min_value))
elif limit_exceeded_max:
actual_value = str(actual_max_value)
elif limit_exceeded_min:
actual_value = str(abs(actual_min_value))
else:
actual_value = ''
limit_item['LimitExceeded'] = limit_exceeded_max or limit_exceeded_min
limit_item['ActualValue'] = actual_value
limit_item['Value'] = str(limit_value)
print "Violation : {0}".format(limit_item["LimitExceeded"])
with open('summary.testresults.json', 'r') as f_in:
sum_rep_json = json.load(f_in)
sum_rep_json['LimitChecks'] = limit_dict['LimitChecks']
with open('summary.testresults.json', 'wb') as f_out:
json.dump(sum_rep_json, f_out, indent=4)
print "Limits updated"
| [
"[email protected]"
] | |
01cabaa83df787a973353fd6f3c195237768f961 | c4a2c5d2ee3bb946333bec267c337858c2eaa87c | /bhiveapi/hivenoderpc.py | 58ce7500c87b948f6e6633ae663e981fa3749a04 | [
"MIT"
] | permissive | TheCrazyGM/bhive | 93b237140def25a8cb4de0160678db116b45d4e0 | 1494e90a99123ecfc5efbd927258f9ba59443e2e | refs/heads/master | 2021-04-10T20:15:59.966431 | 2020-03-22T23:50:52 | 2020-03-22T23:50:52 | 248,962,200 | 3 | 1 | NOASSERTION | 2020-10-27T22:24:53 | 2020-03-21T11:29:02 | Python | UTF-8 | Python | false | false | 9,554 | py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import bytes, int, str
import re
import sys
from .graphenerpc import GrapheneRPC
from . import exceptions
import logging
log = logging.getLogger(__name__)
class HiveNodeRPC(GrapheneRPC):
""" This class allows to call API methods exposed by the witness node via
websockets / rpc-json.
:param str urls: Either a single Websocket/Http URL, or a list of URLs
:param str user: Username for Authentication
:param str password: Password for Authentication
:param int num_retries: Try x times to num_retries to a node on disconnect, -1 for indefinitely
:param int num_retries_call: Repeat num_retries_call times a rpc call on node error (default is 5)
:param int timeout: Timeout setting for https nodes (default is 60)
:param bool use_condenser: Use the old condenser_api rpc protocol on nodes with version
0.19.4 or higher. The settings has no effect on nodes with version of 0.19.3 or lower.
"""
def __init__(self, *args, **kwargs):
""" Init HiveNodeRPC
:param str urls: Either a single Websocket/Http URL, or a list of URLs
:param str user: Username for Authentication
:param str password: Password for Authentication
:param int num_retries: Try x times to num_retries to a node on disconnect, -1 for indefinitely
:param int num_retries_call: Repeat num_retries_call times a rpc call on node error (default is 5)
:param int timeout: Timeout setting for https nodes (default is 60)
"""
super(HiveNodeRPC, self).__init__(*args, **kwargs)
self.next_node_on_empty_reply = False
def set_next_node_on_empty_reply(self, next_node_on_empty_reply=True):
"""Switch to next node on empty reply for the next rpc call"""
self.next_node_on_empty_reply = next_node_on_empty_reply
def rpcexec(self, payload):
""" Execute a call by sending the payload.
It makes use of the GrapheneRPC library.
In here, we mostly deal with Hive specific error handling
:param json payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
if self.url is None:
raise exceptions.RPCConnection("RPC is not connected!")
doRetry = True
maxRetryCountReached = False
while doRetry and not maxRetryCountReached:
doRetry = False
try:
# Forward call to GrapheneWebsocketRPC and catch+evaluate errors
reply = super(HiveNodeRPC, self).rpcexec(payload)
if self.next_node_on_empty_reply and not bool(reply) and self.nodes.working_nodes_count > 1:
self._retry_on_next_node("Empty Reply")
doRetry = True
self.next_node_on_empty_reply = True
else:
self.next_node_on_empty_reply = False
return reply
except exceptions.RPCErrorDoRetry as e:
msg = exceptions.decodeRPCErrorMsg(e).strip()
try:
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
except exceptions.CallRetriesReached:
if self.nodes.working_nodes_count > 1:
self._retry_on_next_node(msg)
doRetry = True
else:
self.next_node_on_empty_reply = False
raise exceptions.CallRetriesReached
except exceptions.RPCError as e:
try:
doRetry = self._check_error_message(e, self.error_cnt_call)
except exceptions.CallRetriesReached:
msg = exceptions.decodeRPCErrorMsg(e).strip()
if self.nodes.working_nodes_count > 1:
self._retry_on_next_node(msg)
doRetry = True
else:
self.next_node_on_empty_reply = False
raise exceptions.CallRetriesReached
except Exception as e:
self.next_node_on_empty_reply = False
raise e
maxRetryCountReached = self.nodes.num_retries_call_reached
self.next_node_on_empty_reply = False
def _retry_on_next_node(self, error_msg):
self.nodes.increase_error_cnt()
self.nodes.sleep_and_check_retries(error_msg, sleep=False, call_retry=False)
self.next()
def _check_error_message(self, e, cnt):
"""Check error message and decide what to do"""
doRetry = False
msg = exceptions.decodeRPCErrorMsg(e).strip()
if re.search("missing required active authority", msg):
raise exceptions.MissingRequiredActiveAuthority
elif re.search("missing required active authority", msg):
raise exceptions.MissingRequiredActiveAuthority
elif re.match("^no method with name.*", msg):
raise exceptions.NoMethodWithName(msg)
elif re.search("Could not find method", msg):
raise exceptions.NoMethodWithName(msg)
elif re.search("Could not find API", msg):
if self._check_api_name(msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self.nodes.disable_node()
self._switch_to_next_node(msg, "ApiNotSupported")
doRetry = True
else:
raise exceptions.ApiNotSupported(msg)
else:
raise exceptions.NoApiWithName(msg)
elif re.search("follow_api_plugin not enabled", msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self._switch_to_next_node(str(e))
doRetry = True
else:
raise exceptions.FollowApiNotEnabled(msg)
elif re.search("irrelevant signature included", msg):
raise exceptions.UnnecessarySignatureDetected(msg)
elif re.search("WinError", msg):
raise exceptions.RPCError(msg)
elif re.search("Unable to acquire database lock", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Request Timeout", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Bad or missing upstream response", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("Internal Error", msg) or re.search("Unknown exception", msg):
self.nodes.sleep_and_check_retries(str(msg), call_retry=True)
doRetry = True
elif re.search("!check_max_block_age", str(e)):
self._switch_to_next_node(str(e))
doRetry = True
elif re.search("Can only vote once every 3 seconds", msg):
raise exceptions.VotedBeforeWaitTimeReached(msg)
elif re.search("out_of_rangeEEEE: unknown key", msg) or re.search("unknown key:unknown key", msg):
raise exceptions.UnkownKey(msg)
elif re.search("Assert Exception:v.is_object(): Input data have to treated as object", msg):
raise exceptions.UnhandledRPCError("Use Operation(op, appbase=True) to prevent error: " + msg)
elif re.search("Client returned invalid format. Expected JSON!", msg):
if self.nodes.working_nodes_count > 1 and self.nodes.num_retries > -1:
self.nodes.disable_node()
self._switch_to_next_node(msg)
doRetry = True
else:
raise exceptions.UnhandledRPCError(msg)
elif msg:
raise exceptions.UnhandledRPCError(msg)
else:
raise e
return doRetry
def _switch_to_next_node(self, msg, error_type="UnhandledRPCError"):
if self.nodes.working_nodes_count == 1:
if error_type == "UnhandledRPCError":
raise exceptions.UnhandledRPCError(msg)
elif error_type == "ApiNotSupported":
raise exceptions.ApiNotSupported(msg)
self.nodes.increase_error_cnt()
self.nodes.sleep_and_check_retries(str(msg), sleep=False)
self.next()
def _check_api_name(self, msg):
error_start = "Could not find API"
known_apis = ['account_history_api', 'tags_api',
'database_api', 'market_history_api',
'block_api', 'account_by_key_api', 'chain_api',
'follow_api', 'condenser_api', 'debug_node_api',
'witness_api', 'test_api',
'network_broadcast_api']
for api in known_apis:
if re.search(error_start + " " + api, msg):
return True
if msg[-18:] == error_start:
return True
return False
def get_account(self, name, **kwargs):
""" Get full account details from account name
:param str name: Account name
"""
if isinstance(name, str):
return self.get_accounts([name], **kwargs)
| [
"[email protected]"
] | |
b9fb87d81b8ea6206160a6408edaca8fa28184b1 | 917974ea96ab36b7fa648dd57762b08e0650f459 | /MySQL/实例/MysqlOperate.py | 4fc8797c3170f610a8f5362ad0be20118f0f1282 | [] | no_license | zhoulongqa/pythonCode | 0d4957c65d2202f7551ba9ab96c06dd86e7b52d5 | 8ffd7503c3e50c5039c907fcf60a028e3829ec40 | refs/heads/master | 2021-09-08T22:23:47.892837 | 2018-03-12T12:20:10 | 2018-03-12T12:20:10 | 124,881,080 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,406 | py | # encoding=utf-8
import MySQLdb
import random
def getDatabaseConnection():
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='123123',
charset='utf8')
cur = conn.cursor()
return conn, cur
def closeDatabase(conn, cur):
cur.close()
conn.close()
def createDatabase(data_base_name):
conn,cur = getDatabaseConnection()
result = cur.execute(
'create database if not exists %s default charset utf8 collate utf8_general_ci;' % data_base_name)
print result
closeDatabase(conn, cur)
def create_table(database_name, table_sql):
conn,cur = getDatabaseConnection()
conn.select_db(database_name)
result = cur.execute(table_sql)
return result
closeDatabase(conn, cur)
def insert_data(database_name, data_sql):
conn,cur = getDatabaseConnection()
conn.select_db(database_name)
result = cur.execute(data_sql)
print result
closeDatabase(conn, cur)
#createDatabase('wangzeliangDB')
table_sql='''CREATE TABLE user( 'id' int(11) default null,'name' VARCHAR(255) DEFAULT NULL,'passwd' VARCHAR(255) DEFAULT NULL,'birthday' DATA DEFAULT NULL)ENGINE=Innodb DEFAULT CHARSET=utf8;'''
data_sql = "insert into user values(1,'Tom','123','1990-01-01')"
create_table('wangzeliangDB',table_sql)
insert_data("wangzeliangDB", data_sql) | [
"[email protected]"
] | |
d15edac876db06faf9c9c07283a6d10c33c1f8f7 | 6d82c2f984855f0d430ebeb9d5d65adae8a6ed94 | /cdent/parser/pir/grammar.py | d3816445808fe4d76e78862d1a4b2149f3acea58 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | ingydotnet/cdent-py | bce12cfc8ffb10060ba3a67970af3649d01ca37c | 013e967f1436269965e166a91e16bcde3995b765 | refs/heads/master | 2023-05-29T19:11:25.698386 | 2011-09-21T15:15:08 | 2011-09-21T15:15:08 | 139,786 | 4 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,085 | py | """
C'Dent Pir parser grammar module.
"""
from cdent.grammar import *
class Grammar():
def __init__(self):
self.__dict__.update(
{ 'BlankLine': Re({'_': '[\\ \\t]*\\r?\\n'}),
'Class': All({'_': [Rule({'_': 'ClassStart'}), Rule({'_': 'ClassBody'}), Rule({'_': 'ClassEnd'})]}),
'ClassBody': All({'_': [Indent({}), Rule({'x': '*', '_': 'Comment'}), Rule({'_': 'Method'}), Any({'x': '*', '_': [Rule({'_': 'Method'}), Rule({'_': 'Comment'})]})]}),
'ClassEnd': Re({'_': ''}),
'ClassStart': Re({'_': '.namespace[\\ \\t]+\\["(\\w+)"\\]\\r?\\n'}),
'Comment': Any({'_': [Rule({'_': 'LineComment'}), Rule({'_': 'BlankLine'})]}),
'DocComment': All({'_': [Rule({'_': 'DocCommentBegin'}), All({'x': '*', '_': [Rule({'!': True, '_': 'DocCommentEnd'}), Rule({'_': 'DocCommentLine'})]}), Rule({'_': 'DocCommentEnd'})]}),
'DocCommentBegin': Re({'_': '#{3}\\r?\\n'}),
'DocCommentEnd': Re({'_': '#{3}\\r?\\n'}),
'DocCommentLine': Re({'_': '#[\\ \\t]?(.*\\r?\\n)'}),
'Id': Re({'_': '\\w+'}),
'IncludeCDent': Re({'_': 'use CDent;'}),
'Line': Re({'_': '.*\\r?\\n'}),
'LineComment': Re({'_': '#(.*\\r?\\n)'}),
'Method': All({'_': [Rule({'_': 'MethodStart'}), Rule({'_': 'MethodBody'}), Rule({'_': 'MethodEnd'})]}),
'MethodBody': All({'_': [Indent({}), Rule({'_': 'Statement'}), Any({'x': '*', '_': [Rule({'_': 'Statement'}), Rule({'_': 'Comment'})]}), Undent({})]}),
'MethodEnd': Re({'_': '.end\\r?\\n'}),
'MethodStart': Re({'_': '.sub[\\ \\t]+(\\w+)[\\ \\t]+:method\\r?\\n'}),
'Module': All({'_': [Rule({'_': 'ModuleStart'}), Rule({'x': '?', '_': 'DocComment'}), Rule({'x': '*', '_': 'Comment'}), Rule({'x': '?', '_': 'IncludeCDent'}), Rule({'x': '*', '_': 'Comment'}), Rule({'_': 'Class'}), Any({'x': '*', '_': [Rule({'_': 'Class'}), Rule({'_': 'Comment'})]}), Rule({'_': 'ModuleEnd'}), Rule({'x': '*', '_': 'Comment'})]}),
'ModuleEnd': Re({'_': ''}),
'ModuleStart': Re({'_': ''}),
'PrintLn': Re({'_': 'say[\\ \\t]+(.+)\\r?\\n'}),
'Statement': Any({'_': [Rule({'_': 'PrintLn'}), Rule({'_': 'Comment'})]}),
'line_comment_start': Re({'_': '#'})}
)
| [
"[email protected]"
] | |
327f9765f5dd9fd7ec5ddb1747f3de2bffe48a72 | 5acc20092ee93935594a7e0522924245a43e5531 | /support_vector_machines/plot_oneclass_svm.py | b3dd6215ed3a9101ee39baa85ae115e8380814cf | [] | no_license | shengchaohua/sklearn-examples | aae2332c4382a57a70c1887777c125e6dc4579d6 | 1dac6a9b5e703185a8da1df7c724022fbd56a9e4 | refs/heads/master | 2020-05-05T01:19:20.037746 | 2019-10-18T08:55:01 | 2019-10-18T08:55:01 | 179,599,221 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,014 | py | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn import svm
xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500))
# Generate train data
X = 0.3 * np.random.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * np.random.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))
# Fit the model
clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)
clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_test = clf.predict(X_test)
y_pred_outliers = clf.predict(X_outliers)
n_error_train = y_pred_train[y_pred_train == -1].size
n_error_test = y_pred_test[y_pred_test == -1].size
n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size
# Plot the line, the points, and the nearest vectors to the plane
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.title("Novelty Detection")
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu)
a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred')
s = 40
b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s, edgecolors='k')
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s,
edgecolors='k')
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s,
edgecolors='k')
plt.axis('tight')
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.legend([a.collections[0], b1, b2, c],
["learned frontier", "training observations",
"new regular observations", "new abnormal observations"],
loc="upper left",
prop=matplotlib.font_manager.FontProperties(size=11))
plt.xlabel(
"error train: %d/200 ; errors novel regular: %d/40 ; "
"errors novel abnormal: %d/40"
% (n_error_train, n_error_test, n_error_outliers))
plt.show()
| [
"[email protected]"
] | |
3fa18fbb6c6c984c8016aa0330fccb80274eeeb2 | e4414bd8152e52855db7ab9065ae12b7329143e0 | /python/src/two_more_random.py | b87bee878dbdfeb7ad6ff81d257bf7e780ba71dd | [] | no_license | catalinc/programmingpraxis-solutions | 39cb847877ec46d2fb85740791c24889ab5654a8 | c0b13906aa76ffac705bf108db138fb9a38bc16a | refs/heads/master | 2021-03-27T16:46:47.781839 | 2017-09-09T15:17:38 | 2017-09-09T15:17:38 | 53,532,233 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 623 | py | # A solution for http://programmingpraxis.com/2012/08/21/two-more-random-exercises/
import math
def rand_middle_square(seed):
n = seed
seed_len = int(round(math.log(seed, 10)))
while True:
yield n
n = (n * n) / (10 ** (seed_len / 2)) % (10 ** seed_len)
def randu(seed):
n = seed
while True:
yield n
n = (65539 * n) % 2147483648
def random(count, seed, rand_fn):
nums = []
random_gen = rand_fn(seed)
for _ in xrange(count):
nums.append(random_gen.next())
return nums
print(random(5, 675248, rand_middle_square))
print(random(5, 7, randu))
| [
"[email protected]"
] | |
1a9658d9fae0218278448f9af37f2b5c5e6f3593 | b9696a277966d85548ebf23c77d24554dd98b1c1 | /LasAndClf-dev/get_data_packages/collectdata2bc.py | 9ff8239bd1826c85a88010e5fb370669aed10557 | [] | no_license | hsulab/multiVASP | f1d277b015f97532588f4db21ce14bae68dafed9 | e05bf8c03ff1653ad2621fdd61b8a706138dc37b | refs/heads/master | 2020-03-07T09:12:32.199150 | 2019-10-22T14:30:18 | 2019-10-22T14:30:18 | 127,394,903 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,986 | py | #!/usr/local/bin/python3
# -*- coding: utf-8 -*-
import os
import re
import time
import numpy as np
import pandas as pd
"""
"""
class GeoData():
# Geometry Features Data
def __init__(self, name):
self.name = name
# Path Settings
__dirpath = os.path.join(os.path.expanduser('~'), 'Desktop/CH4_DS')
def set_path(self, path):
"""Set data path."""
self.__dirpath = path
def get_path(self):
"""Get data path."""
self.__dirpath
# Get Csv Name
def __csvname(self):
"""Get data csvfile."""
for file_name in os.listdir(self.__dirpath):
if re.match(self.name, file_name):
csv_name = file_name
return csv_name
# Get df col=[name, feas]
def df(self, numbers=-1):
"""Get dataframe."""
csv = os.path.join(self.__dirpath, self.__csvname())
df = pd.read_csv(csv, index_col=0)
fea_numbers = len(df.columns) - 3
#print(self.name+' has '+str(fea_numbers)+' features.')
if numbers == -1:
numbers = fea_numbers
feas = []
for i in range(3, numbers+3):
feas.append(df.columns[i])
return df.loc[:,tuple(['name']+feas)]
class EneData(GeoData):
'Energy Data'
def allE(self):
df = self.df()
mtype = [] # mechanism type
mE = []
for i in range(df.shape[0]):
if df.loc[i, 'E_ts'] == 'np.nan' and df.loc[i, 'E_tsra'] == 'np.nan':
mtype.append('np.nan')
mE.append('np.nan')
elif df.loc[i, 'E_ts'] == 'np.nan' and df.loc[i, 'E_tsra'] != 'np.nan':
mtype.append('tsra')
mE.append(df.loc[i, 'E_tsra'])
elif df.loc[i, 'E_ts'] != 'np.nan' and df.loc[i, 'E_tsra'] == 'np.nan':
mtype.append('ts')
mE.append(df.loc[i, 'E_ts'])
elif df.loc[i, 'E_ts'] > df.loc[i, 'E_tsra']:
mtype.append('tsra')
mE.append(df.loc[i, 'E_tsra'])
else:
mtype.append('ts')
mE.append(df.loc[i, 'E_ts'])
df.loc[:, 'mtype'] = mtype
df.loc[:, 'mE'] = mE
return df
def get_data():
"""
Description:
Get Geo DataFrame.
descriptors: distance 45, angles 360, dihedrals 630.
"""
print('Load Data...')
suf = GeoData('suf').df()
hab3 = GeoData('Hab3').df()
ch3ab = GeoData('CH3ab').df()
#
delta_df = pd.DataFrame()
delta_df.loc[:, 'name'] = suf.loc[:, 'name']
cols = suf.columns[1:]
for col in cols:
t = col.strip('suf')
delta_df.loc[:, t+'hab3'] = hab3.loc[:, t+'Hab3'] - suf.loc[:, t+'suf']
for col in cols:
t = col.strip('suf')
delta_df.loc[:, t+'ch3ab'] = ch3ab.loc[:, t+'CH3ab'] - suf.loc[:, t+'suf']
'Merge geofeas'
print('This set has ', delta_df.shape[0], 'samples.')
print('This set has ', delta_df.shape[1]-1, 'features.')
'Get numbers of geofeas'
print('Merge Data...')
E_feas = ['name', 'mtype', 'E_ts', 'E_tsra', 'mE', 'E_Hab3', 'E_CH3ab']
fE = EneData('fE').allE().loc[:, E_feas] # reaction Energy
e_numbers = fE.shape[1]
di = pd.merge(fE, delta_df, on='name')
new_di = di.loc[di.loc[:,'mtype']!='np.nan', :]
# !!!
new_di = new_di.loc[di.loc[:,'name']!='pureMoO2', :] # CH3ab wrong
new_di = new_di.loc[di.loc[:,'name']!='pureMnO2', :] # CH3ab wrong
new_di = new_di.loc[di.loc[:,'name']!='dopCrO2_Ru', :] # CH3ab wrong
print('Energy and Geometry set has ', new_di.shape[0], 'samples.')
print('Energy and Geometry set has ', new_di.shape[1]-5, 'features.')
# Save data -> ./CH4_DataSet.csv
merged_data_csv = './CH4_neo.csv'
print('Save data -> %s' %merged_data_csv)
new_di.to_csv(merged_data_csv)
return new_di # [name, mtype, mE, geo ... feas]
if __name__ == '__main__':
'geoFeatures Total 1035'
get_data()
| [
"[email protected]"
] | |
6b93ecdbb92e6d5706872b8722d49a411dcbc403 | fdd6c6a1b8e6e7e8cd267de97a1b435777342e1b | /tests/test_altdphi.py | 3a840650b023a7e240e31fe5fb070f9cd216cce3 | [
"BSD-3-Clause"
] | permissive | TaiSakuma/altdphi | bccec475432dec5aebafda4e47d12fcc5cf048d6 | ed74418fe6e0e4b08582d80093102795276d17d6 | refs/heads/master | 2021-03-16T08:45:10.249447 | 2019-05-14T16:44:40 | 2019-05-14T16:44:40 | 118,086,863 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,152 | py | # Tai Sakuma <[email protected]>
import numpy as np
import pytest
from altdphi import AltDphi
from .testing import assert_altdphi_equal
from .expected import *
##__________________________________________________________________||
@pytest.fixture(
params=[
(event_nojet, altdphi_nojet, altdphi_met_nojet),
(event_monojet, altdphi_monojet, altdphi_met_monojet),
(event_two_jets, altdphi_two_jets, altdphi_met_two_jets),
(event_three_jets, altdphi_three_jets, altdphi_met_three_jets),
(event_four_jets, altdphi_four_jets, altdphi_met_four_jets),
(event_twelve_jets, altdphi_twelve_jets, altdphi_met_twelve_jets),
],
ids=('nojet', 'monojet', 'two_jets', 'three_jets', 'four_jets', 'twelve_jets')
)
def event_altdphi(request):
return request.param
def test_altdphi(event_altdphi):
event = event_altdphi[0]
expected_altdphi = event_altdphi[1]
pt = event['jet_pt']
phi = event['jet_phi']
actual_altdphi = AltDphi(pt=pt, phi=phi)
assert_altdphi_equal(expected_altdphi, actual_altdphi)
def test_altdphi_met(event_altdphi):
event = event_altdphi[0]
expected_altdphi = event_altdphi[2]
pt = event['jet_pt']
phi = event['jet_phi']
met = event['met']
met_phi = event['met_phi']
actual_altdphi = AltDphi(pt=pt, phi=phi, mht=met, mht_phi=met_phi)
assert_altdphi_equal(expected_altdphi, actual_altdphi)
##__________________________________________________________________||
def test_altdphi_monojet_is_minus_mht():
event = event_monojet
pt = event['jet_pt']
phi = event['jet_phi']
altdphi = AltDphi(pt=pt, phi=phi)
assert pt[0] == altdphi.mht
assert [1] == altdphi.f
assert [-1] == altdphi.cos_dphi
def test_altdphi_monojet_is_not_minus_mht():
event = event_monojet
pt = event['jet_pt']
phi = event['jet_phi']
mht = event['met']
mht_phi = event['met_phi']
altdphi = AltDphi(pt=pt, phi=phi, mht=mht, mht_phi=mht_phi)
assert pt[0] != altdphi.mht
assert [1] != altdphi.f
assert [-1] != altdphi.cos_dphi
##__________________________________________________________________||
| [
"[email protected]"
] | |
728158a4d9026a97e17a89c008935c78bba93cc3 | 2f6817fc8f6ddb48f5f88c913d8e40b672fc3dbf | /MLP/lec13-4[Kmeans].py | 84ab79f09472a0230ce9c1721fc34ce47e22cf64 | [] | no_license | cutz-j/TodayILearned | 320b5774de68a0f4f68fda28a6a8b980097d6ada | 429b24e063283a0d752ccdfbff455abd30ba3859 | refs/heads/master | 2020-03-23T17:34:51.389065 | 2018-11-24T08:49:41 | 2018-11-24T08:49:41 | 141,865,899 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | py | import pandas as pd
from sklearn import datasets
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
iris = datasets.load_iris()
labels = pd.DataFrame(iris.target)
labels.columns = ['labels']
data = pd.DataFrame(iris.data)
data.columns = ['Sepal_length', 'Sepal_width', 'Petal_length', 'Petal_width']
data = pd.concat([data, labels], axis=1)
feature = data[['Sepal_length', 'Sepal_width']]
model = KMeans(n_clusters=5, algorithm='auto')
scaler = StandardScaler()
pipeline = make_pipeline(scaler, model)
pipeline.fit(feature)
predict = pd.DataFrame(pipeline.predict(feature))
ks = range(1,10)
inertias = []
for k in ks:
model = KMeans(n_cluster=k)
model.fit(feature)
inertias.append(model.inertia_)
predict.columns = ['predict']
r = pd.concat([feature, predict], axis=1)
plt.scatter(r['Sepal_length'], r['Sepal_width'], c=r['predict'], alpha=0.5)
centers = pd.DataFrame(model.cluster_centers_, columns=['Sepal_length', 'Sepal_width'])
#center_x = centers['Sepal_length']
#center_y = centers['Sepal_width']
#plt.scatter(center_x, center_y, s=50, marker='D', c='r')
#plt.show() | [
"[email protected]"
] | |
c3e43afbae66f6aa4658cc2e059a94f5e45187c6 | b5d738624d7016f7e10796485624c567099374ab | /starthinker/util/dcm/schema/Activity_Metrics.py | cfddd432e314017727e16532df1791ab7115aa76 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | dvandra/starthinker | 212d8166752c36fbe6a5e0988fb5ad598f35c4a6 | 07a8c1f8bf3c7493b1833d54ca0acc9305a04bc9 | refs/heads/master | 2020-06-14T05:19:08.348496 | 2019-07-02T17:54:06 | 2019-07-02T17:54:06 | 194,915,001 | 1 | 0 | Apache-2.0 | 2019-07-02T18:25:23 | 2019-07-02T18:25:23 | null | UTF-8 | Python | false | false | 3,495 | py | ###########################################################################
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
###########################################################################
Activity_Metrics_Schema = [
{ "name":"Click_Through_Conversions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Click_Through_Revenue", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"View_Through_Conversions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"View_Through_Revenue", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Click_Through_Conversions_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Click_Through_Revenue_Cross_Environment", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Click_Through_Conversion_Events_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Total_Conversions_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Total_Revenue_Cross_Environment", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Total_Conversion_Events_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"View_Through_Conversions_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"View_Through_Revenue_Cross_Environment", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"View_Through_Conversion_Events_Cross_Environment", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Dynamic_Element_Click_Through_Conversions", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Dynamic_Element_Total_Conversions", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Dynamic_Element_View_Through_Conversions", "type":"INTEGER", "mode":"NULLABLE" },
{ "name":"Natural_Search_Actions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Natural_Search_Revenue", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Natural_Search_Transactions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Action_Conversion_Percentage", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Paid_Search_Actions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Average_Cost_Per_Action", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Average_Cost_Per_Transaction", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Average_Dcm_Transaction_Amount", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Paid_Search_Revenue", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Spend_Per_Transaction_Revenue", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Transaction_Conversion_Percentage", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Floodlight_Paid_Search_Transaction_Revenue_Per_Spend", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Paid_Search_Transactions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Total_Conversions", "type":"FLOAT", "mode":"NULLABLE" },
{ "name":"Total_Revenue", "type":"FLOAT", "mode":"NULLABLE" }
] | [
"[email protected]"
] | |
8147ee54973388356c60c895c778940a1eee9e84 | 8d014c5513a0eeca086010b018b67336f8d042e0 | /wicam_vlc.py | 480b078447c514a89f8b8c568d94727f18331028 | [] | no_license | rkuo2000/cv2 | 26ce0a06b4040eabb82319ec44cab5c3639b9495 | 16e64e7092d6654ea470e469d6b15f308ecd1788 | refs/heads/master | 2022-10-12T00:11:35.964818 | 2022-09-30T06:50:35 | 2022-09-30T06:50:35 | 108,848,948 | 5 | 29 | null | 2022-09-29T11:01:48 | 2017-10-30T12:38:58 | Python | UTF-8 | Python | false | false | 457 | py | # Install VLC Player on PC
# Add Environtment System Variables: VLC_PLUGIN_PATH = C:\Program Files\VideoLAN\VLC\plugins
# pip install python-vlc
# WiFi connected to WiCam module (streaming video)
import cv2
import vlc
#player=vlc.MediaPlayer('rtsp://192.168.100.1/cam1/h264')
player=vlc.MediaPlayer('rtsp://192.168.100.1/cam1/mpeg4')
while 1:
frame = player.play()
cv2.imshow('VIDEO',frame)
cv2.waitKey(1)
cv2.destroyAllWindows() | [
"[email protected]"
] | |
2d50a33f7a6f96a094b2b5a8c3082d850f8c3b9a | dea8cfa596d52d5db0e28ac43504e7212b43081b | /python/AtCoder Beginner Contest 123/Five Dishes .py | 5b3b87bc101c5841242a539782cdaf0a6b8925b9 | [] | no_license | Yuta123456/AtCoder | 9871a44f12a8fca87b0e2863a999b716128de1ac | ca04422699719563e311f7d973459ba1dc238c2c | refs/heads/master | 2023-01-04T22:33:54.120454 | 2020-11-04T05:20:37 | 2020-11-04T05:20:37 | 286,409,112 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 483 | py | def ceil(x):
k = x % 10
if k == 0:
return x
else:
return x + (10 - k)
d = []
for i in range(5):
d.append(int(input()))
d_min = []
min = 124
sum = 0
index = -1
for i in range(5):
d_min.append((d[i]) % 10)
for i in range(5):
if d_min[i] != 0:
if min > d_min[i]:
min = d_min[i]
index = i
if index == -1:
index = 0
for i in range(5):
if i != index:
sum = sum + ceil(d[i])
sum += d[index]
print(sum)
| [
"[email protected]"
] | |
40b35aefa6aa53d7c9e97137d474309dfdb68a8e | 0d0cf0165ca108e8d94056c2bae5ad07fe9f9377 | /15_Feature_Engineering_for_Machine_Learning_in_Python/2_Dealing_with_Messy_Data/howSparseIsMyData.py | 6c17397750627c6381fd7a7979223548ea23969e | [] | no_license | MACHEIKH/Datacamp_Machine_Learning_For_Everyone | 550ec4038ebdb69993e16fe22d5136f00101b692 | 9fe8947f490da221430e6dccce6e2165a42470f3 | refs/heads/main | 2023-01-22T06:26:15.996504 | 2020-11-24T11:21:53 | 2020-11-24T11:21:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 679 | py | # How sparse is my data?
# Most data sets contain missing values, often represented as NaN (Not a Number). If you are working with Pandas you can easily check how many missing values exist in each column.
# Let's find out how many of the developers taking the survey chose to enter their age (found in the Age column of so_survey_df) and their gender (Gender column of so_survey_df).
# Instructions 1/2
# 50 XP
# Subset the DataFrame to only include the 'Age' and 'Gender' columns.
# Print the number of non-missing values in both columns.
# Subset the DataFrame
sub_df = so_survey_df[['Age', 'Gender']]
# Print the number of non-missing values
print(sub_df.notnull().sum())
| [
"[email protected]"
] | |
42d6cbdf04e5bbb6398833f05d3653f58dbacfa6 | c5291e50a3c72c885922378573a0ad423fcedf05 | /analysis/analysis/urls.py | 0a94cc17c066e5075d59765c816f00b7aac7ce4e | [] | no_license | raghurammanyam/django-projects | bcc3ed6285882af437a2995514cef33760fb063e | dd20ae354f7f111a0176a1cc047c099bd23e9f05 | refs/heads/master | 2022-12-12T19:22:31.698114 | 2018-12-09T09:41:45 | 2018-12-09T09:41:45 | 137,443,359 | 0 | 0 | null | 2022-11-22T03:01:07 | 2018-06-15T05:08:15 | Python | UTF-8 | Python | false | false | 929 | py | """analysis URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.conf.urls import url,include
#from django.urls import path, include
from django.http import HttpResponse
from django.conf import settings
from data import urls
urlpatterns = [
url('admin/',(admin.site.urls)),
url(r'^',include('data.urls')),
]
| [
"[email protected]"
] | |
2093ce0cb85111f3f214151ed4bcb78b1d2e34fc | ff4fe07752b61aa6404f85a8b4752e21e8a5bac8 | /challenge-209/eric-cheung/python/ch-2.py | 624ac7029fd2589ae8c5e87fe90970b576910183 | [] | no_license | choroba/perlweeklychallenge-club | 7c7127b3380664ca829158f2b6161c2f0153dfd9 | 2b2c6ec6ece04737ba9a572109d5e7072fdaa14a | refs/heads/master | 2023-08-10T08:11:40.142292 | 2023-08-06T20:44:13 | 2023-08-06T20:44:13 | 189,776,839 | 0 | 1 | null | 2019-06-01T20:56:32 | 2019-06-01T20:56:32 | null | UTF-8 | Python | false | false | 1,044 | py |
## arrAccount = [["A", "[email protected]", "[email protected]"], ["B", "[email protected]"], ["A", "[email protected]", "[email protected]"]] ## Example 1
arrAccount = [["A", "[email protected]", "[email protected]"], ["B", "[email protected]"], ["A", "[email protected]"], ["B", "[email protected]", "[email protected]"]] ## Example 2
arrUser = [arrAccount[0][0]]
arrEmail = [arrAccount[0][1:]]
arrFinal = []
for nIndx in range(1, len(arrAccount)):
if arrAccount[nIndx][0] not in arrUser:
arrUser.append(arrAccount[nIndx][0])
arrEmail.append(arrAccount[nIndx][1:])
else:
nFindIndx = arrUser.index(arrAccount[nIndx][0])
if len(list(set(arrEmail[nFindIndx]) & set(arrAccount[nIndx][1:]))) == 0:
arrUser.append(arrAccount[nIndx][0])
arrEmail.append(arrAccount[nIndx][1:])
else:
arrEmail[nFindIndx] = sorted(list(set(arrEmail[nFindIndx] + arrAccount[nIndx][1:])))
## print (arrUser)
## print (arrEmail)
for nIndx in range(0, len(arrUser)):
arrFinal.append([arrUser[nIndx], str(arrEmail[nIndx][:])[1:-1]])
print (arrFinal)
| [
"[email protected]"
] | |
19cdad09fcea597b9049e86da3c0e55f919ffb8e | 14f30311d0c93053d159118f5b978f26352fa201 | /NAIP/loop_FeatureCollection.py | 9c19c5419f0d1ff011badcc08639be57065e84e5 | [
"MIT"
] | permissive | kylebarron/earthengine-py-notebooks | 590a343c5011f3e9a346c2379016e262aa13801f | 4e9e3bae244fb66284f77c264f19aa297fb0fea1 | refs/heads/master | 2022-07-31T07:33:21.109880 | 2020-05-18T23:42:26 | 2020-05-18T23:42:26 | 257,686,790 | 0 | 0 | MIT | 2020-04-21T18:50:58 | 2020-04-21T18:50:57 | null | UTF-8 | Python | false | false | 8,278 | py | # %%
"""
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/NAIP/loop_FeatureCollection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/loop_FeatureCollection.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/NAIP/loop_FeatureCollection.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td>
</table>
"""
# %%
"""
## Install Earth Engine API and geemap
Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.
The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemap#dependencies), including earthengine-api, folium, and ipyleaflet.
**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60#issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).
"""
# %%
# Installs geemap package
import subprocess
try:
import geemap
except ImportError:
print('geemap package not installed. Installing ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap'])
# Checks whether this notebook is running on Google Colab
try:
import google.colab
import geemap.eefolium as emap
except:
import geemap as emap
# Authenticates and initializes Earth Engine
import ee
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
# %%
"""
## Create an interactive map
The default basemap is `Google Satellite`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py#L13) can be added using the `Map.add_basemap()` function.
"""
# %%
Map = emap.Map(center=[40,-100], zoom=4)
Map.add_basemap('ROADMAP') # Add Google Map
Map
# %%
"""
## Add Earth Engine Python script
"""
# %%
# Add Earth Engine dataset
year = 2015
collection = ee.ImageCollection('USDA/NAIP/DOQQ')
startTime = ee.Date(str(year) + '-01-01')
endTime = ee.Date(str(year) + '-12-31')
# year = startTime.get('year').getInfo()
# print(year)
fromFT = ee.FeatureCollection('ft:1CLldB-ULPyULBT2mxoRNv7enckVF0gCQoD2oH7XP')
# count = fromFT.size().getInfo()
# print(count)
polys = fromFT.geometry()
centroid = polys.centroid()
lng, lat = centroid.getInfo()['coordinates']
# print("lng = {}, lat = {}".format(lng, lat))
values = fromFT.reduceColumns(ee.Reducer.toList(2), ['system:index', 'name']).getInfo()['list']
# print(values)
Map.setCenter(lng, lat, 10)
def subsetNAIP(img_col, startTime, endTime, fc):
img = img_col.filterDate(startTime, endTime).filterBounds(fc).mosaic().clip(fc)
return img
def calNDWI(image):
"""A function to compute NDWI."""
ndwi = image.normalizedDifference(['G', 'N'])
ndwiViz = {'min': 0, 'max': 1, 'palette': ['00FFFF', '0000FF']}
ndwiMasked = ndwi.updateMask(ndwi.gte(0.2))
ndwi_bin = ndwiMasked.gt(0)
patch_size = ndwi_bin.connectedPixelCount(500, True)
large_patches = patch_size.eq(500)
large_patches = large_patches.updateMask(large_patches)
opened = large_patches.focal_min(1).focal_max(1)
return opened
def rasterToVector(img, fc):
vec = img.reduceToVectors(geometry=fc, eightConnected=True, maxPixels=59568116121, crs=img.projection(), scale=1)
return vec
def exportToDrive(vec, filename):
taskParams = {
'driveFolder': 'image',
'fileFormat': 'KML'
}
task = ee.batch.Export.table(vec, filename, taskParams)
task.start()
vis = {'bands': ['N', 'R', 'G']}
for (id, name) in values:
watershed = fromFT.filter(ee.Filter.eq('system:index', str(id)))
filename = "Y" + str(year) + "_" + str(id) + "_" + str(name).replace(" ", "_")
print(filename)
image = subsetNAIP(collection, startTime, endTime, watershed)
ndwi = calNDWI(image)
vector = rasterToVector(ndwi, watershed)
exportToDrive(vector, filename)
# Map.addLayer(image, vis)
# Map.addLayer(vector)
# for i in range(2, 2 + count):
# watershed = fromFT.filter(ee.Filter.eq('system:index', str(i)))
# re = fc.filterBounds(watershed)
# task = ee.batch.Export.table(re, 'watershed-' + str(i), taskParams)
# task.start()
#
#
#
# lng_lat = ee.Geometry.Point(lng, lat)
# naip = collection.filterBounds(polys)
# naip_2015 = naip.filterDate('2015-01-01', '2015-12-31')
# ppr = naip_2015.mosaic()
#
# count = naip_2015.size().getInfo()
# print("Count: ", count)
#
# # print(naip_2015.size().getInfo())
# vis = {'bands': ['N', 'R', 'G']}
# Map.setCenter(lng, lat, 12)
# Map.addLayer(ppr,vis)
# # Map.addLayer(polys)
#
# def NDWI(image):
# """A function to compute NDWI."""
# ndwi = image.normalizedDifference(['G', 'N'])
# ndwiViz = {'min': 0, 'max': 1, 'palette': ['00FFFF', '0000FF']}
# ndwiMasked = ndwi.updateMask(ndwi.gte(0.05))
# ndwi_bin = ndwiMasked.gt(0)
# patch_size = ndwi_bin.connectedPixelCount(500, True)
# large_patches = patch_size.eq(500)
# large_patches = large_patches.updateMask(large_patches)
# opened = large_patches.focal_min(1).focal_max(1)
# return opened
#
# ndwi_collection = naip_2015.map(NDWI)
# # Map.addLayer(ndwi_collection)
# # print(ndwi_collection.getInfo())
#
# # downConfig = {'scale': 10, "maxPixels": 1.0E13, 'driveFolder': 'image'} # scale means resolution.
# # img_lst = ndwi_collection.toList(100)
# #
# # taskParams = {
# # 'driveFolder': 'image',
# # 'driveFileNamePrefix': 'ndwi',
# # 'fileFormat': 'KML'
# # }
# #
# # for i in range(0, count):
# # image = ee.Image(img_lst.get(i))
# # name = image.get('system:index').getInfo()
# # print(name)
# # # task = ee.batch.Export.image(image, "ndwi2-" + name, downConfig)
# # # task.start()
#
# mosaic = ndwi_collection.mosaic().clip(polys)
# fc = mosaic.reduceToVectors(eightConnected=True, maxPixels=59568116121, crs=mosaic.projection(), scale=1)
# # Map.addLayer(fc)
# taskParams = {
# 'driveFolder': 'image',
# 'driveFileNamePrefix': 'water',
# 'fileFormat': 'KML'
# }
#
# count = fromFT.size().getInfo()
# Map.setCenter(lng, lat, 10)
#
# for i in range(2, 2 + count):
# watershed = fromFT.filter(ee.Filter.eq('system:index', str(i)))
# re = fc.filterBounds(watershed)
# # task = ee.batch.Export.table(re, 'watershed-' + str(i), taskParams)
# # task.start()
# # Map.addLayer(fc)
#
#
# # lpc = fromFT.filter(ee.Filter.eq('name', 'Little Pipestem Creek'))
# %%
"""
## Display Earth Engine data layers
"""
# %%
Map.addLayerControl() # This line is not needed for ipyleaflet-based Map.
Map | [
"[email protected]"
] | |
5e3155e560a1c4c9932aad5f2150648b1da46f76 | fd7d7e1410874d18823bbe3c0f3c521cb54e079c | /news/migrations/0008_auto_20191002_1652.py | 50dcb8502c426938f35aa56cdf27f8b4495221b8 | [
"MIT"
] | permissive | alex-muliande/tribune | 9c1728311e42b16cf90e3b6e94b64a2b1ed3c8be | 86316dd4b20a76320b4b20b86266f89aac02a326 | refs/heads/master | 2023-08-03T13:20:47.852749 | 2019-10-03T09:25:46 | 2019-10-03T09:25:46 | 212,532,363 | 1 | 0 | MIT | 2021-09-08T01:19:17 | 2019-10-03T08:37:00 | Python | UTF-8 | Python | false | false | 466 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-10-02 13:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0007_article_article_image'),
]
operations = [
migrations.AlterField(
model_name='article',
name='article_image',
field=models.ImageField(upload_to='articles/'),
),
]
| [
"[email protected]"
] | |
39e6bf4ecf39d328147ec7c400a110efd5dcabae | 292b43454189f1cb5e67fc0a6f77b9b76cc5c156 | /dvaapp/views.py | 66c904e64b907a77f5ec8839082008beb94f1765 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | junjiez/DeepVideoAnalytics | b9f4e00d800c972ae71233699f341d6f733c2d61 | 03e708a12e1941cedb1449fc7bbc02b3c0fca1d2 | refs/heads/master | 2021-06-25T21:18:49.767732 | 2017-09-12T19:16:22 | 2017-09-12T19:16:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 53,986 | py | from django.shortcuts import render, redirect
from django.conf import settings
from django.http import JsonResponse
import requests
import glob
import json
from django.views.generic import ListView, DetailView
from django.utils import timezone
from .forms import UploadFileForm, YTVideoForm, AnnotationForm
from .models import Video, Frame, DVAPQL, QueryResults, TEvent, IndexEntries, Region, VDNServer, \
LOPQCodes, Tube, Detector, Segment, FrameLabel, SegmentLabel, \
VideoLabel, RegionLabel, TubeLabel, Label, ManagementAction, StoredDVAPQL, Analyzer,\
Indexer, Retriever, SystemState, QueryRegion
from dva.celery import app
from dvaapp.operations import queuing
import serializers
from rest_framework import viewsets, mixins
from django.contrib.auth.models import User
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from django.db.models import Count
import math
from django.db.models import Max
from shared import handle_uploaded_file, create_annotation, handle_video_url, pull_vdn_list, \
import_vdn_dataset_url, create_detector_dataset, import_vdn_detector_url, refresh_task_status, \
delete_video_object
from operations.processing import DVAPQLProcess
from django.contrib.auth.decorators import user_passes_test,login_required
from django.utils.decorators import method_decorator
from django.contrib.auth.mixins import UserPassesTestMixin
from django_celery_results.models import TaskResult
from rest_framework.authtoken.models import Token
import logging
import defaults
try:
from django.contrib.postgres.search import SearchVector
except ImportError:
SearchVector = None
logging.warning("Could not load Postgres full text search")
from examples import EXAMPLES
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(LoginRequiredMixin, self).dispatch(*args, **kwargs)
def user_check(user):
return user.is_authenticated or settings.AUTH_DISABLED
def force_user_check(user):
return user.is_authenticated
class UserViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = User.objects.all()
serializer_class = serializers.UserSerializer
class SystemStateViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = SystemState.objects.all()
serializer_class = serializers.SystemStateSerializer
class VideoViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Video.objects.all()
serializer_class = serializers.VideoSerializer
class AnalyzerViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Analyzer.objects.all()
serializer_class = serializers.AnalyzerSerializer
class IndexerViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Indexer.objects.all()
serializer_class = serializers.IndexerSerializer
class RetrieverViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Retriever.objects.all()
serializer_class = serializers.RetrieverSerializer
class DetectorViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Detector.objects.all()
serializer_class = serializers.DetectorSerializer
class FrameViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Frame.objects.all()
serializer_class = serializers.FrameSerializer
filter_fields = ('frame_index', 'subdir', 'name', 'video')
class FrameLabelViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = FrameLabel.objects.all()
serializer_class = serializers.FrameLabelSerializer
filter_fields = ('frame_index','segment_index', 'video')
class RegionLabelViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = RegionLabel.objects.all()
serializer_class = serializers.RegionLabelSerializer
class VideoLabelViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = VideoLabel.objects.all()
serializer_class = serializers.VideoLabelSerializer
class SegmentLabelViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = SegmentLabel.objects.all()
serializer_class = serializers.SegmentLabelSerializer
class TubeLabelViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin,
mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = TubeLabel.objects.all()
serializer_class = serializers.TubeLabelSerializer
class SegmentViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Segment.objects.all()
serializer_class = serializers.SegmentSerializer
filter_fields = ('segment_index','video')
class QueryRegionViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = QueryRegion.objects.all()
serializer_class = serializers.QueryRegionSerializer
class RegionViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin,
viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Region.objects.all()
serializer_class = serializers.RegionSerializer
filter_fields = ('video',)
class DVAPQLViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = DVAPQL.objects.all()
serializer_class = serializers.DVAPQLSerializer
def perform_create(self, serializer):
instance = serializer.save(user=self.request.user)
p = DVAPQLProcess(instance)
spec = json.loads(self.request.POST.get('script'))
p.create_from_json(spec, self.request.user)
p.launch()
def perform_update(self, serializer):
"""
Immutable Not allowed
:param serializer:
:return:
"""
raise NotImplementedError
def perform_destroy(self, instance):
"""
:param instance:
:return:
"""
raise ValueError, "Not allowed to delete"
class QueryResultsViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = QueryResults.objects.all()
serializer_class = serializers.QueryResultsSerializer
filter_fields = ('frame', 'video')
class TEventViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = TEvent.objects.all()
serializer_class = serializers.TEventSerializer
filter_fields = ('video', 'operation')
class IndexEntriesViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = IndexEntries.objects.all()
serializer_class = serializers.IndexEntriesSerializer
filter_fields = ('video', 'algorithm', 'detection_name')
class LabelViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Label.objects.all()
serializer_class = serializers.LabelSerializer
class VDNServerViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = VDNServer.objects.all()
serializer_class = serializers.VDNServerSerializer
class TubeViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = Tube.objects.all()
serializer_class = serializers.TubeSerializer
class LOPQCodesViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticatedOrReadOnly,) if settings.AUTH_DISABLED else (IsAuthenticated,)
queryset = LOPQCodes.objects.all()
serializer_class = serializers.LOPQCodesSerializer
class VideoList(UserPassesTestMixin, ListView):
model = Video
paginate_by = 100
def get_context_data(self, **kwargs):
context = super(VideoList, self).get_context_data(**kwargs)
context['exports'] = TEvent.objects.all().filter(operation='perform_export')
return context
def test_func(self):
return user_check(self.request.user)
class TEventDetail(UserPassesTestMixin, DetailView):
model = TEvent
def get_context_data(self, **kwargs):
context = super(TEventDetail, self).get_context_data(**kwargs)
try:
tr = TaskResult.objects.get(task_id=context['object'].task_id)
except TaskResult.DoesNotExist:
context['celery_task'] = None
pass
else:
context['celery_task'] = tr
return context
def test_func(self):
return user_check(self.request.user)
class TEventList(UserPassesTestMixin, ListView):
model = TEvent
paginate_by = 500
def get_queryset(self):
kwargs = {}
if self.kwargs.get('pk',None):
kwargs['video_id']=self.kwargs['pk']
elif self.kwargs.get('process_pk',None):
kwargs['parent_process_id']=self.kwargs['process_pk']
if self.kwargs.get('status',None):
if self.kwargs['status'] == 'running':
kwargs['duration__lt'] = 0
kwargs['started'] = True
kwargs['completed'] = False
kwargs['errored'] = False
elif self.kwargs['status'] == 'successful':
kwargs['completed'] = True
elif self.kwargs['status'] == 'pending':
kwargs['duration__lt'] = 0
kwargs['started'] = False
kwargs['errored'] = False
elif self.kwargs['status'] == 'failed':
kwargs['errored'] = True
new_context = TEvent.objects.filter(**kwargs).order_by('-created')
return new_context
def get_context_data(self, **kwargs):
refresh_task_status()
context = super(TEventList, self).get_context_data(**kwargs)
context['header'] = ""
if self.kwargs.get('pk',None):
context['video'] = Video.objects.get(pk=self.kwargs['pk'])
context['header'] = "video/dataset : {}".format(context['video'].name)
if self.kwargs.get('process_pk',None):
process_pk = self.kwargs.get('process_pk',None)
context['header'] = "process : {}".format(process_pk)
if self.kwargs.get('status',None):
context['header'] += " with status {}".format(self.kwargs['status'])
return context
def test_func(self):
return user_check(self.request.user)
class VideoDetail(UserPassesTestMixin, DetailView):
model = Video
def get_context_data(self, **kwargs):
context = super(VideoDetail, self).get_context_data(**kwargs)
max_frame_index = Frame.objects.all().filter(video=self.object).aggregate(Max('frame_index'))[
'frame_index__max']
context['exports'] = TEvent.objects.all().filter(operation='perform_export', video=self.object)
context['annotation_count'] = Region.objects.all().filter(video=self.object,
region_type=Region.ANNOTATION).count()
context['exportable_annotation_count'] = 0
context['url'] = '{}{}/video/{}.mp4'.format(settings.MEDIA_URL, self.object.pk, self.object.pk)
label_list = []
show_all = self.request.GET.get('show_all_labels', False)
context['label_list'] = label_list
delta = 10000
if context['object'].dataset:
delta = 500
if max_frame_index <= delta:
context['frame_list'] = Frame.objects.all().filter(video=self.object).order_by('frame_index')
context['detection_list'] = Region.objects.all().filter(video=self.object, region_type=Region.DETECTION)
context['annotation_list'] = Region.objects.all().filter(video=self.object, region_type=Region.ANNOTATION)
context['offset'] = 0
context['limit'] = max_frame_index
else:
if self.request.GET.get('frame_index_offset', None) is None:
offset = 0
else:
offset = int(self.request.GET.get('frame_index_offset'))
limit = offset + delta
context['offset'] = offset
context['limit'] = limit
context['frame_list'] = Frame.objects.all().filter(video=self.object, frame_index__gte=offset,
frame_index__lte=limit).order_by('frame_index')
context['detection_list'] = Region.objects.all().filter(video=self.object, frame_index__gte=offset,
frame_index__lte=limit,
region_type=Region.DETECTION)
context['annotation_list'] = Region.objects.all().filter(video=self.object, frame_index__gte=offset,
frame_index__lte=limit,
region_type=Region.ANNOTATION)
context['frame_index_offsets'] = [(k * delta, (k * delta) + delta) for k in
range(int(math.ceil(max_frame_index / float(delta))))]
context['frame_first'] = context['frame_list'].first()
context['frame_last'] = context['frame_list'].last()
context['pending_tasks'] = TEvent.objects.all().filter(video=self.object,started=False, errored=False).count()
context['running_tasks'] = TEvent.objects.all().filter(video=self.object,started=True, completed=False, errored=False).count()
context['successful_tasks'] = TEvent.objects.all().filter(video=self.object,completed=True).count()
context['errored_tasks'] = TEvent.objects.all().filter(video=self.object,errored=True).count()
if context['limit'] > max_frame_index:
context['limit'] = max_frame_index
context['max_frame_index'] = max_frame_index
return context
def test_func(self):
return user_check(self.request.user)
# class RetrieverDetails(UserPassesTestMixin, DetailView):
# model = Clusters
#
# def get_context_data(self, **kwargs):
# context = super(ClustersDetails, self).get_context_data(**kwargs)
# context['coarse'] = []
# context['index_entries'] = [IndexEntries.objects.get(pk=k) for k in self.object.included_index_entries_pk]
# for k in ClusterCodes.objects.filter(clusters_id=self.object.pk).values('coarse_text').annotate(
# count=Count('coarse_text')):
# context['coarse'].append({'coarse_text': k['coarse_text'].replace(' ', '_'),
# 'count': k['count'],
# 'first': ClusterCodes.objects.all().filter(clusters_id=self.object.pk,
# coarse_text=k['coarse_text']).first(),
# 'last': ClusterCodes.objects.all().filter(clusters_id=self.object.pk,
# coarse_text=k['coarse_text']).last()
# })
#
# return context
#
# def test_func(self):
# return user_check(self.request.user)
class DetectionDetail(UserPassesTestMixin, DetailView):
model = Detector
def get_context_data(self, **kwargs):
context = super(DetectionDetail, self).get_context_data(**kwargs)
classdist = context['object'].class_distribution.strip()
context['class_distribution'] = json.loads(classdist) if classdist else {}
context['phase_1_log'] = []
context['phase_2_log'] = []
for k in context['object'].phase_1_log.split('\n')[1:]:
if k.strip():
epoch,train_loss,val_loss = k.strip().split(',')
context['phase_1_log'].append((epoch,round(float(train_loss),2),round(float(val_loss),2)))
for k in context['object'].phase_2_log.split('\n')[1:]:
if k.strip():
epoch,train_loss,val_loss = k.strip().split(',')
context['phase_2_log'].append((epoch,round(float(train_loss),2),round(float(val_loss),2)))
return context
def test_func(self):
return user_check(self.request.user)
class FrameList(UserPassesTestMixin, ListView):
model = Frame
def test_func(self):
return user_check(self.request.user)
class FrameDetail(UserPassesTestMixin, DetailView):
model = Frame
def get_context_data(self, **kwargs):
context = super(FrameDetail, self).get_context_data(**kwargs)
context['detection_list'] = Region.objects.all().filter(frame=self.object, region_type=Region.DETECTION)
context['annotation_list'] = Region.objects.all().filter(frame=self.object, region_type=Region.ANNOTATION)
context['video'] = self.object.video
context['url'] = '{}{}/frames/{}.jpg'.format(settings.MEDIA_URL, self.object.video.pk, self.object.frame_index)
context['previous_frame'] = Frame.objects.filter(video=self.object.video,
frame_index__lt=self.object.frame_index).order_by(
'-frame_index')[0:1]
context['next_frame'] = Frame.objects.filter(video=self.object.video,
frame_index__gt=self.object.frame_index).order_by('frame_index')[
0:1]
return context
def test_func(self):
return user_check(self.request.user)
class SegmentDetail(UserPassesTestMixin, DetailView):
model = Segment
def get_context_data(self, **kwargs):
context = super(SegmentDetail, self).get_context_data(**kwargs)
context['video'] = self.object.video
context['frame_list'] = Frame.objects.all().filter(video=self.object.video,segment_index=self.object.segment_index).order_by('frame_index')
context['region_list'] = Region.objects.all().filter(video=self.object.video,segment_index=self.object.segment_index).order_by('frame_index')
context['url'] = '{}{}/segments/{}.mp4'.format(settings.MEDIA_URL, self.object.video.pk, self.object.segment_index)
context['previous_segment_index'] = self.object.segment_index - 1 if self.object.segment_index else None
context['next_segment_index'] = self.object.segment_index + 1 if (self.object.segment_index+1) < self.object.video.segments else None
return context
def test_func(self):
return user_check(self.request.user)
class VisualSearchList(UserPassesTestMixin, ListView):
model = DVAPQL
template_name = "dvaapp/query_list.html"
def test_func(self):
return user_check(self.request.user)
def get_queryset(self):
new_context = DVAPQL.objects.filter(process_type=DVAPQL.QUERY).order_by('-created')
return new_context
class VisualSearchDetail(UserPassesTestMixin, DetailView):
model = DVAPQL
template_name = "dvaapp/query_detail.html"
def get_context_data(self, **kwargs):
context = super(VisualSearchDetail, self).get_context_data(**kwargs)
qp = DVAPQLProcess(process=context['object'],media_dir=settings.MEDIA_ROOT)
qp.collect()
context['results'] = qp.context['results'].items()
context['regions'] = qp.context['regions']
script = context['object'].script
script[u'image_data_b64'] = "<excluded>"
context['plan'] = script
context['pending_tasks'] = TEvent.objects.all().filter(parent_process=self.object,started=False, errored=False).count()
context['running_tasks'] = TEvent.objects.all().filter(parent_process=self.object,started=True, completed=False, errored=False).count()
context['successful_tasks'] = TEvent.objects.all().filter(parent_process=self.object,completed=True).count()
context['errored_tasks'] = TEvent.objects.all().filter(parent_process=self.object,errored=True).count()
context['url'] = '{}queries/{}.png'.format(settings.MEDIA_URL, self.object.pk, self.object.pk)
return context
def test_func(self):
return user_check(self.request.user)
class ProcessList(UserPassesTestMixin, ListView):
model = DVAPQL
template_name = "dvaapp/process_list.html"
paginate_by = 50
def get_context_data(self, **kwargs):
context = super(ProcessList, self).get_context_data(**kwargs)
return context
def test_func(self):
return user_check(self.request.user)
def get_queryset(self):
new_context = DVAPQL.objects.filter().order_by('-created')
return new_context
class ProcessDetail(UserPassesTestMixin, DetailView):
model = DVAPQL
template_name = "dvaapp/process_detail.html"
def get_context_data(self, **kwargs):
context = super(ProcessDetail, self).get_context_data(**kwargs)
context['json'] = json.dumps(context['object'].script,indent=4)
context['pending_tasks'] = TEvent.objects.all().filter(parent_process=self.object,started=False, errored=False).count()
context['running_tasks'] = TEvent.objects.all().filter(parent_process=self.object,started=True, completed=False, errored=False).count()
context['successful_tasks'] = TEvent.objects.all().filter(parent_process=self.object,completed=True).count()
context['errored_tasks'] = TEvent.objects.all().filter(parent_process=self.object,errored=True).count()
return context
def test_func(self):
return user_check(self.request.user)
class StoredProcessList(UserPassesTestMixin, ListView):
model = StoredDVAPQL
template_name = "dvaapp/stored_process_list.html"
paginate_by = 20
ordering = "-created"
def get_context_data(self, **kwargs):
context = super(StoredProcessList, self).get_context_data(**kwargs)
context['examples'] = json.dumps(EXAMPLES, indent=None)
return context
def test_func(self):
return user_check(self.request.user)
class StoredProcessDetail(UserPassesTestMixin, DetailView):
model = StoredDVAPQL
template_name = "dvaapp/stored_process_detail.html"
def get_context_data(self, **kwargs):
context = super(StoredProcessDetail, self).get_context_data(**kwargs)
context['json'] = json.dumps(context['object'].script,indent=4)
return context
def test_func(self):
return user_check(self.request.user)
@user_passes_test(user_check)
def search(request):
if request.method == 'POST':
qp = DVAPQLProcess()
qp.create_from_request(request)
qp.launch()
qp.wait()
qp.collect()
return JsonResponse(data={'task_id': "",
'primary_key': qp.process.pk,
'results': qp.context['results'],
'regions': qp.context['regions'],
'url': '{}queries/{}.png'.format(settings.MEDIA_URL, qp.process.pk)
})
def home(request):
if request.user.is_authenticated:
return redirect("app")
else:
return render(request, 'home.html', {})
def paper(request):
return render(request, 'paper.html', {})
@user_passes_test(user_check)
def index(request, query_pk=None, frame_pk=None, detection_pk=None):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
user = request.user if request.user.is_authenticated else None
if form.is_valid():
handle_uploaded_file(request.FILES['file'], form.cleaned_data['name'], user=user,rate=form.cleaned_data['nth'],
rescale=form.cleaned_data['rescale'] if 'rescale' in form.cleaned_data else 0)
return redirect('video_list')
else:
raise ValueError
else:
form = UploadFileForm()
context = {'form': form}
context['detectors'] = Detector.objects.all()
context['indexer_retrievers'] = []
for i in Indexer.objects.all():
for r in Retriever.objects.all():
if 'indexer_shasum' in r.source_filters and r.source_filters['indexer_shasum'] == i.shasum and r.last_built:
context['indexer_retrievers'].append(('{} > {} retriever {} (pk:{})'.format(i.name,
r.get_algorithm_display(),r.name,r.pk),
'{}_{}'.format(i.pk,r.pk)))
if query_pk:
previous_query = DVAPQL.objects.get(pk=query_pk)
context['initial_url'] = '{}queries/{}.png'.format(settings.MEDIA_URL, query_pk)
elif frame_pk:
frame = Frame.objects.get(pk=frame_pk)
context['initial_url'] = '{}{}/frames/{}.jpg'.format(settings.MEDIA_URL, frame.video.pk, frame.frame_index)
elif detection_pk:
detection = Region.objects.get(pk=detection_pk)
context['initial_url'] = '{}{}/regions/{}.jpg'.format(settings.MEDIA_URL, detection.video.pk, detection.pk)
context['frame_count'] = Frame.objects.count()
context['query_count'] = DVAPQL.objects.filter(process_type=DVAPQL.QUERY).count()
context['process_count'] = DVAPQL.objects.filter(process_type=DVAPQL.PROCESS).count()
context['index_entries_count'] = IndexEntries.objects.count()
context['external_servers_count'] = VDNServer.objects.count()
context['task_events_count'] = TEvent.objects.count()
context['pending_tasks'] = TEvent.objects.all().filter(started=False, errored=False).count()
context['running_tasks'] = TEvent.objects.all().filter(started=True, completed=False, errored=False).count()
context['successful_tasks'] = TEvent.objects.all().filter(started=True, completed=True).count()
context['errored_tasks'] = TEvent.objects.all().filter(errored=True).count()
context['video_count'] = Video.objects.count()
context['index_entries'] = IndexEntries.objects.all()
context['region_count'] = Region.objects.all().count()
context['tube_count'] = Tube.objects.all().count()
context["videos"] = Video.objects.all().filter()
context['detector_count'] = Detector.objects.all().count()
context['rate'] = defaults.DEFAULT_RATE
return render(request, 'dashboard.html', context)
@user_passes_test(user_check)
def assign_video_labels(request):
if request.method == 'POST':
video = Video.objects.get(pk=request.POST.get('video_pk'))
spec = []
for k in request.POST.get('labels').split(','):
if k.strip():
spec.append({
'MODEL':'VideoLabel',
'spec':{'video_id':video.pk,'label_id':Label.objects.get_or_create(name=k,set="UI")[0].id}
})
p = DVAPQLProcess()
p.create_from_json({
'process_type':DVAPQL.PROCESS,
'create':spec,
},user=request.user if request.user.is_authenticated else None)
p.launch()
return redirect('video_detail', pk=video.pk)
else:
raise NotImplementedError
@user_passes_test(user_check)
def annotate(request, frame_pk):
context = {'frame': None, 'detection': None, 'existing': []}
frame = None
frame = Frame.objects.get(pk=frame_pk)
context['frame'] = frame
context['initial_url'] = '{}{}/frames/{}.jpg'.format(settings.MEDIA_URL, frame.video.pk, frame.frame_index)
context['previous_frame'] = Frame.objects.filter(video=frame.video, frame_index__lt=frame.frame_index).order_by(
'-frame_index')[0:1]
context['next_frame'] = Frame.objects.filter(video=frame.video, frame_index__gt=frame.frame_index).order_by(
'frame_index')[0:1]
context['detections'] = Region.objects.filter(frame=frame, region_type=Region.DETECTION)
for d in Region.objects.filter(frame=frame):
temp = {
'x': d.x,
'y': d.y,
'h': d.h,
'w': d.w,
'pk': d.pk,
'box_type': "detection" if d.region_type == d.DETECTION else 'annotation',
'label': d.object_name,
'full_frame': d.full_frame,
'detection_pk': None
}
context['existing'].append(temp)
context['existing'] = json.dumps(context['existing'])
if request.method == 'POST':
form = AnnotationForm(request.POST)
if form.is_valid():
applied_tags = form.cleaned_data['tags'].split(',') if form.cleaned_data['tags'] else []
create_annotation(form, form.cleaned_data['object_name'], applied_tags, frame)
return JsonResponse({'status': True})
else:
raise ValueError, form.errors
return render(request, 'annotate.html', context)
@user_passes_test(user_check)
def annotate_entire_frame(request, frame_pk):
frame = Frame.objects.get(pk=frame_pk)
annotation = None
if request.method == 'POST':
if request.POST.get('text').strip() \
or request.POST.get('metadata').strip() \
or request.POST.get('object_name', None):
annotation = Region()
annotation.region_type = Region.ANNOTATION
annotation.x = 0
annotation.y = 0
annotation.h = 0
annotation.w = 0
annotation.full_frame = True
annotation.text = request.POST.get('text')
annotation.metadata = request.POST.get('metadata')
annotation.object_name = request.POST.get('object_name', 'frame_metadata')
annotation.frame = frame
annotation.video = frame.video
annotation.save()
for label_name in request.POST.get('tags').split(','):
if label_name.strip():
if annotation:
dl = RegionLabel()
dl.video = frame.video
dl.frame = frame
dl.label = Label.objects.get_or_create(name=label_name,set="UI")[0]
dl.region = annotation
dl.save()
else:
dl = FrameLabel()
dl.video = frame.video
dl.frame = frame
dl.label = Label.objects.get_or_create(name=label_name,set="UI")[0]
dl.save()
return redirect("frame_detail", pk=frame.pk)
@user_passes_test(user_check)
def yt(request):
if request.method == 'POST':
form = YTVideoForm(request.POST, request.FILES)
user = request.user if request.user.is_authenticated else None
if form.is_valid():
rate = form.cleaned_data['nth']
rescale = form.cleaned_data['rescale'] if 'rescale' in form.cleaned_data else 0
video = handle_video_url(form.cleaned_data['name'], form.cleaned_data['url'], user=user)
process_spec = {
'process_type': DVAPQL.PROCESS,
'tasks': [{'video_id': video.pk,
'operation': 'perform_import',
'arguments': {'source': "URL",
'next_tasks':[{'video_id': video.pk,
'operation': 'perform_video_segmentation',
'arguments': {
'next_tasks': [
{'operation': 'perform_video_decode',
'arguments': {
'rate': rate, 'rescale': rescale,
'segments_batch_size': defaults.DEFAULT_SEGMENTS_BATCH_SIZE,
'next_tasks': defaults.DEFAULT_PROCESSING_PLAN_VIDEO
}
}
]},
},]
}
},]
}
p = DVAPQLProcess()
p.create_from_json(process_spec, user)
p.launch()
else:
raise ValueError
else:
raise NotImplementedError
return redirect('video_list')
@user_passes_test(user_check)
def segment_by_index(request,video_pk,segment_index):
segment = Segment.objects.get(video_id=video_pk,segment_index=segment_index)
return redirect('segment_detail',pk=segment.pk)
@user_passes_test(user_check)
def export_video(request):
if request.method == 'POST':
pk = request.POST.get('video_id')
video = Video.objects.get(pk=pk)
export_method = request.POST.get('export_method')
if video:
if export_method == 's3':
key = request.POST.get('key')
bucket = request.POST.get('bucket')
region = request.POST.get('region','us-east-1')
process_spec = {'process_type':DVAPQL.PROCESS,
'tasks':[
{
'video_id':video.pk,
'operation':'perform_export',
'arguments': {'key':key,'bucket':bucket,'region':region,'destination':'S3'}
},
]}
else:
process_spec = {'process_type':DVAPQL.PROCESS,
'tasks':[
{
'video_id':video.pk,
'operation':'perform_export',
'arguments':{'destination':'FILE'}
},
]
}
p = DVAPQLProcess()
p.create_from_json(process_spec)
p.launch()
return redirect('video_list')
else:
raise NotImplementedError
@user_passes_test(user_check)
def coarse_code_detail(request, pk, coarse_code):
coarse_code = coarse_code.replace('_', ' ')
context = {
'code': coarse_code,
'objects': LOPQCodes.objects.all().filter(coarse_text=coarse_code, clusters_id=pk)
}
return render(request, 'coarse_code_details.html', context)
@user_passes_test(user_check)
def status(request):
context = {}
context['logs'] = []
for fname in glob.glob('logs/*.log'):
context['logs'].append((fname,file(fname).read()))
return render(request, 'status.html', context)
@user_passes_test(user_check)
def management(request):
timeout = 1.0
context = {
'timeout':timeout,
'actions':ManagementAction.objects.all(),
'state':SystemState.objects.all().order_by('-created')[:100]
}
if request.method == 'POST':
op = request.POST.get("op","")
host_name = request.POST.get("host_name","").strip()
queue_name = request.POST.get("queue_name","").strip()
if op =="list_workers":
context["queues"] = app.control.inspect(timeout=timeout).active_queues()
elif op == "list":
t = app.send_task('manage_host', args=[op, ], exchange='qmanager')
t.wait(timeout=timeout)
elif op == "gpuinfo":
t = app.send_task('manage_host', args=[op, ], exchange='qmanager')
t.wait(timeout=timeout)
elif op == "launch":
t = app.send_task('manage_host', args=[op,host_name,queue_name],exchange='qmanager')
t.wait(timeout=timeout)
return render(request, 'management.html', context)
@user_passes_test(user_check)
def training(request):
context = {}
context["videos"] = Video.objects.all().filter()
context["detectors"] = Detector.objects.all()
return render(request, 'training.html', context)
@user_passes_test(user_check)
def textsearch(request):
context = {'results': {}, "videos": Video.objects.all().filter()}
q = request.GET.get('q')
if q:
offset = int(request.GET.get('offset',0))
delta = int(request.GET.get('delta',25))
limit = offset + delta
context['q'] = q
context['next'] = limit
context['delta'] = delta
context['offset'] = offset
context['limit'] = limit
if request.GET.get('regions'):
context['results']['regions_meta'] = Region.objects.filter(text__search=q)[offset:limit]
context['results']['regions_name'] = Region.objects.filter(object_name__search=q)[offset:limit]
if request.GET.get('frames'):
context['results']['frames_name'] = Frame.objects.filter(name__search=q)[offset:limit]
context['results']['frames_subdir'] = Frame.objects.filter(subdir__search=q)[offset:limit]
if request.GET.get('labels'):
context['results']['labels'] = Label.objects.filter(name__search=q)[offset:limit]
return render(request, 'textsearch.html', context)
@user_passes_test(user_check)
def retrievers(request):
context = {}
context['algorithms'] = {k.name for k in Indexer.objects.all()}
context['index_entries'] = IndexEntries.objects.all()
context['retrievers'] = Retriever.objects.all()
return render(request, 'retrievers.html', context)
@user_passes_test(user_check)
def create_retriever(request):
if request.method == 'POST':
spec = {}
if request.POST.get('retriever_type') == Retriever.LOPQ:
v = request.POST.get('v')
m = request.POST.get('m')
components = request.POST.get('components')
sub = request.POST.get('sub')
spec['name'] = request.POST.get('name')
spec['algorithm'] = Retriever.LOPQ
args = {}
args['components']= components
args['sub']= sub
args['m']= m
args['v']= v
spec['arguments'] = args
if request.POST.get('source_filters',None):
spec['source_filters'] = json.loads(request.POST.get('source_filter','{}'))
else:
spec['source_filters'] = {'indexer_shasum':Indexer.objects.get(name=request.POST.get('algorithm')).shasum}
next_tasks = [{'operation': "perform_retriever_creation",'arguments': {'retriever_pk':'__pk__'},},]
elif request.POST.get('retriever_type') == Retriever.EXACT:
spec['name'] = request.POST.get('name')
spec['last_built'] = '__timezone.now__'
spec['source_filters'] = json.loads(request.POST.get('source_filters', '{}'))
spec['algorithm'] = Retriever.EXACT
next_tasks = []
else:
raise ValueError
if spec:
p = DVAPQLProcess()
p.create_from_json(j={"process_type": DVAPQL.PROCESS,
"create":[{'MODEL':'Retriever','spec':spec,'tasks': next_tasks}],
}, user=request.user if request.user.is_authenticated else None)
p.launch()
return redirect('retrievers')
@user_passes_test(user_check)
def submit_process(request):
if request.method == 'POST':
process_pk = request.POST.get('process_pk',None)
if process_pk is None:
p = DVAPQLProcess()
p.create_from_json(j=json.loads(request.POST.get('script')), user=request.user if request.user.is_authenticated else None)
p.launch()
else:
p = DVAPQLProcess(process=DVAPQL.objects.get(pk=process_pk))
p.launch()
return redirect("process_detail",pk=p.process.pk)
@user_passes_test(user_check)
def validate_process(request):
if request.method == 'POST':
p = DVAPQLProcess()
p.create_from_json(j=json.loads(request.POST.get('script')), user=request.user if request.user.is_authenticated else None)
p.validate()
return redirect("process_detail",pk=p.process.pk)
@user_passes_test(user_check)
def delete_object(request):
if request.method == 'POST':
pk = request.POST.get('pk')
if request.POST.get('object_type') == 'annotation':
annotation = Region.objects.get(pk=pk)
if annotation.region_type == Region.ANNOTATION:
annotation.delete()
return JsonResponse({'status': True})
@user_passes_test(force_user_check)
def security(request):
context = {}
context['username'] = request.user.username
token, created = Token.objects.get_or_create(user=request.user if request.user.is_authenticated else None)
context['token'] = token
return render(request, 'security.html', context=context)
@user_passes_test(force_user_check)
def expire_token(request):
# TODO Check if this is correct
if request.method == 'POST':
if request.POST.get('expire',False):
token, created = Token.objects.get_or_create(user=request.user if request.user.is_authenticated else None)
if not created:
token.delete()
return redirect("security")
@user_passes_test(user_check)
def import_dataset(request):
if request.method == 'POST':
url = request.POST.get('dataset_url')
server = VDNServer.objects.get(pk=request.POST.get('server_pk'))
user = request.user if request.user.is_authenticated else None
cached_response = server.last_response_datasets[int(request.POST.get('dindex'))]
import_vdn_dataset_url(server, url, user, cached_response)
else:
raise NotImplementedError
return redirect('video_list')
@user_passes_test(user_check)
def import_detector(request):
if request.method == 'POST':
url = request.POST.get('detector_url')
server = VDNServer.objects.get(pk=request.POST.get('server_pk'))
user = request.user if request.user.is_authenticated else None
cached_response = server.last_response_detectors[int(request.POST.get('dindex'))]
import_vdn_detector_url(server, url, user, cached_response)
else:
raise NotImplementedError
return redirect('models')
@user_passes_test(user_check)
def import_s3(request):
if request.method == 'POST':
keys = request.POST.get('key')
region = request.POST.get('region')
bucket = request.POST.get('bucket')
rate = request.POST.get('rate',defaults.DEFAULT_RATE)
rescale = request.POST.get('rescale',defaults.DEFAULT_RESCALE)
user = request.user if request.user.is_authenticated else None
create = []
for key in keys.strip().split('\n'):
tasks =[]
key = key.strip()
if key:
extract_task = {'arguments': {'rate': rate, 'rescale': rescale,
'next_tasks': defaults.DEFAULT_PROCESSING_PLAN_DATASET},
'operation': 'perform_dataset_extraction'}
segment_decode_task = {'operation': 'perform_video_segmentation',
'arguments': {
'next_tasks': [
{'operation': 'perform_video_decode',
'arguments': {
'rate': rate, 'rescale': rescale,
'segments_batch_size':defaults.DEFAULT_SEGMENTS_BATCH_SIZE,
'next_tasks': defaults.DEFAULT_PROCESSING_PLAN_VIDEO
}
}
]},
}
if key.endswith('.dva_export.zip'):
next_tasks = []
elif key.endswith('.zip'):
next_tasks = [extract_task,]
else:
next_tasks = [segment_decode_task,]
tasks.append({'video_id':'__pk__',
'operation':'perform_import',
'arguments':{'key':key,
'bucket':bucket,
'region':region,
'source':'S3',
'next_tasks':next_tasks}
})
create.append({'MODEL': 'Video',
'spec': {'uploader_id': user.pk if user else None,
'name': "pending S3 import {} s3://{}/{}".format(region, bucket, key)},
'tasks': tasks
})
process_spec = {'process_type': DVAPQL.PROCESS,
'create':create}
p = DVAPQLProcess()
p.create_from_json(process_spec,user)
p.launch()
else:
raise NotImplementedError
return redirect('video_list')
@user_passes_test(user_check)
def external(request):
if request.method == 'POST':
pk = request.POST.get('server_pk')
try:
pull_vdn_list(pk)
except:
pass
context = {
'servers': VDNServer.objects.all(),
'available_datasets': {server: server.last_response_datasets for server in VDNServer.objects.all()},
'available_detectors': {server: server.last_response_detectors for server in VDNServer.objects.all()},
}
return render(request, 'external_data.html', context)
@user_passes_test(user_check)
def retry_task(request):
pk = request.POST.get('pk')
event = TEvent.objects.get(pk=int(pk))
spec = {
'process_type':DVAPQL.PROCESS,
'tasks':[
{
'operation':event.operation,
'arguments':event.arguments
}
]
}
p = DVAPQLProcess()
p.create_from_json(spec)
p.launch()
return redirect('/processes/')
@user_passes_test(user_check)
def delete_video(request):
if request.user.is_staff: # currently only staff can delete
video_pk = request.POST.get('video_id')
delete_video_object(video_pk,request.user)
return redirect('video_list')
else:
return redirect('accounts/login/')
@user_passes_test(user_check)
def rename_video(request):
if request.user.is_staff: # currently only staff can rename
video_pk = request.POST.get('video_id')
name = request.POST.get('name')
v = Video.objects.get(pk=int(video_pk))
v.name = name
v.save()
return redirect('video_list')
else:
return redirect('accounts/login/')
@user_passes_test(user_check)
def models(request):
context = {
'visual_index_list': Indexer.objects.all(),
'index_entries': IndexEntries.objects.all(),
"videos": Video.objects.all().filter(),
"region_types": Region.REGION_TYPES,
"detectors": Detector.objects.all()
}
detector_stats = []
context["detectors"] = Detector.objects.all()
return render(request, 'models.html', context)
@user_passes_test(user_check)
def index_video(request):
if request.method == 'POST':
filters = {
'region_type__in': request.POST.getlist('region_type__in', []),
'w__gte': int(request.POST.get('w__gte')),
'h__gte': int(request.POST.get('h__gte'))
}
for optional_key in ['text__contains', 'object_name__contains', 'object_name']:
if request.POST.get(optional_key, None):
filters[optional_key] = request.POST.get(optional_key)
for optional_key in ['h__lte', 'w__lte']:
if request.POST.get(optional_key, None):
filters[optional_key] = int(request.POST.get(optional_key))
args = {'filters':filters,'index':request.POST.get('visual_index_name')}
p = DVAPQLProcess()
spec = {
'process_type':DVAPQL.PROCESS,
'tasks':[
{
'operation':'perform_indexing',
'arguments':args,
'video_id':request.POST.get('video_id')
}
]
}
user = request.user if request.user.is_authenticated else None
p.create_from_json(spec,user)
p.launch()
redirect('process_detail',pk=p.process.pk)
else:
raise ValueError
@user_passes_test(user_check)
def detect_objects(request):
if request.method == 'POST':
detector_pk = request.POST.get('detector_pk')
video_pk = request.POST.get('video_pk')
p = DVAPQLProcess()
p.create_from_json(j={
"process_type":DVAPQL.PROCESS,
"tasks":[{'operation':"perform_detection",
'arguments':{'detector_pk': int(detector_pk),'detector':"custom"},
'video_id':video_pk}]
},user=request.user if request.user.is_authenticated else None)
p.launch()
return redirect('process_detail',pk=p.process.pk)
else:
raise ValueError
@user_passes_test(user_check)
def train_detector(request):
if request.method == 'POST':
args = request.POST.get('args')
args = json.loads(args) if args.strip() else {}
args['name'] = request.POST.get('name')
args['labels'] = [k.strip() for k in request.POST.get('labels').split(',') if k.strip()]
args['object_names'] = [k.strip() for k in request.POST.get('object_names').split(',') if k.strip()]
args['excluded_videos'] = request.POST.getlist('excluded_videos')
args['detector_pk'] = '__pk__'
p = DVAPQLProcess()
p.create_from_json(j={
"process_type":DVAPQL.PROCESS,
"create":[
{
'MODEL':'Detector',
'spec':{
'name':args['name'],
'arguments':json.dumps(args),
'algorithm':'yolo'
},
"tasks":[
{'operation':"perform_detector_training",
'arguments':args,
}]
}
]
},user=request.user if request.user.is_authenticated else None)
p.launch()
return redirect('process_detail', pk=p.process.pk)
# elif request.POST.get('action') == 'estimate':
# args = request.POST.get('args')
# args = json.loads(args) if args.strip() else {}
# args['name'] = request.POST.get('name')
# args['labels'] = [k.strip() for k in request.POST.get('labels').split(',') if k.strip()]
# args['object_names'] = [k.strip() for k in request.POST.get('object_names').split(',') if k.strip()]
# args['excluded_videos'] = request.POST.getlist('excluded_videos')
# labels = set(args['labels']) if 'labels' in args else set()
# object_names = set(args['object_names']) if 'object_names' in args else set()
# class_distribution, class_names, rboxes, rboxes_set,
# frames, i_class_names = create_detector_dataset(object_names, labels)
# context["estimate"] = {
# 'args':args,
# 'class_distribution':class_distribution,
# 'class_names':class_names,
# 'rboxes':rboxes,
# 'rboxes_set':rboxes_set,
# 'frames':frames,
# 'i_class_names':i_class_names
# }
else:
raise ValueError
| [
"[email protected]"
] | |
c2374a4c2a0f8125c15d4daa87dc1bee036aa59b | ef54d37f8a3303013ca7469871a320d303957ed7 | /robo4.2/fusion/tests/wpst_crm/ci_fit/config/I11/CI-FIT-16-CI-FIT-17_old.py | 573ae00df59b8aacdb29e3a48d49f44cd672ae90 | [] | no_license | richa92/Jenkin_Regression_Testing | d18badfcf16bda682dfe7bcbbd66f54a9a27a58d | 24a74926170cbdfafa47e972644e2fe5b627d8ff | refs/heads/master | 2020-07-12T10:01:59.099137 | 2019-08-27T12:14:53 | 2019-08-27T12:14:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 159,115 | py | def make_range_list(vrange):
rlist = []
for x in xrange(vrange['start'], (vrange['end'] + 1)):
rlist.append(vrange['prefix'] + str(x) + vrange['suffix'])
return rlist
admin_credentials = {'userName': 'Administrator', 'password': 'hpvse123'}
vcenter = {'server': '15.186.4.110', 'user': 'Administrator', 'password': 'Compaq123'}
appliance = {'type': 'ApplianceNetworkConfiguration',
'applianceNetworks':
[{'device': 'eth0',
'macAddress': None,
'interfaceName': 'hpqcorpnet',
'activeNode': '1',
'unconfigure': False,
'ipv4Type': 'STATIC',
'ipv4Subnet': '255.255.224.0',
'ipv4Gateway': '15.186.0.1',
'ipv4NameServers': ['16.110.135.51', '16.110.135.52'],
'app1Ipv4Addr': '15.186.7.140',
'ipv6Type': 'UNCONFIGURE',
'hostname': 'I11-CI-FIT-16-17.austin.hp.com',
'confOneNode': True,
'domainName': 'usa.hp.com',
'aliasDisabled': True,
}],
}
timeandlocale = {'type': 'TimeAndLocale', 'dateTime': None, 'timezone': 'UTC', 'ntpServers': ['ntp.hp.net'], 'locale': 'en_US.UTF-8'}
ranges = [{'name': 'CI-FIT-16-MAC', 'type': 'Range', 'category': 'id-range-VMAC', 'rangeCategory': 'CUSTOM', 'startAddress': 'A2:66:66:00:00:00', 'endAddress': 'A2:66:66:0F:FF:FF', 'enabled': True},
{'name': 'CI-FIT-16-WWN', 'type': 'Range', 'category': 'id-range-VWWN', 'rangeCategory': 'CUSTOM', 'startAddress': '26:66:6C:66:00:0F:FF:FF', 'endAddress': '26:66:6C:66:00:0F:FF:FF', 'enabled': True},
{'name': 'CI-FIT-16-SN', 'type': 'Range', 'category': 'id-range-VSN', 'rangeCategory': 'CUSTOM', 'startAddress': 'VCUGGG0000', 'endAddress': 'VCUGGG0ZZZ', 'enabled': True}]
users = [{'userName': 'Serveradmin', 'password': 'Serveradmin', 'fullName': 'Serveradmin', 'roles': ['Server administrator'], 'emailAddress': '[email protected]', 'officePhone': '512-555-0004', 'mobilePhone': '512-500-0004', 'type': 'UserAndRoles'},
{'userName': 'Networkadmin', 'password': 'Networkadmin', 'fullName': 'Networkadmin', 'roles': ['Network administrator'], 'emailAddress': '[email protected]', 'officePhone': '512-555-0003', 'mobilePhone': '512-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Backupadmin', 'password': 'Backupadmin', 'fullName': 'Backupadmin', 'roles': ['Backup administrator'], 'emailAddress': '[email protected]', 'officePhone': '512-555-0003', 'mobilePhone': '512-500-0003', 'type': 'UserAndRoles'},
{'userName': 'Noprivledge', 'password': 'Noprivledge', 'fullName': 'Noprivledge', 'roles': ['Read only'], 'emailAddress': '[email protected]', 'officePhone': '512-555-0003', 'mobilePhone': '512-500-0003', 'type': 'UserAndRoles'}
]
licenses = [{'key': 'YCDE D9MA H9P9 8HUZ U7B5 HWW5 Y9JL KMPL MHND 7AJ9 DXAU 2CSM GHTG L762 LFH6 F4R4 KJVT D5KM EFVW DT5J 83HJ 8VC6 AK2P 3EW2 L9YE HUNJ TZZ7 MB5X 82Z5 WHEF GE4C LUE3 BKT8 WXDG NK6Y C4GA HZL4 XBE7 3VJ6 2MSU 4ZU9 9WGG CZU7 WE4X YN44 CH55 KZLG 2F4N A8RJ UKEG 3F9V JQY5 "423207356 HPOV-NFR2 HP_OneView_w/o_iLO_16_Seat_NFR H3TCJHCGAYAY"'},
{'key': 'QC3C A9MA H9PQ GHVZ U7B5 HWW5 Y9JL KMPL 2HVF 4FZ9 DXAU 2CSM GHTG L762 7JX5 V5FU KJVT D5KM EFVW DV5J 43LL PSS6 AK2P 3EW2 T9YE XUNJ TZZ7 MB5X 82Z5 WHEF GE4C LUE3 BKT8 WXDG NK6Y C4GA HZL4 XBE7 3VJ6 2MSU 4ZU9 9WGG CZU7 WE4X YN44 CH55 KZLG 2F4N A8RJ UKEG 3F9V JQY5 "423207566 HPOV-NFR2 HP_OneView_w/o_iLO_48_Seat_NFR 6H72JHCGY5AU"'}
]
ethernet_networks = [{'name': 'IC',
'type': 'ethernet-networkV3',
'vlanId': None,
'purpose': 'General',
'smartLink': True,
'privateNetwork': False,
'connectionTemplateUri': None,
'ethernetNetworkType': 'Untagged'},
{'name': 'Tunnel1',
'type': 'ethernet-networkV3',
'vlanId': None,
'purpose': 'General',
'smartLink': True,
'privateNetwork': True,
'connectionTemplateUri': None,
'ethernetNetworkType': 'Tunnel'},
{'name': 'Tunnel2',
'type': 'ethernet-networkV3',
'vlanId': None,
'purpose': 'General',
'smartLink': True,
'privateNetwork': True,
'connectionTemplateUri': None,
'ethernetNetworkType': 'Tunnel'},
]
ethernet_ranges = [{'prefix': 'net_', 'suffix': '', 'start': 2, 'end': 45, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'},
{'prefix': 'net_', 'suffix': '-O', 'start': 2, 'end': 45, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'},
{'prefix': 'net_', 'suffix': '-E', 'start': 2, 'end': 45, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'},
{'prefix': 'net_', 'suffix': '', 'start': 3985, 'end': 4000, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'},
{'prefix': 'net_', 'suffix': '-O', 'start': 3985, 'end': 4000, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'},
{'prefix': 'net_', 'suffix': '-E', 'start': 3985, 'end': 4000, 'name': None, 'type': 'ethernet-networkV3',
'vlanId': None, 'purpose': 'General', 'smartLink': False, 'privateNetwork': False, 'connectionTemplateUri': None,
'ethernetNetworkType': 'Tagged'}
]
fc_networks = [{'name': 'SAN-3-A', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-4-B', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-1-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-1-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-1-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-1-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-2-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-2-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-2-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-2-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-3-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-3-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-3-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-3-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-4-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-4-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-4-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-4-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-5-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-5-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-5-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-5-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-6-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-6-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-6-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-6-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-7-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-7-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-7-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-7-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-8-1-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-8-2-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-8-3-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': False, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
{'name': 'SAN-8-4-DA', 'type': 'fc-networkV2', 'linkStabilityTime': 30, 'autoLoginRedistribution': True, 'connectionTemplateUri': None, 'managedSanUri': None, 'fabricType': 'DirectAttach'},
]
network_sets = [{'name': 'NS_4000', 'type': 'network-set', 'networkUris': ['net_4000'], 'nativeNetworkUri': 'net_4000'},
{'name': 'NS_3999', 'type': 'network-set', 'networkUris': ['net_3999'], 'nativeNetworkUri': 'net_3999'},
{'name': 'NS_3998', 'type': 'network-set', 'networkUris': ['net_3998'], 'nativeNetworkUri': 'net_3998'},
{'name': 'NS_3997', 'type': 'network-set', 'networkUris': ['net_3997'], 'nativeNetworkUri': 'net_3997'},
{'name': 'NS_3996', 'type': 'network-set', 'networkUris': ['net_3996'], 'nativeNetworkUri': 'net_3996'},
{'name': 'NS_3995', 'type': 'network-set', 'networkUris': ['net_3995'], 'nativeNetworkUri': 'net_3995'},
{'name': 'NS_3994', 'type': 'network-set', 'networkUris': ['net_3994'], 'nativeNetworkUri': 'net_3994'},
{'name': 'NS_3993', 'type': 'network-set', 'networkUris': ['net_3993'], 'nativeNetworkUri': 'net_3993'},
{'name': 'NS_3992', 'type': 'network-set', 'networkUris': ['net_3992'], 'nativeNetworkUri': 'net_3992'},
{'name': 'NS_3991', 'type': 'network-set', 'networkUris': ['net_3991'], 'nativeNetworkUri': 'net_3991'},
{'name': 'NS_3990', 'type': 'network-set', 'networkUris': ['net_3990'], 'nativeNetworkUri': 'net_3990'},
{'name': 'NS_3989', 'type': 'network-set', 'networkUris': ['net_3989'], 'nativeNetworkUri': 'net_3989'},
{'name': 'NS_3988', 'type': 'network-set', 'networkUris': ['net_3988'], 'nativeNetworkUri': 'net_3988'},
{'name': 'NS_3987', 'type': 'network-set', 'networkUris': ['net_3987'], 'nativeNetworkUri': 'net_3987'},
{'name': 'NS_3986', 'type': 'network-set', 'networkUris': ['net_3986'], 'nativeNetworkUri': 'net_3986'},
{'name': 'NS_3985', 'type': 'network-set', 'networkUris': ['net_3985'], 'nativeNetworkUri': 'net_3985'},
{'name': 'NS_4000-O', 'type': 'network-set', 'networkUris': ['net_4000-O'], 'nativeNetworkUri': 'net_4000-O'},
{'name': 'NS_3999-O', 'type': 'network-set', 'networkUris': ['net_3999-O'], 'nativeNetworkUri': 'net_3999-O'},
{'name': 'NS_3998-O', 'type': 'network-set', 'networkUris': ['net_3998-O'], 'nativeNetworkUri': 'net_3998-O'},
{'name': 'NS_3997-O', 'type': 'network-set', 'networkUris': ['net_3997-O'], 'nativeNetworkUri': 'net_3997-O'},
{'name': 'NS_3996-O', 'type': 'network-set', 'networkUris': ['net_3996-O'], 'nativeNetworkUri': 'net_3996-O'},
{'name': 'NS_3995-O', 'type': 'network-set', 'networkUris': ['net_3995-O'], 'nativeNetworkUri': 'net_3995-O'},
{'name': 'NS_3994-O', 'type': 'network-set', 'networkUris': ['net_3994-O'], 'nativeNetworkUri': 'net_3994-O'},
{'name': 'NS_3993-O', 'type': 'network-set', 'networkUris': ['net_3993-O'], 'nativeNetworkUri': 'net_3993-O'},
{'name': 'NS_3992-O', 'type': 'network-set', 'networkUris': ['net_3992-O'], 'nativeNetworkUri': 'net_3992-O'},
{'name': 'NS_3991-O', 'type': 'network-set', 'networkUris': ['net_3991-O'], 'nativeNetworkUri': 'net_3991-O'},
{'name': 'NS_3990-O', 'type': 'network-set', 'networkUris': ['net_3990-O'], 'nativeNetworkUri': 'net_3990-O'},
{'name': 'NS_3989-O', 'type': 'network-set', 'networkUris': ['net_3989-O'], 'nativeNetworkUri': 'net_3989-O'},
{'name': 'NS_3988-O', 'type': 'network-set', 'networkUris': ['net_3988-O'], 'nativeNetworkUri': 'net_3988-O'},
{'name': 'NS_3987-O', 'type': 'network-set', 'networkUris': ['net_3987-O'], 'nativeNetworkUri': 'net_3987-O'},
{'name': 'NS_3986-O', 'type': 'network-set', 'networkUris': ['net_3986-O'], 'nativeNetworkUri': 'net_3986-O'},
{'name': 'NS_3985-O', 'type': 'network-set', 'networkUris': ['net_3985-O'], 'nativeNetworkUri': 'net_3985-O'},
{'name': 'NS_4000-E', 'type': 'network-set', 'networkUris': ['net_4000-E'], 'nativeNetworkUri': 'net_4000-E'},
{'name': 'NS_3999-E', 'type': 'network-set', 'networkUris': ['net_3999-E'], 'nativeNetworkUri': 'net_3999-E'},
{'name': 'NS_3998-E', 'type': 'network-set', 'networkUris': ['net_3998-E'], 'nativeNetworkUri': 'net_3998-E'},
{'name': 'NS_3997-E', 'type': 'network-set', 'networkUris': ['net_3997-E'], 'nativeNetworkUri': 'net_3997-E'},
{'name': 'NS_3996-E', 'type': 'network-set', 'networkUris': ['net_3996-E'], 'nativeNetworkUri': 'net_3996-E'},
{'name': 'NS_3995-E', 'type': 'network-set', 'networkUris': ['net_3995-E'], 'nativeNetworkUri': 'net_3995-E'},
{'name': 'NS_3994-E', 'type': 'network-set', 'networkUris': ['net_3994-E'], 'nativeNetworkUri': 'net_3994-E'},
{'name': 'NS_3993-E', 'type': 'network-set', 'networkUris': ['net_3993-E'], 'nativeNetworkUri': 'net_3993-E'},
{'name': 'NS_3992-E', 'type': 'network-set', 'networkUris': ['net_3992-E'], 'nativeNetworkUri': 'net_3992-E'},
{'name': 'NS_3991-E', 'type': 'network-set', 'networkUris': ['net_3991-E'], 'nativeNetworkUri': 'net_3991-E'},
{'name': 'NS_3990-E', 'type': 'network-set', 'networkUris': ['net_3990-E'], 'nativeNetworkUri': 'net_3990-E'},
{'name': 'NS_3989-E', 'type': 'network-set', 'networkUris': ['net_3989-E'], 'nativeNetworkUri': 'net_3989-E'},
{'name': 'NS_3988-E', 'type': 'network-set', 'networkUris': ['net_3988-E'], 'nativeNetworkUri': 'net_3988-E'},
{'name': 'NS_3987-E', 'type': 'network-set', 'networkUris': ['net_3987-E'], 'nativeNetworkUri': 'net_3987-E'},
{'name': 'NS_3986-E', 'type': 'network-set', 'networkUris': ['net_3986-E'], 'nativeNetworkUri': 'net_3986-E'},
{'name': 'NS_3985-E', 'type': 'network-set', 'networkUris': ['net_3985-E'], 'nativeNetworkUri': 'net_3985-E'}
]
#network_set_ranges = [{'prefix': 'net_', 'suffix': '-O', 'start': 2502, 'end': 2515, 'name': 'VlanTrunk1-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2502-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2502, 'end': 2515, 'name': 'VlanTrunk1-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2502-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2516, 'end': 2530, 'name': 'VlanTrunk2-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2516-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2516, 'end': 2530, 'name': 'VlanTrunk2-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2516-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2531, 'end': 2545, 'name': 'VlanTrunk3-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2531-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2531, 'end': 2545, 'name': 'VlanTrunk3-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2531-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2546, 'end': 2560, 'name': 'VlanTrunk4-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2546-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2546, 'end': 2560, 'name': 'VlanTrunk4-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2546-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2561, 'end': 2575, 'name': 'VlanTrunk5-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2561-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2561, 'end': 2575, 'name': 'VlanTrunk5-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2561-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2576, 'end': 2590, 'name': 'VlanTrunk6-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2576-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2576, 'end': 2590, 'name': 'VlanTrunk6-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2576-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2591, 'end': 2605, 'name': 'VlanTrunk7-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2591-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2591, 'end': 2605, 'name': 'VlanTrunk7-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2591-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2606, 'end': 2620, 'name': 'VlanTrunk8-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2606-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2606, 'end': 2620, 'name': 'VlanTrunk8-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2606-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2621, 'end': 2635, 'name': 'VlanTrunk9-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2621-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2621, 'end': 2635, 'name': 'VlanTrunk9-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2621-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2636, 'end': 2650, 'name': 'VlanTrunk10-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2636-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2636, 'end': 2650, 'name': 'VlanTrunk10-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2636-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2651, 'end': 2665, 'name': 'VlanTrunk11-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2651-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2651, 'end': 2665, 'name': 'VlanTrunk11-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2651-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2666, 'end': 2680, 'name': 'VlanTrunk12-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2666-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2666, 'end': 2680, 'name': 'VlanTrunk12-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2666-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2681, 'end': 2695, 'name': 'VlanTrunk13-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2681-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2681, 'end': 2695, 'name': 'VlanTrunk13-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2681-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2696, 'end': 2710, 'name': 'VlanTrunk14-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2696-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2696, 'end': 2710, 'name': 'VlanTrunk14-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2696-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2711, 'end': 2725, 'name': 'VlanTrunk15-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2711-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2711, 'end': 2725, 'name': 'VlanTrunk15-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2711-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2726, 'end': 2750, 'name': 'VlanTrunk16-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2726-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2726, 'end': 2750, 'name': 'VlanTrunk16-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2726-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2751, 'end': 2777, 'name': 'VlanTrunk17-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2751-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2751, 'end': 2777, 'name': 'VlanTrunk17-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2751-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2778, 'end': 2804, 'name': 'VlanTrunk18-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2778-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2778, 'end': 2804, 'name': 'VlanTrunk18-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2778-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2805, 'end': 2831, 'name': 'VlanTrunk19-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2805-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2805, 'end': 2831, 'name': 'VlanTrunk19-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2805-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2832, 'end': 2858, 'name': 'VlanTrunk20-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2832-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2832, 'end': 2858, 'name': 'VlanTrunk20-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2832-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2859, 'end': 2885, 'name': 'VlanTrunk21-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2859-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2859, 'end': 2885, 'name': 'VlanTrunk21-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2859-E'},
# {'prefix': 'net_', 'suffix': '-O', 'start': 2886, 'end': 2992, 'name': 'VlanTrunk22-O', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2886-O'},
# {'prefix': 'net_', 'suffix': '-E', 'start': 2886, 'end': 2992, 'name': 'VlanTrunk22-E', 'type': 'network-set', 'networkUris': None, 'nativeNetworkUri': 'net_2886-E'}
# ]
enc_group = [{'name': 'F10D-F10D-F10D-F10D',
'type': 'EnclosureGroupV200',
'enclosureTypeUri': '/rest/enclosure-types/c7000',
'stackingMode': 'Enclosure',
'interconnectBayMappingCount': 8,
'configurationScript': None,
'interconnectBayMappings':
[{'interconnectBay': 1, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 2, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 3, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 4, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 5, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 6, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 7, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'},
{'interconnectBay': 8, 'logicalInterconnectGroupUri': 'LIG:LIG-F10D-F10D-F10D-F10D'}]},
{'name': 'FF-8FC20',
'type': 'EnclosureGroupV200',
'enclosureTypeUri': '/rest/enclosure-types/c7000',
'stackingMode': 'Enclosure',
'interconnectBayMappingCount': 8,
'configurationScript': None,
'interconnectBayMappings':
[{'interconnectBay': 1, 'logicalInterconnectGroupUri': 'LIG:LIG-FF'},
{'interconnectBay': 2, 'logicalInterconnectGroupUri': 'LIG:LIG-FF'},
{'interconnectBay': 3, 'logicalInterconnectGroupUri': 'LIG:LIG-FF'},
{'interconnectBay': 4, 'logicalInterconnectGroupUri': 'LIG:LIG-FF'}]},
]
enc = [{'hostname': '15.186.2.186', 'username': 'Administrator', 'password': 'compaq', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'force': False, 'licensingIntent': 'OneView'},
{'hostname': '15.186.2.137', 'username': 'Administrator', 'password': 'compaq', 'enclosureGroupUri': 'EG:FF-8FC20', 'force': False, 'licensingIntent': 'OneView'},
]
uplink_sets = {'IC-a': {'name': 'IC',
'ethernetNetworkType': 'Untagged',
'networkType': 'Ethernet',
'networkUris': ['IC'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X10', 'speed': 'Auto'}]},
'IC-b': {'name': 'IC',
'ethernetNetworkType': 'Untagged',
'networkType': 'Ethernet',
'networkUris': ['IC'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X6', 'speed': 'Auto'}]},
'SAN-3-A': {'name': 'SAN-3-A',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-3-A'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '3', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-1-2-DA': {'name': 'SAN-1-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-1-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-1-1-DA': {'name': 'SAN-1-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-1-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-1-2-DA': {'name': 'SAN-1-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-1-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-1-3-DA': {'name': 'SAN-1-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-1-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-1-4-DA': {'name': 'SAN-1-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-1-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-2-1-DA': {'name': 'SAN-2-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-2-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '2', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-2-2-DA': {'name': 'SAN-2-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-2-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '2', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-2-3-DA': {'name': 'SAN-2-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-2-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '2', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-2-4-DA': {'name': 'SAN-2-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-2-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '2', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-3-1-DA': {'name': 'SAN-3-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-3-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '3', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-3-2-DA': {'name': 'SAN-3-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-3-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '3', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-3-3-DA': {'name': 'SAN-3-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-3-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '3', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-3-4-DA': {'name': 'SAN-3-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-3-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '3', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-4-1-DA': {'name': 'SAN-4-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-4-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '4', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-4-2-DA': {'name': 'SAN-4-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-4-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '4', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-4-3-DA': {'name': 'SAN-4-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-4-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '4', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-4-4-DA': {'name': 'SAN-4-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-4-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '4', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-5-1-DA': {'name': 'SAN-5-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-5-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '5', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-5-2-DA': {'name': 'SAN-5-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-5-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '5', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-5-3-DA': {'name': 'SAN-5-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-5-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '5', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-5-4-DA': {'name': 'SAN-5-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-5-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '5', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-6-1-DA': {'name': 'SAN-6-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-6-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '6', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-6-2-DA': {'name': 'SAN-6-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-6-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '6', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-6-3-DA': {'name': 'SAN-6-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-6-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '6', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-6-4-DA': {'name': 'SAN-6-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-6-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '6', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-7-1-DA': {'name': 'SAN-7-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-7-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '7', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-7-2-DA': {'name': 'SAN-7-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-7-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '7', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-7-3-DA': {'name': 'SAN-7-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-7-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '7', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-7-4-DA': {'name': 'SAN-7-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-7-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '7', 'port': 'X4', 'speed': 'Auto'}]},
'SAN-8-1-DA': {'name': 'SAN-8-1-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-8-1-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '8', 'port': 'X1', 'speed': 'Auto'}]},
'SAN-8-2-DA': {'name': 'SAN-8-2-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-8-2-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '8', 'port': 'X2', 'speed': 'Auto'}]},
'SAN-8-3-DA': {'name': 'SAN-8-3-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-8-3-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '8', 'port': 'X3', 'speed': 'Auto'}]},
'SAN-8-4-DA': {'name': 'SAN-8-4-DA',
'ethernetNetworkType': 'NotApplicable',
'networkType': 'FibreChannel',
'networkUris': ['SAN-8-4-DA'],
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '8', 'port': 'X4', 'speed': 'Auto'}]},
'BigPipe16': {'name': 'BigPipe16',
'ethernetNetworkType': 'Tagged',
'networkType': 'Ethernet',
'networkUris': make_range_list({'start': 1, 'end': 44, 'prefix':'net_', 'suffix':''}),
'nativeNetworkUri': None,
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X5', 'speed': 'Auto'},
{'bay': '2', 'port': 'X5', 'speed': 'Auto'},
{'bay': '1', 'port': 'X6', 'speed': 'Auto'},
{'bay': '2', 'port': 'X6', 'speed': 'Auto'}]},
'BigPipe17': {'name': 'BigPipe17',
'ethernetNetworkType': 'Tagged',
'networkType': 'Ethernet',
'networkUris': make_range_list({'start': 1, 'end': 44, 'prefix':'net_', 'suffix':''}),
'nativeNetworkUri': 'net_1',
'mode': 'Auto',
'logicalPortConfigInfos': [{'bay': '1', 'port': 'X1', 'speed': 'Auto'},
{'bay': '2', 'port': 'X1', 'speed': 'Auto'}]}
}
ligs = [{'name': 'LIG-F10D-F10D-F10D-F10D',
'type': 'logical-interconnect-groupV3',
'enclosureType': 'C7000',
'interconnectMapTemplate': [{'bay': 1, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 2, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 3, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 4, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 5, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 6, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 7, 'type': 'HP VC Flex-10/10D Module'},
{'bay': 8, 'type': 'HP VC Flex-10/10D Module'},
],
'uplinkSets': [uplink_sets['IC'],
# uplink_sets['SAN-1-1-DA'],
# uplink_sets['SAN-1-2-DA'],
# uplink_sets['SAN-1-3-DA'],
# uplink_sets['SAN-1-4-DA'],
# uplink_sets['SAN-2-1-DA'],
# uplink_sets['SAN-2-2-DA'],
# uplink_sets['SAN-2-3-DA'],
# uplink_sets['SAN-2-4-DA'],
# uplink_sets['SAN-3-1-DA'],
# uplink_sets['SAN-3-2-DA'],
# uplink_sets['SAN-3-3-DA'],
# uplink_sets['SAN-3-4-DA'],
# uplink_sets['SAN-4-1-DA'],
# uplink_sets['SAN-4-2-DA'],
# uplink_sets['SAN-4-3-DA'],
# uplink_sets['SAN-4-4-DA'],
# uplink_sets['SAN-5-1-DA'],
# uplink_sets['SAN-5-2-DA'],
# uplink_sets['SAN-5-3-DA'],
# uplink_sets['SAN-5-4-DA'],
# uplink_sets['SAN-6-1-DA'],
# uplink_sets['SAN-6-2-DA'],
# uplink_sets['SAN-6-3-DA'],
# uplink_sets['SAN-6-4-DA'],
# uplink_sets['SAN-7-1-DA'],
# uplink_sets['SAN-7-2-DA'],
# uplink_sets['SAN-7-3-DA'],
# uplink_sets['SAN-7-4-DA'],
# uplink_sets['SAN-8-1-DA'],
# uplink_sets['SAN-8-2-DA'],
# uplink_sets['SAN-8-3-DA'],
# uplink_sets['SAN-8-4-DA'],
# uplink_sets['BigPipe15-a'],
uplink_sets['BigPipe16']],
'stackingMode': None,
'ethernetSettings': None,
'state': 'Active',
'telemetryConfiguration': None,
'snmpConfiguration': None},
{'name': 'LIG-FF-8FC20',
'type': 'logical-interconnect-groupV3',
'enclosureType': 'C7000',
'interconnectMapTemplate': [{'bay': 1, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'},
{'bay': 2, 'type': 'HP VC FlexFabric 10Gb/24-Port Module'},
{'bay': 3, 'type': 'HP VC 8Gb 20-Port FC Module'},
{'bay': 4, 'type': 'HP VC 8Gb 20-Port FC Module'},
],
'uplinkSets': [uplink_sets['IC'],
uplink_sets['BigPipe17']],
'stackingMode': None,
'ethernetSettings': None,
'state': 'Active',
'telemetryConfiguration': None,
'snmpConfiguration': None},
]
telemetry = {'enableTelemetry': True, 'sampleInterval': 400, 'sampleCount': 20}
trapDestinations = [{'trapSeverities': ['Major'],
'enetTrapCategories': ['Other'],
'fcTrapCategories': ['Other'],
'vcmTrapCategories': ['Legacy'],
'trapFormat': 'SNMPv1',
'trapDestination': '192.168.99.99',
'communityString': 'public'}]
snmp = {'snmpAccess': ['192.168.1.0/24'],
'trapDestinations': trapDestinations}
enet = {'enableFastMacCacheFailover': False}
server_profiles = [{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 1',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay1-BL620cG7', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_9', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_9', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_10', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_10', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_11', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_11', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 2',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay2-BL685cG7', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3996', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3996', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_12', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_12', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Lom 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_13', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Lom 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_13', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_14', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_14', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3995', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3995', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_15', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_15', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_16', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_16', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_17', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_17', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3994', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3994', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_18', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_18', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_19', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_19', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_20', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_20', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_21', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_21', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_22', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_22', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 3',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay3-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3992', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3992', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_23', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_23', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_24', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_24', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_25', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_25', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3991', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3991', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_26', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_26', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_27', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_27', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_28', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_28', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3990', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3990', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_30', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_30', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_31', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_31', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_32', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_32', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_33', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_33', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 4',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay4-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3988', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3988', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_34', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_34', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_35', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_35', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_36', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_36', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3987', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3987', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_37', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_37', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_38', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_38', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_39', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_39', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3986', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3986', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_40', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_40', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_41', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_41', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_42', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_42', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_43', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_43', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_44', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_44', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 5',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay5-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_9', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_9', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_10', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_10', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_11', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_11', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 6',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay6-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3996', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3996', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_12', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_12', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_13', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_13', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_14', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_14', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3995', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3995', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_15', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_15', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_16', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_16', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_17', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_17', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3994', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3994', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_18', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_18', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_19', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_19', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_20', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_20', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_21', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_21', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_22', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_22', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 7',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay7-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3992', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3992', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_23', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_23', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_24', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_24', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_25', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_25', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3991', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3991', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_26', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_26', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_27', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_27', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_28', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_28', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3990', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3990', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_30', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_30', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_31', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_31', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_32', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_32', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_33', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_33', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-16, bay 8',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-16', 'enclosureGroupUri': 'EG:F10D-F10D-F10D-F10D', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-16_Bay8-BL660cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3988', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3988', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_34', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_34', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_35', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_35', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_36', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_36', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 10, 'name': '10', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3987', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 11, 'name': '11', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3987', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 12, 'name': '12', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_37', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 13, 'name': '13', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_37', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 14, 'name': '14', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_38', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 15, 'name': '15', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_38', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 16, 'name': '16', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_39', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 17, 'name': '17', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_39', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 18, 'name': '18', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3986', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 19, 'name': '19', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3986', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 20, 'name': '20', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_40', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 21, 'name': '21', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_40', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 22, 'name': '22', 'functionType': 'Ethernet', 'portId': 'Mezz 2:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_41', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 23, 'name': '23', 'functionType': 'Ethernet', 'portId': 'Mezz 2:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_41', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 24, 'name': '24', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_42', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 25, 'name': '25', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:net_42', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 26, 'name': '26', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel1', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 27, 'name': '27', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-b', 'requestedMbps': '2500', 'networkUri': 'ETH:Tunnel2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 28, 'name': '28', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_43', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 29, 'name': '29', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_43', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 30, 'name': '30', 'functionType': 'Ethernet', 'portId': 'Mezz 3:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_44', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 31, 'name': '31', 'functionType': 'Ethernet', 'portId': 'Mezz 3:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_44', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 1',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay1-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 2',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay2-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 3',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay3-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 4',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay4-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 5',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay5-BL420cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 6',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay6-BL420cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 7',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay7-BL420cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 8',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay8-BL420cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 9',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay9-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 10',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay10-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 11',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay11-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 12',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay12-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 13',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay13-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_4000', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_29', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_2', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 14',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay14-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3999', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_3', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_4', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 15',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay15-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3998', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_5', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_6', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
{'type': 'ServerProfileV5', 'serverHardwareUri': 'CI-FIT-17, bay 16',
'serverHardwareTypeUri': '', 'enclosureUri': 'ENC:CI-FIT-17', 'enclosureGroupUri': 'EG:FF-8FC20', 'serialNumberType': 'Virtual', 'macType': 'Virtual', 'wwnType': 'Virtual',
'name': 'CI-FIT-17_Bay16-BL465cGen8', 'description': '', 'affinity': 'Bay',
'boot': {'manageBoot': True, 'order': ['CD', 'Floppy', 'USB', 'PXE', 'HardDisk']},
'connections': [{'id': 1, 'name': '1', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-a', 'requestedMbps': '2500', 'networkUri': 'ETH:IC', 'boot': {'priority': 'Primary'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 2, 'name': '2', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 3, 'name': '3', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-b', 'requestedMbps': '2500', 'networkUri': 'NS:NS_3997', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 4, 'name': '4', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 5, 'name': '5', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-c', 'requestedMbps': '2500', 'networkUri': 'ETH:net_7', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 6, 'name': '6', 'functionType': 'Ethernet', 'portId': 'Flb 1:1-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 7, 'name': '7', 'functionType': 'Ethernet', 'portId': 'Flb 1:2-d', 'requestedMbps': '2500', 'networkUri': 'ETH:net_8', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 8, 'name': '8', 'functionType': 'Ethernet', 'portId': 'Mezz 1:1', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-3-A', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
{'id': 9, 'name': '9', 'functionType': 'Ethernet', 'portId': 'Mezz 1:2', 'requestedMbps': '2500', 'networkUri': 'FC:SAN-4-B', 'boot': {'priority': 'NotBootable'}, 'mac': None, 'wwpn': '', 'wwnn': ''},
]},
]
true = True
false = False
rc = {'200': 200, '201': 201, '202': 202, '400': 400, '401': 401, '403': 403, '412': 412, '500': 500}
########################################
default_variables = {'admin_credentials': admin_credentials,
'appliance': appliance,
'enc': enc,
'enc_group': enc_group,
'ethernet_networks': ethernet_networks,
'ethernet_ranges': ethernet_ranges,
'fc_networks': fc_networks,
'licenses': licenses,
'ligs': ligs,
'network_sets': network_sets,
# 'network_set_ranges': network_set_ranges,
'ranges': ranges,
'rc': rc,
'server_profiles': server_profiles,
'uplink_sets': uplink_sets,
'users': users,
'timeandlocale': timeandlocale,
'true': true, 'false': false,
'vcenter': vcenter}
def get_variables():
variables = default_variables
return variables
| [
"[email protected]"
] | |
243e12cea1928f4024ea0d1bbd062a8b27808eb6 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /avBHBMAwf9ibDpfNM_17.py | 90a9250d618305bcb7990c7a48831401227015ca | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 122 | py |
import requests
def content_type(url):
r = requests.get('https://edabit.com/')
return r.headers['content-type']
| [
"[email protected]"
] | |
e4da1c60a852bd610107e481b15b04c840883e61 | 306a4c0c7ed32e879f76e6c101da70c46679f6bc | /copying_files_folders.py | 2ff064ba2279ee561714d6f97429272228f18007 | [] | no_license | ksoh512/automatetheboringstuff | 3552f803d73644862e2e31d307b50aff82b6a839 | 0d9ee8de7927dbe0e0f08dbfb73867ffd9bf563c | refs/heads/master | 2021-01-20T03:02:14.554780 | 2017-08-24T22:52:37 | 2017-08-24T22:52:37 | 101,343,630 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 382 | py | import shutil, os
os.chdir('C:\\')
''' COPY FILES '''
shutil.copy('C:\\spam.txt', 'C:\\Users\\koh\\Documents\\codes\\automattheboringstuff')
shutil.copy('C:\\eggs.txt', 'C:\\Users\\koh\\Documents\\codes\\automattheboringstuff')
'''COPY FOLDERS AND FILES CONTAINED IN IT'''
shutil.copytree('C:\\delicious', 'C:\\Users\\koh\\Documents\\codes\\automattheboringstuff')
| [
"[email protected]"
] | |
c0642e90ddb142bbe67af2cbb81148287054d3d3 | f07a42f652f46106dee4749277d41c302e2b7406 | /Data Set/bug-fixing-5/530bd27ed2c4c8e3f6a44b332569c3f73dfcb332-<test_np_mixed_precision_binary_funcs>-fix.py | 8e9d3b67eb8f1b2c486e7784f60da806ef689c24 | [] | no_license | wsgan001/PyFPattern | e0fe06341cc5d51b3ad0fe29b84098d140ed54d1 | cc347e32745f99c0cd95e79a18ddacc4574d7faa | refs/heads/main | 2023-08-25T23:48:26.112133 | 2021-10-23T14:11:22 | 2021-10-23T14:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,667 | py | @with_seed()
@use_np
def test_np_mixed_precision_binary_funcs():
def check_mixed_precision_binary_func(func, low, high, lshape, rshape, ltype, rtype):
class TestMixedBinary(HybridBlock):
def __init__(self, func):
super(TestMixedBinary, self).__init__()
self._func = func
def hybrid_forward(self, F, a, b, *args, **kwargs):
return getattr(F.np, self._func)(a, b)
np_func = getattr(_np, func)
mx_func = TestMixedBinary(func)
np_test_x1 = _np.random.uniform(low, high, lshape).astype(ltype)
np_test_x2 = _np.random.uniform(low, high, rshape).astype(rtype)
mx_test_x1 = mx.numpy.array(np_test_x1, dtype=ltype)
mx_test_x2 = mx.numpy.array(np_test_x2, dtype=rtype)
rtol = (0.01 if ((ltype is np.float16) or (rtype is np.float16)) else 0.001)
atol = (0.001 if ((ltype is np.float16) or (rtype is np.float16)) else 1e-05)
for hybridize in [True, False]:
if hybridize:
mx_func.hybridize()
np_out = np_func(np_test_x1, np_test_x2)
with mx.autograd.record():
y = mx_func(mx_test_x1, mx_test_x2)
assert (y.shape == np_out.shape)
assert_almost_equal(y.asnumpy(), np_out.astype(y.dtype), rtol=rtol, atol=atol, use_broadcast=False, equal_nan=True)
np_out = getattr(_np, func)(np_test_x1, np_test_x2)
mx_out = getattr(mx.np, func)(mx_test_x1, mx_test_x2)
assert (mx_out.shape == np_out.shape)
assert_almost_equal(mx_out.asnumpy(), np_out.astype(mx_out.dtype), rtol=rtol, atol=atol, use_broadcast=False, equal_nan=True)
funcs = {
'add': ((- 1.0), 1.0),
'subtract': ((- 1.0), 1.0),
'multiply': ((- 1.0), 1.0),
}
shape_pairs = [((3, 2), (3, 2)), ((3, 2), (3, 1)), ((3, 1), (3, 0)), ((0, 2), (1, 2)), ((2, 3, 4), (3, 1)), ((2, 3), ()), ((), (2, 3))]
itypes = [np.bool, np.int8, np.int32, np.int64]
ftypes = [np.float16, np.float32, np.float64]
for (func, func_data) in funcs.items():
(low, high) = func_data
for (lshape, rshape) in shape_pairs:
for (type1, type2) in itertools.product(itypes, ftypes):
check_mixed_precision_binary_func(func, low, high, lshape, rshape, type1, type2)
check_mixed_precision_binary_func(func, low, high, lshape, rshape, type2, type1)
for (type1, type2) in itertools.product(ftypes, ftypes):
if (type1 == type2):
continue
check_mixed_precision_binary_func(func, low, high, lshape, rshape, type1, type2) | [
"[email protected]"
] | |
9947a3418aa2766666e453d116400e76bc1b5cfe | decefb13f8a603c1f5cc7eb00634b4649915204f | /packages/node-mobile/deps/openssl/config/archs/solaris-x86-gcc/asm/openssl.gypi | 60c75c7f2eafd2a30bcd31118d95d85e81e6b0a0 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown",
"Zlib",
"CC0-1.0",
"ISC",
"LicenseRef-scancode-public-domain",
"ICU",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"Artistic-2.0",
"BSD-3-Clause",
"NTP",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-unicode",
"NAIST-2003"
] | permissive | open-pwa/open-pwa | f092b377dc6cb04123a16ef96811ad09a9956c26 | 4c88c8520b4f6e7af8701393fd2cedbe1b209e8f | refs/heads/master | 2022-05-28T22:05:19.514921 | 2022-05-20T07:27:10 | 2022-05-20T07:27:10 | 247,925,596 | 24 | 1 | Apache-2.0 | 2021-08-10T07:38:42 | 2020-03-17T09:13:00 | C++ | UTF-8 | Python | false | false | 28,783 | gypi | {
'variables': {
'openssl_sources': [
'openssl/ssl/bio_ssl.c',
'openssl/ssl/d1_lib.c',
'openssl/ssl/d1_msg.c',
'openssl/ssl/d1_srtp.c',
'openssl/ssl/methods.c',
'openssl/ssl/packet.c',
'openssl/ssl/pqueue.c',
'openssl/ssl/record/dtls1_bitmap.c',
'openssl/ssl/record/rec_layer_d1.c',
'openssl/ssl/record/rec_layer_s3.c',
'openssl/ssl/record/ssl3_buffer.c',
'openssl/ssl/record/ssl3_record.c',
'openssl/ssl/record/ssl3_record_tls13.c',
'openssl/ssl/s3_cbc.c',
'openssl/ssl/s3_enc.c',
'openssl/ssl/s3_lib.c',
'openssl/ssl/s3_msg.c',
'openssl/ssl/ssl_asn1.c',
'openssl/ssl/ssl_cert.c',
'openssl/ssl/ssl_ciph.c',
'openssl/ssl/ssl_conf.c',
'openssl/ssl/ssl_err.c',
'openssl/ssl/ssl_init.c',
'openssl/ssl/ssl_lib.c',
'openssl/ssl/ssl_mcnf.c',
'openssl/ssl/ssl_rsa.c',
'openssl/ssl/ssl_sess.c',
'openssl/ssl/ssl_stat.c',
'openssl/ssl/ssl_txt.c',
'openssl/ssl/ssl_utst.c',
'openssl/ssl/statem/extensions.c',
'openssl/ssl/statem/extensions_clnt.c',
'openssl/ssl/statem/extensions_cust.c',
'openssl/ssl/statem/extensions_srvr.c',
'openssl/ssl/statem/statem.c',
'openssl/ssl/statem/statem_clnt.c',
'openssl/ssl/statem/statem_dtls.c',
'openssl/ssl/statem/statem_lib.c',
'openssl/ssl/statem/statem_srvr.c',
'openssl/ssl/t1_enc.c',
'openssl/ssl/t1_lib.c',
'openssl/ssl/t1_trce.c',
'openssl/ssl/tls13_enc.c',
'openssl/ssl/tls_srp.c',
'openssl/crypto/aes/aes_cbc.c',
'openssl/crypto/aes/aes_cfb.c',
'openssl/crypto/aes/aes_core.c',
'openssl/crypto/aes/aes_ecb.c',
'openssl/crypto/aes/aes_ige.c',
'openssl/crypto/aes/aes_misc.c',
'openssl/crypto/aes/aes_ofb.c',
'openssl/crypto/aes/aes_wrap.c',
'openssl/crypto/aria/aria.c',
'openssl/crypto/asn1/a_bitstr.c',
'openssl/crypto/asn1/a_d2i_fp.c',
'openssl/crypto/asn1/a_digest.c',
'openssl/crypto/asn1/a_dup.c',
'openssl/crypto/asn1/a_gentm.c',
'openssl/crypto/asn1/a_i2d_fp.c',
'openssl/crypto/asn1/a_int.c',
'openssl/crypto/asn1/a_mbstr.c',
'openssl/crypto/asn1/a_object.c',
'openssl/crypto/asn1/a_octet.c',
'openssl/crypto/asn1/a_print.c',
'openssl/crypto/asn1/a_sign.c',
'openssl/crypto/asn1/a_strex.c',
'openssl/crypto/asn1/a_strnid.c',
'openssl/crypto/asn1/a_time.c',
'openssl/crypto/asn1/a_type.c',
'openssl/crypto/asn1/a_utctm.c',
'openssl/crypto/asn1/a_utf8.c',
'openssl/crypto/asn1/a_verify.c',
'openssl/crypto/asn1/ameth_lib.c',
'openssl/crypto/asn1/asn1_err.c',
'openssl/crypto/asn1/asn1_gen.c',
'openssl/crypto/asn1/asn1_item_list.c',
'openssl/crypto/asn1/asn1_lib.c',
'openssl/crypto/asn1/asn1_par.c',
'openssl/crypto/asn1/asn_mime.c',
'openssl/crypto/asn1/asn_moid.c',
'openssl/crypto/asn1/asn_mstbl.c',
'openssl/crypto/asn1/asn_pack.c',
'openssl/crypto/asn1/bio_asn1.c',
'openssl/crypto/asn1/bio_ndef.c',
'openssl/crypto/asn1/d2i_pr.c',
'openssl/crypto/asn1/d2i_pu.c',
'openssl/crypto/asn1/evp_asn1.c',
'openssl/crypto/asn1/f_int.c',
'openssl/crypto/asn1/f_string.c',
'openssl/crypto/asn1/i2d_pr.c',
'openssl/crypto/asn1/i2d_pu.c',
'openssl/crypto/asn1/n_pkey.c',
'openssl/crypto/asn1/nsseq.c',
'openssl/crypto/asn1/p5_pbe.c',
'openssl/crypto/asn1/p5_pbev2.c',
'openssl/crypto/asn1/p5_scrypt.c',
'openssl/crypto/asn1/p8_pkey.c',
'openssl/crypto/asn1/t_bitst.c',
'openssl/crypto/asn1/t_pkey.c',
'openssl/crypto/asn1/t_spki.c',
'openssl/crypto/asn1/tasn_dec.c',
'openssl/crypto/asn1/tasn_enc.c',
'openssl/crypto/asn1/tasn_fre.c',
'openssl/crypto/asn1/tasn_new.c',
'openssl/crypto/asn1/tasn_prn.c',
'openssl/crypto/asn1/tasn_scn.c',
'openssl/crypto/asn1/tasn_typ.c',
'openssl/crypto/asn1/tasn_utl.c',
'openssl/crypto/asn1/x_algor.c',
'openssl/crypto/asn1/x_bignum.c',
'openssl/crypto/asn1/x_info.c',
'openssl/crypto/asn1/x_int64.c',
'openssl/crypto/asn1/x_long.c',
'openssl/crypto/asn1/x_pkey.c',
'openssl/crypto/asn1/x_sig.c',
'openssl/crypto/asn1/x_spki.c',
'openssl/crypto/asn1/x_val.c',
'openssl/crypto/async/arch/async_null.c',
'openssl/crypto/async/arch/async_posix.c',
'openssl/crypto/async/arch/async_win.c',
'openssl/crypto/async/async.c',
'openssl/crypto/async/async_err.c',
'openssl/crypto/async/async_wait.c',
'openssl/crypto/bf/bf_cfb64.c',
'openssl/crypto/bf/bf_ecb.c',
'openssl/crypto/bf/bf_ofb64.c',
'openssl/crypto/bf/bf_skey.c',
'openssl/crypto/bio/b_addr.c',
'openssl/crypto/bio/b_dump.c',
'openssl/crypto/bio/b_print.c',
'openssl/crypto/bio/b_sock.c',
'openssl/crypto/bio/b_sock2.c',
'openssl/crypto/bio/bf_buff.c',
'openssl/crypto/bio/bf_lbuf.c',
'openssl/crypto/bio/bf_nbio.c',
'openssl/crypto/bio/bf_null.c',
'openssl/crypto/bio/bio_cb.c',
'openssl/crypto/bio/bio_err.c',
'openssl/crypto/bio/bio_lib.c',
'openssl/crypto/bio/bio_meth.c',
'openssl/crypto/bio/bss_acpt.c',
'openssl/crypto/bio/bss_bio.c',
'openssl/crypto/bio/bss_conn.c',
'openssl/crypto/bio/bss_dgram.c',
'openssl/crypto/bio/bss_fd.c',
'openssl/crypto/bio/bss_file.c',
'openssl/crypto/bio/bss_log.c',
'openssl/crypto/bio/bss_mem.c',
'openssl/crypto/bio/bss_null.c',
'openssl/crypto/bio/bss_sock.c',
'openssl/crypto/blake2/blake2b.c',
'openssl/crypto/blake2/blake2s.c',
'openssl/crypto/blake2/m_blake2b.c',
'openssl/crypto/blake2/m_blake2s.c',
'openssl/crypto/bn/bn_add.c',
'openssl/crypto/bn/bn_blind.c',
'openssl/crypto/bn/bn_const.c',
'openssl/crypto/bn/bn_ctx.c',
'openssl/crypto/bn/bn_depr.c',
'openssl/crypto/bn/bn_dh.c',
'openssl/crypto/bn/bn_div.c',
'openssl/crypto/bn/bn_err.c',
'openssl/crypto/bn/bn_exp.c',
'openssl/crypto/bn/bn_exp2.c',
'openssl/crypto/bn/bn_gcd.c',
'openssl/crypto/bn/bn_gf2m.c',
'openssl/crypto/bn/bn_intern.c',
'openssl/crypto/bn/bn_kron.c',
'openssl/crypto/bn/bn_lib.c',
'openssl/crypto/bn/bn_mod.c',
'openssl/crypto/bn/bn_mont.c',
'openssl/crypto/bn/bn_mpi.c',
'openssl/crypto/bn/bn_mul.c',
'openssl/crypto/bn/bn_nist.c',
'openssl/crypto/bn/bn_prime.c',
'openssl/crypto/bn/bn_print.c',
'openssl/crypto/bn/bn_rand.c',
'openssl/crypto/bn/bn_recp.c',
'openssl/crypto/bn/bn_shift.c',
'openssl/crypto/bn/bn_sqr.c',
'openssl/crypto/bn/bn_sqrt.c',
'openssl/crypto/bn/bn_srp.c',
'openssl/crypto/bn/bn_word.c',
'openssl/crypto/bn/bn_x931p.c',
'openssl/crypto/buffer/buf_err.c',
'openssl/crypto/buffer/buffer.c',
'openssl/crypto/camellia/cmll_cfb.c',
'openssl/crypto/camellia/cmll_ctr.c',
'openssl/crypto/camellia/cmll_ecb.c',
'openssl/crypto/camellia/cmll_ofb.c',
'openssl/crypto/cast/c_cfb64.c',
'openssl/crypto/cast/c_ecb.c',
'openssl/crypto/cast/c_enc.c',
'openssl/crypto/cast/c_ofb64.c',
'openssl/crypto/cast/c_skey.c',
'openssl/crypto/cmac/cm_ameth.c',
'openssl/crypto/cmac/cm_pmeth.c',
'openssl/crypto/cmac/cmac.c',
'openssl/crypto/cms/cms_asn1.c',
'openssl/crypto/cms/cms_att.c',
'openssl/crypto/cms/cms_cd.c',
'openssl/crypto/cms/cms_dd.c',
'openssl/crypto/cms/cms_enc.c',
'openssl/crypto/cms/cms_env.c',
'openssl/crypto/cms/cms_err.c',
'openssl/crypto/cms/cms_ess.c',
'openssl/crypto/cms/cms_io.c',
'openssl/crypto/cms/cms_kari.c',
'openssl/crypto/cms/cms_lib.c',
'openssl/crypto/cms/cms_pwri.c',
'openssl/crypto/cms/cms_sd.c',
'openssl/crypto/cms/cms_smime.c',
'openssl/crypto/conf/conf_api.c',
'openssl/crypto/conf/conf_def.c',
'openssl/crypto/conf/conf_err.c',
'openssl/crypto/conf/conf_lib.c',
'openssl/crypto/conf/conf_mall.c',
'openssl/crypto/conf/conf_mod.c',
'openssl/crypto/conf/conf_sap.c',
'openssl/crypto/conf/conf_ssl.c',
'openssl/crypto/cpt_err.c',
'openssl/crypto/cryptlib.c',
'openssl/crypto/ct/ct_b64.c',
'openssl/crypto/ct/ct_err.c',
'openssl/crypto/ct/ct_log.c',
'openssl/crypto/ct/ct_oct.c',
'openssl/crypto/ct/ct_policy.c',
'openssl/crypto/ct/ct_prn.c',
'openssl/crypto/ct/ct_sct.c',
'openssl/crypto/ct/ct_sct_ctx.c',
'openssl/crypto/ct/ct_vfy.c',
'openssl/crypto/ct/ct_x509v3.c',
'openssl/crypto/ctype.c',
'openssl/crypto/cversion.c',
'openssl/crypto/des/cbc_cksm.c',
'openssl/crypto/des/cbc_enc.c',
'openssl/crypto/des/cfb64ede.c',
'openssl/crypto/des/cfb64enc.c',
'openssl/crypto/des/cfb_enc.c',
'openssl/crypto/des/ecb3_enc.c',
'openssl/crypto/des/ecb_enc.c',
'openssl/crypto/des/fcrypt.c',
'openssl/crypto/des/ofb64ede.c',
'openssl/crypto/des/ofb64enc.c',
'openssl/crypto/des/ofb_enc.c',
'openssl/crypto/des/pcbc_enc.c',
'openssl/crypto/des/qud_cksm.c',
'openssl/crypto/des/rand_key.c',
'openssl/crypto/des/set_key.c',
'openssl/crypto/des/str2key.c',
'openssl/crypto/des/xcbc_enc.c',
'openssl/crypto/dh/dh_ameth.c',
'openssl/crypto/dh/dh_asn1.c',
'openssl/crypto/dh/dh_check.c',
'openssl/crypto/dh/dh_depr.c',
'openssl/crypto/dh/dh_err.c',
'openssl/crypto/dh/dh_gen.c',
'openssl/crypto/dh/dh_kdf.c',
'openssl/crypto/dh/dh_key.c',
'openssl/crypto/dh/dh_lib.c',
'openssl/crypto/dh/dh_meth.c',
'openssl/crypto/dh/dh_pmeth.c',
'openssl/crypto/dh/dh_prn.c',
'openssl/crypto/dh/dh_rfc5114.c',
'openssl/crypto/dh/dh_rfc7919.c',
'openssl/crypto/dsa/dsa_ameth.c',
'openssl/crypto/dsa/dsa_asn1.c',
'openssl/crypto/dsa/dsa_depr.c',
'openssl/crypto/dsa/dsa_err.c',
'openssl/crypto/dsa/dsa_gen.c',
'openssl/crypto/dsa/dsa_key.c',
'openssl/crypto/dsa/dsa_lib.c',
'openssl/crypto/dsa/dsa_meth.c',
'openssl/crypto/dsa/dsa_ossl.c',
'openssl/crypto/dsa/dsa_pmeth.c',
'openssl/crypto/dsa/dsa_prn.c',
'openssl/crypto/dsa/dsa_sign.c',
'openssl/crypto/dsa/dsa_vrf.c',
'openssl/crypto/dso/dso_dl.c',
'openssl/crypto/dso/dso_dlfcn.c',
'openssl/crypto/dso/dso_err.c',
'openssl/crypto/dso/dso_lib.c',
'openssl/crypto/dso/dso_openssl.c',
'openssl/crypto/dso/dso_vms.c',
'openssl/crypto/dso/dso_win32.c',
'openssl/crypto/ebcdic.c',
'openssl/crypto/ec/curve25519.c',
'openssl/crypto/ec/curve448/arch_32/f_impl.c',
'openssl/crypto/ec/curve448/curve448.c',
'openssl/crypto/ec/curve448/curve448_tables.c',
'openssl/crypto/ec/curve448/eddsa.c',
'openssl/crypto/ec/curve448/f_generic.c',
'openssl/crypto/ec/curve448/scalar.c',
'openssl/crypto/ec/ec2_oct.c',
'openssl/crypto/ec/ec2_smpl.c',
'openssl/crypto/ec/ec_ameth.c',
'openssl/crypto/ec/ec_asn1.c',
'openssl/crypto/ec/ec_check.c',
'openssl/crypto/ec/ec_curve.c',
'openssl/crypto/ec/ec_cvt.c',
'openssl/crypto/ec/ec_err.c',
'openssl/crypto/ec/ec_key.c',
'openssl/crypto/ec/ec_kmeth.c',
'openssl/crypto/ec/ec_lib.c',
'openssl/crypto/ec/ec_mult.c',
'openssl/crypto/ec/ec_oct.c',
'openssl/crypto/ec/ec_pmeth.c',
'openssl/crypto/ec/ec_print.c',
'openssl/crypto/ec/ecdh_kdf.c',
'openssl/crypto/ec/ecdh_ossl.c',
'openssl/crypto/ec/ecdsa_ossl.c',
'openssl/crypto/ec/ecdsa_sign.c',
'openssl/crypto/ec/ecdsa_vrf.c',
'openssl/crypto/ec/eck_prn.c',
'openssl/crypto/ec/ecp_mont.c',
'openssl/crypto/ec/ecp_nist.c',
'openssl/crypto/ec/ecp_nistp224.c',
'openssl/crypto/ec/ecp_nistp256.c',
'openssl/crypto/ec/ecp_nistp521.c',
'openssl/crypto/ec/ecp_nistputil.c',
'openssl/crypto/ec/ecp_nistz256.c',
'openssl/crypto/ec/ecp_oct.c',
'openssl/crypto/ec/ecp_smpl.c',
'openssl/crypto/ec/ecx_meth.c',
'openssl/crypto/engine/eng_all.c',
'openssl/crypto/engine/eng_cnf.c',
'openssl/crypto/engine/eng_ctrl.c',
'openssl/crypto/engine/eng_dyn.c',
'openssl/crypto/engine/eng_err.c',
'openssl/crypto/engine/eng_fat.c',
'openssl/crypto/engine/eng_init.c',
'openssl/crypto/engine/eng_lib.c',
'openssl/crypto/engine/eng_list.c',
'openssl/crypto/engine/eng_openssl.c',
'openssl/crypto/engine/eng_pkey.c',
'openssl/crypto/engine/eng_rdrand.c',
'openssl/crypto/engine/eng_table.c',
'openssl/crypto/engine/tb_asnmth.c',
'openssl/crypto/engine/tb_cipher.c',
'openssl/crypto/engine/tb_dh.c',
'openssl/crypto/engine/tb_digest.c',
'openssl/crypto/engine/tb_dsa.c',
'openssl/crypto/engine/tb_eckey.c',
'openssl/crypto/engine/tb_pkmeth.c',
'openssl/crypto/engine/tb_rand.c',
'openssl/crypto/engine/tb_rsa.c',
'openssl/crypto/err/err.c',
'openssl/crypto/err/err_all.c',
'openssl/crypto/err/err_prn.c',
'openssl/crypto/evp/bio_b64.c',
'openssl/crypto/evp/bio_enc.c',
'openssl/crypto/evp/bio_md.c',
'openssl/crypto/evp/bio_ok.c',
'openssl/crypto/evp/c_allc.c',
'openssl/crypto/evp/c_alld.c',
'openssl/crypto/evp/cmeth_lib.c',
'openssl/crypto/evp/digest.c',
'openssl/crypto/evp/e_aes.c',
'openssl/crypto/evp/e_aes_cbc_hmac_sha1.c',
'openssl/crypto/evp/e_aes_cbc_hmac_sha256.c',
'openssl/crypto/evp/e_aria.c',
'openssl/crypto/evp/e_bf.c',
'openssl/crypto/evp/e_camellia.c',
'openssl/crypto/evp/e_cast.c',
'openssl/crypto/evp/e_chacha20_poly1305.c',
'openssl/crypto/evp/e_des.c',
'openssl/crypto/evp/e_des3.c',
'openssl/crypto/evp/e_idea.c',
'openssl/crypto/evp/e_null.c',
'openssl/crypto/evp/e_old.c',
'openssl/crypto/evp/e_rc2.c',
'openssl/crypto/evp/e_rc4.c',
'openssl/crypto/evp/e_rc4_hmac_md5.c',
'openssl/crypto/evp/e_rc5.c',
'openssl/crypto/evp/e_seed.c',
'openssl/crypto/evp/e_sm4.c',
'openssl/crypto/evp/e_xcbc_d.c',
'openssl/crypto/evp/encode.c',
'openssl/crypto/evp/evp_cnf.c',
'openssl/crypto/evp/evp_enc.c',
'openssl/crypto/evp/evp_err.c',
'openssl/crypto/evp/evp_key.c',
'openssl/crypto/evp/evp_lib.c',
'openssl/crypto/evp/evp_pbe.c',
'openssl/crypto/evp/evp_pkey.c',
'openssl/crypto/evp/m_md2.c',
'openssl/crypto/evp/m_md4.c',
'openssl/crypto/evp/m_md5.c',
'openssl/crypto/evp/m_md5_sha1.c',
'openssl/crypto/evp/m_mdc2.c',
'openssl/crypto/evp/m_null.c',
'openssl/crypto/evp/m_ripemd.c',
'openssl/crypto/evp/m_sha1.c',
'openssl/crypto/evp/m_sha3.c',
'openssl/crypto/evp/m_sigver.c',
'openssl/crypto/evp/m_wp.c',
'openssl/crypto/evp/names.c',
'openssl/crypto/evp/p5_crpt.c',
'openssl/crypto/evp/p5_crpt2.c',
'openssl/crypto/evp/p_dec.c',
'openssl/crypto/evp/p_enc.c',
'openssl/crypto/evp/p_lib.c',
'openssl/crypto/evp/p_open.c',
'openssl/crypto/evp/p_seal.c',
'openssl/crypto/evp/p_sign.c',
'openssl/crypto/evp/p_verify.c',
'openssl/crypto/evp/pbe_scrypt.c',
'openssl/crypto/evp/pmeth_fn.c',
'openssl/crypto/evp/pmeth_gn.c',
'openssl/crypto/evp/pmeth_lib.c',
'openssl/crypto/ex_data.c',
'openssl/crypto/getenv.c',
'openssl/crypto/hmac/hm_ameth.c',
'openssl/crypto/hmac/hm_pmeth.c',
'openssl/crypto/hmac/hmac.c',
'openssl/crypto/idea/i_cbc.c',
'openssl/crypto/idea/i_cfb64.c',
'openssl/crypto/idea/i_ecb.c',
'openssl/crypto/idea/i_ofb64.c',
'openssl/crypto/idea/i_skey.c',
'openssl/crypto/init.c',
'openssl/crypto/kdf/hkdf.c',
'openssl/crypto/kdf/kdf_err.c',
'openssl/crypto/kdf/scrypt.c',
'openssl/crypto/kdf/tls1_prf.c',
'openssl/crypto/lhash/lh_stats.c',
'openssl/crypto/lhash/lhash.c',
'openssl/crypto/md4/md4_dgst.c',
'openssl/crypto/md4/md4_one.c',
'openssl/crypto/md5/md5_dgst.c',
'openssl/crypto/md5/md5_one.c',
'openssl/crypto/mdc2/mdc2_one.c',
'openssl/crypto/mdc2/mdc2dgst.c',
'openssl/crypto/mem.c',
'openssl/crypto/mem_dbg.c',
'openssl/crypto/mem_sec.c',
'openssl/crypto/modes/cbc128.c',
'openssl/crypto/modes/ccm128.c',
'openssl/crypto/modes/cfb128.c',
'openssl/crypto/modes/ctr128.c',
'openssl/crypto/modes/cts128.c',
'openssl/crypto/modes/gcm128.c',
'openssl/crypto/modes/ocb128.c',
'openssl/crypto/modes/ofb128.c',
'openssl/crypto/modes/wrap128.c',
'openssl/crypto/modes/xts128.c',
'openssl/crypto/o_dir.c',
'openssl/crypto/o_fips.c',
'openssl/crypto/o_fopen.c',
'openssl/crypto/o_init.c',
'openssl/crypto/o_str.c',
'openssl/crypto/o_time.c',
'openssl/crypto/objects/o_names.c',
'openssl/crypto/objects/obj_dat.c',
'openssl/crypto/objects/obj_err.c',
'openssl/crypto/objects/obj_lib.c',
'openssl/crypto/objects/obj_xref.c',
'openssl/crypto/ocsp/ocsp_asn.c',
'openssl/crypto/ocsp/ocsp_cl.c',
'openssl/crypto/ocsp/ocsp_err.c',
'openssl/crypto/ocsp/ocsp_ext.c',
'openssl/crypto/ocsp/ocsp_ht.c',
'openssl/crypto/ocsp/ocsp_lib.c',
'openssl/crypto/ocsp/ocsp_prn.c',
'openssl/crypto/ocsp/ocsp_srv.c',
'openssl/crypto/ocsp/ocsp_vfy.c',
'openssl/crypto/ocsp/v3_ocsp.c',
'openssl/crypto/pem/pem_all.c',
'openssl/crypto/pem/pem_err.c',
'openssl/crypto/pem/pem_info.c',
'openssl/crypto/pem/pem_lib.c',
'openssl/crypto/pem/pem_oth.c',
'openssl/crypto/pem/pem_pk8.c',
'openssl/crypto/pem/pem_pkey.c',
'openssl/crypto/pem/pem_sign.c',
'openssl/crypto/pem/pem_x509.c',
'openssl/crypto/pem/pem_xaux.c',
'openssl/crypto/pem/pvkfmt.c',
'openssl/crypto/pkcs12/p12_add.c',
'openssl/crypto/pkcs12/p12_asn.c',
'openssl/crypto/pkcs12/p12_attr.c',
'openssl/crypto/pkcs12/p12_crpt.c',
'openssl/crypto/pkcs12/p12_crt.c',
'openssl/crypto/pkcs12/p12_decr.c',
'openssl/crypto/pkcs12/p12_init.c',
'openssl/crypto/pkcs12/p12_key.c',
'openssl/crypto/pkcs12/p12_kiss.c',
'openssl/crypto/pkcs12/p12_mutl.c',
'openssl/crypto/pkcs12/p12_npas.c',
'openssl/crypto/pkcs12/p12_p8d.c',
'openssl/crypto/pkcs12/p12_p8e.c',
'openssl/crypto/pkcs12/p12_sbag.c',
'openssl/crypto/pkcs12/p12_utl.c',
'openssl/crypto/pkcs12/pk12err.c',
'openssl/crypto/pkcs7/bio_pk7.c',
'openssl/crypto/pkcs7/pk7_asn1.c',
'openssl/crypto/pkcs7/pk7_attr.c',
'openssl/crypto/pkcs7/pk7_doit.c',
'openssl/crypto/pkcs7/pk7_lib.c',
'openssl/crypto/pkcs7/pk7_mime.c',
'openssl/crypto/pkcs7/pk7_smime.c',
'openssl/crypto/pkcs7/pkcs7err.c',
'openssl/crypto/poly1305/poly1305.c',
'openssl/crypto/poly1305/poly1305_ameth.c',
'openssl/crypto/poly1305/poly1305_pmeth.c',
'openssl/crypto/rand/drbg_ctr.c',
'openssl/crypto/rand/drbg_lib.c',
'openssl/crypto/rand/rand_egd.c',
'openssl/crypto/rand/rand_err.c',
'openssl/crypto/rand/rand_lib.c',
'openssl/crypto/rand/rand_unix.c',
'openssl/crypto/rand/rand_vms.c',
'openssl/crypto/rand/rand_win.c',
'openssl/crypto/rand/randfile.c',
'openssl/crypto/rc2/rc2_cbc.c',
'openssl/crypto/rc2/rc2_ecb.c',
'openssl/crypto/rc2/rc2_skey.c',
'openssl/crypto/rc2/rc2cfb64.c',
'openssl/crypto/rc2/rc2ofb64.c',
'openssl/crypto/ripemd/rmd_dgst.c',
'openssl/crypto/ripemd/rmd_one.c',
'openssl/crypto/rsa/rsa_ameth.c',
'openssl/crypto/rsa/rsa_asn1.c',
'openssl/crypto/rsa/rsa_chk.c',
'openssl/crypto/rsa/rsa_crpt.c',
'openssl/crypto/rsa/rsa_depr.c',
'openssl/crypto/rsa/rsa_err.c',
'openssl/crypto/rsa/rsa_gen.c',
'openssl/crypto/rsa/rsa_lib.c',
'openssl/crypto/rsa/rsa_meth.c',
'openssl/crypto/rsa/rsa_mp.c',
'openssl/crypto/rsa/rsa_none.c',
'openssl/crypto/rsa/rsa_oaep.c',
'openssl/crypto/rsa/rsa_ossl.c',
'openssl/crypto/rsa/rsa_pk1.c',
'openssl/crypto/rsa/rsa_pmeth.c',
'openssl/crypto/rsa/rsa_prn.c',
'openssl/crypto/rsa/rsa_pss.c',
'openssl/crypto/rsa/rsa_saos.c',
'openssl/crypto/rsa/rsa_sign.c',
'openssl/crypto/rsa/rsa_ssl.c',
'openssl/crypto/rsa/rsa_x931.c',
'openssl/crypto/rsa/rsa_x931g.c',
'openssl/crypto/seed/seed.c',
'openssl/crypto/seed/seed_cbc.c',
'openssl/crypto/seed/seed_cfb.c',
'openssl/crypto/seed/seed_ecb.c',
'openssl/crypto/seed/seed_ofb.c',
'openssl/crypto/sha/keccak1600.c',
'openssl/crypto/sha/sha1_one.c',
'openssl/crypto/sha/sha1dgst.c',
'openssl/crypto/sha/sha256.c',
'openssl/crypto/sha/sha512.c',
'openssl/crypto/siphash/siphash.c',
'openssl/crypto/siphash/siphash_ameth.c',
'openssl/crypto/siphash/siphash_pmeth.c',
'openssl/crypto/sm2/sm2_crypt.c',
'openssl/crypto/sm2/sm2_err.c',
'openssl/crypto/sm2/sm2_pmeth.c',
'openssl/crypto/sm2/sm2_sign.c',
'openssl/crypto/sm3/m_sm3.c',
'openssl/crypto/sm3/sm3.c',
'openssl/crypto/sm4/sm4.c',
'openssl/crypto/srp/srp_lib.c',
'openssl/crypto/srp/srp_vfy.c',
'openssl/crypto/stack/stack.c',
'openssl/crypto/store/loader_file.c',
'openssl/crypto/store/store_err.c',
'openssl/crypto/store/store_init.c',
'openssl/crypto/store/store_lib.c',
'openssl/crypto/store/store_register.c',
'openssl/crypto/store/store_strings.c',
'openssl/crypto/threads_none.c',
'openssl/crypto/threads_pthread.c',
'openssl/crypto/threads_win.c',
'openssl/crypto/ts/ts_asn1.c',
'openssl/crypto/ts/ts_conf.c',
'openssl/crypto/ts/ts_err.c',
'openssl/crypto/ts/ts_lib.c',
'openssl/crypto/ts/ts_req_print.c',
'openssl/crypto/ts/ts_req_utils.c',
'openssl/crypto/ts/ts_rsp_print.c',
'openssl/crypto/ts/ts_rsp_sign.c',
'openssl/crypto/ts/ts_rsp_utils.c',
'openssl/crypto/ts/ts_rsp_verify.c',
'openssl/crypto/ts/ts_verify_ctx.c',
'openssl/crypto/txt_db/txt_db.c',
'openssl/crypto/ui/ui_err.c',
'openssl/crypto/ui/ui_lib.c',
'openssl/crypto/ui/ui_null.c',
'openssl/crypto/ui/ui_openssl.c',
'openssl/crypto/ui/ui_util.c',
'openssl/crypto/uid.c',
'openssl/crypto/whrlpool/wp_block.c',
'openssl/crypto/whrlpool/wp_dgst.c',
'openssl/crypto/x509/by_dir.c',
'openssl/crypto/x509/by_file.c',
'openssl/crypto/x509/t_crl.c',
'openssl/crypto/x509/t_req.c',
'openssl/crypto/x509/t_x509.c',
'openssl/crypto/x509/x509_att.c',
'openssl/crypto/x509/x509_cmp.c',
'openssl/crypto/x509/x509_d2.c',
'openssl/crypto/x509/x509_def.c',
'openssl/crypto/x509/x509_err.c',
'openssl/crypto/x509/x509_ext.c',
'openssl/crypto/x509/x509_lu.c',
'openssl/crypto/x509/x509_meth.c',
'openssl/crypto/x509/x509_obj.c',
'openssl/crypto/x509/x509_r2x.c',
'openssl/crypto/x509/x509_req.c',
'openssl/crypto/x509/x509_set.c',
'openssl/crypto/x509/x509_trs.c',
'openssl/crypto/x509/x509_txt.c',
'openssl/crypto/x509/x509_v3.c',
'openssl/crypto/x509/x509_vfy.c',
'openssl/crypto/x509/x509_vpm.c',
'openssl/crypto/x509/x509cset.c',
'openssl/crypto/x509/x509name.c',
'openssl/crypto/x509/x509rset.c',
'openssl/crypto/x509/x509spki.c',
'openssl/crypto/x509/x509type.c',
'openssl/crypto/x509/x_all.c',
'openssl/crypto/x509/x_attrib.c',
'openssl/crypto/x509/x_crl.c',
'openssl/crypto/x509/x_exten.c',
'openssl/crypto/x509/x_name.c',
'openssl/crypto/x509/x_pubkey.c',
'openssl/crypto/x509/x_req.c',
'openssl/crypto/x509/x_x509.c',
'openssl/crypto/x509/x_x509a.c',
'openssl/crypto/x509v3/pcy_cache.c',
'openssl/crypto/x509v3/pcy_data.c',
'openssl/crypto/x509v3/pcy_lib.c',
'openssl/crypto/x509v3/pcy_map.c',
'openssl/crypto/x509v3/pcy_node.c',
'openssl/crypto/x509v3/pcy_tree.c',
'openssl/crypto/x509v3/v3_addr.c',
'openssl/crypto/x509v3/v3_admis.c',
'openssl/crypto/x509v3/v3_akey.c',
'openssl/crypto/x509v3/v3_akeya.c',
'openssl/crypto/x509v3/v3_alt.c',
'openssl/crypto/x509v3/v3_asid.c',
'openssl/crypto/x509v3/v3_bcons.c',
'openssl/crypto/x509v3/v3_bitst.c',
'openssl/crypto/x509v3/v3_conf.c',
'openssl/crypto/x509v3/v3_cpols.c',
'openssl/crypto/x509v3/v3_crld.c',
'openssl/crypto/x509v3/v3_enum.c',
'openssl/crypto/x509v3/v3_extku.c',
'openssl/crypto/x509v3/v3_genn.c',
'openssl/crypto/x509v3/v3_ia5.c',
'openssl/crypto/x509v3/v3_info.c',
'openssl/crypto/x509v3/v3_int.c',
'openssl/crypto/x509v3/v3_lib.c',
'openssl/crypto/x509v3/v3_ncons.c',
'openssl/crypto/x509v3/v3_pci.c',
'openssl/crypto/x509v3/v3_pcia.c',
'openssl/crypto/x509v3/v3_pcons.c',
'openssl/crypto/x509v3/v3_pku.c',
'openssl/crypto/x509v3/v3_pmaps.c',
'openssl/crypto/x509v3/v3_prn.c',
'openssl/crypto/x509v3/v3_purp.c',
'openssl/crypto/x509v3/v3_skey.c',
'openssl/crypto/x509v3/v3_sxnet.c',
'openssl/crypto/x509v3/v3_tlsf.c',
'openssl/crypto/x509v3/v3_utl.c',
'openssl/crypto/x509v3/v3err.c',
'openssl/engines/e_capi.c',
'openssl/engines/e_padlock.c',
],
'openssl_sources_solaris-x86-gcc': [
'./config/archs/solaris-x86-gcc/asm/crypto/aes/aesni-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/aes/vpaes-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/bf/bf-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/bn/bn-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/bn/co-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/bn/x86-gf2m.s',
'./config/archs/solaris-x86-gcc/asm/crypto/bn/x86-mont.s',
'./config/archs/solaris-x86-gcc/asm/crypto/camellia/cmll-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/chacha/chacha-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/des/crypt586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/des/des-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/ec/ecp_nistz256-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/md5/md5-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/modes/ghash-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/poly1305/poly1305-x86.s',
'./config/archs/solaris-x86-gcc/asm/crypto/rc4/rc4-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/ripemd/rmd-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/sha/sha1-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/sha/sha256-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/sha/sha512-586.s',
'./config/archs/solaris-x86-gcc/asm/crypto/whrlpool/wp-mmx.s',
'./config/archs/solaris-x86-gcc/asm/crypto/x86cpuid.s',
'./config/archs/solaris-x86-gcc/asm/engines/e_padlock-x86.s',
],
'openssl_defines_solaris-x86-gcc': [
'NDEBUG',
'FILIO_H',
'L_ENDIAN',
'OPENSSL_PIC',
'OPENSSL_CPUID_OBJ',
'OPENSSL_BN_ASM_PART_WORDS',
'OPENSSL_IA32_SSE2',
'OPENSSL_BN_ASM_MONT',
'OPENSSL_BN_ASM_GF2m',
'SHA1_ASM',
'SHA256_ASM',
'SHA512_ASM',
'RC4_ASM',
'MD5_ASM',
'RMD160_ASM',
'AESNI_ASM',
'VPAES_ASM',
'WHIRLPOOL_ASM',
'GHASH_ASM',
'ECP_NISTZ256_ASM',
'POLY1305_ASM',
],
'openssl_cflags_solaris-x86-gcc': [
'-Wa,--noexecstack',
'-Wall -O3 -fomit-frame-pointer',
'-pthread',
'-Wall -O3 -fomit-frame-pointer',
],
'openssl_ex_libs_solaris-x86-gcc': [
'-lsocket -lnsl -ldl -pthread',
],
},
'include_dirs': [
'.',
'./include',
'./crypto',
'./crypto/include/internal',
],
'defines': ['<@(openssl_defines_solaris-x86-gcc)'],
'cflags' : ['<@(openssl_cflags_solaris-x86-gcc)'],
'libraries': ['<@(openssl_ex_libs_solaris-x86-gcc)'],
'sources': ['<@(openssl_sources)', '<@(openssl_sources_solaris-x86-gcc)'],
}
| [
"[email protected]"
] | |
34c27860cdf81fee0a1067a3153e527e6bec3bf2 | 126970b5a7aef7def577922f9ed4bc0889ec5804 | /products/views.py | 6d46af5e0d4df6315060a0e34a7600163f3b5171 | [] | no_license | HeshamSayed/ElectroBekia | 6544955d1449ce03e6fd432bfdff05422a9f92ba | 42fab2ed3dc43f6f3e3e75cc17a7a26cb747d385 | refs/heads/master | 2022-12-13T21:47:10.673963 | 2019-06-18T16:03:04 | 2019-06-18T16:03:04 | 186,132,437 | 0 | 3 | null | 2022-12-08T05:08:00 | 2019-05-11T12:50:58 | CSS | UTF-8 | Python | false | false | 623 | py | from django.shortcuts import render, get_object_or_404
from .models import *
from cart.forms import CartAddProductForm
def product_list(request):
categories = Category.objects.all()
products = Product.objects.all()
context = {
'categories': categories,
'products': products,
}
return render(request, 'products/list.html', context)
def product_detail(request, pk):
product = get_object_or_404(Product, pk=pk)
cart_product_form = CartAddProductForm()
context = {
'product': product,
'cart_product_form': cart_product_form,
}
return render(request, 'products/detail.html', context)
| [
"[email protected]"
] | |
360817c27d99ca21241781e95372efb461f4a4b0 | dba16143d8fa6aa73ca1d4df7bcfaca42824412c | /src/year2021/day05b.py | 7312f094f2e1e4a1e1a73ecd10c0b4f4b98def4c | [
"Unlicense"
] | permissive | lancelote/advent_of_code | 84559bf633189db3c3e4008b7777b1112f7ecd30 | 4b8ac6a97859b1320f77ba0ee91168b58db28cdb | refs/heads/master | 2023-02-03T14:13:07.674369 | 2023-01-24T20:06:43 | 2023-01-24T20:06:43 | 47,609,324 | 11 | 0 | null | 2019-10-07T07:06:42 | 2015-12-08T08:35:51 | Python | UTF-8 | Python | false | false | 305 | py | """2021 - Day 5 Part 2: Hydrothermal Venture."""
from src.year2021.day05a import Floor
from src.year2021.day05a import Segment
def solve(task: str) -> int:
segments = [Segment.from_line(line) for line in task.splitlines()]
floor = Floor()
floor.draw(segments)
return floor.num_overlap
| [
"[email protected]"
] | |
0c4ced2b9b0cda7893c263ca688f35f779c8fbfb | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_257/ch16_2020_09_23_12_39_52_743421.py | 18424641beeb01c2388537b04c4757f22a441245 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | conta= float(input("Valor da conta com 10%: R$ "))
conta += conta*10/100
print("Valor da conta com 10%: R$ {0:.2f}".format(conta)) | [
"[email protected]"
] | |
1c44748dba44714166cfa7f35d87338249edc098 | 088e000eb5f16e6d0d56c19833b37de4e67d1097 | /inference-engine/ie_bridges/python/sample/benchmark_app/benchmark/utils/inputs_filling.py | 00a294524716055d8a481d0892e5cc307a9458b6 | [
"Apache-2.0"
] | permissive | projectceladon/dldt | 614ba719a428cbb46d64ab8d1e845ac25e85a53e | ba6e22b1b5ee4cbefcc30e8d9493cddb0bb3dfdf | refs/heads/2019 | 2022-11-24T10:22:34.693033 | 2019-08-09T16:02:42 | 2019-08-09T16:02:42 | 204,383,002 | 1 | 1 | Apache-2.0 | 2022-11-22T04:06:09 | 2019-08-26T02:48:52 | C++ | UTF-8 | Python | false | false | 8,029 | py | """
Copyright (C) 2018-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import os
import cv2
import numpy as np
import sys
from glob import glob
from random import choice
from .logging import logger
IMAGE_EXTENSIONS = ['JPEG', 'JPG', 'PNG', 'BMP']
BINARY_EXTENSIONS = ['BIN']
def isImage(blob):
if (blob.layout != "NCHW"):
return False
channels = blob.shape[1]
return (channels == 3)
def isImageInfo(blob):
if (blob.layout != "NC"):
return False
channels = blob.shape[1]
return (channels >= 2)
def getInputs(path_to_input, batch_size, input_info, requests):
input_image_sizes = {}
for key in input_info.keys():
if (isImage(input_info[key])):
input_image_sizes[key] = (input_info[key].shape[2], input_info[key].shape[3])
logger.info("Network input '{}' precision {}, dimensions ({}): {}".format(key,
input_info[key].precision,
input_info[key].layout,
" ".join(str(x) for x in input_info[key].shape)))
images_count = len(input_image_sizes.keys())
binaries_count = len(input_info) - images_count
image_files = list()
binary_files = list()
if (path_to_input):
image_files = get_files_by_extensions(path_to_input, IMAGE_EXTENSIONS)
image_files.sort()
binary_files = get_files_by_extensions(path_to_input, BINARY_EXTENSIONS)
binary_files.sort()
if (len(image_files) == 0) and (len(binary_files) == 0):
logger.warn("No input files were given: all inputs will be filled with random values!")
else:
binary_to_be_used = binaries_count*batch_size*len(requests)
if binary_to_be_used > 0 and len(binary_files) == 0:
logger.warn("No supported binary inputs found! Please check your file extensions: {}".format(",".join(BINARY_EXTENSIONS)))
elif binary_to_be_used > len(binary_files):
logger.warn("Some binary input files will be duplicated: {} files are required, but only {} were provided".format(binary_to_be_used, len(binary_files)))
elif binary_to_be_used < len(binary_files):
logger.warn("Some binary input files will be ignored: only {} files are required from {}".format(binary_to_be_used, len(binary_files)))
images_to_be_used = images_count*batch_size*len(requests)
if images_to_be_used > 0 and len(image_files) == 0:
logger.warn("No supported image inputs found! Please check your file extensions: {}".format(",".join(IMAGE_EXTENSIONS)))
elif images_to_be_used > len(image_files):
logger.warn("Some image input files will be duplicated: {} files are required, but only {} were provided".format(images_to_be_used, len(image_files)))
elif images_to_be_used < len(image_files):
logger.warn("Some image input files will be ignored: only {} files are required from {}".format(images_to_be_used, len(image_files)))
requests_input_data = []
for request_id in range(0, len(requests)):
logger.info("Infer Request {} filling".format(request_id))
input_data = {}
keys = list(input_info.keys())
for key in keys:
if isImage(input_info[key]):
# input is image
if (len(image_files) > 0):
input_data[key] = fill_blob_with_image(image_files, request_id, batch_size, keys.index(key), len(keys), input_info[key].shape)
continue
# input is binary
if (len(binary_files) > 0):
input_data[key] = fill_blob_with_binary(binary_files, input_info[key].shape)
continue
# most likely input is image info
if isImageInfo(input_info[key]) and len(input_image_sizes) == 1:
image_size = input_image_sizes[list(input_image_sizes.keys()).pop()]
logger.info("Fill input '" + key + "' with image size " + str(image_size[0]) + "x" +
str(image_size[1]))
input_data[key] = fill_blob_with_image_info(image_size, input_info[key].shape)
continue
# fill with random data
logger.info("Fill input '{}' with random values ({} is expected)".format(key, "image" if isImage(input_info[key]) else "some binary data"))
input_data[key] = fill_blob_with_random(input_info[key].precision, input_info[key].shape)
requests_input_data.append(input_data)
return requests_input_data
def get_files_by_extensions(path_to_input, extensions):
input_files = list()
if os.path.isfile(path_to_input):
input_files.append(path_to_input)
else:
path = os.path.join(path_to_input, '*')
files = glob(path, recursive=True)
for file in files:
file_extension = file.rsplit('.').pop().upper()
if file_extension in extensions:
input_files.append(file)
return input_files
def fill_blob_with_image(image_paths, request_id, batch_size, input_id, input_size, shape):
images = np.ndarray(shape)
image_index = request_id*batch_size*input_size + input_id
for b in range(batch_size):
image_index %= len(image_paths)
image_filename = image_paths[image_index]
image = cv2.imread(image_filename)
new_im_size = tuple(shape[2:])
if image.shape[:-1] != new_im_size:
logger.warn("Image {} is resized from ({}) to ({})".format(image_filename, image.shape[:-1], new_im_size))
image = cv2.resize(image, new_im_size)
image = image.transpose((2, 1, 0))
images[b] = image
image_index += input_size
return images
def fill_blob_with_binary(binary_paths, request_id, batch_size, input_id, input_size, shape):
binaries = np.ndarray(shape)
binary_index = request_id*batch_size*input_size + input_id
for b in range(batch_size):
binary_index %= len(image_paths)
binary_filename = binary_paths[binary_index]
binary_file_size = os.path.getsize(binary_file)
input_size = np.prod(shape)/batch_size
if (input_size != binary_file_size):
raise Exception("File " + binary_filename + " contains " << str(binary_file_size) + " bytes " +
"but network expects " + str(input_size))
with open(binary_file, 'r') as f:
binary_data = f.read()
binaries[b] = binary_data
binary_index += input_size
return binaries
def fill_blob_with_image_info(image_size, shape):
im_info = np.ndarray(shape)
for b in range(shape[0]):
for i in range(shape[1]):
im_info[b][i] = image_size[i] if i in [0, 1] else 1
return im_info
def fill_blob_with_random(precision, shape):
if precision == "FP32":
return np.random.rand(*shape).astype(np.float32)
elif precision == "FP16":
return np.random.rand(*shape).astype(np.float16)
elif precision == "I32":
return np.random.rand(*shape).astype(np.int32)
elif precision == "U8":
return np.random.rand(*shape).astype(np.uint8)
elif precision == "I8":
return np.random.rand(*shape).astype(np.int8)
elif precision == "U16":
return np.random.rand(*shape).astype(np.uint16)
elif precision == "I16":
return np.random.rand(*shape).astype(np.int16)
else:
raise Exception("Input precision is not supported: " + precision)
| [
"[email protected]"
] | |
b11132f9a28ade952b2c9bb6c536a6194a591483 | c4e729edfb9b056b9aa111a31eebefe41f39ac46 | /cloudweb/db/message/message_object.py | 5f4f03c9a16d5b91d0beb86ef7b8ac7b1a9f8a7d | [] | no_license | sun3shines/web | 870a558538278ecb4a39e5d9cab4ba2ebb626ca3 | 9e6f83e6e793f86ecdf7202daae3903cc052f266 | refs/heads/master | 2021-01-18T23:49:48.722245 | 2016-07-02T10:25:24 | 2016-07-02T10:25:24 | 54,888,971 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,712 | py | # -*- coding: utf-8 -*-
from urllib import unquote
from cloudweb.db.db_record import record_put
# msgPut -> db_message_object_put
# msgGet -> db_message_object_get
# msgHead -> db_message_object_head
# msgMeta -> db_message_object_meta
# msgDelete -> db_message_object_delete
# msgDeleteRecycle -> db_message_object_deleterecycle
# msgMove -> db_message_object_move
# msgCopy -> db_message_object_copy
# msgMoveRecycle -> db_message_object_moverecycle
# msgPost -> db_message_object_post
def db_message_object_put(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s PUT OBJECT %s' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_get(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s DOWNLOAD OBJECT %s' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_head(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s GET OBJECT %s INFO' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_meta(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s GET OBJECT %s METADATA' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_delete(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s DELETE OBJECT %s' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_deleterecycle(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s MOVE OBJECT %s TO RECYCLE' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_move(db,objPath,dstName):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s MOVE OBJECT %s TO %s' % (urName,objName,dstName)
return record_put(db, msg, urName, objPath)
def db_message_object_copy(db,objPath,dstName):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s COPY OBJECT %s TO %s' % (urName,objName,dstName)
return record_put(db, msg, urName, objPath)
def db_message_object_moverecycle(db,objPath):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s MOVE OBJECT %s FROM RECYCLE' % (urName,objName)
return record_put(db, msg, urName, objPath)
def db_message_object_post(db,objPath,header):
# objPath = unquote(path)
# objPath = '/'.join(objPath.split('/')[3:])
urName = objPath.split('/')[0]
objName = objPath.split('/')[-1]
msg = ' %s UPDATE OBJECT METADATA %s' % (urName,objName,header)
return record_put(db, msg, urName, objPath)
| [
"[email protected]"
] | |
f78c3b2044a52976c4a838d5b89dbdf2832b3022 | 3b8a4101995b1ba889dc685901a62db72ab13184 | /examples/tweets/config.py | 9956e34e66ccae84cc8211d70d5b54357f47a9c3 | [
"BSD-3-Clause"
] | permissive | tchen0123/pulsar | 586aeb69419c0eac034431405979edd91b4347b2 | 53a311e51974a27f6ef081c38193b41dede1412f | refs/heads/master | 2021-01-18T19:12:04.143947 | 2015-07-21T06:29:04 | 2015-07-21T06:29:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 243 | py | twitter_api_key = 'twitter API key of your registered twitter application'
twitter_api_secret = 'consumer secret'
twitter_access_token = 'Access token'
twitter_access_secret = 'Access token secret'
twitter_stream_filter = {'track': 'python'}
| [
"[email protected]"
] | |
b03ac5488518a3f330bc0113472150497457e28f | 44d2f40d4229f1cb26cec013cb18751d8006a219 | /snippets_backend/settings/development.py | ffcb584fad67c3d5c1faf1d5e6527be5cf605b3f | [] | no_license | prettyirrelevant/snippets-backend | 4bcb1d4c2cfa9bcd099856f026320c1250f08dc3 | 0006c194870904620599ca52b8b1510b11c1e2e9 | refs/heads/master | 2023-03-21T19:36:22.230824 | 2021-03-22T09:57:14 | 2021-03-22T09:57:14 | 331,959,739 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,559 | py | """
Django settings for snippets_backend project.
Generated by 'django-admin startproject' using Django 3.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '@w*wfy5)lp19)4-zf&0y^je9wc8=)ljqjcwoj82xsujxfi&o-1'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
AUTH_USER_MODEL = 'api.User'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'rest_framework',
'knox',
'api'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'snippets_backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'snippets_backend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': ['knox.auth.TokenAuthentication'],
'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.AllowAny']
}
REST_KNOX = {
'USER_SERIALIZER': 'api.serializers.UserSerializer',
'EXPIRY_DATETIME_FORMAT': None
}
CORS_ALLOWED_ORIGINS = ["http://localhost:3000"]
| [
"[email protected]"
] | |
07ececcce929817e0e7dd845a6f6bbe686954a00 | 701ff727e23005eebc4410b30752f32e64ead30e | /config/settings.py | 78b947ed91b70730b28c4c615c31a10434da97e3 | [] | no_license | sinjorjob/django-chat | 79ae5a94464301b2913be18ef5c81d2c870817b2 | d35d7fdb3888cdefa1a4daead05f10454a20ef4f | refs/heads/master | 2023-06-25T09:18:51.551222 | 2021-07-30T19:13:02 | 2021-07-30T19:13:02 | 391,166,548 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,930 | py | """
Django settings for config project.
Generated by 'django-admin startproject' using Django 3.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^dal#)b$5x8j2)2(osq^d^i-tt*=7pux8$i$(-pjd%bi+ia9@n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat.apps.ChatConfig', #追加
'accounts.apps.AccountsConfig', #追加
'widget_tweaks', #追加
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'config.urls'
import os
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'config.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'ja'
TIME_ZONE = 'Asia/Tokyo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# カスタムユーザモデル
AUTH_USER_MODEL = 'accounts.CustomUser'
#ログイン後のリダイレクトURL設定
LOGIN_REDIRECT_URL = '/chat_room/'
#ログアウト後のリダイレクト先
LOGOUT_REDIRECT_URL = '/'
# ファイルアップロード用
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')
MEDIA_URL = '/media/'
| [
"[email protected]"
] | |
2252b90ba8deb223db2d75fe3370861ede934d35 | bcc5ebe8c5d0b78c43087f0c292e329cb8d78e6a | /venv/bin/pasteurize | fbc9fe65369d9648f41dfaf9c689c7a6bbe36855 | [
"MIT"
] | permissive | RaymondDashWu/generative-structures-dapp | 1ce0fc0028c97de49c2843d4b3e30c84e92fb769 | 06819e9333c663a8be3eca444b55dd244d31f87b | refs/heads/master | 2022-12-26T22:59:14.699771 | 2019-08-09T20:13:59 | 2019-08-09T20:13:59 | 193,174,106 | 0 | 0 | MIT | 2022-12-03T14:43:11 | 2019-06-22T00:27:31 | Python | UTF-8 | Python | false | false | 320 | #!/Users/raymondmbp/makeschool/BEW-2.4-Decentralized-Apps-Distributed-Protocols/generative-structures/venv/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from libpasteurize.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"[email protected]"
] | ||
515f571aec0c41aa280a7ad4f155a691de756151 | e7efae2b83216d9621bd93390959d652de779c3d | /datadog_checks_dev/datadog_checks/dev/tooling/commands/agent/__init__.py | 8153698063f3e5affe147fad62925b3a12cfa3e0 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSD-3-Clause-Modification",
"Unlicense",
"Apache-2.0",
"LGPL-3.0-only",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"CC0-1.0"
] | permissive | DataDog/integrations-core | ee1886cc7655972b2791e6ab8a1c62ab35afdb47 | 406072e4294edff5b46b513f0cdf7c2c00fac9d2 | refs/heads/master | 2023-08-31T04:08:06.243593 | 2023-08-30T18:22:10 | 2023-08-30T18:22:10 | 47,203,045 | 852 | 1,548 | BSD-3-Clause | 2023-09-14T16:39:54 | 2015-12-01T16:41:45 | Python | UTF-8 | Python | false | false | 617 | py | # (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import click
from ..console import CONTEXT_SETTINGS
from .changelog import changelog
from .integrations import integrations
from .integrations_changelog import integrations_changelog
from .requirements import requirements
ALL_COMMANDS = (changelog, requirements, integrations, integrations_changelog)
@click.group(context_settings=CONTEXT_SETTINGS, short_help='A collection of tasks related to the Datadog Agent')
def agent():
pass
for command in ALL_COMMANDS:
agent.add_command(command)
| [
"[email protected]"
] | |
70926b02978529fa9edc66e2ea1a2862ddad1222 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_074/ch153_2020_04_13_20_39_02_324902.py | 7c41c4092f5c5dbd3653ad6e6e0f0b55a83b2984 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 391 | py | def agrupa_por_idade(dicio):
dicio={[nome]:idade}
key=nome
dic={}
if idade<=11:
dic.update={criança:[nome]}
return dic
if idade>=12 and idade>=17:
dic.update={adolescente:[nome]}
return dic
if idade>=18 and idade<=59:
dic.update={adulto:[nome]}
return dic
else:
dic.update={idoso:[nome]}
return dic | [
"[email protected]"
] | |
83fec668e56fcdff66e94ad5af3d22793aba1ac8 | 2e67bdd45c0427490880ca02f913a923a0890cdf | /foodcartapp/migrations/0043_order_products.py | 759a18dabb4d27be55133c80f21cd2960ebab509 | [] | no_license | KozhevnikovM/devman-star-burger | 5ed72c2a8a99bee12770bd2d28aa35c92be0cff8 | 54836d0216ea1117ea12ddfff11afbef15e7a3b5 | refs/heads/master | 2023-04-12T23:23:28.862134 | 2021-04-19T13:17:15 | 2021-04-19T13:17:15 | 355,147,980 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 443 | py | # Generated by Django 3.0.7 on 2021-03-23 12:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('foodcartapp', '0042_auto_20210317_1251'),
]
operations = [
migrations.AddField(
model_name='order',
name='products',
field=models.ManyToManyField(through='foodcartapp.OrderPosition', to='foodcartapp.Product'),
),
]
| [
"[email protected]"
] | |
849bc3bb90ec4d300eed4c9ce126e2b3ed2aeef5 | b483c598fa375e9af02348960f210b9f482bd655 | /pythonbrasil/exercicios/listas/LT resp 06.py | 4a956fe6704cf8f89b2b9ac2bdcf1bef84176545 | [
"MIT"
] | permissive | brunofonsousa/python | 6f766d08bf193180ea9a4903cb93ffd167db588d | 8f2f26c77015c0baaa76174e004406b4115272c7 | refs/heads/master | 2022-09-30T14:58:01.080749 | 2020-06-08T09:55:35 | 2020-06-08T09:55:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 540 | py | '''
Faça um Programa que peça as quatro notas de 10 alunos, calcule e
armazene num vetor a média de cada aluno, imprima o número de alunos
com média maior ou igual a 7.0.
'''
alunos = 2
nota = 0
soma = 0
for i in range(1,3):
notas = []
for j in range(1,3):
nota += float(input("Digite a %iª nota do aluno %i: " %(i, j)))
nota /= 2
notas.append(nota)
for media in notas:
if media > 7:
soma += 1
print("O número de alunos com média maior que 7.00 foi de %i." %soma)
| [
"[email protected]"
] | |
683033b34e5ba82571bedabf75dda4cfedc1e88c | bb62f4738e32b82904b61d4be9d21b41d05ed694 | /motion_planners/rrt_connect.py | bb1702b156f42c9066f8eda37cc052634eb5eeba | [
"MIT"
] | permissive | yhome22/motion-planners | 34049b1f65cb8f45d656ce61d94e4a605d861615 | 891423418a9c6ac5d6fbe2bbc9c51087ae7d9b03 | refs/heads/master | 2023-06-11T10:38:10.807421 | 2021-06-15T23:54:51 | 2021-06-15T23:54:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,461 | py | import time
from .primitives import extend_towards
from .rrt import TreeNode, configs
from .utils import irange, RRT_ITERATIONS, INF, elapsed_time
def wrap_collision_fn(collision_fn):
# TODO: joint limits
# import inspect
# print(inspect.getargspec(collision_fn))
# print(dir(collision_fn))
def fn(q1, q2):
try:
return collision_fn(q1, q2)
except TypeError:
return collision_fn(q2)
return fn
def rrt_connect(start, goal, distance_fn, sample_fn, extend_fn, collision_fn,
max_iterations=RRT_ITERATIONS, max_time=INF, **kwargs):
"""
:param start: Start configuration - conf
:param goal: End configuration - conf
:param distance_fn: Distance function - distance_fn(q1, q2)->float
:param sample_fn: Sample function - sample_fn()->conf
:param extend_fn: Extension function - extend_fn(q1, q2)->[q', ..., q"]
:param collision_fn: Collision function - collision_fn(q)->bool
:param max_iterations: Maximum number of iterations - int
:param max_time: Maximum runtime - float
:param kwargs: Keyword arguments
:return: Path [q', ..., q"] or None if unable to find a solution
"""
# TODO: goal sampling function connected to a None node
start_time = time.time()
if collision_fn(start) or collision_fn(goal):
return None
# TODO: support continuous collision_fn with two arguments
#collision_fn = wrap_collision_fn(collision_fn)
nodes1, nodes2 = [TreeNode(start)], [TreeNode(goal)] # TODO: allow a tree to be prespecified (possibly as start)
for iteration in irange(max_iterations):
if elapsed_time(start_time) >= max_time:
break
swap = len(nodes1) > len(nodes2)
tree1, tree2 = nodes1, nodes2
if swap:
tree1, tree2 = nodes2, nodes1
target = sample_fn()
last1, _ = extend_towards(tree1, target, distance_fn, extend_fn, collision_fn,
swap, **kwargs)
last2, success = extend_towards(tree2, last1.config, distance_fn, extend_fn, collision_fn,
not swap, **kwargs)
if success:
path1, path2 = last1.retrace(), last2.retrace()
if swap:
path1, path2 = path2, path1
#print('{} max_iterations, {} nodes'.format(iteration, len(nodes1) + len(nodes2)))
path = configs(path1[:-1] + path2[::-1])
# TODO: return the trees
return path
return None
#################################################################
def birrt(start, goal, distance_fn, sample_fn, extend_fn, collision_fn, **kwargs):
"""
:param start: Start configuration - conf
:param goal: End configuration - conf
:param distance_fn: Distance function - distance_fn(q1, q2)->float
:param sample_fn: Sample function - sample_fn()->conf
:param extend_fn: Extension function - extend_fn(q1, q2)->[q', ..., q"]
:param collision_fn: Collision function - collision_fn(q)->bool
:param kwargs: Keyword arguments
:return: Path [q', ..., q"] or None if unable to find a solution
"""
# TODO: deprecate
from .meta import random_restarts
solutions = random_restarts(rrt_connect, start, goal, distance_fn, sample_fn, extend_fn, collision_fn,
max_solutions=1, **kwargs)
if not solutions:
return None
return solutions[0]
| [
"[email protected]"
] | |
938d74f683b6899da1a3a4e45a9ca95feeccf13d | 5b777b268b804bc984f87d714ef25677ab10fab1 | /causallib/estimation/marginal_outcome.py | 6c83f15371c3f78daa5f11e480dbc6c2d0148bae | [
"Apache-2.0"
] | permissive | vishalbelsare/causallib | 71c06cafbf9d3f2163c4921d64cab8d36413ca67 | 9f0ddb4696d580cf0a529a6c6ce98b40b34e3796 | refs/heads/master | 2023-07-10T09:57:57.293064 | 2022-12-19T15:19:28 | 2022-12-19T15:19:28 | 230,206,247 | 0 | 0 | Apache-2.0 | 2022-12-22T00:45:47 | 2019-12-26T06:14:10 | Python | UTF-8 | Python | false | false | 3,669 | py | """
(C) Copyright 2019 IBM Corp.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Created on Apr 25, 2018
"""
import pandas as pd
from .base_weight import WeightEstimator
from .base_estimator import PopulationOutcomeEstimator
class MarginalOutcomeEstimator(WeightEstimator, PopulationOutcomeEstimator):
"""
A marginal outcome predictor.
Assumes the sample is marginally exchangeable, and therefore does not correct (adjust, control) for covariates.
Predicts the outcome/effect as if the sample came from a randomized control trial: $\\Pr[Y|A]$.
"""
def compute_weight_matrix(self, X, a, use_stabilized=None, **kwargs):
# Another way to view this is that Uncorrected is basically an IPW-like with all individuals equally weighted.
treatment_values = a.unique()
treatment_values = treatment_values.sort()
weights = pd.DataFrame(data=1, index=a.index, columns=treatment_values)
return weights
def compute_weights(self, X, a, treatment_values=None, use_stabilized=None, **kwargs):
# Another way to view this is that Uncorrected is basically an IPW-like with all individuals equally weighted.
weights = pd.Series(data=1, index=a.index)
return weights
def fit(self, X=None, a=None, y=None):
"""
Dummy implementation to match the API.
MarginalOutcomeEstimator acts as a WeightEstimator that weights each sample as 1
Args:
X (pd.DataFrame): Covariate matrix of size (num_subjects, num_features).
a (pd.Series): Treatment assignment of size (num_subjects,).
y (pd.Series): Observed outcome of size (num_subjects,).
Returns:
MarginalOutcomeEstimator: a fitted model.
"""
return self
def estimate_population_outcome(self, X, a, y, w=None, treatment_values=None):
"""
Calculates potential population outcome for each treatment value.
Args:
X (pd.DataFrame): Covariate matrix of size (num_subjects, num_features).
a (pd.Series): Treatment assignment of size (num_subjects,).
y (pd.Series): Observed outcome of size (num_subjects,).
w (pd.Series | None): Individual (sample) weights calculated. Used to achieved unbiased average outcome.
If not provided, will be calculated on the data.
treatment_values (Any): Desired treatment value/s to stratify upon before aggregating individual into
population outcome.
If not supplied, calculates for all available treatment values.
Returns:
pd.Series[Any, float]: Series which index are treatment values, and the values are numbers - the
aggregated outcome for the strata of people whose assigned treatment is the key.
"""
if w is None:
w = self.compute_weights(X, a)
res = self._compute_stratified_weighted_aggregate(y, sample_weight=w, stratify_by=a,
treatment_values=treatment_values)
return res
| [
"[email protected]"
] | |
9e2d106caf576c763e11e32eb14eb27cc379899f | 3c0fb20d77a8b4b63691fc8233cce44a50ecf36b | /src/core/geom/data/transform.py | 124b6149b51c0042e0b47a1a0325c7e1461de25c | [] | no_license | jorjuato/panda3dstudio | 8a9b35000b8850c0d2968f529a983b66ad01f2f8 | b6cf2a1d126273ca64ecec29f23eba7bf297f418 | refs/heads/master | 2020-12-06T19:16:42.105673 | 2016-04-26T18:14:44 | 2016-04-26T18:14:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,187 | py | from ...base import *
class GeomTransformBase(BaseObject):
def __init__(self):
self._verts_to_transf = {"vert": {}, "edge": {}, "poly": {}}
self._rows_to_transf = {"vert": None, "edge": None, "poly": None}
self._transf_start_data = {"bbox": None, "pos_array": None}
def _update_verts_to_transform(self, subobj_lvl):
selected_subobj_ids = self._selected_subobj_ids[subobj_lvl]
verts = self._subobjs["vert"]
self._verts_to_transf[subobj_lvl] = verts_to_transf = {}
self._rows_to_transf[
subobj_lvl] = rows_to_transf = SparseArray.allOff()
merged_verts = self._merged_verts
merged_verts_to_transf = set()
if subobj_lvl == "vert":
for vert_id in selected_subobj_ids:
merged_verts_to_transf.add(merged_verts[vert_id])
elif subobj_lvl == "edge":
edges = self._subobjs["edge"]
for edge_id in selected_subobj_ids:
edge = edges[edge_id]
for vert_id in edge:
merged_verts_to_transf.add(merged_verts[vert_id])
elif subobj_lvl == "poly":
polys = self._subobjs["poly"]
for poly_id in selected_subobj_ids:
poly = polys[poly_id]
for vert_ids in poly:
for vert_id in vert_ids:
merged_verts_to_transf.add(merged_verts[vert_id])
for merged_vert in merged_verts_to_transf:
rows = merged_vert.get_row_indices()
verts_to_transf[merged_vert] = rows
for row in rows:
rows_to_transf.set_bit(row)
def init_transform(self):
geom_node_top = self._geoms["top"]["shaded"].node()
start_data = self._transf_start_data
start_data["bbox"] = geom_node_top.get_bounds()
start_data["pos_array"] = geom_node_top.get_geom(
0).get_vertex_data().get_array(0)
def transform_selection(self, subobj_lvl, transf_type, value):
geom_node_top = self._geoms["top"]["shaded"].node()
vertex_data_top = geom_node_top.modify_geom(0).modify_vertex_data()
tmp_vertex_data = GeomVertexData(vertex_data_top)
if transf_type == "translate":
grid_origin = Mgr.get(("grid", "origin"))
vec = self._origin.get_relative_vector(grid_origin, value)
rows = self._rows_to_transf[subobj_lvl]
start_data = self._transf_start_data
tmp_vertex_data.set_array(0, start_data["pos_array"])
mat = Mat4.translate_mat(vec)
tmp_vertex_data.transform_vertices(mat, rows)
elif transf_type == "rotate":
grid_origin = Mgr.get(("grid", "origin"))
tc_pos = self._origin.get_relative_point(
self.world, Mgr.get("transf_center_pos"))
quat = self._origin.get_quat(
grid_origin) * value * grid_origin.get_quat(self._origin)
rows = self._rows_to_transf[subobj_lvl]
start_data = self._transf_start_data
tmp_vertex_data.set_array(0, start_data["pos_array"])
quat_mat = Mat4()
quat.extract_to_matrix(quat_mat)
offset_mat = Mat4.translate_mat(-tc_pos)
mat = offset_mat * quat_mat
offset_mat = Mat4.translate_mat(tc_pos)
mat *= offset_mat
tmp_vertex_data.transform_vertices(mat, rows)
elif transf_type == "scale":
grid_origin = Mgr.get(("grid", "origin"))
tc_pos = self._origin.get_relative_point(
self.world, Mgr.get("transf_center_pos"))
scale_mat = Mat4.scale_mat(value)
mat = self._origin.get_mat(
grid_origin) * scale_mat * grid_origin.get_mat(self._origin)
# remove translation component
mat.set_row(3, VBase3())
rows = self._rows_to_transf[subobj_lvl]
start_data = self._transf_start_data
tmp_vertex_data.set_array(0, start_data["pos_array"])
offset_mat = Mat4.translate_mat(-tc_pos)
mat = offset_mat * mat
offset_mat = Mat4.translate_mat(tc_pos)
mat *= offset_mat
tmp_vertex_data.transform_vertices(mat, rows)
array = tmp_vertex_data.get_array(0)
vertex_data_top.set_array(0, array)
for subobj_type in ("vert", "poly"):
vertex_data = self._vertex_data[subobj_type]
vertex_data.set_array(0, array)
array = GeomVertexArrayData(array)
handle = array.modify_handle()
handle.set_data(handle.get_data() * 2)
self._vertex_data["edge"].set_array(0, array)
def finalize_transform(self, cancelled=False):
start_data = self._transf_start_data
geom_node_top = self._geoms["top"]["shaded"].node()
vertex_data_top = geom_node_top.modify_geom(0).modify_vertex_data()
if cancelled:
bounds = start_data["bbox"]
pos_array = start_data["pos_array"]
vertex_data_top.set_array(0, pos_array)
for subobj_type in ("vert", "poly"):
self._vertex_data[subobj_type].set_array(0, pos_array)
pos_array = GeomVertexArrayData(pos_array)
handle = pos_array.modify_handle()
handle.set_data(handle.get_data() * 2)
self._vertex_data["edge"].set_array(0, pos_array)
else:
bounds = geom_node_top.get_bounds()
pos_reader = GeomVertexReader(vertex_data_top, "vertex")
subobj_lvl = Mgr.get_global("active_obj_level")
polys = self._subobjs["poly"]
poly_ids = set()
for merged_vert, indices in self._verts_to_transf[subobj_lvl].iteritems():
pos_reader.set_row(indices[0])
pos = Point3(pos_reader.get_data3f())
merged_vert.set_pos(pos)
poly_ids.update(merged_vert.get_polygon_ids())
vert_ids = []
for poly_id in poly_ids:
poly = polys[poly_id]
poly.update_center_pos()
poly.update_normal()
vert_ids.extend(poly.get_vertex_ids())
merged_verts = set(self._merged_verts[
vert_id] for vert_id in vert_ids)
self._update_vertex_normals(merged_verts)
self._origin.node().set_bounds(bounds)
self.get_toplevel_object().get_bbox().update(*self._origin.get_tight_bounds())
start_data.clear()
def _restore_subobj_transforms(self, old_time_id, new_time_id):
obj_id = self.get_toplevel_object().get_id()
prop_id = "subobj_transform"
prev_time_ids = Mgr.do("load_last_from_history",
obj_id, prop_id, old_time_id)
new_time_ids = Mgr.do("load_last_from_history",
obj_id, prop_id, new_time_id)
if prev_time_ids is None:
prev_time_ids = ()
if new_time_ids is None:
new_time_ids = ()
if not (prev_time_ids or new_time_ids):
return
if prev_time_ids and new_time_ids:
i = 0
for time_id in new_time_ids:
if time_id not in prev_time_ids:
break
i += 1
common_time_ids = prev_time_ids[:i]
prev_time_ids = prev_time_ids[i:]
new_time_ids = new_time_ids[i:]
verts = self._subobjs["vert"]
polys = self._subobjs["poly"]
data_id = "vert_pos_data"
time_ids_to_restore = {}
prev_prop_times = {}
positions = {}
# to undo transformations, determine the time IDs of the transforms that
# need to be restored by checking the data that was stored when transforms
# occurred, at times leading up to the time that is being replaced (the old
# time)
for time_id in prev_time_ids[::-1]:
# time_id is a Time ID to update time_ids_to_restore with
subobj_data = Mgr.do("load_from_history", obj_id, data_id, time_id)
# subobj_data.get("prev", {}) yields previous transform times
time_ids_to_restore.update(subobj_data.get("prev", {}))
data_for_loading = {}
# time_ids_to_restore.keys() are the IDs of vertices that need a
# transform update
for vert_id, time_id in time_ids_to_restore.iteritems():
if vert_id in verts:
prev_prop_times[vert_id] = time_id
# since multiple vertex positions might have to be loaded from the same
# datafile, make sure each datafile is loaded only once
data_for_loading.setdefault(time_id, []).append(vert_id)
for time_id, vert_ids in data_for_loading.iteritems():
pos_data = Mgr.do("load_from_history", obj_id,
data_id, time_id)["pos"]
for vert_id in vert_ids:
if vert_id in pos_data:
positions[vert_id] = pos_data[vert_id]
# to redo transformations, retrieve the transforms that need to be restored
# from the data that was stored when transforms occurred, at times leading
# up to the time that is being restored (the new time)
for time_id in new_time_ids:
subobj_data = Mgr.do("load_from_history", obj_id, data_id, time_id)
positions.update(subobj_data.get("pos", {}))
for vert_id in subobj_data.get("prev", {}):
if vert_id in verts:
prev_prop_times[vert_id] = time_id
# restore the verts' previous transform time IDs
for vert_id, time_id in prev_prop_times.iteritems():
verts[vert_id].set_previous_property_time("transform", time_id)
polys_to_update = set()
vertex_data_top = self._geoms["top"][
"shaded"].node().modify_geom(0).modify_vertex_data()
pos_writer = GeomVertexWriter(vertex_data_top, "vertex")
for vert_id, pos in positions.iteritems():
if vert_id in verts:
vert = verts[vert_id]
poly = polys[vert.get_polygon_id()]
polys_to_update.add(poly)
vert.set_pos(pos)
row = vert.get_row_index()
pos_writer.set_row(row)
pos_writer.set_data3f(pos)
pos_array = vertex_data_top.get_array(0)
self._vertex_data["vert"].set_array(0, pos_array)
self._vertex_data["poly"].set_array(0, pos_array)
pos_array = GeomVertexArrayData(pos_array)
handle = pos_array.modify_handle()
handle.set_data(handle.get_data() * 2)
self._vertex_data["edge"].set_array(0, pos_array)
vert_ids = []
for poly in polys_to_update:
poly.update_center_pos()
poly.update_normal()
vert_ids.extend(poly.get_vertex_ids())
self._vert_normal_change.update(vert_ids)
self.get_toplevel_object().get_bbox().update(*self._origin.get_tight_bounds())
| [
"[email protected]"
] | |
d627be799d34ca09b15dbb8a8ba4999497693d40 | babc3e26d66a8084c9f84a0431338bafabae6ffd | /TaeJuneJoung/COD/lv2.OddOccurrencesInArray.py | d4d409749fec81fd81fda721db9af44dc3514b7c | [] | no_license | hoteldelluna/AlgoStudy | 5c23a1bfb07dbfbabc5bedd541d61784d58d3edc | 49ec098cecf2b775727d5648161f773e5488089b | refs/heads/dev | 2022-10-09T14:29:00.580834 | 2020-01-25T14:40:55 | 2020-01-25T14:40:55 | 201,632,052 | 5 | 0 | null | 2020-01-25T14:40:57 | 2019-08-10T13:11:41 | Python | UTF-8 | Python | false | false | 1,356 | py | """
무조건 하나만 홀수가 발생하니
마지막 index는 짝수일 수밖에 없다.(0부터 시작이니)
[조건]
1. A의 크기가 1인 경우
2. 홀수가 중간에 있는 경우
3. 홀수가 맨 마지막에 있는 경우
"""
def solution(A):
A.sort()
for i in range(0, len(A)-1, 2):
if A[i] != A[i+1]:
# 조건2 - 홀수가 1개밖에 없으니 답이 아니라면 짝수개이므로 앞에 것이 틀리다.
return A[i]
# 조건1, 3 - 조건2에서 끝나지 않았다면 맨 마지막 값이 답
return A[-1]
"""
[처음 풀이]
시도를 해본 문제
문제를 이해를 잘못한 부분도 한몫하였고,
효율성을 가장 크게 생각해야했던 문제
처음에는 set으로 감싸서 중복을 없앤 후,
해당 set내용으로 A.count를 하였으나 N^2이 나와 실패
Dict형태도 퍼포먼스에서는 좋지 않았다.
어떻게 짜면 효율적일지 다른 방도로 생각해보면 좋을듯한 문제.
현재 방법은 100점이나, 더 좋은 방도가 없을까?
"""
def solution(A):
A.sort()
if len(A) < 2:
return A[0]
cnt = 1
for i in range(1, len(A)):
if A[i-1] == A[i]:
cnt += 1
else:
if cnt%2:
return A[i-1]
else:
cnt = 1
return A[i] | [
"[email protected]"
] | |
92ea82d00e3baa47f0708f8943155310bef045d0 | eda9187adfd53c03f55207ad05d09d2d118baa4f | /python3_base/exception.py | 78bffed238c1ab8437126e7d6c33d8e406d2aae6 | [] | no_license | HuiZhaozh/python_tutorials | 168761c9d21ad127a604512d7c6c6b38b4faa3c7 | bde4245741081656875bcba2e4e4fcb6b711a3d9 | refs/heads/master | 2023-07-07T20:36:20.137647 | 2020-04-24T07:18:25 | 2020-04-24T07:18:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 457 | py | # -*- coding:utf-8 -*-
# /usr/bin/python
'''
Author:Yan Errol
Email:[email protected]
Wechat:qq260187357
Date:2019-04-29--21:59
Describe:异常诊断
'''
import time
def func():
try:
for i in range(5):
if i >3:
raise Exception("数字大于3了==")
except Exception as ret:
print (ret)
func()
import re
a = "张明 99分"
ret = re.sub(r"\d+","100",a)
print (ret)
a = [1,2,3]
b = [4,5,6]
print(a+b) | [
"[email protected]"
] | |
46a9ea2d394fede56dd4689d643f5f6492dbb5d8 | 9e05aa78126e76040e4afdd83c1eba95a9c787f5 | /generator/list2.py | 9ddb23a03b2684eb7ade8a8f5033cda8d41be041 | [
"MIT"
] | permissive | lreis2415/geovalidator | 8df4cb4671288b1242d0035cf1cde1944676e1df | dd64b0577aa458b39022afa503e890e966eb56d8 | refs/heads/master | 2022-12-10T18:32:41.293337 | 2021-03-10T01:04:20 | 2021-03-10T01:04:20 | 233,007,264 | 0 | 0 | MIT | 2022-12-08T08:04:28 | 2020-01-10T09:00:31 | Python | UTF-8 | Python | false | false | 1,131 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: houzhiwei
# time: 2020/1/4 16:10
from rdflib import BNode, Graph, RDF, Namespace, Literal
from rdflib.namespace import DCTERMS
g = Graph()
# namespaces
data = Namespace("http://www.egc.org/ont/data#")
saga = Namespace("http://www.egc.org/ont/process/saga#")
sh = Namespace("http://www.w3.org/ns/shacl#")
process = Namespace('http://www.egc.org/ont/gis/process#')
# prefixes
g.bind('data', data)
g.bind('sh', sh)
g.bind('saga', saga)
g.bind('process', process)
g.bind('dcterms', DCTERMS)
# SHACL shape graph
ds = saga.FlowAccumulationTopDownShape
g.add((ds, RDF.type, sh.NodeShape))
# [tool]_[parameter]
g.add((ds, sh.targetNode, saga.method_of_flow_accumulation_top_down))
p1 = BNode()
g.add((p1, sh.path, process.hasData))
g.add((p1, sh.minCount, Literal(0)))
g.add((p1, sh.maxCount, Literal(1)))
g.add((p1, sh.message, Literal('Must has at most one input value for option ‘Method’ of tool ‘Flow Accumulation (Top-Down)’', lang='en')))
g.add((ds, sh.property, p1))
# save as turtle file
g.serialize('../shapes/L2_FunctionalityLevelShape.ttl', format='turtle')
| [
"[email protected]"
] | |
7562eab065b565fc40986e5b85bde0cffe2bf27d | dfcb65de02953afaac24cc926ee32fcdede1ac21 | /src/pyrin/caching/local/handlers/__init__.py | 4f7d9594e8de35a0a70f0749192b9e0b9fa7c5d4 | [
"BSD-3-Clause"
] | permissive | mononobi/pyrin | 031d0c38da945b76b07ea100554ffc7f8081b05e | 9d4776498225de4f3d16a4600b5b19212abe8562 | refs/heads/master | 2023-08-31T03:56:44.700142 | 2023-08-20T22:20:06 | 2023-08-20T22:20:06 | 185,481,041 | 20 | 8 | null | null | null | null | UTF-8 | Python | false | false | 348 | py | # -*- coding: utf-8 -*-
"""
caching local handlers package.
"""
from pyrin.packaging.base import Package
class CachingLocalHandlersPackage(Package):
"""
caching local handlers package class.
"""
NAME = __name__
DEPENDS = ['pyrin.configuration',
'pyrin.globalization.datetime',
'pyrin.logging']
| [
"[email protected]"
] | |
8f8808d79b13456226c20d29fa09308ae24382df | cdf23a2b22b0d0643f9bf48fd8c7d0a8ef83945d | /qstrader/utils/console.py | beee1fa020b1139e7988a543dd9ea3de95049652 | [
"MIT"
] | permissive | PabloHebe/qstrader | 2e23d267e0e2cf6632011eaea486891c8eed4c17 | 81c9473fbb782220c5cced2e331fb7a7b0b0082d | refs/heads/master | 2022-08-27T10:28:27.411188 | 2019-12-16T14:17:40 | 2019-12-16T14:17:40 | 111,547,620 | 0 | 1 | MIT | 2020-01-05T12:54:16 | 2017-11-21T12:42:55 | Python | UTF-8 | Python | false | false | 258 | py | BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
def string_colour(text, colour=WHITE):
"""
Create string text in a particular colour to the terminal.
"""
seq = "\x1b[1;%dm" % (30 + colour) + text + "\x1b[0m"
return seq
| [
"[email protected]"
] | |
c7d99b683e6acbbe80cbc85721394ac0f1c7323f | f999bc5a6e0da4f0904ef2112d7b6191f180ca5b | /Advent of code/Day2_Part1.py | 44f5dafb0aa805206e823978d61b1740a82b147f | [] | no_license | ritesh-deshmukh/Algorithms-and-Data-Structures | 721485fbe91a5bdb4d7f99042077e3f813d177cf | 2d3a9842824305b1c64b727abd7c354d221b7cda | refs/heads/master | 2022-11-09T00:18:51.203415 | 2018-10-08T22:31:05 | 2018-10-08T22:31:05 | 132,504,988 | 0 | 1 | null | 2022-10-23T00:51:15 | 2018-05-07T19:07:33 | Python | UTF-8 | Python | false | false | 1,297 | py | # f = open("elves_input", "r")
# if f.mode == "r":
# input_task = f.read()
# input_task = f.readlines()
# for symbol in input_task:
# dimensions = symbol.split("x")
# print(dimensions)
with open('elves_input') as f:
dimensions_data = []
for line in f:
line = line.split('x') # to deal with blank
if line: # lines (ie skip them)
line = [int(i) for i in line]
dimensions_data.append(line)
# product = dimensions_data[0][0]
# print(dimensions_data[0])
total_area = 0
for dimensions in dimensions_data:
# sorted = sorted(dimensions)
# small_side_1 = sorted[0]
# small_side_2 = sorted[1]
area = ((2* dimensions[0] * dimensions[1])
+ (2* dimensions[1] * dimensions[2])
+ (2* dimensions[0] * dimensions[2]))
total_area += area
# print(sorted)
print(f"Area total: {total_area}")
total_small_side = 0
for dimensions1 in dimensions_data:
area1 = sorted(dimensions1)
# print(area1[0] * area1[1])
small_side = area1[0] * area1[1]
total_small_side += small_side
print(f"Small side total: {total_small_side}")
answer = total_area + total_small_side
print(f"Total Square feet: {answer}") | [
"[email protected]"
] | |
1e68f4426a5b3835594ad8792a036f353f9b5734 | 32eba552c1a8bccb3a329d3d152b6b042161be3c | /15_pj_pdf_merger.py | d316f0b6a7a805701c4abd4debff148e5b564734 | [] | no_license | ilmoi/ATBS | d3f501dbf4b1099b76c42bead3ec48de3a935a86 | 7f6993751e2ad18af36de04168d32b049d85a9c1 | refs/heads/master | 2022-07-11T21:56:23.284871 | 2020-05-15T05:26:06 | 2020-05-15T05:26:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,486 | py | """Finds all pdfs in cur dir > sorts alphabetically > merges together taking the first page only once."""
import PyPDF2
import os
import re
# prep the files list
files = os.listdir()
chosen = []
r = re.compile(r'.*\.pdf')
for file in files:
try:
mo = r.search(file)
# print(mo.group())
chosen.append(mo.group())
except:
pass
chosen.sort()
# manually removing the encrypted file (cba)
chosen.pop(1)
chosen.pop(1)
print(chosen)
# create writer
writer = PyPDF2.PdfFileWriter()
# iterate through files and pages and write them all down
for i, file in enumerate(chosen):
with open(file, 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
# for first doc - add the first page too
if i == 0:
pageObj = reader.getPage(0)
writer.addPage(pageObj)
# for all docs
for p in range(1, reader.numPages):
pageObj = reader.getPage(p)
writer.addPage(pageObj)
# finally write
# NOTE this one needs to sit inside of the with open statement or the pages will be blank!
with open('longfile.pdf', 'wb') as f:
writer.write(f)
# lets check number of pages matches
for file in chosen:
with open(file, 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
print(reader.numPages)
print('compare that to ----->')
with open('longfile.pdf', 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
print(reader.numPages)
# sounds correct!
| [
"[email protected]"
] | |
9dedd846ed49f891c3ea2109f26b3eed81fcdf88 | 320bf3ddd6233577d9f2f08f046eaef96f881e4e | /simplemooc/core/urls.py | eb0570de064c9f271570646c26f555b2bce99b28 | [
"MIT"
] | permissive | leorzz/simplemooc | 057ba3e220c20907017edfd8d0fc0422f9a6d99c | 8b1c5e939d534b1fd729596df4c59fc69708b896 | refs/heads/master | 2022-10-22T02:24:46.733062 | 2017-12-17T16:37:04 | 2017-12-17T16:37:04 | 112,488,280 | 0 | 1 | MIT | 2022-10-08T17:50:17 | 2017-11-29T14:52:23 | Python | UTF-8 | Python | false | false | 523 | py | from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
import simplemooc.core.views
urlpatterns = [
url(r'^$', simplemooc.core.views.home, name='home'),
url(r'^contact/$',simplemooc.core.views.contact, name='contact'),
url(r'^about/$',simplemooc.core.views.about, name='about'),
]
#urlpatterns = patterns('simplemooc.core.views',
# url(r'^$','home', name='home'),
# url(r'^contact/$','contact', name='contact'),
# url(r'^about/$','about', name='about'),
#)
| [
"[email protected]"
] | |
c2cfda99592ea8ed25c13139448162753c8e3e09 | 6ff7b3cd99aea670792aad35f49b4d762bd3952a | /migrations/versions/f8f3d3338933_initial.py | e1fddda3a2e45b3ac97c7d14513b75afa99b9458 | [] | no_license | melardev/FlaskApiCrud | 3af8c1f375f6aefe258334368fdc7bcab900a2a0 | 40e0ffe6f690a1698a3c3f6dd1a03398260cd073 | refs/heads/master | 2020-04-27T23:06:51.527985 | 2019-03-10T00:52:26 | 2019-03-10T00:52:26 | 174,762,571 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 953 | py | """'initial'
Revision ID: f8f3d3338933
Revises:
Create Date: 2019-03-08 21:02:46.699000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f8f3d3338933'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('todos',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('completed', sa.Boolean(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('todos')
# ### end Alembic commands ###
| [
"[email protected]"
] | |
dfbba26851a42e9ca1b1a62230992475e7e16da9 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/12/usersdata/76/5514/submittedfiles/impedimento.py | e64198eb3222c4320efd7c71f70c7c45cd091526 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 276 | py | # -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CÓDIGO AQUI
L = input('Digite o valor de L:')
R = input('Digite o valor de R:')
D = input('Digite o valor de D:')
if R>50 and L<R and R>D:
print('S')
if R>50 and L<R and R<D:
print('N') | [
"[email protected]"
] | |
aad8c4965b91dbc1a68802b5dc45aa593d98d20a | d65cb684d344ab072d0f9801afbd074768a059a2 | /Suanfa/天际线问题Suanfa1_3.py | e826e906c21a8c27b4b7e96acc49c55fb8d6548d | [] | no_license | QiuHongHao123/Algorithm-Practise | a918debd002182010b78e284df038c01d9921619 | e7a7b7537edbbb8fa35c2dddf2b122cf863e479d | refs/heads/master | 2023-03-14T09:16:28.407137 | 2021-03-01T11:57:54 | 2021-03-01T11:57:54 | 272,642,085 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,274 | py | def getSkyline(buildings):
if not buildings: return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = getSkyline(buildings[:mid])
right = getSkyline(buildings[mid:])
return merge(left, right)
def merge(left, right):
# 记录目前左右建筑物的高度
lheight = rheight = 0
# 位置
l = r = 0
res = []
while l < len(left) and r < len(right):
if left[l][0] < right[r][0]:
cp = [left[l][0], max(left[l][1], rheight)]
lheight = left[l][1]
l += 1
elif left[l][0] > right[r][0]:
cp = [right[r][0], max(right[r][1], lheight)]
rheight = right[r][1]
r += 1
else:
cp = [left[l][0], max(left[l][1], right[r][1])]
lheight = left[l][1]
rheight = right[r][1]
l += 1
r += 1
# 和前面高度比较,不一样才加入
if len(res) == 0 or res[-1][1] != cp[1]:
res.append(cp)
# 剩余部分添加进去
res.extend(left[l:] or right[r:])
return res
print(getSkyline([[1,5,11], [2,7,6], [3,9,13], [12,16,7], [14,25,3], [19,22,18], [23,29,13],[24,28,4]])) | [
"[email protected]"
] | |
869d7f8aec582f9c09dfa15e9791d99d7c9c617d | 170a4c0b1accb9468567f6a88254ff738f2a8166 | /EQ5D.py | 3fab62e39350976be780783eaeae004522dfd006 | [] | no_license | yazhisun/Labs_PreferenceScores | 2ecd9acdb21403f912200db1fa41f0f6e325ef18 | 3eb0ec0e55f1772b15a3108dd0a85dbcf75e1743 | refs/heads/master | 2021-05-09T22:56:44.996009 | 2018-01-18T16:03:31 | 2018-01-18T16:03:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 377 | py |
# EQ-5D regression coefficients
Constant = 0.081
N3 = 0.269
dictCoefficients = {'Mobility': [0, 0.069, 0.314],
'Self-Care': [0, 0.104, 0.214],
'Usual Activity': [0, 0.036, 0.094],
'Pain/Discomfort': [0, 0.123, 0.386],
'Anxiety/Depression': [0, 0.071, 0.236]};
| [
"[email protected]"
] | |
49681f30a6612dac501c48d0b1e070e630b6bf72 | fd9257a4cc04b89c2b8c92008770a82ccdfe85bd | /build/spdlog/catkin_generated/generate_cached_setup.py | 3db5318c1429f193fb60f8495755cfd61895d77f | [] | no_license | Zauberr/KAL | 40b135f02e9ae9c7bf55b064094aaff88c43628e | 225e538058b632c8c14cc638e12fcb124bd81e29 | refs/heads/master | 2020-08-16T18:26:19.863213 | 2019-10-16T13:38:46 | 2019-10-16T13:38:46 | 215,537,226 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,350 | py | # -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/mrtros/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.join('/opt/mrtros/share/catkin/cmake', '..', 'python'))
try:
from catkin.environment_cache import generate_environment_script
except ImportError:
# search for catkin package in all workspaces and prepend to path
for workspace in "/home/kal5-2/rammbo/devel;/opt/mrtros;/opt/mrtsoftware/local;/opt/mrtsoftware/release".split(';'):
python_path = os.path.join(workspace, 'lib/python2.7/dist-packages')
if os.path.isdir(os.path.join(python_path, 'catkin')):
sys.path.insert(0, python_path)
break
from catkin.environment_cache import generate_environment_script
code = generate_environment_script('/home/kal5-2/rammbo/devel/.private/spdlog/env.sh')
output_filename = '/home/kal5-2/rammbo/build/spdlog/catkin_generated/setup_cached.sh'
with open(output_filename, 'w') as f:
#print('Generate script for cached setup "%s"' % output_filename)
f.write('\n'.join(code))
mode = os.stat(output_filename).st_mode
os.chmod(output_filename, mode | stat.S_IXUSR)
| [
"[email protected]"
] | |
37b973fff2fbbb70adca43095f7713a15f44886e | b6fc54cff7037f5e4ef26cb4a645d5ea5a6fecdf | /000989letpy/letpy_059_is_20200503.py | 6e16cfdee1ebd5c0dcfe90e1764e2c9e70037371 | [
"Apache-2.0"
] | permissive | SafonovMikhail/python_000577 | 5483eaf2f7c73bc619ce1f5de67d8d689d2e7dd4 | f2dccac82a37df430c4eb7425b5d084d83520409 | refs/heads/master | 2022-12-08T10:53:57.202746 | 2022-12-07T09:09:51 | 2022-12-07T09:09:51 | 204,713,341 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 53 | py | a = "Hello, world!"
b = "Hello, world!"
print(a is b) | [
"[email protected]"
] | |
4c69aba309858501551b000e6236b893e0d8f7f7 | 30b2eb381ec8f3225671274e77a55b63206dfb60 | /leetcode/p0461/solve.py | d9975e98a22b92ab40c7733e7fe0660fbb2ee3ca | [] | no_license | b1ueskydragon/PythonGround | 52888f32336e5e20be8490454beb67e676be7057 | 5a401250e88926235f581e6c004d1a4acb44230d | refs/heads/master | 2021-07-10T03:00:38.340959 | 2021-04-02T03:34:29 | 2021-04-02T03:34:29 | 98,208,402 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 373 | py | class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor = x ^ y
ones = 0
while xor:
if (xor | 1) == xor:
ones += 1
xor >>= 1
return ones
if __name__ == '__main__':
s = Solution()
"""
011
101
---
110
count = 2
"""
print(s.hammingDistance(3, 5))
| [
"[email protected]"
] | |
61d86514b4f788b34ca4fa7e4b2e2c9fe7d8d723 | c07de6f278e7ffc11b4e1c7b37fdeae0d8aeb4a1 | /Section A/group10/task_1/part_1.py | 81576b2078ad1bfc40b4448aba58bd1cf2c06845 | [] | no_license | Medhashah/Big-DataProject | 729c1d14efc5096bae3dd150e9c218fa583a7861 | 571473626e82881b07073edf1de52f2b3563b294 | refs/heads/master | 2020-10-01T07:30:25.637471 | 2019-12-12T21:16:08 | 2019-12-12T21:16:08 | 227,487,323 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,176 | py | import json
import subprocess
import os
from dateutil import parser
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
import pyspark.sql.functions as F
import time
import sys
def main(start_index, end_index):
spark = SparkSession \
.builder \
.appName("big_data_prof") \
.config("spark.some.config.option", "some-value") \
.getOrCreate()
# conf = spark.sparkContext._conf.setAll(
# [('spark.executor.memory', '8g'), ('spark.app.name', 'big_data_proj'), ('spark.executor.cores', '4'),
# ('spark.cores.max', '4'), ('spark.driver.memory', '8g')])
# spark.sparkContext.stop()
# spark = SparkSession.builder.config(conf=conf).getOrCreate()
# new_conf = spark.sparkContext._conf.getAll()
# print(new_conf)
cmd = "hadoop fs -ls /user/hm74/NYCOpenData"
files = subprocess.check_output(cmd, shell=True).decode().strip().split('\n')
pfiles = [(x.split()[7], int(x.split()[4])) for x in files[1:]]
pfiles_sorted = sorted(pfiles, key=lambda x: x[1])
if not os.path.exists('job_{}_{}'.format(start_index, end_index)):
os.mkdir('job_{}_{}'.format(start_index, end_index))
for i, nyc_open_datafile in enumerate(pfiles_sorted[start_index:end_index]):
print("processing number {} of {}".format(i+start_index, end_index))
# pretty hacky preprocessing but it will work for now
# could maybe use pathlib library or get it with hdfs
processed_path = nyc_open_datafile[0]
df_nod = spark.read.option("header", "true").option("delimiter", "\t").csv(processed_path)
try:
file_name = processed_path.split('/')[-1].replace('.tsv.gz', '')
print(file_name)
if os.path.exists("job_{}_{}/{}.json".format(start_index, end_index, file_name)):
continue
start_process = time.time()
bp = BasicProfiling(processed_path, df_nod)
table_dict = bp.process()
json_type = json.dumps(table_dict)
#write to hdfs
# spark.parallelize([json_type]).toDF().coalesce(1).write.json('/user/gl758/big_data/job_{}_{}/{}'.format(start_index, end_index, file_name))
with open("job_{}_{}/{}.json".format(start_index, end_index, file_name), 'w+', encoding="utf-8") as f:
f.write(json_type)
end_process = time.time()
print("total process time {}".format(end_process - start_process))
except Exception as e:
print("unable to process because {}".format(e))
# We should put this in it's on package, but submitting with packages is kind of annoying so
# I moved it out for now look at --py-files
#https://spark.apache.org/docs/latest/submitting-applications.html
class BasicProfiling:
"""
Class for data profiling basic schema and statistics on a dataframe
"""
def __init__(self, dataset_name, df_nod):
self.dataset_name = dataset_name
self.df_nod = df_nod
self.table_dict = dict()
self.columns = self.df_nod.columns
self.spec_types = ['INT', 'REAL', 'DATE', 'TEXT']
# self.column_dict = None # the currently processed column dict
# self.column = None # the currently processed column dataframe
def __set_up_dictionary(self):
self.table_dict['dataset_name'] = self.dataset_name
self.table_dict['columns'] = []
def __add_column_general_info(self, column, column_name):
general_count = column.agg(lit(column_name).alias("name"), count(when(col(column_name).isNotNull(), True)).alias("count_not_null"), countDistinct(col(column_name)).alias("distinct"), count(when(col(column_name).isNull(), True)).alias("count_null"))
general_fre = column.groupBy(column_name).agg(count(column_name).alias("count_col")).orderBy(desc("count_col")).limit(5).agg(collect_list(column_name).alias('fre'))
return general_count, general_fre
def _add_datatype_columns(self, column, column_name):
"""
Adds a type column to add every column we currently have, obviously this doubles the size
:return:
"""
get_column_type_udf = udf(self.get_column_type)
column = column.withColumn("dtype", get_column_type_udf(column_name))
return column
def __get_stats_int(self, column, column_name):
int_info = column.filter("dtype = 'INT'").withColumn(column_name[1:-1], col(column_name).cast('int'))\
.select(array(count(col(column_name)), F.max(col(column_name)), F.min(col(column_name)), mean(col(column_name)), stddev(col(column_name))).alias('stats_int'))
return int_info
def __get_stats_double(self, column, column_name):
double_info = column.filter("dtype = 'REAL'").withColumn(column_name[1:-1], column[column_name].cast('double')).\
select(array(count(column_name), max(column_name), min(column_name), mean(column_name), stddev(column_name)).alias('stats_double'))
return double_info
def __get_stats_date(self, column, column_name):
udf_cast_date = udf(BasicProfiling.__get_datetime)
date_info = column.filter("dtype = 'DATE'").select(array(count(column_name), max(udf_cast_date(column_name)),
min(udf_cast_date(column_name))).alias('stats_date'))
return date_info
def __get_stats_text(self, column, column_name):
df_len = column.filter("dtype = 'TEXT'").withColumn("len", length(column_name))
text_info = df_len.select(array(count(column_name), mean("len")).alias('stats_text'))
shortest = df_len.orderBy(asc("len")).limit(5).agg(collect_list(column_name).alias('shortest_values')).select('shortest_values')
longest = df_len.orderBy(desc("len")).limit(5).agg(collect_list(column_name).alias('longest_values')).select('longest_values')
return text_info, shortest, longest
def __convert_df_to_dict(self, integer, real, date, text, shortest, longest, count, fre):
stats_int = integer.collect()
stats_double = real.collect()
stats_date = date.collect()
stats_text = text.collect()
stats_shortest = shortest.collect()
stats_longest = longest.collect()
general_count = count.collect()
# general_empty = empty.collect()
general_fre = fre.collect()
for i in range(len(stats_int)):
column_dict = {}
column_stats = [general_count[i][0], stats_int[i][0], stats_double[i][0], stats_date[i][0], stats_text[i][0], stats_shortest[i][0], stats_longest[i][0]]
column_dict['column_name'] = column_stats[0]
column_dict['number_empty_cells'] = general_count[i][3]
column_dict['number_non_empty_cells'] = general_count[i][1]
column_dict['number_distinct_values'] = general_count[i][2]
column_dict['frequent_values'] = general_fre[i][0]
column_dict['data_type'] = []
if column_stats[1][0] != 0:
type_dict = {}
type_dict['type'] = "INTERGER(LONG)"
type_dict['count'] = int(column_stats[1][0])
type_dict['max_value'] = int(column_stats[1][1])
type_dict['min_value'] = int(column_stats[1][2])
type_dict['mean'] = float(column_stats[1][3])
type_dict['stddev'] = float(column_stats[1][4])
column_dict['data_type'].append(type_dict)
if column_stats[2][0] != 0:
type_dict = {}
type_dict['type'] = 'REAL'
type_dict['count'] = int(column_stats[2][0])
type_dict['max_value'] = float(column_stats[2][1])
type_dict['min_value'] = float(column_stats[2][2])
type_dict['mean'] = float(column_stats[2][3])
type_dict['stddev'] = float(column_stats[2][4])
column_dict['data_type'].append(type_dict)
if column_stats[3][0] != '0':
type_dict = {}
type_dict['type'] = "DATE/TIME"
type_dict['count'] = int(column_stats[3][0])
type_dict['max_value'] = column_stats[3][1]
type_dict['min_value'] = column_stats[3][2]
column_dict['data_type'].append(type_dict)
if column_stats[4][0] != 0:
type_dict = {}
type_dict['type'] = "TEXT"
type_dict['count'] = column_stats[4][0]
type_dict['shortest_value'] = column_stats[5]
type_dict['longest_value'] = column_stats[6]
type_dict['average_length'] = column_stats[4][1]
column_dict['data_type'].append(type_dict)
self.table_dict['columns'].append(column_dict)
@staticmethod
def get_column_type(val):
"""
Returns the type of the value
:param val:
:return:
"""
if BasicProfiling.__is_int(val):
return 'INT'
elif BasicProfiling.__is_real(val):
return 'REAL'
elif BasicProfiling.__is_datetime(val):
return 'DATE'
elif val is None:
return None
else:
return 'TEXT'
@staticmethod
def __is_int(val):
try:
int(val)
return True
except (ValueError, TypeError):
return False
@staticmethod
def __is_real(val):
try:
float(val)
return True
except (ValueError, TypeError):
return False
@staticmethod
def __is_datetime(val):
try:
parser.parse(val)
return True
# raw exception here, I tried to catch none raw dateutil error exception, but it's giving some errors
# not sure I will need to fix up.
except:
return False
@staticmethod
def __get_datetime(val):
#tried to give actual timestamp, but then we can't put it into array, so instead I'm giving iso format
return parser.parse(val).isoformat()
def process(self):
start = time.time()
self.__set_up_dictionary()
for i, column_name in enumerate(self.columns):
column_name = "`{}`".format(column_name)
column = self.df_nod.select(column_name)
general_count, general_fre = self.__add_column_general_info(column, column_name)
# # generate type_dict
column = self._add_datatype_columns(column, column_name)
stats_int = self.__get_stats_int(column, column_name)
stats_double = self.__get_stats_double(column, column_name)
stats_date = self.__get_stats_date(column, column_name)
stats_text, shortest, longest = self.__get_stats_text(column, column_name)
if i == 0:
stats_table_int = stats_int
stats_table_double = stats_double
stats_table_date = stats_date
stats_table_text = stats_text
table_shortest = shortest
table_longest = longest
general_table_count = general_count
general_table_fre = general_fre
else:
stats_table_int = stats_table_int.union(stats_int)
stats_table_double = stats_table_double.union(stats_double)
stats_table_date = stats_table_date.union(stats_date)
stats_table_text = stats_table_text.union(stats_text)
table_shortest = table_shortest.union(shortest)
table_longest = table_longest.union(longest)
general_table_count = general_table_count.union(general_count)
general_table_fre = general_table_fre.union(general_fre)
self.__convert_df_to_dict(stats_table_int, stats_table_double, stats_table_date, stats_table_text, table_shortest, table_longest, general_table_count, general_table_fre)
return self.table_dict
if __name__ == "__main__":
start_index = int(sys.argv[1])
end_index = int(sys.argv[2])
main(start_index, end_index)
| [
"[email protected]"
] | |
5493b2f3a565402852a6d878c4d63e0d4b1c5509 | 3263139017e2e3cc253e93a9fb92604b00176466 | /pias/pias_logging.py | 761213610fb3cf88f47af4c7ab242ecf47990d20 | [] | no_license | saalfeldlab/pias | 245fb589b30e197fc03c152231ecc138d6ac7ae3 | acc7c19dc0ca81b846816ec0d0edf7ff87d46665 | refs/heads/master | 2020-04-22T06:38:58.126298 | 2019-03-10T19:01:53 | 2019-03-10T19:01:56 | 170,197,621 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 368 | py | import logging
print(logging)
trace = logging.DEBUG- 5
logging.TRACE = trace
logging.addLevelName(trace, 'TRACE')
class PiasLogger(logging.getLoggerClass()):
def trace(self, msg, *args, **kwargs):
self.log(trace, msg, *args, **kwargs)
logging.setLoggerClass(PiasLogger)
levels = ('NOTSET', 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL', 'FATAL', 'TRACE') | [
"[email protected]"
] | |
ba81708752f0fb17ace59645543fa3e7548bc1cb | 6bfcb3b91c2489cab0d9788079f69f37cf7e1387 | /test/test-bbox.py | fdd971e119df9736e87277292955aa7e59241bc5 | [
"BSD-3-Clause"
] | permissive | glamod/cdm-lens | 02f77f4270594acfadcf5b628bcdd8ea9a574b46 | d257906a3cd9fd01c118777803ef6b880b15ba81 | refs/heads/master | 2023-01-28T17:44:25.861444 | 2023-01-13T08:55:13 | 2023-01-13T08:55:13 | 212,615,087 | 1 | 0 | NOASSERTION | 2022-12-08T06:50:15 | 2019-10-03T15:34:44 | Python | UTF-8 | Python | false | false | 2,423 | py | import requests
import pandas as pd
import io
import math
TMPL = 'http://glamod2.ceda.ac.uk/select/?domain=land&frequency=monthly&variable=accumulated_precipitation,air_temperature&intended_use=non-commercial&data_quality=quality_controlled&column_selection=detailed_metadata&year=1974&month=03&bbox={w}.0,{s}.0,{e}.0,{n}.0&compress=false'
def _assert_in_range(df, w, s, e, n, to_nearest_degree=False):
if len(df) == 0:
print('Empty df')
return
lats, lons = df.latitude, df.longitude
min_lat, max_lat = lats.min(), lats.max()
min_lon, max_lon = lons.min(), lons.max()
print(f'Wanted lons: {w} to {e}; lats: {s} to {n}')
print(f'Actual lons: {min_lon} to {max_lon}; lats: {min_lat} to {max_lat}')
def fix(n):
if n < 0:
return math.ceil(n)
else:
return math.floor(n)
if to_nearest_degree:
min_lat, max_lat, min_lon, max_lon = [fix(_) for _ in [min_lat, max_lat, min_lon, max_lon]]
# print(lats, lats.max(), lats.min())
assert(min_lat >= s), 'min_lat >= s'
assert(max_lat <= n), 'max_lat <= n'
if min_lat == max_lat and min_lat == -90 or min_lat == 90:
print('Longitude checks are meaningless at the north/south pole')
return
if 90 in list(lats) or -90 in list(lats):
print('Some lats are north/south pole - so ignore longitude checks')
assert(min_lon >= w), 'min_lon >= w'
assert(max_lon <= e), 'max_lon <= e'
def _fetch_as_df(w, s, e, n):
url = TMPL.format(**vars())
print(f'{url}')
content = requests.get(url).text
if content.startswith('Exception raised'):
print(f'[ERROR] Fetch error: {content}')
return content
return pd.read_csv(io.StringIO(content))
def test_bbox_in_range():
for w in range(-180, 160, 30):
e = w + 30
for s in range(-90, 61, 30):
n = s + 30
df = _fetch_as_df(w, s, e, n)
_assert_in_range(df, w, s, e, n, True)
def test_bbox_full_range():
bboxes = ['-180,-90,180,90'] #, '-90,90,-180,180', '-90,-180,90,180']
for bbox in bboxes:
w, s, e, n = [int(_) for _ in bbox.split(',')]
df = _fetch_as_df(w, s, e, n)
if type(df) == str:
continue
_assert_in_range(df, w, s, e, n, True)
if __name__ == '__main__':
test_bbox_full_range()
test_bbox_in_range()
| [
"[email protected]"
] | |
1e4c3dc8648edeb0f51d861b4003419811ebc27a | 28b6e6a35b6591f36140b6cb907ac60c71dbcab1 | /app/migrations/0001_initial.py | b9dba1404818a767036d64bf7989c45046f5bdcf | [] | no_license | mahmud-sajib/Social-Profile-Rest-Api | 97c89af42439d08e730b3901fc76ac21cc3a7280 | 5c84ad847ce3303d63284a4363a2b1b4aaf76319 | refs/heads/master | 2023-03-22T09:24:00.439550 | 2021-03-15T08:18:44 | 2021-03-15T08:18:44 | 347,887,887 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 989 | py | # Generated by Django 3.1 on 2021-02-28 06:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Status',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('content', models.TextField(blank=True, null=True)),
('image', models.ImageField(blank=True, null=True, upload_to='uploads/%Y/%m/%d')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"[email protected]"
] | |
0a6291eaae1de1fc9b8321ad436642d3776c3ae5 | d48dfa622e07d346a91be3aa8e8657e409faf552 | /RozbudowaKodu/lab_files/lab_file_2.py | 6b25fe1a7a19217f18835bf54768e39c3fa1b477 | [] | no_license | sineczek/PythonSrednioZaawansowany | 71c8c94f7cdc193482a50b94315b86e1f0ab0039 | 75823b36de99ef9ac487672cf131a0b84ce23d2b | refs/heads/main | 2023-03-14T04:33:26.853500 | 2021-03-06T18:13:02 | 2021-03-06T18:13:02 | 332,524,333 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 250 | py | import math
argument_list = []
results_list = []
for i in range (1000000):
argument_list.append(i/10)
for x in argument_list:
results_list.append(abs(x**3 - x**0.5))
print('min = {} max = {}'.format(min(results_list), max(results_list))) | [
"[email protected]"
] | |
c668614ba1c31b9ddada5697bd9bd9833931bd3e | d28a65d23c204a9736b597ae510d9dd54d2ffd0f | /bin/newdb | cbffe8f0ede31ac97c8ea7393d309dee7b9fa505 | [
"BSD-3-Clause"
] | permissive | cts2/rf2db | 99ba327611e620fc5533245064afcc1daff7c164 | 985cd7ad84c8907306a0d7d309d4a1c0fb422ba4 | refs/heads/master | 2020-05-17T22:37:25.476553 | 2015-08-24T22:18:19 | 2015-08-24T22:18:19 | 15,264,407 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,053 | #!/usr/local/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2013, Mayo Clinic
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# Neither the name of the Mayo Clinic nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
# OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
import argparse
import os
# Assuming that we are running in the bin directory
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
sys.path.append(os.path.join(_curdir, '..'))
# TODO: Make this into a package
sys.path.append(os.path.join(_curdir, '..', '..', 'ConfigManager'))
from rf2db.db.RF2DBConnection import config_parms, debug_parms, cp_values, db_values, RF2DBConnection
helpargs = ['-h', '-?']
def main(argv):
""" Create a MySQL database for RF2 files and/or manage the connection parameters. Example sequence:
* python newdb --upd ../../rf2service/settings.conf --host localhost --db rf220140731 --charset utf8 --user root --passwd pw
* python newdb --show ../../rf2service/settings.conf
* python newdb --create ../../rf2service/settings.conf
"""
parser = argparse.ArgumentParser(description="Set up RF2 DB parameters and optionally create a database")
parser.add_argument('configfile', help="configuration file location")
parser.add_argument('--show', dest='show', action="store_true", help="show current configuration")
parser.add_argument('--upd', dest='update', action="store_true", help="update configuration file")
parser.add_argument('--create', action="store_true", help="create database if it doesn't exist")
# Can't do a lot more if there isn't configuration file
if len(argv) == 0 or (len(argv) == 1 and argv[0] in helpargs):
config_parms.add_to_parser(parser)
debug_parms.add_to_parser(parser)
parser.parse_args(argv)
return
# There is (or should be) a configuration file -- pick it out of the arguments and then reparse
args = [e for e in argv if e not in helpargs]
fileopt, _ = parser.parse_known_args(args)
# Open the existing configuration file so we know what the defaults should be
cp_values.set_configfile(fileopt.configfile)
config_parms.add_to_parser(parser, cp_values)
debug_parms.add_to_parser(parser, db_values)
opts = parser.parse_args(argv)
cp_values.update(vars(opts))
if opts.show:
print(str(cp_values))
if opts.update or not opts.show:
if cp_values.flush():
print("\nConfiguration file updated")
if opts.create:
RF2DBConnection().newDB()
print("Database %s created in %s" % (cp_values.db, cp_values.host + ((':' + cp_values.port) if cp_values.port else '')))
if __name__ == '__main__':
main(sys.argv[1:])
| [
"[email protected]"
] | ||
852065b653ca396ea321c7ff5ad1faeaba1cebe6 | 88b4b883c1a262b5f9ca2c97bf1835d6d73d9f0b | /src/api/python/hce/ftests/ftest_exit_code_simple.py | b2c4a8d9a82b0002258fc983f2ffd5611aca4435 | [] | no_license | hce-project/hce-bundle | 2f93dc219d717b9983c4bb534884e4a4b95e9b7b | 856a6df2acccd67d7af640ed09f05b2c99895f2e | refs/heads/master | 2021-09-07T22:55:20.964266 | 2018-03-02T12:00:42 | 2018-03-02T12:00:42 | 104,993,955 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 551 | py | #!/usr/bin/python
"""
HCE project, Python bindings, Distributed Tasks Manager application.
RTCFinalizer Class content main functional for finalize realtime crawling.
@package: dc
@file rtc-finalizer.py
@author Oleksii <[email protected]>, bgv, Alexander Vybornyh <[email protected]>
@link: http://hierarchical-cluster-engine.com/
@copyright: Copyright © 2013-2015 IOIX Ukraine
@license: http://hierarchical-cluster-engine.com/license/
@since: 0.1
"""
import ppath
from ppath import sys
import os
import sys
os._exit(11)
| [
"bgv@bgv-d9"
] | bgv@bgv-d9 |
65e1d34a1f7f96955c2ec68156d6da06d5ed4e7f | 9c38f3a354844f5080632005630d249d6487ebb3 | /haspy/test/simple/classdef_4.py | e8b6676653624320671c3245c2ff360d34222689 | [
"MIT"
] | permissive | keithroe/keithscode | ee7247ad6bdd844279f29a56718992cb886f9215 | 470c6b833b9b8bc2c78d1b43aac896b0ce9c9a7c | refs/heads/master | 2021-01-10T08:48:12.729594 | 2018-10-16T17:48:31 | 2018-10-16T17:48:31 | 51,531,627 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 25 | py | @b(c)
@d
class a:
pass
| [
"keithroe@cba41313-dcc7-113d-0d3d-2a2d30939b49"
] | keithroe@cba41313-dcc7-113d-0d3d-2a2d30939b49 |
8025ba35b9d424317c8728eb00872d51f226b847 | 5fe083b1082dd960dda5789b1cac7287be1d882b | /bin/parse_oneway.py | ade40fc8bd3d76417799a19345007a36ee098b97 | [
"MIT"
] | permissive | single-cell-rna-sequencing/scanorama | d412a98386354483a7ae768cb314731084c36431 | 60d21e5f71722baedc1cc0c2f0bff0338116b16a | refs/heads/master | 2020-05-18T19:03:02.178470 | 2018-12-11T23:14:55 | 2018-12-11T23:14:55 | 184,600,314 | 0 | 1 | null | 2019-05-02T14:55:33 | 2019-05-02T14:55:33 | null | UTF-8 | Python | false | false | 1,088 | py | import numpy as np
from scanorama import plt
plt.rcParams.update({'font.size': 25})
import sys
scano, uncor = {}, {}
in_scano = True
for line in open(sys.argv[1]):
fields = line.rstrip().split()
if len(fields) > 3:
continue
try:
F = float(fields[1])
except ValueError:
continue
if in_scano:
scano[fields[0]] = F
else:
uncor[fields[0]] = F
if fields[0] == 'ZZZ3':
in_scano = False
scanorama, uncorrected = [], []
for gene in set(scano.keys()) & set(uncor.keys()):
scanorama.append(scano[gene])
uncorrected.append(uncor[gene])
scanorama = np.array(scanorama)
uncorrected = np.array(uncorrected)
below = sum(scanorama > uncorrected + 50)
above = sum(scanorama < uncorrected - 50)
print('{}% above line'.format(float(above) / float(above + below) * 100))
name = sys.argv[1].split('.')[0]
line = min(max(scanorama), max(uncorrected))
plt.figure()
plt.scatter(scanorama, uncorrected, s=10)
plt.plot([0, line], [0, line], 'r--')
plt.tight_layout()
plt.savefig('oneway_{}.png'.format(name))
| [
"[email protected]"
] | |
32f4c462ec8097a34c1519e066a80a65f1a14c8f | 4f3a4c194451eae32f1ff7cf3b0db947e3892365 | /contest24/matrix.py | 6a654f89bbe393517b379bdacf7311c9a7f2387e | [] | no_license | szhongren/leetcode | 84dd848edbfd728b344927f4f3c376b89b6a81f4 | 8cda0518440488992d7e2c70cb8555ec7b34083f | refs/heads/master | 2021-12-01T01:34:54.639508 | 2021-11-30T05:54:45 | 2021-11-30T05:54:45 | 83,624,410 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,146 | py | """
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:
0 0 0
0 1 0
0 0 0
Output:
0 0 0
0 1 0
0 0 0
Example 2:
Input:
0 0 0
0 1 0
1 1 1
Output:
0 0 0
0 1 0
1 2 1
Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.
"""
class Solution(object):
def updateMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
indexes = [(i, j) for i in range(len(matrix)) for j in range(len(matrix[0])) if matrix[i][j] == 1]
matrix = [[0 if val == 0 else -1 for val in row]for row in matrix]
curr_level = 0
while len(indexes) > 0:
new_indexes = []
for index in indexes:
done = False
x = index[0]
y = index[1]
if x > 0:
if matrix[x - 1][y] == curr_level:
done = True
matrix[x][y] = curr_level + 1
if y > 0:
if matrix[x][y - 1] == curr_level:
done = True
matrix[x][y] = curr_level + 1
if x < len(matrix) - 1:
if matrix[x + 1][y] == curr_level:
done = True
matrix[x][y] = curr_level + 1
if y < len(matrix[0]) - 1:
if matrix[x][y + 1] == curr_level:
done = True
matrix[x][y] = curr_level + 1
if not done:
new_indexes.append(index)
curr_level += 1
indexes = new_indexes
return matrix
ans = Solution()
print(ans.updateMatrix([
[0, 0, 0],
[0, 1, 0],
[0, 0, 0]
]))
print(ans.updateMatrix([
[1, 1, 1],
[0, 1, 0],
[0, 0, 0]
]))
| [
"[email protected]"
] | |
86c74660e97fcfad69873b6025a9430d87b3496f | 492d3e666b87eff971628a74fe13facde01e2949 | /htmlcov/_python_Django_My Projects_student-portal_Lib_site-packages_django_db_migrations_graph_py.html.py | 05c7ac90efdcb13c551ee039f2457e7c75ee6996 | [] | no_license | OmarFateh/Student-Portal | 42050da15327aa01944dc79b5e00ca34deb51531 | 167ffd3a4183529c0cbc5db4ab232026711ea915 | refs/heads/master | 2023-06-13T01:03:16.475588 | 2021-07-08T11:09:09 | 2021-07-08T11:09:09 | 382,895,837 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 96,031 | py | XXXXXXXXX XXXXX
XXXXXX
XXXXXX
XXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXX
XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXX XX
XXXXXXXXXXXXXXX XXX XX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XXX XXXXXXXXXXXXXXXXX XXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXX XXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXX
XXXXXX
XXXX XXXXXXXXXXXX
XXXX XXXXXXXXXXXXXXXX
XXX
XX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXX XXXXXX XX XXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX
XXXXXXX XX XXXXXXXXXX XXXXX XXXXX
XXXX
XXXXXX
XXXXXX
XXXXXXX
XXXXXXX
| [
"[email protected]"
] | |
dbee469da3d768ac8bd9b40a106f32df70d98ae3 | 069dafce9f495f09bf8c2f76dbf5c045b7551721 | /run_size_V1_inhibition_overlapping.py | 2445079f234bb3bce526b0f73ebe9143a77a5600 | [] | no_license | dguarino/T2 | 26b1bc640812aa5438b09f9fab2bc73096cd7eef | 66b786928508089492f5f696c7c1576e098c6615 | refs/heads/master | 2020-04-03T22:39:06.059845 | 2020-03-13T15:43:02 | 2020-03-13T15:43:02 | 41,812,819 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,661 | py | # -*- coding: utf-8 -*-
"""
This is
"""
from pyNN import nest
import sys
import mozaik
import mozaik.controller
from mozaik.controller import run_workflow, setup_logging
from mozaik.storage.datastore import Hdf5DataStore, PickledDataStore
from parameters import ParameterSet
from model_V1_full import ThalamoCorticalModel
from experiments import create_experiments_size_V1_inactivated_overlapping
from analysis_and_visualization import perform_analysis_test
from analysis_and_visualization import perform_analysis_and_visualization
from analysis_and_visualization import perform_analysis_and_visualization_radius
try:
from mpi4py import MPI
except ImportError:
MPI = None
if MPI:
mpi_comm = MPI.COMM_WORLD
MPI_ROOT = 0
logger = mozaik.getMozaikLogger()
# Manage what is executed
# a set of variable here to manage the type of experiment and whether the pgn, cortex are there or not.
withPGN = True #
withV1 = True # open-loop
withFeedback_CxPGN = True # closed loop
withFeedback_CxLGN = True # closed loop
# Model execution
if True:
data_store,model = run_workflow('ThalamoCorticalModel', ThalamoCorticalModel, create_experiments_size_V1_inactivated_overlapping )
data_store.save()
# or only load pickled data
else:
setup_logging()
# data_store = PickledDataStore(load=True,parameters=ParameterSet({'root_directory':'Deliverable/ThalamoCorticalModel_data_size_overlapping_____', 'store_stimuli' : False}),replace=True)
data_store = PickledDataStore(load=True,parameters=ParameterSet({'root_directory':'ThalamoCorticalModel_data_size_overlapping_____', 'store_stimuli' : False}),replace=True)
logger.info('Loaded data store')
# Analysis and Plotting
if mpi_comm.rank == MPI_ROOT:
# perform_analysis_test( data_store )
# perform_analysis_and_visualization( data_store, 'luminance', withPGN, withV1 )
# perform_analysis_and_visualization( data_store, 'contrast', withPGN, withV1 )
# perform_analysis_and_visualization( data_store, 'spatial_frequency', withPGN, withV1 )
# perform_analysis_and_visualization( data_store, 'temporal_frequency', withPGN, withV1 )
perform_analysis_and_visualization( data_store, 'size', withPGN, withV1 )
# perform_analysis_and_visualization( data_store, 'size_radius', withPGN, withV1 )
# perform_analysis_and_visualization( data_store, 'orientation', withPGN, withV1 )
# import numpy
# step = .2
# for i in numpy.arange(step, 2.+step, step):
# perform_analysis_and_visualization_radius( data_store, 'size_radius', [i-step,i], withPGN, withV1 )
data_store.save()
| [
"[email protected]"
] | |
72624296abb72df145e8940e711e87d4f531eab1 | 09ae3f372d1000f118ad80874870ae420a4be66f | /scikit-learn-master/sklearn/datasets/tests/test_base.py | 08a6ba29413cf8bbe4e7c2cdcbf499993f650548 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | lqkweb/learnMLflow | 998f80c3828879b8d542125bc95c6345b8e9b29a | 13c5decaebba95b1b90f92021be35e343b4764af | refs/heads/master | 2022-10-18T06:17:23.584172 | 2019-01-18T09:51:38 | 2019-01-18T09:51:38 | 166,145,472 | 2 | 0 | Apache-2.0 | 2022-09-30T18:26:17 | 2019-01-17T02:22:29 | Python | UTF-8 | Python | false | false | 8,270 | py | import os
import shutil
import tempfile
import warnings
import numpy
from pickle import loads
from pickle import dumps
from functools import partial
import pytest
from sklearn.datasets import get_data_home
from sklearn.datasets import clear_data_home
from sklearn.datasets import load_files
from sklearn.datasets import load_sample_images
from sklearn.datasets import load_sample_image
from sklearn.datasets import load_digits
from sklearn.datasets import load_diabetes
from sklearn.datasets import load_linnerud
from sklearn.datasets import load_iris
from sklearn.datasets import load_breast_cancer
from sklearn.datasets import load_boston
from sklearn.datasets import load_wine
from sklearn.datasets.base import Bunch
from sklearn.datasets.tests.test_common import check_return_X_y
from sklearn.externals._pilutil import pillow_installed
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_raises
def _remove_dir(path):
if os.path.isdir(path):
shutil.rmtree(path)
@pytest.fixture(scope="module")
def data_home(tmpdir_factory):
tmp_file = str(tmpdir_factory.mktemp("scikit_learn_data_home_test"))
yield tmp_file
_remove_dir(tmp_file)
@pytest.fixture(scope="module")
def load_files_root(tmpdir_factory):
tmp_file = str(tmpdir_factory.mktemp("scikit_learn_load_files_test"))
yield tmp_file
_remove_dir(tmp_file)
@pytest.fixture
def test_category_dir_1(load_files_root):
test_category_dir1 = tempfile.mkdtemp(dir=load_files_root)
sample_file = tempfile.NamedTemporaryFile(dir=test_category_dir1,
delete=False)
sample_file.write(b"Hello World!\n")
sample_file.close()
yield str(test_category_dir1)
_remove_dir(test_category_dir1)
@pytest.fixture
def test_category_dir_2(load_files_root):
test_category_dir2 = tempfile.mkdtemp(dir=load_files_root)
yield str(test_category_dir2)
_remove_dir(test_category_dir2)
def test_data_home(data_home):
# get_data_home will point to a pre-existing folder
data_home = get_data_home(data_home=data_home)
assert_equal(data_home, data_home)
assert os.path.exists(data_home)
# clear_data_home will delete both the content and the folder it-self
clear_data_home(data_home=data_home)
assert not os.path.exists(data_home)
# if the folder is missing it will be created again
data_home = get_data_home(data_home=data_home)
assert os.path.exists(data_home)
def test_default_empty_load_files(load_files_root):
res = load_files(load_files_root)
assert_equal(len(res.filenames), 0)
assert_equal(len(res.target_names), 0)
assert_equal(res.DESCR, None)
def test_default_load_files(test_category_dir_1, test_category_dir_2,
load_files_root):
res = load_files(load_files_root)
assert_equal(len(res.filenames), 1)
assert_equal(len(res.target_names), 2)
assert_equal(res.DESCR, None)
assert_equal(res.data, [b"Hello World!\n"])
def test_load_files_w_categories_desc_and_encoding(
test_category_dir_1, test_category_dir_2, load_files_root):
category = os.path.abspath(test_category_dir_1).split('/').pop()
res = load_files(load_files_root, description="test",
categories=category, encoding="utf-8")
assert_equal(len(res.filenames), 1)
assert_equal(len(res.target_names), 1)
assert_equal(res.DESCR, "test")
assert_equal(res.data, ["Hello World!\n"])
def test_load_files_wo_load_content(
test_category_dir_1, test_category_dir_2, load_files_root):
res = load_files(load_files_root, load_content=False)
assert_equal(len(res.filenames), 1)
assert_equal(len(res.target_names), 2)
assert_equal(res.DESCR, None)
assert_equal(res.get('data'), None)
def test_load_sample_images():
try:
res = load_sample_images()
assert_equal(len(res.images), 2)
assert_equal(len(res.filenames), 2)
assert res.DESCR
except ImportError:
warnings.warn("Could not load sample images, PIL is not available.")
def test_load_digits():
digits = load_digits()
assert_equal(digits.data.shape, (1797, 64))
assert_equal(numpy.unique(digits.target).size, 10)
# test return_X_y option
check_return_X_y(digits, partial(load_digits))
def test_load_digits_n_class_lt_10():
digits = load_digits(9)
assert_equal(digits.data.shape, (1617, 64))
assert_equal(numpy.unique(digits.target).size, 9)
def test_load_sample_image():
try:
china = load_sample_image('china.jpg')
assert_equal(china.dtype, 'uint8')
assert_equal(china.shape, (427, 640, 3))
except ImportError:
warnings.warn("Could not load sample images, PIL is not available.")
def test_load_missing_sample_image_error():
if pillow_installed:
assert_raises(AttributeError, load_sample_image,
'blop.jpg')
else:
warnings.warn("Could not load sample images, PIL is not available.")
def test_load_diabetes():
res = load_diabetes()
assert_equal(res.data.shape, (442, 10))
assert res.target.size, 442
assert_equal(len(res.feature_names), 10)
assert res.DESCR
# test return_X_y option
check_return_X_y(res, partial(load_diabetes))
def test_load_linnerud():
res = load_linnerud()
assert_equal(res.data.shape, (20, 3))
assert_equal(res.target.shape, (20, 3))
assert_equal(len(res.target_names), 3)
assert res.DESCR
assert os.path.exists(res.data_filename)
assert os.path.exists(res.target_filename)
# test return_X_y option
check_return_X_y(res, partial(load_linnerud))
def test_load_iris():
res = load_iris()
assert_equal(res.data.shape, (150, 4))
assert_equal(res.target.size, 150)
assert_equal(res.target_names.size, 3)
assert res.DESCR
assert os.path.exists(res.filename)
# test return_X_y option
check_return_X_y(res, partial(load_iris))
def test_load_wine():
res = load_wine()
assert_equal(res.data.shape, (178, 13))
assert_equal(res.target.size, 178)
assert_equal(res.target_names.size, 3)
assert res.DESCR
# test return_X_y option
check_return_X_y(res, partial(load_wine))
def test_load_breast_cancer():
res = load_breast_cancer()
assert_equal(res.data.shape, (569, 30))
assert_equal(res.target.size, 569)
assert_equal(res.target_names.size, 2)
assert res.DESCR
assert os.path.exists(res.filename)
# test return_X_y option
check_return_X_y(res, partial(load_breast_cancer))
def test_load_boston():
res = load_boston()
assert_equal(res.data.shape, (506, 13))
assert_equal(res.target.size, 506)
assert_equal(res.feature_names.size, 13)
assert res.DESCR
assert os.path.exists(res.filename)
# test return_X_y option
check_return_X_y(res, partial(load_boston))
def test_loads_dumps_bunch():
bunch = Bunch(x="x")
bunch_from_pkl = loads(dumps(bunch))
bunch_from_pkl.x = "y"
assert_equal(bunch_from_pkl['x'], bunch_from_pkl.x)
def test_bunch_pickle_generated_with_0_16_and_read_with_0_17():
bunch = Bunch(key='original')
# This reproduces a problem when Bunch pickles have been created
# with scikit-learn 0.16 and are read with 0.17. Basically there
# is a surprising behaviour because reading bunch.key uses
# bunch.__dict__ (which is non empty for 0.16 Bunch objects)
# whereas assigning into bunch.key uses bunch.__setattr__. See
# https://github.com/scikit-learn/scikit-learn/issues/6196 for
# more details
bunch.__dict__['key'] = 'set from __dict__'
bunch_from_pkl = loads(dumps(bunch))
# After loading from pickle the __dict__ should have been ignored
assert_equal(bunch_from_pkl.key, 'original')
assert_equal(bunch_from_pkl['key'], 'original')
# Making sure that changing the attr does change the value
# associated with __getitem__ as well
bunch_from_pkl.key = 'changed'
assert_equal(bunch_from_pkl.key, 'changed')
assert_equal(bunch_from_pkl['key'], 'changed')
def test_bunch_dir():
# check that dir (important for autocomplete) shows attributes
data = load_iris()
assert "data" in dir(data)
| [
"[email protected]"
] | |
d74fff88ba05004f13b29253044811a8d2b7d787 | 3249577773cf18e5c09ea36de62477ddb43b662b | /Python/flask_fundamentals/Disappearing Ninja/server.py | 91bc33c8de93b14123c980e0d252bf8f7f89d6c4 | [] | no_license | HollinRoberts/code | 5394abe2a7c42bbbe83d8f64a99c50a52f05792b | 8026522ab169c4174037fdf1b271de60b75d79bf | refs/heads/master | 2021-01-01T16:12:11.674680 | 2017-10-18T21:08:10 | 2017-10-18T21:08:10 | 97,786,418 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 671 | py | from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/ninja")
def ninja():
return render_template("ninja.html")
@app.route("/ninja/<color>")
def ninja_color(color):
if color=="blue":
return render_template("leonardo.html" )
elif color=="orange":
return render_template("michelangelo.html")
elif color=="red":
return render_template("raphael.html")
elif color=="purple":
return render_template("donatello.html")
else:
return render_template("notapril.html")
app.run(debug=True) | [
"[email protected]"
] | |
d59c7349c687bb89df6ffe6c91d0cb52724efdaa | d4eb113c44c86322b3811513a7286d176f106eb6 | /experiments/variational_autoencoder/validation/compare_results.py | 9533452ba1c680b701a373947b1b8279453615c6 | [] | no_license | philip-brohan/Machine-Learning | 67a2eb780383b3436da4fef1d763f39d255ae696 | dc53b9c336d5f12272257f327abe49dec436ea04 | refs/heads/master | 2021-03-27T12:33:07.518279 | 2020-04-30T19:38:02 | 2020-04-30T19:38:02 | 56,614,781 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,113 | py | #!/usr/bin/env python
# Model training results plot
import tensorflow as tf
tf.enable_eager_execution()
import numpy
import IRData.twcr as twcr
import iris
import datetime
import argparse
import os
import math
import pickle
import Meteorographica as mg
import matplotlib
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
import cartopy
import cartopy.crs as ccrs
# Function to resize and rotate pole
def rr_cube(cbe):
# Use the Cassini projection (boundary is the equator)
cs=iris.coord_systems.RotatedGeogCS(0.0,60.0,270.0)
# Latitudes cover -90 to 90 with 79 values
lat_values=numpy.arange(-90,91,180/78)
latitude = iris.coords.DimCoord(lat_values,
standard_name='latitude',
units='degrees_north',
coord_system=cs)
# Longitudes cover -180 to 180 with 159 values
lon_values=numpy.arange(-180,181,360/158)
longitude = iris.coords.DimCoord(lon_values,
standard_name='longitude',
units='degrees_east',
coord_system=cs)
dummy_data = numpy.zeros((len(lat_values), len(lon_values)))
dummy_cube = iris.cube.Cube(dummy_data,
dim_coords_and_dims=[(latitude, 0),
(longitude, 1)])
n_cube=cbe.regrid(dummy_cube,iris.analysis.Linear())
return(n_cube)
# Get the 20CR data
ic=twcr.load('prmsl',datetime.datetime(2009,3,12,18),
version='2c')
ic=rr_cube(ic.extract(iris.Constraint(member=1)))
# Get the autoencoder
model_save_file=("%s/Machine-Learning-experiments/"+
"variational_autoencoder/"+
"/saved_models/Epoch_%04d/autoencoder") % (
os.getenv('SCRATCH'),500)
autoencoder=tf.keras.models.load_model(model_save_file,compile=False)
# Normalisation - Pa to mean=0, sd=1 - and back
def normalise(x):
x -= 101325
x /= 3000
return x
def unnormalise(x):
x *= 3000
x += 101325
return x
fig=Figure(figsize=(9.6,10.8), # 1/2 HD
dpi=100,
facecolor=(0.88,0.88,0.88,1),
edgecolor=None,
linewidth=0.0,
frameon=False,
subplotpars=None,
tight_layout=None)
canvas=FigureCanvas(fig)
# Top - map showing original and reconstructed fields
projection=ccrs.RotatedPole(pole_longitude=60.0,
pole_latitude=0.0,
central_rotated_longitude=270.0)
ax_map=fig.add_axes([0.01,0.51,0.98,0.48],projection=projection)
ax_map.set_axis_off()
extent=[-180,180,-90,90]
ax_map.set_extent(extent, crs=projection)
matplotlib.rc('image',aspect='auto')
# Run the data through the autoencoder and convert back to iris cube
pm=ic.copy()
pm.data=normalise(pm.data)
ict=tf.convert_to_tensor(pm.data, numpy.float32)
ict=tf.reshape(ict,[1,79,159,1])
result=autoencoder.predict_on_batch(ict)
result=tf.reshape(result,[79,159])
pm.data=unnormalise(result)
# Background, grid and land
ax_map.background_patch.set_facecolor((0.88,0.88,0.88,1))
#mg.background.add_grid(ax_map)
land_img_orig=ax_map.background_img(name='GreyT', resolution='low')
# original pressures as red contours
mg.pressure.plot(ax_map,ic,
scale=0.01,
resolution=0.25,
levels=numpy.arange(870,1050,7),
colors='red',
label=False,
linewidths=1)
# Encoded pressures as blue contours
mg.pressure.plot(ax_map,pm,
scale=0.01,
resolution=0.25,
levels=numpy.arange(870,1050,7),
colors='blue',
label=False,
linewidths=1)
mg.utils.plot_label(ax_map,
'%04d-%02d-%02d:%02d' % (2009,3,12,6),
facecolor=(0.88,0.88,0.88,0.9),
fontsize=8,
x_fraction=0.98,
y_fraction=0.03,
verticalalignment='bottom',
horizontalalignment='right')
# Scatterplot of encoded v original
ax=fig.add_axes([0.08,0.05,0.45,0.4])
aspect=.225/.4*16/9
# Axes ranges from data
dmin=min(ic.data.min(),pm.data.min())
dmax=max(ic.data.max(),pm.data.max())
dmean=(dmin+dmax)/2
dmax=dmean+(dmax-dmean)*1.05
dmin=dmean-(dmean-dmin)*1.05
if aspect<1:
ax.set_xlim(dmin/100,dmax/100)
ax.set_ylim((dmean-(dmean-dmin)*aspect)/100,
(dmean+(dmax-dmean)*aspect)/100)
else:
ax.set_ylim(dmin/100,dmax/100)
ax.set_xlim((dmean-(dmean-dmin)*aspect)/100,
(dmean+(dmax-dmean)*aspect)/100)
ax.scatter(x=pm.data.flatten()/100,
y=ic.data.flatten()/100,
c='black',
alpha=0.25,
marker='.',
s=2)
ax.set(ylabel='Original',
xlabel='Encoded')
ax.grid(color='black',
alpha=0.2,
linestyle='-',
linewidth=0.5)
# Plot the training history
history_save_file=("%s/Machine-Learning-experiments/"+
"variational_autoencoder/"+
"saved_models/history_to_%04d.pkl") % (
os.getenv('SCRATCH'),500)
history=pickle.load( open( history_save_file, "rb" ) )
ax=fig.add_axes([0.62,0.05,0.35,0.4])
# Axes ranges from data
ax.set_xlim(0,len(history['loss']))
ax.set_ylim(0,numpy.max(numpy.concatenate((history['loss'],
history['val_loss']))))
ax.set(xlabel='Epochs',
ylabel='Loss (grey) and validation loss (black)')
ax.grid(color='black',
alpha=0.2,
linestyle='-',
linewidth=0.5)
ax.plot(range(len(history['loss'])),
history['loss'],
color='grey',
linestyle='-',
linewidth=2)
ax.plot(range(len(history['val_loss'])),
history['val_loss'],
color='black',
linestyle='-',
linewidth=2)
# Render the figure as a png
fig.savefig("comparison_results.png")
| [
"[email protected]"
] | |
a2010a39af08d72a34b058f92fd12104c0aa8d29 | aa0cc19eedf38baca2ecef3de6f2a4c69ce68675 | /clld/scripts/postgres2sqlite.py | 168f94320038122afe286f29dcc8c331998e4f23 | [] | no_license | mitcho/clld | de84c54247138efa53ee5f68a87edc2a0ab06bbf | dcf5f063a44ac5167f677f05b2c66b0d094d4ff3 | refs/heads/master | 2021-01-18T09:56:18.486647 | 2013-08-23T15:13:18 | 2013-08-23T15:13:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,229 | py | """
python postgres2sqlite.py apics 2>&1 >/dev/null | less
Unfortunately this approach does not seem to work, thus, our only option is
intialize_db and making sure all db changes are done via alembic migrations.
"""
from subprocess import call
from importlib import import_module
import pkg_resources
import re
from tempfile import mktemp
from path import path
from sqlalchemy import create_engine
from clld.db.meta import Base
def replace_booleans(line):
"""replaces postgres boolean literals with 0|1 within the values in an INSERT
statement as created by pg_dump.
.. note::
- we rely on the INSERT statements not containing newlines.
- we somewhat naively split the values at commas and assume that if a single
token equals "true" or false", it was a boolean value in postgres. Obviously
this assumption does not hold for a text value like "..., true, ...".
We may switch to using sqlparse for a more robust detection of booleans.
>>> assert replace_booleans('INSERT (true, false);').strip() == 'INSERT (1, 0);'
"""
insert, values = line.split('(', 1)
assert values.endswith(');')
values = values[:-2]
clean_values = []
for token in values.split(', '):
if token == 'true':
token = "1"
elif token == 'false':
token = "0"
clean_values.append(token)
return '%s(%s);\n' % (insert, ', '.join(clean_values))
STMT_END = re.compile("([^\']\'|\, [0-9]+)\)\;$")
def inserts(iterator):
"""
>>> assert list(inserts(["INSERT (1, 1);"])) == ['INSERT (1, 1);']
>>> assert list(inserts(["INSERT ('a", "b');"])) == ["INSERT ('a__newline__b');"]
"""
insert = []
for line in iterator:
line = line.strip()
if line.startswith('INSERT '):
if STMT_END.search(line):
yield line
else:
insert = [line]
else:
if insert:
# a continuation line!
insert.append(line)
if STMT_END.search(line):
c = '__newline__'.join(insert)
insert = []
yield c
def convert_dump(i, o): # pragma: no cover
_insert = False
with file(o, 'w') as fp:
fp.write('.echo OFF\n.bail ON\n')
fp.write('BEGIN;\n')
for n, insert in enumerate(inserts(file(i))):
fp.write(replace_booleans(insert))
fp.write('END;\n')
def postgres2sqlite(name): # pragma: no cover
pg_sql = path(mktemp('.sql'))
sqlite_sql = path(mktemp('.sql'))
sqlite = mktemp('.sqlite')
call("pg_dump -f {0} --data-only --inserts {1}".format(pg_sql, name), shell=True)
convert_dump(pg_sql, sqlite_sql)
engine = create_engine('sqlite:////{0}'.format(sqlite))
m = import_module('{0}.models'.format(name))
Base.metadata.create_all(engine)
call('sqlite3 -bail -init {0} {1} ".exit"'.format(sqlite_sql, sqlite), shell=True)
if pg_sql.exists():
pg_sql.remove()
if sqlite_sql.exists():
sqlite_sql.remove()
return sqlite
if __name__ == '__main__': # pragma: no cover
import sys
postgres2sqlite(sys.argv[1])
sys.exit(0)
| [
"[email protected]"
] | |
f60880e5d4192b5bcbd9bd669c188d6935c9d098 | 4bee31f6a823fb1aebbd3dfe1d163aa0b1d41a7c | /seata/registry/FileRegistry.py | 460f4982eb6b95f9f7bcc623f50e55a313c15d63 | [
"Apache-2.0"
] | permissive | rohankumardubey/seata-python | 92532d1e8f8c961f2317aa8c23e2f53fe07711e9 | 66fb3382217a43effa3d1bc5ec2b62204d499dba | refs/heads/master | 2023-08-17T08:29:12.603412 | 2021-09-27T06:04:56 | 2021-09-27T06:04:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,249 | py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
from seata.config.Config import ConfigFactory
from seata.core.rpc.Address import Address
from seata.registry.Registry import Registry
class FileRegistry(Registry):
config = ConfigFactory.get_config()
def __init__(self):
pass
def register(self, address):
pass
def unregister(self, address):
pass
def subscribe(self, cluster, listener):
pass
def unsubscribe(self, cluster, listener):
pass
def lookup(self, key):
cluster_name = super(FileRegistry, self).get_service_group(key)
if cluster_name is None:
return None
endpoint_str = self.config.get('service.grouplist.' + cluster_name)
endpoints = endpoint_str.split(';')
addresses = []
for endpoint in endpoints:
if endpoint is None or len(endpoint.strip()) == 0:
continue
ip_port_arr = endpoint.split(':')
if len(ip_port_arr) != 2:
raise ValueError('endpoint format should like ip:port')
addresses.append(Address(ip_port_arr[0], int(ip_port_arr[1])))
return addresses
def close(self):
pass
| [
"[email protected]"
] | |
a06e048a185a9d0251f8d18dda29718efb09a160 | 462e52636f351a30da5bf2159bc9b30719bbe79b | /stuff/finished libraries/pytorch/_torch_docs.py | 5737af3d182faaa9e7a7cddb16dc5de740dcd382 | [] | no_license | SoutiRini/Top-20-Python-Libraries | c27b1ae77e11209bfe97405f8e324c54d4d49db4 | 1adcc6255dc59b25a831df2d23fa759e1e7c3264 | refs/heads/master | 2022-12-08T11:09:19.587218 | 2020-08-28T22:16:41 | 2020-08-28T22:16:41 | 291,153,411 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 267,122 | py | """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}
def merge_dicts(*dicts):
return {x: d[x] for d in dicts for x in d}
common_args = parse_kwargs("""
input (Tensor): the input tensor.
generator (:class:`torch.Generator`, optional): a pseudorandom number generator for sampling
out (Tensor, optional): the output tensor.
""")
reduceops_common_args = merge_dicts(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.
keepdim (bool): whether the output tensor has :attr:`dim` retained or not.
"""))
multi_dim_common = merge_dicts(reduceops_common_args, parse_kwargs("""
dim (int or tuple of ints): the dimension or dimensions to reduce.
"""), {'keepdim_details': """
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).
"""})
single_dim_common = merge_dicts(reduceops_common_args, parse_kwargs("""
dim (int): the dimension to reduce.
"""), {'keepdim_details': """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`."""})
factory_common_args = merge_dicts(common_args, parse_kwargs("""
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``.
pin_memory (bool, optional): If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: ``False``.
memory_format (:class:`torch.memory_format`, optional): the desired memory format of
returned Tensor. Default: ``torch.contiguous_format``.
"""))
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``.
pin_memory (bool, optional): If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. Default: ``False``.
memory_format (:class:`torch.memory_format`, optional): the desired memory format of
returned Tensor. Default: ``torch.preserve_format``.
""")
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``.
pin_memory (bool, optional): If set, returned tensor would be allocated in
the pinned memory. Works only for CPU tensors. 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}|
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.abs(torch.tensor([-1, -2, 3]))
tensor([ 1, 2, 3])
""".format(**common_args))
add_docstr(torch.absolute,
r"""
absolute(input, out=None) -> Tensor
Alias for :func:`torch.abs`
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.acosh,
r"""
acosh(input, out=None) -> Tensor
Returns a new tensor with the inverse hyperbolic cosine of the elements of :attr:`input`.
Note:
The domain of the inverse hyperbolic cosine is `[1, inf)` and values outside this range
will be mapped to ``NaN``, except for `+ INF` for which the output is mapped to `+ INF`.
.. math::
\text{out}_{i} = \cosh^{-1}(\text{input}_{i})
""" + r"""
Args:
{input}
Keyword arguments:
{out}
Example::
>>> a = torch.randn(4).uniform_(1, 2)
>>> a
tensor([ 1.3192, 1.9915, 1.9674, 1.7151 ])
>>> torch.acosh(a)
tensor([ 0.7791, 1.3120, 1.2979, 1.1341 ])
""".format(**common_args))
add_docstr(torch.add,
r"""
add(input, other, out=None)
Adds the scalar :attr:`other` to each element of the input :attr:`input`
and returns a new resulting tensor.
.. math::
\text{{out}} = \text{{input}} + \text{{other}}
If :attr:`input` is of type FloatTensor or DoubleTensor, :attr:`other` must be
a real number, otherwise it should be an integer.
Args:
{input}
value (Number): the number to be added to each element of :attr:`input`
Keyword arguments:
{out}
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, other, *, alpha=1, out=None)
Each element of the tensor :attr:`other` is multiplied by the scalar
:attr:`alpha` 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{{alpha}} \times \text{{other}}
If :attr:`other` is of type FloatTensor or DoubleTensor, :attr:`alpha` must be
a real number, otherwise it should be an integer.
Args:
input (Tensor): the first input tensor
other (Tensor): the second input tensor
alpha (Number): the scalar multiplier for :attr:`other`
Keyword arguments:
{out}
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, b, alpha=10)
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]])
""".format(**common_args))
add_docstr(torch.addbmm,
r"""
addbmm(input, batch1, batch2, *, beta=1, alpha=1, 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:`input` 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:`input` 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{input} + \alpha\ (\sum_{i=0}^{b-1} \text{batch1}_i \mathbin{@} \text{batch2}_i)
""" + r"""
For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and :attr:`alpha`
must be real numbers, otherwise they should be integers.
Args:
batch1 (Tensor): the first batch of matrices to be multiplied
batch2 (Tensor): the second batch of matrices to be multiplied
beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
input (Tensor): matrix to be added
alpha (Number, optional): multiplier for `batch1 @ batch2` (:math:`\alpha`)
{out}
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]])
""".format(**common_args))
add_docstr(torch.addcdiv,
r"""
addcdiv(input, tensor1, tensor2, *, value=1, 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:`input`.
.. warning::
Integer division with addcdiv is no longer supported, and in a future release
addcdiv will perform a true division of :attr:`tensor1` and :attr:`tensor2`.
The historic addcdiv behavior can be implemented using :func:`floor_divide`
for integral inputs
(:attr:`input` + :attr:`value` * :attr:`tensor1` // :attr:`tensor2`)
and :func:`div` for float inputs
(:attr:`input` + :attr:`value` * :attr:`tensor1` / :attr:`tensor2`).
The future addcdiv behavior can be implemented with :func:`true_divide`
(:attr:`input` + :attr:`value` * torch.true_divide(:attr:`tensor1`,
:attr:`tensor2`).
.. math::
\text{out}_i = \text{input}_i + \text{value} \times \frac{\text{tensor1}_i}{\text{tensor2}_i}
""" + r"""
The shapes of :attr:`input`, :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:
input (Tensor): the tensor to be added
tensor1 (Tensor): the numerator tensor
tensor2 (Tensor): the denominator tensor
value (Number, optional): multiplier for :math:`\text{{tensor1}} / \text{{tensor2}}`
{out}
Example::
>>> t = torch.randn(1, 3)
>>> t1 = torch.randn(3, 1)
>>> t2 = torch.randn(1, 3)
>>> torch.addcdiv(t, t1, t2, value=0.1)
tensor([[-0.2312, -3.6496, 0.1312],
[-1.0428, 3.4292, -0.1030],
[-0.5369, -0.9829, 0.0430]])
""".format(**common_args))
add_docstr(torch.addcmul,
r"""
addcmul(input, tensor1, tensor2, *, value=1, 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:`input`.
.. math::
\text{out}_i = \text{input}_i + \text{value} \times \text{tensor1}_i \times \text{tensor2}_i
""" + r"""
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:
input (Tensor): the tensor to be added
tensor1 (Tensor): the tensor to be multiplied
tensor2 (Tensor): the tensor to be multiplied
value (Number, optional): multiplier for :math:`tensor1 .* tensor2`
{out}
Example::
>>> t = torch.randn(1, 3)
>>> t1 = torch.randn(3, 1)
>>> t2 = torch.randn(1, 3)
>>> torch.addcmul(t, t1, t2, value=0.1)
tensor([[-0.8635, -0.6391, 1.6174],
[-0.7617, -0.5879, 1.7388],
[-0.8353, -0.6249, 1.6511]])
""".format(**common_args))
add_docstr(torch.addmm,
r"""
addmm(input, mat1, mat2, *, beta=1, alpha=1, out=None) -> Tensor
Performs a matrix multiplication of the matrices :attr:`mat1` and :attr:`mat2`.
The matrix :attr:`input` 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:`input` 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:`input` respectively.
.. math::
\text{out} = \beta\ \text{input} + \alpha\ (\text{mat1}_i \mathbin{@} \text{mat2}_i)
""" + r"""
For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
:attr:`alpha` must be real numbers, otherwise they should be integers.
Args:
input (Tensor): matrix to be added
mat1 (Tensor): the first matrix to be multiplied
mat2 (Tensor): the second matrix to be multiplied
beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
alpha (Number, optional): multiplier for :math:`mat1 @ mat2` (:math:`\alpha`)
{out}
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]])
""".format(**common_args))
add_docstr(torch.addmv,
r"""
addmv(input, mat, vec, *, beta=1, alpha=1, out=None) -> Tensor
Performs a matrix-vector product of the matrix :attr:`mat` and
the vector :attr:`vec`.
The vector :attr:`input` 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:`input` 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:`input` respectively.
.. math::
\text{out} = \beta\ \text{input} + \alpha\ (\text{mat} \mathbin{@} \text{vec})
""" + r"""
For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
:attr:`alpha` must be real numbers, otherwise they should be integers
Args:
input (Tensor): vector to be added
mat (Tensor): matrix to be multiplied
vec (Tensor): vector to be multiplied
beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
alpha (Number, optional): multiplier for :math:`mat @ vec` (:math:`\alpha`)
{out}
Example::
>>> M = torch.randn(2)
>>> mat = torch.randn(2, 3)
>>> vec = torch.randn(3)
>>> torch.addmv(M, mat, vec)
tensor([-0.3768, -5.5565])
""".format(**common_args))
add_docstr(torch.addr,
r"""
addr(input, vec1, vec2, *, beta=1, alpha=1, out=None) -> Tensor
Performs the outer-product of vectors :attr:`vec1` and :attr:`vec2`
and adds it to the matrix :attr:`input`.
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:`input` respectively.
.. math::
\text{out} = \beta\ \text{input} + \alpha\ (\text{vec1} \otimes \text{vec2})
""" + r"""
If :attr:`vec1` is a vector of size `n` and :attr:`vec2` is a vector
of size `m`, then :attr:`input` 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:
input (Tensor): matrix to be added
vec1 (Tensor): the first vector of the outer product
vec2 (Tensor): the second vector of the outer product
beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
alpha (Number, optional): multiplier for :math:`\text{{vec1}} \otimes \text{{vec2}}` (:math:`\alpha`)
{out}
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.]])
""".format(**common_args))
add_docstr(torch.allclose,
r"""
allclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> bool
This function checks if all :attr:`input` and :attr:`other` satisfy the condition:
.. math::
\lvert \text{input} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert
""" + r"""
elementwise, for all elements of :attr:`input` 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:
input (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 (bool, optional): if ``True``, then two ``NaN`` s will be considered 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.angle,
r"""
angle(input, out=None) -> Tensor
Computes the element-wise angle (in radians) of the given :attr:`input` tensor.
.. math::
\text{out}_{i} = angle(\text{input}_{i})
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.angle(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))*180/3.14159
tensor([ 135., 135, -45])
""".format(**common_args))
add_docstr(torch.as_strided,
r"""
as_strided(input, size, stride, storage_offset=0) -> Tensor
Create a view of an existing `torch.Tensor` :attr:`input` with specified
:attr:`size`, :attr:`stride` and :attr:`storage_offset`.
.. warning::
More than one element of a created tensor may refer to a single memory
location. As a result, in-place operations (especially ones that are
vectorized) may result in incorrect behavior. If you need to write to
the tensors, please clone them first.
Many PyTorch functions, which return a view of a tensor, are internally
implemented with this function. Those functions, like
:meth:`torch.Tensor.expand`, are easier to read and are therefore more
advisable to use.
Args:
{input}
size (tuple or ints): the shape of the output tensor
stride (tuple or ints): the stride of the output tensor
storage_offset (int, optional): the offset in the underlying storage of the output tensor
Example::
>>> x = torch.randn(3, 3)
>>> x
tensor([[ 0.9039, 0.6291, 1.0795],
[ 0.1586, 2.1939, -0.4900],
[-0.1909, -0.7503, 1.9355]])
>>> t = torch.as_strided(x, (2, 2), (1, 2))
>>> t
tensor([[0.9039, 1.0795],
[0.6291, 0.1586]])
>>> t = torch.as_strided(x, (2, 2), (1, 2), 1)
tensor([[0.6291, 0.1586],
[1.0795, 2.1939]])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.asinh,
r"""
asinh(input, out=None) -> Tensor
Returns a new tensor with the inverse hyperbolic sine of the elements of :attr:`input`.
.. math::
\text{out}_{i} = \sinh^{-1}(\text{input}_{i})
""" + r"""
Args:
{input}
Keyword arguments:
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([ 0.1606, -1.4267, -1.0899, -1.0250 ])
>>> torch.asinh(a)
tensor([ 0.1599, -1.1534, -0.9435, -0.8990 ])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.atan2,
r"""
atan2(input, other, out=None) -> Tensor
Element-wise arctangent of :math:`\text{{input}}_{{i}} / \text{{other}}_{{i}}`
with consideration of the quadrant. Returns a new tensor with the signed angles
in radians between vector :math:`(\text{{other}}_{{i}}, \text{{input}}_{{i}})`
and vector :math:`(1, 0)`. (Note that :math:`\text{{other}}_{{i}}`, the second
parameter, is the x-coordinate, while :math:`\text{{input}}_{{i}}`, the first
parameter, is the y-coordinate.)
The shapes of ``input`` and ``other`` must be
:ref:`broadcastable <broadcasting-semantics>`.
Args:
input (Tensor): the first input tensor
other (Tensor): the second input tensor
{out}
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])
""".format(**common_args))
add_docstr(torch.atanh,
r"""
atanh(input, out=None) -> Tensor
Returns a new tensor with the inverse hyperbolic tangent of the elements of :attr:`input`.
Note:
The domain of the inverse hyperbolic tangent is `(-1, 1)` and values outside this range
will be mapped to ``NaN``, except for the values `1` and `-1` for which the output is
mapped to `+/-INF` respectively.
.. math::
\text{out}_{i} = \tanh^{-1}(\text{input}_{i})
""" + r"""
Args:
{input}
Keyword arguments:
{out}
Example::
>>> a = torch.randn(4).uniform_(-1, 1)
>>> a
tensor([ -0.9385, 0.2968, -0.8591, -0.1871 ])
>>> torch.atanh(a)
tensor([ -1.7253, 0.3060, -1.2899, -0.1893 ])
""".format(**common_args))
add_docstr(torch.baddbmm,
r"""
baddbmm(input, batch1, batch2, *, beta=1, alpha=1, out=None) -> Tensor
Performs a batch matrix-matrix product of matrices in :attr:`batch1`
and :attr:`batch2`.
:attr:`input` 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:`input` 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{input}_i + \alpha\ (\text{batch1}_i \mathbin{@} \text{batch2}_i)
""" + r"""
For inputs of type `FloatTensor` or `DoubleTensor`, arguments :attr:`beta` and
:attr:`alpha` must be real numbers, otherwise they should be integers.
Args:
input (Tensor): the tensor to be added
batch1 (Tensor): the first batch of matrices to be multiplied
batch2 (Tensor): the second batch of matrices to be multiplied
beta (Number, optional): multiplier for :attr:`input` (:math:`\beta`)
alpha (Number, optional): multiplier for :math:`\text{{batch1}} \mathbin{{@}} \text{{batch2}}` (:math:`\alpha`)
{out}
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])
""".format(**common_args))
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})
""" + r"""
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
{generator}
{out}
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.]])
""".format(**common_args))
add_docstr(torch.bincount,
r"""
bincount(input, 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``.
Note:
In some circumstances when using the CUDA backend with CuDNN, this operator
may select a nondeterministic algorithm to increase performance. If this is
undesirable, you can try to make the operation deterministic (potentially at
a performance cost) by setting ``torch.backends.cudnn.deterministic =
True``.
Please see the notes on :doc:`/notes/randomness` for background.
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.bitwise_not,
r"""
bitwise_not(input, out=None) -> Tensor
Computes the bitwise NOT of the given input tensor. The input tensor must be of
integral or Boolean types. For bool tensors, it computes the logical NOT.
Args:
{input}
{out}
Example:
>>> torch.bitwise_not(torch.tensor([-1, -2, 3], dtype=torch.int8))
tensor([ 0, 1, -4], dtype=torch.int8)
""".format(**common_args))
add_docstr(torch.bmm,
r"""
bmm(input, mat2, deterministic=False, out=None) -> Tensor
Performs a batch matrix-matrix product of matrices stored in :attr:`input`
and :attr:`mat2`.
:attr:`input` and :attr:`mat2` must be 3-D tensors each containing
the same number of matrices.
If :attr:`input` is a :math:`(b \times n \times m)` tensor, :attr:`mat2` 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{input}_i \mathbin{@} \text{mat2}_i
""" + r"""
.. note:: This function does not :ref:`broadcast <broadcasting-semantics>`.
For broadcasting matrix products, see :func:`torch.matmul`.
Args:
input (Tensor): the first batch of matrices to be multiplied
mat2 (Tensor): the second batch of matrices to be multiplied
deterministic (bool, optional): flag to choose between a faster non-deterministic
calculation, or a slower deterministic calculation.
This argument is only available for sparse-dense CUDA bmm.
Default: ``False``
{out}
Example::
>>> input = torch.randn(10, 3, 4)
>>> mat2 = torch.randn(10, 4, 5)
>>> res = torch.bmm(input, mat2)
>>> res.size()
torch.Size([10, 3, 5])
""".format(**common_args))
add_docstr(torch.bitwise_and,
r"""
bitwise_and(input, other, out=None) -> Tensor
Computes the bitwise AND of :attr:`input` and :attr:`other`. The input tensor must be of
integral or Boolean types. For bool tensors, it computes the logical AND.
Args:
input: the first input tensor
other: the second input tensor
{out}
Example:
>>> torch.bitwise_and(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
tensor([1, 0, 3], dtype=torch.int8)
>>> torch.bitwise_and(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
tensor([ False, True, False])
""".format(**common_args))
add_docstr(torch.bitwise_or,
r"""
bitwise_or(input, other, out=None) -> Tensor
Computes the bitwise OR of :attr:`input` and :attr:`other`. The input tensor must be of
integral or Boolean types. For bool tensors, it computes the logical OR.
Args:
input: the first input tensor
other: the second input tensor
{out}
Example:
>>> torch.bitwise_or(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
tensor([-1, -2, 3], dtype=torch.int8)
>>> torch.bitwise_or(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
tensor([ True, True, False])
""".format(**common_args))
add_docstr(torch.bitwise_xor,
r"""
bitwise_xor(input, other, out=None) -> Tensor
Computes the bitwise XOR of :attr:`input` and :attr:`other`. The input tensor must be of
integral or Boolean types. For bool tensors, it computes the logical XOR.
Args:
input: the first input tensor
other: the second input tensor
{out}
Example:
>>> torch.bitwise_xor(torch.tensor([-1, -2, 3], dtype=torch.int8), torch.tensor([1, 0, 3], dtype=torch.int8))
tensor([-2, -2, 0], dtype=torch.int8)
>>> torch.bitwise_xor(torch.tensor([True, True, False]), torch.tensor([False, True, False]))
tensor([ True, False, False])
""".format(**common_args))
add_docstr(torch.stack,
r"""
stack(tensors, dim=0, out=None) -> Tensor
Concatenates sequence of tensors along a new dimension.
All tensors need to be of the same size.
Arguments:
tensors (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}
""".format(**common_args))
add_docstr(torch.chunk,
r"""
chunk(input, chunks, dim=0) -> List of Tensors
Splits a tensor into a specific number of chunks. Each chunk is a view of
the input tensor.
Last chunk will be smaller if the tensor size along the given dimension
:attr:`dim` is not divisible by :attr:`chunks`.
Arguments:
input (Tensor): the tensor to split
chunks (int): number of chunks to return
dim (int): dimension along which to split the tensor
""")
add_docstr(torch.unsafe_chunk,
r"""
unsafe_chunk(input, chunks, dim=0) -> List of Tensors
Works like :func:`torch.chunk` but without enforcing the autograd restrictions
on inplace modification of the outputs.
.. warning::
This function is safe to use as long as only the input, or only the outputs
are modified inplace after calling this function. It is user's
responsibility to ensure that is the case. If both the input and one or more
of the outputs are modified inplace, gradients computed by autograd will be
silently incorrect.
""")
add_docstr(torch.unsafe_split,
r"""
unsafe_split(tensor, split_size_or_sections, dim=0) -> List of Tensors
Works like :func:`torch.split` but without enforcing the autograd restrictions
on inplace modification of the outputs.
.. warning::
This function is safe to use as long as only the input, or only the outputs
are modified inplace after calling this function. It is user's
responsibility to ensure that is the case. If both the input and one or more
of the outputs are modified inplace, gradients computed by autograd will be
silently incorrect.
""")
add_docstr(torch.can_cast,
r"""
can_cast(from, to) -> bool
Determines if a type conversion is allowed under PyTorch casting rules
described in the type promotion :ref:`documentation <type-promotion-doc>`.
Args:
from (dtype): The original :class:`torch.dtype`.
to (dtype): The target :class:`torch.dtype`.
Example::
>>> torch.can_cast(torch.double, torch.float)
True
>>> torch.can_cast(torch.float, torch.int)
False
""")
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}
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]])
""".format(**common_args))
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
""" + r"""
Args:
{input}
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([-0.6341, -1.4208, -1.0900, 0.5826])
>>> torch.ceil(a)
tensor([-0., -1., -1., 1.])
""".format(**common_args))
add_docstr(torch.real,
r"""
real(input) -> Tensor
Returns a new tensor containing real values of the :attr:`self` tensor.
The returned tensor and :attr:`self` share the same underlying storage.
.. warning::
:func:`real` is only supported for tensors with complex dtypes.
Args:
{input}
Example::
>>> x=torch.randn(4, dtype=torch.cfloat)
>>> x
tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)])
>>> x.real
tensor([ 0.3100, -0.5445, -1.6492, -0.0638])
""".format(**common_args))
add_docstr(torch.imag,
r"""
imag(input) -> Tensor
Returns a new tensor containing imaginary values of the :attr:`self` tensor.
The returned tensor and :attr:`self` share the same underlying storage.
.. warning::
:func:`imag` is only supported for tensors with complex dtypes.
Args:
{input}
Example::
>>> x=torch.randn(4, dtype=torch.cfloat)
>>> x
tensor([(0.3100+0.3553j), (-0.5445-0.7896j), (-1.6492-0.0633j), (-0.0638-0.8119j)])
>>> x.imag
tensor([ 0.3553, -0.7896, -0.0633, -0.8119])
""".format(**common_args))
add_docstr(torch.view_as_real,
r"""
view_as_real(input) -> Tensor
Returns a view of :attr:`input` as a real tensor. For an input complex tensor of
:attr:`size` :math:`m1, m2, \dots, mi`, this function returns a new
real tensor of size :math:`m1, m2, \dots, mi, 2`, where the last dimension of size 2
represents the real and imaginary components of complex numbers.
.. warning::
:func:`view_as_real` is only supported for tensors with ``complex dtypes``.
Args:
{input}
Example::
>>> x=torch.randn(4, dtype=torch.cfloat)
>>> x
tensor([(0.4737-0.3839j), (-0.2098-0.6699j), (0.3470-0.9451j), (-0.5174-1.3136j)])
>>> torch.view_as_real(x)
tensor([[ 0.4737, -0.3839],
[-0.2098, -0.6699],
[ 0.3470, -0.9451],
[-0.5174, -1.3136]])
""".format(**common_args))
add_docstr(torch.view_as_complex,
r"""
view_as_complex(input) -> Tensor
Returns a view of :attr:`input` as a complex tensor. For an input complex
tensor of :attr:`size` :math:`m1, m2, \dots, mi, 2`, this function returns a
new complex tensor of :attr:`size` :math:`m1, m2, \dots, mi` where the last
dimension of the input tensor is expected to represent the real and imaginary
components of complex numbers.
.. warning::
:func:`view_as_complex` is only supported for tensors with
:class:`torch.dtype` ``torch.float64`` and ``torch.float32``. The input is
expected to have the last dimension of :attr:`size` 2. In addition, the
tensor must have a `stride` of 1 for its last dimension. The strides of all
other dimensions must be even numbers.
Args:
{input}
Example::
>>> x=torch.randn(4, 2)
>>> x
tensor([[ 1.6116, -0.5772],
[-1.4606, -0.9120],
[ 0.0786, -1.7497],
[-0.6561, -1.6623]])
>>> torch.view_as_complex(x)
tensor([(1.6116-0.5772j), (-1.4606-0.9120j), (0.0786-1.7497j), (-0.6561-1.6623j)])
""".format(**common_args))
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}}
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.cholesky, r"""
cholesky(input, 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 :math:`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:
input (Tensor): the input tensor :math:`A` of size :math:`(*, 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.cholesky_solve, r"""
cholesky_solve(input, input2, upper=False, out=None) -> Tensor
Solves a linear system of equations with a positive semidefinite
matrix to be inverted given its Cholesky factor matrix :math:`u`.
If :attr:`upper` is ``False``, :math:`u` is and lower triangular and `c` is
returned such that:
.. math::
c = (u u^T)^{{-1}} b
If :attr:`upper` is ``True`` or not provided, :math:`u` is upper triangular
and `c` is returned such that:
.. math::
c = (u^T u)^{{-1}} b
`torch.cholesky_solve(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`
Args:
input (Tensor): input matrix :math:`b` of size :math:`(*, m, k)`,
where :math:`*` is zero or more batch dimensions
input2 (Tensor): input matrix :math:`u` 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 consider the Cholesky factor as a
lower or upper triangular matrix. Default: ``False``.
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.cholesky_solve(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.cholesky_inverse, r"""
cholesky_inverse(input, upper=False, out=None) -> Tensor
Computes the inverse of a symmetric positive-definite matrix :math:`A` using its
Cholesky factor :math:`u`: returns matrix ``inv``. The inverse is computed using
LAPACK routines ``dpotri`` and ``spotri`` (and the corresponding MAGMA routines).
If :attr:`upper` is ``False``, :math:`u` is lower triangular
such that the returned tensor is
.. math::
inv = (uu^{{T}})^{{-1}}
If :attr:`upper` is ``True`` or not provided, :math:`u` is upper
triangular such that the returned tensor is
.. math::
inv = (u^T u)^{{-1}}
Args:
input (Tensor): the input 2-D tensor :math:`u`, a upper or lower triangular
Cholesky factor
upper (bool, optional): whether to return a lower (default) or upper triangular matrix
out (Tensor, optional): the output tensor for `inv`
Example::
>>> a = torch.randn(3, 3)
>>> a = torch.mm(a, a.t()) + 1e-05 * torch.eye(3) # 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.cholesky_inverse(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.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}
""" + r"""
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}
min (Number): lower-bound of the range to be clamped to
max (Number): upper-bound of the range to be clamped to
{out}
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}
value (Number): minimal value of each element in the output
{out}
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}
value (Number): maximal value of each element in the output
{out}
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])
""".format(**common_args))
add_docstr(torch.conj,
r"""
conj(input, out=None) -> Tensor
Computes the element-wise conjugate of the given :attr:`input` tensor.
.. math::
\text{out}_{i} = conj(\text{input}_{i})
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.conj(torch.tensor([-1 + 1j, -2 + 2j, 3 - 3j]))
tensor([-1 - 1j, -2 - 2j, 3 + 3j])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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}
other (Tensor): the second input tensor
dim (int, optional): the dimension to take the cross-product in.
{out}
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]])
""".format(**common_args))
add_docstr(torch.logcumsumexp,
r"""
logcumsumexp(input, dim, out=None) -> Tensor
Returns the logarithm of the cumulative summation of the exponentiation of
elements of :attr:`input` in the dimension :attr:`dim`.
For summation index :math:`j` given by `dim` and other indices :math:`i`, the result is
.. math::
\text{{logcumsumexp}}(x)_{{ij}} = \log \sum\limits_{{j=0}}^{{i}} \exp(x_{{ij}})
Args:
{input}
dim (int): the dimension to do the operation over
{out}
Example::
>>> a = torch.randn(10)
>>> torch.logcumsumexp(a, dim=0)
tensor([-0.42296738, -0.04462666, 0.86278635, 0.94622083, 1.05277811,
1.39202815, 1.83525007, 1.84492621, 2.06084887, 2.06844475]))
""".format(**reduceops_common_args))
add_docstr(torch.cummax,
r"""
cummax(input, dim, out=None) -> (Tensor, LongTensor)
Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative maximum of
elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index
location of each maximum value found in the dimension :attr:`dim`.
.. math::
y_i = max(x_1, x_2, x_3, \dots, x_i)
Args:
{input}
dim (int): the dimension to do the operation over
out (tuple, optional): the result tuple of two output tensors (values, indices)
Example::
>>> a = torch.randn(10)
>>> a
tensor([-0.3449, -1.5447, 0.0685, -1.5104, -1.1706, 0.2259, 1.4696, -1.3284,
1.9946, -0.8209])
>>> torch.cummax(a, dim=0)
torch.return_types.cummax(
values=tensor([-0.3449, -0.3449, 0.0685, 0.0685, 0.0685, 0.2259, 1.4696, 1.4696,
1.9946, 1.9946]),
indices=tensor([0, 0, 2, 2, 2, 5, 6, 6, 8, 8]))
""".format(**reduceops_common_args))
add_docstr(torch.cummin,
r"""
cummin(input, dim, out=None) -> (Tensor, LongTensor)
Returns a namedtuple ``(values, indices)`` where ``values`` is the cumulative minimum of
elements of :attr:`input` in the dimension :attr:`dim`. And ``indices`` is the index
location of each maximum value found in the dimension :attr:`dim`.
.. math::
y_i = min(x_1, x_2, x_3, \dots, x_i)
Args:
{input}
dim (int): the dimension to do the operation over
out (tuple, optional): the result tuple of two output tensors (values, indices)
Example::
>>> a = torch.randn(10)
>>> a
tensor([-0.2284, -0.6628, 0.0975, 0.2680, -1.3298, -0.4220, -0.3885, 1.1762,
0.9165, 1.6684])
>>> torch.cummin(a, dim=0)
torch.return_types.cummin(
values=tensor([-0.2284, -0.6628, -0.6628, -0.6628, -1.3298, -1.3298, -1.3298, -1.3298,
-1.3298, -1.3298]),
indices=tensor([0, 1, 1, 1, 4, 4, 4, 4, 4, 4]))
""".format(**reduceops_common_args))
add_docstr(torch.cumprod,
r"""
cumprod(input, dim, out=None, 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}
dim (int): the dimension to do the operation over
{dtype}
{out}
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}
dim (int): the dimension to do the operation over
{dtype}
{out}
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.count_nonzero,
r"""
count_nonzero(input, dim=None) -> Tensor
Counts the number of non-zero values in the tensor :attr:`input` along the given :attr:`dim`.
If no dim is specified then all non-zeros in the tensor are counted.
Args:
{input}
dim (int or tuple of ints, optional): Dim or tuple of dims along which to count non-zeros.
Example::
>>> x = torch.zeros(3,3)
>>> x[torch.randn(3,3) > 0.5] = 1
>>> x
tensor([[0., 1., 1.],
[0., 0., 0.],
[0., 0., 1.]])
>>> torch.count_nonzero(x)
tensor(3)
>>> torch.count_nonzero(x, dim=0)
tensor([0, 1, 2])
""".format(**reduceops_common_args))
add_docstr(torch.dequantize,
r"""
dequantize(tensor) -> Tensor
Given a quantized Tensor, dequantize it and return an fp32 Tensor
Args:
tensor (Tensor): A quantized Tensor
.. function:: dequantize(tensors) -> sequence of Tensors
Given a list of quantized Tensors, dequantize them and return a list of fp32 Tensors
Args:
tensors (sequence of Tensors): A list of quantized Tensors
""")
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}
diagonal (int, optional): the diagonal to consider
{out}
.. 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])
""".format(**common_args))
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} 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]]])
""".format(**common_args))
add_docstr(torch.diagflat,
r"""
diagflat(input, offset=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}
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]])
""".format(**common_args))
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} 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]]])
""".format(**common_args))
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}
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)
""".format(**common_args))
add_docstr(torch.div,
r"""
div(input, other, out=None) -> Tensor
Divides each element of the input ``input`` with the scalar ``other`` and
returns a new resulting tensor.
.. warning::
Integer division using div is no longer supported, and in a future release
div will perform true division as in Python 3. Use :func:`torch.true_divide`
or :func:`torch.floor_divide` (// in Python), instead.
.. math::
\text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}}}
If the :class:`torch.dtype` of ``input`` and ``other`` differ, the
:class:`torch.dtype` of the result tensor is determined following rules
described in the type promotion :ref:`documentation <type-promotion-doc>`. If
``out`` is specified, the result must be :ref:`castable <type-promotion-doc>`
to the :class:`torch.dtype` of the specified output tensor. Integral division
by zero leads to undefined behavior.
Args:
{input}
other (Number): the number to be divided to each element of ``input``
Keyword args:
{out}
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 ``input`` is divided by each element of the tensor
``other``. The resulting tensor is returned.
.. math::
\text{{out}}_i = \frac{{\text{{input}}_i}}{{\text{{other}}_i}}
The shapes of ``input`` and ``other`` must be :ref:`broadcastable
<broadcasting-semantics>`. If the :class:`torch.dtype` of ``input`` and
``other`` differ, the :class:`torch.dtype` of the result tensor is determined
following rules described in the type promotion :ref:`documentation
<type-promotion-doc>`. If ``out`` is specified, the result must be
:ref:`castable <type-promotion-doc>` to the :class:`torch.dtype` of the
specified output tensor. Integral division by zero leads to undefined behavior.
Args:
input (Tensor): the numerator tensor
other (Tensor): the denominator tensor
Keyword args:
{out}
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]])
""".format(**common_args))
add_docstr(torch.dot,
r"""
dot(input, tensor) -> 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(input, eigenvectors=False, out=None) -> (Tensor, Tensor)
Computes the eigenvalues and eigenvectors of a real square matrix.
.. note::
Since eigenvalues and eigenvectors might be complex, backward pass is supported only
for :func:`torch.symeig`
Args:
input (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 namedtuple (eigenvalues, eigenvectors) containing
- **eigenvalues** (*Tensor*): Shape :math:`(n \times 2)`. Each row is an eigenvalue of ``input``,
where the first element is the real part and the second element is the imaginary part.
The eigenvalues are not necessarily ordered.
- **eigenvectors** (*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 as follows.
If the corresponding `eigenvalues[j]` is a real number, column `eigenvectors[:, j]` is the eigenvector
corresponding to `eigenvalues[j]`.
If the corresponding `eigenvalues[j]` and `eigenvalues[j + 1]` form a complex conjugate pair, then the
true eigenvectors can be computed as
:math:`\text{true eigenvector}[j] = eigenvectors[:, j] + i \times eigenvectors[:, j + 1]`,
:math:`\text{true eigenvector}[j + 1] = eigenvectors[:, j] - i \times eigenvectors[:, 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} Must be a `ByteTensor`
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location where comparison is true
Example::
>>> torch.eq(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[ True, False],
[False, True]])
""".format(**common_args))
add_docstr(torch.equal,
r"""
equal(input, other) -> 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(input, 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
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.erf(torch.tensor([0, -1., 10.]))
tensor([ 0.0000, -0.8427, 1.0000])
""".format(**common_args))
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
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.erfc(torch.tensor([0, -1., 10.]))
tensor([ 1.0000, 1.8427, 0.0000])
""".format(**common_args))
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
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.erfinv(torch.tensor([0, 0.5, -1.]))
tensor([ 0.0000, 0.4769, -inf])
""".format(**common_args))
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}}
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.exp(torch.tensor([0, math.log(2.)]))
tensor([ 1., 2.])
""".format(**common_args))
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
""" + r"""
Args:
{input}
{out}
Example::
>>> torch.expm1(torch.tensor([0, math.log(2.)]))
tensor([ 0., 1.])
""".format(**common_args))
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
""" + r"""
Args:
{input}
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([-0.8166, 1.5308, -0.2530, -0.2091])
>>> torch.floor(a)
tensor([-1., 1., -1., -1.])
""".format(**common_args))
add_docstr(torch.floor_divide,
r"""
floor_divide(input, other, out=None) -> Tensor
Return the division of the inputs rounded down to the nearest integer. See :func:`torch.div`
for type promotion and broadcasting rules.
.. math::
\text{{out}}_i = \left\lfloor \frac{{\text{{input}}_i}}{{\text{{other}}_i}} \right\rfloor
""" + r"""
Args:
input (Tensor): the numerator tensor
other (Tensor or Scalar): the denominator
Keyword args:
{out}
Example::
>>> a = torch.tensor([4.0, 3.0])
>>> b = torch.tensor([2.0, 2.0])
>>> torch.floor_divide(a, b)
tensor([2.0, 1.0])
>>> torch.floor_divide(a, 1.4)
tensor([2.0, 2.0])
""".format(**common_args))
add_docstr(torch.fmod,
r"""
fmod(input, other, 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:`other` is a tensor, the shapes of :attr:`input` and
:attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`.
Args:
input (Tensor): the dividend
other (Tensor or float): the divisor, which may be either a number or a tensor of the same shape as the dividend
{out}
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])
""".format(**common_args))
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 * \operatorname{sgn}(\text{input}_{i})
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.
It currently accepts :attr:`ndarray` with dtypes of ``numpy.float64``,
``numpy.float32``, ``numpy.float16``, ``numpy.complex64``, ``numpy.complex128``,
``numpy.int64``, ``numpy.int32``, ``numpy.int16``, ``numpy.int8``, ``numpy.uint8``,
and ``numpy.bool``.
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}
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]])
""".format(**common_args))
add_docstr(torch.gather,
r"""
gather(input, dim, index, out=None, sparse_grad=False) -> 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`.
""" + r"""
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
sparse_grad(bool,optional): If ``True``, gradient w.r.t. :attr:`input` will be a sparse 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.gcd,
r"""
gcd(input, other, out=None) -> Tensor
Computes the element-wise greatest common divisor (GCD) of :attr:`input` and :attr:`other`.
Both :attr:`input` and :attr:`other` must have integer types.
.. note::
This defines :math:`gcd(0, 0) = 0`.
Args:
{input}
other (Tensor): the second input tensor
Keyword arguments:
{out}
Example::
>>> a = torch.tensor([5, 10, 15])
>>> b = torch.tensor([3, 4, 5])
>>> torch.gcd(a, b)
tensor([1, 2, 5])
>>> c = torch.tensor([3])
>>> torch.gcd(a, c)
tensor([1, 1, 3])
""".format(**common_args))
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 `BoolTensor`
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location where comparison is true
Example::
>>> torch.ge(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[True, True], [False, True]])
""")
add_docstr(torch.geqrf,
r"""
geqrf(input, out=None) -> (Tensor, Tensor)
This is a low-level function for calling LAPACK directly. This function
returns a namedtuple (a, tau) as defined in `LAPACK documentation for geqrf`_ .
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(input, vec2, out=None) -> Tensor
Outer product of :attr:`input` and :attr:`vec2`.
If :attr:`input` 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:
input (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.solve,
r"""
torch.solve(input, A, out=None) -> (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 namedtuple `solution, LU`.
`LU` contains `L` and `U` factors for LU factorization of `A`.
`torch.solve(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 `solution, LU`.
.. note::
Irrespective of the original strides, the returned matrices
`solution` and `LU` will be transposed, i.e. with strides like
`B.contiguous().transpose(-1, -2).stride()` and
`A.contiguous().transpose(-1, -2).stride()` respectively.
Args:
input (Tensor): input matrix :math:`B` 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.solve(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.solve(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
Returns the number of threads used for parallelizing CPU operations
""")
add_docstr(torch.get_num_interop_threads,
r"""
get_num_interop_threads() -> int
Returns the number of threads used for inter-op parallelism on CPU
(e.g. in JIT interpreter)
""")
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 `BoolTensor`
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location where comparison is true
Example::
>>> torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[False, True], [False, False]])
""")
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.
Elements lower than min and higher than max are ignored.
Args:
{input}
bins (int): number of histogram bins
min (int): lower end of the range (inclusive)
max (int): upper end of the range (inclusive)
{out}
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.])
""".format(**common_args))
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}
dim (int): the dimension in which we index
index (LongTensor): the 1-D tensor containing the indices to index
{out}
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]])
""".format(**common_args))
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).stride()`
Args:
input (Tensor): the input tensor of size :math:`(*, n, n)` where `*` is zero or more
batch dimensions
{out}
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)
""".format(**common_args))
add_docstr(torch.isinf,
r"""
Returns a new tensor with boolean elements representing if each element is `+/-INF` or not.
Complex values are infinite when their real and/or imaginary part is infinite.
Arguments:
tensor (Tensor): A tensor to check
Returns:
Tensor: ``A torch.Tensor with dtype torch.bool`` containing a True at each location of `+/-INF` elements and False otherwise
Example::
>>> torch.isinf(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')]))
tensor([False, True, False, True, False])
""")
add_docstr(torch.isclose,
r"""
isclose(input, other, rtol=1e-05, atol=1e-08, equal_nan=False) -> Tensor
Returns a new tensor with boolean elements representing if each element of
:attr:`input` is "close" to the corresponding element of :attr:`other`.
Closeness is defined as:
.. math::
\lvert \text{input} - \text{other} \rvert \leq \texttt{atol} + \texttt{rtol} \times \lvert \text{other} \rvert
""" + r"""
where :attr:`input` and :attr:`other` are finite. Where :attr:`input`
and/or :attr:`other` are nonfinite they are close if and only if
they are equal, with NaNs being considered equal to each other when
:attr:`equal_nan` is True.
Args:
input (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 (bool, optional): if ``True``, then two ``NaN`` s will be considered equal. Default: ``False``
Examples::
>>> torch.isclose(torch.tensor((1., 2, 3)), torch.tensor((1 + 1e-10, 3, 4)))
tensor([ True, False, False])
>>> torch.isclose(torch.tensor((float('inf'), 4)), torch.tensor((float('inf'), 6)), rtol=.5)
tensor([True, True])
""")
add_docstr(torch.isfinite,
r"""
Returns a new tensor with boolean elements representing if each element is `finite` or not.
Real values are finite when they are not NaN, negative infinity, or infinity.
Complex values are finite when both their real and imaginary parts are finite.
Arguments:
tensor (Tensor): A tensor to check
Returns:
Tensor: ``A torch.Tensor with dtype torch.bool`` containing a True at each location of finite elements and False otherwise
Example::
>>> torch.isfinite(torch.tensor([1, float('inf'), 2, float('-inf'), float('nan')]))
tensor([True, False, True, False, False])
""")
add_docstr(torch.isnan,
r"""
Returns a new tensor with boolean elements representing if each element is `NaN` or not.
Complex values are considered `NaN` when either their real and/or imaginary part is NaN.
Arguments:
input (Tensor): A tensor to check
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location of `NaN` elements.
Example::
>>> torch.isnan(torch.tensor([1, float('nan'), 2]))
tensor([False, True, False])
""")
add_docstr(torch.is_floating_point,
r"""
is_floating_point(input) -> (bool)
Returns True if the data type of :attr:`input` is a floating point data type i.e.,
one of ``torch.float64``, ``torch.float32`` and ``torch.float16``.
Args:
input (Tensor): the PyTorch tensor to test
""")
add_docstr(torch.is_complex,
r"""
is_complex(input) -> (bool)
Returns True if the data type of :attr:`input` is a complex data type i.e.,
one of ``torch.complex64``, and ``torch.complex128``.
Args:
input (Tensor): the PyTorch tensor to test
""")
add_docstr(torch.is_nonzero,
r"""
is_nonzero(input) -> (bool)
Returns True if the :attr:`input` is a single element tensor which is not equal to zero
after type conversions.
i.e. not equal to ``torch.tensor([0.])`` or ``torch.tensor([0])`` or
``torch.tensor([False])``.
Throws a ``RuntimeError`` if ``torch.numel() != 1`` (even in case
of sparse tensors).
Args:
input (Tensor): the PyTorch tensor to test
Example::
>>> torch.is_nonzero(torch.tensor([0.]))
False
>>> torch.is_nonzero(torch.tensor([1.5]))
True
>>> torch.is_nonzero(torch.tensor([False]))
False
>>> torch.is_nonzero(torch.tensor([3]))
True
>>> torch.is_nonzero(torch.tensor([1, 3, 5]))
Traceback (most recent call last):
...
RuntimeError: bool value of Tensor with more than one value is ambiguous
>>> torch.is_nonzero(torch.tensor([]))
Traceback (most recent call last):
...
RuntimeError: bool value of Tensor with no values is ambiguous
""")
add_docstr(torch.kthvalue,
r"""
kthvalue(input, k, dim=None, keepdim=False, out=None) -> (Tensor, LongTensor)
Returns a namedtuple ``(values, indices)`` where ``values`` is the :attr:`k` th
smallest element of each row of the :attr:`input` tensor in the given dimension
:attr:`dim`. And ``indices`` is the index location of each element found.
If :attr:`dim` is not given, the last dimension of the `input` is chosen.
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}
k (int): k for the k-th smallest element
dim (int, optional): the dimension to find the kth value along
{keepdim}
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)
torch.return_types.kthvalue(values=tensor(4.), indices=tensor(3))
>>> x=torch.arange(1.,7.).resize_(2,3)
>>> x
tensor([[ 1., 2., 3.],
[ 4., 5., 6.]])
>>> torch.kthvalue(x, 2, 0, True)
torch.return_types.kthvalue(values=tensor([[4., 5., 6.]]), indices=tensor([[1, 1, 1]]))
""".format(**single_dim_common))
add_docstr(torch.lcm,
r"""
lcm(input, other, out=None) -> Tensor
Computes the element-wise least common multiple (LCM) of :attr:`input` and :attr:`other`.
Both :attr:`input` and :attr:`other` must have integer types.
.. note::
This defines :math:`lcm(0, 0) = 0` and :math:`lcm(0, a) = 0`.
Args:
{input}
other (Tensor): the second input tensor
Keyword arguments:
{out}
Example::
>>> a = torch.tensor([5, 10, 15])
>>> b = torch.tensor([3, 4, 5])
>>> torch.lcm(a, b)
tensor([15, 20, 15])
>>> c = torch.tensor([3])
>>> torch.lcm(a, c)
tensor([15, 30, 15])
""".format(**common_args))
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 `BoolTensor`
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location where comparison is true
Example::
>>> torch.le(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[True, False], [True, True]])
""")
add_docstr(torch.lerp,
r"""
lerp(input, end, weight, out=None)
Does a linear interpolation of two tensors :attr:`start` (given by :attr:`input`) and :attr:`end` based
on a scalar or tensor :attr:`weight` and returns the resulting :attr:`out` tensor.
.. math::
\text{out}_i = \text{start}_i + \text{weight}_i \times (\text{end}_i - \text{start}_i)
""" + r"""
The shapes of :attr:`start` and :attr:`end` must be
:ref:`broadcastable <broadcasting-semantics>`. If :attr:`weight` is a tensor, then
the shapes of :attr:`weight`, :attr:`start`, and :attr:`end` must be :ref:`broadcastable <broadcasting-semantics>`.
Args:
input (Tensor): the tensor with the starting points
end (Tensor): the tensor with the ending points
weight (float or tensor): the weight for the interpolation formula
{out}
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])
>>> torch.lerp(start, end, torch.full_like(start, 0.5))
tensor([ 5.5000, 6.0000, 6.5000, 7.0000])
""".format(**common_args))
add_docstr(torch.lgamma,
r"""
lgamma(input, out=None) -> Tensor
Computes the logarithm of the gamma function on :attr:`input`.
.. math::
\text{out}_{i} = \log \Gamma(\text{input}_{i})
""" + """
Args:
{input}
{out}
Example::
>>> a = torch.arange(0.5, 2, 0.5)
>>> torch.lgamma(a)
tensor([ 0.5724, 0.0000, -0.1208])
""".format(**common_args))
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.])
>>> torch.linspace(start=-10, end=10, steps=1)
tensor([-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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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)
""" + r"""
.. note:: This function is more accurate than :func:`torch.log` for small
values of :attr:`input`
Args:
{input}
{out}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.logaddexp,
r"""
logaddexp(input, other, out=None) -> Tensor
Logarithm of the sum of exponentiations of the inputs.
Calculates pointwise :math:`\log\left(e^x + e^y\right)`. This function is useful
in statistics where the calculated probabilities of events may be so small as to
exceed the range of normal floating point numbers. In such cases the logarithm
of the calculated probability is stored. This function allows adding
probabilities stored in such a fashion.
This op should be disambiguated with :func:`torch.logsumexp` which performs a
reduction on a single tensor.
Args:
{input}
other (Tensor): the second input tensor
Keyword arguments:
{out}
Example::
>>> torch.logaddexp(torch.tensor([-1.0]), torch.tensor([-1.0, -2, -3]))
tensor([-0.3069, -0.6867, -0.8731])
>>> torch.logaddexp(torch.tensor([-100.0, -200, -300]), torch.tensor([-1.0, -2, -3]))
tensor([-1., -2., -3.])
>>> torch.logaddexp(torch.tensor([1.0, 2000, 30000]), torch.tensor([-1.0, -2, -3]))
tensor([1.1269e+00, 2.0000e+03, 3.0000e+04])
""".format(**common_args))
add_docstr(torch.logaddexp2,
r"""
logaddexp2(input, other, out=None) -> Tensor
Logarithm of the sum of exponentiations of the inputs in base-2.
Calculates pointwise :math:`\log_2\left(2^x + 2^y\right)`. See
:func:`torch.logaddexp` for more details.
Args:
{input}
other (Tensor): the second input tensor
Keyword arguments:
{out}
""".format(**common_args))
add_docstr(torch.logical_and,
r"""
logical_and(input, other, out=None) -> Tensor
Computes the element-wise logical AND of the given input tensors. Zeros are treated as ``False`` and nonzeros are
treated as ``True``.
Args:
{input}
other (Tensor): the tensor to compute AND with
{out}
Example::
>>> torch.logical_and(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
tensor([ True, False, False])
>>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
>>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
>>> torch.logical_and(a, b)
tensor([False, False, True, False])
>>> torch.logical_and(a.double(), b.double())
tensor([False, False, True, False])
>>> torch.logical_and(a.double(), b)
tensor([False, False, True, False])
>>> torch.logical_and(a, b, out=torch.empty(4, dtype=torch.bool))
tensor([False, False, True, False])
""".format(**common_args))
add_docstr(torch.logical_not,
r"""
logical_not(input, out=None) -> Tensor
Computes the element-wise logical NOT of the given input tensor. If not specified, the output tensor will have the bool
dtype. If the input tensor is not a bool tensor, zeros are treated as ``False`` and non-zeros are treated as ``True``.
Args:
{input}
{out}
Example::
>>> torch.logical_not(torch.tensor([True, False]))
tensor([False, True])
>>> torch.logical_not(torch.tensor([0, 1, -10], dtype=torch.int8))
tensor([ True, False, False])
>>> torch.logical_not(torch.tensor([0., 1.5, -10.], dtype=torch.double))
tensor([ True, False, False])
>>> torch.logical_not(torch.tensor([0., 1., -10.], dtype=torch.double), out=torch.empty(3, dtype=torch.int16))
tensor([1, 0, 0], dtype=torch.int16)
""".format(**common_args))
add_docstr(torch.logical_or,
r"""
logical_or(input, other, out=None) -> Tensor
Computes the element-wise logical OR of the given input tensors. Zeros are treated as ``False`` and nonzeros are
treated as ``True``.
Args:
{input}
other (Tensor): the tensor to compute OR with
{out}
Example::
>>> torch.logical_or(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
tensor([ True, False, True])
>>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
>>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
>>> torch.logical_or(a, b)
tensor([ True, True, True, False])
>>> torch.logical_or(a.double(), b.double())
tensor([ True, True, True, False])
>>> torch.logical_or(a.double(), b)
tensor([ True, True, True, False])
>>> torch.logical_or(a, b, out=torch.empty(4, dtype=torch.bool))
tensor([ True, True, True, False])
""".format(**common_args))
add_docstr(torch.logical_xor,
r"""
logical_xor(input, other, out=None) -> Tensor
Computes the element-wise logical XOR of the given input tensors. Zeros are treated as ``False`` and nonzeros are
treated as ``True``.
Args:
{input}
other (Tensor): the tensor to compute XOR with
{out}
Example::
>>> torch.logical_xor(torch.tensor([True, False, True]), torch.tensor([True, False, False]))
tensor([False, False, True])
>>> a = torch.tensor([0, 1, 10, 0], dtype=torch.int8)
>>> b = torch.tensor([4, 0, 1, 0], dtype=torch.int8)
>>> torch.logical_xor(a, b)
tensor([ True, True, False, False])
>>> torch.logical_xor(a.double(), b.double())
tensor([ True, True, False, False])
>>> torch.logical_xor(a.double(), b)
tensor([ True, True, False, False])
>>> torch.logical_xor(a, b, out=torch.empty(4, dtype=torch.bool))
tensor([ True, True, False, False])
""".format(**common_args))
add_docstr(torch.logspace,
r"""
logspace(start, end, steps=100, base=10.0, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) -> Tensor
Returns a one-dimensional tensor of :attr:`steps` points
logarithmically spaced with base :attr:`base` between
:math:`{{\text{{base}}}}^{{\text{{start}}}}` and :math:`{{\text{{base}}}}^{{\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``.
base (float): base of the logarithm function. Default: ``10.0``.
{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])
>>> torch.logspace(start=0.1, end=1.0, steps=1)
tensor([1.2589])
>>> torch.logspace(start=2, end=2, steps=1, base=2)
tensor([4.0])
""".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}})
{keepdim_details}
Args:
{input}
{dim}
{keepdim}
{out}
Example::
>>> a = torch.randn(3, 3)
>>> torch.logsumexp(a, 1)
tensor([ 0.8442, 1.4322, 0.8711])
""".format(**multi_dim_common))
add_docstr(torch.lstsq,
r"""
lstsq(input, 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:`lstsq` solves the least-squares problem:
.. math::
\begin{array}{ll}
\min_X & \|AX-B\|_2.
\end{array}
If :math:`m < n`, :func:`lstsq` 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.
.. note::
The case when :math:`m < n` is not supported on the GPU.
Args:
input (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 namedtuple (solution, QR) containing:
- **solution** (*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.lstsq(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.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 `BoolTensor`
Returns:
Tensor: A `torch.BoolTensor` containing a True at each location where comparison is true
Example::
>>> torch.lt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[False, False], [True, False]])
""")
add_docstr(torch.lu_solve,
r"""
lu_solve(input, LU_data, LU_pivots, out=None) -> Tensor
Returns the LU solve of the linear system :math:`Ax = b` using the partially pivoted
LU factorization of A from :meth:`torch.lu`.
Arguments:
b (Tensor): the RHS tensor of size :math:`(*, m, k)`, where :math:`*`
is zero or more batch dimensions.
LU_data (Tensor): the pivoted LU factorization of A from :meth:`torch.lu` of size :math:`(*, m, m)`,
where :math:`*` is zero or more batch dimensions.
LU_pivots (IntTensor): the pivots of the LU factorization from :meth:`torch.lu` of size :math:`(*, m)`,
where :math:`*` is zero or more batch dimensions.
The batch dimensions of :attr:`LU_pivots` must be equal to the batch dimensions of
:attr:`LU_data`.
{out}
Example::
>>> A = torch.randn(2, 3, 3)
>>> b = torch.randn(2, 3, 1)
>>> A_LU = torch.lu(A)
>>> x = torch.lu_solve(b, *A_LU)
>>> torch.norm(torch.bmm(A, x) - b)
tensor(1.00000e-07 *
2.8312)
""".format(**common_args))
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 boolean mask :attr:`mask` which is a `BoolTensor`.
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}
mask (BoolTensor): the tensor containing the binary mask to index with
{out}
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([[False, False, False, False],
[False, True, True, True],
[False, False, False, True]])
>>> torch.masked_select(x, mask)
tensor([ 1.2252, 0.5002, 0.6248, 2.0139])
""".format(**common_args))
add_docstr(torch.matrix_rank,
r"""
matrix_rank(input, tol=None, 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}
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]]])
""".format(**common_args))
add_docstr(torch.max,
r"""
max(input) -> Tensor
Returns the maximum value of all elements in the ``input`` tensor.
.. warning::
This function produces deterministic (sub)gradients unlike ``max(dim=0)``
Args:
{input}
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 a namedtuple ``(values, indices)`` where ``values`` is the maximum
value of each row of the :attr:`input` tensor in the given dimension
:attr:`dim`. And ``indices`` is the index location of each maximum value found
(argmax).
.. warning::
``indices`` does not necessarily contain the first occurrence of each
maximal value found, unless it is unique.
The exact implementation details are device-specific.
Do not expect the same result when run on CPU and GPU in general.
For the same reason do not expect the gradients to be deterministic.
If ``keepdim`` is ``True``, the output tensors are of the same size
as ``input`` except in the dimension ``dim`` where they are of size 1.
Otherwise, ``dim`` is squeezed (see :func:`torch.squeeze`), resulting
in the output tensors having 1 fewer dimension than ``input``.
Args:
{input}
{dim}
{keepdim} Default: ``False``.
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)
torch.return_types.max(values=tensor([0.8475, 1.1949, 1.5717, 1.0036]), indices=tensor([3, 0, 0, 1]))
.. function:: max(input, other, out=None) -> Tensor
Each element of the tensor ``input`` is compared with the corresponding
element of the tensor ``other`` and an element-wise maximum is taken.
The shapes of ``input`` and ``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}
other (Tensor): the second input tensor
{out}
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])
""".format(**single_dim_common))
add_docstr(torch.argmax,
r"""
argmax(input) -> LongTensor
Returns the indices of the maximum value of all elements in the :attr:`input` tensor.
This is the second value returned by :meth:`torch.max`. See its
documentation for the exact semantics of this method.
Args:
{input}
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
[-0.7401, -0.8805, -0.3402, -1.1936],
[ 0.4907, -1.3948, -1.0691, -0.3132],
[-1.6092, 0.5419, -0.2993, 0.3195]])
>>> torch.argmax(a)
tensor(0)
.. function:: argmax(input, dim, keepdim=False) -> LongTensor
Returns the indices of the maximum values of a tensor across a dimension.
This is the second value returned by :meth:`torch.max`. See its
documentation for the exact semantics of this method.
Args:
{input}
{dim} If ``None``, the argmax of the flattened input is returned.
{keepdim} Ignored if ``dim=None``.
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 1.3398, 0.2663, -0.2686, 0.2450],
[-0.7401, -0.8805, -0.3402, -1.1936],
[ 0.4907, -1.3948, -1.0691, -0.3132],
[-1.6092, 0.5419, -0.2993, 0.3195]])
>>> torch.argmax(a, dim=1)
tensor([ 0, 2, 0, 1])
""".format(**single_dim_common))
add_docstr(torch.mean,
r"""
mean(input) -> Tensor
Returns the mean value of all elements in the :attr:`input` tensor.
Args:
{input}
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.
{keepdim_details}
Args:
{input}
{dim}
{keepdim}
{out}
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]])
""".format(**multi_dim_common))
add_docstr(torch.median,
r"""
median(input) -> Tensor
Returns the median value of all elements in the :attr:`input` tensor.
.. warning::
This function produces deterministic (sub)gradients unlike ``median(dim=0)``
Args:
{input}
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, out=None) -> (Tensor, LongTensor)
Returns a namedtuple ``(values, indices)`` where ``values`` is the median
value of each row of the :attr:`input` tensor in the given dimension
:attr:`dim`. And ``indices`` is the index location of each median value found.
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`.
.. warning::
``indices`` does not necessarily contain the first occurrence of each
median value found, unless it is unique.
The exact implementation details are device-specific.
Do not expect the same result when run on CPU and GPU in general.
For the same reason do not expect the gradients to be deterministic.
Args:
{input}
{dim}
{keepdim}
out (tuple, optional): the result tuple of two output tensors (max, max_indices)
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)
torch.return_types.median(values=tensor([-0.3982, 0.2270, 0.2488, 0.4742]), indices=tensor([1, 4, 4, 3]))
""".format(**single_dim_common))
add_docstr(torch.min,
r"""
min(input) -> Tensor
Returns the minimum value of all elements in the :attr:`input` tensor.
.. warning::
This function produces deterministic (sub)gradients unlike ``min(dim=0)``
Args:
{input}
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 a namedtuple ``(values, indices)`` where ``values`` is the minimum
value of each row of the :attr:`input` tensor in the given dimension
:attr:`dim`. And ``indices`` is the index location of each minimum value found
(argmin).
.. warning::
``indices`` does not necessarily contain the first occurrence of each
minimal value found, unless it is unique.
The exact implementation details are device-specific.
Do not expect the same result when run on CPU and GPU in general.
For the same reason do not expect the gradients to be deterministic.
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}
{dim}
{keepdim}
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)
torch.return_types.min(values=tensor([-1.1899, -1.4644, 0.0384, -0.1153]), indices=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}
other (Tensor): the second input tensor
{out}
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])
""".format(**single_dim_common))
add_docstr(torch.argmin,
r"""
argmin(input) -> LongTensor
Returns the indices of the minimum value of all elements in the :attr:`input` tensor.
This is the second value returned by :meth:`torch.min`. See its
documentation for the exact semantics of this method.
Args:
{input}
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.1139, 0.2254, -0.1381, 0.3687],
[ 1.0100, -1.1975, -0.0102, -0.4732],
[-0.9240, 0.1207, -0.7506, -1.0213],
[ 1.7809, -1.2960, 0.9384, 0.1438]])
>>> torch.argmin(a)
tensor(13)
.. function:: argmin(input, dim, keepdim=False, out=None) -> LongTensor
Returns the indices of the minimum values of a tensor across a dimension.
This is the second value returned by :meth:`torch.min`. See its
documentation for the exact semantics of this method.
Args:
{input}
{dim} If ``None``, the argmin of the flattened input is returned.
{keepdim} Ignored if ``dim=None``.
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.1139, 0.2254, -0.1381, 0.3687],
[ 1.0100, -1.1975, -0.0102, -0.4732],
[-0.9240, 0.1207, -0.7506, -1.0213],
[ 1.7809, -1.2960, 0.9384, 0.1438]])
>>> torch.argmin(a, dim=1)
tensor([ 2, 1, 3, 1])
""".format(**single_dim_common))
add_docstr(torch.mm,
r"""
mm(input, mat2, out=None) -> Tensor
Performs a matrix multiplication of the matrices :attr:`input` and :attr:`mat2`.
If :attr:`input` 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:
input (Tensor): the first matrix to be multiplied
mat2 (Tensor): the second matrix to be multiplied
{out}
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]])
""".format(**common_args))
add_docstr(torch.matmul,
r"""
matmul(input, other, 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:`input` is a
:math:`(j \times 1 \times n \times m)` tensor and :attr:`other` 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:
input (Tensor): the first tensor to be multiplied
other (Tensor): the second tensor to be multiplied
{out}
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])
""".format(**common_args))
add_docstr(torch.mode,
r"""
mode(input, dim=-1, keepdim=False, out=None) -> (Tensor, LongTensor)
Returns a namedtuple ``(values, indices)`` where ``values`` is the mode
value of each row of the :attr:`input` tensor in the given dimension
:attr:`dim`, i.e. a value which appears most often
in that row, and ``indices`` is the index location of each mode value found.
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}
{dim}
{keepdim}
out (tuple, optional): the result tuple of two output tensors (values, indices)
Example::
>>> a = torch.randint(10, (5,))
>>> a
tensor([6, 5, 1, 0, 2])
>>> b = a + (torch.randn(50, 1) * 5).long()
>>> torch.mode(b, 0)
torch.return_types.mode(values=tensor([6, 5, 1, 0, 2]), indices=tensor([2, 2, 2, 2, 2]))
""".format(**single_dim_common))
add_docstr(torch.mul,
r"""
mul(input, other, out=None)
Multiplies each element of the input :attr:`input` with the scalar
:attr:`other` and returns a new resulting tensor.
.. math::
\text{out}_i = \text{other} \times \text{input}_i
""" + r"""
If :attr:`input` is of type `FloatTensor` or `DoubleTensor`, :attr:`other`
should be a real number, otherwise it should be an integer
Args:
{input}
value (Number): the number to be multiplied to each element of :attr:`input`
{out}
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 the corresponding
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
""" + r"""
Args:
input (Tensor): the first multiplicand tensor
other (Tensor): the second multiplicand tensor
{out}
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]])
""".format(**common_args))
add_docstr(torch.multinomial,
r"""
multinomial(input, num_samples, replacement=False, *, generator=None, 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.
.. note::
When drawn without replacement, :attr:`num_samples` must be lower than
number of non-zero elements in :attr:`input` (or the min number of non-zero
elements in each row 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
{generator}
{out}
Example::
>>> weights = torch.tensor([0, 10, 3, 0], dtype=torch.float) # create a tensor of weights
>>> torch.multinomial(weights, 2)
tensor([1, 2])
>>> torch.multinomial(weights, 4) # ERROR!
RuntimeError: invalid argument 2: invalid multinomial distribution (with replacement=False,
not enough non-negative category to sample) at ../aten/src/TH/generic/THTensorRandom.cpp:320
>>> torch.multinomial(weights, 4, replacement=True)
tensor([ 2, 1, 1, 1])
""".format(**common_args))
add_docstr(torch.mv,
r"""
mv(input, vec, out=None) -> Tensor
Performs a matrix-vector product of the matrix :attr:`input` and the vector
:attr:`vec`.
If :attr:`input` 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:
input (Tensor): matrix to be multiplied
vec (Tensor): vector to be multiplied
{out}
Example::
>>> mat = torch.randn(2, 3)
>>> vec = torch.randn(3)
>>> torch.mv(mat, vec)
tensor([ 1.0404, -0.6361])
""".format(**common_args))
add_docstr(torch.mvlgamma,
r"""
mvlgamma(input, p) -> Tensor
Computes the `multivariate log-gamma function
<https://en.wikipedia.org/wiki/Multivariate_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)}{4}` and :math:`\Gamma(\cdot)` is the Gamma function.
All elements must be greater than :math:`\frac{p - 1}{2}`, otherwise an error would be 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, dim, 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
dim (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 `BoolTensor`
Returns:
Tensor: A ``torch.BoolTensor`` containing a True at each location where comparison is true.
Example::
>>> torch.ne(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]]))
tensor([[False, True], [True, False]])
""")
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}
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.nonzero,
r"""
nonzero(input, *, out=None, as_tuple=False) -> LongTensor or tuple of LongTensors
.. note::
:func:`torch.nonzero(..., as_tuple=False) <torch.nonzero>` (default) returns a
2-D tensor where each row is the index for a nonzero value.
:func:`torch.nonzero(..., as_tuple=True) <torch.nonzero>` returns a tuple of 1-D
index tensors, allowing for advanced indexing, so ``x[x.nonzero(as_tuple=True)]``
gives all nonzero values of tensor ``x``. Of the returned tuple, each index tensor
contains nonzero indices for a certain dimension.
See below for more details on the two behaviors.
**When** :attr:`as_tuple` **is ``False`` (default)**:
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`. The result is sorted lexicographically, with
the last index changing the fastest (C-style).
If :attr:`input` has :math:`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.
**When** :attr:`as_tuple` **is ``True``**:
Returns a tuple of 1-D tensors, one for each dimension in :attr:`input`,
each containing the indices (in that dimension) of all non-zero elements of
:attr:`input` .
If :attr:`input` has :math:`n` dimensions, then the resulting tuple contains :math:`n`
tensors of size :math:`z`, where :math:`z` is the total number of
non-zero elements in the :attr:`input` tensor.
As a special case, when :attr:`input` has zero dimensions and a nonzero scalar
value, it is treated as a one-dimensional tensor with one element.
Args:
{input}
out (LongTensor, optional): the output tensor containing indices
Returns:
LongTensor or tuple of LongTensor: If :attr:`as_tuple` is ``False``, the output
tensor containing indices. If :attr:`as_tuple` is ``True``, one 1-D tensor for
each dimension, containing the indices of each nonzero element along that
dimension.
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]])
>>> torch.nonzero(torch.tensor([1, 1, 1, 0, 1]), as_tuple=True)
(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]]), as_tuple=True)
(tensor([0, 1, 2, 3]), tensor([0, 1, 2, 3]))
>>> torch.nonzero(torch.tensor(5), as_tuple=True)
(tensor([0]),)
""".format(**common_args))
add_docstr(torch.normal,
r"""
normal(mean, std, *, generator=None, 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
{generator}
{out}
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}
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])
.. function:: normal(mean, std, size, *, out=None) -> Tensor
Similar to the function above, but the means and standard deviations are shared
among all drawn elements. The resulting tensor has size given by :attr:`size`.
Args:
mean (float): the mean for all distributions
std (float): the standard deviation for all distributions
size (int...): a sequence of integers defining the shape of the output tensor.
{out}
Example::
>>> torch.normal(2, 3, size=(1, 4))
tensor([[-1.3987, -1.9544, 3.6048, 0.7909]])
""".format(**common_args))
add_docstr(torch.numel,
r"""
numel(input) -> int
Returns the total number of elements in the :attr:`input` tensor.
Args:
{input}
Example::
>>> a = torch.randn(1, 2, 3, 4, 5)
>>> torch.numel(a)
120
>>> a = torch.zeros(4,4)
>>> torch.numel(a)
16
""".format(**common_args))
add_docstr(torch.ones,
r"""
ones(*size, 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:`size`.
Args:
size (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, memory_format=torch.preserve_format) -> 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}
{memory_format}
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(input, input2) -> Tensor
Computes the orthogonal matrix `Q` of a QR factorization, from the `(input, input2)`
tuple returned by :func:`torch.geqrf`.
This directly calls the underlying LAPACK function `?orgqr`.
See `LAPACK documentation for orgqr`_ for further details.
Args:
input (Tensor): the `a` from :func:`torch.geqrf`.
input2 (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(input, input2, input3, left=True, transpose=False) -> Tensor
Multiplies `mat` (given by :attr:`input3`) by the orthogonal `Q` matrix of the QR factorization
formed by :func:`torch.geqrf` that is represented by `(a, tau)` (given by (:attr:`input`, :attr:`input2`)).
This directly calls the underlying LAPACK function `?ormqr`.
See `LAPACK documentation for ormqr`_ for further details.
Args:
input (Tensor): the `a` from :func:`torch.geqrf`.
input2 (Tensor): the `tau` from :func:`torch.geqrf`.
input3 (Tensor): the matrix to be multiplied.
.. _LAPACK documentation for ormqr:
https://software.intel.com/en-us/mkl-developer-reference-c-ormqr
""")
add_docstr(torch.poisson,
r"""
poisson(input *, generator=None) -> Tensor
Returns a tensor of the same size as :attr:`input` with each element
sampled from a Poisson distribution with rate parameter given by the corresponding
element in :attr:`input` i.e.,
.. math::
\text{{out}}_i \sim \text{{Poisson}}(\text{{input}}_i)
Args:
input (Tensor): the input tensor containing the rates of the Poisson distribution
{generator}
Example::
>>> rates = torch.rand(4, 4) * 5 # rate parameter between 0 and 5
>>> torch.poisson(rates)
tensor([[9., 1., 3., 5.],
[8., 6., 6., 0.],
[0., 4., 5., 3.],
[2., 1., 4., 2.]])
""".format(**common_args))
add_docstr(torch.polygamma,
r"""
polygamma(n, input, out=None) -> Tensor
Computes the :math:`n^{th}` derivative of the digamma function on :attr:`input`.
:math:`n \geq 0` is called the order of the polygamma function.
.. math::
\psi^{(n)}(x) = \frac{d^{(n)}}{dx^{(n)}} \psi(x)
.. note::
This function is not implemented for :math:`n \geq 2`.
""" + """
Args:
n (int): the order of the polygamma function
{input}
{out}
Example::
>>> a = torch.tensor([1, 0.5])
>>> torch.polygamma(1, a)
tensor([1.64493, 4.9348])
""".format(**common_args))
add_docstr(torch.pow,
r"""
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}
""" + r"""
When :attr:`exponent` is a tensor, the shapes of :attr:`input`
and :attr:`exponent` must be :ref:`broadcastable <broadcasting-semantics>`.
Args:
{input}
exponent (float or tensor): the exponent value
{out}
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(self, exponent, out=None) -> Tensor
:attr:`self` is a scalar ``float`` value, and :attr:`exponent` is a tensor.
The returned tensor :attr:`out` is of the same shape as :attr:`exponent`
The operation applied is:
.. math::
\text{{out}}_i = \text{{self}} ^ {{\text{{exponent}}_i}}
Args:
self (float): the scalar base value for the power operation
exponent (Tensor): the exponent tensor
{out}
Example::
>>> exp = torch.arange(1., 5.)
>>> base = 2
>>> torch.pow(base, exp)
tensor([ 2., 4., 8., 16.])
""".format(**common_args))
add_docstr(torch.prod,
r"""
prod(input, dtype=None) -> Tensor
Returns the product of all elements in the :attr:`input` tensor.
Args:
{input}
{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`.
{keepdim_details}
Args:
{input}
{dim}
{keepdim}
{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(**single_dim_common))
add_docstr(torch.promote_types,
r"""
promote_types(type1, type2) -> dtype
Returns the :class:`torch.dtype` with the smallest size and scalar kind that is
not smaller nor of lower kind than either `type1` or `type2`. See type promotion
:ref:`documentation <type-promotion-doc>` for more information on the type
promotion logic.
Args:
type1 (:class:`torch.dtype`)
type2 (:class:`torch.dtype`)
Example::
>>> torch.promote_types(torch.int32, torch.float32))
torch.float32
>>> torch.promote_types(torch.uint8, torch.long)
torch.long
""")
add_docstr(torch.qr,
r"""
qr(input, some=True, out=None) -> (Tensor, Tensor)
Computes the QR decomposition of a matrix or a batch of matrices :attr:`input`,
and returns a namedtuple (Q, R) of tensors such that :math:`\text{input} = Q R`
with :math:`Q` being an orthogonal matrix or batch of orthogonal matrices and
:math:`R` being an upper triangular matrix or batch of upper triangular matrices.
If :attr:`some` is ``True``, then this function returns the thin (reduced) QR factorization.
Otherwise, if :attr:`some` is ``False``, this function returns the complete 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.
Args:
input (Tensor): the input tensor of size :math:`(*, m, n)` where `*` is zero or more
batch dimensions consisting of matrices of dimension :math:`m \times n`.
some (bool, optional): Set to ``True`` for reduced QR decomposition and ``False`` for
complete QR decomposition.
out (tuple, optional): tuple of `Q` and `R` tensors
satisfying :code:`input = torch.matmul(Q, R)`.
The dimensions of `Q` and `R` are :math:`(*, m, k)` and :math:`(*, k, n)`
respectively, where :math:`k = \min(m, n)` if :attr:`some:` is ``True`` and
:math:`k = m` otherwise.
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.]])
>>> a = torch.randn(3, 4, 5)
>>> q, r = torch.qr(a, some=False)
>>> torch.allclose(torch.matmul(q, r), a)
True
>>> torch.allclose(torch.matmul(q.transpose(-2, -1), q), torch.eye(5))
True
""")
add_docstr(torch.rad2deg,
r"""
rad2deg(input, out=None) -> Tensor
Returns a new tensor with each of the elements of :attr:`input`
converted from angles in radians to degrees.
Args:
{input}
Keyword arguments:
{out}
Example::
>>> a = torch.tensor([[3.142, -3.142], [6.283, -6.283], [1.570, -1.570]])
>>> torch.rad2deg(a)
tensor([[ 180.0233, -180.0233],
[ 359.9894, -359.9894],
[ 89.9544, -89.9544]])
""".format(**common_args))
add_docstr(torch.deg2rad,
r"""
deg2rad(input, out=None) -> Tensor
Returns a new tensor with each of the elements of :attr:`input`
converted from angles in degrees to radians.
Args:
{input}
Keyword arguments:
{out}
Example::
>>> a = torch.tensor([[180.0, -180.0], [360.0, -360.0], [90.0, -90.0]])
>>> torch.deg2rad(a)
tensor([[ 3.1416, -3.1416],
[ 6.2832, -6.2832],
[ 1.5708, -1.5708]])
""".format(**common_args))
add_docstr(torch.rand,
r"""
rand(*size, 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:`size`.
Args:
size (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, memory_format=torch.preserve_format) -> 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}
{memory_format}
""".format(**factory_like_common_args))
add_docstr(torch.randint,
"""
randint(low=0, high, size, \\*, generator=None, 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.
{generator}
{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,
"""
randint_like(input, low=0, high, dtype=None, layout=torch.strided, device=None, requires_grad=False, \
memory_format=torch.preserve_format) -> 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}
{memory_format}
""".format(**factory_like_common_args))
add_docstr(torch.randn,
r"""
randn(*size, 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:`size`.
Args:
size (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, memory_format=torch.preserve_format) -> 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}
{memory_format}
""".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, pin_memory=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.as_tensor`.
.. 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}
{pin_memory}
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} 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.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\lceil \frac{\text{end} - \text{start}}{\text{step}} \right\rceil`
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, other, 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 divisor :attr:`other`.
When :attr:`other` is a tensor, the shapes of :attr:`input` and
:attr:`other` must be :ref:`broadcastable <broadcasting-semantics>`.
Args:
input (Tensor): the dividend
other (Tensor or float): the divisor that may be either a number or a
Tensor of the same shape as the dividend
{out}
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()``.
""".format(**common_args))
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}
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}
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]])
""".format(**common_args))
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.result_type,
r"""
result_type(tensor1, tensor2) -> dtype
Returns the :class:`torch.dtype` that would result from performing an arithmetic
operation on the provided input tensors. See type promotion :ref:`documentation <type-promotion-doc>`
for more information on the type promotion logic.
Args:
tensor1 (Tensor or Number): an input tensor or number
tensor2 (Tensor or Number): an input tensor or number
Example::
>>> torch.result_type(torch.tensor([1, 2], dtype=torch.int), 1.0)
torch.float32
>>> torch.result_type(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor(1))
torch.uint8
""")
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}
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([ 0.9920, 0.6077, 0.9734, -1.0362])
>>> torch.round(a)
tensor([ 1., 1., 1., -1.])
""".format(**common_args))
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}}}
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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 threads used for intraop parallelism on CPU.
WARNING:
To ensure that the correct number of threads is used, set_num_threads
must be called before running eager, JIT or autograd code.
""")
add_docstr(torch.set_num_interop_threads,
r"""
set_num_interop_threads(int)
Sets the number of threads used for interop parallelism
(e.g. in JIT interpreter) on CPU.
WARNING: Can only be called once and before any inter-op parallel work
is started (e.g. JIT execution).
""")
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}}}
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.logit,
r"""
logit(input, eps=None, out=None) -> Tensor
Returns a new tensor with the logit of the elements of :attr:`input`.
:attr:`input` is clamped to [eps, 1 - eps] when eps is not None.
When eps is None and :attr:`input` < 0 or :attr:`input` > 1, the function will yields NaN.
.. math::
y_{i} = \ln(\frac{z_{i}}{1 - z_{i}}) \\
z_{i} = \begin{cases}
x_{i} & \text{if eps is None} \\
\text{eps} & \text{if } x_{i} < \text{eps} \\
x_{i} & \text{if } \text{eps} \leq x_{i} \leq 1 - \text{eps} \\
1 - \text{eps} & \text{if } x_{i} > 1 - \text{eps}
\end{cases}
""" + r"""
Args:
{input}
eps (float, optional): the epsilon for input clamp bound. Default: ``None``
{out}
Example::
>>> a = torch.rand(5)
>>> a
tensor([0.2796, 0.9331, 0.6486, 0.1523, 0.6516])
>>> torch.logit(a, eps=1e-6)
tensor([-0.9466, 2.6352, 0.6131, -1.7169, 0.6261])
""".format(**common_args))
add_docstr(torch.sign,
r"""
sign(input, out=None) -> Tensor
Returns a new tensor with the signs of the elements of :attr:`input`.
.. math::
\text{out}_{i} = \operatorname{sgn}(\text{input}_{i})
""" + r"""
Args:
{input}
{out}
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.])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.sort,
r"""
sort(input, dim=-1, 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 namedtuple of (values, indices) is returned, where the `values` are the
sorted values and `indices` are the indices of the elements in the original
`input` tensor.
Args:
{input}
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]])
""".format(**common_args))
add_docstr(torch.argsort,
r"""
argsort(input, dim=-1, descending=False) -> LongTensor
Returns the indices that sort a tensor along a given dimension in ascending
order by value.
This is the second value returned by :meth:`torch.sort`. See its documentation
for the exact semantics of this method.
Args:
{input}
dim (int, optional): the dimension to sort along
descending (bool, optional): controls the sorting order (ascending or descending)
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.0785, 1.5267, -0.8521, 0.4065],
[ 0.1598, 0.0788, -0.0745, -1.2700],
[ 1.2208, 1.0722, -0.7064, 1.2564],
[ 0.0669, -0.2318, -0.8229, -0.9280]])
>>> torch.argsort(a, dim=1)
tensor([[2, 0, 3, 1],
[3, 2, 1, 0],
[2, 1, 0, 3],
[3, 2, 1, 0]])
""".format(**common_args))
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}
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
""".format(**factory_common_args))
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}}
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
add_docstr(torch.square,
r"""
square(input, out=None) -> Tensor
Returns a new tensor with the square of the elements of :attr:`input`.
Args:
{input}
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([-2.0755, 1.0226, 0.0831, 0.4806])
>>> torch.square(a)
tensor([ 4.3077, 1.0457, 0.0069, 0.2310])
""".format(**common_args))
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.
.. warning:: If the tensor has a batch dimension of size 1, then `squeeze(input)`
will also remove the batch dimension, which can lead to unexpected
errors.
Args:
{input}
dim (int, optional): if given, the input will be squeezed only in
this dimension
{out}
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])
""".format(**common_args))
add_docstr(torch.std,
r"""
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}
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, unbiased=True, keepdim=False, out=None) -> Tensor
Returns the standard-deviation of each row of the :attr:`input` tensor in the
dimension :attr:`dim`. If :attr:`dim` is a list of dimensions,
reduce over all of them.
{keepdim_details}
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}
{dim}
unbiased (bool): whether to use the unbiased estimation or not
{keepdim}
{out}
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])
""".format(**multi_dim_common))
add_docstr(torch.std_mean,
r"""
std_mean(input, unbiased=True) -> (Tensor, Tensor)
Returns the standard-deviation and mean 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}
unbiased (bool): whether to use the unbiased estimation or not
Example::
>>> a = torch.randn(1, 3)
>>> a
tensor([[0.3364, 0.3591, 0.9462]])
>>> torch.std_mean(a)
(tensor(0.3457), tensor(0.5472))
.. function:: std_mean(input, dim, unbiased=True, keepdim=False) -> (Tensor, Tensor)
Returns the standard-deviation and mean of each row of the :attr:`input` tensor in the
dimension :attr:`dim`. If :attr:`dim` is a list of dimensions,
reduce over all of them.
{keepdim_details}
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}
{dim}
unbiased (bool): whether to use the unbiased estimation or not
{keepdim}
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[ 0.5648, -0.5984, -1.2676, -1.4471],
[ 0.9267, 1.0612, 1.1050, -0.6014],
[ 0.0154, 1.9301, 0.0125, -1.0904],
[-1.9711, -0.7748, -1.3840, 0.5067]])
>>> torch.std_mean(a, 1)
(tensor([0.9110, 0.8197, 1.2552, 1.0608]), tensor([-0.6871, 0.6229, 0.2169, -0.9058]))
""".format(**multi_dim_common))
add_docstr(torch.sum,
r"""
sum(input, dtype=None) -> Tensor
Returns the sum of all elements in the :attr:`input` tensor.
Args:
{input}
{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.
{keepdim_details}
Args:
{input}
{dim}
{keepdim}
{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(**multi_dim_common))
add_docstr(torch.svd,
r"""
svd(input, some=True, compute_uv=True, out=None) -> (Tensor, Tensor, Tensor)
This function returns a namedtuple ``(U, S, V)`` which is the singular value
decomposition of a input real matrix or batches of real matrices :attr:`input` such that
:math:`input = U \times diag(S) \times V^T`.
If :attr:`some` is ``True`` (default), the method returns the reduced singular value decomposition
i.e., if the last two dimensions of :attr:`input` are ``m`` and ``n``, then 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:`(m \times m)` and :math:`(n \times n)` respectively. :attr:`some` will be ignored here.
.. note:: The singular values are returned in descending order. If :attr:`input` is a batch of matrices,
then the singular values of each matrix in the batch is returned in descending order.
.. 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 :code:`U.contiguous().transpose(-2, -1).stride()`
.. 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 :code:`U[..., :, min(m, n):]`
and :code:`V[..., :, min(m, n):]` 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 tensor of size :math:`(*, m, n)` where `*` is zero or more
batch dimensions consisting of :math:`m \times n` matrices.
some (bool, optional): controls the shape of returned `U` and `V`
compute_uv (bool, optional): option whether to compute `U` and `V` or not
out (tuple, optional): the output tuple of tensors
Example::
>>> a = torch.randn(5, 3)
>>> a
tensor([[ 0.2364, -0.7752, 0.6372],
[ 1.7201, 0.7394, -0.0504],
[-0.3371, -1.0584, 0.5296],
[ 0.3550, -0.4022, 1.5569],
[ 0.2445, -0.0158, 1.1414]])
>>> u, s, v = torch.svd(a)
>>> u
tensor([[ 0.4027, 0.0287, 0.5434],
[-0.1946, 0.8833, 0.3679],
[ 0.4296, -0.2890, 0.5261],
[ 0.6604, 0.2717, -0.2618],
[ 0.4234, 0.2481, -0.4733]])
>>> s
tensor([2.3289, 2.0315, 0.7806])
>>> v
tensor([[-0.0199, 0.8766, 0.4809],
[-0.5080, 0.4054, -0.7600],
[ 0.8611, 0.2594, -0.4373]])
>>> torch.dist(a, torch.mm(torch.mm(u, torch.diag(s)), v.t()))
tensor(8.6531e-07)
>>> a_big = torch.randn(7, 5, 3)
>>> u, s, v = torch.svd(a_big)
>>> torch.dist(a_big, torch.matmul(torch.matmul(u, torch.diag_embed(s)), v.transpose(-2, -1)))
tensor(2.6503e-06)
""")
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` or a batch of real symmetric matrices,
represented by a namedtuple (eigenvalues, eigenvectors).
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
both eigenvectors and eigenvalues 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:: The eigenvalues are returned in ascending order. If :attr:`input` is a batch of matrices,
then the eigenvalues of each matrix in the batch is returned in ascending order.
.. note:: Irrespective of the original strides, the returned matrix `V` will
be transposed, i.e. with strides `V.contiguous().transpose(-1, -2).stride()`.
.. note:: Extra care needs to be taken when backward through outputs. Such
operation is really only stable when all eigenvalues are distinct.
Otherwise, ``NaN`` can appear as the gradients are not properly defined.
Args:
input (Tensor): the input tensor of size :math:`(*, n, n)` where `*` is zero or more
batch dimensions consisting of symmetric matrices.
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 namedtuple (eigenvalues, eigenvectors) containing
- **eigenvalues** (*Tensor*): Shape :math:`(*, m)`. The eigenvalues in ascending order.
- **eigenvectors** (*Tensor*): Shape :math:`(*, m, m)`.
If ``eigenvectors=False``, it's an empty tensor.
Otherwise, this tensor contains the orthonormal eigenvectors of the ``input``.
Examples::
>>> a = torch.randn(5, 5)
>>> a = a + a.t() # To make a symmetric
>>> a
tensor([[-5.7827, 4.4559, -0.2344, -1.7123, -1.8330],
[ 4.4559, 1.4250, -2.8636, -3.2100, -0.1798],
[-0.2344, -2.8636, 1.7112, -5.5785, 7.1988],
[-1.7123, -3.2100, -5.5785, -2.6227, 3.1036],
[-1.8330, -0.1798, 7.1988, 3.1036, -5.1453]])
>>> e, v = torch.symeig(a, eigenvectors=True)
>>> e
tensor([-13.7012, -7.7497, -2.3163, 5.2477, 8.1050])
>>> v
tensor([[ 0.1643, 0.9034, -0.0291, 0.3508, 0.1817],
[-0.2417, -0.3071, -0.5081, 0.6534, 0.4026],
[-0.5176, 0.1223, -0.0220, 0.3295, -0.7798],
[-0.4850, 0.2695, -0.5773, -0.5840, 0.1337],
[ 0.6415, -0.0447, -0.6381, -0.0193, -0.4230]])
>>> a_big = torch.randn(5, 2, 2)
>>> a_big = a_big + a_big.transpose(-2, -1) # To make a_big symmetric
>>> e, v = a_big.symeig(eigenvectors=True)
>>> torch.allclose(torch.matmul(v, torch.matmul(e.diag_embed(), v.transpose(-2, -1))), a_big)
True
""")
add_docstr(torch.t,
r"""
t(input) -> Tensor
Expects :attr:`input` to be <= 2-D tensor and transposes dimensions 0
and 1.
0-D and 1-D tensors are returned as is. When input is a 2-D tensor this
is equivalent to ``transpose(input, 0, 1)``.
Args:
{input}
Example::
>>> x = torch.randn(())
>>> x
tensor(0.1995)
>>> torch.t(x)
tensor(0.1995)
>>> x = torch.randn(3)
>>> x
tensor([ 2.4320, -0.4608, 0.7702])
>>> torch.t(x)
tensor([ 2.4320, -0.4608, 0.7702])
>>> 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]])
""".format(**common_args))
add_docstr(torch.flip,
r"""
flip(input, dims) -> Tensor
Reverse the order of a n-D tensor along given axis in dims.
Args:
{input}
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]]])
""".format(**common_args))
add_docstr(torch.fliplr,
r"""
fliplr(input) -> Tensor
Flip array in the left/right direction, returning a new tensor.
Flip the entries in each row in the left/right direction.
Columns are preserved, but appear in a different order than before.
Note:
Equivalent to input[:,::-1]. Requires the array to be at least 2-D.
Args:
input (Tensor): Must be at least 2-dimensional.
Example::
>>> x = torch.arange(4).view(2, 2)
>>> x
tensor([[0, 1],
[2, 3]])
>>> torch.fliplr(x)
tensor([[1, 0],
[3, 2]])
""".format(**common_args))
add_docstr(torch.flipud,
r"""
flipud(input) -> Tensor
Flip array in the up/down direction, returning a new tensor.
Flip the entries in each column in the up/down direction.
Rows are preserved, but appear in a different order than before.
Note:
Equivalent to input[::-1,...]. Requires the array to be at least 1-D.
Args:
input (Tensor): Must be at least 1-dimensional.
Example::
>>> x = torch.arange(4).view(2, 2)
>>> x
tensor([[0, 1],
[2, 3]])
>>> torch.flipud(x)
tensor([[2, 3],
[0, 1]])
""".format(**common_args))
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}
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]])
""".format(**common_args))
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}
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]]])
""".format(**common_args))
add_docstr(torch.take,
r"""
take(input, index) -> 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}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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})
""" + r"""
Args:
{input}
{out}
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])
""".format(**common_args))
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 namedtuple 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}
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)
torch.return_types.topk(values=tensor([5., 4., 3.]), indices=tensor([4, 3, 2]))
""".format(**common_args))
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}
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]])
""".format(**common_args))
add_docstr(torch.triangular_solve,
r"""
triangular_solve(input, 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 :math:`b`.
In particular, solves :math:`AX = b` and assumes :math:`A` is upper-triangular
with the default keyword arguments.
`torch.triangular_solve(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`
Args:
input (Tensor): multiple right-hand sides of size :math:`(*, m, k)` where
:math:`*` is zero of more batch dimensions (:math:`b`)
A (Tensor): the input triangular coefficient matrix of size :math:`(*, m, m)`
where :math:`*` is zero or more batch dimensions
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 namedtuple `(solution, cloned_coefficient)` where `cloned_coefficient`
is a clone of :math:`A` and `solution` is the solution :math:`X` to :math:`AX = b`
(or whatever variant of the system of equations, depending on the keyword arguments.)
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.triangular_solve(b, A)
torch.return_types.triangular_solve(
solution=tensor([[ 1.7841, 2.9046, -2.5405],
[ 1.9320, 0.9270, -1.2826]]),
cloned_coefficient=tensor([[ 1.1527, -1.0753],
[ 0.0000, 0.7986]]))
""")
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.
""" + r"""
Args:
{input}
diagonal (int, optional): the diagonal to consider
{out}
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]])
""".format(**common_args))
# docstr is split in two parts to avoid format mis-captureing :math: braces '{}'
# as common args.
add_docstr(torch.tril_indices,
r"""
tril_indices(row, col, offset=0, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor
Returns the indices of the lower triangular part of a :attr:`row`-by-
:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row
coordinates of all indices and the second row contains column coordinates.
Indices are ordered based on rows and then columns.
The lower triangular part of the matrix is defined as the elements on and
below the diagonal.
The argument :attr:`offset` controls which diagonal to consider. If
:attr:`offset` = 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.
.. note::
When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to
prevent overflow during calculation.
""" + r"""
Args:
row (``int``): number of rows in the 2-D matrix.
col (``int``): number of columns in the 2-D matrix.
offset (``int``): diagonal offset from the main diagonal.
Default: if not provided, 0.
dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
Default: if ``None``, ``torch.long``.
{device}
layout (:class:`torch.layout`, optional): currently only support ``torch.strided``.
Example::
>>> a = torch.tril_indices(3, 3)
>>> a
tensor([[0, 1, 1, 2, 2, 2],
[0, 0, 1, 0, 1, 2]])
>>> a = torch.tril_indices(4, 3, -1)
>>> a
tensor([[1, 2, 2, 3, 3, 3],
[0, 0, 1, 0, 1, 2]])
>>> a = torch.tril_indices(4, 3, 1)
>>> a
tensor([[0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3],
[0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 2]])
""".format(**factory_common_args))
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 above 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.
""" + r"""
Args:
{input}
diagonal (int, optional): the diagonal to consider
{out}
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]])
""".format(**common_args))
# docstr is split in two parts to avoid format mis-capturing :math: braces '{}'
# as common args.
add_docstr(torch.triu_indices,
r"""
triu_indices(row, col, offset=0, dtype=torch.long, device='cpu', layout=torch.strided) -> Tensor
Returns the indices of the upper triangular part of a :attr:`row` by
:attr:`col` matrix in a 2-by-N Tensor, where the first row contains row
coordinates of all indices and the second row contains column coordinates.
Indices are ordered based on rows and then columns.
The upper triangular part of the matrix is defined as the elements on and
above the diagonal.
The argument :attr:`offset` controls which diagonal to consider. If
:attr:`offset` = 0, all elements on and above 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.
.. note::
When running on CUDA, ``row * col`` must be less than :math:`2^{59}` to
prevent overflow during calculation.
""" + r"""
Args:
row (``int``): number of rows in the 2-D matrix.
col (``int``): number of columns in the 2-D matrix.
offset (``int``): diagonal offset from the main diagonal.
Default: if not provided, 0.
dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
Default: if ``None``, ``torch.long``.
{device}
layout (:class:`torch.layout`, optional): currently only support ``torch.strided``.
Example::
>>> a = torch.triu_indices(3, 3)
>>> a
tensor([[0, 0, 0, 1, 1, 2],
[0, 1, 2, 1, 2, 2]])
>>> a = torch.triu_indices(4, 3, -1)
>>> a
tensor([[0, 0, 0, 1, 1, 1, 2, 2, 3],
[0, 1, 2, 0, 1, 2, 1, 2, 2]])
>>> a = torch.triu_indices(4, 3, 1)
>>> a
tensor([[0, 0, 1],
[1, 2, 2]])
""".format(**factory_common_args))
add_docstr(torch.true_divide,
r"""
true_divide(dividend, divisor) -> Tensor
Performs "true division" that always computes the division
in floating point. Analogous to division in Python 3 and equivalent to
:func:`torch.div` except when both inputs have bool or integer scalar types,
in which case they are cast to the default (floating) scalar type before the division.
.. math::
\text{{out}}_i = \frac{{\text{{dividend}}_i}}{{\text{{divisor}}}}
Args:
dividend (Tensor): the dividend
divisor (Tensor or Scalar): the divisor
Keyword args:
{out}
Example::
>>> dividend = torch.tensor([5, 3], dtype=torch.int)
>>> divisor = torch.tensor([3, 2], dtype=torch.int)
>>> torch.true_divide(dividend, divisor)
tensor([1.6667, 1.5000])
>>> torch.true_divide(dividend, 2)
tensor([2.5000, 1.5000])
""".format(**common_args))
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}
{out}
Example::
>>> a = torch.randn(4)
>>> a
tensor([ 3.4742, 0.5466, -0.8008, -0.9079])
>>> torch.trunc(a)
tensor([ 3., 0., -0., -0.])
""".format(**common_args))
add_docstr(torch.unsqueeze,
r"""
unsqueeze(input, dim) -> 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}
dim (int): the index at which to insert the singleton dimension
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]])
""".format(**common_args))
add_docstr(torch.var,
r"""
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}
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`.
{keepdim_details}
If :attr:`unbiased` is ``False``, then the variance will be calculated via the
biased estimator. Otherwise, Bessel's correction will be used.
Args:
{input}
{dim}
{keepdim}
unbiased (bool): whether to use the unbiased estimation or not
{out}
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])
""".format(**multi_dim_common))
add_docstr(torch.var_mean,
r"""
var_mean(input, unbiased=True) -> (Tensor, Tensor)
Returns the variance and mean 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}
unbiased (bool): whether to use the unbiased estimation or not
Example::
>>> a = torch.randn(1, 3)
>>> a
tensor([[0.0146, 0.4258, 0.2211]])
>>> torch.var_mean(a)
(tensor(0.0423), tensor(0.2205))
.. function:: var_mean(input, dim, keepdim=False, unbiased=True) -> (Tensor, Tensor)
Returns the variance and mean of each row of the :attr:`input` tensor in the given
dimension :attr:`dim`.
{keepdim_details}
If :attr:`unbiased` is ``False``, then the variance will be calculated via the
biased estimator. Otherwise, Bessel's correction will be used.
Args:
{input}
{dim}
{keepdim}
unbiased (bool): whether to use the unbiased estimation or not
Example::
>>> a = torch.randn(4, 4)
>>> a
tensor([[-1.5650, 2.0415, -0.1024, -0.5790],
[ 0.2325, -2.6145, -1.6428, -0.3537],
[-0.2159, -1.1069, 1.2882, -1.3265],
[-0.6706, -1.5893, 0.6827, 1.6727]])
>>> torch.var_mean(a, 1)
(tensor([2.3174, 1.6403, 1.4092, 2.0791]), tensor([-0.0512, -1.0946, -0.3403, 0.0239]))
""".format(**multi_dim_common))
add_docstr(torch.zeros,
r"""
zeros(*size, 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:`size`.
Args:
size (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, memory_format=torch.preserve_format) -> 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}
{memory_format}
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.empty,
r"""
empty(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) -> Tensor
Returns a tensor filled with uninitialized data. The shape of the tensor is
defined by the variable argument :attr:`size`.
Args:
size (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}
{pin_memory}
{memory_format}
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, memory_format=torch.preserve_format) -> 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}
{memory_format}
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.empty_strided,
r"""
empty_strided(size, stride, dtype=None, layout=None, device=None, requires_grad=False, pin_memory=False) -> Tensor
Returns a tensor filled with uninitialized data. The shape and strides of the tensor is
defined by the variable argument :attr:`size` and :attr:`stride` respectively.
``torch.empty_strided(size, stride)`` is equivalent to
``torch.empty(size).as_strided(size, stride)``.
.. warning::
More than one element of the created tensor may refer to a single memory
location. As a result, in-place operations (especially ones that are
vectorized) may result in incorrect behavior. If you need to write to
the tensors, please clone them first.
Args:
size (tuple of ints): the shape of the output tensor
stride (tuple of ints): the strides of the output tensor
{dtype}
{layout}
{device}
{requires_grad}
{pin_memory}
Example::
>>> a = torch.empty_strided((2, 3), (1, 2))
>>> a
tensor([[8.9683e-44, 4.4842e-44, 5.1239e+07],
[0.0000e+00, 0.0000e+00, 3.0705e-41]])
>>> a.stride()
(1, 2)
>>> a.size()
torch.Size([2, 3])
""".format(**factory_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`.
.. warning::
Providing a bool or integral :attr:`fill_value` without setting
the optional :attr:`dtype` or :attr:`out` arguments is currently unsupported.
In PyTorch 1.7, when :attr:`dtype` and :attr:`out` are not set
a bool :attr:`fill_value` will return a tensor of torch.bool dtype,
and an integral :attr:`fill_value` will return a tensor of torch.long dtype.
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,
"""
full_like(input, fill_value, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, \
memory_format=torch.preserve_format) -> 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(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}
{memory_format}
""".format(**factory_like_common_args))
add_docstr(torch.det,
r"""
det(input) -> Tensor
Calculates determinant of a square matrix or batches of square matrices.
.. note::
Backward through :meth:`det` internally uses SVD results when :attr:`input` is
not invertible. In this case, double backward through :meth:`det` will be
unstable in when :attr:`input` doesn't have distinct singular values. See
:meth:`~torch.svd` for details.
Arguments:
input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more
batch dimensions.
Example::
>>> A = torch.randn(3, 3)
>>> torch.det(A)
tensor(3.7641)
>>> A = torch.randn(3, 2, 2)
>>> A
tensor([[[ 0.9254, -0.6213],
[-0.5787, 1.6843]],
[[ 0.3242, -0.9665],
[ 0.4539, -0.0887]],
[[ 1.1336, -0.4025],
[-0.7089, 0.9032]]])
>>> A.det()
tensor([1.1990, 0.4099, 0.7386])
""")
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::
\text{out}_i = \begin{cases}
\text{x}_i & \text{if } \text{condition}_i \\
\text{y}_i & \text{otherwise} \\
\end{cases}
.. note::
The tensors :attr:`condition`, :attr:`x`, :attr:`y` must be :ref:`broadcastable <broadcasting-semantics>`.
Arguments:
condition (BoolTensor): 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]])
.. function:: where(condition) -> tuple of LongTensor
``torch.where(condition)`` is identical to
``torch.nonzero(condition, as_tuple=True)``.
.. note::
See also :func:`torch.nonzero`.
""")
add_docstr(torch.logdet,
r"""
logdet(input) -> Tensor
Calculates log determinant of a square matrix or batches of square matrices.
.. note::
Result is ``-inf`` if :attr:`input` has zero log determinant, and is ``nan`` if
:attr:`input` has negative determinant.
.. note::
Backward through :meth:`logdet` internally uses SVD results when :attr:`input`
is not invertible. In this case, double backward through :meth:`logdet` will
be unstable in when :attr:`input` doesn't have distinct singular values. See
:meth:`~torch.svd` for details.
Arguments:
input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more
batch dimensions.
Example::
>>> A = torch.randn(3, 3)
>>> torch.det(A)
tensor(0.2611)
>>> torch.logdet(A)
tensor(-1.3430)
>>> A
tensor([[[ 0.9254, -0.6213],
[-0.5787, 1.6843]],
[[ 0.3242, -0.9665],
[ 0.4539, -0.0887]],
[[ 1.1336, -0.4025],
[-0.7089, 0.9032]]])
>>> A.det()
tensor([1.1990, 0.4099, 0.7386])
>>> A.det().log()
tensor([ 0.1815, -0.8917, -0.3031])
""")
add_docstr(torch.slogdet,
r"""
slogdet(input) -> (Tensor, Tensor)
Calculates the sign and log absolute value of the determinant(s) of a square matrix or batches of square matrices.
.. note::
If ``input`` has zero determinant, this returns ``(0, -inf)``.
.. note::
Backward through :meth:`slogdet` internally uses SVD results when :attr:`input`
is not invertible. In this case, double backward through :meth:`slogdet`
will be unstable in when :attr:`input` doesn't have distinct singular values.
See :meth:`~torch.svd` for details.
Arguments:
input (Tensor): the input tensor of size ``(*, n, n)`` where ``*`` is zero or more
batch dimensions.
Returns:
A namedtuple (sign, logabsdet) containing the sign of the determinant, and the log
value of the absolute determinant.
Example::
>>> A = torch.randn(3, 3)
>>> A
tensor([[ 0.0032, -0.2239, -1.1219],
[-0.6690, 0.1161, 0.4053],
[-1.6218, -0.9273, -0.0082]])
>>> torch.det(A)
tensor(-0.7576)
>>> torch.logdet(A)
tensor(nan)
>>> torch.slogdet(A)
torch.return_types.slogdet(sign=tensor(-1.), logabsdet=tensor(-0.2776))
""")
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 tensor of size :math:`(*, m, n)` where :math:`*` is zero or more batch dimensions
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, 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]])
>>> # Batched pinverse example
>>> a = torch.randn(2,6,3)
>>> b = torch.pinverse(a)
>>> torch.matmul(b, a)
tensor([[[ 1.0000e+00, 1.6391e-07, -1.1548e-07],
[ 8.3121e-08, 1.0000e+00, -2.7567e-07],
[ 3.5390e-08, 1.4901e-08, 1.0000e+00]],
[[ 1.0000e+00, -8.9407e-08, 2.9802e-08],
[-2.2352e-07, 1.0000e+00, 1.1921e-07],
[ 0.0000e+00, 8.9407e-08, 1.0000e+00]]])
.. _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-1} \dots \sum_{n_d=0}^{N_d-1} 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
configuration. See :ref:`cufft-plan-cache` for more details on how to
monitor and control the cache.
.. warning::
Due to limited dynamic range of half datatype, performing this operation in half
precision may cause the first element of result to overflow for certain inputs.
.. 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-1} \dots \sum_{n_d=0}^{N_d-1} 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
configuration. See :ref:`cufft-plan-cache` for more details on how to
monitor and control the cache.
.. warning::
Due to limited dynamic range of half datatype, performing this operation in half
precision may cause the first element of result to overflow for certain inputs.
.. 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
configuration. See :ref:`cufft-plan-cache` for more details on how to
monitor and control the cache.
.. warning::
Due to limited dynamic range of half datatype, performing this operation in half
precision may cause the first element of result to overflow for certain inputs.
.. 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`.
.. note::
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 preferably 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, input to 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
configuration. See :ref:`cufft-plan-cache` for more details on how to
monitor and control the cache.
.. warning::
Due to limited dynamic range of half datatype, performing this operation in half
precision may cause the first element of result to overflow for certain inputs.
.. 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.
alpha (float, optional): The coefficient :math:`\alpha` in the equation above
beta (float, optional): The coefficient :math:`\beta` in the equation above
{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.vander,
"""
vander(x, N=None, increasing=False) -> Tensor
""" + r"""
Generates a Vandermonde matrix.
The columns of the output matrix are elementwise powers of the input vector :math:`x^{{(N-1)}}, x^{{(N-2)}}, ..., x^0`.
If increasing is True, the order of the columns is reversed :math:`x^0, x^1, ..., x^{{(N-1)}}`. Such a
matrix with a geometric progression in each row is named for Alexandre-Theophile Vandermonde.
Arguments:
x (Tensor): 1-D input tensor.
N (int, optional): Number of columns in the output. If N is not specified,
a square array is returned :math:`(N = len(x))`.
increasing (bool, optional): Order of the powers of the columns. If True,
the powers increase from left to right, if False (the default) they are reversed.
Returns:
Tensor: Vandermonde matrix. If increasing is False, the first column is :math:`x^{{(N-1)}}`,
the second :math:`x^{{(N-2)}}` and so forth. If increasing is True, the columns
are :math:`x^0, x^1, ..., x^{{(N-1)}}`.
Example::
>>> x = torch.tensor([1, 2, 3, 5])
>>> torch.vander(x)
tensor([[ 1, 1, 1, 1],
[ 8, 4, 2, 1],
[ 27, 9, 3, 1],
[125, 25, 5, 1]])
>>> torch.vander(x, N=3)
tensor([[ 1, 1, 1],
[ 4, 2, 1],
[ 9, 3, 1],
[25, 5, 1]])
>>> torch.vander(x, N=3, increasing=True)
tensor([[ 1, 1, 1],
[ 1, 2, 4],
[ 1, 3, 9],
[ 1, 5, 25]])
""".format(**factory_common_args))
add_docstr(torch.unbind,
r"""
unbind(input, dim=0) -> seq
Removes a tensor dimension.
Returns a tuple of all slices along a given dimension, already without it.
Arguments:
input (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]))
""")
add_docstr(torch.combinations,
r"""
combinations(input, r=2, with_replacement=False) -> seq
Compute combinations of length :math:`r` of the given tensor. The behavior is similar to
python's `itertools.combinations` when `with_replacement` is set to `False`, and
`itertools.combinations_with_replacement` when `with_replacement` is set to `True`.
Arguments:
input (Tensor): 1D vector.
r (int, optional): number of elements to combine
with_replacement (boolean, optional): whether to allow duplication in combination
Returns:
Tensor: A tensor equivalent to converting all the input tensors into lists, do
`itertools.combinations` or `itertools.combinations_with_replacement` on these
lists, and finally convert the resulting list into tensor.
Example::
>>> a = [1, 2, 3]
>>> list(itertools.combinations(a, r=2))
[(1, 2), (1, 3), (2, 3)]
>>> list(itertools.combinations(a, r=3))
[(1, 2, 3)]
>>> list(itertools.combinations_with_replacement(a, r=2))
[(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
>>> tensor_a = torch.tensor(a)
>>> torch.combinations(tensor_a)
tensor([[1, 2],
[1, 3],
[2, 3]])
>>> torch.combinations(tensor_a, r=3)
tensor([[1, 2, 3]])
>>> torch.combinations(tensor_a, with_replacement=True)
tensor([[1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 3],
[3, 3]])
""")
add_docstr(torch.trapz,
r"""
trapz(y, x, *, dim=-1) -> Tensor
Estimate :math:`\int y\,dx` along `dim`, using the trapezoid rule.
Arguments:
y (Tensor): The values of the function to integrate
x (Tensor): The points at which the function `y` is sampled.
If `x` is not in ascending order, intervals on which it is decreasing
contribute negatively to the estimated integral (i.e., the convention
:math:`\int_a^b f = -\int_b^a f` is followed).
dim (int): The dimension along which to integrate.
By default, use the last dimension.
Returns:
A Tensor with the same shape as the input, except with `dim` removed.
Each element of the returned tensor represents the estimated integral
:math:`\int y\,dx` along `dim`.
Example::
>>> y = torch.randn((2, 3))
>>> y
tensor([[-2.1156, 0.6857, -0.2700],
[-1.2145, 0.5540, 2.0431]])
>>> x = torch.tensor([[1, 3, 4], [1, 2, 3]])
>>> torch.trapz(y, x)
tensor([-1.2220, 0.9683])
.. function:: trapz(y, *, dx=1, dim=-1) -> Tensor
As above, but the sample points are spaced uniformly at a distance of `dx`.
Arguments:
y (Tensor): The values of the function to integrate
dx (float): The distance between points at which `y` is sampled.
dim (int): The dimension along which to integrate.
By default, use the last dimension.
Returns:
A Tensor with the same shape as the input, except with `dim` removed.
Each element of the returned tensor represents the estimated integral
:math:`\int y\,dx` along `dim`.
""")
add_docstr(torch.repeat_interleave,
r"""
repeat_interleave(input, repeats, dim=None) -> Tensor
Repeat elements of a tensor.
.. warning::
This is different from :meth:`torch.Tensor.repeat` but similar to ``numpy.repeat``.
Args:
{input}
repeats (Tensor or int): The number of repetitions for each element.
repeats is broadcasted to fit the shape of the given axis.
dim (int, optional): The dimension along which to repeat values.
By default, use the flattened input array, and return a flat output
array.
Returns:
Tensor: Repeated tensor which has the same shape as input, except along the
given axis.
Example::
>>> x = torch.tensor([1, 2, 3])
>>> x.repeat_interleave(2)
tensor([1, 1, 2, 2, 3, 3])
>>> y = torch.tensor([[1, 2], [3, 4]])
>>> torch.repeat_interleave(y, 2)
tensor([1, 1, 2, 2, 3, 3, 4, 4])
>>> torch.repeat_interleave(y, 3, dim=1)
tensor([[1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4]])
>>> torch.repeat_interleave(y, torch.tensor([1, 2]), dim=0)
tensor([[1, 2],
[3, 4],
[3, 4]])
.. function:: repeat_interleave(repeats) -> Tensor
If the `repeats` is `tensor([n1, n2, n3, ...])`, then the output will be
`tensor([0, 0, ..., 1, 1, ..., 2, 2, ..., ...])` where `0` appears `n1` times,
`1` appears `n2` times, `2` appears `n3` times, etc.
""".format(**common_args))
add_docstr(torch.quantize_per_tensor,
r"""
quantize_per_tensor(input, scale, zero_point, dtype) -> Tensor
Converts a float tensor to quantized tensor with given scale and zero point.
Arguments:
input (Tensor): float tensor to quantize
scale (float): scale to apply in quantization formula
zero_point (int): offset in integer value that maps to float zero
dtype (:class:`torch.dtype`): the desired data type of returned tensor.
Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32``
Returns:
Tensor: A newly quantized tensor
Example::
>>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8)
tensor([-1., 0., 1., 2.], size=(4,), dtype=torch.quint8,
quantization_scheme=torch.per_tensor_affine, scale=0.1, zero_point=10)
>>> torch.quantize_per_tensor(torch.tensor([-1.0, 0.0, 1.0, 2.0]), 0.1, 10, torch.quint8).int_repr()
tensor([ 0, 10, 20, 30], dtype=torch.uint8)
""")
add_docstr(torch.quantize_per_channel,
r"""
quantize_per_channel(input, scales, zero_points, axis, dtype) -> Tensor
Converts a float tensor to per-channel quantized tensor with given scales and zero points.
Arguments:
input (Tensor): float tensor to quantize
scales (Tensor): float 1D tensor of scales to use, size should match ``input.size(axis)``
zero_points (int): integer 1D tensor of offset to use, size should match ``input.size(axis)``
axis (int): dimension on which apply per-channel quantization
dtype (:class:`torch.dtype`): the desired data type of returned tensor.
Has to be one of the quantized dtypes: ``torch.quint8``, ``torch.qint8``, ``torch.qint32``
Returns:
Tensor: A newly quantized tensor
Example::
>>> x = torch.tensor([[-1.0, 0.0], [1.0, 2.0]])
>>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8)
tensor([[-1., 0.],
[ 1., 2.]], size=(2, 2), dtype=torch.quint8,
quantization_scheme=torch.per_channel_affine,
scale=tensor([0.1000, 0.0100], dtype=torch.float64),
zero_point=tensor([10, 0]), axis=0)
>>> torch.quantize_per_channel(x, torch.tensor([0.1, 0.01]), torch.tensor([10, 0]), 0, torch.quint8).int_repr()
tensor([[ 0, 10],
[100, 200]], dtype=torch.uint8)
""")
add_docstr(torch.Generator,
r"""
Generator(device='cpu') -> Generator
Creates and returns a generator object which manages the state of the algorithm that
produces pseudo random numbers. Used as a keyword argument in many :ref:`inplace-random-sampling`
functions.
Arguments:
device (:class:`torch.device`, optional): the desired device for the generator.
Returns:
Generator: An torch.Generator object.
Example::
>>> g_cpu = torch.Generator()
>>> g_cuda = torch.Generator(device='cuda')
""")
add_docstr(torch.Generator.set_state,
r"""
Generator.set_state(new_state) -> void
Sets the Generator state.
Arguments:
new_state (torch.ByteTensor): The desired state.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu_other = torch.Generator()
>>> g_cpu.set_state(g_cpu_other.get_state())
""")
add_docstr(torch.Generator.get_state,
r"""
Generator.get_state() -> Tensor
Returns the Generator state as a ``torch.ByteTensor``.
Returns:
Tensor: A ``torch.ByteTensor`` which contains all the necessary bits
to restore a Generator to a specific point in time.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu.get_state()
""")
add_docstr(torch.Generator.manual_seed,
r"""
Generator.manual_seed(seed) -> Generator
Sets the seed for generating random numbers. Returns a `torch.Generator` object.
It is recommended to set a large seed, i.e. a number that has a good balance of 0
and 1 bits. Avoid having many 0 bits in the seed.
Arguments:
seed (int): The desired seed.
Returns:
Generator: An torch.Generator object.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu.manual_seed(2147483647)
""")
add_docstr(torch.Generator.initial_seed,
r"""
Generator.initial_seed() -> int
Returns the initial seed for generating random numbers.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu.initial_seed()
2147483647
""")
add_docstr(torch.Generator.seed,
r"""
Generator.seed() -> int
Gets a non-deterministic random number from std::random_device or the current
time and uses it to seed a Generator.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu.seed()
1516516984916
""")
add_docstr(torch.Generator.device,
r"""
Generator.device -> device
Gets the current device of the generator.
Example::
>>> g_cpu = torch.Generator()
>>> g_cpu.device
device(type='cpu')
""")
add_docstr(torch.searchsorted,
r"""
searchsorted(sorted_sequence, values, out_int32=False, right=False, out=None) -> Tensor
Find the indices from the *innermost* dimension of :attr:`sorted_sequence` such that, if the
corresponding values in :attr:`values` were inserted before the indices, the order of the
corresponding *innermost* dimension within :attr:`sorted_sequence` would be preserved.
Return a new tensor with the same size as :attr:`values`. If :attr:`right` is False (default),
then the left boundary of :attr:`sorted_sequence` is closed. More formally, the returned index
satisfies the following rules:
.. list-table::
:widths: 12 10 78
:header-rows: 1
* - :attr:`sorted_sequence`
- :attr:`right`
- *returned index satisfies*
* - 1-D
- False
- ``sorted_sequence[i-1] <= values[m][n]...[l][x] < sorted_sequence[i]``
* - 1-D
- True
- ``sorted_sequence[i-1] < values[m][n]...[l][x] <= sorted_sequence[i]``
* - N-D
- False
- ``sorted_sequence[m][n]...[l][i-1] <= values[m][n]...[l][x] < sorted_sequence[m][n]...[l][i]``
* - N-D
- True
- ``sorted_sequence[m][n]...[l][i-1] < values[m][n]...[l][x] <= sorted_sequence[m][n]...[l][i]``
Args:
sorted_sequence (Tensor): N-D or 1-D tensor, containing monotonically increasing sequence on the *innermost*
dimension.
values (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s).
out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise.
Default value is False, i.e. default output data type is torch.int64.
right (bool, optional): if False, return the first suitable location that is found. If True, return the
last such index. If no suitable index found, return 0 for non-numerical value
(eg. nan, inf) or the size of *innermost* dimension within :attr:`sorted_sequence`
(one pass the last index of the *innermost* dimension). In other words, if False,
gets the lower bound index for each value in :attr:`values` on the corresponding
*innermost* dimension of the :attr:`sorted_sequence`. If True, gets the upper
bound index instead. Default value is False.
out (Tensor, optional): the output tensor, must be the same size as :attr:`values` if provided.
.. note:: If your use case is always 1-D sorted sequence, :func:`torch.bucketize` is preferred,
because it has fewer dimension checks resulting in slightly better performance.
Example::
>>> sorted_sequence = torch.tensor([[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]])
>>> sorted_sequence
tensor([[ 1, 3, 5, 7, 9],
[ 2, 4, 6, 8, 10]])
>>> values = torch.tensor([[3, 6, 9], [3, 6, 9]])
>>> values
tensor([[3, 6, 9],
[3, 6, 9]])
>>> torch.searchsorted(sorted_sequence, values)
tensor([[1, 3, 4],
[1, 2, 4]])
>>> torch.searchsorted(sorted_sequence, values, right=True)
tensor([[2, 3, 5],
[1, 3, 4]])
>>> sorted_sequence_1d = torch.tensor([1, 3, 5, 7, 9])
>>> sorted_sequence_1d
tensor([1, 3, 5, 7, 9])
>>> torch.searchsorted(sorted_sequence_1d, values)
tensor([[1, 3, 4],
[1, 3, 4]])
""")
add_docstr(torch.bucketize,
r"""
bucketize(input, boundaries, out_int32=False, right=False, out=None) -> Tensor
Returns the indices of the buckets to which each value in the :attr:`input` belongs, where the
boundaries of the buckets are set by :attr:`boundaries`. Return a new tensor with the same size
as :attr:`input`. If :attr:`right` is False (default), then the left boundary is closed. More
formally, the returned index satisfies the following rules:
.. list-table::
:widths: 15 85
:header-rows: 1
* - :attr:`right`
- *returned index satisfies*
* - False
- ``boundaries[i-1] <= input[m][n]...[l][x] < boundaries[i]``
* - True
- ``boundaries[i-1] < input[m][n]...[l][x] <= boundaries[i]``
Args:
input (Tensor or Scalar): N-D tensor or a Scalar containing the search value(s).
boundaries (Tensor): 1-D tensor, must contain a monotonically increasing sequence.
out_int32 (bool, optional): indicate the output data type. torch.int32 if True, torch.int64 otherwise.
Default value is False, i.e. default output data type is torch.int64.
right (bool, optional): if False, return the first suitable location that is found. If True, return the
last such index. If no suitable index found, return 0 for non-numerical value
(eg. nan, inf) or the size of :attr:`boundaries` (one pass the last index).
In other words, if False, gets the lower bound index for each value in :attr:`input`
from :attr:`boundaries`. If True, gets the upper bound index instead.
Default value is False.
out (Tensor, optional): the output tensor, must be the same size as :attr:`input` if provided.
Example::
>>> boundaries = torch.tensor([1, 3, 5, 7, 9])
>>> boundaries
tensor([1, 3, 5, 7, 9])
>>> v = torch.tensor([[3, 6, 9], [3, 6, 9]])
>>> v
tensor([[3, 6, 9],
[3, 6, 9]])
>>> torch.bucketize(v, boundaries)
tensor([[1, 3, 4],
[1, 3, 4]])
>>> torch.bucketize(v, boundaries, right=True)
tensor([[2, 3, 5],
[2, 3, 5]])
""")
| [
"[email protected]"
] | |
efaf5827b686a2a2c8b12a2e327f2178fa269f5c | 7954d761dde104a9d977006c514ff976a9c88444 | /backend/menu/migrations/0001_initial.py | a6a707da319ae2e8ae9d0ffbe9ae598eb1ac1002 | [] | no_license | crowdbotics-apps/firebase-25585 | 3c693fee6f6e75805fe5b8d40f24ee6b137e29e3 | 5473848fbdad0683030c8f3bd64d03fdc4a1382c | refs/heads/master | 2023-04-05T13:07:26.443879 | 2021-04-09T10:28:31 | 2021-04-09T10:28:31 | 356,229,816 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,144 | py | # Generated by Django 2.2.19 on 2021-04-09 10:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('delivery_user_profile', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('image', models.URLField()),
('icon', models.URLField()),
],
),
migrations.CreateModel(
name='Country',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('prefix', models.CharField(max_length=8)),
('flag', models.URLField()),
],
),
migrations.CreateModel(
name='Item',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('image', models.URLField()),
('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='item_category', to='menu.Category')),
],
),
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('rating', models.FloatField()),
('review_text', models.TextField()),
('timestamp_created', models.DateTimeField(auto_now_add=True)),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='review_item', to='menu.Item')),
('profile', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='review_profile', to='delivery_user_profile.Profile')),
],
),
migrations.CreateModel(
name='ItemVariant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255)),
('description', models.TextField()),
('price', models.FloatField()),
('image', models.URLField()),
('country', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_country', to='menu.Country')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='itemvariant_item', to='menu.Item')),
],
),
]
| [
"[email protected]"
] | |
2973c8a04aa45789fe2dd63d8482dcf76c80e95b | 53440fe1e7370b564d3e1161a2a39bd99425f2f7 | /fairing/constants/constants.py | 703f260d7848b679e869cb80c980ec0ea0265a54 | [
"Apache-2.0"
] | permissive | karthikrajkumar/fairing | a89123c0c1385f691bb8d2b301926360c9e70ed3 | 4f9e007365101443e1230ee206980ed6014f7d31 | refs/heads/master | 2020-06-24T01:11:10.950976 | 2019-07-22T03:06:52 | 2019-07-22T03:06:52 | 198,804,843 | 0 | 0 | Apache-2.0 | 2019-07-25T09:51:13 | 2019-07-25T09:51:13 | null | UTF-8 | Python | false | false | 1,125 | py | TEMP_TAR_GZ_FILENAME = '/tmp/fairing.layer.tar.gz'
DEFAULT_IMAGE_NAME = 'fairing-job'
DEFAULT_BASE_IMAGE = 'gcr.io/kubeflow-images-public/fairing:dev'
DEFAULT_REGISTRY = 'index.docker.io'
DEFAULT_DEST_PREFIX = '/app/'
DEFAULT_CONTEXT_FILENAME = '/tmp/fairing.context.tar.gz'
DEFAULT_GENERATED_DOCKERFILE_FILENAME = '/tmp/Dockerfile'
GOOGLE_CREDS_ENV = 'GOOGLE_APPLICATION_CREDENTIALS'
GCP_CREDS_SECRET_NAME = 'user-gcp-sa'
AWS_CREDS_SECRET_NAME = 'aws-secret'
DEFAULT_USER_AGENT = 'kubeflow-fairing/{VERSION}'
# Job Constants
JOB_DEFAULT_NAME = 'fairing-job-'
JOB_DEPLOPYER_TYPE = 'job'
# Serving Constants
SERVING_DEPLOPYER_TYPE = 'serving'
#TFJob Constants
TF_JOB_GROUP = "kubeflow.org"
TF_JOB_KIND = "TFJob"
TF_JOB_PLURAL = "tfjobs"
TF_JOB_VERSION = "v1beta2"
TF_JOB_DEFAULT_NAME = 'fairing-tfjob-'
TF_JOB_DEPLOYER_TYPE = 'tfjob'
# KFServing constants
KFSERVING_GROUP = "serving.kubeflow.org"
KFSERVING_KIND = "KFService"
KFSERVING_PLURAL = "kfservices"
KFSERVING_VERSION = "v1alpha1"
KFSERVING_DEFAULT_NAME = 'fairing-kfserving-'
KFSERVING_DEPLOYER_TYPE = 'kfservice'
KFSERVING_CONTAINER_NAME = 'user-container'
| [
"[email protected]"
] | |
a0321890fdf0babae23c4b46e7dca8a0e7afbf90 | 60dff076fae5d36af71af1066ac7eb4f833d2f2f | /tools/ci_build/github/apple/c/assemble_c_pod_package.py | 18dc8a19d23ceffa99f30900c4c998c464d550e2 | [
"MIT"
] | permissive | NervanaSystems/onnxruntime | 79e60f9c6feb8c147868d27de8077a276755cc90 | 96b3c09e2a5e0a5b4f98ed9059a719d9c7b73724 | refs/heads/master | 2023-06-22T02:55:35.250834 | 2023-01-03T22:54:46 | 2023-01-03T22:54:46 | 162,268,647 | 1 | 3 | MIT | 2021-01-14T12:56:23 | 2018-12-18T10:09:13 | C++ | UTF-8 | Python | false | false | 2,687 | py | #!/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import pathlib
import shutil
import sys
_script_dir = pathlib.Path(__file__).parent.resolve(strict=True)
sys.path.append(str(_script_dir.parent))
from package_assembly_utils import ( # noqa: E402
copy_repo_relative_to_dir, gen_file_from_template, load_framework_info)
def parse_args():
parser = argparse.ArgumentParser(description="""
Assembles the files for the C/C++ pod package in a staging directory.
This directory can be validated (e.g., with `pod lib lint`) and then zipped to create a package for release.
""")
parser.add_argument("--staging-dir", type=pathlib.Path,
default=pathlib.Path("./onnxruntime-mobile-c-staging"),
help="Path to the staging directory for the C/C++ pod files.")
parser.add_argument("--pod-version", required=True,
help="C/C++ pod version.")
parser.add_argument("--framework-info-file", type=pathlib.Path, required=True,
help="Path to the framework_info.json file containing additional values for the podspec. "
"This file should be generated by CMake in the build directory.")
parser.add_argument("--framework-dir", type=pathlib.Path, required=True,
help="Path to the onnxruntime.framework directory to include in the pod.")
return parser.parse_args()
def main():
args = parse_args()
framework_info = load_framework_info(args.framework_info_file.resolve())
staging_dir = args.staging_dir.resolve()
print(f"Assembling files in staging directory: {staging_dir}")
if staging_dir.exists():
print("Warning: staging directory already exists", file=sys.stderr)
# copy the necessary files to the staging directory
framework_dir = args.framework_dir.resolve()
shutil.copytree(framework_dir, staging_dir / framework_dir.name, dirs_exist_ok=True)
copy_repo_relative_to_dir(["LICENSE"], staging_dir)
# generate the podspec file from the template
variable_substitutions = {
"VERSION": args.pod_version,
"IOS_DEPLOYMENT_TARGET": framework_info["IOS_DEPLOYMENT_TARGET"],
"WEAK_FRAMEWORK": framework_info["WEAK_FRAMEWORK"],
"LICENSE_FILE": '"LICENSE"',
}
podspec_template = _script_dir / "onnxruntime-mobile-c.podspec.template"
podspec = staging_dir / "onnxruntime-mobile-c.podspec"
gen_file_from_template(podspec_template, podspec, variable_substitutions)
return 0
if __name__ == "__main__":
sys.exit(main())
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.