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
8c9a7d507e750f6953abd89f
train
class
class SpotifyPlaybackError(Exception): pass
class SpotifyPlaybackError(Exception):
pass
user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', )) SPOTIFY_OAUTH_REDIRECT_SERVER_PORT = 5000 class DeviceNotFoundError(Exception): pass class SpotifyOAuthCredentialsError(Exception): pass class SpotifyPlaybackError(Exception):
64
64
9
6
57
eriklindebratt/flic-chromecast-love
caster.py
Python
SpotifyPlaybackError
SpotifyPlaybackError
53
54
53
53
dcfb0ab09dfce95c4d5de224b9f2a51b1e843df0
bigcode/the-stack
train
37a7099547faf2e3e9a4ade4
train
function
def _getSpotifyAvailableDevices(calledFromSelf=False): if not _spotifyClient: raise Exception('Spotify client is not set up') try: devices = _spotifyClient.devices().get('devices', []) except spotipy.client.SpotifyException: if calledFromSelf: logger.exception( ...
def _getSpotifyAvailableDevices(calledFromSelf=False):
if not _spotifyClient: raise Exception('Spotify client is not set up') try: devices = _spotifyClient.devices().get('devices', []) except spotipy.client.SpotifyException: if calledFromSelf: logger.exception( 'Error: Failed to get Spotify devices (second at...
uri.startswith('spotify:') def isSpotifyPlaylistUri(uri): return isSpotifyUri(uri) and uri.startswith('spotify:playlist:') def isSpotifyTrackUri(uri): return isSpotifyUri(uri) and uri.startswith('spotify:track:') def _getSpotifyAvailableDevices(calledFromSelf=False):
63
64
187
12
52
eriklindebratt/flic-chromecast-love
caster.py
Python
_getSpotifyAvailableDevices
_getSpotifyAvailableDevices
370
402
370
370
d98ceb67753825720257b2ac0729b8ebf3238743
bigcode/the-stack
train
cfbd6636798bd31a47c6e39e
train
function
def quit(device, disconnectFromDevice=False): if not device: return logger.info('Closing Chromecast application on "{}"'.format(device.name)) try: if device.app_id: device.quit_app() else: logger.info( ' - no Chromecast application active ' ...
def quit(device, disconnectFromDevice=False):
if not device: return logger.info('Closing Chromecast application on "{}"'.format(device.name)) try: if device.app_id: device.quit_app() else: logger.info( ' - no Chromecast application active ' 'on "{}"!'.format(device.name) ...
logger.error('Failed to stop: {}'.format(e)) onError(e) return if disconnectFromDevice: logger.info( 'Playback stopped on "{}" - disconnecting..'.format(device.name) ) device.disconnect(blocking=False) def quit(device, disconnectFromDevice=False):
64
64
132
9
55
eriklindebratt/flic-chromecast-love
caster.py
Python
quit
quit
243
264
243
243
4f0ba3e6eb7f56af6c547fad440b6041de617d9c
bigcode/the-stack
train
5959b76e14a43d5e35f3120c
train
function
def addDeviceStatusListener(device, callback): device.media_controller.register_status_listener( DeviceStatusListener(device, callback) )
def addDeviceStatusListener(device, callback):
device.media_controller.register_status_listener( DeviceStatusListener(device, callback) )
SpotifyUri(data['media']['uri']): _playSpotifyUri( device=device, uri=data['media']['uri'] ) else: mc.play_media(data['media']['uri'], **mediaArgs) mc.block_until_active() return device def addDeviceStatusListener(device, callback):
64
64
27
9
54
eriklindebratt/flic-chromecast-love
caster.py
Python
addDeviceStatusListener
addDeviceStatusListener
652
655
652
652
e96ca97f22f953355557d97803f2f8452053c4e0
bigcode/the-stack
train
23fae1c4fcc6ca8fe7137364
train
function
def _setupSpotifyClient(): global _spotifyClient logger.info('Setting up Spotify client...') try: oAuthClientId = os.environ['SPOTIFY_OAUTH_CLIENT_ID'] oAuthClientSecret = os.environ['SPOTIFY_OAUTH_CLIENT_SECRET'] except KeyError: raise SpotifyOAuthCredentialsError( ...
def _setupSpotifyClient():
global _spotifyClient logger.info('Setting up Spotify client...') try: oAuthClientId = os.environ['SPOTIFY_OAUTH_CLIENT_ID'] oAuthClientSecret = os.environ['SPOTIFY_OAUTH_CLIENT_SECRET'] except KeyError: raise SpotifyOAuthCredentialsError( 'Missing Spotify OAuth app...
device.keys()): passedFilters = False break if device[key] != filters[key]: passedFilters = False break if passedFilters: filteredSpotifyDevices.append(device) try: deviceId = filteredSpotifyDevices[0]['id'] ...
83
83
278
6
76
eriklindebratt/flic-chromecast-love
caster.py
Python
_setupSpotifyClient
_setupSpotifyClient
436
472
436
436
9fcef0fb4a768628d903e54bc9de7116a1221a2d
bigcode/the-stack
train
6eecb361e21067143d1da124
train
function
def _getSpotifyDeviceId(filters): ''' :param filters: dict ''' availableSpotifyDevices = _getSpotifyAvailableDevices() logger.debug('Available Spotify devices: {}'.format( availableSpotifyDevices)) filteredSpotifyDevices = [] for device in availableSpotifyDevices: passedFi...
def _getSpotifyDeviceId(filters):
''' :param filters: dict ''' availableSpotifyDevices = _getSpotifyAvailableDevices() logger.debug('Available Spotify devices: {}'.format( availableSpotifyDevices)) filteredSpotifyDevices = [] for device in availableSpotifyDevices: passedFilters = True for key in fi...
logger.warning( 'No available Spotify devices found ' '- trying once more' ) return _getSpotifyAvailableDevices(calledFromSelf=True) else: logger.warning( 'No available Spotify devices found after second attempt' )...
64
64
156
8
55
eriklindebratt/flic-chromecast-love
caster.py
Python
_getSpotifyDeviceId
_getSpotifyDeviceId
405
433
405
405
fb9a0271433271761f331a2d0a82c63fe0691804
bigcode/the-stack
train
280f3d2b5cf9d297d5c30a77
train
function
def getDevice(deviceName, calledFromSelf=False): if not calledFromSelf: logger.debug('Getting device "{}"'.format(deviceName)) try: host = next(i for i in deviceHosts if i[-1] == deviceName) device = pychromecast.Chromecast(host[0], host[1]) except StopIteration: if not call...
def getDevice(deviceName, calledFromSelf=False):
if not calledFromSelf: logger.debug('Getting device "{}"'.format(deviceName)) try: host = next(i for i in deviceHosts if i[-1] == deviceName) device = pychromecast.Chromecast(host[0], host[1]) except StopIteration: if not calledFromSelf: logger.warning( ...
OfHosts def cancelDeviceHostScanner(): global deviceHostScanTimer if deviceHostScanTimer is not None and deviceHostScanTimer.is_alive(): logger.debug('Canceling device host scanner') deviceHostScanTimer.cancel() deviceHostScanTimer = None def getDevice(deviceName, calledFromSelf=False...
69
69
230
11
57
eriklindebratt/flic-chromecast-love
caster.py
Python
getDevice
getDevice
179
215
179
179
addb55f311df5d44d159d3b243fe3205867054df
bigcode/the-stack
train
7dea2e5d9d6a8d27f267a7ac
train
function
def isPlaying(device): if not device: return False try: return isSpotifyPlaying(device) or \ device.media_controller.status.player_is_playing except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPlaying`: {}'.format(e)) onError(e...
def isPlaying(device):
if not device: return False try: return isSpotifyPlaying(device) or \ device.media_controller.status.player_is_playing except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPlaying`: {}'.format(e)) onError(e) return False
: logger.info( 'Volume set on "{}" - disconnecting...'.format(device.name) ) device.disconnect() if disconnectFromDevice: logger.info( 'Volume set on "{}" - disconnecting...'.format(device.name) ) device.disconnect() def isPlaying(device):
64
64
72
5
59
eriklindebratt/flic-chromecast-love
caster.py
Python
isPlaying
isPlaying
298
308
298
298
6bc6a5e477918b1ff7ef70f94ba5df858cacf66e
bigcode/the-stack
train
223651b8bac6091a132842d6
train
function
def _playSpotifyUri(device=None, uri=None): logger.debug('Playing Spotify URI...') # launch the Spotify app on the device we want to cast to try: controller = _getSpotifyChromecastController() device.register_handler(controller) controller.launch_app() except pychromecast.error....
def _playSpotifyUri(device=None, uri=None):
logger.debug('Playing Spotify URI...') # launch the Spotify app on the device we want to cast to try: controller = _getSpotifyChromecastController() device.register_handler(controller) controller.launch_app() except pychromecast.error.LaunchError as e: raise SpotifyPlayb...
return _spotifyClient def _getSpotifyChromecastController(): try: spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME'] spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD'] except KeyError: raise SpotifyPlaybackError( 'Missing Spotify user credentials in env va...
156
156
523
11
145
eriklindebratt/flic-chromecast-love
caster.py
Python
_playSpotifyUri
_playSpotifyUri
494
570
494
494
dec846c6756cae18e82e125321e7fa9f37ade9f7
bigcode/the-stack
train
82a2a79e28dda71d89fff2cd
train
class
class DeviceMediaStatusListener: def __init__(self, device, callback): self.device = device self.callback = callback self.lastPlayerState = None def new_media_status(self, status): logger.debug('Device "{}" got new media status: {}'.format( self.device.name, ...
class DeviceMediaStatusListener:
def __init__(self, device, callback): self.device = device self.callback = callback self.lastPlayerState = None def new_media_status(self, status): logger.debug('Device "{}" got new media status: {}'.format( self.device.name, status )) if...
device, callback): self.device = device self.callback = callback def new_cast_status(self, status): logger.debug('Device "{}" got new device status: {}'.format( self.device.name, status )) self.callback(self.device, status) class DeviceMediaStatusLi...
64
64
110
6
58
eriklindebratt/flic-chromecast-love
caster.py
Python
DeviceMediaStatusListener
DeviceMediaStatusListener
71
89
71
71
479aa546b2a157f8079db8132296af2449c671e4
bigcode/the-stack
train
746e3172de55b7af0aa97409
train
function
def _getSpotifyChromecastController(): try: spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME'] spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD'] except KeyError: raise SpotifyPlaybackError( 'Missing Spotify user credentials in env vars ' '`SPOTIFY_U...
def _getSpotifyChromecastController():
try: spotifyUserUsername = os.environ['SPOTIFY_USER_USERNAME'] spotifyUserPassword = os.environ['SPOTIFY_USER_PASSWORD'] except KeyError: raise SpotifyPlaybackError( 'Missing Spotify user credentials in env vars ' '`SPOTIFY_USER_USERNAME` and/or `SPOTIFY_USER_PASS...
Spotify client successfully set up') except Exception: raise SpotifyOAuthCredentialsError( 'Failed to get initial Spotify access token') if logger.level == logging.DEBUG: spotipy.trace = True spotipy.trace_out = True return _spotifyClient def _getSpotifyChromecastContro...
64
64
139
8
55
eriklindebratt/flic-chromecast-love
caster.py
Python
_getSpotifyChromecastController
_getSpotifyChromecastController
475
491
475
475
60f731342cc12200bb240ee6fe6db33bda7e9f15
bigcode/the-stack
train
60a00750b3136fe8f1fc1910
train
function
def addDevicePlayerStatusListener(device, callback): device.media_controller.register_status_listener( DeviceMediaStatusListener(device, callback) )
def addDevicePlayerStatusListener(device, callback):
device.media_controller.register_status_listener( DeviceMediaStatusListener(device, callback) )
else: mc.play_media(data['media']['uri'], **mediaArgs) mc.block_until_active() return device def addDeviceStatusListener(device, callback): device.media_controller.register_status_listener( DeviceStatusListener(device, callback) ) def addDevicePlayerStatusListener(device, callbac...
64
64
29
10
54
eriklindebratt/flic-chromecast-love
caster.py
Python
addDevicePlayerStatusListener
addDevicePlayerStatusListener
658
661
658
658
f9b8df608bc67ed0422ffbce95f666a308bfb3a5
bigcode/the-stack
train
341087726929410fb24319eb
train
class
class DeviceStatusListener: def __init__(self, device, callback): self.device = device self.callback = callback def new_cast_status(self, status): logger.debug('Device "{}" got new device status: {}'.format( self.device.name, status )) self.callb...
class DeviceStatusListener:
def __init__(self, device, callback): self.device = device self.callback = callback def new_cast_status(self, status): logger.debug('Device "{}" got new device status: {}'.format( self.device.name, status )) self.callback(self.device, status)
user-modify-playback-state', 'user-read-currently-playing', )) SPOTIFY_OAUTH_REDIRECT_SERVER_PORT = 5000 class DeviceNotFoundError(Exception): pass class SpotifyOAuthCredentialsError(Exception): pass class SpotifyPlaybackError(Exception): pass class DeviceStatusListener:
64
64
70
5
58
eriklindebratt/flic-chromecast-love
caster.py
Python
DeviceStatusListener
DeviceStatusListener
57
68
57
57
5bf2d2b390b12354919fc476180811d8abc44401
bigcode/the-stack
train
75a0a4c3750c21c66a2556d3
train
function
def stop(device, disconnectFromDevice=False): if not device: return logger.info('Stopping playback on "{}"'.format(device.name)) try: _pauseSpotify() except (Exception, SpotifyPlaybackError): logger.exception('Failed to pause Spotify playback') try: device.media_co...
def stop(device, disconnectFromDevice=False):
if not device: return logger.info('Stopping playback on "{}"'.format(device.name)) try: _pauseSpotify() except (Exception, SpotifyPlaybackError): logger.exception('Failed to pause Spotify playback') try: device.media_controller.stop() except pychromecast.error....
Name) ) # start worker thread and wait for cast device to be ready logger.debug('Device "{}" found, connecting...'.format(deviceName)) device.wait() logger.debug('Connected to "{}"'.format(deviceName)) return device def stop(device, disconnectFromDevice=False):
64
64
134
9
54
eriklindebratt/flic-chromecast-love
caster.py
Python
stop
stop
218
240
218
218
8da9d8fb64416f05a3e9637a64fb75924748c8a4
bigcode/the-stack
train
c68f03b4f1d2c65bf822051c
train
function
def isSpotifyPlaylistUri(uri): return isSpotifyUri(uri) and uri.startswith('spotify:playlist:')
def isSpotifyPlaylistUri(uri):
return isSpotifyUri(uri) and uri.startswith('spotify:playlist:')
_controller.status.player_is_paused except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPaused`: {}'.format(e)) onError(e) return False def isSpotifyUri(uri): return uri.startswith('spotify:') def isSpotifyPlaylistUri(uri):
63
64
22
7
57
eriklindebratt/flic-chromecast-love
caster.py
Python
isSpotifyPlaylistUri
isSpotifyPlaylistUri
362
363
362
362
1c1b550b96616bef024d5cea218c017562e7e97b
bigcode/the-stack
train
b9959379996a0d472ad78757
train
function
def setVolume(device, volume, callback=None, disconnectFromDevice=False): if not device: return logger.info( 'Setting volume to {}% on "{}"'.format( volume * 100, device.name ) ) try: device.set_volume(volume) except pychromecast.error.Contro...
def setVolume(device, volume, callback=None, disconnectFromDevice=False):
if not device: return logger.info( 'Setting volume to {}% on "{}"'.format( volume * 100, device.name ) ) try: device.set_volume(volume) except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to set volume: {}'.fo...
e: logger.error('Failed to quit: {}'.format(e)) onError(e) return if disconnectFromDevice: logger.info('Disconnecting from "{}"'.format(device.name)) device.disconnect(blocking=False) def setVolume(device, volume, callback=None, disconnectFromDevice=False):
64
64
161
15
49
eriklindebratt/flic-chromecast-love
caster.py
Python
setVolume
setVolume
267
295
267
267
0176fc0b02cbb2993d9361fed2c91aac5a62de4e
bigcode/the-stack
train
71cdf3feed34b47af0ff3652
train
class
class SpotifyOAuthCredentialsError(Exception): pass
class SpotifyOAuthCredentialsError(Exception):
pass
_SCOPE = ','.join(( 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', )) SPOTIFY_OAUTH_REDIRECT_SERVER_PORT = 5000 class DeviceNotFoundError(Exception): pass class SpotifyOAuthCredentialsError(Exception):
64
64
10
7
56
eriklindebratt/flic-chromecast-love
caster.py
Python
SpotifyOAuthCredentialsError
SpotifyOAuthCredentialsError
49
50
49
49
e1e0680acf1f4e882ce1a02572bb5d45fd8670bf
bigcode/the-stack
train
e3959f78944f9ae66c675d0f
train
function
def isSpotifyPlaying(device): if not device: return False if not _spotifyClient: return False try: playbackStatus = _spotifyClient.current_playback() except spotipy.client.SpotifyException: logger.exception( 'Error: Failed to get current Spotify playback sta...
def isSpotifyPlaying(device):
if not device: return False if not _spotifyClient: return False try: playbackStatus = _spotifyClient.current_playback() except spotipy.client.SpotifyException: logger.exception( 'Error: Failed to get current Spotify playback status' ' - got Spoti...
try: return isSpotifyPlaying(device) or \ device.media_controller.status.player_is_playing except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPlaying`: {}'.format(e)) onError(e) return False def isSpotifyPlaying(device):
64
64
206
6
57
eriklindebratt/flic-chromecast-love
caster.py
Python
isSpotifyPlaying
isSpotifyPlaying
311
343
311
311
efd9f6859f0850daf764af596507d3e680a51e86
bigcode/the-stack
train
f4cd7e9d4d81257ba99fcf11
train
class
class DeviceNotFoundError(Exception): pass
class DeviceNotFoundError(Exception):
pass
'.spotify-tokens') SPOTIFY_OAUTH_SCOPE = ','.join(( 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', )) SPOTIFY_OAUTH_REDIRECT_SERVER_PORT = 5000 class DeviceNotFoundError(Exception):
64
64
10
7
56
eriklindebratt/flic-chromecast-love
caster.py
Python
DeviceNotFoundError
DeviceNotFoundError
45
46
45
45
8910df61f17e2cd24bda6309c07acb42d0b17ec7
bigcode/the-stack
train
0919108a49353b67096871af
train
function
def isPaused(device): if not device: return False try: return device.media_controller.status.player_is_paused except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPaused`: {}'.format(e)) onError(e) return False
def isPaused(device):
if not device: return False try: return device.media_controller.status.player_is_paused except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPaused`: {}'.format(e)) onError(e) return False
name from the one specified ({}) - considering ' 'playback status as "not playing"'.format( playbackStatus.get('device', {}).get('name'), device.name ) ) return False return playbackStatus.get('is_playing', False) def isPaused(device):
64
64
64
5
59
eriklindebratt/flic-chromecast-love
caster.py
Python
isPaused
isPaused
346
355
346
346
864aad74e3b785c0ca9d44938a7349922e5031f6
bigcode/the-stack
train
ade1f84c6202093c5b005a84
train
function
def play(data, device=None): ''' :param data: dict :param device ''' if data is None: data = {} if not data['media'].get('args'): data['media']['args'] = {} ######################## # set up media data structure mediaArgs = dict(data['media']['args']) if not i...
def play(data, device=None):
''' :param data: dict :param device ''' if data is None: data = {} if not data['media'].get('args'): data['media']['args'] = {} ######################## # set up media data structure mediaArgs = dict(data['media']['args']) if not isSpotifyUri(data['media']['ur...
filters={'is_active': True}) if not spotifyDeviceId: logger.debug( 'Can\'t pause Spotify playback - ' 'Spotify returned no active devices' ) return try: _spotifyClient.pause_playback(device_id=spotifyDeviceId) except spotipy.client.SpotifyException:...
98
98
329
7
91
eriklindebratt/flic-chromecast-love
caster.py
Python
play
play
596
649
596
596
1bcf578f5015ef7a460259461196d079946c2758
bigcode/the-stack
train
384772a156e193d8f3ef8ef1
train
function
def isSpotifyTrackUri(uri): return isSpotifyUri(uri) and uri.startswith('spotify:track:')
def isSpotifyTrackUri(uri):
return isSpotifyUri(uri) and uri.startswith('spotify:track:')
Failed to get `isPaused`: {}'.format(e)) onError(e) return False def isSpotifyUri(uri): return uri.startswith('spotify:') def isSpotifyPlaylistUri(uri): return isSpotifyUri(uri) and uri.startswith('spotify:playlist:') def isSpotifyTrackUri(uri):
63
64
22
7
57
eriklindebratt/flic-chromecast-love
caster.py
Python
isSpotifyTrackUri
isSpotifyTrackUri
366
367
366
366
3b8b926825ac86f44231fe0a35be2cb28b4017f6
bigcode/the-stack
train
15f0fd5a40541642a7fe533a
train
function
def _pauseSpotify(): if not _spotifyClient: raise Exception('Spotify client is not set up') spotifyDeviceId, availableSpotifyDevices = _getSpotifyDeviceId( filters={'is_active': True}) if not spotifyDeviceId: logger.debug( 'Can\'t pause Spotify playback - ' ...
def _pauseSpotify():
if not _spotifyClient: raise Exception('Spotify client is not set up') spotifyDeviceId, availableSpotifyDevices = _getSpotifyDeviceId( filters={'is_active': True}) if not spotifyDeviceId: logger.debug( 'Can\'t pause Spotify playback - ' 'Spotify returned no ...
device_id=spotifyDeviceId, context_uri=uri ) except spotipy.client.SpotifyException: logger.exception( 'Error: Failed to start Spotify playback' ' - got Spotify error' ) raise SpotifyPlaybackError('Could not start playback') def _pauseSpo...
64
64
130
5
59
eriklindebratt/flic-chromecast-love
caster.py
Python
_pauseSpotify
_pauseSpotify
573
593
573
573
404c41e0d6ff88802629e0221b4f546bbecfb62e
bigcode/the-stack
train
a651adab544be90e1a5bfaa8
train
function
def setup(logLevel=None, errorHandler=None): global onError if logLevel: logger.setLevel(logLevel) logger.info('Setting up...') if errorHandler: onError = errorHandler _setupSpotifyClient() if not scanForDeviceHosts(): logger.error('Setup completed with failing scann...
def setup(logLevel=None, errorHandler=None):
global onError if logLevel: logger.setLevel(logLevel) logger.info('Setting up...') if errorHandler: onError = errorHandler _setupSpotifyClient() if not scanForDeviceHosts(): logger.error('Setup completed with failing scanner') else: logger.info('Setup com...
status: {}'.format( self.device.name, status )) if self.lastPlayerState and \ self.lastPlayerState == status.player_state: return self.lastPlayerState = status.player_state self.callback(self.device, status) def setup(logLevel=None,...
64
64
81
10
54
eriklindebratt/flic-chromecast-love
caster.py
Python
setup
setup
92
108
92
92
f2a4b78bb9eb55e154fbf75c280d594e4baea8d8
bigcode/the-stack
train
f859425e4be2ff39e11779db
train
function
def isSpotifyUri(uri): return uri.startswith('spotify:')
def isSpotifyUri(uri):
return uri.startswith('spotify:')
if not device: return False try: return device.media_controller.status.player_is_paused except pychromecast.error.ControllerNotRegistered as e: logger.error('Failed to get `isPaused`: {}'.format(e)) onError(e) return False def isSpotifyUri(uri):
64
64
13
6
57
eriklindebratt/flic-chromecast-love
caster.py
Python
isSpotifyUri
isSpotifyUri
358
359
358
358
8a76f4bc499a772b10794ed447170a9988688a3d
bigcode/the-stack
train
3b054c711b224fb9369ae0c3
train
function
def scanForDeviceHosts(): ''' Returns: Bool Whether scanner returned any device hosts or not ''' global deviceHosts, deviceHostScanTimer # cancel currently running scanner, if any cancelDeviceHostScanner() logger.debug('Scanning for device hosts...') startTime = datetime.utcnow() ...
def scanForDeviceHosts():
''' Returns: Bool Whether scanner returned any device hosts or not ''' global deviceHosts, deviceHostScanTimer # cancel currently running scanner, if any cancelDeviceHostScanner() logger.debug('Scanning for device hosts...') startTime = datetime.utcnow() deviceHosts = pychromecas...
self.lastPlayerState = status.player_state self.callback(self.device, status) def setup(logLevel=None, errorHandler=None): global onError if logLevel: logger.setLevel(logLevel) logger.info('Setting up...') if errorHandler: onError = errorHandler _setupSpotifyClient() ...
104
104
348
6
98
eriklindebratt/flic-chromecast-love
caster.py
Python
scanForDeviceHosts
scanForDeviceHosts
111
167
111
111
21d68eebffc328d4aae6da82ed8e4b97082838b1
bigcode/the-stack
train
6ef4f182034ff6009709b1b4
train
function
@click.command(short_help="Merge a stack of raster datasets.") @files_inout_arg @options.output_opt @format_opt @options.bounds_opt @options.resolution_opt @options.nodata_opt @options.force_overwrite_opt @click.option('--precision', type=int, default=7, help="Number of decimal places of precision in alig...
@click.command(short_help="Merge a stack of raster datasets.") @files_inout_arg @options.output_opt @format_opt @options.bounds_opt @options.resolution_opt @options.nodata_opt @options.force_overwrite_opt @click.option('--precision', type=int, default=7, help="Number of decimal places of precision in alig...
"""Copy valid pixels from input files to an output file. All files must have the same number of bands, data type, and coordinate reference system. Input files are merged in their listed order using the reverse painter's algorithm. If the output file exists, its values will be overwritten by in...
from cligj import files_inout_arg, format_opt import rasterio from rasterio.rio import options from rasterio.rio.helpers import resolve_inout @click.command(short_help="Merge a stack of raster datasets.") @files_inout_arg @options.output_opt @format_opt @options.bounds_opt @options.resolution_opt @options.nodata_opt @...
152
152
508
116
35
dimitri-justeau/rasterio
rasterio/rio/merge.py
Python
merge
merge
12
72
12
26
7a6d17d292d0919b4e964ada810fa8c9bd2fa48a
bigcode/the-stack
train
db37a353e0a297e0cba7803f
train
class
class RecordUtilTest(unittest.TestCase): def setUp(self): self.meta = create_local_meta(None, '') def test_create_meta(self): self.assertEqual(self.meta['name'], '') self.assertEqual(self.meta['coord'], ['', (0,)]) def test_create_sub_meta(self): name = 'Testing' m...
class RecordUtilTest(unittest.TestCase):
def setUp(self): self.meta = create_local_meta(None, '') def test_create_meta(self): self.assertEqual(self.meta['name'], '') self.assertEqual(self.meta['coord'], ['', (0,)]) def test_create_sub_meta(self): name = 'Testing' meta = create_local_meta(self.meta, name) ...
import unittest from openmdao.util.record_util import create_local_meta, update_local_meta, format_iteration_coordinate class RecordUtilTest(unittest.TestCase):
31
107
358
8
22
jcchin/project_clippy
openmdao/util/test/test_record_util.py
Python
RecordUtilTest
RecordUtilTest
5
56
5
5
afc772ee6a092af249c185460bcf06f68acfd908
bigcode/the-stack
train
7b0a9d040eaefe66c733374b
train
class
class ELeclercSpider(scrapy.spiders.SitemapSpider): name = "e_leclerc" item_attributes = {"brand": "E.Leclerc", "brand_wikidata": "Q1273376"} allowed_domains = ["e-leclerc.com"] sitemap_urls = [ "https://www.e-leclerc.com/sitemap_www_index.xml", ] sitemap_rules = [(r"https:\/\/www\.e-lec...
class ELeclercSpider(scrapy.spiders.SitemapSpider):
name = "e_leclerc" item_attributes = {"brand": "E.Leclerc", "brand_wikidata": "Q1273376"} allowed_domains = ["e-leclerc.com"] sitemap_urls = [ "https://www.e-leclerc.com/sitemap_www_index.xml", ] sitemap_rules = [(r"https:\/\/www\.e-leclerc\.com\/[^\/]+?$", "parse_location")] sitemap...
# -*- coding: utf-8 -*- import re import scrapy from locations.items import GeojsonPointItem class ELeclercSpider(scrapy.spiders.SitemapSpider):
36
129
433
13
22
cmecklenborg/alltheplaces
locations/spiders/e_leclerc.py
Python
ELeclercSpider
ELeclercSpider
9
56
9
9
3817cfd8a749bda0928aebcb4f968fb2e790cd77
bigcode/the-stack
train
1f7b03908418edc19b3a7d48
train
class
class Task(object): cmd_re = re.compile("\(Command: (.+)\)") def __init__(self, master, items): self.master = master self.__items = items def __str__(self): return "{}:{}".format(a_sync.block(self.slave), self["id"]) def __getitem__(self, name): return self.__items[na...
class Task(object):
cmd_re = re.compile("\(Command: (.+)\)") def __init__(self, master, items): self.master = master self.__items = items def __str__(self): return "{}:{}".format(a_sync.block(self.slave), self["id"]) def __getitem__(self, name): return self.__items[name] async def ex...
use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIO...
145
145
484
4
140
jackchi/paasta
paasta_tools/mesos/task.py
Python
Task
Task
28
97
28
29
ca2738200f0b27ad2302845a8760e666f2984ac7
bigcode/the-stack
train
5960a05d689768f13dd625bb
train
function
def create(kernel): result = Static() result.template = "object/static/structure/tatooine/shared_antenna_tatt_style_2.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def create(kernel):
result = Static() result.template = "object/static/structure/tatooine/shared_antenna_tatt_style_2.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel):
46
64
71
4
42
obi-two/GameServer
data/scripts/templates/object/static/structure/tatooine/shared_antenna_tatt_style_2.py
Python
create
create
7
17
7
7
90d92abf7fe16cfaa247267075e96ac81d51d2b1
bigcode/the-stack
train
2c9a1a9836094bb0de55f91d
train
function
def push(type_data): subprocess.run(["sudo", "git", "add", "images/", "data/"]) subprocess.run(["sudo", "git", "commit", "-m", "[auto] data update: {}".format(type_data)]) subprocess.run(["git", "push"]) print("pushed")
def push(type_data):
subprocess.run(["sudo", "git", "add", "images/", "data/"]) subprocess.run(["sudo", "git", "commit", "-m", "[auto] data update: {}".format(type_data)]) subprocess.run(["git", "push"]) print("pushed")
subprocess.run(["sudo", "git", "fetch", "--all"]) subprocess.run(["sudo", "git", "reset", "--hard", "origin/master"]) subprocess.run(["sudo", "jupyter", "nbconvert", "--to", "script", "*.ipynb"]) def push(type_data):
63
64
65
5
58
Pomidorka1234/covid-19
script_update_data.py
Python
push
push
39
43
39
39
8a89dd1e2605a78bd8e818573977e25b1e73b5b8
bigcode/the-stack
train
e64181bb0a0d93f85cdc29a0
train
function
def update_repo(): subprocess.run(["sudo", "git", "fetch", "--all"]) subprocess.run(["sudo", "git", "reset", "--hard", "origin/master"]) subprocess.run(["sudo", "jupyter", "nbconvert", "--to", "script", "*.ipynb"])
def update_repo():
subprocess.run(["sudo", "git", "fetch", "--all"]) subprocess.run(["sudo", "git", "reset", "--hard", "origin/master"]) subprocess.run(["sudo", "jupyter", "nbconvert", "--to", "script", "*.ipynb"])
as dt import time import subprocess import requests import re ### FUNCTION DEFINITIONS ### url_metadata = "https://www.data.gouv.fr/fr/organizations/sante-publique-france/datasets-resources.csv" metadata = requests.get(url_metadata) content = str(metadata.content) def update_repo():
64
64
63
4
60
Pomidorka1234/covid-19
script_update_data.py
Python
update_repo
update_repo
34
37
34
34
91ac4f16ba78b3ec07c1efe60a6b801bfb730f98
bigcode/the-stack
train
966842c4a9b6ad7e60b3ee0d
train
function
def get_datetime_spf(): metadata = requests.get(url_metadata) content = str(metadata.content) re_result = re.search("donnees-hospitalieres-nouveaux-covid19-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}h[0-9]{2}.csv", content) re_date = re.match(".*covid19-([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})h([0-9]{2}).csv...
def get_datetime_spf():
metadata = requests.get(url_metadata) content = str(metadata.content) re_result = re.search("donnees-hospitalieres-nouveaux-covid19-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}h[0-9]{2}.csv", content) re_date = re.match(".*covid19-([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})h([0-9]{2}).csv", re_result[0]) dat...
(["sudo", "git", "add", "images/", "data/"]) subprocess.run(["sudo", "git", "commit", "-m", "[auto] data update: {}".format(type_data)]) subprocess.run(["git", "push"]) print("pushed") def get_datetime_spf():
63
64
187
6
57
Pomidorka1234/covid-19
script_update_data.py
Python
get_datetime_spf
get_datetime_spf
45
51
45
45
1082614b31e3840ce25dcd572839443c7e23cded
bigcode/the-stack
train
f5d6d629940df97673806cc3
train
function
def try_update_france(): datetime_spf = get_datetime_spf() print("try update, now: "+ str(dt.datetime.now())) print("datetime_spf: " + str(datetime_spf)) t1 = dt.datetime.now() t2 = datetime_spf print("diff t1 t2: {}".format(max(t1, t2) - min(t1, t2)) ) print("(max(t1, t2) - min(t1, t2)...
def try_update_france():
datetime_spf = get_datetime_spf() print("try update, now: "+ str(dt.datetime.now())) print("datetime_spf: " + str(datetime_spf)) t1 = dt.datetime.now() t2 = datetime_spf print("diff t1 t2: {}".format(max(t1, t2) - min(t1, t2)) ) print("(max(t1, t2) - min(t1, t2)).total_seconds()/3600 = ...
f(): metadata = requests.get(url_metadata) content = str(metadata.content) re_result = re.search("donnees-hospitalieres-nouveaux-covid19-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}h[0-9]{2}.csv", content) re_date = re.match(".*covid19-([0-9]{4})-([0-9]{2})-([0-9]{2})-([0-9]{2})h([0-9]{2}).csv", re_result[0]) ...
189
189
633
6
182
Pomidorka1234/covid-19
script_update_data.py
Python
try_update_france
try_update_france
53
110
53
53
17cd6c46d51463aa68a0e532f764ab8bd5c57fee
bigcode/the-stack
train
806a0cf16787f5ffd34327c2
train
class
class MqttConnector(Connector, Thread): def __init__(self, gateway, config, connector_type): super().__init__() self.__log = log self.config = config self.__connector_type = connector_type self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0}...
class MqttConnector(Connector, Thread):
def __init__(self, gateway, config, connector_type): super().__init__() self.__log = log self.config = config self.__connector_type = connector_type self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0} self.__gateway = gateway ...
0. ThingsBoard # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
256
256
3,257
9
246
pticaTor/thingsboard-gateway
thingsboard_gateway/connectors/mqtt/mqtt_connector.py
Python
MqttConnector
MqttConnector
29
369
29
29
39690ebe94d44ed93a21036eca6d495778640092
bigcode/the-stack
train
ea2da24d931bf195fd1802eb
train
function
def to_pytraj_Topology(item, molecular_system, atom_indices='all', structure_indices='all'): from molsysmt.form.pytraj_Trajectory import to_pytraj_Topology as pytraj_Trajectory_to_pytraj_Topology tmp_item = pytraj_Trajectory_to_pytraj_Topology(item, atom_indices=atom_indices, check=False) return tmp_item...
def to_pytraj_Topology(item, molecular_system, atom_indices='all', structure_indices='all'):
from molsysmt.form.pytraj_Trajectory import to_pytraj_Topology as pytraj_Trajectory_to_pytraj_Topology tmp_item = pytraj_Trajectory_to_pytraj_Topology(item, atom_indices=atom_indices, check=False) return tmp_item
False, 'forcefield' : False, 'temperature' : False, 'pressure' : False, 'integrator' : False, 'damping' : False, } def to_pytraj_Topology(item, molecular_system, atom_indices='all', structure_indices='all'):
64
64
85
23
41
uibcdf/MolModSAKs
molsysmt/api_forms/api_pytraj_Trajectory.py
Python
to_pytraj_Topology
to_pytraj_Topology
66
72
66
67
d6ad32e9bbbcbbe2b9504e5b49b4510b0ae63033
bigcode/the-stack
train
12560143b63f8002c8159a1d
train
function
def to_molsysmt_Structures(item, molecular_system, atom_indices='all', structure_indices='all'): from molsysmt.form.pytraj_Trajectory import to_molsysmt_Structures as pytraj_Trajectory_to_molsysmt_Structures tmp_item = pytraj_Trajectory_to_molsysmt_Structures(item, atom_indices=atom_indices, ...
def to_molsysmt_Structures(item, molecular_system, atom_indices='all', structure_indices='all'):
from molsysmt.form.pytraj_Trajectory import to_molsysmt_Structures as pytraj_Trajectory_to_molsysmt_Structures tmp_item = pytraj_Trajectory_to_molsysmt_Structures(item, atom_indices=atom_indices, structure_indices=structure_indices, check=False) retu...
ysmt_Topology tmp_item = pytraj_Trajectory_to_molsysmt_Topology(item, atom_indices=atom_indices, check=False) return tmp_item def to_molsysmt_Structures(item, molecular_system, atom_indices='all', structure_indices='all'):
64
64
100
25
38
uibcdf/MolModSAKs
molsysmt/api_forms/api_pytraj_Trajectory.py
Python
to_molsysmt_Structures
to_molsysmt_Structures
91
98
91
92
1fd514696bf2c7d64b3013979046b87a1121919a
bigcode/the-stack
train
ccb4ef07c4d0077479d95166
train
function
def to_molsysmt_Topology(item, molecular_system, atom_indices='all', structure_indices='all'): from molsysmt.form.pytraj_Trajectory import to_molsysmt_Topology as pytraj_Trajectory_to_molsysmt_Topology tmp_item = pytraj_Trajectory_to_molsysmt_Topology(item, atom_indices=atom_indices, check=False) return ...
def to_molsysmt_Topology(item, molecular_system, atom_indices='all', structure_indices='all'):
from molsysmt.form.pytraj_Trajectory import to_molsysmt_Topology as pytraj_Trajectory_to_molsysmt_Topology tmp_item = pytraj_Trajectory_to_molsysmt_Topology(item, atom_indices=atom_indices, check=False) return tmp_item
tmp_item = pytraj_Trajectory_to_molsysmt_MolSys(item, atom_indices=atom_indices, structure_indices=structure_indices, check=False) return tmp_item def to_molsysmt_Topology(item, molecular_system, atom_indices='all', structure_indices='all'):
64
64
93
25
38
uibcdf/MolModSAKs
molsysmt/api_forms/api_pytraj_Trajectory.py
Python
to_molsysmt_Topology
to_molsysmt_Topology
83
89
83
84
10d2f27421ac5763f184d64ab2cc8ddd7a41a01b
bigcode/the-stack
train
4f0319470adca0e4e9fad688
train
function
def to_molsysmt_MolSys(item, molecular_system, atom_indices='all', structure_indices='all'): from molsysmt.form.pytraj_Trajectory import to_molsysmt_MolSys as pytraj_Trajectory_to_molsysmt_MolSys tmp_item = pytraj_Trajectory_to_molsysmt_MolSys(item, atom_indices=atom_indices, ...
def to_molsysmt_MolSys(item, molecular_system, atom_indices='all', structure_indices='all'):
from molsysmt.form.pytraj_Trajectory import to_molsysmt_MolSys as pytraj_Trajectory_to_molsysmt_MolSys tmp_item = pytraj_Trajectory_to_molsysmt_MolSys(item, atom_indices=atom_indices, structure_indices=structure_indices, check=False) return tmp_item
jectory_to_pytraj_Topology tmp_item = pytraj_Trajectory_to_pytraj_Topology(item, atom_indices=atom_indices, check=False) return tmp_item def to_molsysmt_MolSys(item, molecular_system, atom_indices='all', structure_indices='all'):
64
64
100
25
38
uibcdf/MolModSAKs
molsysmt/api_forms/api_pytraj_Trajectory.py
Python
to_molsysmt_MolSys
to_molsysmt_MolSys
74
81
74
75
0219866ed86af1cd95a86f49874adc3359f56811
bigcode/the-stack
train
c58a6cd29c55f8827b37d76a
train
class
class BaseTestCase(testtools.TestCase): def setUp(self, conf=cfg.CONF): super(BaseTestCase, self).setUp() moxfixture = self.useFixture(moxstubout.MoxStubout()) self.mox = moxfixture.mox self.stubs = moxfixture.stubs self.conf = conf self.addCleanup(self.conf.reset) ...
class BaseTestCase(testtools.TestCase):
def setUp(self, conf=cfg.CONF): super(BaseTestCase, self).setUp() moxfixture = self.useFixture(moxstubout.MoxStubout()) self.mox = moxfixture.mox self.stubs = moxfixture.stubs self.conf = conf self.addCleanup(self.conf.reset) self.useFixture(fixtures.FakeLogge...
0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # unde...
119
119
398
9
109
etaivan/stx-config
sysinv/sysinv/sysinv/sysinv/tests/utils.py
Python
BaseTestCase
BaseTestCase
30
80
30
31
758ecb42e11c5fac885a739584b787b13e6257e2
bigcode/the-stack
train
e400c31f610ce007ea5a86a1
train
class
class SBG2ROS(object): def sbg_cb(self, sbg_imu, sbg_quat, sbg_mag): imu_msg = Imu() imu_msg.header.frame_id = self.imu_frame imu_msg.header.stamp = sbg_imu.header.stamp # NED to ENU imu_msg.orientation.x = sbg_quat.quaternion.y imu_msg.orientation.y = sbg_quat.quat...
class SBG2ROS(object):
def sbg_cb(self, sbg_imu, sbg_quat, sbg_mag): imu_msg = Imu() imu_msg.header.frame_id = self.imu_frame imu_msg.header.stamp = sbg_imu.header.stamp # NED to ENU imu_msg.orientation.x = sbg_quat.quaternion.y imu_msg.orientation.y = sbg_quat.quaternion.x imu_msg...
#!/usr/bin/python import rospy import numpy as np import tf from geometry_msgs.msg import TwistWithCovarianceStamped import message_filters from sbg_driver.msg import SbgImuData, SbgEkfQuat, SbgEkfEuler, SbgMag, SbgUtcTime from sensor_msgs.msg import Imu class SBG2ROS(object):
79
252
840
7
71
Jollerprutt/smarc_navigation
sam_dead_reckoning/scripts/sbg_to_ros.py
Python
SBG2ROS
SBG2ROS
11
79
11
12
74a516a3072696f186362009180ad7f98b7e9f27
bigcode/the-stack
train
4d31efcdef81b51c0db02411
train
function
async def getPayloadSearch(payload): try: async with aiohttp.ClientSession() as session: async with session.get(url='https://nhentai.net/api/galleries/search', params=payload) as resp: response = await resp.json() # Await response return response; except: ...
async def getPayloadSearch(payload):
try: async with aiohttp.ClientSession() as session: async with session.get(url='https://nhentai.net/api/galleries/search', params=payload) as resp: response = await resp.json() # Await response return response; except: print("Error: Web request failed....
795361837066616852/hentei.jpg") if _deleteTimer == 0: return await _channel.send(embed = embed); else: return await _channel.send(embed = embed,delete_after = _deleteTimer); # Returns the response with payload async def getPayloadSearch(payload):
64
64
75
7
56
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
getPayloadSearch
getPayloadSearch
175
182
175
175
5e13f8fa4c90ade585a8e217a23945074fa8aca7
bigcode/the-stack
train
a8dbb2de8136d13eea019ce6
train
function
async def buildEmbedMessage(_title, _headers, _contents, _color, _footer, _channel, _inline, _deleteTimer): embed = discord.Embed(colour = _color) embed.set_author(name = _title) for h, c, i in zip(_headers, _contents, _inline): embed.add_field(name = h, value = c, inline = i) if _footer == "D...
async def buildEmbedMessage(_title, _headers, _contents, _color, _footer, _channel, _inline, _deleteTimer):
embed = discord.Embed(colour = _color) embed.set_author(name = _title) for h, c, i in zip(_headers, _contents, _inline): embed.add_field(name = h, value = c, inline = i) if _footer == "DEFAULT": _footer = '🍜Data provided by nHentai. 🔥Created by EpicGamer and AlphaAlpaka.🔥' embed...
810/795361837066616852/hentei.jpg") # Send message return await _channel.send(embed = embed); # Create embeded message async def buildEmbedMessage(_title, _headers, _contents, _color, _footer, _channel, _inline, _deleteTimer):
64
64
199
30
33
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
buildEmbedMessage
buildEmbedMessage
158
172
158
158
0068ff3d27c0f37fab57cc47ce3df7e27c7f2250
bigcode/the-stack
train
2af829579c009ec24d28fc75
train
function
async def getRequestedAmount(messagecontent): if str(messagecontent[-2:]).isdigit(): requestedAmount = int(messagecontent[-2:]) messagecontent = messagecontent[:-3] else: if str(messagecontent[-1:]).isdigit(): requestedAmount = int(messagecontent[-1:]) messagecont...
async def getRequestedAmount(messagecontent):
if str(messagecontent[-2:]).isdigit(): requestedAmount = int(messagecontent[-2:]) messagecontent = messagecontent[:-3] else: if str(messagecontent[-1:]).isdigit(): requestedAmount = int(messagecontent[-1:]) messagecontent = messagecontent[:-2] else: ...
='https://nhentai.net/api/galleries/search', params=payload) as resp: response = await resp.json() # Await response return response; except: print("Error: Web request failed. (Payload)") # Returns the requested search amount async def getRequestedAmount(messagecontent):
64
64
89
8
55
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
getRequestedAmount
getRequestedAmount
185
196
185
185
1b60c0ebb4ffd596a3dd80d74fa31740e98de524
bigcode/the-stack
train
51b81aa925f0693757d01c1a
train
function
async def buildDailyHentai(_channel): requestedID = random.randint(1,300000) response = await getHentaiByID(requestedID) while response == False: requestedID = random.randint(1,300000) response = await getHentaiByID(requestedID) response = await getHentaiByID(requestedID) await...
async def buildDailyHentai(_channel):
requestedID = random.randint(1,300000) response = await getHentaiByID(requestedID) while response == False: requestedID = random.randint(1,300000) response = await getHentaiByID(requestedID) response = await getHentaiByID(requestedID) await infoEmbedMessage(response, _channel)
): # sleep until the specified datetime now = datetime.now() await asyncio.sleep((dt - now).total_seconds()) # Run at async def run_at(dt, coro): await wait_until(dt) return await coro # Build daily hentai async def buildDailyHentai(_channel):
64
64
88
9
54
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
buildDailyHentai
buildDailyHentai
60
69
60
60
e0fc61aeb595452914e6d07cc7057fcdf7592a50
bigcode/the-stack
train
a8c7af3ba64352a820d607c8
train
function
async def catchLoliTags(response,_channel): tagString = await getGenresString(response) if "loli" in tagString or "lolicon" in tagString or "shota" in tagString or "shotacon" in tagString or "guro" in tagString: await buildEmbedMessage("Oewh.",["Contains🥀illegal🥶tags😲."],["😍😊😳"],discord.Colour.red...
async def catchLoliTags(response,_channel):
tagString = await getGenresString(response) if "loli" in tagString or "lolicon" in tagString or "shota" in tagString or "shotacon" in tagString or "guro" in tagString: await buildEmbedMessage("Oewh.",["Contains🥀illegal🥶tags😲."],["😍😊😳"],discord.Colour.red(),"This message will delete itself later.",...
String = "ERROR: could not get tags" tagsString = tagsString[:-2] if len(tagsString) > 1000: tagsString = tagsString[:1000]+"..." return tagsString; # catch for loli in tags async def catchLoliTags(response,_channel):
64
64
117
10
53
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
catchLoliTags
catchLoliTags
92
98
92
92
0ea3217eec04bedd9c0c268969f297a3e633ea71
bigcode/the-stack
train
a235098ee7acedabce73625d
train
function
async def run_at(dt, coro): await wait_until(dt) return await coro
async def run_at(dt, coro):
await wait_until(dt) return await coro
except: print("Error: Web request failed. (ID)") # Wait until async def wait_until(dt): # sleep until the specified datetime now = datetime.now() await asyncio.sleep((dt - now).total_seconds()) # Run at async def run_at(dt, coro):
64
64
19
8
55
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
run_at
run_at
55
57
55
55
fca4d59d5492844455b2819446192fc2f99acc39
bigcode/the-stack
train
19dea2e309bc011d7168d6e0
train
function
async def wait_until(dt): # sleep until the specified datetime now = datetime.now() await asyncio.sleep((dt - now).total_seconds())
async def wait_until(dt): # sleep until the specified datetime
now = datetime.now() await asyncio.sleep((dt - now).total_seconds())
# Await respone if "error" in response: # Does not exist: return False; else: return response; except: print("Error: Web request failed. (ID)") # Wait until async def wait_until(dt): # sleep until the specifi...
64
64
32
14
49
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
wait_until
wait_until
49
52
49
50
49482e9ac1eb7a3358e9d8aad8ff276f6e6cb473
bigcode/the-stack
train
c8d977b4428f73b6967abe4e
train
function
async def getHentaiByID(id): if not str(id).isdigit(): return False; try: async with aiohttp.ClientSession() as session: async with session.get('http://nhentai.net/api/gallery/'+str(id)) as resp: response = await resp.json() # Await respone if "error...
async def getHentaiByID(id):
if not str(id).isdigit(): return False; try: async with aiohttp.ClientSession() as session: async with session.get('http://nhentai.net/api/gallery/'+str(id)) as resp: response = await resp.json() # Await respone if "error" in response: ...
=REDDIT_CLIENT_ID, client_secret=REDDIT_KEY, user_agent="Henteidev") submissionList = [] onlineSince = datetime.now() allowedChannels = [] # System functions ----------------------------------------------------------------------------------------------------------------- # G...
64
64
107
9
54
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
getHentaiByID
getHentaiByID
30
46
30
30
da99b87a4eff610177892c87b89ab5a9e8c91f09
bigcode/the-stack
train
3ac26f29071514a99f81ca4d
train
function
@client.event async def on_ready(): print(f'Bot is connected.') await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=" h!help ")) guild = client.get_guild(796469914151026718) allowedChannels.append(discord.utils.get(guild.text_channels, name="spam")) #allow...
@client.event async def on_ready():
print(f'Bot is connected.') await client.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=" h!help ")) guild = client.get_guild(796469914151026718) allowedChannels.append(discord.utils.get(guild.text_channels, name="spam")) #allowedChannels.append(discord.utils.get(...
failed. (Payload)") # Returns the requested search amount async def getRequestedAmount(messagecontent): if str(messagecontent[-2:]).isdigit(): requestedAmount = int(messagecontent[-2:]) messagecontent = messagecontent[:-3] else: if str(messagecontent[-1:]).isdigit(): reques...
120
120
403
9
110
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
on_ready
on_ready
201
236
201
202
9ddc1ad257071377f9705fc36d5289cfca633d70
bigcode/the-stack
train
3ad303596fa1f37b0c4b4ac2
train
function
async def infoEmbedMessage(_response, _channel): # ID requestedID = str(_response["id"]) # Japanese title nameJapanese = _response["title"]["japanese"] if nameJapanese == "": nameJapanese = "NOT AVAILABLE" # English title nameEnglish = _response["title"]["pretty"] if nameEnglis...
async def infoEmbedMessage(_response, _channel): # ID
requestedID = str(_response["id"]) # Japanese title nameJapanese = _response["title"]["japanese"] if nameJapanese == "": nameJapanese = "NOT AVAILABLE" # English title nameEnglish = _response["title"]["pretty"] if nameEnglish == "": nameEnglish = _response["title"]["english...
2] if len(tagsString) > 1000: tagsString = tagsString[:1000]+"..." return tagsString; # catch for loli in tags async def catchLoliTags(response,_channel): tagString = await getGenresString(response) if "loli" in tagString or "lolicon" in tagString or "shota" in tagString or "shotacon" in tagSt...
179
179
599
15
163
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
infoEmbedMessage
infoEmbedMessage
101
155
101
102
40992ab13dcc4c8ab4b9c6448079f26d91a4b6fa
bigcode/the-stack
train
7cb42498c6cab5a9ef36d9a6
train
function
async def getGenresString(response): tagsListDicts = response["tags"] tagsString = " " for i in tagsListDicts: tagsString += (str(i['name']))+", " if tagsString == " ": tagsString = "ERROR: could not get tags" tagsString = tagsString[:-2] if len(tagsString) > 1000: tagsSt...
async def getGenresString(response):
tagsListDicts = response["tags"] tagsString = " " for i in tagsListDicts: tagsString += (str(i['name']))+", " if tagsString == " ": tagsString = "ERROR: could not get tags" tagsString = tagsString[:-2] if len(tagsString) > 1000: tagsString = tagsString[:1000]+"..." r...
(_channel): if _channel in allowedChannels: await buildEmbedMessage("Wrong channel.","Use channels:",allowedChannels,discord.Colour.red(),"This message will delete itself later.",_channel,[True],10 ) # Helper functions ----------------------------------------------------------------------------------------...
64
64
100
7
56
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
getGenresString
getGenresString
78
89
78
78
03b589ed2c5ce86869ba28a4533891b637b76d60
bigcode/the-stack
train
863ab93297e26eb9a8ac274c
train
function
async def checkAllowedChannel(_channel): if _channel in allowedChannels: await buildEmbedMessage("Wrong channel.","Use channels:",allowedChannels,discord.Colour.red(),"This message will delete itself later.",_channel,[True],10 )
async def checkAllowedChannel(_channel):
if _channel in allowedChannels: await buildEmbedMessage("Wrong channel.","Use channels:",allowedChannels,discord.Colour.red(),"This message will delete itself later.",_channel,[True],10 )
False: requestedID = random.randint(1,300000) response = await getHentaiByID(requestedID) response = await getHentaiByID(requestedID) await infoEmbedMessage(response, _channel) #delete if wrong Channel async def checkAllowedChannel(_channel):
64
64
50
8
55
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
checkAllowedChannel
checkAllowedChannel
72
74
72
72
301c6cd74b124ba9a399f496550b3b6bff349812
bigcode/the-stack
train
d61ff2182f9bb3a11af680f7
train
function
@client.event async def on_message(message): channel = message.channel messageAuthor = message.author guild = message.guild #filter wrong channel if channel in allowedChannels: # Help if message.content.startswith("h!help"): title = "👊😎Hentei : Help page😎👊" ...
@client.event async def on_message(message):
channel = message.channel messageAuthor = message.author guild = message.guild #filter wrong channel if channel in allowedChannels: # Help if message.content.startswith("h!help"): title = "👊😎Hentei : Help page😎👊" headers = ["h!help", "h!sear...
, buildDailyHentai(channel))) loop.run_until_complete() except: print("Daily hentei scheduled for "+str(time.strftime("%H:%M:%S"))+".") channel = discord.utils.get(guild.text_channels, name="general") #await buildEmbedMessage("Connected!",["Are you ready for freddy?"],["Are you?"],di...
256
256
4,140
10
245
ManuelStaffa/croppedHentei
croppedHentei/main.py
Python
on_message
on_message
241
664
241
242
6b098babe35467e466077c13be8b2ee1c5062630
bigcode/the-stack
train
4c45e800f05ef4bda6560919
train
class
class QuestionCreationHandler(base.BaseHandler): """A handler that creates the question model given a question dict.""" @acl_decorators.can_manage_question_skill_status def post(self, skill_id): """Handles POST requests.""" if not constants.ENABLE_NEW_STRUCTURE_EDITORS: raise se...
class QuestionCreationHandler(base.BaseHandler):
"""A handler that creates the question model given a question dict.""" @acl_decorators.can_manage_question_skill_status def post(self, skill_id): """Handles POST requests.""" if not constants.ENABLE_NEW_STRUCTURE_EDITORS: raise self.PageNotFoundException skill_domain.Sk...
and # limitations under the License. """Controllers for the questions editor, from where questions are edited and are created. """ from constants import constants from core.controllers import acl_decorators from core.controllers import base from core.domain import question_domain from core.domain import question_ser...
86
86
289
8
77
WickedBrat/oppia
core/controllers/question_editor.py
Python
QuestionCreationHandler
QuestionCreationHandler
29
63
29
29
d434643f8008dd4818bbe5b009ac232d3268b13a
bigcode/the-stack
train
32cf0d48a81b51c8b88df39b
train
class
class EditableQuestionDataHandler(base.BaseHandler): """A data handler for questions which supports writing.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_view_question_editor def get(self, question_id): """Gets the data for the question overview page.""" ...
class EditableQuestionDataHandler(base.BaseHandler):
"""A data handler for questions which supports writing.""" GET_HANDLER_ERROR_RETURN_TYPE = feconf.HANDLER_TYPE_JSON @acl_decorators.can_view_question_editor def get(self, question_id): """Gets the data for the question overview page.""" if not constants.ENABLE_NEW_STRUCTURE_EDITORS: ...
raise self.PageNotFoundException skill_domain.Skill.require_valid_skill_id(skill_id) skill = skill_services.get_skill_by_id(skill_id, strict=False) if skill is None: raise self.PageNotFoundException( 'The skill with the given id doesn\'t exist.') question_s...
166
166
554
9
157
WickedBrat/oppia
core/controllers/question_editor.py
Python
EditableQuestionDataHandler
EditableQuestionDataHandler
96
178
96
96
4757cf5e3741de3710090b40f1fd5708834e53cb
bigcode/the-stack
train
00fe4daee97505a7b9bc3f47
train
class
class QuestionSkillLinkHandler(base.BaseHandler): """A handler for linking and unlinking questions to or from a skill.""" @acl_decorators.can_manage_question_skill_status def post(self, question_id, skill_id): """Links a question to a skill.""" if not constants.ENABLE_NEW_STRUCTURE_EDITORS:...
class QuestionSkillLinkHandler(base.BaseHandler):
"""A handler for linking and unlinking questions to or from a skill.""" @acl_decorators.can_manage_question_skill_status def post(self, question_id, skill_id): """Links a question to a skill.""" if not constants.ENABLE_NEW_STRUCTURE_EDITORS: raise self.PageNotFoundException ...
= question_domain.Question.from_dict(question_dict) question_services.add_question(self.user_id, question) question_services.create_new_question_skill_link( question.id, skill_id) self.values.update({ 'question_id': question.id }) self.render_json(self.va...
67
67
226
9
58
WickedBrat/oppia
core/controllers/question_editor.py
Python
QuestionSkillLinkHandler
QuestionSkillLinkHandler
66
93
66
66
38efe2e99b584a98878ea60f8085a10cc80e0cb1
bigcode/the-stack
train
5d6e190c9dce6bf8a0c22ee4
train
class
class ObstacleDetection(Sensor): """ Actor implementation details for a obstacle detection """ def __init__(self, uid, name, parent, relative_spawn_pose, node, carla_actor, synchronous_mode): """ Constructor :param uid: unique identifier for this object :type uid: int ...
class ObstacleDetection(Sensor):
""" Actor implementation details for a obstacle detection """ def __init__(self, uid, name, parent, relative_spawn_pose, node, carla_actor, synchronous_mode): """ Constructor :param uid: unique identifier for this object :type uid: int :param name: name identiyi...
#!/usr/bin/env python # # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. # """ Classes to handle obstacle_detection events """ from carla_ros_bridge.sensor import Sensor from carla_msgs.msg import CarlaObstacleDetectionEvent class ObstacleDetectio...
73
138
463
7
65
ricardodeazambuja/carla-ros-bridge
carla_ros_bridge/src/carla_ros_bridge/obstacle_detection_sensor.py
Python
ObstacleDetection
ObstacleDetection
17
74
17
18
cd2fcb0e496a61026ec1671b8acb72937bb4ce7e
bigcode/the-stack
train
2dcfc7c0ca1243ae54cbf70f
train
class
class Enrollment(models.Model): AUDIT = 'audit' HONOR = 'honor' BETA = 'BETA' COURSE_MODES = [ (AUDIT, 'Audit'), (HONOR, 'Honor'), (BETA, 'BETA') ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delet...
class Enrollment(models.Model):
AUDIT = 'audit' HONOR = 'honor' BETA = 'BETA' COURSE_MODES = [ (AUDIT, 'Audit'), (HONOR, 'Honor'), (BETA, 'BETA') ] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) date_enrol...
Key(Course, on_delete=models.CASCADE) content = models.TextField() # Enrollment model # <HINT> Once a user enrolled a class, an enrollment entry should be created between the user and course # And we could use the enrollment to track information such as exam submissions class Enrollment(models.Model):
64
64
138
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Enrollment
Enrollment
82
95
82
82
e23259bc26c76c4841827ca940098d7fc0b5e08f
bigcode/the-stack
train
169d5264316e296db298d048
train
class
class Instructor(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) full_time = models.BooleanField(default=True) total_learners = models.IntegerField() def __str__(self): return self.user.username
class Instructor(models.Model):
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) full_time = models.BooleanField(default=True) total_learners = models.IntegerField() def __str__(self): return self.user.username
import sys from django.utils.timezone import now try: from django.db import models except Exception: print("There was an error loading django modules. Do you have django installed?") sys.exit() from django.conf import settings import uuid # Instructor model class Instructor(models.Model):
62
64
59
5
56
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Instructor
Instructor
14
23
14
14
28fbe7c8ff815dd17250fa08714f7679b909f50c
bigcode/the-stack
train
f394db2318ed568b1782fb4a
train
class
class Course(models.Model): name = models.CharField(null=False, max_length=30, default='online course') image = models.ImageField(upload_to='course_images/') description = models.CharField(max_length=1000) pub_date = models.DateField(null=True) instructors = models.ManyToManyField(Instructor) us...
class Course(models.Model):
name = models.CharField(null=False, max_length=30, default='online course') image = models.ImageField(upload_to='course_images/') description = models.CharField(max_length=1000) pub_date = models.DateField(null=True) instructors = models.ManyToManyField(Instructor) users = models.ManyToManyField...
_length=20, choices=OCCUPATION_CHOICES, default=STUDENT ) social_link = models.URLField(max_length=200) def __str__(self): return self.user.username + "," + \ self.occupation # Course model class Course(models.Model):
64
64
134
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Course
Course
56
68
56
56
6e074a87952fa7de570db8f24ebc1eafc9caad9f
bigcode/the-stack
train
95a7c946d111144ac46ae69d
train
class
class Question(models.Model): question_text = models.CharField(max_length=100) grade = models.IntegerField() course = models.ForeignKey(Course, on_delete=models.CASCADE) def is_get_score(self, selected_ids): all_answers = self.choice_set.filter(is_correct=True).count() selected_correct = ...
class Question(models.Model):
question_text = models.CharField(max_length=100) grade = models.IntegerField() course = models.ForeignKey(Course, on_delete=models.CASCADE) def is_get_score(self, selected_ids): all_answers = self.choice_set.filter(is_correct=True).count() selected_correct = self.choice_set.filter(is_corr...
question content for a course # Has a One-To-Many (or Many-To-Many if you want to reuse questions) relationship with course # Has a grade point for each question # Has question content # Other fields and methods you would like to design class Question(models.Model):
64
64
102
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Question
Question
105
116
105
105
c446112387c4e57338ff11d2d0e9155918a61f11
bigcode/the-stack
train
79dbc1cc7f5a5ec18738d873
train
class
class Submission(models.Model): enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE) choices = models.ManyToManyField(Choice)
class Submission(models.Model):
enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE) choices = models.ManyToManyField(Choice)
=50) is_correct = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE) # <HINT> The submission model # One enrollment could have multiple submission # One submission could have multiple choices # One choice could belong to multiple submissions class Submission(models.Model):
64
64
30
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Submission
Submission
129
131
129
129
16d0dcb5d165d183c72c63d784346f2abfcf2c05
bigcode/the-stack
train
9e9e4fbf80b9d217cfcec8ed
train
class
class Learner(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) STUDENT = 'student' DEVELOPER = 'developer' DATA_SCIENTIST = 'data_scientist' DATABASE_ADMIN = 'dba' OCCUPATION_CHOICES = [ (STUDENT, 'Student'), (DEVE...
class Learner(models.Model):
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) STUDENT = 'student' DEVELOPER = 'developer' DATA_SCIENTIST = 'data_scientist' DATABASE_ADMIN = 'dba' OCCUPATION_CHOICES = [ (STUDENT, 'Student'), (DEVELOPER, 'Developer'), ...
user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) full_time = models.BooleanField(default=True) total_learners = models.IntegerField() def __str__(self): return self.user.username # Learner model class Learner(models.Model):
64
64
179
6
57
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Learner
Learner
27
52
27
27
995041fe56608d36067d4732bfabcaf683669603
bigcode/the-stack
train
8ebf299d2e189324058dfa6a
train
class
class Choice(models.Model): choice_text = models.CharField(max_length=50) is_correct = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE)
class Choice(models.Model):
choice_text = models.CharField(max_length=50) is_correct = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE)
(self, selected_ids): all_answers = self.choice_set.filter(is_correct=True).count() selected_correct = self.choice_set.filter(is_correct=True, id__in=selected_ids).count() if all_answers == selected_correct: return True else: return False class Choice(models.Model):
64
64
39
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Choice
Choice
119
122
119
119
a73b1b797a837c4f1c6228889bd730e31f1daef4
bigcode/the-stack
train
a57d0851d07e4f2dbdf485fe
train
class
class Lesson(models.Model): title = models.CharField(max_length=200, default="title") order = models.IntegerField(default=0) course = models.ForeignKey(Course, on_delete=models.CASCADE) content = models.TextField()
class Lesson(models.Model):
title = models.CharField(max_length=200, default="title") order = models.IntegerField(default=0) course = models.ForeignKey(Course, on_delete=models.CASCADE) content = models.TextField()
_USER_MODEL, through='Enrollment') total_enrollment = models.IntegerField(default=0) is_enrolled = False def __str__(self): return "Name: " + self.name + "," + \ "Description: " + self.description # Lesson model class Lesson(models.Model):
64
64
51
5
58
SteffanoX/final-cloud-app-with-database
onlinecourse/models.py
Python
Lesson
Lesson
72
76
72
72
e70f370c823d596b5a2334fefb0f2592368204c4
bigcode/the-stack
train
db9acf37af92f994bf923574
train
class
@unittest.skipUnless(os.environ.get('WITH_SELENIUM', False), "The WITH_SELENIUM env variable is not set.") class SeleniumTestCase(horizon_helpers.SeleniumTestCase): def setUp(self): super(SeleniumTestCase, self).setUp() test_utils.load_test_data(self) self.mox = mox.Mo...
@unittest.skipUnless(os.environ.get('WITH_SELENIUM', False), "The WITH_SELENIUM env variable is not set.") class SeleniumTestCase(horizon_helpers.SeleniumTestCase):
def setUp(self): super(SeleniumTestCase, self).setUp() test_utils.load_test_data(self) self.mox = mox.Mox() self._real_get_user = utils.get_user self.setActiveUser(id=self.user.id, token=self.token, username=self.user.na...
return self.troveclient def stub_saharaclient(self): if not hasattr(self, "saharaclient"): self.mox.StubOutWithMock(sahara_client, 'Client') self.saharaclient = self.mox.CreateMock(sahara_client.Client) return self.saharaclient @unittest.skipUnless(os.environ.get('WITH_SELE...
109
109
365
41
67
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
SeleniumTestCase
SeleniumTestCase
427
472
427
430
b2b66b12b63dbc36cc0897de991251d02a6b8ecf
bigcode/the-stack
train
f06c552126a7935804e93cbb
train
class
class PluginTestCase(TestCase): """Test case for testing plugin system of Horizon. For use with tests which deal with the pluggable dashboard and panel configuration, it takes care of backing up and restoring the Horizon configuration. """ def setUp(self): super(PluginTestCase, self).se...
class PluginTestCase(TestCase):
"""Test case for testing plugin system of Horizon. For use with tests which deal with the pluggable dashboard and panel configuration, it takes care of backing up and restoring the Horizon configuration. """ def setUp(self): super(PluginTestCase, self).setUp() self.old_horizon_c...
for Selenium. Sets an active user with the "admin" role for testing admin-only views and functionality. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.roles.admin._info] super(SeleniumAdminTestCase, self).setActiveUser(*args,...
148
148
494
7
141
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
PluginTestCase
PluginTestCase
497
549
497
497
187075be0d3a9eacb0e138d257b174409a4e702f
bigcode/the-stack
train
60f6a787ef59fa2b72ec0a1f
train
function
def create_stubs(stubs_to_create={}): """decorator to simplify setting up multiple stubs at once via mox :param stubs_to_create: methods to stub in one or more modules :type stubs_to_create: dict The keys are python paths to the module containing the methods to mock. To mock a method in openstack...
def create_stubs(stubs_to_create={}):
"""decorator to simplify setting up multiple stubs at once via mox :param stubs_to_create: methods to stub in one or more modules :type stubs_to_create: dict The keys are python paths to the module containing the methods to mock. To mock a method in openstack_dashboard/api/nova.py, the key is:: ...
sahara_client from swiftclient import client as swift_client from troveclient import client as trove_client from horizon import base from horizon import conf from horizon.test import helpers as horizon_helpers from openstack_dashboard import api from openstack_dashboard import context_processors from openstack_dashbo...
116
116
389
10
105
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
create_stubs
create_stubs
60
111
60
60
3b584c50dd42792df96045ff23f461f891a9dca6
bigcode/the-stack
train
40b360c998bc41dbb0f93d40
train
function
def my_custom_sort(flavor): sort_order = { 'm1.secret': 0, 'm1.tiny': 1, 'm1.massive': 2, 'm1.metadata': 3, } return sort_order[flavor.name]
def my_custom_sort(flavor):
sort_order = { 'm1.secret': 0, 'm1.tiny': 1, 'm1.massive': 2, 'm1.metadata': 3, } return sort_order[flavor.name]
. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.roles.admin._info] super(SeleniumAdminTestCase, self).setActiveUser(*args, **kwargs) def my_custom_sort(flavor):
64
64
61
7
57
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
my_custom_sort
my_custom_sort
487
494
487
487
35c8e3bc5ef952c8edaa6f961ecca8c223ad1d6e
bigcode/the-stack
train
8020c96799e4c19b7d737a6f
train
class
class RequestFactoryWithMessages(RequestFactory): def get(self, *args, **kwargs): req = super(RequestFactoryWithMessages, self).get(*args, **kwargs) req.user = utils.get_user(req) req.session = [] req._messages = default_storage(req) return req def post(self, *args, **kw...
class RequestFactoryWithMessages(RequestFactory):
def get(self, *args, **kwargs): req = super(RequestFactoryWithMessages, self).get(*args, **kwargs) req.user = utils.get_user(req) req.session = [] req._messages = default_storage(req) return req def post(self, *args, **kwargs): req = super(RequestFactoryWithMessa...
type(stubs_to_create[key]).__name__) for value in stubs_to_create[key]: self.mox.StubOutWithMock(key, value) return fn(self, *args, **kwargs) return instance_stub_out return inner_stub_out class RequestFactoryWithMessages(RequestFactory):
64
64
120
8
55
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
RequestFactoryWithMessages
RequestFactoryWithMessages
114
127
114
114
0f5f03de0cbd9ef28c16d24760f876460a0fe3e5
bigcode/the-stack
train
a1f180cdafcce45e934f3e9e
train
class
@unittest.skipIf(os.environ.get('SKIP_UNITTESTS', False), "The SKIP_UNITTESTS env variable is set.") class TestCase(horizon_helpers.TestCase): """Specialized base test case class for Horizon. It gives access to numerous additional features: * A full suite of test data through various at...
@unittest.skipIf(os.environ.get('SKIP_UNITTESTS', False), "The SKIP_UNITTESTS env variable is set.") class TestCase(horizon_helpers.TestCase):
"""Specialized base test case class for Horizon. It gives access to numerous additional features: * A full suite of test data through various attached objects and managers (e.g. ``self.servers``, ``self.user``, etc.). See the docs for :class:`~openstack_dashboard.test.test_data.u...
isinstance(stubs_to_create[key], list)): raise TypeError("The values of the create_stub " "dict must be lists or tuples, but " "is a %s." % type(stubs_to_create[key]).__name__) ...
256
256
1,224
39
216
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
TestCase
TestCase
130
268
130
132
63db2976992827156e1af30e09c0d6684b6c4cc7
bigcode/the-stack
train
591f1db0f96268b1368300f5
train
class
class update_settings(django_test_utils.override_settings): """override_settings which allows override an item in dict. django original override_settings replaces a dict completely, however OpenStack dashboard setting has many dictionary configuration and there are test case where we want to override o...
class update_settings(django_test_utils.override_settings):
"""override_settings which allows override an item in dict. django original override_settings replaces a dict completely, however OpenStack dashboard setting has many dictionary configuration and there are test case where we want to override only one item in a dictionary and keep other items in the...
to be re-calculated after registering new dashboards. Useful only for testing and should never be used on a live site. """ urlresolvers.clear_url_caches() reload(import_module(settings.ROOT_URLCONF)) base.Horizon._urls() class update_settings(django_test_utils.override_settings)...
64
64
197
10
54
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
update_settings
update_settings
552
574
552
552
80de8d54bd3c3d05666ed4d2519eed2be3738651
bigcode/the-stack
train
dce2441947cc5135db4601f2
train
class
class APITestCase(TestCase): """Testing APIs. For use with tests which deal with the underlying clients rather than stubbing out the openstack_dashboard.api.* methods. """ def setUp(self): super(APITestCase, self).setUp() utils.patch_middleware_get_user() def fake_keystonec...
class APITestCase(TestCase):
"""Testing APIs. For use with tests which deal with the underlying clients rather than stubbing out the openstack_dashboard.api.* methods. """ def setUp(self): super(APITestCase, self).setUp() utils.patch_middleware_get_user() def fake_keystoneclient(request, admin=False): ...
in unicode(errors): self.fail("Expected message not found, instead found: %s" % ["%s: %s" % (key, [e for e in field_errors]) for (key, field_errors) in errors.items()]) else: assert len(errors) > 0, "No errors were found on the ...
256
256
1,329
7
248
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
APITestCase
APITestCase
293
424
293
293
3d42d52187ebba6ae258b3b445650808e0d1904f
bigcode/the-stack
train
9d69a1a418bc9fe7439a638d
train
class
class BaseAdminViewTests(TestCase): """Sets an active user with the "admin" role. For testing admin-only views and functionality. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.roles.admin._info] super(BaseAdminViewTests, self...
class BaseAdminViewTests(TestCase):
"""Sets an active user with the "admin" role. For testing admin-only views and functionality. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.roles.admin._info] super(BaseAdminViewTests, self).setActiveUser(*args, **kwargs) ...
" % ["%s: %s" % (key, [e for e in field_errors]) for (key, field_errors) in errors.items()]) else: assert len(errors) > 0, "No errors were found on the form" class BaseAdminViewTests(TestCase):
64
64
175
8
56
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
BaseAdminViewTests
BaseAdminViewTests
271
290
271
271
cf5e9807308dd12b23c15feb22b014976369e008
bigcode/the-stack
train
1fd70fa875051e00a659912d
train
class
class SeleniumAdminTestCase(SeleniumTestCase): """Version of AdminTestCase for Selenium. Sets an active user with the "admin" role for testing admin-only views and functionality. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.role...
class SeleniumAdminTestCase(SeleniumTestCase):
"""Version of AdminTestCase for Selenium. Sets an active user with the "admin" role for testing admin-only views and functionality. """ def setActiveUser(self, *args, **kwargs): if "roles" not in kwargs: kwargs['roles'] = [self.roles.admin._info] super(SeleniumAdminTestC...
user=username, tenant_id=tenant_id, service_catalog=service_catalog, roles=roles, enabled=enabled, authorized_tenants=authorized_tenants, ...
64
64
97
10
53
gabrielhurley/horizon
openstack_dashboard/test/helpers.py
Python
SeleniumAdminTestCase
SeleniumAdminTestCase
475
484
475
475
8df478fd7bc85e3c77dd136bbf964a67813fd973
bigcode/the-stack
train
0fd05ded8c6aeabdec765b4e
train
class
class LiveServer(Server): # pragma: no cover # Python 3.6 only """ A test server running on a live location. """ sends_reason = True def __init__(self, host: str, port: int) -> None: self._host = host self._port = port @property def netloc(self) -> Tuple[bytes, int]: ...
class LiveServer(Server): # pragma: no cover # Python 3.6 only
""" A test server running on a live location. """ sends_reason = True def __init__(self, host: str, port: int) -> None: self._host = host self._port = port @property def netloc(self) -> Tuple[bytes, int]: return (self._host.encode("ascii"), self._port) @proper...
-> str: raise NotImplementedError # pragma: no cover @property def host_header(self) -> Tuple[bytes, bytes]: raise NotImplementedError # pragma: no cover class LiveServer(Server): # pragma: no cover # Python 3.6 only
64
64
134
20
43
jborean93/httpcore
tests/utils.py
Python
LiveServer
LiveServer
61
78
61
61
131e92a655eab4ad63d80c0c024e9946c56edb20
bigcode/the-stack
train
a17f1881749ebdf0324bcfcc
train
class
class HypercornServer(Server): # pragma: no cover # Python 3.7+ only """ A test server running in-process, powered by Hypercorn. """ sends_reason = False def __init__( self, app: Callable, bind: str, certfile: str = None, keyfile: str = None, ) -> None...
class HypercornServer(Server): # pragma: no cover # Python 3.7+ only
""" A test server running in-process, powered by Hypercorn. """ sends_reason = False def __init__( self, app: Callable, bind: str, certfile: str = None, keyfile: str = None, ) -> None: assert hypercorn_config is not None self._app = app ...
""" A test server running on a live location. """ sends_reason = True def __init__(self, host: str, port: int) -> None: self._host = host self._port = port @property def netloc(self) -> Tuple[bytes, int]: return (self._host.encode("ascii"), self._port) @proper...
136
137
459
22
114
jborean93/httpcore
tests/utils.py
Python
HypercornServer
HypercornServer
81
148
81
81
aca47009eefb8f3ad44666f6d813d77100f01f48
bigcode/the-stack
train
9fc0dd5dc965ff459757ef53
train
function
def lookup_async_backend(): return sniffio.current_async_library()
def lookup_async_backend():
return sniffio.current_async_library()
hypercorn import config as hypercorn_config, trio as hypercorn_trio except ImportError: # pragma: no cover # Python 3.6 hypercorn_config = None # type: ignore hypercorn_trio = None # type: ignore def lookup_async_backend():
64
64
13
5
58
jborean93/httpcore
tests/utils.py
Python
lookup_async_backend
lookup_async_backend
20
21
20
20
cc7b80b5a6b0dcdc82057054b6539ab8a159834d
bigcode/the-stack
train
92f57d11a025248acb494420
train
function
@contextlib.contextmanager def http_proxy_server(proxy_host: str, proxy_port: int): """ This function launches pproxy process like this: $ pproxy -b <blocked_hosts_file> -l http://127.0.0.1:8080 What does it mean? It runs HTTP proxy on 127.0.0.1:8080 and blocks access to some external hosts, ...
@contextlib.contextmanager def http_proxy_server(proxy_host: str, proxy_port: int):
""" This function launches pproxy process like this: $ pproxy -b <blocked_hosts_file> -l http://127.0.0.1:8080 What does it mean? It runs HTTP proxy on 127.0.0.1:8080 and blocks access to some external hosts, specified in blocked_hosts_file Relevant pproxy docs could be found in their g...
= threading.Thread(target=self._run) thread.start() try: while not self._started: time.sleep(1e-3) yield finally: self._should_exit = True thread.join() @contextlib.contextmanager def http_proxy_server(proxy_host: str, proxy_port: ...
69
69
231
20
49
jborean93/httpcore
tests/utils.py
Python
http_proxy_server
http_proxy_server
151
181
151
152
9472042ad4a6c9ac25d4362758fbd8fc2583d1e1
bigcode/the-stack
train
b0daa6b35e6fe8c830c36e60
train
function
@contextlib.contextmanager def create_proxy_block_file(blocked_domains: List[str]): """ The context manager yields pproxy block file. This file should contain line delimited hostnames. We use it in the following test: test_proxy_socket_does_not_leak_when_the_connection_hasnt_been_added_to_pool "...
@contextlib.contextmanager def create_proxy_block_file(blocked_domains: List[str]):
""" The context manager yields pproxy block file. This file should contain line delimited hostnames. We use it in the following test: test_proxy_socket_does_not_leak_when_the_connection_hasnt_been_added_to_pool """ with tempfile.NamedTemporaryFile(delete=True, mode="w+") as file: fo...
proc = subprocess.Popen(command) _wait_can_connect(proxy_host, proxy_port) yield b"http", proxy_host.encode(), proxy_port, b"/" finally: if proc is not None: proc.kill() @contextlib.contextmanager def create_proxy_block_file(blocked_domains: List[str]):
64
64
114
18
46
jborean93/httpcore
tests/utils.py
Python
create_proxy_block_file
create_proxy_block_file
184
199
184
185
6154d5065d561ceb4d1e1c317274597bd89420cb
bigcode/the-stack
train
4675081017535ffeaeadfd09
train
function
def _wait_can_connect(host: str, port: int): while True: try: sock = socket.create_connection((host, port)) except ConnectionRefusedError: time.sleep(0.25) else: sock.close() break
def _wait_can_connect(host: str, port: int):
while True: try: sock = socket.create_connection((host, port)) except ConnectionRefusedError: time.sleep(0.25) else: sock.close() break
.6 hypercorn_config = None # type: ignore hypercorn_trio = None # type: ignore def lookup_async_backend(): return sniffio.current_async_library() def lookup_sync_backend(): return "sync" def _wait_can_connect(host: str, port: int):
64
64
56
13
51
jborean93/httpcore
tests/utils.py
Python
_wait_can_connect
_wait_can_connect
28
36
28
28
3f083fe0da06a1ffbf681c5dadc2d375bfce3fc8
bigcode/the-stack
train
f0913c1739f894d09d5abb10
train
function
def lookup_sync_backend(): return "sync"
def lookup_sync_backend():
return "sync"
_trio except ImportError: # pragma: no cover # Python 3.6 hypercorn_config = None # type: ignore hypercorn_trio = None # type: ignore def lookup_async_backend(): return sniffio.current_async_library() def lookup_sync_backend():
64
64
10
5
59
jborean93/httpcore
tests/utils.py
Python
lookup_sync_backend
lookup_sync_backend
24
25
24
24
42b773beaddeb4e808131c7f8e02b837424930dd
bigcode/the-stack
train
762315bfc484e482310b9000
train
class
class Server: """ Base interface for servers we can test against. """ @property def sends_reason(self) -> bool: raise NotImplementedError # pragma: no cover @property def netloc(self) -> Tuple[bytes, int]: raise NotImplementedError # pragma: no cover @property de...
class Server:
""" Base interface for servers we can test against. """ @property def sends_reason(self) -> bool: raise NotImplementedError # pragma: no cover @property def netloc(self) -> Tuple[bytes, int]: raise NotImplementedError # pragma: no cover @property def uds(self) ->...
return "sync" def _wait_can_connect(host: str, port: int): while True: try: sock = socket.create_connection((host, port)) except ConnectionRefusedError: time.sleep(0.25) else: sock.close() break class Server:
64
64
124
3
60
jborean93/httpcore
tests/utils.py
Python
Server
Server
39
58
39
39
8ea4d30f4777f235457e85b9aeb82b1735c446da
bigcode/the-stack
train
487443f15549ccf800344683
train
class
class _Upsample(nn.Module): def __init__(self, num_maps_in, skip_maps_in, num_maps_out, use_bn=True, k=3): super(_Upsample, self).__init__() #print(f'Upsample layer: in = {num_maps_in}, skip = {skip_maps_in}, out = {num_maps_out}') self.bottleneck = _BNReluConv(skip_maps_in, num_maps_in, k=1...
class _Upsample(nn.Module):
def __init__(self, num_maps_in, skip_maps_in, num_maps_out, use_bn=True, k=3): super(_Upsample, self).__init__() #print(f'Upsample layer: in = {num_maps_in}, skip = {skip_maps_in}, out = {num_maps_out}') self.bottleneck = _BNReluConv(skip_maps_in, num_maps_in, k=1, batch_norm=use_bn) ...
_module('relu', nn.ReLU(inplace=batch_norm is True)) padding = k // 2 self.add_module('conv', nn.Conv2d(num_maps_in, num_maps_out, kernel_size=k, padding=padding, bias=bias, dilation=dilation)) class _Upsample(nn.Module):
64
64
192
7
57
pinghu6/FANet
Testing/models/swiftnet/util.py
Python
_Upsample
_Upsample
30
43
30
30
8cf079042e04fa636ca59aaa4547acf291c26b24
bigcode/the-stack
train
5b9689cb8e54f7cf895dedb5
train
class
class _UpsampleBlend(nn.Module): def __init__(self, num_features, use_bn=True): super(_UpsampleBlend, self).__init__() self.blend_conv = _BNReluConv(num_features, num_features, k=3, batch_norm=use_bn) def forward(self, x, skip): skip_size = skip.size()[2:4] x = upsample(x, skip_...
class _UpsampleBlend(nn.Module):
def __init__(self, num_features, use_bn=True): super(_UpsampleBlend, self).__init__() self.blend_conv = _BNReluConv(num_features, num_features, k=3, batch_norm=use_bn) def forward(self, x, skip): skip_size = skip.size()[2:4] x = upsample(x, skip_size) x = x + skip ...
]) level = self.spp[i].forward(x_pooled) level = upsample(level, target_size) levels.append(level) x = torch.cat(levels, 1) x = self.spp[-1].forward(x) return x class _UpsampleBlend(nn.Module):
64
64
111
8
55
pinghu6/FANet
Testing/models/swiftnet/util.py
Python
_UpsampleBlend
_UpsampleBlend
89
99
89
89
acf3e83cb26af97b10bc716d06737cdb3182ea0c
bigcode/the-stack
train
c2a33f1b5081f42c32ae1401
train
class
class _BNReluConv(nn.Sequential): def __init__(self, num_maps_in, num_maps_out, k=3, batch_norm=True, bn_momentum=0.1, bias=False, dilation=1): super(_BNReluConv, self).__init__() if batch_norm: self.add_module('norm', nn.BatchNorm2d(num_maps_in, momentum=bn_momentum)) self.add_m...
class _BNReluConv(nn.Sequential):
def __init__(self, num_maps_in, num_maps_out, k=3, batch_norm=True, bn_momentum=0.1, bias=False, dilation=1): super(_BNReluConv, self).__init__() if batch_norm: self.add_module('norm', nn.BatchNorm2d(num_maps_in, momentum=bn_momentum)) self.add_module('relu', nn.ReLU(inplace=batc...
0.01 / 2 def get_n_params(parameters): pp = 0 for p in parameters: nn = 1 for s in list(p.size()): nn = nn * s pp += nn return pp class _BNReluConv(nn.Sequential):
64
64
146
9
54
pinghu6/FANet
Testing/models/swiftnet/util.py
Python
_BNReluConv
_BNReluConv
19
27
19
19
e390c40c7a368a7e7a0ed049602991b4d238f50e
bigcode/the-stack
train
0a128b5a94fa93876ebd597d
train
class
class SpatialPyramidPooling(nn.Module): def __init__(self, num_maps_in, num_levels, bt_size=512, level_size=128, out_size=128, grids=(6, 3, 2, 1), square_grid=False, bn_momentum=0.1, use_bn=True): super(SpatialPyramidPooling, self).__init__() self.grids = grids self.square_g...
class SpatialPyramidPooling(nn.Module):
def __init__(self, num_maps_in, num_levels, bt_size=512, level_size=128, out_size=128, grids=(6, 3, 2, 1), square_grid=False, bn_momentum=0.1, use_bn=True): super(SpatialPyramidPooling, self).__init__() self.grids = grids self.square_grid = square_grid self.spp = nn....
= {skip_maps_in}, out = {num_maps_out}') self.bottleneck = _BNReluConv(skip_maps_in, num_maps_in, k=1, batch_norm=use_bn) self.blend_conv = _BNReluConv(num_maps_in, num_maps_out, k=k, batch_norm=use_bn) def forward(self, x, skip): skip = self.bottleneck.forward(skip) skip_size = sk...
139
139
466
8
130
pinghu6/FANet
Testing/models/swiftnet/util.py
Python
SpatialPyramidPooling
SpatialPyramidPooling
46
86
46
46
400eef2eeaa0b309555bd51ae62ca0af2829ef0b
bigcode/the-stack
train
d52dca54abe553a3d20b79ba
train
function
def get_n_params(parameters): pp = 0 for p in parameters: nn = 1 for s in list(p.size()): nn = nn * s pp += nn return pp
def get_n_params(parameters):
pp = 0 for p in parameters: nn = 1 for s in list(p.size()): nn = nn * s pp += nn return pp
import torch import torch.nn as nn import torch.nn.functional as F upsample = lambda x, size: F.interpolate(x, size, mode='bilinear', align_corners=False) batchnorm_momentum = 0.01 / 2 def get_n_params(parameters):
59
64
48
6
52
pinghu6/FANet
Testing/models/swiftnet/util.py
Python
get_n_params
get_n_params
9
16
9
9
b81672bf14eb803db2418364df6b84c2a81ba99e
bigcode/the-stack
train
03f39bcb70d776194b44224c
train
class
class ReinforceAgentAdapter(AgentAdapter): def _create(self, model_id, environment_specs, **kwargs): model = ReinforceAgent( id=model_id, obs_dim=environment_specs.num_input, act_dim=environment_specs.num_action, **kwargs ) model_user_data = { "environment_implementat...
class ReinforceAgentAdapter(AgentAdapter):
def _create(self, model_id, environment_specs, **kwargs): model = ReinforceAgent( id=model_id, obs_dim=environment_specs.num_input, act_dim=environment_specs.num_action, **kwargs ) model_user_data = { "environment_implementation": environment_specs.implementation, ...
from cogment_verse_tf_agents.reinforce.sample_producer import sample_producer from cogment_verse_tf_agents.reinforce.training_run import create_training_run from cogment_verse_tf_agents.wrapper import cog_action_from_tf_action, tf_obs_from_cog_obs from data_pb2 import RunConfig from prometheus_client import Summary CO...
156
156
523
9
146
kharyal/cogment-verse
tf_agents/cogment_verse_tf_agents/reinforce/reinforce_agent_adapter.py
Python
ReinforceAgentAdapter
ReinforceAgentAdapter
38
98
38
38
546d1d981c9baaa13c0d43ff5daca039ad06e7d8
bigcode/the-stack
train
13a323b19b3916536200871c
train
function
async def save_audio(): stream = MicrophoneStreaming() await stream.record_to_file(filename=filename, duration=duration)
async def save_audio():
stream = MicrophoneStreaming() await stream.record_to_file(filename=filename, duration=duration)
=0, sr=16000, dtype="float32") for block in stream.generator(): # process here print(len(block)) ## saving recording to audio file filename = "hello.wav" duration = 10 ## saving recording to audio file async def save_audio():
64
64
26
5
58
Leofltt/rg_speech_to_text
examples/wavenet/example.py
Python
save_audio
save_audio
39
41
39
39
a88f72b0ea2fbea9d9ed4ff411daa9e4cf5bf430
bigcode/the-stack
train
f946808b7781c65ba65ce412
train
function
async def capture(): stream = MicrophoneStreaming() async for block, status in stream.generator(): # process data here print(len(block))
async def capture():
stream = MicrophoneStreaming() async for block, status in stream.generator(): # process data here print(len(block))
## saving recording to audio file async def save_audio(): stream = MicrophoneStreaming() await stream.record_to_file(filename=filename, duration=duration) print("start recording") try: asyncio.run(save_audio()) except KeyboardInterrupt: print("Exited") # microphone streaming async def capture():
64
64
32
4
59
Leofltt/rg_speech_to_text
examples/wavenet/example.py
Python
capture
capture
51
55
51
51
94e629834db069dd05e0cc5c96a1eb1510aaaf26
bigcode/the-stack
train
f7eff7c4f496aa876a676dc2
train
class
class GridView(CollectionView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/grid.html"]
class GridView(CollectionView):
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/grid.html"]
().get_context_data( sources=self.get_sources(), series_id=self.kwargs.get('pk'), **kwargs ) class ListView(CollectionView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/list.html"] class GridView(CollectionView):
63
64
30
6
57
mincem/media_list
src/media_list/views/base_views.py
Python
GridView
GridView
33
35
33
33
8ac10d85a795a24278ee832f9b4230818dfda027
bigcode/the-stack
train
eda21fd0a38953c1e8f66fee
train
class
class EditFieldsView(generic.UpdateView): category = None def get_success_url(self): return reverse_lazy( f"categories:{self.get_category().path}:detail", kwargs={"pk": self.object.id} ) def get_category(self): if self.category: return self.categ...
class EditFieldsView(generic.UpdateView):
category = None def get_success_url(self): return reverse_lazy( f"categories:{self.get_category().path}:detail", kwargs={"pk": self.object.id} ) def get_category(self): if self.category: return self.category if self.model and self.model.c...
): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/edit.html"] def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list", kwargs={"pk": self.object.id}) class EditFieldsView(generic.UpdateView):
64
64
87
9
55
mincem/media_list
src/media_list/views/base_views.py
Python
EditFieldsView
EditFieldsView
77
91
77
77
b1382699878922a945493dafee5740e943f81ff7
bigcode/the-stack
train
a3c3b107f97208436ef8b5a9
train
class
class FetchExternalItemView(DetailView): def get(self, request, *args, **kwargs): item = self.get_object() item.external_info = ExternalItemFetcher.for_item(item).fetch() item.save() return super().get(self, request, *args, **kwargs)
class FetchExternalItemView(DetailView):
def get(self, request, *args, **kwargs): item = self.get_object() item.external_info = ExternalItemFetcher.for_item(item).fetch() item.save() return super().get(self, request, *args, **kwargs)
): def get(self, request, *args, **kwargs): item = self.get_object() item.external_id = ExternalIDFinder.for_item(item).get_id() item.save() return super().get(self, request, *args, **kwargs) class FetchExternalItemView(DetailView):
64
64
62
9
55
mincem/media_list
src/media_list/views/base_views.py
Python
FetchExternalItemView
FetchExternalItemView
51
56
51
51
b485bc2523b9bc343b9d9def1615e2ea989acff8
bigcode/the-stack
train
0ec1cb2262e5951905739a9f
train
class
class SwapTitlesView(DetailView): def get(self, request, *args, **kwargs): self.get_object().swap_titles() return super().get(self, request, *args, **kwargs)
class SwapTitlesView(DetailView):
def get(self, request, *args, **kwargs): self.get_object().swap_titles() return super().get(self, request, *args, **kwargs)
View(EditFieldsView): fields = ['alternate_title'] class DeleteView(generic.DeleteView): template_name = "media_list/categories/base/confirm_delete.html" def get_success_url(self): return reverse_lazy(f"categories:{self.model.category.path}:list") class SwapTitlesView(DetailView):
64
64
44
8
56
mincem/media_list
src/media_list/views/base_views.py
Python
SwapTitlesView
SwapTitlesView
113
116
113
113
28829b8cd08420cf6003d6cff26dde2c5ba90c77
bigcode/the-stack
train
c38f863cd7a2b5c079d0cbe9
train
class
class CreateView(CreateWithInlinesView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/create.html"] def get_success_url(self): if "add_another" in self.request.POST: return reverse_lazy(f"categories:{self.model.category.path}:create") ...
class CreateView(CreateWithInlinesView):
def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/create.html"] def get_success_url(self): if "add_another" in self.request.POST: return reverse_lazy(f"categories:{self.model.category.path}:create") return reverse_lazy(f"categories:{sel...
View): def get(self, request, *args, **kwargs): item = self.get_object() item.external_info = ExternalItemFetcher.for_item(item).fetch() item.save() return super().get(self, request, *args, **kwargs) class CreateView(CreateWithInlinesView):
64
64
90
9
55
mincem/media_list
src/media_list/views/base_views.py
Python
CreateView
CreateView
59
66
59
59
1ba72bc03ca14cece786ac8f750a715b534f39c7
bigcode/the-stack
train
0fc0a42251a979440ebc3db4
train
class
class EditInterestView(EditFieldsView): fields = ['interest']
class EditInterestView(EditFieldsView):
fields = ['interest']
self.get_category().path}:detail", kwargs={"pk": self.object.id} ) def get_category(self): if self.category: return self.category if self.model and self.model.category: return self.model.category raise NotImplementedError class EditInterestView(Ed...
64
64
14
8
55
mincem/media_list
src/media_list/views/base_views.py
Python
EditInterestView
EditInterestView
94
95
94
94
ee62170f5932d725153d0bfda6b72d07a129594f
bigcode/the-stack
train
05103a19cb0d6900efe317f0
train
class
class FetchExternalIDView(DetailView): def get(self, request, *args, **kwargs): item = self.get_object() item.external_id = ExternalIDFinder.for_item(item).get_id() item.save() return super().get(self, request, *args, **kwargs)
class FetchExternalIDView(DetailView):
def get(self, request, *args, **kwargs): item = self.get_object() item.external_id = ExternalIDFinder.for_item(item).get_id() item.save() return super().get(self, request, *args, **kwargs)
_template_names(self): return [f"media_list/categories/{self.model.category.path}/grid.html"] class DetailView(generic.DetailView): def get_template_names(self): return [f"media_list/categories/{self.model.category.path}/detail.html"] class FetchExternalIDView(DetailView):
63
64
63
9
54
mincem/media_list
src/media_list/views/base_views.py
Python
FetchExternalIDView
FetchExternalIDView
43
48
43
43
32f93f76f5c4b9e534c8bef5fce6f20e67bf3b5c
bigcode/the-stack
train