_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17100 | create_hls_profile | train | def create_hls_profile(apps, schema_editor):
""" Create hls profile """
Profile = apps.get_model("edxval", "Profile")
Profile.objects.get_or_create(profile_name=HLS_PROFILE) | python | {
"resource": ""
} |
q17101 | delete_hls_profile | train | def delete_hls_profile(apps, schema_editor):
""" Delete hls profile """
Profile = apps.get_model("edxval", "Profile")
Profile.objects.filter(profile_name=HLS_PROFILE).delete() | python | {
"resource": ""
} |
q17102 | create_default_profiles | train | def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile = apps.get_model("edxval", "Profile")
for profile in DEFAULT_PROFILES:
Profile.objects.get_or_create(profile_name=profile) | python | {
"resource": ""
} |
q17103 | delete_default_profiles | train | def delete_default_profiles(apps, schema_editor):
""" Remove default profiles """
Profile = apps.get_model("edxval", "Profile")
Profile.objects.filter(profile_name__in=DEFAULT_PROFILES).delete() | python | {
"resource": ""
} |
q17104 | TranscriptSerializer.validate | train | def validate(self, data):
"""
Validates the transcript data.
"""
video_id = self.context.get('video_id')
video = Video.get_or_none(edx_video_id=video_id)
if not video:
raise serializers.ValidationError('Video "{video_id}" is not valid.'.format(video_id=video_i... | python | {
"resource": ""
} |
q17105 | CourseSerializer.to_internal_value | train | def to_internal_value(self, data):
"""
Convert data into CourseVideo instance and image filename tuple.
"""
course_id = data
course_video = image = ''
if data:
if isinstance(data, dict):
(course_id, image), = list(data.items())
cou... | python | {
"resource": ""
} |
q17106 | VideoSerializer.validate | train | def validate(self, data):
"""
Check that the video data is valid.
"""
if data is not None and not isinstance(data, dict):
raise serializers.ValidationError("Invalid data")
try:
profiles = [ev["profile"] for ev in data.get("encoded_videos", [])]
... | python | {
"resource": ""
} |
q17107 | VideoSerializer.create | train | def create(self, validated_data):
"""
Create the video and its nested resources.
"""
courses = validated_data.pop("courses", [])
encoded_videos = validated_data.pop("encoded_videos", [])
video = Video.objects.create(**validated_data)
EncodedVideo.objects.bulk_cr... | python | {
"resource": ""
} |
q17108 | VideoSerializer.update | train | def update(self, instance, validated_data):
"""
Update an existing video resource.
"""
instance.status = validated_data["status"]
instance.client_video_id = validated_data["client_video_id"]
instance.duration = validated_data["duration"]
instance.save()
#... | python | {
"resource": ""
} |
q17109 | get_video_image_storage | train | def get_video_image_storage():
"""
Return the configured django storage backend.
"""
if hasattr(settings, 'VIDEO_IMAGE_SETTINGS'):
return get_storage_class(
settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_CLASS'),
)(**settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_KWARGS', {}))
el... | python | {
"resource": ""
} |
q17110 | get_video_transcript_storage | train | def get_video_transcript_storage():
"""
Return the configured django storage backend for video transcripts.
"""
if hasattr(settings, 'VIDEO_TRANSCRIPTS_SETTINGS'):
return get_storage_class(
settings.VIDEO_TRANSCRIPTS_SETTINGS.get('STORAGE_CLASS'),
)(**settings.VIDEO_TRANSCRIP... | python | {
"resource": ""
} |
q17111 | create_file_in_fs | train | def create_file_in_fs(file_data, file_name, file_system, static_dir):
"""
Writes file in specific file system.
Arguments:
file_data (str): Data to store into the file.
file_name (str): File name of the file to be created.
file_system (OSFS): Import file system.
static_dir (s... | python | {
"resource": ""
} |
q17112 | get_transcript_format | train | def get_transcript_format(transcript_content):
"""
Returns transcript format.
Arguments:
transcript_content (str): Transcript file content.
"""
try:
sjson_obj = json.loads(transcript_content)
except ValueError:
# With error handling (set to 'ERROR_RAISE'), we will be get... | python | {
"resource": ""
} |
q17113 | MultipleFieldLookupMixin.get_object | train | def get_object(self):
"""
Returns an object instance that should be used for detail views.
"""
queryset = self.get_queryset() # Get the base queryset
queryset = self.filter_queryset(queryset) # Apply any filter backends
filter = {} # pylint: disable=W0622
... | python | {
"resource": ""
} |
q17114 | VideoTranscriptView.post | train | def post(self, request):
"""
Creates a video transcript instance with the given information.
Arguments:
request: A WSGI request.
"""
attrs = ('video_id', 'name', 'language_code', 'provider', 'file_format')
missing = [attr for attr in attrs if attr not in requ... | python | {
"resource": ""
} |
q17115 | VideoStatusView.patch | train | def patch(self, request):
"""
Update the status of a video.
"""
attrs = ('edx_video_id', 'status')
missing = [attr for attr in attrs if attr not in request.data]
if missing:
return Response(
status=status.HTTP_400_BAD_REQUEST,
d... | python | {
"resource": ""
} |
q17116 | VideoImagesView.post | train | def post(self, request):
"""
Update a course video image instance with auto generated image names.
"""
attrs = ('course_id', 'edx_video_id', 'generated_images')
missing = [attr for attr in attrs if attr not in request.data]
if missing:
return Response(
... | python | {
"resource": ""
} |
q17117 | HLSMissingVideoView.put | train | def put(self, request):
"""
Update a single profile for a given video.
Example request data:
{
'edx_video_id': '1234'
'profile': 'hls',
'encode_data': {
'url': 'foo.com/qwe.m3u8'
'file_size': 34
... | python | {
"resource": ""
} |
q17118 | video_status_update_callback | train | def video_status_update_callback(sender, **kwargs): # pylint: disable=unused-argument
"""
Log video status for an existing video instance
"""
video = kwargs['instance']
if kwargs['created']:
logger.info('VAL: Video created with id [%s] and status [%s]', video.edx_video_id, video.status)
... | python | {
"resource": ""
} |
q17119 | ModelFactoryWithValidation.create_with_validation | train | def create_with_validation(cls, *args, **kwargs):
"""
Factory method that creates and validates the model object before it is saved.
"""
ret_val = cls(*args, **kwargs)
ret_val.full_clean()
ret_val.save()
return ret_val | python | {
"resource": ""
} |
q17120 | Video.get_or_none | train | def get_or_none(cls, **filter_kwargs):
"""
Returns a video or None.
"""
try:
video = cls.objects.get(**filter_kwargs)
except cls.DoesNotExist:
video = None
return video | python | {
"resource": ""
} |
q17121 | Video.by_youtube_id | train | def by_youtube_id(cls, youtube_id):
"""
Look up video by youtube id
"""
qset = cls.objects.filter(
encoded_videos__profile__profile_name='youtube',
encoded_videos__url=youtube_id
).prefetch_related('encoded_videos', 'courses')
return qset | python | {
"resource": ""
} |
q17122 | ListField.get_prep_value | train | def get_prep_value(self, value):
"""
Converts a list to its json representation to store in database as text.
"""
if value and not isinstance(value, list):
raise ValidationError(u'ListField value {} is not a list.'.format(value))
return json.dumps(self.validate_list(v... | python | {
"resource": ""
} |
q17123 | ListField.to_python | train | def to_python(self, value):
"""
Converts the value into a list.
"""
if not value:
value = []
# If a list is set then validated its items
if isinstance(value, list):
py_list = self.validate_list(value)
else: # try to de-serialize value and... | python | {
"resource": ""
} |
q17124 | ListField.validate_list | train | def validate_list(self, value):
"""
Validate data before saving to database.
Arguemtns:
value(list): list to be validated
Returns:
list if validation is successful
Raises:
ValidationError
"""
if len(value) > self.max_items:
... | python | {
"resource": ""
} |
q17125 | VideoImage.create_or_update | train | def create_or_update(cls, course_video, file_name=None, image_data=None, generated_images=None):
"""
Create a VideoImage object for a CourseVideo.
NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise
a new file name is constructed based on uuid and exten... | python | {
"resource": ""
} |
q17126 | VideoTranscript.filename | train | def filename(self):
"""
Returns readable filename for a transcript
"""
client_id, __ = os.path.splitext(self.video.client_video_id)
file_name = u'{name}-{language}.{format}'.format(
name=client_id,
language=self.language_code,
format=self.file_... | python | {
"resource": ""
} |
q17127 | VideoTranscript.get_or_none | train | def get_or_none(cls, video_id, language_code):
"""
Returns a data model object if found or none otherwise.
Arguments:
video_id(unicode): video id to which transcript may be associated
language_code(unicode): language of the requested transcript
"""
try:
... | python | {
"resource": ""
} |
q17128 | VideoTranscript.create | train | def create(cls, video, language_code, file_format, content, provider):
"""
Create a Video Transcript.
Arguments:
video(Video): Video data model object
language_code(unicode): A language code.
file_format(unicode): Transcript file format.
content(I... | python | {
"resource": ""
} |
q17129 | VideoTranscript.create_or_update | train | def create_or_update(cls, video, language_code, metadata, file_data=None):
"""
Create or update Transcript object.
Arguments:
video (Video): Video for which transcript is going to be saved.
language_code (str): language code for (to be created/updated) transcript
... | python | {
"resource": ""
} |
q17130 | ThirdPartyTranscriptCredentialsState.update_or_create | train | def update_or_create(cls, org, provider, exists):
"""
Update or create credentials state.
"""
instance, created = cls.objects.update_or_create(
org=org,
provider=provider,
defaults={'exists': exists},
)
return instance, created | python | {
"resource": ""
} |
q17131 | create_video | train | def create_video(video_data):
"""
Called on to create Video objects in the database
create_video is used to create Video objects whose children are EncodedVideo
objects which are linked to Profile objects. This is an alternative to the HTTP
requests so it can be used internally. The VideoSerializer... | python | {
"resource": ""
} |
q17132 | update_video | train | def update_video(video_data):
"""
Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the vi... | python | {
"resource": ""
} |
q17133 | update_video_status | train | def update_video_status(edx_video_id, status):
"""
Update status for an existing video.
Args:
edx_video_id: ID of the video
status: video status
Raises:
Raises ValVideoNotFoundError if the video cannot be retrieved.
"""
try:
video = _get_video(edx_video_id)
... | python | {
"resource": ""
} |
q17134 | get_transcript_credentials_state_for_org | train | def get_transcript_credentials_state_for_org(org, provider=None):
"""
Returns transcript credentials state for an org
Arguments:
org (unicode): course organization
provider (unicode): transcript provider
Returns:
dict: provider name and their credential existance map
{... | python | {
"resource": ""
} |
q17135 | is_transcript_available | train | def is_transcript_available(video_id, language_code=None):
"""
Returns whether the transcripts are available for a video.
Arguments:
video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.
language_code: it will the language code of the re... | python | {
"resource": ""
} |
q17136 | get_video_transcript | train | def get_video_transcript(video_id, language_code):
"""
Get video transcript info
Arguments:
video_id(unicode): A video id, it can be an edx_video_id or an external video id extracted from
external sources of a video component.
language_code(unicode): it will be the language code of ... | python | {
"resource": ""
} |
q17137 | get_video_transcript_data | train | def get_video_transcript_data(video_id, language_code):
"""
Get video transcript data
Arguments:
video_id(unicode): An id identifying the Video.
language_code(unicode): it will be the language code of the requested transcript.
Returns:
A dict containing transcript file name and... | python | {
"resource": ""
} |
q17138 | get_available_transcript_languages | train | def get_available_transcript_languages(video_id):
"""
Get available transcript languages
Arguments:
video_id(unicode): An id identifying the Video.
Returns:
A list containing transcript language codes for the Video.
"""
available_languages = VideoTranscript.objects.filter(
... | python | {
"resource": ""
} |
q17139 | get_video_transcript_url | train | def get_video_transcript_url(video_id, language_code):
"""
Returns course video transcript url or None if no transcript
Arguments:
video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.
language_code: language code of a video transcript
... | python | {
"resource": ""
} |
q17140 | create_video_transcript | train | def create_video_transcript(video_id, language_code, file_format, content, provider=TranscriptProviderType.CUSTOM):
"""
Create a video transcript.
Arguments:
video_id(unicode): An Id identifying the Video data model object.
language_code(unicode): A language code.
file_format(unicod... | python | {
"resource": ""
} |
q17141 | create_or_update_video_transcript | train | def create_or_update_video_transcript(video_id, language_code, metadata, file_data=None):
"""
Create or Update video transcript for an existing video.
Arguments:
video_id: it can be an edx_video_id or an external_id extracted from external sources in a video component.
language_code: langua... | python | {
"resource": ""
} |
q17142 | delete_video_transcript | train | def delete_video_transcript(video_id, language_code):
"""
Delete transcript for an existing video.
Arguments:
video_id: id identifying the video to which the transcript is associated.
language_code: language code of a video transcript.
"""
video_transcript = VideoTranscript.get_or_n... | python | {
"resource": ""
} |
q17143 | get_transcript_preferences | train | def get_transcript_preferences(course_id):
"""
Retrieves course wide transcript preferences
Arguments:
course_id (str): course id
"""
try:
transcript_preference = TranscriptPreference.objects.get(course_id=course_id)
except TranscriptPreference.DoesNotExist:
return
... | python | {
"resource": ""
} |
q17144 | create_or_update_transcript_preferences | train | def create_or_update_transcript_preferences(course_id, **preferences):
"""
Creates or updates course-wide transcript preferences
Arguments:
course_id(str): course id
Keyword Arguments:
preferences(dict): keyword arguments
"""
transcript_preference, __ = TranscriptPreference.obj... | python | {
"resource": ""
} |
q17145 | remove_transcript_preferences | train | def remove_transcript_preferences(course_id):
"""
Deletes course-wide transcript preferences.
Arguments:
course_id(str): course id
"""
try:
transcript_preference = TranscriptPreference.objects.get(course_id=course_id)
transcript_preference.delete()
except TranscriptPrefe... | python | {
"resource": ""
} |
q17146 | get_course_video_image_url | train | def get_course_video_image_url(course_id, edx_video_id):
"""
Returns course video image url or None if no image found
"""
try:
video_image = CourseVideo.objects.select_related('video_image').get(
course_id=course_id, video__edx_video_id=edx_video_id
).video_image
retu... | python | {
"resource": ""
} |
q17147 | update_video_image | train | def update_video_image(edx_video_id, course_id, image_data, file_name):
"""
Update video image for an existing video.
NOTE: If `image_data` is None then `file_name` value will be used as it is, otherwise
a new file name is constructed based on uuid and extension from `file_name` value.
`image_data`... | python | {
"resource": ""
} |
q17148 | create_profile | train | def create_profile(profile_name):
"""
Used to create Profile objects in the database
A profile needs to exists before an EncodedVideo object can be created.
Args:
profile_name (str): ID of the profile
Raises:
ValCannotCreateError: Raised if the profile name is invalid or exists
... | python | {
"resource": ""
} |
q17149 | _get_video | train | def _get_video(edx_video_id):
"""
Get a Video instance, prefetching encoded video and course information.
Raises ValVideoNotFoundError if the video cannot be retrieved.
"""
try:
return Video.objects.prefetch_related("encoded_videos", "courses").get(edx_video_id=edx_video_id)
except Vide... | python | {
"resource": ""
} |
q17150 | get_urls_for_profiles | train | def get_urls_for_profiles(edx_video_id, profiles):
"""
Returns a dict mapping profiles to URLs.
If the profiles or video is not found, urls will be blank.
Args:
edx_video_id (str): id of the video
profiles (list): list of profiles we want to search for
Returns:
(dict): A d... | python | {
"resource": ""
} |
q17151 | _get_videos_for_filter | train | def _get_videos_for_filter(video_filter, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None):
"""
Returns a generator expression that contains the videos found, sorted by
the given field and direction, with ties broken by edx_video_id to ensure a
total order.
"""
videos = Video.ob... | python | {
"resource": ""
} |
q17152 | get_course_video_ids_with_youtube_profile | train | def get_course_video_ids_with_youtube_profile(course_ids=None, offset=None, limit=None):
"""
Returns a list that contains all the course ids and video ids with the youtube profile
Args:
course_ids (list): valid course ids
limit (int): batch records limit
offset (int): an offset f... | python | {
"resource": ""
} |
q17153 | get_videos_for_course | train | def get_videos_for_course(course_id, sort_field=None, sort_dir=SortDirection.asc, pagination_conf=None):
"""
Returns an iterator of videos for the given course id.
Args:
course_id (String)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A generator express... | python | {
"resource": ""
} |
q17154 | remove_video_for_course | train | def remove_video_for_course(course_id, edx_video_id):
"""
Soft deletes video for particular course.
Arguments:
course_id (str): id of the course
edx_video_id (str): id of the video to be hidden
"""
course_video = CourseVideo.objects.get(course_id=course_id, video__edx_video_id=edx_v... | python | {
"resource": ""
} |
q17155 | get_videos_for_ids | train | def get_videos_for_ids(
edx_video_ids,
sort_field=None,
sort_dir=SortDirection.asc
):
"""
Returns an iterator of videos that match the given list of ids.
Args:
edx_video_ids (list)
sort_field (VideoSortField)
sort_dir (SortDirection)
Returns:
A g... | python | {
"resource": ""
} |
q17156 | get_video_info_for_course_and_profiles | train | def get_video_info_for_course_and_profiles(course_id, profiles):
"""
Returns a dict of edx_video_ids with a dict of requested profiles.
Args:
course_id (str): id of the course
profiles (list): list of profile_names
Returns:
(dict): Returns all the profiles attached to a specific... | python | {
"resource": ""
} |
q17157 | copy_course_videos | train | def copy_course_videos(source_course_id, destination_course_id):
"""
Adds the destination_course_id to the videos taken from the source_course_id
Args:
source_course_id: The original course_id
destination_course_id: The new course_id where the videos will be copied
"""
if source_cou... | python | {
"resource": ""
} |
q17158 | export_to_xml | train | def export_to_xml(video_id, resource_fs, static_dir, course_id=None):
"""
Exports data for a video into an xml object.
NOTE: For external video ids, only transcripts information will be added into xml.
If external=False, then edx_video_id is going to be on first index of the list.
Arguments:... | python | {
"resource": ""
} |
q17159 | create_transcript_file | train | def create_transcript_file(video_id, language_code, file_format, resource_fs, static_dir):
"""
Writes transcript file to file system.
Arguments:
video_id (str): Video id of the video transcript file is attached.
language_code (str): Language code of the transcript.
file_format (str)... | python | {
"resource": ""
} |
q17160 | create_transcripts_xml | train | def create_transcripts_xml(video_id, video_el, resource_fs, static_dir):
"""
Creates xml for transcripts.
For each transcript element, an associated transcript file is also created in course OLX.
Arguments:
video_id (str): Video id of the video.
video_el (Element): lxml Element object
... | python | {
"resource": ""
} |
q17161 | import_from_xml | train | def import_from_xml(xml, edx_video_id, resource_fs, static_dir, external_transcripts=dict(), course_id=None):
"""
Imports data from a video_asset element about the given video_id.
If the edx_video_id already exists, then no changes are made. If an unknown
profile is referenced by an encoded video, that... | python | {
"resource": ""
} |
q17162 | import_transcript_from_fs | train | def import_transcript_from_fs(edx_video_id, language_code, file_name, provider, resource_fs, static_dir):
"""
Imports transcript file from file system and creates transcript record in DS.
Arguments:
edx_video_id (str): Video id of the video.
language_code (unicode): Language code of the req... | python | {
"resource": ""
} |
q17163 | create_transcript_objects | train | def create_transcript_objects(xml, edx_video_id, resource_fs, static_dir, external_transcripts):
"""
Create VideoTranscript objects.
Arguments:
xml (Element): lxml Element object.
edx_video_id (str): Video id of the video.
resource_fs (OSFS): Import file system.
static_dir (... | python | {
"resource": ""
} |
q17164 | get_cache_stats | train | def get_cache_stats():
"""
Returns a list of dictionaries of all cache servers and their stats,
if they provide stats.
"""
cache_stats = []
for name, _ in six.iteritems(settings.CACHES):
cache_backend = caches[name]
try:
cache_backend_stats = cache_backend._cache.get... | python | {
"resource": ""
} |
q17165 | register_git_injector | train | def register_git_injector(username, password):
"""Generate a script that writes the password to the git command line tool"""
fd, tmp_path = mkstemp()
atexit.register(lambda: os.remove(tmp_path))
with os.fdopen(fd, 'w') as f:
f.write(ASKPASS.format(username=username, password=password or ''))
... | python | {
"resource": ""
} |
q17166 | to_snake | train | def to_snake(camel):
"""TimeSkill -> time_skill"""
if not camel:
return camel
return ''.join('_' + x if 'A' <= x <= 'Z' else x for x in camel).lower()[camel[0].isupper():] | python | {
"resource": ""
} |
q17167 | serialized | train | def serialized(func):
"""Write a serializer by yielding each line of output"""
@wraps(func)
def wrapper(*args, **kwargs):
return '\n'.join(
' '.join(parts) if isinstance(parts, tuple) else parts
for parts in func(*args, **kwargs)
)
return wrapper | python | {
"resource": ""
} |
q17168 | UpgradeAction.create_pr_message | train | def create_pr_message(self, skill_git: Git, skill_repo: Repository) -> tuple:
"""Reads git commits from skill repo to create a list of changes as the PR content"""
title = 'Upgrade ' + self.skill.name
body = body_template.format(
skill_name=self.skill.name,
commits='\n'.j... | python | {
"resource": ""
} |
q17169 | ship_move | train | def ship_move(ship, x, y, speed):
"""Moves SHIP to the new location X,Y."""
click.echo('Moving ship %s to %s,%s with speed %s' % (ship, x, y, speed)) | python | {
"resource": ""
} |
q17170 | _check_status | train | def _check_status(sdp_state):
"""SDP Status check.
Do all the tests to determine, if the SDP state is
"broken", what could be the cause, and return a
suitable status message to be sent back by the calling
function.
"""
try:
errval = "error"
errdict = dict(state="unknown", re... | python | {
"resource": ""
} |
q17171 | health | train | def health():
"""Check the health of this service."""
up_time = time.time() - START_TIME
response = dict(service=__service_id__,
uptime='{:.2f}s'.format(up_time))
return response, HTTPStatus.OK | python | {
"resource": ""
} |
q17172 | allowed_transitions | train | def allowed_transitions():
"""Get target states allowed for the current state."""
try:
sdp_state = SDPState()
return sdp_state.allowed_target_states[sdp_state.current_state]
except KeyError:
LOG.error("Key Error")
return dict(state="KeyError", reason="KeyError") | python | {
"resource": ""
} |
q17173 | get_state | train | def get_state():
"""SDP State.
Return current state; target state and allowed
target states.
"""
sdp_state = SDPState()
errval, errdict = _check_status(sdp_state)
if errval == "error":
LOG.debug(errdict['reason'])
return dict(
current_state="unknown",
... | python | {
"resource": ""
} |
q17174 | get_current_state | train | def get_current_state():
"""Return the SDP State and the timestamp for when it was updated."""
sdp_state = SDPState()
errval, errdict = _check_status(sdp_state)
if errval == "error":
LOG.debug(errdict['reason'])
return dict(
current_state="unknown",
last_updated="... | python | {
"resource": ""
} |
q17175 | processing_block_list | train | def processing_block_list():
"""Return the list of processing blocks known to SDP."""
pb_list = ProcessingBlockList()
return dict(active=pb_list.active,
completed=pb_list.completed,
aborted=pb_list.aborted) | python | {
"resource": ""
} |
q17176 | scheduling_blocks | train | def scheduling_blocks():
"""Return list of Scheduling Block instances known to SDP."""
sbi_list = SchedulingBlockInstanceList()
return dict(active=sbi_list.active,
completed=sbi_list.completed,
aborted=sbi_list.aborted) | python | {
"resource": ""
} |
q17177 | configure_sbi | train | def configure_sbi():
"""Configure an SBI using POSTed configuration."""
# Need an ID for the subarray - guessing I just get
# the list of inactive subarrays and use the first
inactive_list = SubarrayList().inactive
request_data = request.data
LOG.debug('request is of type %s', type(request_data)... | python | {
"resource": ""
} |
q17178 | home | train | def home():
"""Temporary helper function to link to the API routes"""
return dict(links=dict(api='{}{}'.format(request.url, PREFIX[1:]))), \
HTTPStatus.OK | python | {
"resource": ""
} |
q17179 | catch_all | train | def catch_all(path):
"""Catch all path - return a JSON 404 """
return (dict(error='Invalid URL: /{}'.format(path),
links=dict(root='{}{}'.format(request.url_root, PREFIX[1:]))),
HTTPStatus.NOT_FOUND) | python | {
"resource": ""
} |
q17180 | SubarrayList.get_active | train | def get_active() -> List[str]:
"""Return the list of active subarrays."""
active = []
for i in range(__num_subarrays__):
key = Subarray.get_key(i)
if DB.get_hash_value(key, 'active').upper() == 'TRUE':
active.append(Subarray.get_id(i))
return activ... | python | {
"resource": ""
} |
q17181 | SubarrayList.get_inactive | train | def get_inactive() -> List[str]:
"""Return the list of inactive subarrays."""
inactive = []
for i in range(__num_subarrays__):
key = Subarray.get_key(i)
if DB.get_hash_value(key, 'active').upper() == 'FALSE':
inactive.append(Subarray.get_id(i))
ret... | python | {
"resource": ""
} |
q17182 | node_run | train | def node_run(input_file, coords_only, bc_settings, bc_grid_weights):
"""Main function to process visibility data on Spark cluster nodes.
Args:
input_file (str):
RDD element containing filename to process.
coords_only (boolean):
If true, read only baseline coordinates to ... | python | {
"resource": ""
} |
q17183 | save_image | train | def save_image(imager, grid_data, grid_norm, output_file):
"""Makes an image from gridded visibilities and saves it to a FITS file.
Args:
imager (oskar.Imager): Handle to configured imager.
grid_data (numpy.ndarray): Final visibility grid.
grid_norm (float): G... | python | {
"resource": ""
} |
q17184 | reduce_sequences | train | def reduce_sequences(object_a, object_b):
"""Performs an element-wise addition of sequences into a new list.
Both sequences must have the same length, and the addition operator must be
defined for each element of the sequence.
"""
def is_seq(obj):
"""Returns true if the object passed is a s... | python | {
"resource": ""
} |
q17185 | main | train | def main():
"""Runs test imaging pipeline using Spark."""
# Check command line arguments.
if len(sys.argv) < 3:
raise RuntimeError(
'Usage: spark-submit spark_imager_test.py <settings_file> <dir> '
'[partitions]')
# Create log object.
log = logging.getLogger('pyspark... | python | {
"resource": ""
} |
q17186 | load_schema | train | def load_schema(path):
"""Loads a JSON schema file."""
with open(path) as json_data:
schema = json.load(json_data)
return schema | python | {
"resource": ""
} |
q17187 | clear_db | train | def clear_db():
"""Clear the entire db."""
cursor = '0'
while cursor != 0:
cursor, keys = DB.scan(cursor, match='*', count=5000)
if keys:
DB.delete(*keys) | python | {
"resource": ""
} |
q17188 | get_scheduling_block_ids | train | def get_scheduling_block_ids():
"""Return list of scheduling block IDs"""
ids = [key.split('/')[-1]
for key in DB.keys(pattern='scheduling_block/*')]
return sorted(ids) | python | {
"resource": ""
} |
q17189 | add_scheduling_block | train | def add_scheduling_block(config, schema_path=None):
"""Add a Scheduling Block to the Configuration Database.
The configuration dictionary must match the schema defined in
in the schema_path variable at the top of the function.
Args:
config (dict): Scheduling Block instance request configuratio... | python | {
"resource": ""
} |
q17190 | delete_scheduling_block | train | def delete_scheduling_block(block_id):
"""Delete Scheduling Block with the specified ID"""
DB.delete('scheduling_block/{}'.format(block_id))
# Add a event to the scheduling block event list to notify
# of a deleting a scheduling block from the db
DB.rpush('scheduling_block_events',
jso... | python | {
"resource": ""
} |
q17191 | get_scheduling_block_event | train | def get_scheduling_block_event():
"""Return the latest Scheduling Block event"""
event = DB.rpoplpush('scheduling_block_events',
'scheduling_block_event_history')
if event:
event = json.loads(event.decode('utf-8'))
return event | python | {
"resource": ""
} |
q17192 | get_sub_array_ids | train | def get_sub_array_ids():
"""Return list of sub-array Id's currently known to SDP"""
ids = set()
for key in sorted(DB.keys(pattern='scheduling_block/*')):
config = json.loads(DB.get(key))
ids.add(config['sub_array_id'])
return sorted(list(ids)) | python | {
"resource": ""
} |
q17193 | get_subarray_sbi_ids | train | def get_subarray_sbi_ids(sub_array_id):
"""Return list of scheduling block Id's associated with the given
sub_array_id
"""
ids = []
for key in sorted(DB.keys(pattern='scheduling_block/*')):
config = json.loads(DB.get(key))
if config['sub_array_id'] == sub_array_id:
ids.ap... | python | {
"resource": ""
} |
q17194 | get_processing_block_ids | train | def get_processing_block_ids():
"""Return an array of Processing Block ids"""
ids = []
for key in sorted(DB.keys(pattern='scheduling_block/*')):
config = json.loads(DB.get(key))
for processing_block in config['processing_blocks']:
ids.append(processing_block['id'])
return ids | python | {
"resource": ""
} |
q17195 | get_processing_block | train | def get_processing_block(block_id):
"""Return the Processing Block Configuration for the specified ID"""
identifiers = block_id.split(':')
scheduling_block_id = identifiers[0]
scheduling_block_config = get_scheduling_block(scheduling_block_id)
for processing_block in scheduling_block_config['process... | python | {
"resource": ""
} |
q17196 | delete_processing_block | train | def delete_processing_block(processing_block_id):
"""Delete Processing Block with the specified ID"""
scheduling_block_id = processing_block_id.split(':')[0]
config = get_scheduling_block(scheduling_block_id)
processing_blocks = config.get('processing_blocks')
processing_block = list(filter(
... | python | {
"resource": ""
} |
q17197 | get_processing_block_event | train | def get_processing_block_event():
"""Return the latest Processing Block event"""
event = DB.rpoplpush('processing_block_events',
'processing_block_event_history')
if event:
event = json.loads(event.decode('utf-8'))
return event | python | {
"resource": ""
} |
q17198 | subscribe | train | def subscribe(object_type: str, subscriber: str,
callback_handler: Callable = None) -> EventQueue:
"""Subscribe to the specified object type.
Returns an EventQueue object which can be used to query events
associated with the object type for this subscriber.
Args:
object_type (str... | python | {
"resource": ""
} |
q17199 | get_subscribers | train | def get_subscribers(object_type: str) -> List[str]:
"""Get the list of subscribers to events of the object type.
Args:
object_type (str): Type of object.
Returns:
List[str], list of subscriber names.
"""
return DB.get_list(_keys.subscribers(object_type)) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.