uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
ac5747fe5b2bee2a61414c84
train
class
class Dialog( QW.QDialog ): def __init__( self, parent = None, **kwargs ): title = None if 'title' in kwargs: title = kwargs['title'] del kwargs['title'] QW.QDialog.__init__( self, parent, **kwargs ) ...
class Dialog( QW.QDialog ):
def __init__( self, parent = None, **kwargs ): title = None if 'title' in kwargs: title = kwargs['title'] del kwargs['title'] QW.QDialog.__init__( self, parent, **kwargs ) self.setWindowFlag( ...
_line = fontMetrics.elidedText( last_line, QC.Qt.ElideRight, self.width() ) painter.drawText( QC.QPoint( 0, y + fontMetrics.ascent() ), elided_last_line ) done = True break ...
81
83
279
9
72
XVicarious/hydrus
include/QtPorting.py
Python
Dialog
Dialog
1,997
2,052
1,997
1,998
5f246878da48a292bbe19f5013364d0455a2ba51
bigcode/the-stack
train
e05f281f3307a444015a807e
train
class
class CheckBoxDelegate(QW.QStyledItemDelegate): def __init__(self, parent=None): super( CheckBoxDelegate, self ).__init__(parent) def createEditor( self, parent, op, idx ): self.editor = QW.QCheckBox( parent )
class CheckBoxDelegate(QW.QStyledItemDelegate):
def __init__(self, parent=None): super( CheckBoxDelegate, self ).__init__(parent) def createEditor( self, parent, op, idx ): self.editor = QW.QCheckBox( parent )
OCUS', callback ) def EVT_SIZE( self, callback ): self._AddCallback( 'EVT_SIZE', callback ) # wew lad # https://stackoverflow.com/questions/46456238/checkbox-not-visible-inside-combobox class CheckBoxDelegate(QW.QStyledItemDelegate):
64
64
64
12
51
XVicarious/hydrus
include/QtPorting.py
Python
CheckBoxDelegate
CheckBoxDelegate
2,533
2,542
2,533
2,534
aa4d4062cc51270f4a8f7f2f081c823bc418b342
bigcode/the-stack
train
01e46bf8f674ef1f7ee732f1
train
class
class WidgetEventFilter ( QC.QObject ): _mouse_tracking_required = { 'EVT_MOTION', 'EVT_MOUSE_EVENTS' } _strong_focus_required = { 'EVT_KEY_DOWN' } def __init__( self, parent_widget ): self._parent_widget = parent_widget QC.QObject.__init__( self, parent_widget ) ...
class WidgetEventFilter ( QC.QObject ):
_mouse_tracking_required = { 'EVT_MOTION', 'EVT_MOUSE_EVENTS' } _strong_focus_required = { 'EVT_KEY_DOWN' } def __init__( self, parent_widget ): self._parent_widget = parent_widget QC.QObject.__init__( self, parent_widget ) parent_widget.installEventFilter( self ...
( colour ) ) painter.end() self.setIcon( QG.QIcon( px ) ) self.setIconSize( px.size() ) self.setFlat( True ) self.setFixedSize( px.size() ) def enterEvent( self, event ): self._highlighted = True ...
256
256
1,774
10
245
XVicarious/hydrus
include/QtPorting.py
Python
WidgetEventFilter
WidgetEventFilter
2,298
2,529
2,298
2,299
71af0dd25709ca26b40adc1e18925ea11313009a
bigcode/the-stack
train
27ac5fe3542845f417c612f7
train
class
class CheckListBox( QW.QListWidget ): checkListBoxChanged = QC.Signal( int ) rightClicked = QC.Signal() def __init__( self, parent = None ): QW.QListWidget.__init__( self, parent ) self.itemClicked.connect( self._ItemCheckStateChanged ) self.setSe...
class CheckListBox( QW.QListWidget ):
checkListBoxChanged = QC.Signal( int ) rightClicked = QC.Signal() def __init__( self, parent = None ): QW.QListWidget.__init__( self, parent ) self.itemClicked.connect( self._ItemCheckStateChanged ) self.setSelectionMode( QW.QAbstractItemView.ExtendedS...
( True ) desc_layout = QW.QVBoxLayout() desc_layout.addWidget( desc_label, alignment = QC.Qt.AlignHCenter ) desc_label.setWordWrap( True ) desc_label.setAlignment( QC.Qt.AlignHCenter | QC.Qt.AlignVCenter ) desc_layout.addWidget( url_label, alignment = QC.Qt.Alig...
172
172
575
12
160
XVicarious/hydrus
include/QtPorting.py
Python
CheckListBox
CheckListBox
1,676
1,790
1,676
1,677
8f71b488d8cfb775a91b3f87d44367dd22a5277e
bigcode/the-stack
train
c8d219c480fe461a53f93712
train
function
def ListsToTuples( l ): # Since lists are not hashable, we need to (recursively) convert lists to tuples in data that is to be added to BetterListCtrl if isinstance( l, list ) or isinstance( l, tuple ): return tuple( map( ListsToTuples, l ) ) else: return l
def ListsToTuples( l ): # Since lists are not hashable, we need to (recursively) convert lists to tuples in data that is to be added to BetterListCtrl
if isinstance( l, list ) or isinstance( l, tuple ): return tuple( map( ListsToTuples, l ) ) else: return l
= self._colour ) if new_colour.isValid(): self.SetColour( new_colour ) def ListsToTuples( l ): # Since lists are not hashable, we need to (recursively) convert lists to tuples in data that is to be added to BetterListCtrl
61
64
77
39
22
XVicarious/hydrus
include/QtPorting.py
Python
ListsToTuples
ListsToTuples
2,287
2,295
2,287
2,288
19f263afbeb1360157d268cfa16153415bbbac2a
bigcode/the-stack
train
9c85ba8f172883bec52a726d
train
class
class UIActionSimulator: def __init__( self ): pass def Char( self, key, text = None ): ev1 = QG.QKeyEvent( QC.QEvent.KeyPress, key, QC.Qt.NoModifier, text = text ) ev2 = QG.QKeyEvent( QC.QEvent.KeyRelease, key, QC.Qt.NoModifier, text = text ) ...
class UIActionSimulator:
def __init__( self ): pass def Char( self, key, text = None ): ev1 = QG.QKeyEvent( QC.QEvent.KeyPress, key, QC.Qt.NoModifier, text = text ) ev2 = QG.QKeyEvent( QC.QEvent.KeyRelease, key, QC.Qt.NoModifier, text = text ) QW.QApplication.post...
= description def SetLicense( self, license ): self.license = license def SetDevelopers( self, developers_list ): self.developers = developers_list def SetWebSite( self, url ): self.website = url class UIActionSimulator:
64
64
122
6
57
XVicarious/hydrus
include/QtPorting.py
Python
UIActionSimulator
UIActionSimulator
1,592
1,605
1,592
1,593
b17a46d9670a505ca6ad5b6a1ad98e23d385ac38
bigcode/the-stack
train
7c7e2a555f51d38fbcdef9ec
train
function
def ListWidgetGetSelection( widget ): for i in range( widget.count() ): if widget.item( i ).isSelected(): return i return -1
def ListWidgetGetSelection( widget ):
for i in range( widget.count() ): if widget.item( i ).isSelected(): return i return -1
[1] ) def ListWidgetDelete( widget, idx ): if isinstance( idx, QC.QModelIndex ): idx = idx.row() if idx != -1: item = widget.takeItem( idx ) del item def ListWidgetGetSelection( widget ):
64
64
38
9
54
XVicarious/hydrus
include/QtPorting.py
Python
ListWidgetGetSelection
ListWidgetGetSelection
1,358
1,364
1,358
1,359
645cb3248a44557ec35f995fef66bf0d24cd0ee6
bigcode/the-stack
train
d4f59c5e1322da843a9d0d4d
train
function
def ListWidgetDelete( widget, idx ): if isinstance( idx, QC.QModelIndex ): idx = idx.row() if idx != -1: item = widget.takeItem( idx ) del item
def ListWidgetDelete( widget, idx ):
if isinstance( idx, QC.QModelIndex ): idx = idx.row() if idx != -1: item = widget.takeItem( idx ) del item
ToQSize( tup ): if isinstance( tup, QC.QSize ): raise ValueError( 'Unnecessary use of TupleToQSize' ) else: return QC.QSize( tup[0], tup[1] ) def ListWidgetDelete( widget, idx ):
64
64
51
10
54
XVicarious/hydrus
include/QtPorting.py
Python
ListWidgetDelete
ListWidgetDelete
1,345
1,355
1,345
1,346
902a1f3c0c5ba8ae2acf5ecb2bfc9ac1ecd02e3a
bigcode/the-stack
train
839c2df04233dd69053b4c6f
train
class
class FilePickerCtrl( QW.QWidget ): filePickerChanged = QC.Signal() def __init__( self, parent = None, wildcard = None ): QW.QWidget.__init__( self, parent ) layout = HBoxLayout( spacing = 2 ) self._path_edit = QW.QLineEdit( self ) self._button = QW.QPushButton(...
class FilePickerCtrl( QW.QWidget ):
filePickerChanged = QC.Signal() def __init__( self, parent = None, wildcard = None ): QW.QWidget.__init__( self, parent ) layout = HBoxLayout( spacing = 2 ) self._path_edit = QW.QLineEdit( self ) self._button = QW.QPushButton( 'browse', self ) self._button.c...
( self ): return self._path_edit.text() def _Browse( self ): existing_path = self._path_edit.text() path = QW.QFileDialog.getExistingDirectory( self, '', existing_path ) if path == '': return ...
141
143
479
11
130
XVicarious/hydrus
include/QtPorting.py
Python
FilePickerCtrl
FilePickerCtrl
259
348
259
260
926f24ce21df022bd19ca5d6ad9321cdf623122c
bigcode/the-stack
train
7be698daae7baadbb67ae43c
train
class
class CallAfterEventFilter( QC.QObject ): def __init__( self, parent = None ): QC.QObject.__init__( self, parent ) def eventFilter( self, watched, event ): if event.type() == CallAfterEventType and isinstance( event, CallAfterEvent ): ...
class CallAfterEventFilter( QC.QObject ):
def __init__( self, parent = None ): QC.QObject.__init__( self, parent ) def eventFilter( self, watched, event ): if event.type() == CallAfterEventType and isinstance( event, CallAfterEvent ): event.Execute() event...
= fn self._args = args self._kwargs = kwargs def Execute( self ): if self._fn is not None: self._fn( *self._args, **self._kwargs ) class CallAfterEventFilter( QC.QObject ):
61
64
87
11
50
XVicarious/hydrus
include/QtPorting.py
Python
CallAfterEventFilter
CallAfterEventFilter
1,205
1,223
1,205
1,206
9c8f59eb323390b1bd7cd2069bf4fc280f3750a9
bigcode/the-stack
train
4d0183565f522cc5431cdae6
train
function
def SetClientSize( widget, size ): if isinstance( size, tuple ): size = QC.QSize( size[ 0 ], size[ 1 ] ) if size.width() < 0: size.setWidth( widget.width() ) if size.height() < 0: size.setHeight( widget.height() ) widget.resize( size )
def SetClientSize( widget, size ):
if isinstance( size, tuple ): size = QC.QSize( size[ 0 ], size[ 1 ] ) if size.width() < 0: size.setWidth( widget.width() ) if size.height() < 0: size.setHeight( widget.height() ) widget.resize( size )
( object_name, QG.QColor( colour ).name() ) ) def SetStringSelection( combobox, string ): index = combobox.findText( string ) if index != -1: combobox.setCurrentIndex( index ) def SetClientSize( widget, size ):
64
64
77
10
54
XVicarious/hydrus
include/QtPorting.py
Python
SetClientSize
SetClientSize
1,498
1,507
1,498
1,499
f75b47c0770f4e7c9deac919f780a633244672e1
bigcode/the-stack
train
64a27cff89e926e5f8620428
train
function
def SplitterVisibleCount( splitter ): count = 0 for i in range( splitter.count() ): if splitter.widget( i ).isVisible(): count += 1 return count
def SplitterVisibleCount( splitter ):
count = 0 for i in range( splitter.count() ): if splitter.widget( i ).isVisible(): count += 1 return count
Range( self, min, max ): self._slider.setRange( min, max ) self._UpdateLabels() def SetValue( self, value ): self._slider.setValue( value ) self._UpdateLabels() def SplitterVisibleCount( splitter ):
63
64
45
9
54
XVicarious/hydrus
include/QtPorting.py
Python
SplitterVisibleCount
SplitterVisibleCount
185
193
185
186
fba86534f533cdc89baa9cb7bd8a330bbf6f9350
bigcode/the-stack
train
b32e69dc445c4d6bb72192b3
train
function
def SplitVertically( splitter, w1, w2, hpos ): splitter.setOrientation( QC.Qt.Horizontal ) if w1.parentWidget() != splitter: splitter.addWiget( w1 ) w1.setVisible( True ) if w2.parentWidget() != splitter: splitter.addWiget( w2 ) w2.setVisible( True ) total...
def SplitVertically( splitter, w1, w2, hpos ):
splitter.setOrientation( QC.Qt.Horizontal ) if w1.parentWidget() != splitter: splitter.addWiget( w1 ) w1.setVisible( True ) if w2.parentWidget() != splitter: splitter.addWiget( w2 ) w2.setVisible( True ) total_sum = sum( splitter.sizes() ) if hpos < 0:...
def DeleteAllNotebookPages( notebook ): while notebook.count() > 0: tab = notebook.widget( 0 ) notebook.removeTab( 0 ) tab.deleteLater() def SplitVertically( splitter, w1, w2, hpos ):
62
64
143
17
45
XVicarious/hydrus
include/QtPorting.py
Python
SplitVertically
SplitVertically
812
836
812
813
6832c87689f83df9af10d91ee35f83f309a6306b
bigcode/the-stack
train
0621bf7d3d7236fb0276b58e
train
class
class CollectComboCtrl( QW.QComboBox ): itemChanged = QC.Signal() def __init__( self, parent, media_collect ): QW.QComboBox.__init__( self, parent ) self.view().pressed.connect( self._HandleItemPressed ) if QW.QApplication.style().metaObject().className() == ...
class CollectComboCtrl( QW.QComboBox ):
itemChanged = QC.Signal() def __init__( self, parent, media_collect ): QW.QComboBox.__init__( self, parent ) self.view().pressed.connect( self._HandleItemPressed ) if QW.QApplication.style().metaObject().className() == "QFusionStyle": ...
_MOUSEWHEEL', callback ) def EVT_MOVE( self, callback ): self._AddCallback( 'EVT_MOVE', callback ) def EVT_MOVE_END( self, callback ): self._AddCallback( 'EVT_MOVE_END', callback ) def EVT_RIGHT_DOWN( self, callback ): self._AddCallback( 'EVT_RIGHT_DOWN'...
255
256
1,103
12
243
XVicarious/hydrus
include/QtPorting.py
Python
CollectComboCtrl
CollectComboCtrl
2,545
2,747
2,545
2,546
676d5703df5f2bd9ebb4dc49f73286c9dc6666fe
bigcode/the-stack
train
9d0943f6a95623355eaf2230
train
function
def ToKeySequence( modifiers, key ): if isinstance( modifiers, QC.Qt.KeyboardModifiers ): seq_str = '' for modifier in [ QC.Qt.ShiftModifier, QC.Qt.ControlModifier, QC.Qt.AltModifier, QC.Qt.MetaModifier, QC.Qt.KeypadModifier, QC.Qt.GroupSwitchModifier ]: ...
def ToKeySequence( modifiers, key ):
if isinstance( modifiers, QC.Qt.KeyboardModifiers ): seq_str = '' for modifier in [ QC.Qt.ShiftModifier, QC.Qt.ControlModifier, QC.Qt.AltModifier, QC.Qt.MetaModifier, QC.Qt.KeypadModifier, QC.Qt.GroupSwitchModifier ]: if modifiers & modifier: seq_str += QG....
Text( painter, x, y, text ): boundingRect = painter.fontMetrics().size( QC.Qt.TextSingleLine, text ) painter.drawText( QC.QRectF( x, y, boundingRect.width(), boundingRect.height() ), text ) def ToKeySequence( modifiers, key ):
64
64
132
10
54
XVicarious/hydrus
include/QtPorting.py
Python
ToKeySequence
ToKeySequence
1,134
1,148
1,134
1,135
9ff1797bb9ff67eb15f7597292ee60ba84f4d17c
bigcode/the-stack
train
b0e0554539b2039484315f60
train
class
class TabBar( QW.QTabBar ): def __init__( self, parent = None ): QW.QTabBar.__init__( self, parent ) self.setMouseTracking( True ) self.setAcceptDrops( True ) self._supplementary_drop_target = None self._last_clicked_tab_index = -1 self._la...
class TabBar( QW.QTabBar ):
def __init__( self, parent = None ): QW.QTabBar.__init__( self, parent ) self.setMouseTracking( True ) self.setAcceptDrops( True ) self._supplementary_drop_target = None self._last_clicked_tab_index = -1 self._last_clicked_global_pos = None ...
else: path = QW.QFileDialog.getOpenFileName( self, '', existing_path )[0] if path == '': return path = os.path.normpath( path ) self._path_edit.setText( pa...
126
128
427
11
115
XVicarious/hydrus
include/QtPorting.py
Python
TabBar
TabBar
352
437
352
353
6afd6d70b6810b4ee182d660bf687b6cbc562e81
bigcode/the-stack
train
02efa9259d8582a6fd96b276
train
class
class ColourPickerCtrl( QW.QPushButton ): def __init__( self, parent = None ): QW.QPushButton.__init__( self, parent ) self._colour = QG.QColor( 0, 0, 0, 0 ) self.clicked.connect( self._ChooseColour ) self._highlighted = False de...
class ColourPickerCtrl( QW.QPushButton ):
def __init__( self, parent = None ): QW.QPushButton.__init__( self, parent ) self._colour = QG.QColor( 0, 0, 0, 0 ) self.clicked.connect( self._ChooseColour ) self._highlighted = False def SetColour( self, colour ): s...
item, column ): self._UpdateCheckState( item, item.checkState( 0 ) ) def _UpdateCheckState( self, item, check_state ): # this is an int, should be a checkstate item.setCheckState( 0, check_state ) for i in range( item.childCount() ): ...
104
107
358
12
92
XVicarious/hydrus
include/QtPorting.py
Python
ColourPickerCtrl
ColourPickerCtrl
2,212
2,283
2,212
2,213
815b10b5b2cc129eb7d66d4bda9d5a812fbfe0a8
bigcode/the-stack
train
8497cd9391a1f3ef16e12f3a
train
function
def AddToLayout( layout, item, flag = None, alignment = None, sizePolicy = None ): if isinstance( layout, GridLayout ): cols = layout.GetFixedColumnCount() count = layout.count() row = math.floor( count / cols ) col = count % cols ...
def AddToLayout( layout, item, flag = None, alignment = None, sizePolicy = None ):
if isinstance( layout, GridLayout ): cols = layout.GetFixedColumnCount() count = layout.count() row = math.floor( count / cols ) col = count % cols if isinstance( item, QW.QLayout ): layout.addLayout( item,...
Widget() != splitter: splitter.addWiget( w2 ) w2.setVisible( True ) total_sum = sum( splitter.sizes() ) if vpos < 0: splitter.setSizes( [ total_sum + vpos, -vpos ] ) elif vpos > 0: splitter.setSizes( [ vpos, total_sum - vpos ] ) de...
254
256
1,789
23
231
XVicarious/hydrus
include/QtPorting.py
Python
AddToLayout
AddToLayout
894
1,084
894
895
66b2c9726ef00910f727fe7ee235f2a88ab6c7db
bigcode/the-stack
train
67b5697d81f94167cd69a3a6
train
function
def Unsplit( splitter, widget ): if widget.parentWidget() == splitter: widget.setVisible( False )
def Unsplit( splitter, widget ):
if widget.parentWidget() == splitter: widget.setVisible( False )
0, QC.Qt.UserRole ) elif isinstance( widget, QW.QListWidget ): return widget.item( idx ).data( QC.Qt.UserRole ) else: raise ValueError( 'Unknown widget class in GetClientData' ) def Unsplit( splitter, widget ):
64
64
26
9
55
XVicarious/hydrus
include/QtPorting.py
Python
Unsplit
Unsplit
1,290
1,294
1,290
1,291
4450e8b868fe4cdd1f80abeca7b29e9bcb8ee235
bigcode/the-stack
train
a3b08925191fbd16507b94a6
train
function
def GetClientData( widget, idx ): if isinstance( widget, QW.QComboBox ): return widget.itemData( idx, QC.Qt.UserRole ) elif isinstance( widget, CheckListBox ): return widget.item( idx ).data( QC.Qt.UserRole ) elif isinstance( widget, QW.QTreeWidget ): ...
def GetClientData( widget, idx ):
if isinstance( widget, QW.QComboBox ): return widget.itemData( idx, QC.Qt.UserRole ) elif isinstance( widget, CheckListBox ): return widget.item( idx ).data( QC.Qt.UserRole ) elif isinstance( widget, QW.QTreeWidget ): return widget.topLevelItem( i...
spacer layout.removeItem( item ) def ListWidgetGetStringSelection( widget ): for i in range( widget.count() ): if widget.item( i ).isSelected(): return widget.item( i ).text() return None def GetClientData( widget, idx ):
64
64
143
10
53
XVicarious/hydrus
include/QtPorting.py
Python
GetClientData
GetClientData
1,267
1,287
1,267
1,268
5c89b4b94127d73cb7287c29f095ef981a7b45ac
bigcode/the-stack
train
aa6490e1a44b1e47cd4f8fa9
train
function
def SetInitialSize( widget, size ): if hasattr( widget, 'SetInitialSize' ): widget.SetInitialSize( size ) return if isinstance( size, tuple ): size = QC.QSize( size[0], size[1] ) if size.width() >= 0: widget.setMinimumWidth( size.wid...
def SetInitialSize( widget, size ):
if hasattr( widget, 'SetInitialSize' ): widget.SetInitialSize( size ) return if isinstance( size, tuple ): size = QC.QSize( size[0], size[1] ) if size.width() >= 0: widget.setMinimumWidth( size.width() ) if size.height() >= 0: widget....
( min ) if max is not None: spinbox.setMaximum( max ) if initial is not None: spinbox.setValue( initial ) if width is not None: spinbox.setMinimumWidth( width ) return spinbox def SetInitialSize( widget, size ):
64
64
98
10
53
XVicarious/hydrus
include/QtPorting.py
Python
SetInitialSize
SetInitialSize
1,422
1,436
1,422
1,423
7852a3c3eae6c267b8620553fbe7a0d22bf500fc
bigcode/the-stack
train
2cb7b8c87eaab9439fbf8861
train
function
def SetStringSelection( combobox, string ): index = combobox.findText( string ) if index != -1: combobox.setCurrentIndex( index )
def SetStringSelection( combobox, string ):
index = combobox.findText( string ) if index != -1: combobox.setCurrentIndex( index )
: {} }}'.format( object_name, TupleToQColor( colour ).name() ) ) else: widget.setStyleSheet( '#{} {{ color: {} }}'.format( object_name, QG.QColor( colour ).name() ) ) def SetStringSelection( combobox, string ):
64
64
39
11
53
XVicarious/hydrus
include/QtPorting.py
Python
SetStringSelection
SetStringSelection
1,489
1,495
1,489
1,490
743c8fcb6f834eac77a71636643f5073499a4b93
bigcode/the-stack
train
93c8584014c454d95573e2b2
train
function
def TupleToQSize( tup ): if isinstance( tup, QC.QSize ): raise ValueError( 'Unnecessary use of TupleToQSize' ) else: return QC.QSize( tup[0], tup[1] )
def TupleToQSize( tup ):
if isinstance( tup, QC.QSize ): raise ValueError( 'Unnecessary use of TupleToQSize' ) else: return QC.QSize( tup[0], tup[1] )
TupleToQPoint( tup ): if isinstance( tup, QC.QPoint ): raise ValueError( 'Unnecessary use of TupleToQPoint' ) else: return QC.QPoint( tup[ 0 ], tup[ 1 ] ) def TupleToQSize( tup ):
64
64
56
9
55
XVicarious/hydrus
include/QtPorting.py
Python
TupleToQSize
TupleToQSize
1,334
1,342
1,334
1,335
6fe87ea0eb79c99a0daaab3e3b7bf4483c01be44
bigcode/the-stack
train
1a5e4c79573913c793ad4efe
train
function
def TupleToQColor( tup): return QG.QColor( *tup )
def TupleToQColor( tup):
return QG.QColor( *tup )
Screen( window ): window.move( QW.QApplication.desktop().availableGeometry().center() - window.rect().center() ) def WarningHandler( msg_type, context, str ): if msg_type == QC.QtWarningMsg: print( str ) def TupleToQColor( tup):
64
64
20
9
55
XVicarious/hydrus
include/QtPorting.py
Python
TupleToQColor
TupleToQColor
1,318
1,320
1,318
1,319
d51b8275d6e20f4e9ea03129d3eefbb02a9b9567
bigcode/the-stack
train
e1dd45bd03e377bba7ab6188
train
class
class DirDialog( QW.QFileDialog ): def __init__( self, parent = None, message = None ): QW.QFileDialog.__init__( self, parent ) if message is not None: self.setWindowTitle( message ) self.setAcceptMode( QW.QFileDialog.AcceptOpen ) self.setFileMode...
class DirDialog( QW.QFileDialog ):
def __init__( self, parent = None, message = None ): QW.QFileDialog.__init__( self, parent ) if message is not None: self.setWindowTitle( message ) self.setAcceptMode( QW.QFileDialog.AcceptOpen ) self.setFileMode( QW.QFileDialog.Directory ) ...
._cancel_button ) button_layout.addWidget( self._ok_button ) self.layout().addLayout( entry_layout ) self.layout().addLayout( button_layout ) def GetValue( self ): return self._password.text() class DirDialog( QW.QFileDialog ):
63
64
210
11
52
XVicarious/hydrus
include/QtPorting.py
Python
DirDialog
DirDialog
2,095
2,134
2,095
2,096
f23de72cd96a7920ecaba125d61d3ea706c12841
bigcode/the-stack
train
34219bec0da842c223a81ef3
train
function
def setup_positions(source, version, n_walkers, params0=None, mag=1e-3): """Sets up and returns posititons of walkers Parameters ---------- source : str version : int n_walkers: int, number of mcmc walkers to use params0: array, initial guess (mdot1, x, z, qb, g, redshift, d, inc) mag: ...
def setup_positions(source, version, n_walkers, params0=None, mag=1e-3):
"""Sets up and returns posititons of walkers Parameters ---------- source : str version : int n_walkers: int, number of mcmc walkers to use params0: array, initial guess (mdot1, x, z, qb, g, redshift, d, inc) mag: flt, magnitude of random seeds to use for initial mcmc 'ball' """ ...
version, verbose=False, re_interp=False, **kwargs) sampler = emcee.EnsembleSampler(n_walkers, n_dimensions, bfit.lhood, threads=n_threads) return sampler def setup_positions(source, version, n_walkers, params0=None, mag=1e-3):
64
64
198
22
41
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
setup_positions
setup_positions
39
56
39
39
7ad3c19168bb62b23a1f353de6b89cb37540fb4f
bigcode/the-stack
train
b641971d59f5a50bffd89a29
train
function
def get_acceptance_fraction(source=None, version=None, n_walkers=None, n_steps=None, sampler=None): """Returns acceptance fraction averaged over all walkers for all steps Must provide either: 1. a sampler object (as returned from load_sampler_state) 2. source, versio...
def get_acceptance_fraction(source=None, version=None, n_walkers=None, n_steps=None, sampler=None):
"""Returns acceptance fraction averaged over all walkers for all steps Must provide either: 1. a sampler object (as returned from load_sampler_state) 2. source, version, n_walkers, and n_steps """ if sampler is None: if None in (source, version, n_walkers, n_steps): ...
print(f'Time per step: {time_per_step:.1f} s') print(f'Time per sample: {time_per_sample:.4f} s') return result def get_acceptance_fraction(source=None, version=None, n_walkers=None, n_steps=None, sampler=None):
64
64
182
24
39
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
get_acceptance_fraction
get_acceptance_fraction
83
100
83
84
37d2f0040a73eb836ffab5a50d5ad035850d9c27
bigcode/the-stack
train
9bf78a794b2b201cdca07c27
train
function
def optimise(source, version, x0=None): """Optimise the starting position of the mcmc walkers using standard minimisation methods Parameters ---------- x0 : ndarray Initial guess of parameters """ bfit = burstfit.BurstFit(source=source, version=version, verbose=False, ...
def optimise(source, version, x0=None):
"""Optimise the starting position of the mcmc walkers using standard minimisation methods Parameters ---------- x0 : ndarray Initial guess of parameters """ bfit = burstfit.BurstFit(source=source, version=version, verbose=False, lhood_factor=-1, zero...
= mcmc_tools.load_sampler_state(source=source, version=version, n_steps=n_steps, n_walkers=n_walkers) else: n_steps = sampler['iterations'] return np.average(sampler['naccepted'] / n_steps) def optimise(source, version, x0=None):
64
64
125
10
54
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
optimise
optimise
103
117
103
103
ad97fb755050be489c6c3fc83c75416849a048d1
bigcode/the-stack
train
637268bb1fb6821456db8541
train
function
def setup_sampler(source, version, pos=None, n_walkers=None, n_threads=1, **kwargs): """Initialises and returns EnsembleSampler object NOTE: Only uses pos to get n_walkers and n_dimensions """ if pos is None: if n_walkers is None: print('ERROR: must provide either ...
def setup_sampler(source, version, pos=None, n_walkers=None, n_threads=1, **kwargs):
"""Initialises and returns EnsembleSampler object NOTE: Only uses pos to get n_walkers and n_dimensions """ if pos is None: if n_walkers is None: print('ERROR: must provide either pos or n_walkers') pos = setup_positions(source=source, version=version, n_walkers=n_walkers) ...
c_tools from pyburst.misc.pyprint import check_params_length GRIDS_PATH = os.environ['KEPLER_GRIDS'] MODELS_PATH = os.environ['KEPLER_MODELS'] def setup_sampler(source, version, pos=None, n_walkers=None, n_threads=1, **kwargs):
64
64
173
24
40
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
setup_sampler
setup_sampler
17
36
17
18
aa6035c61aee34db467768a6b4db55ccfdead473
bigcode/the-stack
train
e29ce577cf67fe0859cb7ddd
train
function
def run_sampler(sampler, pos, n_steps, verbose=True): """Runs emcee chain for n_steps """ t0 = time.time() result = None # TODO: update to use pool for i, result in enumerate(sampler.sample(pos, iterations=n_steps, progress=True)): pass t1 = time.time() dtime = t1 - t0 time_...
def run_sampler(sampler, pos, n_steps, verbose=True):
"""Runs emcee chain for n_steps """ t0 = time.time() result = None # TODO: update to use pool for i, result in enumerate(sampler.sample(pos, iterations=n_steps, progress=True)): pass t1 = time.time() dtime = t1 - t0 time_per_step = dtime / n_steps n_walkers = pos.shape[...
params0 = mcmc_version.initial_position n_dimensions = len(params0) pos = [params0 * (1 + mag * np.random.randn(n_dimensions)) for i in range(n_walkers)] return np.array(pos) def run_sampler(sampler, pos, n_steps, verbose=True):
64
64
200
14
50
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
run_sampler
run_sampler
59
80
59
59
161591b8d6242d9ade6976458333ccf0567cd51a
bigcode/the-stack
train
97cbc0c1f8ed9e33655577e2
train
function
def convert_params(params, source, version): """Converts params from dict to raw list format, and vice versa (ensures order) """ pkeys = mcmc_versions.get_parameter(source, version, parameter='param_keys') check_params_length(params=params, n=len(pkeys)) ptype = type(params) if ptype == dict: ...
def convert_params(params, source, version):
"""Converts params from dict to raw list format, and vice versa (ensures order) """ pkeys = mcmc_versions.get_parameter(source, version, parameter='param_keys') check_params_length(params=params, n=len(pkeys)) ptype = type(params) if ptype == dict: params_out = [] for key in pke...
lhood_factor=-1, zero_lhood=-1e9) if x0 is None: x0 = bfit.mcmc_version.initial_position return fmin(bfit.lhood, x0=x0, maxfun=10000) def convert_params(params, source, version):
64
64
163
9
55
zacjohnston/pyburst
pyburst/mcmc/mcmc.py
Python
convert_params
convert_params
120
139
120
120
300e740349a9c0f75e22fd33ea6b38ef524632cc
bigcode/the-stack
train
c02194a043c9f73fd5faa8ac
train
function
def _get_traced_redis(ddtracer, baseclass, service, meta): return baseclass
def _get_traced_redis(ddtracer, baseclass, service, meta):
return baseclass
.0.0") def get_traced_redis_from(ddtracer, baseclass, service=DEFAULT_SERVICE, meta=None): return _get_traced_redis(ddtracer, baseclass, service, meta) def _get_traced_redis(ddtracer, baseclass, service, meta):
64
64
23
18
46
mykytarudenko/new-project
ddtrace/contrib/redis/tracers.py
Python
_get_traced_redis
_get_traced_redis
19
20
19
19
b0a5632bb999c5abb03c7b6c9c9b1a599d7212d7
bigcode/the-stack
train
85e796ae7c805ab8e077c26e
train
function
@deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis(ddtracer, service=DEFAULT_SERVICE, meta=None): return _get_traced_redis(ddtracer, StrictRedis, service, meta)
@deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis(ddtracer, service=DEFAULT_SERVICE, meta=None):
return _get_traced_redis(ddtracer, StrictRedis, service, meta)
from redis import StrictRedis from ...utils.deprecation import deprecated DEFAULT_SERVICE = "redis" @deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis(ddtracer, service=DEFAULT_SERVICE, meta=None):
60
64
59
40
20
mykytarudenko/new-project
ddtrace/contrib/redis/tracers.py
Python
get_traced_redis
get_traced_redis
9
11
9
10
9ef29d7e8f33f2df0e7815903d67b2af8bf65ff6
bigcode/the-stack
train
b7b7868e43d5880add2ad34f
train
function
@deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis_from(ddtracer, baseclass, service=DEFAULT_SERVICE, meta=None): return _get_traced_redis(ddtracer, baseclass, service, meta)
@deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis_from(ddtracer, baseclass, service=DEFAULT_SERVICE, meta=None):
return _get_traced_redis(ddtracer, baseclass, service, meta)
): return _get_traced_redis(ddtracer, StrictRedis, service, meta) @deprecated(message="Use patching instead (see the docs).", version="1.0.0") def get_traced_redis_from(ddtracer, baseclass, service=DEFAULT_SERVICE, meta=None):
64
64
63
44
20
mykytarudenko/new-project
ddtrace/contrib/redis/tracers.py
Python
get_traced_redis_from
get_traced_redis_from
14
16
14
15
88c439f9f0e66802a67a9d2f51ac12fd52e276b1
bigcode/the-stack
train
347aee8348d96a2753914152
train
function
def supports_vif_related_pci_allocations(context, host): """Checks if the compute host service is new enough to support VIF related PCI allocation during live migration :param context: The user request context. :param host: The nova-compute host to check. :returns: True if the compute host is new e...
def supports_vif_related_pci_allocations(context, host):
"""Checks if the compute host service is new enough to support VIF related PCI allocation during live migration :param context: The user request context. :param host: The nova-compute host to check. :returns: True if the compute host is new enough to support vif related PCI allocation...
from nova.i18n import _ from nova.network import neutron from nova import objects from nova.objects import fields as obj_fields from nova.scheduler import utils as scheduler_utils LOG = logging.getLogger(__name__) CONF = nova.conf.CONF def supports_vif_related_pci_allocations(context, host):
64
64
110
13
50
bbc/nova
nova/conductor/tasks/live_migrate.py
Python
supports_vif_related_pci_allocations
supports_vif_related_pci_allocations
35
45
35
35
6a3c171973158c977f7f379adef0aadfdb2bcb6d
bigcode/the-stack
train
611051ea6b00879928019e78
train
class
class LiveMigrationTask(base.TaskBase): def __init__(self, context, instance, destination, block_migration, disk_over_commit, migration, compute_rpcapi, servicegroup_api, query_client, report_client, request_spec=None): super(LiveMigrationTask, self).__init...
class LiveMigrationTask(base.TaskBase):
def __init__(self, context, instance, destination, block_migration, disk_over_commit, migration, compute_rpcapi, servicegroup_api, query_client, report_client, request_spec=None): super(LiveMigrationTask, self).__init__(context, instance) self.desti...
nova.i18n import _ from nova.network import neutron from nova import objects from nova.objects import fields as obj_fields from nova.scheduler import utils as scheduler_utils LOG = logging.getLogger(__name__) CONF = nova.conf.CONF def supports_vif_related_pci_allocations(context, host): """Checks if the compute...
256
256
5,060
8
247
bbc/nova
nova/conductor/tasks/live_migrate.py
Python
LiveMigrationTask
LiveMigrationTask
59
593
59
59
f4a054fc0194af371f890c9bbcc03a6de227c3cc
bigcode/the-stack
train
e35510f6aa588459e423d8ec
train
function
def supports_vpmem_live_migration(context): """Checks if the commpute host service is new enough to support instance live migration with virtual persistent memory. :param context: The user request context. :returns: True if the compute hosts are new enough to support live migration with v...
def supports_vpmem_live_migration(context):
"""Checks if the commpute host service is new enough to support instance live migration with virtual persistent memory. :param context: The user request context. :returns: True if the compute hosts are new enough to support live migration with vpmem """ return objects.Service.get_...
host to check. :returns: True if the compute host is new enough to support vif related PCI allocations """ svc = objects.Service.get_by_host_and_binary(context, host, 'nova-compute') return svc.version >= 36 def supports_vpmem_live_migration(context):
64
64
88
10
53
bbc/nova
nova/conductor/tasks/live_migrate.py
Python
supports_vpmem_live_migration
supports_vpmem_live_migration
48
56
48
48
5af7034b76fe570a720d6d22afc9f892fea12a74
bigcode/the-stack
train
c5406d6d19b21d7a07401d64
train
function
def vectorize_sequences(sequences, dimension=10000): results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): results[i, sequence] = 1. return results
def vectorize_sequences(sequences, dimension=10000):
results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): results[i, sequence] = 1. return results
from keras.datasets import imdb import numpy as np from keras import models from keras import layers import matplotlib.pyplot as plt (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000) def vectorize_sequences(sequences, dimension=10000):
62
64
48
12
50
bluewaitor/playground
python/deep_learning_with_python/3.4_imdb/main.py
Python
vectorize_sequences
vectorize_sequences
9
13
9
9
ad69f4b759f41405b15f248f6e294967215551af
bigcode/the-stack
train
76baa55687aed2a84a427efd
train
class
class Solution: def removeDuplicates(self, nums: List[int]) -> int: l, r, n, p = 0, 0, 0, nums[0] for r in range(len(nums)): if nums[r] == p: n += 1 else: n = 1 p = nums[r] nums[l], nums[r] = nums[r], nums[l] ...
class Solution:
def removeDuplicates(self, nums: List[int]) -> int: l, r, n, p = 0, 0, 0, nums[0] for r in range(len(nums)): if nums[r] == p: n += 1 else: n = 1 p = nums[r] nums[l], nums[r] = nums[r], nums[l] if n <= 2: ...
""" https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ """ from typing import List class Solution:
25
64
107
3
21
hopeness/leetcode
algorithms/80.Remove-Duplicates-from-Sorted-Array-II/Python/solution_1.py
Python
Solution
Solution
8
20
8
8
abdeb7c07714cb71b51a8ab9c85680da1a835fc7
bigcode/the-stack
train
71ccceb7844804f95a99e688
train
function
def parse_cmd_line(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--version', help='Print the version and exit.', action='version', version='%(prog)s {}'.format(VERSION)) return parser.parse_args()
def parse_cmd_line():
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--version', help='Print the version and exit.', action='version', version='%(prog)s {}'.format(VERSION)) return parser.parse_args()
): cycle_spinner(sequence) return 0 def cycle_spinner(char_sequence): stdout = sys.stdout for char in char_sequence: stdout.write(char) stdout.flush() time.sleep(0.3) stdout.write('\b\b\b') stdout.flush() def parse_cmd_line():
64
64
54
5
59
fretboardfreak/code
spinner.py
Python
parse_cmd_line
parse_cmd_line
32
37
32
32
fbfc523b73e8642a317a41f3a373361543a4a2cc
bigcode/the-stack
train
ea8b585797523e45641a5e9c
train
function
def cycle_spinner(char_sequence): stdout = sys.stdout for char in char_sequence: stdout.write(char) stdout.flush() time.sleep(0.3) stdout.write('\b\b\b') stdout.flush()
def cycle_spinner(char_sequence):
stdout = sys.stdout for char in char_sequence: stdout.write(char) stdout.flush() time.sleep(0.3) stdout.write('\b\b\b') stdout.flush()
args = parse_cmd_line() spinner1 = '-/|\\' spinner2 = 'v<^>' while True: for sequence in [spinner1, spinner2]: for _ in range(5): cycle_spinner(sequence) return 0 def cycle_spinner(char_sequence):
64
64
48
6
57
fretboardfreak/code
spinner.py
Python
cycle_spinner
cycle_spinner
22
29
22
22
377e027165ec526b2ca32bc120bdd20e70e6ad01
bigcode/the-stack
train
a4b10aa681baa93956eca868
train
function
def main(): args = parse_cmd_line() spinner1 = '-/|\\' spinner2 = 'v<^>' while True: for sequence in [spinner1, spinner2]: for _ in range(5): cycle_spinner(sequence) return 0
def main():
args = parse_cmd_line() spinner1 = '-/|\\' spinner2 = 'v<^>' while True: for sequence in [spinner1, spinner2]: for _ in range(5): cycle_spinner(sequence) return 0
#!/usr/bin/env python3 """A demo implementation of a UI spinner.""" import sys, argparse import time VERSION = "1.0" def main():
34
64
61
3
31
fretboardfreak/code
spinner.py
Python
main
main
11
19
11
11
94b675e517ddc3ed33992653fe33fcace21e31f5
bigcode/the-stack
train
226ba393c052d5a24f6b1736
train
class
class AnonymousTestCase(TestCase): fixtures = [ 'user.json', 'profile.json', 'post.json', 'vote.json', 'comment.json', 'comment_vote.json' ] POST_ID = 9527 COMMENT_ID = 1
class AnonymousTestCase(TestCase):
fixtures = [ 'user.json', 'profile.json', 'post.json', 'vote.json', 'comment.json', 'comment_vote.json' ] POST_ID = 9527 COMMENT_ID = 1
#!/usr/bin/env python from django.test import TestCase from django.test.client import Client class AnonymousTestCase(TestCase):
27
64
59
7
19
knownsec/PyHackerNews
src/pyhn/libs/tests/base.py
Python
AnonymousTestCase
AnonymousTestCase
8
20
8
9
90cf74153df6324dbbdf56d4e087d73e2f529e5f
bigcode/the-stack
train
105fafe229117d4824cb8f02
train
class
class AuthorizedTestCase(AnonymousTestCase): def setUp(self): self.client = Client(enforce_csrf_checks=False) self.client.login(username='admin', password='admin') def tearDown(self): self.client.logout()
class AuthorizedTestCase(AnonymousTestCase):
def setUp(self): self.client = Client(enforce_csrf_checks=False) self.client.login(username='admin', password='admin') def tearDown(self): self.client.logout()
(TestCase): fixtures = [ 'user.json', 'profile.json', 'post.json', 'vote.json', 'comment.json', 'comment_vote.json' ] POST_ID = 9527 COMMENT_ID = 1 class AuthorizedTestCase(AnonymousTestCase):
64
64
50
9
54
knownsec/PyHackerNews
src/pyhn/libs/tests/base.py
Python
AuthorizedTestCase
AuthorizedTestCase
23
30
23
24
921cfbc22edf39d26e7618da2af290d8af338843
bigcode/the-stack
train
957850e85b9dff1b9838e8bc
train
function
@pytest.mark.version('>=2.0') def test_1(act_1: Action): act_1.expected_stdout = expected_stdout_1 act_1.execute() assert act_1.clean_stdout == act_1.clean_expected_stdout
@pytest.mark.version('>=2.0') def test_1(act_1: Action):
act_1.expected_stdout = expected_stdout_1 act_1.execute() assert act_1.clean_stdout == act_1.clean_expected_stdout
1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """PLAN (ST INDEX (I_F1_F2_ASC)) F1 F2 ============ ================== 100 55""" @pytest.mark.version('>=2.0') def test_1(act_1: Action):
64
64
52
19
45
FirebirdSQL/firebird-qa
tests/functional/arno/optimizer/test_opt_multi_index_selection_08.py
Python
test_1
test_1
83
87
83
84
67eaf6bafaaf4debbfbab9a1d203ef862290f807
bigcode/the-stack
train
7e0072fc10e990ec4438bab5
train
function
def draw_RGB_with_Rect2(RGB_image, Boundary_boxes, cp): ret, thresh = cv2.threshold(cp, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) x, y, width, height = cv2.boundingRect(contours[0]) y0 = y y1 = y + height x0 = x x1 = x + width roi...
def draw_RGB_with_Rect2(RGB_image, Boundary_boxes, cp):
ret, thresh = cv2.threshold(cp, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) x, y, width, height = cv2.boundingRect(contours[0]) y0 = y y1 = y + height x0 = x x1 = x + width roi = RGB_image[y:y + height, x:x + width] return roi
hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img, contours, -1, (0, 255, 0), 3) # ---------------------------------------------------------------------------- def draw_RGB_with_Rect2(RGB_image, Boundary_boxes, cp):
64
64
125
15
48
amrkh97/Lipify-LipReading
FunctionLevelLipsDetection/LipsBoundry.py
Python
draw_RGB_with_Rect2
draw_RGB_with_Rect2
37
46
37
37
5c71c7cd63f13a02fc541a76b8872626cd3972df
bigcode/the-stack
train
1b22876630a751ee92991074
train
function
def get_box2(img, RGB_img): bounding_boxes = [] masks = np.zeros(img.shape).astype("uint8") output = cv2.connectedComponentsWithStats(img, 8, cv2.CV_32S) index = 0 num_labels = output[0] labels = output[1] stats = output[2] if num_labels > 0: box_ratio_upper_bound = 1.1 b...
def get_box2(img, RGB_img):
bounding_boxes = [] masks = np.zeros(img.shape).astype("uint8") output = cv2.connectedComponentsWithStats(img, 8, cv2.CV_32S) index = 0 num_labels = output[0] labels = output[1] stats = output[2] if num_labels > 0: box_ratio_upper_bound = 1.1 box_ratio_lower_bound = 0.4 ...
ret, thresh = cv2.threshold(cp, 127, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) x, y, width, height = cv2.boundingRect(contours[0]) y0 = y y1 = y + height x0 = x x1 = x + width roi = RGB_image[y:y + height, x:x + width] return roi ...
144
144
481
9
134
amrkh97/Lipify-LipReading
FunctionLevelLipsDetection/LipsBoundry.py
Python
get_box2
get_box2
53
93
53
53
8be7170476e0ec2fbeab42357094e1dc12a2102b
bigcode/the-stack
train
ba195f265e3f7066884cad61
train
function
def mouthExtraction(img): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) R = img[:, :, 0] G = img[:, :, 1] B = img[:, :, 2] I = (((2 * G) - R - (0.5 * B)) / 4) I = binaryImage2(I) return I
def mouthExtraction(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) R = img[:, :, 0] G = img[:, :, 1] B = img[:, :, 2] I = (((2 * G) - R - (0.5 * B)) / 4) I = binaryImage2(I) return I
* N / 8)) x3 = x2 + int((2 * M / 5)) y3 = y2 + int((N / 2)) mouth = img[y2: y3, x2: x3] return mouth # ---------------------------------------------------------------------------- def mouthExtraction(img):
64
64
82
5
58
amrkh97/Lipify-LipReading
FunctionLevelLipsDetection/LipsBoundry.py
Python
mouthExtraction
mouthExtraction
20
27
20
20
8722d6f4a5689d5729b990a4bdee04d83b37adba
bigcode/the-stack
train
c78ae4e2441641fce18c8f21
train
function
def drawMouthContour(img): contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
def drawMouthContour(img):
contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE) cv2.drawContours(img, contours, -1, (0, 255, 0), 3)
0] G = img[:, :, 1] B = img[:, :, 2] I = (((2 * G) - R - (0.5 * B)) / 4) I = binaryImage2(I) return I # ---------------------------------------------------------------------------- def drawMouthContour(img):
64
64
56
7
56
amrkh97/Lipify-LipReading
FunctionLevelLipsDetection/LipsBoundry.py
Python
drawMouthContour
drawMouthContour
31
33
31
31
6afb91e2263c02d19dcdb06f32cced4edab7ae2c
bigcode/the-stack
train
007cc68634db4dfcc40f9c67
train
function
def extractMouthArea(img, y0, y1, x0, x1): N = y1 - y0 M = x1 - x0 x2 = x0 + int(M / 3) y2 = y0 + int((5 * N / 8)) x3 = x2 + int((2 * M / 5)) y3 = y2 + int((N / 2)) mouth = img[y2: y3, x2: x3] return mouth
def extractMouthArea(img, y0, y1, x0, x1):
N = y1 - y0 M = x1 - x0 x2 = x0 + int(M / 3) y2 = y0 + int((5 * N / 8)) x3 = x2 + int((2 * M / 5)) y3 = y2 + int((N / 2)) mouth = img[y2: y3, x2: x3] return mouth
import cv2 import numpy as np from SuportFunctions import binaryImage2 # ---------------------------------------------------------------------------- def extractMouthArea(img, y0, y1, x0, x1):
40
64
116
19
20
amrkh97/Lipify-LipReading
FunctionLevelLipsDetection/LipsBoundry.py
Python
extractMouthArea
extractMouthArea
8
16
8
8
394c59ed9e85662b2764f4240c6a1704b1c1926b
bigcode/the-stack
train
ede98aee7f5e00ca95a92618
train
function
def LocateOptionalPath(fileName, searchPaths): """Like LocatePath, but returns None if the user cancels. """ try: return LocatePath(fileName, searchPaths) except KeyboardInterrupt: return None
def LocateOptionalPath(fileName, searchPaths):
"""Like LocatePath, but returns None if the user cancels. """ try: return LocatePath(fileName, searchPaths) except KeyboardInterrupt: return None
os.path.abspath(retPath) def LocatePath(fileName, searchPaths): """Like LocateFileName, but returns a directory only. """ import os return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0]) def LocateOptionalPath(fileName, searchPaths):
64
64
49
10
54
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
LocateOptionalPath
LocateOptionalPath
184
190
184
184
79b9c56ed4b1ea2d1709c9675f2d0c288f17d510
bigcode/the-stack
train
56000f9f80343e84922d2d60
train
function
def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ): import regutil try: pathLook = FindHelpPath(helpFile, helpDesc, searchPaths) except error as details: print("*** ", details) return # print "%s found at %s" % (helpFile, pathLook) regutil.RegisterHelpFile(h...
def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ):
import regutil try: pathLook = FindHelpPath(helpFile, helpDesc, searchPaths) except error as details: print("*** ", details) return # print "%s found at %s" % (helpFile, pathLook) regutil.RegisterHelpFile(helpFile, pathLook, helpDesc)
""" import regutil, string fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths) if not ok: regutil.RegisterPythonExe(fname, exeAlias) return fname def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ):
64
64
88
16
47
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindRegisterHelpFile
FindRegisterHelpFile
298
307
298
298
a68a5011477444d5effe60a36640ef59e7b9c2ec
bigcode/the-stack
train
d9034455b723729e503b35cd
train
function
def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK import os, win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: path ...
def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK
import os, win32api, win32con try: key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS) try: try: path = win32api.RegQueryValueEx(key, helpDesc)[0] if FileExists(os.path.join(path, hel...
, packageName, knownFileName): # Found it ret = os.path.abspath(pathLook) return ret, ret raise error("The package %s can not be located" % packageName) def FindHelpPath(helpFile, helpDesc, searchPaths): # See if the current registry entry is OK
69
69
230
24
45
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindHelpPath
FindHelpPath
58
80
58
59
cdba70a581620416c73120cfcd45d54429274c8e
bigcode/the-stack
train
de54576c24d6e9be445603c4
train
function
def IsDebug(): """Return "_d" if we're running a debug version. This is to be used within DLL names when locating them. """ import imp for suffix_item in imp.get_suffixes(): if suffix_item[0]=='_d.pyd': return '_d' return ''
def IsDebug():
"""Return "_d" if we're running a debug version. This is to be used within DLL names when locating them. """ import imp for suffix_item in imp.get_suffixes(): if suffix_item[0]=='_d.pyd': return '_d' return ''
a known file name in the root of the package, see if this path is good. """ import os if knownFileName is None: knownFileName = "." return FileExists(os.path.join(os.path.join(path, packageName),knownFileName)) def IsDebug():
64
64
66
4
60
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
IsDebug
IsDebug
27
36
27
27
9f613d4ef285dfe5cf9072488e89582c21440b08
bigcode/the-stack
train
621d74446af73f45987a5e25
train
function
def LocatePythonCore(searchPaths): """Locate and validate the core Python directories. Returns a list of paths that should be used as the core (ie, un-named) portion of the Python path. """ import os, regutil currentPath = regutil.GetRegisteredNamedPath(None) if currentPath: prese...
def LocatePythonCore(searchPaths):
"""Locate and validate the core Python directories. Returns a list of paths that should be used as the core (ie, un-named) portion of the Python path. """ import os, regutil currentPath = regutil.GetRegisteredNamedPath(None) if currentPath: presearchPaths = currentPath.split(";") ...
None if the user cancels. """ try: return LocatePath(fileName, searchPaths) except KeyboardInterrupt: return None def LocateOptionalFileName(fileName, searchPaths = None): """Like LocateFileName, but returns None if the user cancels. """ try: return LocateFileName(file...
92
92
309
7
84
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
LocatePythonCore
LocatePythonCore
201
234
201
201
17c0d4d1dd14d8cbb3d10fdf9658d314c5737578
bigcode/the-stack
train
12e6c0dd3e7975dc27c3d9a0
train
function
def LocatePath(fileName, searchPaths): """Like LocateFileName, but returns a directory only. """ import os return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0])
def LocatePath(fileName, searchPaths):
"""Like LocateFileName, but returns a directory only. """ import os return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0])
,None) dlg.SetOFNTitle("Locate " + fileName) if dlg.DoModal() != win32con.IDOK: raise KeyboardInterrupt("User cancelled the process") retPath = dlg.GetPathName() return os.path.abspath(retPath) def LocatePath(fileName, searchPaths):
64
64
48
9
55
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
LocatePath
LocatePath
178
182
178
178
2d51edbe011922af9fa2349caae83d71e9766c66
bigcode/the-stack
train
19dbe2e057ba65d3bf02546a
train
function
def FindAppPath(appName, knownFileName, searchPaths): """Find an application. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ # Look in the first path. import regutil, string, os regPath = regutil.GetRegisteredNamedPath(appName) if reg...
def FindAppPath(appName, knownFileName, searchPaths):
"""Find an application. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ # Look in the first path. import regutil, string, os regPath = regutil.GetRegisteredNamedPath(appName) if regPath: pathLook = regPath.split(";")[0] if ...
= os.path.join(pathLook, "Help") if FileExists(os.path.join( pathLook, helpFile)): return os.path.abspath(pathLook) raise error("The help file %s can not be located" % helpFile) def FindAppPath(appName, knownFileName, searchPaths):
64
64
187
14
50
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindAppPath
FindAppPath
82
100
82
82
bf8f11e59c8f289da615600ee0c0a20d5368dde3
bigcode/the-stack
train
5128153f6202dac334b0c506
train
function
def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None): """Find and Register a Python exe (not necessarily *the* python.exe) Assumes the core registry setup correctly. """ import regutil, string fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths) if not ok: ...
def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None):
"""Find and Register a Python exe (not necessarily *the* python.exe) Assumes the core registry setup correctly. """ import regutil, string fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths) if not ok: regutil.RegisterPythonExe(fname, exeAlias) return fname
knownFile, searchPaths) if pathLook: paths.append(pathLook) except error as details: print("*** ", details) return regutil.RegisterNamedPath(appName, ";".join(paths)) def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None):
64
64
92
18
46
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindRegisterPythonExe
FindRegisterPythonExe
286
295
286
286
ce1c1eb37d25e413ad3cb5020044d7b2b3c48244
bigcode/the-stack
train
3c411da8b01a101fc85bb606
train
function
def IsPackageDir(path, packageName, knownFileName): """Given a path, a ni package name, and possibly a known file name in the root of the package, see if this path is good. """ import os if knownFileName is None: knownFileName = "." return FileExists(os.path.join(os.path.join(path, pa...
def IsPackageDir(path, packageName, knownFileName):
"""Given a path, a ni package name, and possibly a known file name in the root of the package, see if this path is good. """ import os if knownFileName is None: knownFileName = "." return FileExists(os.path.join(os.path.join(path, packageName),knownFileName))
! def FileExists(fname): """Check if a file exists. Returns true or false. """ import os try: os.stat(fname) return 1 except os.error as details: return 0 def IsPackageDir(path, packageName, knownFileName):
64
64
86
13
50
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
IsPackageDir
IsPackageDir
18
25
18
18
953fecd99cdb10dbd6196fd4872c706811be0172
bigcode/the-stack
train
54a0f0e7731747049893c8f0
train
function
def RegisterShellInfo(searchPaths): """Registers key parts of the Python installation with the Windows Shell. Assumes a valid, minimal Python installation exists (ie, SetupCore() has been previously successfully run) """ import regutil, win32con suffix = IsDebug() # Set up a pointer t...
def RegisterShellInfo(searchPaths):
"""Registers key parts of the Python installation with the Windows Shell. Assumes a valid, minimal Python installation exists (ie, SetupCore() has been previously successfully run) """ import regutil, win32con suffix = IsDebug() # Set up a pointer to the .exe's exePath = FindRegis...
# value check = os.path.join(sys.prefix, "PCBuild") if "64 bit" in sys.version: check = os.path.join(check, "amd64") if os.path.isdir(check): regutil.RegisterNamedPath("PCBuild",check) def RegisterShellInfo(searchPaths):
64
64
208
7
57
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
RegisterShellInfo
RegisterShellInfo
352
367
352
352
5ed835811702a6543f283dede7c324e97e8523e2
bigcode/the-stack
train
4d184584a9c87823fb8b757b
train
function
def LocateOptionalFileName(fileName, searchPaths = None): """Like LocateFileName, but returns None if the user cancels. """ try: return LocateFileName(fileName, searchPaths) except KeyboardInterrupt: return None
def LocateOptionalFileName(fileName, searchPaths = None):
"""Like LocateFileName, but returns None if the user cancels. """ try: return LocateFileName(fileName, searchPaths) except KeyboardInterrupt: return None
0]) def LocateOptionalPath(fileName, searchPaths): """Like LocatePath, but returns None if the user cancels. """ try: return LocatePath(fileName, searchPaths) except KeyboardInterrupt: return None def LocateOptionalFileName(fileName, searchPaths = None):
64
64
54
13
50
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
LocateOptionalFileName
LocateOptionalFileName
193
199
193
193
c0fabee86e0ccd137ea0594c4a215490bea9ce09
bigcode/the-stack
train
d8098c8db9f2fefd7a36f7c8
train
function
def FindPythonExe(exeAlias, possibleRealNames, searchPaths): """Find an exe. Returns the full path to the .exe, and a boolean indicating if the current registered entry is OK. We don't trust the already registered version even if it exists - it may be wrong (ie, for a different Python version...
def FindPythonExe(exeAlias, possibleRealNames, searchPaths):
"""Find an exe. Returns the full path to the .exe, and a boolean indicating if the current registered entry is OK. We don't trust the already registered version even if it exists - it may be wrong (ie, for a different Python version) """ import win32api, regutil, string, os, sys i...
# Search down the search paths. for pathLook in searchPaths: if FileExists(os.path.join(pathLook, knownFileName)): # Found it return os.path.abspath(pathLook) raise error("The file %s can not be located for application %s" % (knownFileName, appName)) def FindPythonExe(exeAlias, ...
83
83
277
15
68
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindPythonExe
FindPythonExe
102
128
102
102
5727a6a38b8f1f2f5a9cc9e87761afd427dc4e34
bigcode/the-stack
train
4087c0b0c353404d3b03edd4
train
function
def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName = None): """Find and Register a package. Assumes the core registry setup correctly. In addition, if the location located by the package is already in the **core** path, then an entry is registered, but no path. ...
def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName = None):
"""Find and Register a package. Assumes the core registry setup correctly. In addition, if the location located by the package is already in the **core** path, then an entry is registered, but no path. (no other paths are checked, as the application whose path was used may later...
is not None: corePath = LocatePath("unicodedata%s.pyd" % suffix, searchPaths) if corePath is None: raise error("The core Python path could not be located.") installPath = os.path.abspath(os.path.join(libPath, "..")) return installPath, [libPath, corePath] def FindRegisterPackage(packageNam...
90
90
300
19
71
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindRegisterPackage
FindRegisterPackage
236
262
236
236
203df41d6fd84d663bfba1cf5a876e50a8056945
bigcode/the-stack
train
eb0bd3d9a09cad1af4fd0be4
train
function
def FindPackagePath(packageName, knownFileName, searchPaths): """Find a package. Given a ni style package name, check the package is registered. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ import regutil, os pathLook = regutil....
def FindPackagePath(packageName, knownFileName, searchPaths):
"""Find a package. Given a ni style package name, check the package is registered. First place looked is the registry for an existing entry. Then the searchPaths are searched. """ import regutil, os pathLook = regutil.GetRegisteredNamedPath(packageName) if pathLook and IsPack...
. This is to be used within DLL names when locating them. """ import imp for suffix_item in imp.get_suffixes(): if suffix_item[0]=='_d.pyd': return '_d' return '' def FindPackagePath(packageName, knownFileName, searchPaths):
64
64
178
14
50
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindPackagePath
FindPackagePath
38
56
38
38
5286aad5774933bad33c8d699f2dcacf132080e5
bigcode/the-stack
train
32abaf47085c84b8cbd11598
train
function
def FindRegisterApp(appName, knownFiles, searchPaths): """Find and Register a package. Assumes the core registry setup correctly. """ import regutil, string if type(knownFiles)==type(''): knownFiles = [knownFiles] paths=[] try: for knownFile in knownFiles: pa...
def FindRegisterApp(appName, knownFiles, searchPaths):
"""Find and Register a package. Assumes the core registry setup correctly. """ import regutil, string if type(knownFiles)==type(''): knownFiles = [knownFiles] paths=[] try: for knownFile in knownFiles: pathLook = FindAppPath(appName, knownFile, searchPaths) ...
Name, details)) print("*** Please ensure you have passed the correct paths on the command line.") print("*** - For packages, you should pass a path to the packages parent directory,") print("*** - and not the package directory itself...") def FindRegisterApp(appName, knownFiles, searchPaths):
63
64
127
13
51
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FindRegisterApp
FindRegisterApp
265
284
265
265
9db0bb89de6c5b42070f8081a6df9726f3e5e652
bigcode/the-stack
train
40e06020b70347133123dc75
train
function
def QuotedFileName(fname): """Given a filename, return a quoted version if necessary """ import regutil, string try: fname.index(" ") # Other chars forcing quote? return '"%s"' % fname except ValueError: # No space in name. return fname
def QuotedFileName(fname):
"""Given a filename, return a quoted version if necessary """ import regutil, string try: fname.index(" ") # Other chars forcing quote? return '"%s"' % fname except ValueError: # No space in name. return fname
try: registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias) registered_ok = found==registered except win32api.error: pass return found, registered_ok def QuotedFileName(fname):
64
64
68
7
56
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
QuotedFileName
QuotedFileName
130
139
130
130
4ff7db13329e27d0dac0b98b065703b5bfd37a4b
bigcode/the-stack
train
3f043e6bdcef971a011fd3c3
train
function
def FileExists(fname): """Check if a file exists. Returns true or false. """ import os try: os.stat(fname) return 1 except os.error as details: return 0
def FileExists(fname):
"""Check if a file exists. Returns true or false. """ import os try: os.stat(fname) return 1 except os.error as details: return 0
# A tool to setup the Python registry. class error(Exception): pass import sys # at least we can count on this! def FileExists(fname):
32
64
50
5
27
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
FileExists
FileExists
8
16
8
8
1ad1ef5d33fd40ed32bbc8bcb7de9361463a6f9b
bigcode/the-stack
train
4d54674bb54d0dfeee55a0a5
train
function
def SetupCore(searchPaths): """Setup the core Python information in the registry. This function makes no assumptions about the current state of sys.path. After this function has completed, you should have access to the standard Python library, and the standard Win32 extensions """ im...
def SetupCore(searchPaths):
"""Setup the core Python information in the registry. This function makes no assumptions about the current state of sys.path. After this function has completed, you should have access to the standard Python library, and the standard Win32 extensions """ import sys for path in sea...
searchPaths) if not ok: regutil.RegisterPythonExe(fname, exeAlias) return fname def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ): import regutil try: pathLook = FindHelpPath(helpFile, helpDesc, searchPaths) except error as details: print("*** ", details) ...
117
117
390
6
111
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
SetupCore
SetupCore
309
350
309
309
b5f0a13a05ff6639f0654f3d08182459df257bbd
bigcode/the-stack
train
457f2603ccd43c8a52e5bdd5
train
class
class error(Exception): pass
class error(Exception):
pass
# A tool to setup the Python registry. class error(Exception):
13
64
7
4
9
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
error
error
3
4
3
3
1d7ff5edbc7d9e7d9e9055f6cab0637fb51786c0
bigcode/the-stack
train
a1248ffe8c5f999ae0e710ad
train
function
def LocateFileName(fileNamesString, searchPaths): """Locate a file name, anywhere on the search path. If the file can not be located, prompt the user to find it for us (using a common OpenFile dialog) Raises KeyboardInterrupt if the user cancels. """ import regutil, string, os fil...
def LocateFileName(fileNamesString, searchPaths):
"""Locate a file name, anywhere on the search path. If the file can not be located, prompt the user to find it for us (using a common OpenFile dialog) Raises KeyboardInterrupt if the user cancels. """ import regutil, string, os fileNames = fileNamesString.split(";") for path i...
registered_ok = found==registered except win32api.error: pass return found, registered_ok def QuotedFileName(fname): """Given a filename, return a quoted version if necessary """ import regutil, string try: fname.index(" ") # Other chars forcing quote? return '"%s"' % f...
103
103
344
11
91
sshaky2/python-netflow-v9-softflowd
venv/Lib/site-packages/win32/scripts/regsetup.py
Python
LocateFileName
LocateFileName
141
176
141
141
e4958a89096f2c83829e5fd65a1dff6c00897744
bigcode/the-stack
train
4c7e362ca4cab4652f544fcc
train
class
class Basic(): def __init__(self, x, action, history): self.w = w self.x = x self.b = b self.action = action self.history = histoty def line(self, w, x, b): result = self.w * self.x + self.b return result def exp_reward(self): ...
class Basic():
def __init__(self, x, action, history): self.w = w self.x = x self.b = b self.action = action self.history = histoty def line(self, w, x, b): result = self.w * self.x + self.b return result def exp_reward(self): rewards = his...
rewards): best_action = 0 max_action_value = 0 for action in actions: cur_action_value = rewards if cur_action_value > max_action_value: best_action = action max_action_value = cur_action_value return best_action class Basic():
63
64
107
3
59
seongmin-Jo/DeepRL_in-action
chapter 2/get_best_action.py
Python
Basic
Basic
37
52
37
37
98801b1d8790bd51f8e577a38d7084ef15ce7671
bigcode/the-stack
train
392980452c16a8005c5acf21
train
class
class get_beset_action(): def __init__(self, episodes): self.episodes = episodes def get_action_and_reward(self): actions = np.zeros(self.episodes) rewards = 0 for episode in range(1, self.episodes): env = gym.make('CartPole-v0') state =...
class get_beset_action():
def __init__(self, episodes): self.episodes = episodes def get_action_and_reward(self): actions = np.zeros(self.episodes) rewards = 0 for episode in range(1, self.episodes): env = gym.make('CartPole-v0') state = env.reset() d...
import numpy as np import gym class get_beset_action():
15
64
200
7
7
seongmin-Jo/DeepRL_in-action
chapter 2/get_best_action.py
Python
get_beset_action
get_beset_action
4
33
4
4
e7a26ac930d0d83a01c4db69611044cf80860b0f
bigcode/the-stack
train
9837ae0769fca0e7dfa6330b
train
function
def load_data(): return
def load_data():
return
# https://github.com/twopirllc/pandas-ta import pandas as pd import pandas_ta as ta import investpy as iv # Get data def get_data(): return # Load data def load_data():
52
64
7
4
47
spideynolove/Other-repo
davidgoliath/project/forexcalculator/tasks/candlepatterns.py
Python
load_data
load_data
13
14
13
13
7876a262d9c90a65d19d3dddb57066d9c3c0b91d
bigcode/the-stack
train
73311edad76ea3d5be26e8dd
train
function
def get_data(): return
def get_data():
return
# https://github.com/twopirllc/pandas-ta import pandas as pd import pandas_ta as ta import investpy as iv # Get data def get_data():
41
64
7
4
36
spideynolove/Other-repo
davidgoliath/project/forexcalculator/tasks/candlepatterns.py
Python
get_data
get_data
8
9
8
8
862160d02d164308f74fdbbf981e3f9b122528d3
bigcode/the-stack
train
fd81df796ca439e9bb41ead9
train
function
def main(): pass
def main():
pass
# https://github.com/twopirllc/pandas-ta import pandas as pd import pandas_ta as ta import investpy as iv # Get data def get_data(): return # Load data def load_data(): return def main():
58
64
6
3
54
spideynolove/Other-repo
davidgoliath/project/forexcalculator/tasks/candlepatterns.py
Python
main
main
17
18
17
17
378685506c7f6439c83db41d6cba95c3fcdadc8e
bigcode/the-stack
train
000f26a334409673119e8e35
train
class
class PathListingWidgetTest( GafferUITest.TestCase ) : def testExpandedPaths( self ) : d = {} for i in range( 0, 10 ) : dd = {} for j in range( 0, 10 ) : dd[str(j)] = j d[str(i)] = dd p = Gaffer.DictPath( d, "/" ) w = GafferUI.PathListingWidget( p ) _GafferUI._pathListingWidgetAttachTester( ...
class PathListingWidgetTest( GafferUITest.TestCase ) :
def testExpandedPaths( self ) : d = {} for i in range( 0, 10 ) : dd = {} for j in range( 0, 10 ) : dd[str(j)] = j d[str(i)] = dd p = Gaffer.DictPath( d, "/" ) w = GafferUI.PathListingWidget( p ) _GafferUI._pathListingWidgetAttachTester( GafferUI._qtAddress( w._qtWidget() ) ) self.assertEqua...
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 A...
256
256
9,725
14
241
GafferHQ/gaffer
python/GafferUITest/PathListingWidgetTest.py
Python
PathListingWidgetTest
PathListingWidgetTest
52
964
52
53
fbfaf36948bf9263f603ec5638c6138ef21882a4
bigcode/the-stack
train
368f2b59655b1af39c2025e8
train
class
@dataclass class Root: class Meta: name = "root" namespace = "http://xstest-tns/IBMd3_16v07" union_element: List[Union[XmlDate, int, str]] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, ...
@dataclass class Root:
class Meta: name = "root" namespace = "http://xstest-tns/IBMd3_16v07" union_element: List[Union[XmlDate, int, str]] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 1, "pattern": r"[a-z][x...
from dataclasses import dataclass, field from typing import List, Union from xsdata.models.datatype import XmlDate __NAMESPACE__ = "http://xstest-tns/IBMd3_16v07" @dataclass class Root:
54
64
99
6
48
tefra/xsdata-w3c-tests
output/models/ibm_data/valid/s3_16_2/s3_16_2v07_xsd/s3_16_2v07.py
Python
Root
Root
8
22
8
9
180ad2a5ba95c1e01ff8ea80f4cd504640ecb6c6
bigcode/the-stack
train
25e294b759d88d96d2c67312
train
class
class ClientCommunicationConsumer(WebsocketConsumer): """ The websocket connection used by EVERY player - it is used to login and talk to the game server """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None # Link to the user account self....
class ClientCommunicationConsumer(WebsocketConsumer):
""" The websocket connection used by EVERY player - it is used to login and talk to the game server """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None # Link to the user account self.player_id = None # Link to the player data of this ac...
STANTS as CONSTANTS from .message_utils import error_message from websocket_controller.auth_event_handler import handle_auth_event from .disconnect_event_handler import handle_disconnect_event # TODO: REMOVE THIS MONSTER LATER from . import auth_event_handler, building_placement_request_handler, guild_creation_reques...
145
145
486
8
137
nokia-wroclaw/innovativeproject-city-game
city_game_backend/websocket_controller/consumers.py
Python
ClientCommunicationConsumer
ClientCommunicationConsumer
24
92
24
24
20ae3abbf7d802a5c8f6e99184454f33131370a5
bigcode/the-stack
train
beb7200a2d8699ffef14c9cb
train
class
class ListConversationsResponse(proto.Message): r"""The response message for [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. Attributes: conversations (Sequence[google.cloud.dialogflow_v2.types.Conversation]): The list of conversations. The...
class ListConversationsResponse(proto.Message):
r"""The response message for [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. Attributes: conversations (Sequence[google.cloud.dialogflow_v2.types.Conversation]): The list of conversations. There will be a maximum number of items...
__. """ parent = proto.Field(proto.STRING, number=1,) page_size = proto.Field(proto.INT32, number=2,) page_token = proto.Field(proto.STRING, number=3,) filter = proto.Field(proto.STRING, number=4,) class ListConversationsResponse(proto.Message):
63
64
165
8
55
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
ListConversationsResponse
ListConversationsResponse
189
210
189
189
2ad6f32533562a5c04ae76730dd8f46820137eb5
bigcode/the-stack
train
330f99e6ac2b575a1caa0b40
train
class
class Conversation(proto.Message): r"""Represents a conversation. A conversation is an interaction between an agent, including live agents and Dialogflow agents, and a support customer. Conversations can include phone calls and text-based chat sessions. Attributes: name (str): ...
class Conversation(proto.Message):
r"""Represents a conversation. A conversation is an interaction between an agent, including live agents and Dialogflow agents, and a support customer. Conversations can include phone calls and text-based chat sessions. Attributes: name (str): Output only. The unique identifi...
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 I...
227
227
757
5
222
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
Conversation
Conversation
38
109
38
38
8c6932350aad070df37a86d92e42bf5b7c81136b
bigcode/the-stack
train
1af955234ee9134889cb02b1
train
class
class ListMessagesResponse(proto.Message): r"""The response message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. Attributes: messages (Sequence[google.cloud.dialogflow_v2.types.Message]): The list of messages. There will be a maximum number of...
class ListMessagesResponse(proto.Message):
r"""The response message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. Attributes: messages (Sequence[google.cloud.dialogflow_v2.types.Message]): The list of messages. There will be a maximum number of items returned based on the pa...
list request. """ parent = proto.Field(proto.STRING, number=1,) filter = proto.Field(proto.STRING, number=4,) page_size = proto.Field(proto.INT32, number=2,) page_token = proto.Field(proto.STRING, number=3,) class ListMessagesResponse(proto.Message):
63
64
179
7
56
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
ListMessagesResponse
ListMessagesResponse
274
297
274
274
a5b0a6dd171a34fa8e7374eb98ae351852d58189
bigcode/the-stack
train
45feb9dd998123e259947fa4
train
class
class GetConversationRequest(proto.Message): r"""The request message for [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. Attributes: name (str): Required. The name of the conversation. Format: ``projects/<Project ID>/locations/<Loca...
class GetConversationRequest(proto.Message):
r"""The request message for [Conversations.GetConversation][google.cloud.dialogflow.v2.Conversations.GetConversation]. Attributes: name (str): Required. The name of the conversation. Format: ``projects/<Project ID>/locations/<Location ID>/conversations/<Conversation ID>``. ...
list. """ @property def raw_page(self): return self conversations = proto.RepeatedField( proto.MESSAGE, number=1, message="Conversation", ) next_page_token = proto.Field(proto.STRING, number=2,) class GetConversationRequest(proto.Message):
63
64
86
7
56
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
GetConversationRequest
GetConversationRequest
213
223
213
213
0335f406b376f8320bac18ecc0166a662efc6f64
bigcode/the-stack
train
2cb41d9bda12fbeccae59e8d
train
class
class ListConversationsRequest(proto.Message): r"""The request message for [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. Attributes: parent (str): Required. The project from which to list all conversation. Format: ``projects/<...
class ListConversationsRequest(proto.Message):
r"""The request message for [Conversations.ListConversations][google.cloud.dialogflow.v2.Conversations.ListConversations]. Attributes: parent (str): Required. The project from which to list all conversation. Format: ``projects/<Project ID>/locations/<Location ID>``. ...
in range of [3,64]. If the field is provided, the caller is resposible for 1. the uniqueness of the ID, otherwise the request will be rejected. 2. the consistency for whether to use custom ID or not under a project to better ensure uniquenes...
120
121
404
8
112
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
ListConversationsRequest
ListConversationsRequest
144
186
144
144
5c25c3998dfd0cd759f3b9b52d0641c9236bb49c
bigcode/the-stack
train
97ef1d74326535426bed03f2
train
class
class CreateConversationRequest(proto.Message): r"""The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. Attributes: parent (str): Required. Resource identifier of the project creating the conversation. Form...
class CreateConversationRequest(proto.Message):
r"""The request message for [Conversations.CreateConversation][google.cloud.dialogflow.v2.Conversations.CreateConversation]. Attributes: parent (str): Required. Resource identifier of the project creating the conversation. Format: ``projects/<Project ID>/location...
( proto.MESSAGE, number=4, message="ConversationPhoneNumber", ) start_time = proto.Field(proto.MESSAGE, number=5, message=timestamp_pb2.Timestamp,) end_time = proto.Field(proto.MESSAGE, number=6, message=timestamp_pb2.Timestamp,) conversation_stage = proto.Field(proto.ENUM, number=7, enum=Conver...
83
84
283
7
76
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
CreateConversationRequest
CreateConversationRequest
112
141
112
112
d7f4c6deabf809147c12a107cb90028e689e2bae
bigcode/the-stack
train
7fd16edbaf63bbabd05f2436
train
class
class ConversationPhoneNumber(proto.Message): r"""Represents a phone number for telephony integration. It allows for connecting a particular conversation over telephony. Attributes: phone_number (str): Output only. The phone number to connect to this conversation. """ ...
class ConversationPhoneNumber(proto.Message):
r"""Represents a phone number for telephony integration. It allows for connecting a particular conversation over telephony. Attributes: phone_number (str): Output only. The phone number to connect to this conversation. """ phone_number = proto.Field(proto.STRING, nu...
list. """ @property def raw_page(self): return self messages = proto.RepeatedField( proto.MESSAGE, number=1, message=participant.Message, ) next_page_token = proto.Field(proto.STRING, number=2,) class ConversationPhoneNumber(proto.Message):
63
64
72
7
56
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
ConversationPhoneNumber
ConversationPhoneNumber
300
310
300
300
881224480add61eddacbf83b6553bcc27d851f48
bigcode/the-stack
train
7e39456552bc62bdb77f2575
train
class
class CompleteConversationRequest(proto.Message): r"""The request message for [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. Attributes: name (str): Required. Resource identifier of the conversation to close. Format: ...
class CompleteConversationRequest(proto.Message):
r"""The request message for [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. Attributes: name (str): Required. Resource identifier of the conversation to close. Format: ``projects/<Project ID>/locations/<Locatio...
.GetConversation]. Attributes: name (str): Required. The name of the conversation. Format: ``projects/<Project ID>/locations/<Location ID>/conversations/<Conversation ID>``. """ name = proto.Field(proto.STRING, number=1,) class CompleteConversationRequest(proto.Message):
63
64
91
7
56
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
CompleteConversationRequest
CompleteConversationRequest
226
237
226
226
f1603143150fc9e53f8b227ab2f9ea4059d50148
bigcode/the-stack
train
37ad9dd656fa420e496c35df
train
class
class ListMessagesRequest(proto.Message): r"""The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. Attributes: parent (str): Required. The name of the conversation to list messages for. Format: ``projects/<P...
class ListMessagesRequest(proto.Message):
r"""The request message for [Conversations.ListMessages][google.cloud.dialogflow.v2.Conversations.ListMessages]. Attributes: parent (str): Required. The name of the conversation to list messages for. Format: ``projects/<Project ID>/locations/<Location ID>/convers...
"""The request message for [Conversations.CompleteConversation][google.cloud.dialogflow.v2.Conversations.CompleteConversation]. Attributes: name (str): Required. Resource identifier of the conversation to close. Format: ``projects/<Project ID>/locations/<Location ID>...
89
90
301
7
82
reichenbch/python-dialogflow
google/cloud/dialogflow_v2/types/conversation.py
Python
ListMessagesRequest
ListMessagesRequest
240
271
240
240
444767de1a842e7d5647aff7b5ce356f81ea2d49
bigcode/the-stack
train
8d179341bd62313f19c772f5
train
function
def getPreM(agent): ''' gets prematchings for t-algorithm ''' updated = [] for w in agent.getRanking(): for j in agent.getMatchings(): if(w == j.getName()): updated.append(j) continue return updated
def getPreM(agent):
''' gets prematchings for t-algorithm ''' updated = [] for w in agent.getRanking(): for j in agent.getMatchings(): if(w == j.getName()): updated.append(j) continue return updated
for i in range(len(past)): if(len(past[i]) != len(current[i])): return False for j in range(len(past[i])): if(past[i][j] != current[i][j]): return False return True def getPreM(agent):
64
64
61
7
56
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
getPreM
getPreM
785
793
785
785
def01caf260ae406aa53e59da3f4454135c11859
bigcode/the-stack
train
34b71ecb8cd9911529726f00
train
function
def fillInUtilities(hospital, hospital_names, worker_index, cu_sorted, iu_sorted, utilities_sorted): ''' Hospital_names, cu_sorted, iu_sorted, utilities_sorted are all in the same order (each entry is a preference list for a hospital) Within the cu_sorted, iu_sorted, utilities_sorted lists, they preferences...
def fillInUtilities(hospital, hospital_names, worker_index, cu_sorted, iu_sorted, utilities_sorted):
''' Hospital_names, cu_sorted, iu_sorted, utilities_sorted are all in the same order (each entry is a preference list for a hospital) Within the cu_sorted, iu_sorted, utilities_sorted lists, they preferences lists are in the order of doctors with highest CU first worker_index is 0 for the doctor with hi...
is None): return 0 # unmatched for i in range(len(pprime)): if(pprime[i] == h.getName()): return i + 1 return -1 def fillInUtilities(hospital, hospital_names, worker_index, cu_sorted, iu_sorted, utilities_sorted):
64
64
191
22
41
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
fillInUtilities
fillInUtilities
857
869
857
857
76d619d61e84cd0820b1d83f8f99f6c1793f846e
bigcode/the-stack
train
ba9bf5c01e5f4012bc8dbe20
train
function
def getRank(desired, judge): ranking = judge.getP_dict() return ranking[desired.getName()]
def getRank(desired, judge):
ranking = judge.getP_dict() return ranking[desired.getName()]
ranking[x] = ranking[y] pref[y] = temp1 ranking[y] = temp2 def getEquiv(avail, judge): equiv = [] for a in avail: equiv.append(getRank(a, judge)) return equiv def getRank(desired, judge):
64
64
24
8
55
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
getRank
getRank
748
750
748
748
0adb95af13ad07aeecbc368e5f9913e5d85fbbcc
bigcode/the-stack
train
2c6cbc4773931aee8322174a
train
function
def fastersort(pref, ranking): # note this sorts in ascending order # previous sorts sort in descending order since the first argument, "pref" # represents utilities # here, "pref" represents a ranking, so we want "1" to be first return zip(*sorted(zip(pref, ranking)))
def fastersort(pref, ranking): # note this sorts in ascending order # previous sorts sort in descending order since the first argument, "pref" # represents utilities # here, "pref" represents a ranking, so we want "1" to be first
return zip(*sorted(zip(pref, ranking)))
] return top def fastersort(pref, ranking): # note this sorts in ascending order # previous sorts sort in descending order since the first argument, "pref" # represents utilities # here, "pref" represents a ranking, so we want "1" to be first
64
64
69
59
4
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
fastersort
fastersort
720
725
720
724
aa7198f24c29e1a69c334206ebb9ccf31445e246
bigcode/the-stack
train
fa16250e2edbd7bcf7850f4e
train
class
class Hospital(object): name = "" p = [] #original preferences, list of strings of names of workers ranked, unchanged p_dict = {} # same as above but as a dictionary ranking = [] #list of strings of names of workers ranked matchings = [] #list of workers that hospital is matched to, t-algorithm ...
class Hospital(object):
name = "" p = [] #original preferences, list of strings of names of workers ranked, unchanged p_dict = {} # same as above but as a dictionary ranking = [] #list of strings of names of workers ranked matchings = [] #list of workers that hospital is matched to, t-algorithm wishes = [] #list of nam...
if(self.current is None): #since every hospital is ranked in p, then if worker is unmatched it prefers h to being unmatched return True for h2 in self.p: if(h2 == self.current.getName()): return False if(h2 == h.getName()): return Tru...
256
256
3,028
4
251
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
Hospital
Hospital
327
680
327
327
4e2034e9969c831440b7f41b90090922f1882a85
bigcode/the-stack
train
41e45a3026ee702e28d8acb2
train
function
def doGS(workers, hospitals, x, y, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_p_docs, match_gs_pp_docs, array_to_record, num_doctors, min_index, match_name): # Here, we run Gale Shapley with no interview stage # Thus, we see what happens if there were no interviews and ...
def doGS(workers, hospitals, x, y, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_p_docs, match_gs_pp_docs, array_to_record, num_doctors, min_index, match_name): # Here, we run Gale Shapley with no interview stage # Thus, we see what happens if there were no interviews and ...
w3gs = [] h3gs = [] for w in workers: w.setWishes2() #sets wishes according to original preferences w.setMatch(None) w3gs.append(w) for h in hospitals: h.setWishes2() #sets wishes according to original preferences h.setMatch(None) h3gs.append(h) prin...
only if (h.getCurrent() is None): match_name.append("Unmatched") else: match_name.append(h.getCurrent().getName()) # now we record blocking pairs recordBlockingPairs(x, y, w5, h5, array_to_record, num_doctors, min_index) def doGS(workers, hospitals, x, y, doDocsPropose,...
166
166
556
99
67
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
doGS
doGS
999
1,054
999
1,002
4bcf51ec8ec7a45cb08cb80077c0753ea2b1ca87
bigcode/the-stack
train
926191b9015ad9bbfd39842d
train
class
class Worker(object): name = "" p = [] #original preferences, list of strings of names of hospitals ranked, unchanged p_dict = {} # same as p but as a mapping of hospital name to ranking in p ranking = [] #list of strings of names of hospitals ranked matchings = [] #list of hospitals that worker is ...
class Worker(object):
name = "" p = [] #original preferences, list of strings of names of hospitals ranked, unchanged p_dict = {} # same as p but as a mapping of hospital name to ranking in p ranking = [] #list of strings of names of hospitals ranked matchings = [] #list of hospitals that worker is matched to, t-algorith...
# -*- coding: utf-8 -*- """faster_simulations_sigs_revised.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1_-oQDQXJCYRE3JnPBMlYaLIdoBOpX25f """ import numpy as np import pandas as pd class Worker(object):
84
256
2,438
4
79
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
Worker
Worker
13
321
13
13
201863ad71cfe7ce2317122b8de69a5b7939aadd
bigcode/the-stack
train
8e1625a1f6d0e5f9b29dcc8a
train
function
def doTruncatedGS(workers, hospitals, x, y, max_interviews, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_truncated_pp_docs, match_gs_truncated_p_docs, array_to_record, num_doctors, min_index, match_name): w5 = [] h5 = [] for w in workers: w.setWishes3(max_intervie...
def doTruncatedGS(workers, hospitals, x, y, max_interviews, doDocsPropose, doctors_p, doctors_pprime, hospitals_p, hospital_pprime, match_gs_truncated_pp_docs, match_gs_truncated_p_docs, array_to_record, num_doctors, min_index, match_name):
w5 = [] h5 = [] for w in workers: w.setWishes3(max_interviews) # sets wishes according to original preferences, but truncated w.setMatch(None) w5.append(w) for h in hospitals: h.setWishes2() # sets wishes according to original preferences h.setMatch(None) ...
# get the actual worker w = name_to_worker[d] for j in range(len(y)): e = y[j] # get the actual hospital h = name_to_hospital[e] if(h.block(w) and w.block(h)): array_to_record[i + min_index] += 1 arra...
155
155
518
67
87
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
doTruncatedGS
doTruncatedGS
947
997
947
947
d47abfd00ea8100e503f48a4c6eadd3bf99b5252
bigcode/the-stack
train
901407b76ffda26d76bc03bc
train
function
def getEquiv(avail, judge): equiv = [] for a in avail: equiv.append(getRank(a, judge)) return equiv
def getEquiv(avail, judge):
equiv = [] for a in avail: equiv.append(getRank(a, judge)) return equiv
swap(pref, ranking, x, y): temp1 = pref[x] temp2 = ranking[x] pref[x] = pref[y] ranking[x] = ranking[y] pref[y] = temp1 ranking[y] = temp2 def getEquiv(avail, judge):
64
64
32
9
54
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
getEquiv
getEquiv
742
746
742
742
fecd7e765c9e2e48e0d9a4da914f94ede9e6f964
bigcode/the-stack
train
af91e4f6f4df48fa11ccc411
train
function
def getR2(w): ''' gets the rank of hospital w is matched to based on p (original preferences) (this is based on matchings after both t-algorithm and Gale Shapley are run) ''' h = w.getCurrent() if(h is None): return 0 # unmatched for i in range(len(w.getRanking())): if(w.getR...
def getR2(w):
''' gets the rank of hospital w is matched to based on p (original preferences) (this is based on matchings after both t-algorithm and Gale Shapley are run) ''' h = w.getCurrent() if(h is None): return 0 # unmatched for i in range(len(w.getRanking())): if(w.getRanking()[i] ==...
preferences ''' h = w.getCurrent() if(h is None): return 0 # unmatched for i in range(len(w.getMatchings())): if(w.getMatchings()[i].getName() == h.getName()): return i + 1 def getR2(w):
64
64
98
6
57
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
getR2
getR2
834
843
834
834
a60b4de90180b0640f4d67ddd371532532734de1
bigcode/the-stack
train
c9753253d2aefd78073e0ea9
train
function
def proposals(workers,hospitals): ''' gale shapley algorithm where workers propose If order of parameters is switched then hospitals propose ''' while(len(workers)>0): y = None for i in range(len(workers)): w = workers[0] y = None if(len...
def proposals(workers,hospitals):
''' gale shapley algorithm where workers propose If order of parameters is switched then hospitals propose ''' while(len(workers)>0): y = None for i in range(len(workers)): w = workers[0] y = None if(len(w.getWishes()) > 0 and w.getCurren...
''' gets prematchings for t-algorithm ''' updated = [] for w in agent.getRanking(): for j in agent.getMatchings(): if(w == j.getName()): updated.append(j) continue return updated def proposals(workers,hospitals):
64
64
116
9
54
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
proposals
proposals
795
810
795
795
e6a5cd5115a8286f21a8eb0e8c8e728903fc970c
bigcode/the-stack
train
78f3faa0725231e356e113ae
train
function
def runSIGSOnly(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, match_in_pp_docs, match_in_p_docs, cu_ranks): workers, hospitals, workers2, workers3, hospitals2, cuw, cuh = getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals) ...
def runSIGSOnly(num_doctors, num_hospitals, we_doctors, we_hospitals, max_interviews, ids, docs, works, types, runs, run_num, match_in_pp_docs, match_in_p_docs, cu_ranks):
workers, hospitals, workers2, workers3, hospitals2, cuw, cuh = getDoctorsAndHospitals(num_doctors, num_hospitals, we_doctors, we_hospitals) # First, we simply update the docs, works, and runs lists addDoctorsAndWorkersToLists(num_doctors, num_hospitals, docs, works, types, runs, run_num, cu_ranks) # T...
_name.append(w.getCurrent().getName()) # Now we do the same thing, but recording the matchings for hospitals for i in range(len(y)): d = y[i] # get the actual hospital h = h3gs_nameToWorkerDict[d] match_gs_pp_docs.append(getR3(h, hospital_pprime[i])) match_gs_p_docs.ap...
256
256
1,291
54
201
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
runSIGSOnly
runSIGSOnly
1,058
1,176
1,058
1,058
2b73636038c4c3bdb7cc031a287dbc54f6d140ce
bigcode/the-stack
train
116b7523202b42b57a35bbac
train
function
def getDoctorsAndHospitalsExtended(num_doctors, num_hospitals, we_doctors, we_hospitals): ''' we_doctors is weight for common utility for doctors we_hospitals is weight for common utility for hospitals ''' # First, note that we can change the distribution and its parameters for common utility ...
def getDoctorsAndHospitalsExtended(num_doctors, num_hospitals, we_doctors, we_hospitals):
''' we_doctors is weight for common utility for doctors we_hospitals is weight for common utility for hospitals ''' # First, note that we can change the distribution and its parameters for common utility cuw = [np.random.normal(0, 1) for x in range(num_hospitals)] # common utility hospitals...
creates array of workers with their own randomized preferences hospitals2 = [Hospital(cuh, "H" + str(x), we_hospitals, num_doctors) for x in range(1, num_hospitals + 1)] # creates array of hospitals with their own randomized preferences workers3 = [Worker(cuw, "W" + str(x), we_doctors, num_hospitals) for x in ...
157
157
525
25
131
alistairjwilson/nrmpInterviews_SimData
500SIGS/Code to Run SIGS only/Sim500_5_50_75.py
Python
getDoctorsAndHospitalsExtended
getDoctorsAndHospitalsExtended
888
905
888
888
8962a4ce8d856f399fa3dee8a8df939ead0c4cee
bigcode/the-stack
train