body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
0358c85d0133ab323f97e8db868c0edffb3a60cebe6dd4cf5e00c628cb22d7a2
def _save_current_fixed_range_indices(testcase_id, fixed_range_start, fixed_range_end): 'Save current fixed range indices in case we die in middle of task.' testcase = data_handler.get_testcase_by_id(testcase_id) testcase.set_metadata('last_progression_min', fixed_range_start, update_testcase=False) testcase.set_metadata('last_progression_max', fixed_range_end, update_testcase=False) testcase.put()
Save current fixed range indices in case we die in middle of task.
src/python/bot/tasks/progression_task.py
_save_current_fixed_range_indices
eepeep/clusterfuzz
3
python
def _save_current_fixed_range_indices(testcase_id, fixed_range_start, fixed_range_end): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.set_metadata('last_progression_min', fixed_range_start, update_testcase=False) testcase.set_metadata('last_progression_max', fixed_range_end, update_testcase=False) testcase.put()
def _save_current_fixed_range_indices(testcase_id, fixed_range_start, fixed_range_end): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.set_metadata('last_progression_min', fixed_range_start, update_testcase=False) testcase.set_metadata('last_progression_max', fixed_range_end, update_testcase=False) testcase.put()<|docstring|>Save current fixed range indices in case we die in middle of task.<|endoftext|>
2ce87267eb0fa4ab726ff5ae1b8ce699c0ba3db1857d0de47353d34bee28a5c9
def _save_fixed_range(testcase_id, min_revision, max_revision): 'Update a test case and other metadata with a fixed range.' testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = ('%d:%d' % (min_revision, max_revision)) testcase.open = False _update_completion_metadata(testcase, max_revision, message=('fixed in range r%s' % testcase.fixed)) _write_to_bigquery(testcase, min_revision, max_revision)
Update a test case and other metadata with a fixed range.
src/python/bot/tasks/progression_task.py
_save_fixed_range
eepeep/clusterfuzz
3
python
def _save_fixed_range(testcase_id, min_revision, max_revision): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = ('%d:%d' % (min_revision, max_revision)) testcase.open = False _update_completion_metadata(testcase, max_revision, message=('fixed in range r%s' % testcase.fixed)) _write_to_bigquery(testcase, min_revision, max_revision)
def _save_fixed_range(testcase_id, min_revision, max_revision): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = ('%d:%d' % (min_revision, max_revision)) testcase.open = False _update_completion_metadata(testcase, max_revision, message=('fixed in range r%s' % testcase.fixed)) _write_to_bigquery(testcase, min_revision, max_revision)<|docstring|>Update a test case and other metadata with a fixed range.<|endoftext|>
dd6e27bed061df06d14f6172a875bfa593e8a77fff37cd5c4b4f3b34a7976040
def find_fixed_range(testcase_id, job_type): 'Attempt to find the revision range where a testcase was fixed.' deadline = tasks.get_task_completion_deadline() testcase = data_handler.get_testcase_by_id(testcase_id) if (not testcase): return if testcase.fixed: logs.log_error(('Fixed range is already set as %s, skip.' % testcase.fixed)) return (file_list, _, testcase_file_path) = setup.setup_testcase(testcase, job_type) if (not file_list): return testcase.set_metadata('progression_pending', True) if build_manager.is_custom_binary(): _check_fixed_for_custom_binary(testcase, job_type, testcase_file_path) return build_bucket_path = build_manager.get_primary_bucket_path() revision_list = build_manager.get_revisions_list(build_bucket_path, testcase=testcase) if (not revision_list): testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Failed to fetch revision list') tasks.add_task('progression', testcase_id, job_type) return min_revision = testcase.get_metadata('last_progression_min') max_revision = testcase.get_metadata('last_progression_max') last_tested_revision = testcase.get_metadata('last_tested_crash_revision') known_crash_revision = (last_tested_revision or testcase.crash_revision) if (not min_revision): min_revision = known_crash_revision if (not max_revision): max_revision = revisions.get_last_revision_in_list(revision_list) min_index = revisions.find_min_revision_index(revision_list, min_revision) if (min_index is None): raise errors.BuildNotFoundError(min_revision, job_type) max_index = revisions.find_max_revision_index(revision_list, max_revision) if (max_index is None): raise errors.BuildNotFoundError(max_revision, job_type) testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED, ('r%d' % max_revision)) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, max_revision, update_metadata=True) if result.is_crash(): logs.log(('Found crash with same signature on latest revision r%d.' % max_revision)) app_path = environment.get_value('APP_PATH') command = testcase_manager.get_command_line_for_application(testcase_file_path, app_path=app_path, needs_http=testcase.http_flag) symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True) unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False) stacktrace = utils.get_crash_stacktrace_output(command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace) testcase = data_handler.get_testcase_by_id(testcase_id) testcase.last_tested_crash_stacktrace = data_handler.filter_stacktrace(stacktrace) _update_completion_metadata(testcase, max_revision, is_crash=True, message=('still crashes on latest revision r%s' % max_revision)) task_creation.mark_unreproducible_if_flaky(testcase, False) state = result.get_symbolized_data() crash_uploader.save_crash_info_if_needed(testcase_id, max_revision, job_type, state.crash_type, state.crash_address, state.frames) return environment.set_value('CACHE_STORE', False) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, min_revision) if (result and (not result.is_crash())): testcase = data_handler.get_testcase_by_id(testcase_id) if data_handler.is_first_retry_for_task(testcase, reset_after_retry=True): tasks.add_task('progression', testcase_id, job_type) error_message = ('Known crash revision %d did not crash, will retry on another bot to confirm result' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) _update_completion_metadata(testcase, max_revision) return _clear_progression_pending(testcase) error_message = ('Known crash revision %d did not crash' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) task_creation.mark_unreproducible_if_flaky(testcase, True) return while (time.time() < deadline): min_revision = revision_list[min_index] max_revision = revision_list[max_index] if ((max_index - min_index) == 1): _save_fixed_range(testcase_id, min_revision, max_revision) return elif ((max_index - min_index) < 1): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = 'NA' testcase.open = False message = ('Fixed testing errored out (min and max revisions are both %d)' % min_revision) _update_completion_metadata(testcase, max_revision, message=message) return middle_index = ((min_index + max_index) // 2) middle_revision = revision_list[middle_index] testcase = data_handler.get_testcase_by_id(testcase_id) log_message = ('Testing r%d (current range %d:%d)' % (middle_revision, min_revision, max_revision)) data_handler.update_testcase_comment(testcase, data_types.TaskState.WIP, log_message) try: result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, middle_revision) except errors.BadBuildError: del revision_list[middle_index] max_index -= 1 continue if result.is_crash(): min_index = middle_index else: max_index = middle_index _save_current_fixed_range_indices(testcase_id, revision_list[min_index], revision_list[max_index]) testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Timed out, current range r%d:r%d' % (revision_list[min_index], revision_list[max_index])) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) tasks.add_task('progression', testcase_id, job_type)
Attempt to find the revision range where a testcase was fixed.
src/python/bot/tasks/progression_task.py
find_fixed_range
eepeep/clusterfuzz
3
python
def find_fixed_range(testcase_id, job_type): deadline = tasks.get_task_completion_deadline() testcase = data_handler.get_testcase_by_id(testcase_id) if (not testcase): return if testcase.fixed: logs.log_error(('Fixed range is already set as %s, skip.' % testcase.fixed)) return (file_list, _, testcase_file_path) = setup.setup_testcase(testcase, job_type) if (not file_list): return testcase.set_metadata('progression_pending', True) if build_manager.is_custom_binary(): _check_fixed_for_custom_binary(testcase, job_type, testcase_file_path) return build_bucket_path = build_manager.get_primary_bucket_path() revision_list = build_manager.get_revisions_list(build_bucket_path, testcase=testcase) if (not revision_list): testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Failed to fetch revision list') tasks.add_task('progression', testcase_id, job_type) return min_revision = testcase.get_metadata('last_progression_min') max_revision = testcase.get_metadata('last_progression_max') last_tested_revision = testcase.get_metadata('last_tested_crash_revision') known_crash_revision = (last_tested_revision or testcase.crash_revision) if (not min_revision): min_revision = known_crash_revision if (not max_revision): max_revision = revisions.get_last_revision_in_list(revision_list) min_index = revisions.find_min_revision_index(revision_list, min_revision) if (min_index is None): raise errors.BuildNotFoundError(min_revision, job_type) max_index = revisions.find_max_revision_index(revision_list, max_revision) if (max_index is None): raise errors.BuildNotFoundError(max_revision, job_type) testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED, ('r%d' % max_revision)) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, max_revision, update_metadata=True) if result.is_crash(): logs.log(('Found crash with same signature on latest revision r%d.' % max_revision)) app_path = environment.get_value('APP_PATH') command = testcase_manager.get_command_line_for_application(testcase_file_path, app_path=app_path, needs_http=testcase.http_flag) symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True) unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False) stacktrace = utils.get_crash_stacktrace_output(command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace) testcase = data_handler.get_testcase_by_id(testcase_id) testcase.last_tested_crash_stacktrace = data_handler.filter_stacktrace(stacktrace) _update_completion_metadata(testcase, max_revision, is_crash=True, message=('still crashes on latest revision r%s' % max_revision)) task_creation.mark_unreproducible_if_flaky(testcase, False) state = result.get_symbolized_data() crash_uploader.save_crash_info_if_needed(testcase_id, max_revision, job_type, state.crash_type, state.crash_address, state.frames) return environment.set_value('CACHE_STORE', False) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, min_revision) if (result and (not result.is_crash())): testcase = data_handler.get_testcase_by_id(testcase_id) if data_handler.is_first_retry_for_task(testcase, reset_after_retry=True): tasks.add_task('progression', testcase_id, job_type) error_message = ('Known crash revision %d did not crash, will retry on another bot to confirm result' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) _update_completion_metadata(testcase, max_revision) return _clear_progression_pending(testcase) error_message = ('Known crash revision %d did not crash' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) task_creation.mark_unreproducible_if_flaky(testcase, True) return while (time.time() < deadline): min_revision = revision_list[min_index] max_revision = revision_list[max_index] if ((max_index - min_index) == 1): _save_fixed_range(testcase_id, min_revision, max_revision) return elif ((max_index - min_index) < 1): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = 'NA' testcase.open = False message = ('Fixed testing errored out (min and max revisions are both %d)' % min_revision) _update_completion_metadata(testcase, max_revision, message=message) return middle_index = ((min_index + max_index) // 2) middle_revision = revision_list[middle_index] testcase = data_handler.get_testcase_by_id(testcase_id) log_message = ('Testing r%d (current range %d:%d)' % (middle_revision, min_revision, max_revision)) data_handler.update_testcase_comment(testcase, data_types.TaskState.WIP, log_message) try: result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, middle_revision) except errors.BadBuildError: del revision_list[middle_index] max_index -= 1 continue if result.is_crash(): min_index = middle_index else: max_index = middle_index _save_current_fixed_range_indices(testcase_id, revision_list[min_index], revision_list[max_index]) testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Timed out, current range r%d:r%d' % (revision_list[min_index], revision_list[max_index])) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) tasks.add_task('progression', testcase_id, job_type)
def find_fixed_range(testcase_id, job_type): deadline = tasks.get_task_completion_deadline() testcase = data_handler.get_testcase_by_id(testcase_id) if (not testcase): return if testcase.fixed: logs.log_error(('Fixed range is already set as %s, skip.' % testcase.fixed)) return (file_list, _, testcase_file_path) = setup.setup_testcase(testcase, job_type) if (not file_list): return testcase.set_metadata('progression_pending', True) if build_manager.is_custom_binary(): _check_fixed_for_custom_binary(testcase, job_type, testcase_file_path) return build_bucket_path = build_manager.get_primary_bucket_path() revision_list = build_manager.get_revisions_list(build_bucket_path, testcase=testcase) if (not revision_list): testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, 'Failed to fetch revision list') tasks.add_task('progression', testcase_id, job_type) return min_revision = testcase.get_metadata('last_progression_min') max_revision = testcase.get_metadata('last_progression_max') last_tested_revision = testcase.get_metadata('last_tested_crash_revision') known_crash_revision = (last_tested_revision or testcase.crash_revision) if (not min_revision): min_revision = known_crash_revision if (not max_revision): max_revision = revisions.get_last_revision_in_list(revision_list) min_index = revisions.find_min_revision_index(revision_list, min_revision) if (min_index is None): raise errors.BuildNotFoundError(min_revision, job_type) max_index = revisions.find_max_revision_index(revision_list, max_revision) if (max_index is None): raise errors.BuildNotFoundError(max_revision, job_type) testcase = data_handler.get_testcase_by_id(testcase_id) data_handler.update_testcase_comment(testcase, data_types.TaskState.STARTED, ('r%d' % max_revision)) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, max_revision, update_metadata=True) if result.is_crash(): logs.log(('Found crash with same signature on latest revision r%d.' % max_revision)) app_path = environment.get_value('APP_PATH') command = testcase_manager.get_command_line_for_application(testcase_file_path, app_path=app_path, needs_http=testcase.http_flag) symbolized_crash_stacktrace = result.get_stacktrace(symbolized=True) unsymbolized_crash_stacktrace = result.get_stacktrace(symbolized=False) stacktrace = utils.get_crash_stacktrace_output(command, symbolized_crash_stacktrace, unsymbolized_crash_stacktrace) testcase = data_handler.get_testcase_by_id(testcase_id) testcase.last_tested_crash_stacktrace = data_handler.filter_stacktrace(stacktrace) _update_completion_metadata(testcase, max_revision, is_crash=True, message=('still crashes on latest revision r%s' % max_revision)) task_creation.mark_unreproducible_if_flaky(testcase, False) state = result.get_symbolized_data() crash_uploader.save_crash_info_if_needed(testcase_id, max_revision, job_type, state.crash_type, state.crash_address, state.frames) return environment.set_value('CACHE_STORE', False) result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, min_revision) if (result and (not result.is_crash())): testcase = data_handler.get_testcase_by_id(testcase_id) if data_handler.is_first_retry_for_task(testcase, reset_after_retry=True): tasks.add_task('progression', testcase_id, job_type) error_message = ('Known crash revision %d did not crash, will retry on another bot to confirm result' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) _update_completion_metadata(testcase, max_revision) return _clear_progression_pending(testcase) error_message = ('Known crash revision %d did not crash' % known_crash_revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) task_creation.mark_unreproducible_if_flaky(testcase, True) return while (time.time() < deadline): min_revision = revision_list[min_index] max_revision = revision_list[max_index] if ((max_index - min_index) == 1): _save_fixed_range(testcase_id, min_revision, max_revision) return elif ((max_index - min_index) < 1): testcase = data_handler.get_testcase_by_id(testcase_id) testcase.fixed = 'NA' testcase.open = False message = ('Fixed testing errored out (min and max revisions are both %d)' % min_revision) _update_completion_metadata(testcase, max_revision, message=message) return middle_index = ((min_index + max_index) // 2) middle_revision = revision_list[middle_index] testcase = data_handler.get_testcase_by_id(testcase_id) log_message = ('Testing r%d (current range %d:%d)' % (middle_revision, min_revision, max_revision)) data_handler.update_testcase_comment(testcase, data_types.TaskState.WIP, log_message) try: result = _testcase_reproduces_in_revision(testcase, testcase_file_path, job_type, middle_revision) except errors.BadBuildError: del revision_list[middle_index] max_index -= 1 continue if result.is_crash(): min_index = middle_index else: max_index = middle_index _save_current_fixed_range_indices(testcase_id, revision_list[min_index], revision_list[max_index]) testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Timed out, current range r%d:r%d' % (revision_list[min_index], revision_list[max_index])) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) tasks.add_task('progression', testcase_id, job_type)<|docstring|>Attempt to find the revision range where a testcase was fixed.<|endoftext|>
3e9c56c494db04486839a08912a88f7a4d52db8604f85c4f29044b6f6f6b4620
def execute_task(testcase_id, job_type): 'Execute progression task.' try: find_fixed_range(testcase_id, job_type) except errors.BuildSetupError as error: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Build setup failed r%d' % error.revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) build_fail_wait = environment.get_value('FAIL_WAIT') tasks.add_task('progression', testcase_id, job_type, wait_time=build_fail_wait) except errors.BadBuildError: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = 'Unable to recover from bad build' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message)
Execute progression task.
src/python/bot/tasks/progression_task.py
execute_task
eepeep/clusterfuzz
3
python
def execute_task(testcase_id, job_type): try: find_fixed_range(testcase_id, job_type) except errors.BuildSetupError as error: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Build setup failed r%d' % error.revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) build_fail_wait = environment.get_value('FAIL_WAIT') tasks.add_task('progression', testcase_id, job_type, wait_time=build_fail_wait) except errors.BadBuildError: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = 'Unable to recover from bad build' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message)
def execute_task(testcase_id, job_type): try: find_fixed_range(testcase_id, job_type) except errors.BuildSetupError as error: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = ('Build setup failed r%d' % error.revision) data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message) build_fail_wait = environment.get_value('FAIL_WAIT') tasks.add_task('progression', testcase_id, job_type, wait_time=build_fail_wait) except errors.BadBuildError: testcase = data_handler.get_testcase_by_id(testcase_id) error_message = 'Unable to recover from bad build' data_handler.update_testcase_comment(testcase, data_types.TaskState.ERROR, error_message)<|docstring|>Execute progression task.<|endoftext|>
702a78ab8de07900a496ae0dccba1333f5a6f4cb0220b1af7fae5717526e4007
def fit(self, data): '\n Fit the given data to the model.\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n ' data = data[:((data.shape[0] // self.batch_size) * self.batch_size)] data = self.data_transform(data) if self.pretrain: if self.verbose: print('Pretraining network') self.__pretrain(data) early_stopping = EarlyStopping(monitor='loss', patience=self.patience) P = compute_joint_probabilities(data, batch_size=self.batch_size, d=self.out_dim, perplexity=self.perplexity, tol=self.tol, verbose=self.verbose) y_train = P.reshape(data.shape[0], (- 1)) self.model.fit(data, y_train, epochs=self.epochs, callbacks=[early_stopping], batch_size=self.batch_size, shuffle=False, verbose=self.verbose)
Fit the given data to the model. Parameters ---------- data : array Array of training samples where each sample is of size `in_dim`
dimdrop/models/param_tsne.py
fit
TheOZoneBE/dimdrop
1
python
def fit(self, data): '\n Fit the given data to the model.\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n ' data = data[:((data.shape[0] // self.batch_size) * self.batch_size)] data = self.data_transform(data) if self.pretrain: if self.verbose: print('Pretraining network') self.__pretrain(data) early_stopping = EarlyStopping(monitor='loss', patience=self.patience) P = compute_joint_probabilities(data, batch_size=self.batch_size, d=self.out_dim, perplexity=self.perplexity, tol=self.tol, verbose=self.verbose) y_train = P.reshape(data.shape[0], (- 1)) self.model.fit(data, y_train, epochs=self.epochs, callbacks=[early_stopping], batch_size=self.batch_size, shuffle=False, verbose=self.verbose)
def fit(self, data): '\n Fit the given data to the model.\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n ' data = data[:((data.shape[0] // self.batch_size) * self.batch_size)] data = self.data_transform(data) if self.pretrain: if self.verbose: print('Pretraining network') self.__pretrain(data) early_stopping = EarlyStopping(monitor='loss', patience=self.patience) P = compute_joint_probabilities(data, batch_size=self.batch_size, d=self.out_dim, perplexity=self.perplexity, tol=self.tol, verbose=self.verbose) y_train = P.reshape(data.shape[0], (- 1)) self.model.fit(data, y_train, epochs=self.epochs, callbacks=[early_stopping], batch_size=self.batch_size, shuffle=False, verbose=self.verbose)<|docstring|>Fit the given data to the model. Parameters ---------- data : array Array of training samples where each sample is of size `in_dim`<|endoftext|>
f1a1662835e1515cff5150446f5601f42858a942562121974b185a1530e595ba
def transform(self, data): '\n Transform the given data\n\n Parameters\n ----------\n data : array\n Array of samples to be transformed, where each sample is of size\n `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' data = self.data_transform(data) return self.model.predict(data, verbose=self.verbose)
Transform the given data Parameters ---------- data : array Array of samples to be transformed, where each sample is of size `in_dim` Returns ------- array Transformed samples, where each sample is of size `out_dim`
dimdrop/models/param_tsne.py
transform
TheOZoneBE/dimdrop
1
python
def transform(self, data): '\n Transform the given data\n\n Parameters\n ----------\n data : array\n Array of samples to be transformed, where each sample is of size\n `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' data = self.data_transform(data) return self.model.predict(data, verbose=self.verbose)
def transform(self, data): '\n Transform the given data\n\n Parameters\n ----------\n data : array\n Array of samples to be transformed, where each sample is of size\n `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' data = self.data_transform(data) return self.model.predict(data, verbose=self.verbose)<|docstring|>Transform the given data Parameters ---------- data : array Array of samples to be transformed, where each sample is of size `in_dim` Returns ------- array Transformed samples, where each sample is of size `out_dim`<|endoftext|>
59fbd7de86f328ea3da99f292a8e73b63b713e1fd1ccb95fa23632808d0406b6
def fit_transform(self, data): '\n Fit the given data to the model and return its transformation\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' self.fit(data) return self.transform(data)
Fit the given data to the model and return its transformation Parameters ---------- data : array Array of training samples where each sample is of size `in_dim` Returns ------- array Transformed samples, where each sample is of size `out_dim`
dimdrop/models/param_tsne.py
fit_transform
TheOZoneBE/dimdrop
1
python
def fit_transform(self, data): '\n Fit the given data to the model and return its transformation\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' self.fit(data) return self.transform(data)
def fit_transform(self, data): '\n Fit the given data to the model and return its transformation\n\n Parameters\n ----------\n data : array\n Array of training samples where each sample is of size `in_dim`\n\n Returns\n -------\n array\n Transformed samples, where each sample is of size `out_dim`\n ' self.fit(data) return self.transform(data)<|docstring|>Fit the given data to the model and return its transformation Parameters ---------- data : array Array of training samples where each sample is of size `in_dim` Returns ------- array Transformed samples, where each sample is of size `out_dim`<|endoftext|>
6c9d048e704295c2c86c7ae6b026f0ddb8d12e14deae3b605e6843da714078d8
def inc_lat(x): ' Increment latitude x by one square edge length. ' return min((x + square_size), lat_bounds[1])
Increment latitude x by one square edge length.
get_square_regions.py
inc_lat
wtraylor/HadCM3B_60ka_for_LPJ-GUESS
0
python
def inc_lat(x): ' ' return min((x + square_size), lat_bounds[1])
def inc_lat(x): ' ' return min((x + square_size), lat_bounds[1])<|docstring|>Increment latitude x by one square edge length.<|endoftext|>
9aeb6ec6905e54164d4c06cc9f237248f4e2b9ca7997bb027612f7781d12e3de
def inc_lon(x): ' Increment longitude x by one square edge length. ' return min((x + square_size), lon_bounds[1])
Increment longitude x by one square edge length.
get_square_regions.py
inc_lon
wtraylor/HadCM3B_60ka_for_LPJ-GUESS
0
python
def inc_lon(x): ' ' return min((x + square_size), lon_bounds[1])
def inc_lon(x): ' ' return min((x + square_size), lon_bounds[1])<|docstring|>Increment longitude x by one square edge length.<|endoftext|>
373f680d022eeb3ab1671985417e669098ccf78843086aede4e3091778ae9607
def norm_lon(x): ' Normalize longitude x into range [0,360]. ' if (x == 360): return 360 else: return (x % 360)
Normalize longitude x into range [0,360].
get_square_regions.py
norm_lon
wtraylor/HadCM3B_60ka_for_LPJ-GUESS
0
python
def norm_lon(x): ' ' if (x == 360): return 360 else: return (x % 360)
def norm_lon(x): ' ' if (x == 360): return 360 else: return (x % 360)<|docstring|>Normalize longitude x into range [0,360].<|endoftext|>
a2688e81e077bb9805700b01e8b7a1cbdcf33941803d2ab906f9fa107e3e1e35
def nodes(self, tag_filters): 'Return a list of node ids filtered by the specified tags dict.\n\n This list must not include terminated nodes.\n\n Examples:\n >>> provider.nodes({TAG_RAY_NODE_TYPE: "Worker"})\n ["node-1", "node-2"]\n ' raise NotImplementedError
Return a list of node ids filtered by the specified tags dict. This list must not include terminated nodes. Examples: >>> provider.nodes({TAG_RAY_NODE_TYPE: "Worker"}) ["node-1", "node-2"]
python/ray/autoscaler/node_provider.py
nodes
rickyHong/Ray-repl
1
python
def nodes(self, tag_filters): 'Return a list of node ids filtered by the specified tags dict.\n\n This list must not include terminated nodes.\n\n Examples:\n >>> provider.nodes({TAG_RAY_NODE_TYPE: "Worker"})\n ["node-1", "node-2"]\n ' raise NotImplementedError
def nodes(self, tag_filters): 'Return a list of node ids filtered by the specified tags dict.\n\n This list must not include terminated nodes.\n\n Examples:\n >>> provider.nodes({TAG_RAY_NODE_TYPE: "Worker"})\n ["node-1", "node-2"]\n ' raise NotImplementedError<|docstring|>Return a list of node ids filtered by the specified tags dict. This list must not include terminated nodes. Examples: >>> provider.nodes({TAG_RAY_NODE_TYPE: "Worker"}) ["node-1", "node-2"]<|endoftext|>
2ebab1b8e6bcc8169d477690f95dd0013d1d6e03b95226a9ea1a226905214e03
def is_running(self, node_id): 'Return whether the specified node is running.' raise NotImplementedError
Return whether the specified node is running.
python/ray/autoscaler/node_provider.py
is_running
rickyHong/Ray-repl
1
python
def is_running(self, node_id): raise NotImplementedError
def is_running(self, node_id): raise NotImplementedError<|docstring|>Return whether the specified node is running.<|endoftext|>
d27dd07b01d101de58871bae1eed5bb08089f9c9c5431e5a1b640013a82f5f43
def is_terminated(self, node_id): 'Return whether the specified node is terminated.' raise NotImplementedError
Return whether the specified node is terminated.
python/ray/autoscaler/node_provider.py
is_terminated
rickyHong/Ray-repl
1
python
def is_terminated(self, node_id): raise NotImplementedError
def is_terminated(self, node_id): raise NotImplementedError<|docstring|>Return whether the specified node is terminated.<|endoftext|>
70f885ed68aa3b0add2364fdc16ca943028e44666cd451c7497356ced55793b9
def node_tags(self, node_id): 'Returns the tags of the given node (string dict).' raise NotImplementedError
Returns the tags of the given node (string dict).
python/ray/autoscaler/node_provider.py
node_tags
rickyHong/Ray-repl
1
python
def node_tags(self, node_id): raise NotImplementedError
def node_tags(self, node_id): raise NotImplementedError<|docstring|>Returns the tags of the given node (string dict).<|endoftext|>
6df6622fbb31ee78ece38cf80ccf7dd94973485f0a853b6796925984aaabc49c
def external_ip(self, node_id): 'Returns the external ip of the given node.' raise NotImplementedError
Returns the external ip of the given node.
python/ray/autoscaler/node_provider.py
external_ip
rickyHong/Ray-repl
1
python
def external_ip(self, node_id): raise NotImplementedError
def external_ip(self, node_id): raise NotImplementedError<|docstring|>Returns the external ip of the given node.<|endoftext|>
41d0ea83bb10658737e744fa4e0465bee5624bba4978ac819dc92e9c1d7f5450
def create_node(self, node_config, tags, count): 'Creates a number of nodes within the namespace.' raise NotImplementedError
Creates a number of nodes within the namespace.
python/ray/autoscaler/node_provider.py
create_node
rickyHong/Ray-repl
1
python
def create_node(self, node_config, tags, count): raise NotImplementedError
def create_node(self, node_config, tags, count): raise NotImplementedError<|docstring|>Creates a number of nodes within the namespace.<|endoftext|>
86d9b7bce3004970dcee98f6560343e913f238386828ef4098bda6bc1624f267
def set_node_tags(self, node_id, tags): 'Sets the tag values (string dict) for the specified node.' raise NotImplementedError
Sets the tag values (string dict) for the specified node.
python/ray/autoscaler/node_provider.py
set_node_tags
rickyHong/Ray-repl
1
python
def set_node_tags(self, node_id, tags): raise NotImplementedError
def set_node_tags(self, node_id, tags): raise NotImplementedError<|docstring|>Sets the tag values (string dict) for the specified node.<|endoftext|>
678efe1d1ec02e35cd5d670e852205f80ea61961d878133aa8d21f6fce013d10
def terminate_node(self, node_id): 'Terminates the specified node.' raise NotImplementedError
Terminates the specified node.
python/ray/autoscaler/node_provider.py
terminate_node
rickyHong/Ray-repl
1
python
def terminate_node(self, node_id): raise NotImplementedError
def terminate_node(self, node_id): raise NotImplementedError<|docstring|>Terminates the specified node.<|endoftext|>
6c3bb23648bbdd044645976fa389861ab97ed08f302fcb41db85ab37371a4cd3
def __init__(self, package_name, viewer=False): '\n Service for communicating with the Google Play Developer API.\n\n :param package_name: The package name for the app, e.g. com.package.name\n :param viewer: (Optional) True if data will only be viewed (e.g. list tracks),\n False if data will be edited (e.g. upload binary).\n ' self.package_name = package_name self.service = self.build_publisher_service(viewer)
Service for communicating with the Google Play Developer API. :param package_name: The package name for the app, e.g. com.package.name :param viewer: (Optional) True if data will only be viewed (e.g. list tracks), False if data will be edited (e.g. upload binary).
android_store_service/googleplay_build_service.py
__init__
Rajpratik71/android-store-service
5
python
def __init__(self, package_name, viewer=False): '\n Service for communicating with the Google Play Developer API.\n\n :param package_name: The package name for the app, e.g. com.package.name\n :param viewer: (Optional) True if data will only be viewed (e.g. list tracks),\n False if data will be edited (e.g. upload binary).\n ' self.package_name = package_name self.service = self.build_publisher_service(viewer)
def __init__(self, package_name, viewer=False): '\n Service for communicating with the Google Play Developer API.\n\n :param package_name: The package name for the app, e.g. com.package.name\n :param viewer: (Optional) True if data will only be viewed (e.g. list tracks),\n False if data will be edited (e.g. upload binary).\n ' self.package_name = package_name self.service = self.build_publisher_service(viewer)<|docstring|>Service for communicating with the Google Play Developer API. :param package_name: The package name for the app, e.g. com.package.name :param viewer: (Optional) True if data will only be viewed (e.g. list tracks), False if data will be edited (e.g. upload binary).<|endoftext|>
e45a1b586f0a2d251231c0d5df05baaaf696a72a56e46d5026db28cd0acbd918
def request(self, method, path, data=None, stream=False, headers=None, **kwargs): 'Send a request\n\n Always set the Content-Length header.\n ' if (headers is None): headers = {} if (not ('Content-Length' in headers)): length = super_len(data) if (length is not None): headers['Content-Length'] = length headers['Accept'] = 'application/json' kwargs['assert_same_host'] = False kwargs['redirect'] = False return self.pool.urlopen(method, path, body=data, preload_content=(not stream), headers=headers, **kwargs)
Send a request Always set the Content-Length header.
src/crate/client/http.py
request
jeffnappi/crate-python
0
python
def request(self, method, path, data=None, stream=False, headers=None, **kwargs): 'Send a request\n\n Always set the Content-Length header.\n ' if (headers is None): headers = {} if (not ('Content-Length' in headers)): length = super_len(data) if (length is not None): headers['Content-Length'] = length headers['Accept'] = 'application/json' kwargs['assert_same_host'] = False kwargs['redirect'] = False return self.pool.urlopen(method, path, body=data, preload_content=(not stream), headers=headers, **kwargs)
def request(self, method, path, data=None, stream=False, headers=None, **kwargs): 'Send a request\n\n Always set the Content-Length header.\n ' if (headers is None): headers = {} if (not ('Content-Length' in headers)): length = super_len(data) if (length is not None): headers['Content-Length'] = length headers['Accept'] = 'application/json' kwargs['assert_same_host'] = False kwargs['redirect'] = False return self.pool.urlopen(method, path, body=data, preload_content=(not stream), headers=headers, **kwargs)<|docstring|>Send a request Always set the Content-Length header.<|endoftext|>
269e1f47cd3081e6083357cbc4b647bd0284a869e8c3650a32ef113e9a158ade
def _get_sql_path(self, **url_params): '\n create the HTTP path to send SQL Requests to\n ' if url_params: return '{0}?{1}'.format(self.SQL_PATH, urlencode(url_params)) else: return self.SQL_PATH
create the HTTP path to send SQL Requests to
src/crate/client/http.py
_get_sql_path
jeffnappi/crate-python
0
python
def _get_sql_path(self, **url_params): '\n \n ' if url_params: return '{0}?{1}'.format(self.SQL_PATH, urlencode(url_params)) else: return self.SQL_PATH
def _get_sql_path(self, **url_params): '\n \n ' if url_params: return '{0}?{1}'.format(self.SQL_PATH, urlencode(url_params)) else: return self.SQL_PATH<|docstring|>create the HTTP path to send SQL Requests to<|endoftext|>
7422d6412bf3837ba77a89199fe8cc47e787a7cd3bdf8976b80b4c63138f639c
@staticmethod def _server_url(server): "\n Normalizes a given server string to an url\n\n >>> print(Client._server_url('a'))\n http://a\n >>> print(Client._server_url('a:9345'))\n http://a:9345\n >>> print(Client._server_url('https://a:9345'))\n https://a:9345\n >>> print(Client._server_url('https://a'))\n https://a\n >>> print(Client._server_url('demo.crate.io'))\n http://demo.crate.io\n " if (not _HTTP_PAT.match(server)): server = ('http://%s' % server) parsed = urlparse(server) url = ('%s://%s' % (parsed.scheme, parsed.netloc)) return url
Normalizes a given server string to an url >>> print(Client._server_url('a')) http://a >>> print(Client._server_url('a:9345')) http://a:9345 >>> print(Client._server_url('https://a:9345')) https://a:9345 >>> print(Client._server_url('https://a')) https://a >>> print(Client._server_url('demo.crate.io')) http://demo.crate.io
src/crate/client/http.py
_server_url
jeffnappi/crate-python
0
python
@staticmethod def _server_url(server): "\n Normalizes a given server string to an url\n\n >>> print(Client._server_url('a'))\n http://a\n >>> print(Client._server_url('a:9345'))\n http://a:9345\n >>> print(Client._server_url('https://a:9345'))\n https://a:9345\n >>> print(Client._server_url('https://a'))\n https://a\n >>> print(Client._server_url('demo.crate.io'))\n http://demo.crate.io\n " if (not _HTTP_PAT.match(server)): server = ('http://%s' % server) parsed = urlparse(server) url = ('%s://%s' % (parsed.scheme, parsed.netloc)) return url
@staticmethod def _server_url(server): "\n Normalizes a given server string to an url\n\n >>> print(Client._server_url('a'))\n http://a\n >>> print(Client._server_url('a:9345'))\n http://a:9345\n >>> print(Client._server_url('https://a:9345'))\n https://a:9345\n >>> print(Client._server_url('https://a'))\n https://a\n >>> print(Client._server_url('demo.crate.io'))\n http://demo.crate.io\n " if (not _HTTP_PAT.match(server)): server = ('http://%s' % server) parsed = urlparse(server) url = ('%s://%s' % (parsed.scheme, parsed.netloc)) return url<|docstring|>Normalizes a given server string to an url >>> print(Client._server_url('a')) http://a >>> print(Client._server_url('a:9345')) http://a:9345 >>> print(Client._server_url('https://a:9345')) https://a:9345 >>> print(Client._server_url('https://a')) https://a >>> print(Client._server_url('demo.crate.io')) http://demo.crate.io<|endoftext|>
5a77212adc9162488f0ba0835b23cad5ede83be5797eab7270555d146fad7507
def sql(self, stmt, parameters=None, bulk_parameters=None): '\n Execute SQL stmt against the crate server.\n ' if (stmt is None): return None if (not isinstance(stmt, basestring)): raise ValueError('stmt is not a string type') data = {'stmt': stmt} if parameters: data['args'] = parameters if bulk_parameters: data['bulk_args'] = bulk_parameters logger.debug('Sending request to %s with payload: %s', self.path, data) content = self._json_request('POST', self.path, data=data) logger.debug('JSON response for stmt(%s): %s', stmt, content) return content
Execute SQL stmt against the crate server.
src/crate/client/http.py
sql
jeffnappi/crate-python
0
python
def sql(self, stmt, parameters=None, bulk_parameters=None): '\n \n ' if (stmt is None): return None if (not isinstance(stmt, basestring)): raise ValueError('stmt is not a string type') data = {'stmt': stmt} if parameters: data['args'] = parameters if bulk_parameters: data['bulk_args'] = bulk_parameters logger.debug('Sending request to %s with payload: %s', self.path, data) content = self._json_request('POST', self.path, data=data) logger.debug('JSON response for stmt(%s): %s', stmt, content) return content
def sql(self, stmt, parameters=None, bulk_parameters=None): '\n \n ' if (stmt is None): return None if (not isinstance(stmt, basestring)): raise ValueError('stmt is not a string type') data = {'stmt': stmt} if parameters: data['args'] = parameters if bulk_parameters: data['bulk_args'] = bulk_parameters logger.debug('Sending request to %s with payload: %s', self.path, data) content = self._json_request('POST', self.path, data=data) logger.debug('JSON response for stmt(%s): %s', stmt, content) return content<|docstring|>Execute SQL stmt against the crate server.<|endoftext|>
88cdc9acb5ab9c53763f46bab1d0f66ab8070cc0ea43d415092b4f395b702f6e
def blob_put(self, table, digest, data): '\n Stores the contents of the file like @data object in a blob under the\n given table and digest.\n ' response = self._request('PUT', self._blob_path(table, digest), data=data) if (response.status == 201): return True if (response.status == 409): return False if (response.status == 400): raise BlobsDisabledException(table, digest) self._raise_for_status(response)
Stores the contents of the file like @data object in a blob under the given table and digest.
src/crate/client/http.py
blob_put
jeffnappi/crate-python
0
python
def blob_put(self, table, digest, data): '\n Stores the contents of the file like @data object in a blob under the\n given table and digest.\n ' response = self._request('PUT', self._blob_path(table, digest), data=data) if (response.status == 201): return True if (response.status == 409): return False if (response.status == 400): raise BlobsDisabledException(table, digest) self._raise_for_status(response)
def blob_put(self, table, digest, data): '\n Stores the contents of the file like @data object in a blob under the\n given table and digest.\n ' response = self._request('PUT', self._blob_path(table, digest), data=data) if (response.status == 201): return True if (response.status == 409): return False if (response.status == 400): raise BlobsDisabledException(table, digest) self._raise_for_status(response)<|docstring|>Stores the contents of the file like @data object in a blob under the given table and digest.<|endoftext|>
abe123ffbc85010cfe3d67e031ed60f6dd74d15fbd854d7dbf9be833e5651cfc
def blob_del(self, table, digest): '\n Deletes the blob with given digest under the given table.\n ' response = self._request('DELETE', self._blob_path(table, digest)) if (response.status == 204): return True if (response.status == 404): return False self._raise_for_status(response)
Deletes the blob with given digest under the given table.
src/crate/client/http.py
blob_del
jeffnappi/crate-python
0
python
def blob_del(self, table, digest): '\n \n ' response = self._request('DELETE', self._blob_path(table, digest)) if (response.status == 204): return True if (response.status == 404): return False self._raise_for_status(response)
def blob_del(self, table, digest): '\n \n ' response = self._request('DELETE', self._blob_path(table, digest)) if (response.status == 204): return True if (response.status == 404): return False self._raise_for_status(response)<|docstring|>Deletes the blob with given digest under the given table.<|endoftext|>
ea8f788d799a6f044b1656849d2d3ce187fd6fda872fe091ed42f93b3e9bf2b7
def blob_get(self, table, digest, chunk_size=(1024 * 128)): '\n Returns a file like object representing the contents of the blob with the given\n digest.\n ' response = self._request('GET', self._blob_path(table, digest), stream=True) if (response.status == 404): raise DigestNotFoundException(table, digest) self._raise_for_status(response) return response.stream(amt=chunk_size)
Returns a file like object representing the contents of the blob with the given digest.
src/crate/client/http.py
blob_get
jeffnappi/crate-python
0
python
def blob_get(self, table, digest, chunk_size=(1024 * 128)): '\n Returns a file like object representing the contents of the blob with the given\n digest.\n ' response = self._request('GET', self._blob_path(table, digest), stream=True) if (response.status == 404): raise DigestNotFoundException(table, digest) self._raise_for_status(response) return response.stream(amt=chunk_size)
def blob_get(self, table, digest, chunk_size=(1024 * 128)): '\n Returns a file like object representing the contents of the blob with the given\n digest.\n ' response = self._request('GET', self._blob_path(table, digest), stream=True) if (response.status == 404): raise DigestNotFoundException(table, digest) self._raise_for_status(response) return response.stream(amt=chunk_size)<|docstring|>Returns a file like object representing the contents of the blob with the given digest.<|endoftext|>
789f83a78ad8bc7519bb703d08cdca7c91bd6433da9faa2d967904f73b1fff30
def blob_exists(self, table, digest): '\n Returns true if the blob with the given digest exists under the given table.\n ' response = self._request('HEAD', self._blob_path(table, digest)) if (response.status == 200): return True elif (response.status == 404): return False self._raise_for_status(response)
Returns true if the blob with the given digest exists under the given table.
src/crate/client/http.py
blob_exists
jeffnappi/crate-python
0
python
def blob_exists(self, table, digest): '\n \n ' response = self._request('HEAD', self._blob_path(table, digest)) if (response.status == 200): return True elif (response.status == 404): return False self._raise_for_status(response)
def blob_exists(self, table, digest): '\n \n ' response = self._request('HEAD', self._blob_path(table, digest)) if (response.status == 200): return True elif (response.status == 404): return False self._raise_for_status(response)<|docstring|>Returns true if the blob with the given digest exists under the given table.<|endoftext|>
fedebb41cc107f09454844fb08aa7777fa3cf506648199f6309bc3933d21b223
def _request(self, method, path, server=None, **kwargs): 'Execute a request to the cluster\n\n A server is selected from the server pool.\n ' while True: next_server = (server or self._get_server()) try: response = self._do_request(next_server, method, path, **kwargs) redirect_location = response.get_redirect_location() if (redirect_location and (300 <= response.status <= 308)): redirect_server = self._server_url(redirect_location) self._add_server(redirect_server) return self._request(method, path, server=redirect_server, **kwargs) if ((not server) and (response.status in SRV_UNAVAILABLE_STATUSES)): with self._lock: self._drop_server(next_server, response.reason) else: return response except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.SSLError, urllib3.exceptions.HTTPError, urllib3.exceptions.ProxyError) as ex: ex_message = ((hasattr(ex, 'message') and ex.message) or str(ex)) if server: raise ConnectionError(('Server not available, exception: %s' % ex_message)) with self._lock: self._drop_server(next_server, ex_message) except Exception as e: ex_message = ((hasattr(e, 'message') and e.message) or str(e)) raise ProgrammingError(ex_message)
Execute a request to the cluster A server is selected from the server pool.
src/crate/client/http.py
_request
jeffnappi/crate-python
0
python
def _request(self, method, path, server=None, **kwargs): 'Execute a request to the cluster\n\n A server is selected from the server pool.\n ' while True: next_server = (server or self._get_server()) try: response = self._do_request(next_server, method, path, **kwargs) redirect_location = response.get_redirect_location() if (redirect_location and (300 <= response.status <= 308)): redirect_server = self._server_url(redirect_location) self._add_server(redirect_server) return self._request(method, path, server=redirect_server, **kwargs) if ((not server) and (response.status in SRV_UNAVAILABLE_STATUSES)): with self._lock: self._drop_server(next_server, response.reason) else: return response except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.SSLError, urllib3.exceptions.HTTPError, urllib3.exceptions.ProxyError) as ex: ex_message = ((hasattr(ex, 'message') and ex.message) or str(ex)) if server: raise ConnectionError(('Server not available, exception: %s' % ex_message)) with self._lock: self._drop_server(next_server, ex_message) except Exception as e: ex_message = ((hasattr(e, 'message') and e.message) or str(e)) raise ProgrammingError(ex_message)
def _request(self, method, path, server=None, **kwargs): 'Execute a request to the cluster\n\n A server is selected from the server pool.\n ' while True: next_server = (server or self._get_server()) try: response = self._do_request(next_server, method, path, **kwargs) redirect_location = response.get_redirect_location() if (redirect_location and (300 <= response.status <= 308)): redirect_server = self._server_url(redirect_location) self._add_server(redirect_server) return self._request(method, path, server=redirect_server, **kwargs) if ((not server) and (response.status in SRV_UNAVAILABLE_STATUSES)): with self._lock: self._drop_server(next_server, response.reason) else: return response except (urllib3.exceptions.MaxRetryError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.SSLError, urllib3.exceptions.HTTPError, urllib3.exceptions.ProxyError) as ex: ex_message = ((hasattr(ex, 'message') and ex.message) or str(ex)) if server: raise ConnectionError(('Server not available, exception: %s' % ex_message)) with self._lock: self._drop_server(next_server, ex_message) except Exception as e: ex_message = ((hasattr(e, 'message') and e.message) or str(e)) raise ProgrammingError(ex_message)<|docstring|>Execute a request to the cluster A server is selected from the server pool.<|endoftext|>
bb17d8316d411aec7b8d9e3bd0506591b560be063b7b70655be4929e20c6a6f2
def _do_request(self, server, method, path, **kwargs): 'do the actual request to a chosen server' if (not path.startswith('/')): path = ('/' + path) return self.server_pool[server].request(method, path, **kwargs)
do the actual request to a chosen server
src/crate/client/http.py
_do_request
jeffnappi/crate-python
0
python
def _do_request(self, server, method, path, **kwargs): if (not path.startswith('/')): path = ('/' + path) return self.server_pool[server].request(method, path, **kwargs)
def _do_request(self, server, method, path, **kwargs): if (not path.startswith('/')): path = ('/' + path) return self.server_pool[server].request(method, path, **kwargs)<|docstring|>do the actual request to a chosen server<|endoftext|>
29e915ab89bb68020ebc05a3abb9937f379e413fe93608944353e5da9990de43
def _raise_for_status(self, response): ' make sure that only crate.exceptions are raised that are defined in\n the DB-API specification ' http_error_msg = '' if (400 <= response.status < 500): http_error_msg = ('%s Client Error: %s' % (response.status, response.reason)) elif (500 <= response.status < 600): http_error_msg = ('%s Server Error: %s' % (response.status, response.reason)) else: return if (response.status == 503): raise ConnectionError(http_error_msg) if response.headers.get('content-type', '').startswith('application/json'): data = json.loads(six.text_type(response.data, 'utf-8')) error = data.get('error', {}) error_trace = data.get('error_trace', None) if ('results' in data): errors = [res['error_message'] for res in data['results'] if res.get('error_message')] if errors: raise ProgrammingError('\n'.join(errors)) if isinstance(error, dict): raise ProgrammingError(error.get('message', ''), error_trace=error_trace) raise ProgrammingError(error, error_trace=error_trace) raise ProgrammingError(http_error_msg)
make sure that only crate.exceptions are raised that are defined in the DB-API specification
src/crate/client/http.py
_raise_for_status
jeffnappi/crate-python
0
python
def _raise_for_status(self, response): ' make sure that only crate.exceptions are raised that are defined in\n the DB-API specification ' http_error_msg = if (400 <= response.status < 500): http_error_msg = ('%s Client Error: %s' % (response.status, response.reason)) elif (500 <= response.status < 600): http_error_msg = ('%s Server Error: %s' % (response.status, response.reason)) else: return if (response.status == 503): raise ConnectionError(http_error_msg) if response.headers.get('content-type', ).startswith('application/json'): data = json.loads(six.text_type(response.data, 'utf-8')) error = data.get('error', {}) error_trace = data.get('error_trace', None) if ('results' in data): errors = [res['error_message'] for res in data['results'] if res.get('error_message')] if errors: raise ProgrammingError('\n'.join(errors)) if isinstance(error, dict): raise ProgrammingError(error.get('message', ), error_trace=error_trace) raise ProgrammingError(error, error_trace=error_trace) raise ProgrammingError(http_error_msg)
def _raise_for_status(self, response): ' make sure that only crate.exceptions are raised that are defined in\n the DB-API specification ' http_error_msg = if (400 <= response.status < 500): http_error_msg = ('%s Client Error: %s' % (response.status, response.reason)) elif (500 <= response.status < 600): http_error_msg = ('%s Server Error: %s' % (response.status, response.reason)) else: return if (response.status == 503): raise ConnectionError(http_error_msg) if response.headers.get('content-type', ).startswith('application/json'): data = json.loads(six.text_type(response.data, 'utf-8')) error = data.get('error', {}) error_trace = data.get('error_trace', None) if ('results' in data): errors = [res['error_message'] for res in data['results'] if res.get('error_message')] if errors: raise ProgrammingError('\n'.join(errors)) if isinstance(error, dict): raise ProgrammingError(error.get('message', ), error_trace=error_trace) raise ProgrammingError(error, error_trace=error_trace) raise ProgrammingError(http_error_msg)<|docstring|>make sure that only crate.exceptions are raised that are defined in the DB-API specification<|endoftext|>
b63145261e892ec10b962c4329b29dd8c6b030a283fcfb2fce4bd958d79dd746
def _json_request(self, method, path, data=None): '\n Issue request against the crate HTTP API.\n ' if data: data = json.dumps(data) response = self._request(method, path, data=data) self._raise_for_status(response) if (len(response.data) > 0): try: return json.loads(six.text_type(response.data, 'utf-8')) except ValueError: raise ProgrammingError(("Invalid server response of content-type '%s'" % response.headers.get('content-type', ''))) return response.data
Issue request against the crate HTTP API.
src/crate/client/http.py
_json_request
jeffnappi/crate-python
0
python
def _json_request(self, method, path, data=None): '\n \n ' if data: data = json.dumps(data) response = self._request(method, path, data=data) self._raise_for_status(response) if (len(response.data) > 0): try: return json.loads(six.text_type(response.data, 'utf-8')) except ValueError: raise ProgrammingError(("Invalid server response of content-type '%s'" % response.headers.get('content-type', ))) return response.data
def _json_request(self, method, path, data=None): '\n \n ' if data: data = json.dumps(data) response = self._request(method, path, data=data) self._raise_for_status(response) if (len(response.data) > 0): try: return json.loads(six.text_type(response.data, 'utf-8')) except ValueError: raise ProgrammingError(("Invalid server response of content-type '%s'" % response.headers.get('content-type', ))) return response.data<|docstring|>Issue request against the crate HTTP API.<|endoftext|>
3d3ce9ca204e1c18c527d1da138a2ab620313e6904feeb54d27b79bc6081a713
def _get_server(self): '\n Get server to use for request.\n Also process inactive server list, re-add them after given interval.\n ' with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: (ts, server, message) = heapq.heappop(self._inactive_servers) except IndexError: pass else: if ((ts + self.retry_interval) > time()): heapq.heappush(self._inactive_servers, (ts, server, message)) else: self._active_servers.append(server) logger.warn('Restored server %s into active pool', server) if (not self._active_servers): (ts, server, message) = heapq.heappop(self._inactive_servers) self._active_servers.append(server) logger.info('Restored server %s into active pool', server) server = self._active_servers[0] self._roundrobin() return server
Get server to use for request. Also process inactive server list, re-add them after given interval.
src/crate/client/http.py
_get_server
jeffnappi/crate-python
0
python
def _get_server(self): '\n Get server to use for request.\n Also process inactive server list, re-add them after given interval.\n ' with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: (ts, server, message) = heapq.heappop(self._inactive_servers) except IndexError: pass else: if ((ts + self.retry_interval) > time()): heapq.heappush(self._inactive_servers, (ts, server, message)) else: self._active_servers.append(server) logger.warn('Restored server %s into active pool', server) if (not self._active_servers): (ts, server, message) = heapq.heappop(self._inactive_servers) self._active_servers.append(server) logger.info('Restored server %s into active pool', server) server = self._active_servers[0] self._roundrobin() return server
def _get_server(self): '\n Get server to use for request.\n Also process inactive server list, re-add them after given interval.\n ' with self._lock: inactive_server_count = len(self._inactive_servers) for i in range(inactive_server_count): try: (ts, server, message) = heapq.heappop(self._inactive_servers) except IndexError: pass else: if ((ts + self.retry_interval) > time()): heapq.heappush(self._inactive_servers, (ts, server, message)) else: self._active_servers.append(server) logger.warn('Restored server %s into active pool', server) if (not self._active_servers): (ts, server, message) = heapq.heappop(self._inactive_servers) self._active_servers.append(server) logger.info('Restored server %s into active pool', server) server = self._active_servers[0] self._roundrobin() return server<|docstring|>Get server to use for request. Also process inactive server list, re-add them after given interval.<|endoftext|>
c47a1814ac2f0292da15e14c3e5706c77f7baec935cde5cd393a75c7c6389ad5
@property def active_servers(self): 'get the active servers for this client' with self._lock: return list(self._active_servers)
get the active servers for this client
src/crate/client/http.py
active_servers
jeffnappi/crate-python
0
python
@property def active_servers(self): with self._lock: return list(self._active_servers)
@property def active_servers(self): with self._lock: return list(self._active_servers)<|docstring|>get the active servers for this client<|endoftext|>
8d381441f45599b786221ba5f32e1ddfa5889b40729d4be641dca62edcb62a9a
def _drop_server(self, server, message): '\n Drop server from active list and adds it to the inactive ones.\n ' try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning('Removed server %s from active pool', server) if (not self._active_servers): raise ConnectionError(('No more Servers available, exception from last server: %s' % message))
Drop server from active list and adds it to the inactive ones.
src/crate/client/http.py
_drop_server
jeffnappi/crate-python
0
python
def _drop_server(self, server, message): '\n \n ' try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning('Removed server %s from active pool', server) if (not self._active_servers): raise ConnectionError(('No more Servers available, exception from last server: %s' % message))
def _drop_server(self, server, message): '\n \n ' try: self._active_servers.remove(server) except ValueError: pass else: heapq.heappush(self._inactive_servers, (time(), server, message)) logger.warning('Removed server %s from active pool', server) if (not self._active_servers): raise ConnectionError(('No more Servers available, exception from last server: %s' % message))<|docstring|>Drop server from active list and adds it to the inactive ones.<|endoftext|>
1773efbb3b5f69d3ad9ae34a0868dd35c4d7a8ee9658a8b3b58e810400857a03
def _roundrobin(self): '\n Very simple round-robin implementation\n ' self._active_servers.append(self._active_servers.pop(0))
Very simple round-robin implementation
src/crate/client/http.py
_roundrobin
jeffnappi/crate-python
0
python
def _roundrobin(self): '\n \n ' self._active_servers.append(self._active_servers.pop(0))
def _roundrobin(self): '\n \n ' self._active_servers.append(self._active_servers.pop(0))<|docstring|>Very simple round-robin implementation<|endoftext|>
06d4f9bc6844e6e607c9988c4bb4fbefe69712a5fdae8e70ec31242faf82ea69
def mean(data): 'Return the sample arithmetic mean of data.' n = len(data) if (n < 1): raise ValueError('mean requires at least one data point') return (sum(data) / n)
Return the sample arithmetic mean of data.
metawibele/common/extract_abundance_feature_subset.py
mean
biobakery/metawibele
3
python
def mean(data): n = len(data) if (n < 1): raise ValueError('mean requires at least one data point') return (sum(data) / n)
def mean(data): n = len(data) if (n < 1): raise ValueError('mean requires at least one data point') return (sum(data) / n)<|docstring|>Return the sample arithmetic mean of data.<|endoftext|>
ee42bb6460a4b6c1453c25e8bc5156227534b14048082d6ad50b9dd3176b8ae0
def find_prj_in_dir(self): '\n ritorna il nome deprj se lo trovata\n "" altrimenti\n ' lst = self._run_dir_p.glob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return '' pid_path = prj_paths[0] prj_name = self.read_prj_name(pid_path) return prj_name
ritorna il nome deprj se lo trovata "" altrimenti
teimedlib/teimprjmap.py
find_prj_in_dir
gmaterni/teimed
0
python
def find_prj_in_dir(self): '\n ritorna il nome deprj se lo trovata\n altrimenti\n ' lst = self._run_dir_p.glob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return pid_path = prj_paths[0] prj_name = self.read_prj_name(pid_path) return prj_name
def find_prj_in_dir(self): '\n ritorna il nome deprj se lo trovata\n altrimenti\n ' lst = self._run_dir_p.glob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return pid_path = prj_paths[0] prj_name = self.read_prj_name(pid_path) return prj_name<|docstring|>ritorna il nome deprj se lo trovata "" altrimenti<|endoftext|>
63794bc1b5a8efbe143bdf6f38331ef10aa589dbd05fbddbb2e6ffbb54f0c368
def find_prj_in_desc_dir(self): '\n cerca a partire dalla run_dir\n ' lst = self._run_dir_p.rglob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return ([], []) prj_names = [] for path in prj_paths: prj_name = self.read_prj_name(path) prj_names.append(prj_name) return (prj_paths, prj_names)
cerca a partire dalla run_dir
teimedlib/teimprjmap.py
find_prj_in_desc_dir
gmaterni/teimed
0
python
def find_prj_in_desc_dir(self): '\n \n ' lst = self._run_dir_p.rglob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return ([], []) prj_names = [] for path in prj_paths: prj_name = self.read_prj_name(path) prj_names.append(prj_name) return (prj_paths, prj_names)
def find_prj_in_desc_dir(self): '\n \n ' lst = self._run_dir_p.rglob('__prj__') prj_paths = [pid for pid in lst] if (prj_paths == []): return ([], []) prj_names = [] for path in prj_paths: prj_name = self.read_prj_name(path) prj_names.append(prj_name) return (prj_paths, prj_names)<|docstring|>cerca a partire dalla run_dir<|endoftext|>
7cded0fb5421e5eb0ab11468580e5843e9845172c3981b84738fba5ed9c7ab20
def check_prj_dir_of_name(self): '\n controlla se run_dir==prj_dir\n e se self.prj_name!==project_name della dir\n setta run_dir_pos=1\n se run_dir è parent di cd_prj_dir\n controllo che self.prj_name== prj_name della dur\n e setta run_dir_pos=2\n ' prj_name = self.find_prj_in_dir() if ((prj_name == self._run_dir_p.name) and (prj_name == self._prj_name)): self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1 return (prj_paths, prj_names) = self.find_prj_in_desc_dir() if (prj_names == []): return for path in prj_paths: prj_name = self.read_prj_name(path) if (prj_name == self._prj_name): self._prj_dir_p = path.parent self._run_dir_pos = 2
controlla se run_dir==prj_dir e se self.prj_name!==project_name della dir setta run_dir_pos=1 se run_dir è parent di cd_prj_dir controllo che self.prj_name== prj_name della dur e setta run_dir_pos=2
teimedlib/teimprjmap.py
check_prj_dir_of_name
gmaterni/teimed
0
python
def check_prj_dir_of_name(self): '\n controlla se run_dir==prj_dir\n e se self.prj_name!==project_name della dir\n setta run_dir_pos=1\n se run_dir è parent di cd_prj_dir\n controllo che self.prj_name== prj_name della dur\n e setta run_dir_pos=2\n ' prj_name = self.find_prj_in_dir() if ((prj_name == self._run_dir_p.name) and (prj_name == self._prj_name)): self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1 return (prj_paths, prj_names) = self.find_prj_in_desc_dir() if (prj_names == []): return for path in prj_paths: prj_name = self.read_prj_name(path) if (prj_name == self._prj_name): self._prj_dir_p = path.parent self._run_dir_pos = 2
def check_prj_dir_of_name(self): '\n controlla se run_dir==prj_dir\n e se self.prj_name!==project_name della dir\n setta run_dir_pos=1\n se run_dir è parent di cd_prj_dir\n controllo che self.prj_name== prj_name della dur\n e setta run_dir_pos=2\n ' prj_name = self.find_prj_in_dir() if ((prj_name == self._run_dir_p.name) and (prj_name == self._prj_name)): self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1 return (prj_paths, prj_names) = self.find_prj_in_desc_dir() if (prj_names == []): return for path in prj_paths: prj_name = self.read_prj_name(path) if (prj_name == self._prj_name): self._prj_dir_p = path.parent self._run_dir_pos = 2<|docstring|>controlla se run_dir==prj_dir e se self.prj_name!==project_name della dir setta run_dir_pos=1 se run_dir è parent di cd_prj_dir controllo che self.prj_name== prj_name della dur e setta run_dir_pos=2<|endoftext|>
66e114f5f58fcedfda172972cc0bf4e7f7b73d96fd34d1e6bb5878bbd7ee0b72
def check_prj_dir_of_none(self): "\n controlla si run_dir==prj_dir con self.prj_name=='\n viene settato quello di prj_dir\n setta run_dir_pos=1\n " prj_name = self.find_prj_in_dir() if (prj_name == self._run_dir_p.name): self._prj_name = prj_name self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1
controlla si run_dir==prj_dir con self.prj_name==' viene settato quello di prj_dir setta run_dir_pos=1
teimedlib/teimprjmap.py
check_prj_dir_of_none
gmaterni/teimed
0
python
def check_prj_dir_of_none(self): "\n controlla si run_dir==prj_dir con self.prj_name=='\n viene settato quello di prj_dir\n setta run_dir_pos=1\n " prj_name = self.find_prj_in_dir() if (prj_name == self._run_dir_p.name): self._prj_name = prj_name self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1
def check_prj_dir_of_none(self): "\n controlla si run_dir==prj_dir con self.prj_name=='\n viene settato quello di prj_dir\n setta run_dir_pos=1\n " prj_name = self.find_prj_in_dir() if (prj_name == self._run_dir_p.name): self._prj_name = prj_name self._prj_dir_p = self._run_dir_p self._run_dir_pos = 1<|docstring|>controlla si run_dir==prj_dir con self.prj_name==' viene settato quello di prj_dir setta run_dir_pos=1<|endoftext|>
0a5b44036455253d2a8a318938521b9c5d6e58689a46a23f58e193a35c895041
def check_prj_dir(self, prj_name=None): '"\n ritorna\n 1) run_dir == prj_dir\n 2) run_dir = parent di prj_dir\n ' self._prj_name = prj_name if (not self._prj_name): self.check_prj_dir_of_none() else: self.check_prj_dir_of_name() return self.run_dir_pos
" ritorna 1) run_dir == prj_dir 2) run_dir = parent di prj_dir
teimedlib/teimprjmap.py
check_prj_dir
gmaterni/teimed
0
python
def check_prj_dir(self, prj_name=None): '"\n ritorna\n 1) run_dir == prj_dir\n 2) run_dir = parent di prj_dir\n ' self._prj_name = prj_name if (not self._prj_name): self.check_prj_dir_of_none() else: self.check_prj_dir_of_name() return self.run_dir_pos
def check_prj_dir(self, prj_name=None): '"\n ritorna\n 1) run_dir == prj_dir\n 2) run_dir = parent di prj_dir\n ' self._prj_name = prj_name if (not self._prj_name): self.check_prj_dir_of_none() else: self.check_prj_dir_of_name() return self.run_dir_pos<|docstring|>" ritorna 1) run_dir == prj_dir 2) run_dir = parent di prj_dir<|endoftext|>
fc0ea2b1a1423f1a3f7ee52ac2a2b4209ab1cd5bd8195bef49b3d0ec872c96e8
def __init__(self, verbose: bool=False): '\n Abstract class that defines basic methods for probability estimators.\n\n Args:\n verbose: whether to print misc information\n ' self.verbose = verbose self.logger = logging.getLogger(Path(__file__).name) self.logger.setLevel((logging.DEBUG if self.verbose else logging.INFO)) self.output_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.output_handler.setFormatter(formatter) self.logger.addHandler(self.output_handler)
Abstract class that defines basic methods for probability estimators. Args: verbose: whether to print misc information
lexsubgen/prob_estimators/base_estimator.py
__init__
myrachins/LexSubGen
32
python
def __init__(self, verbose: bool=False): '\n Abstract class that defines basic methods for probability estimators.\n\n Args:\n verbose: whether to print misc information\n ' self.verbose = verbose self.logger = logging.getLogger(Path(__file__).name) self.logger.setLevel((logging.DEBUG if self.verbose else logging.INFO)) self.output_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.output_handler.setFormatter(formatter) self.logger.addHandler(self.output_handler)
def __init__(self, verbose: bool=False): '\n Abstract class that defines basic methods for probability estimators.\n\n Args:\n verbose: whether to print misc information\n ' self.verbose = verbose self.logger = logging.getLogger(Path(__file__).name) self.logger.setLevel((logging.DEBUG if self.verbose else logging.INFO)) self.output_handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.output_handler.setFormatter(formatter) self.logger.addHandler(self.output_handler)<|docstring|>Abstract class that defines basic methods for probability estimators. Args: verbose: whether to print misc information<|endoftext|>
46cf1becf3dd4bbc273237d499bbc205c787823396ab682fe71b92dc273ec36c
def get_log_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Compute probabilities for each target word in tokens lists.\n Process all input data with batches.\n\n Args:\n tokens_lists: list of tokenized sequences, each list corresponds to one tokenized example.\n target_ids: indices of target words from all tokens lists.\n Returns:\n `numpy.ndarray` of log-probs distribution over vocabulary and the relative vocabulary.\n\n Examples:\n >>> token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n >>> target_ids_list = [1,2]\n >>> self.get_log_probs(tokens_lists, target_ids)\n # This means that we want to get probability distribution for words "world" and "stackoverflow".\n ' raise NotImplementedError()
Compute probabilities for each target word in tokens lists. Process all input data with batches. Args: tokens_lists: list of tokenized sequences, each list corresponds to one tokenized example. target_ids: indices of target words from all tokens lists. Returns: `numpy.ndarray` of log-probs distribution over vocabulary and the relative vocabulary. Examples: >>> token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]] >>> target_ids_list = [1,2] >>> self.get_log_probs(tokens_lists, target_ids) # This means that we want to get probability distribution for words "world" and "stackoverflow".
lexsubgen/prob_estimators/base_estimator.py
get_log_probs
myrachins/LexSubGen
32
python
def get_log_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Compute probabilities for each target word in tokens lists.\n Process all input data with batches.\n\n Args:\n tokens_lists: list of tokenized sequences, each list corresponds to one tokenized example.\n target_ids: indices of target words from all tokens lists.\n Returns:\n `numpy.ndarray` of log-probs distribution over vocabulary and the relative vocabulary.\n\n Examples:\n >>> token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n >>> target_ids_list = [1,2]\n >>> self.get_log_probs(tokens_lists, target_ids)\n # This means that we want to get probability distribution for words "world" and "stackoverflow".\n ' raise NotImplementedError()
def get_log_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Compute probabilities for each target word in tokens lists.\n Process all input data with batches.\n\n Args:\n tokens_lists: list of tokenized sequences, each list corresponds to one tokenized example.\n target_ids: indices of target words from all tokens lists.\n Returns:\n `numpy.ndarray` of log-probs distribution over vocabulary and the relative vocabulary.\n\n Examples:\n >>> token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n >>> target_ids_list = [1,2]\n >>> self.get_log_probs(tokens_lists, target_ids)\n # This means that we want to get probability distribution for words "world" and "stackoverflow".\n ' raise NotImplementedError()<|docstring|>Compute probabilities for each target word in tokens lists. Process all input data with batches. Args: tokens_lists: list of tokenized sequences, each list corresponds to one tokenized example. target_ids: indices of target words from all tokens lists. Returns: `numpy.ndarray` of log-probs distribution over vocabulary and the relative vocabulary. Examples: >>> token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]] >>> target_ids_list = [1,2] >>> self.get_log_probs(tokens_lists, target_ids) # This means that we want to get probability distribution for words "world" and "stackoverflow".<|endoftext|>
118c869e3701720b8ceccbc82b69db233eb592f002affc2b04671aeb4792a800
def get_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Computes probability distribution over vocabulary for a given instances.\n\n Args:\n tokens_lists: list of contexts.\n target_ids: list of target word ids.\n E.g.:\n token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n target_ids_list = [1,2]\n This means that we want to get probability distribution for words "world" and "stackoverflow".\n Returns:\n Probability distribution over vocabulary and the relative vocabulary.\n ' (logits, word2id) = self.get_log_probs(tokens_lists, target_ids) probs = softmax(logits, axis=(- 1)) return (probs, word2id)
Computes probability distribution over vocabulary for a given instances. Args: tokens_lists: list of contexts. target_ids: list of target word ids. E.g.: token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]] target_ids_list = [1,2] This means that we want to get probability distribution for words "world" and "stackoverflow". Returns: Probability distribution over vocabulary and the relative vocabulary.
lexsubgen/prob_estimators/base_estimator.py
get_probs
myrachins/LexSubGen
32
python
def get_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Computes probability distribution over vocabulary for a given instances.\n\n Args:\n tokens_lists: list of contexts.\n target_ids: list of target word ids.\n E.g.:\n token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n target_ids_list = [1,2]\n This means that we want to get probability distribution for words "world" and "stackoverflow".\n Returns:\n Probability distribution over vocabulary and the relative vocabulary.\n ' (logits, word2id) = self.get_log_probs(tokens_lists, target_ids) probs = softmax(logits, axis=(- 1)) return (probs, word2id)
def get_probs(self, tokens_lists: List[List[str]], target_ids: List[int]) -> Tuple[(np.ndarray, Dict[(str, int)])]: '\n Computes probability distribution over vocabulary for a given instances.\n\n Args:\n tokens_lists: list of contexts.\n target_ids: list of target word ids.\n E.g.:\n token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]]\n target_ids_list = [1,2]\n This means that we want to get probability distribution for words "world" and "stackoverflow".\n Returns:\n Probability distribution over vocabulary and the relative vocabulary.\n ' (logits, word2id) = self.get_log_probs(tokens_lists, target_ids) probs = softmax(logits, axis=(- 1)) return (probs, word2id)<|docstring|>Computes probability distribution over vocabulary for a given instances. Args: tokens_lists: list of contexts. target_ids: list of target word ids. E.g.: token_lists = [["Hello", "world", "!"], ["Go", "to" "stackoverflow"]] target_ids_list = [1,2] This means that we want to get probability distribution for words "world" and "stackoverflow". Returns: Probability distribution over vocabulary and the relative vocabulary.<|endoftext|>
f498e1dd9ec6d8a265935b16c51bd72b235d126a2aae3a484bb95452e825d87a
def __init__(self) -> None: 'DataHandler constructor.\n\n Returns a new instance of a DataHandler.\n\n Should not be called directly, but rather through the factory method `DataHandler.get_handler()`.\n ' log.info('Creating new handler') (self.person_names, self.person_names_inverse) = DataHandler._load_persons() log.info('Loaded Person Info') self.manuscripts = DataHandler._load_ms_info(persons=self.person_names) log.info('Loaded MS Info') self.text_matrix = DataHandler._load_text_matrix(self.manuscripts) log.info('Loaded Text Info') self.person_matrix = DataHandler._load_person_matrix(self.manuscripts) log.info('Loaded Person-MSS-Matrix Info') self.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {self.groups}') self.manuscripts.drop(columns=['content', 'soup'], inplace=True) log.info('Successfully created a Datahandler instance.') GitUtil.update_handler_state()
DataHandler constructor. Returns a new instance of a DataHandler. Should not be called directly, but rather through the factory method `DataHandler.get_handler()`.
util/datahandler.py
__init__
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def __init__(self) -> None: 'DataHandler constructor.\n\n Returns a new instance of a DataHandler.\n\n Should not be called directly, but rather through the factory method `DataHandler.get_handler()`.\n ' log.info('Creating new handler') (self.person_names, self.person_names_inverse) = DataHandler._load_persons() log.info('Loaded Person Info') self.manuscripts = DataHandler._load_ms_info(persons=self.person_names) log.info('Loaded MS Info') self.text_matrix = DataHandler._load_text_matrix(self.manuscripts) log.info('Loaded Text Info') self.person_matrix = DataHandler._load_person_matrix(self.manuscripts) log.info('Loaded Person-MSS-Matrix Info') self.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {self.groups}') self.manuscripts.drop(columns=['content', 'soup'], inplace=True) log.info('Successfully created a Datahandler instance.') GitUtil.update_handler_state()
def __init__(self) -> None: 'DataHandler constructor.\n\n Returns a new instance of a DataHandler.\n\n Should not be called directly, but rather through the factory method `DataHandler.get_handler()`.\n ' log.info('Creating new handler') (self.person_names, self.person_names_inverse) = DataHandler._load_persons() log.info('Loaded Person Info') self.manuscripts = DataHandler._load_ms_info(persons=self.person_names) log.info('Loaded MS Info') self.text_matrix = DataHandler._load_text_matrix(self.manuscripts) log.info('Loaded Text Info') self.person_matrix = DataHandler._load_person_matrix(self.manuscripts) log.info('Loaded Person-MSS-Matrix Info') self.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {self.groups}') self.manuscripts.drop(columns=['content', 'soup'], inplace=True) log.info('Successfully created a Datahandler instance.') GitUtil.update_handler_state()<|docstring|>DataHandler constructor. Returns a new instance of a DataHandler. Should not be called directly, but rather through the factory method `DataHandler.get_handler()`.<|endoftext|>
5588474ba16d8a2246fc285cfc954da1e852a2cace40fe170adddb03526f6792
@staticmethod def _from_pickle() -> Optional[DataHandler]: 'Load datahandler from pickle, if available. Returns None otherwise.' if os.path.exists(HANDLER_PATH_PICKLE): try: prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='rb') as file: sys.setrecursionlimit((prev * 100)) obj = pickle.load(file) sys.setrecursionlimit(prev) if isinstance(obj, DataHandler): obj.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {obj.groups}') return obj except Exception: log.exception('Cound not load handler from pickle') return None
Load datahandler from pickle, if available. Returns None otherwise.
util/datahandler.py
_from_pickle
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def _from_pickle() -> Optional[DataHandler]: if os.path.exists(HANDLER_PATH_PICKLE): try: prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='rb') as file: sys.setrecursionlimit((prev * 100)) obj = pickle.load(file) sys.setrecursionlimit(prev) if isinstance(obj, DataHandler): obj.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {obj.groups}') return obj except Exception: log.exception('Cound not load handler from pickle') return None
@staticmethod def _from_pickle() -> Optional[DataHandler]: if os.path.exists(HANDLER_PATH_PICKLE): try: prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='rb') as file: sys.setrecursionlimit((prev * 100)) obj = pickle.load(file) sys.setrecursionlimit(prev) if isinstance(obj, DataHandler): obj.groups = (Groups.from_cache() or Groups()) log.debug(f'Groups loaded: {obj.groups}') return obj except Exception: log.exception('Cound not load handler from pickle') return None<|docstring|>Load datahandler from pickle, if available. Returns None otherwise.<|endoftext|>
6274f43f63878c346f0deff08b27caf0566934ff730337ae4638d072e9a8f296
@staticmethod def _load_ms_info(persons: Dict[(str, str)]) -> pd.DataFrame: 'Load manuscript metadata' df = tamer.deliver_handler_data() df['soup'] = df['content'].apply((lambda x: BeautifulSoup(x, 'xml', from_encoding='utf-8'))) msinfo = df['soup'].apply((lambda x: tamer.get_msinfo(x, persons))) log.info('Loaded MS Info') df = df.join(msinfo) return df
Load manuscript metadata
util/datahandler.py
_load_ms_info
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def _load_ms_info(persons: Dict[(str, str)]) -> pd.DataFrame: df = tamer.deliver_handler_data() df['soup'] = df['content'].apply((lambda x: BeautifulSoup(x, 'xml', from_encoding='utf-8'))) msinfo = df['soup'].apply((lambda x: tamer.get_msinfo(x, persons))) log.info('Loaded MS Info') df = df.join(msinfo) return df
@staticmethod def _load_ms_info(persons: Dict[(str, str)]) -> pd.DataFrame: df = tamer.deliver_handler_data() df['soup'] = df['content'].apply((lambda x: BeautifulSoup(x, 'xml', from_encoding='utf-8'))) msinfo = df['soup'].apply((lambda x: tamer.get_msinfo(x, persons))) log.info('Loaded MS Info') df = df.join(msinfo) return df<|docstring|>Load manuscript metadata<|endoftext|>
6d2d6dd810a692ea9c6169c310120797929f2df2eedc38c9ddeea2e33ec11306
@staticmethod def _load_text_matrix(df: pd.DataFrame) -> pd.DataFrame: 'Load the text-manuscript-matrix' (mss_ids, text_names, coords) = tamer.get_text_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=text_names) return df
Load the text-manuscript-matrix
util/datahandler.py
_load_text_matrix
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def _load_text_matrix(df: pd.DataFrame) -> pd.DataFrame: (mss_ids, text_names, coords) = tamer.get_text_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=text_names) return df
@staticmethod def _load_text_matrix(df: pd.DataFrame) -> pd.DataFrame: (mss_ids, text_names, coords) = tamer.get_text_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=text_names) return df<|docstring|>Load the text-manuscript-matrix<|endoftext|>
3c53287d5e367dc71ec86b4aeccabfd2b35cc18537ebdd6a52e8311e040f7a81
@staticmethod def _load_person_matrix(df: pd.DataFrame) -> pd.DataFrame: 'Load the person-manuscript-matrix' (mss_ids, pers_ids, coords) = tamer.get_person_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=pers_ids) return df
Load the person-manuscript-matrix
util/datahandler.py
_load_person_matrix
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def _load_person_matrix(df: pd.DataFrame) -> pd.DataFrame: (mss_ids, pers_ids, coords) = tamer.get_person_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=pers_ids) return df
@staticmethod def _load_person_matrix(df: pd.DataFrame) -> pd.DataFrame: (mss_ids, pers_ids, coords) = tamer.get_person_mss_matrix_coordinatres(df) (r, c) = map(list, zip(*coords)) row = np.array(r) col = np.array(c) data = np.array(([True] * len(row))) matrix = sparse.coo_matrix((data, (row, col))) df = pd.DataFrame.sparse.from_spmatrix(matrix, index=mss_ids, columns=pers_ids) return df<|docstring|>Load the person-manuscript-matrix<|endoftext|>
9fd1a7744baf7a74c9a0d0e7c273dcc90c554ba5c829ff284e337258f7d6d781
@staticmethod def _load_persons() -> Tuple[(Dict[(str, str)], Dict[(str, List[str])])]: 'Load person data' person_names = tamer.get_person_names() return (person_names, tamer.get_person_names_inverse(person_names))
Load person data
util/datahandler.py
_load_persons
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def _load_persons() -> Tuple[(Dict[(str, str)], Dict[(str, List[str])])]: person_names = tamer.get_person_names() return (person_names, tamer.get_person_names_inverse(person_names))
@staticmethod def _load_persons() -> Tuple[(Dict[(str, str)], Dict[(str, List[str])])]: person_names = tamer.get_person_names() return (person_names, tamer.get_person_names_inverse(person_names))<|docstring|>Load person data<|endoftext|>
04ace5267c0da098e747da19a5dccac3dc8ac3298bd83888e91f3d60fe8f079e
@staticmethod def is_cached() -> bool: 'Check if the data handler should be available from cache.' return os.path.exists(HANDLER_PATH_PICKLE)
Check if the data handler should be available from cache.
util/datahandler.py
is_cached
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@staticmethod def is_cached() -> bool: return os.path.exists(HANDLER_PATH_PICKLE)
@staticmethod def is_cached() -> bool: return os.path.exists(HANDLER_PATH_PICKLE)<|docstring|>Check if the data handler should be available from cache.<|endoftext|>
635e29af5fba53541582b5705be8f3ffdce915f794220f450c10b48c18542f68
@classmethod def get_handler(cls) -> DataHandler: 'Get a DataHandler\n\n Factory method to get a DataHandler object.\n\n Returns:\n DataHandler: A DataHandler, either loaded from cache or created anew.\n ' log.info('Getting DataHandler') res: Optional[DataHandler] = cls._from_pickle() if res: return res log.info('Could not get DataHandler from pickle') res = cls() res._to_pickle() log.info('DataHandler ready.') return res
Get a DataHandler Factory method to get a DataHandler object. Returns: DataHandler: A DataHandler, either loaded from cache or created anew.
util/datahandler.py
get_handler
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
@classmethod def get_handler(cls) -> DataHandler: 'Get a DataHandler\n\n Factory method to get a DataHandler object.\n\n Returns:\n DataHandler: A DataHandler, either loaded from cache or created anew.\n ' log.info('Getting DataHandler') res: Optional[DataHandler] = cls._from_pickle() if res: return res log.info('Could not get DataHandler from pickle') res = cls() res._to_pickle() log.info('DataHandler ready.') return res
@classmethod def get_handler(cls) -> DataHandler: 'Get a DataHandler\n\n Factory method to get a DataHandler object.\n\n Returns:\n DataHandler: A DataHandler, either loaded from cache or created anew.\n ' log.info('Getting DataHandler') res: Optional[DataHandler] = cls._from_pickle() if res: return res log.info('Could not get DataHandler from pickle') res = cls() res._to_pickle() log.info('DataHandler ready.') return res<|docstring|>Get a DataHandler Factory method to get a DataHandler object. Returns: DataHandler: A DataHandler, either loaded from cache or created anew.<|endoftext|>
2f120c3e21fa9911d5daf384b9795fa33a8b845633cc88459685fba9300114d4
def _to_pickle(self) -> None: 'Save the present DataHandler instance as pickle.' log.info('Saving handler to pickle') prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='wb') as file: try: sys.setrecursionlimit((prev * 100)) pickle.dump(self, file) sys.setrecursionlimit(prev) except Exception: log.exception('Failed to pickle the data handler.')
Save the present DataHandler instance as pickle.
util/datahandler.py
_to_pickle
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def _to_pickle(self) -> None: log.info('Saving handler to pickle') prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='wb') as file: try: sys.setrecursionlimit((prev * 100)) pickle.dump(self, file) sys.setrecursionlimit(prev) except Exception: log.exception('Failed to pickle the data handler.')
def _to_pickle(self) -> None: log.info('Saving handler to pickle') prev = sys.getrecursionlimit() with open(HANDLER_PATH_PICKLE, mode='wb') as file: try: sys.setrecursionlimit((prev * 100)) pickle.dump(self, file) sys.setrecursionlimit(prev) except Exception: log.exception('Failed to pickle the data handler.')<|docstring|>Save the present DataHandler instance as pickle.<|endoftext|>
38dd50128cab760b067f2181069cd8f7a485746c30cc430e470d96d705b13c05
def get_all_manuscript_data(self) -> pd.DataFrame: "Get the manuscripts dataframe.\n\n Returns:\n A dataframe containing all manuscripts with their respective metadata.\n\n The dataframe will have the followin structure:\n\n Per row, there will be metadata to one manuscript. The row indices are integers 0..n.\n\n The dataframe contains the following columns:\n\n - 'shelfmark'\n - 'shorttitle'\n - 'country'\n - 'settlement'\n - 'repository'\n - 'origin'\n - 'date'\n - 'Terminus post quem'\n - 'Terminus ante quem'\n - 'meandate'\n - 'yearrange'\n - 'support'\n - 'folio'\n - 'height'\n - 'width'\n - 'extent'\n - 'description'\n - 'creator'\n - 'id'\n - 'full_id'\n - 'filename'\n " return self.manuscripts
Get the manuscripts dataframe. Returns: A dataframe containing all manuscripts with their respective metadata. The dataframe will have the followin structure: Per row, there will be metadata to one manuscript. The row indices are integers 0..n. The dataframe contains the following columns: - 'shelfmark' - 'shorttitle' - 'country' - 'settlement' - 'repository' - 'origin' - 'date' - 'Terminus post quem' - 'Terminus ante quem' - 'meandate' - 'yearrange' - 'support' - 'folio' - 'height' - 'width' - 'extent' - 'description' - 'creator' - 'id' - 'full_id' - 'filename'
util/datahandler.py
get_all_manuscript_data
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def get_all_manuscript_data(self) -> pd.DataFrame: "Get the manuscripts dataframe.\n\n Returns:\n A dataframe containing all manuscripts with their respective metadata.\n\n The dataframe will have the followin structure:\n\n Per row, there will be metadata to one manuscript. The row indices are integers 0..n.\n\n The dataframe contains the following columns:\n\n - 'shelfmark'\n - 'shorttitle'\n - 'country'\n - 'settlement'\n - 'repository'\n - 'origin'\n - 'date'\n - 'Terminus post quem'\n - 'Terminus ante quem'\n - 'meandate'\n - 'yearrange'\n - 'support'\n - 'folio'\n - 'height'\n - 'width'\n - 'extent'\n - 'description'\n - 'creator'\n - 'id'\n - 'full_id'\n - 'filename'\n " return self.manuscripts
def get_all_manuscript_data(self) -> pd.DataFrame: "Get the manuscripts dataframe.\n\n Returns:\n A dataframe containing all manuscripts with their respective metadata.\n\n The dataframe will have the followin structure:\n\n Per row, there will be metadata to one manuscript. The row indices are integers 0..n.\n\n The dataframe contains the following columns:\n\n - 'shelfmark'\n - 'shorttitle'\n - 'country'\n - 'settlement'\n - 'repository'\n - 'origin'\n - 'date'\n - 'Terminus post quem'\n - 'Terminus ante quem'\n - 'meandate'\n - 'yearrange'\n - 'support'\n - 'folio'\n - 'height'\n - 'width'\n - 'extent'\n - 'description'\n - 'creator'\n - 'id'\n - 'full_id'\n - 'filename'\n " return self.manuscripts<|docstring|>Get the manuscripts dataframe. Returns: A dataframe containing all manuscripts with their respective metadata. The dataframe will have the followin structure: Per row, there will be metadata to one manuscript. The row indices are integers 0..n. The dataframe contains the following columns: - 'shelfmark' - 'shorttitle' - 'country' - 'settlement' - 'repository' - 'origin' - 'date' - 'Terminus post quem' - 'Terminus ante quem' - 'meandate' - 'yearrange' - 'support' - 'folio' - 'height' - 'width' - 'extent' - 'description' - 'creator' - 'id' - 'full_id' - 'filename'<|endoftext|>
706c8ecd1185ea741a05df03140e8a7fa1d5cf27079ecb6720392f48815b57c7
def search_manuscript_data(self, full_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, ms_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, shelfmarks: Union[(List[str], pd.Series, pd.DataFrame)]=None, filenames: Union[(List[str], pd.Series, pd.DataFrame)]=None) -> Optional[pd.DataFrame]: 'Search manuscript metadata for certain manuscripts.\n\n Basic search function:\n\n Searches for manuscripts with a certain IDs, and returns the metadata for the respective manuscripts.\n\n IDs can either be full_id (i.e. a certain catalogue entry),\n ms_ids (i.e. a certain manuscript that can have catalogue entries in multiple languages)\n shelfmarks (which will possibly yield multiple results per shelfmark)\n or filenames (refers to the XML files of the catalogue entry).\n\n Note: Exactly one of the four optional parameters should be passed.\n\n Args:\n full_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of catalogue entry IDs. Defaults to None.\n ms_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n shelfmarks (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n filenames (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of XML file names. Defaults to None.\n\n Returns:\n Optional[pd.DataFrame]: A dataframe containing the metadata for the requested manuscripts. \n Returns None if no manuscript was found or if no parameters were passed.\n ' log.info(f'Searching for manuscripts: {full_ids}/{ms_ids}/{filenames}') if (full_ids is not None): if (isinstance(full_ids, list) and full_ids): return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif isinstance(full_ids, pd.DataFrame): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids['full_id'])] elif isinstance(full_ids, pd.Series): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif (ms_ids is not None): if (isinstance(ms_ids, list) and ms_ids): return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif isinstance(ms_ids, pd.DataFrame): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids['id'])] elif isinstance(ms_ids, pd.Series): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif (filenames is not None): if (isinstance(filenames, list) and filenames): return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif isinstance(filenames, pd.DataFrame): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames['filename'])] elif isinstance(filenames, pd.Series): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif (shelfmarks is not None): if (isinstance(shelfmarks, list) and shelfmarks): return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] elif isinstance(shelfmarks, pd.DataFrame): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks['shelfmark'])] elif isinstance(shelfmarks, pd.Series): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] return None
Search manuscript metadata for certain manuscripts. Basic search function: Searches for manuscripts with a certain IDs, and returns the metadata for the respective manuscripts. IDs can either be full_id (i.e. a certain catalogue entry), ms_ids (i.e. a certain manuscript that can have catalogue entries in multiple languages) shelfmarks (which will possibly yield multiple results per shelfmark) or filenames (refers to the XML files of the catalogue entry). Note: Exactly one of the four optional parameters should be passed. Args: full_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of catalogue entry IDs. Defaults to None. ms_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None. shelfmarks (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None. filenames (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of XML file names. Defaults to None. Returns: Optional[pd.DataFrame]: A dataframe containing the metadata for the requested manuscripts. Returns None if no manuscript was found or if no parameters were passed.
util/datahandler.py
search_manuscript_data
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def search_manuscript_data(self, full_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, ms_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, shelfmarks: Union[(List[str], pd.Series, pd.DataFrame)]=None, filenames: Union[(List[str], pd.Series, pd.DataFrame)]=None) -> Optional[pd.DataFrame]: 'Search manuscript metadata for certain manuscripts.\n\n Basic search function:\n\n Searches for manuscripts with a certain IDs, and returns the metadata for the respective manuscripts.\n\n IDs can either be full_id (i.e. a certain catalogue entry),\n ms_ids (i.e. a certain manuscript that can have catalogue entries in multiple languages)\n shelfmarks (which will possibly yield multiple results per shelfmark)\n or filenames (refers to the XML files of the catalogue entry).\n\n Note: Exactly one of the four optional parameters should be passed.\n\n Args:\n full_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of catalogue entry IDs. Defaults to None.\n ms_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n shelfmarks (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n filenames (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of XML file names. Defaults to None.\n\n Returns:\n Optional[pd.DataFrame]: A dataframe containing the metadata for the requested manuscripts. \n Returns None if no manuscript was found or if no parameters were passed.\n ' log.info(f'Searching for manuscripts: {full_ids}/{ms_ids}/{filenames}') if (full_ids is not None): if (isinstance(full_ids, list) and full_ids): return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif isinstance(full_ids, pd.DataFrame): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids['full_id'])] elif isinstance(full_ids, pd.Series): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif (ms_ids is not None): if (isinstance(ms_ids, list) and ms_ids): return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif isinstance(ms_ids, pd.DataFrame): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids['id'])] elif isinstance(ms_ids, pd.Series): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif (filenames is not None): if (isinstance(filenames, list) and filenames): return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif isinstance(filenames, pd.DataFrame): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames['filename'])] elif isinstance(filenames, pd.Series): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif (shelfmarks is not None): if (isinstance(shelfmarks, list) and shelfmarks): return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] elif isinstance(shelfmarks, pd.DataFrame): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks['shelfmark'])] elif isinstance(shelfmarks, pd.Series): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] return None
def search_manuscript_data(self, full_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, ms_ids: Union[(List[str], pd.Series, pd.DataFrame)]=None, shelfmarks: Union[(List[str], pd.Series, pd.DataFrame)]=None, filenames: Union[(List[str], pd.Series, pd.DataFrame)]=None) -> Optional[pd.DataFrame]: 'Search manuscript metadata for certain manuscripts.\n\n Basic search function:\n\n Searches for manuscripts with a certain IDs, and returns the metadata for the respective manuscripts.\n\n IDs can either be full_id (i.e. a certain catalogue entry),\n ms_ids (i.e. a certain manuscript that can have catalogue entries in multiple languages)\n shelfmarks (which will possibly yield multiple results per shelfmark)\n or filenames (refers to the XML files of the catalogue entry).\n\n Note: Exactly one of the four optional parameters should be passed.\n\n Args:\n full_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of catalogue entry IDs. Defaults to None.\n ms_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n shelfmarks (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None.\n filenames (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of XML file names. Defaults to None.\n\n Returns:\n Optional[pd.DataFrame]: A dataframe containing the metadata for the requested manuscripts. \n Returns None if no manuscript was found or if no parameters were passed.\n ' log.info(f'Searching for manuscripts: {full_ids}/{ms_ids}/{filenames}') if (full_ids is not None): if (isinstance(full_ids, list) and full_ids): return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif isinstance(full_ids, pd.DataFrame): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids['full_id'])] elif isinstance(full_ids, pd.Series): if full_ids.empty: return None return self.manuscripts.loc[self.manuscripts['full_id'].isin(full_ids)] elif (ms_ids is not None): if (isinstance(ms_ids, list) and ms_ids): return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif isinstance(ms_ids, pd.DataFrame): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids['id'])] elif isinstance(ms_ids, pd.Series): if ms_ids.empty: return None return self.manuscripts.loc[self.manuscripts['id'].isin(ms_ids)] elif (filenames is not None): if (isinstance(filenames, list) and filenames): return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif isinstance(filenames, pd.DataFrame): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames['filename'])] elif isinstance(filenames, pd.Series): if filenames.empty: return None return self.manuscripts.loc[self.manuscripts['filename'].isin(filenames)] elif (shelfmarks is not None): if (isinstance(shelfmarks, list) and shelfmarks): return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] elif isinstance(shelfmarks, pd.DataFrame): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks['shelfmark'])] elif isinstance(shelfmarks, pd.Series): if shelfmarks.empty: return None return self.manuscripts.loc[self.manuscripts['shelfmark'].isin(shelfmarks)] return None<|docstring|>Search manuscript metadata for certain manuscripts. Basic search function: Searches for manuscripts with a certain IDs, and returns the metadata for the respective manuscripts. IDs can either be full_id (i.e. a certain catalogue entry), ms_ids (i.e. a certain manuscript that can have catalogue entries in multiple languages) shelfmarks (which will possibly yield multiple results per shelfmark) or filenames (refers to the XML files of the catalogue entry). Note: Exactly one of the four optional parameters should be passed. Args: full_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of catalogue entry IDs. Defaults to None. ms_ids (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None. shelfmarks (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of manuscript IDs. Defaults to None. filenames (Union[List[str], pd.Series, pd.DataFrame], optional): List/Series/Dataframe of XML file names. Defaults to None. Returns: Optional[pd.DataFrame]: A dataframe containing the metadata for the requested manuscripts. Returns None if no manuscript was found or if no parameters were passed.<|endoftext|>
7265072406092e578990ebd8f4b472ba3f6e770c46ea90076c2e56ecd60af570
def get_all_texts(self) -> pd.DataFrame: 'return the text-manuscript-matrix' return self.text_matrix
return the text-manuscript-matrix
util/datahandler.py
get_all_texts
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def get_all_texts(self) -> pd.DataFrame: return self.text_matrix
def get_all_texts(self) -> pd.DataFrame: return self.text_matrix<|docstring|>return the text-manuscript-matrix<|endoftext|>
a7308dee9f170df9430e09455b7030e10723f418316cc2c54b84c8eed9f8795f
def search_manuscripts_containing_texts(self, texts: List[str], searchOption: SearchOptions) -> List[str]: 'Search manuscripts containing certain texts\n\n Args:\n texts (List[str]): A list of text names\n searchOption (SearchOption): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of `full_id`s of manuscripts containing either one or all of the passed texts, depending on the chosen searchOption.\n Returns an empty list, if none were found.\n ' log.info(f'Searching for manuscripts with texts: {texts} ({searchOption})') if (not texts): log.debug('Searched texts are empty list') return [] if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] mss = list(df.index) hits += mss res_ = list(set(hits)) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) if (not res): log.info('no manuscripts found') return [] log.info(f'Search result: {res}') return res else: hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] s = set(df.index) hits.append(s) if (not hits): log.info('no manuscripts fond') return [] intersection = set.intersection(*hits) res_ = list(intersection) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) log.info(f'Search result: {res}') return res
Search manuscripts containing certain texts Args: texts (List[str]): A list of text names searchOption (SearchOption): wether to do an AND or an OR search Returns: List[str]: A list of `full_id`s of manuscripts containing either one or all of the passed texts, depending on the chosen searchOption. Returns an empty list, if none were found.
util/datahandler.py
search_manuscripts_containing_texts
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def search_manuscripts_containing_texts(self, texts: List[str], searchOption: SearchOptions) -> List[str]: 'Search manuscripts containing certain texts\n\n Args:\n texts (List[str]): A list of text names\n searchOption (SearchOption): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of `full_id`s of manuscripts containing either one or all of the passed texts, depending on the chosen searchOption.\n Returns an empty list, if none were found.\n ' log.info(f'Searching for manuscripts with texts: {texts} ({searchOption})') if (not texts): log.debug('Searched texts are empty list') return [] if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] mss = list(df.index) hits += mss res_ = list(set(hits)) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) if (not res): log.info('no manuscripts found') return [] log.info(f'Search result: {res}') return res else: hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] s = set(df.index) hits.append(s) if (not hits): log.info('no manuscripts fond') return [] intersection = set.intersection(*hits) res_ = list(intersection) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) log.info(f'Search result: {res}') return res
def search_manuscripts_containing_texts(self, texts: List[str], searchOption: SearchOptions) -> List[str]: 'Search manuscripts containing certain texts\n\n Args:\n texts (List[str]): A list of text names\n searchOption (SearchOption): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of `full_id`s of manuscripts containing either one or all of the passed texts, depending on the chosen searchOption.\n Returns an empty list, if none were found.\n ' log.info(f'Searching for manuscripts with texts: {texts} ({searchOption})') if (not texts): log.debug('Searched texts are empty list') return [] if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] mss = list(df.index) hits += mss res_ = list(set(hits)) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) if (not res): log.info('no manuscripts found') return [] log.info(f'Search result: {res}') return res else: hits = [] for t in texts: df = self.text_matrix[(self.text_matrix[t] == True)] s = set(df.index) hits.append(s) if (not hits): log.info('no manuscripts fond') return [] intersection = set.intersection(*hits) res_ = list(intersection) _res = self.manuscripts[self.manuscripts['full_id'].isin(res_)] res = list(set(_res['shelfmark'].tolist())) log.info(f'Search result: {res}') return res<|docstring|>Search manuscripts containing certain texts Args: texts (List[str]): A list of text names searchOption (SearchOption): wether to do an AND or an OR search Returns: List[str]: A list of `full_id`s of manuscripts containing either one or all of the passed texts, depending on the chosen searchOption. Returns an empty list, if none were found.<|endoftext|>
aeb28acfe25db922a14adfa359b1c3ec54fb1245fd0b62ace4a2b1f572f90aa3
def search_texts_contained_by_manuscripts(self, Inmss: List[str], searchOption: SearchOptions) -> List[str]: 'Search the texts contained by certain manuscripts.\n\n Search for all texts contained by a given number of manuscripts.\n\n Depending on the search option, either the texts appearing in one of the named manuscripts,\n or the texts appearing in all manuscripts will be returned.\n\n Args:\n mss (List[str]): a list of manuscript full_id strings\n searchOption (SearchOptions): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of text names.\n ' log.info(f'Searching for texts contained by manuscripts: {Inmss} ({searchOption})') if (not Inmss): log.debug('Searched for empty list of mss') return [] mss_ = self.manuscripts[self.manuscripts['full_id'].isin(Inmss)] mss = mss_['full_id'].tolist() df = self.text_matrix.transpose() if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for ms in mss: d = df[(df[ms] == True)] mss = list(d.index) hits += mss res = list(set(hits)) if (not res): log.info('no texts found') return [] log.info(f'Search result: {res}') return res else: sets = [] for ms in mss: d = df[(df[ms] == True)] s = set(d.index) sets.append(s) if (not sets): log.info('no texts found') return [] intersection = set.intersection(*sets) res = list(intersection) log.info(f'Search result: {res}') return res
Search the texts contained by certain manuscripts. Search for all texts contained by a given number of manuscripts. Depending on the search option, either the texts appearing in one of the named manuscripts, or the texts appearing in all manuscripts will be returned. Args: mss (List[str]): a list of manuscript full_id strings searchOption (SearchOptions): wether to do an AND or an OR search Returns: List[str]: A list of text names.
util/datahandler.py
search_texts_contained_by_manuscripts
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def search_texts_contained_by_manuscripts(self, Inmss: List[str], searchOption: SearchOptions) -> List[str]: 'Search the texts contained by certain manuscripts.\n\n Search for all texts contained by a given number of manuscripts.\n\n Depending on the search option, either the texts appearing in one of the named manuscripts,\n or the texts appearing in all manuscripts will be returned.\n\n Args:\n mss (List[str]): a list of manuscript full_id strings\n searchOption (SearchOptions): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of text names.\n ' log.info(f'Searching for texts contained by manuscripts: {Inmss} ({searchOption})') if (not Inmss): log.debug('Searched for empty list of mss') return [] mss_ = self.manuscripts[self.manuscripts['full_id'].isin(Inmss)] mss = mss_['full_id'].tolist() df = self.text_matrix.transpose() if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for ms in mss: d = df[(df[ms] == True)] mss = list(d.index) hits += mss res = list(set(hits)) if (not res): log.info('no texts found') return [] log.info(f'Search result: {res}') return res else: sets = [] for ms in mss: d = df[(df[ms] == True)] s = set(d.index) sets.append(s) if (not sets): log.info('no texts found') return [] intersection = set.intersection(*sets) res = list(intersection) log.info(f'Search result: {res}') return res
def search_texts_contained_by_manuscripts(self, Inmss: List[str], searchOption: SearchOptions) -> List[str]: 'Search the texts contained by certain manuscripts.\n\n Search for all texts contained by a given number of manuscripts.\n\n Depending on the search option, either the texts appearing in one of the named manuscripts,\n or the texts appearing in all manuscripts will be returned.\n\n Args:\n mss (List[str]): a list of manuscript full_id strings\n searchOption (SearchOptions): wether to do an AND or an OR search\n\n Returns:\n List[str]: A list of text names.\n ' log.info(f'Searching for texts contained by manuscripts: {Inmss} ({searchOption})') if (not Inmss): log.debug('Searched for empty list of mss') return [] mss_ = self.manuscripts[self.manuscripts['full_id'].isin(Inmss)] mss = mss_['full_id'].tolist() df = self.text_matrix.transpose() if (searchOption == SearchOptions.CONTAINS_ONE): hits = [] for ms in mss: d = df[(df[ms] == True)] mss = list(d.index) hits += mss res = list(set(hits)) if (not res): log.info('no texts found') return [] log.info(f'Search result: {res}') return res else: sets = [] for ms in mss: d = df[(df[ms] == True)] s = set(d.index) sets.append(s) if (not sets): log.info('no texts found') return [] intersection = set.intersection(*sets) res = list(intersection) log.info(f'Search result: {res}') return res<|docstring|>Search the texts contained by certain manuscripts. Search for all texts contained by a given number of manuscripts. Depending on the search option, either the texts appearing in one of the named manuscripts, or the texts appearing in all manuscripts will be returned. Args: mss (List[str]): a list of manuscript full_id strings searchOption (SearchOptions): wether to do an AND or an OR search Returns: List[str]: A list of text names.<|endoftext|>
4c1451d2b649cdd10e63abb93bb856617750dd8efbf5788a99ae8abd2f67681d
def get_person_name(self, pers_id: str) -> str: "Get a person's name, identified by the person's ID" return (self.person_names.get(pers_id) or '')
Get a person's name, identified by the person's ID
util/datahandler.py
get_person_name
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def get_person_name(self, pers_id: str) -> str: return (self.person_names.get(pers_id) or )
def get_person_name(self, pers_id: str) -> str: return (self.person_names.get(pers_id) or )<|docstring|>Get a person's name, identified by the person's ID<|endoftext|>
e1afdec941b4cdf77c2ddf907fcfd85f357b9ee73575a2b5701c2cdd91970783
def get_person_ids(self, pers_name: str) -> List[str]: 'Get IDs of all persons with a certain name' return self.person_names_inverse[pers_name]
Get IDs of all persons with a certain name
util/datahandler.py
get_person_ids
arbeitsgruppe-digitale-altnordistik/Sammlung-Toole
0
python
def get_person_ids(self, pers_name: str) -> List[str]: return self.person_names_inverse[pers_name]
def get_person_ids(self, pers_name: str) -> List[str]: return self.person_names_inverse[pers_name]<|docstring|>Get IDs of all persons with a certain name<|endoftext|>
2de1fe88e2a20d5d05ab776c1b63c1a6c388df29bd794558fb0e2f7dd4ffcf92
def findRelativeRanks(self, nums): '\n :type nums: List[int]\n :rtype: List[str]\n ' l = [] for i in range(len(nums)): l.append((((- 1) * nums[i]), i)) res = ['' for i in range(len(nums))] l.sort() res[l[0][1]] = 'Gold Medal' if (len(l) == 1): return res res[l[1][1]] = 'Silver Medal' if (len(l) == 2): return res res[l[2][1]] = 'Bronze Medal' i = 3 while (i < len(l)): res[l[i][1]] = str((i + 1)) i += 1 return res
:type nums: List[int] :rtype: List[str]
506. Relative Ranks/main.py
findRelativeRanks
Competitive-Programmers-Community/LeetCode
2
python
def findRelativeRanks(self, nums): '\n :type nums: List[int]\n :rtype: List[str]\n ' l = [] for i in range(len(nums)): l.append((((- 1) * nums[i]), i)) res = [ for i in range(len(nums))] l.sort() res[l[0][1]] = 'Gold Medal' if (len(l) == 1): return res res[l[1][1]] = 'Silver Medal' if (len(l) == 2): return res res[l[2][1]] = 'Bronze Medal' i = 3 while (i < len(l)): res[l[i][1]] = str((i + 1)) i += 1 return res
def findRelativeRanks(self, nums): '\n :type nums: List[int]\n :rtype: List[str]\n ' l = [] for i in range(len(nums)): l.append((((- 1) * nums[i]), i)) res = [ for i in range(len(nums))] l.sort() res[l[0][1]] = 'Gold Medal' if (len(l) == 1): return res res[l[1][1]] = 'Silver Medal' if (len(l) == 2): return res res[l[2][1]] = 'Bronze Medal' i = 3 while (i < len(l)): res[l[i][1]] = str((i + 1)) i += 1 return res<|docstring|>:type nums: List[int] :rtype: List[str]<|endoftext|>
94114f4727891da5614e0811a2352ffb11c810fd376e8b73b4a81d8a807a475c
def build_estimator(model_dir, nbuckets, hidden_units): '\n Build an estimator starting from INPUT COLUMNS.\n These include feature transformations and synthetic features.\n The model is a wide-and-deep model.\n ' (dayofweek, hourofday, plat, plon, dlat, dlon, pcount, latdiff, londiff, euclidean) = INPUT_COLUMNS latbuckets = np.linspace(38.0, 42.0, nbuckets).tolist() lonbuckets = np.linspace((- 76.0), (- 72.0), nbuckets).tolist() b_plat = tf.feature_column.bucketized_column(plat, latbuckets) b_dlat = tf.feature_column.bucketized_column(dlat, latbuckets) b_plon = tf.feature_column.bucketized_column(plon, lonbuckets) b_dlon = tf.feature_column.bucketized_column(dlon, lonbuckets) ploc = tf.feature_column.crossed_column([b_plat, b_plon], (nbuckets * nbuckets)) dloc = tf.feature_column.crossed_column([b_dlat, b_dlon], (nbuckets * nbuckets)) pd_pair = tf.feature_column.crossed_column([ploc, dloc], (nbuckets ** 4)) day_hr = tf.feature_column.crossed_column([dayofweek, hourofday], (24 * 7)) wide_columns = [dloc, ploc, pd_pair, day_hr, dayofweek, hourofday, pcount] deep_columns = [tf.feature_column.embedding_column(pd_pair, 10), tf.feature_column.embedding_column(day_hr, 10), plat, plon, dlat, dlon, latdiff, londiff, euclidean] run_config = tf.estimator.RunConfig(save_checkpoints_secs=30, keep_checkpoint_max=3) estimator = tf.estimator.DNNLinearCombinedRegressor(model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=hidden_units, config=run_config) estimator = tf.compat.v1.estimator.add_metrics(estimator, add_eval_metrics) return estimator
Build an estimator starting from INPUT COLUMNS. These include feature transformations and synthetic features. The model is a wide-and-deep model.
courses/machine_learning/feateng/taxifare/trainer/model.py
build_estimator
KayvanShah1/training-data-analyst
6,140
python
def build_estimator(model_dir, nbuckets, hidden_units): '\n Build an estimator starting from INPUT COLUMNS.\n These include feature transformations and synthetic features.\n The model is a wide-and-deep model.\n ' (dayofweek, hourofday, plat, plon, dlat, dlon, pcount, latdiff, londiff, euclidean) = INPUT_COLUMNS latbuckets = np.linspace(38.0, 42.0, nbuckets).tolist() lonbuckets = np.linspace((- 76.0), (- 72.0), nbuckets).tolist() b_plat = tf.feature_column.bucketized_column(plat, latbuckets) b_dlat = tf.feature_column.bucketized_column(dlat, latbuckets) b_plon = tf.feature_column.bucketized_column(plon, lonbuckets) b_dlon = tf.feature_column.bucketized_column(dlon, lonbuckets) ploc = tf.feature_column.crossed_column([b_plat, b_plon], (nbuckets * nbuckets)) dloc = tf.feature_column.crossed_column([b_dlat, b_dlon], (nbuckets * nbuckets)) pd_pair = tf.feature_column.crossed_column([ploc, dloc], (nbuckets ** 4)) day_hr = tf.feature_column.crossed_column([dayofweek, hourofday], (24 * 7)) wide_columns = [dloc, ploc, pd_pair, day_hr, dayofweek, hourofday, pcount] deep_columns = [tf.feature_column.embedding_column(pd_pair, 10), tf.feature_column.embedding_column(day_hr, 10), plat, plon, dlat, dlon, latdiff, londiff, euclidean] run_config = tf.estimator.RunConfig(save_checkpoints_secs=30, keep_checkpoint_max=3) estimator = tf.estimator.DNNLinearCombinedRegressor(model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=hidden_units, config=run_config) estimator = tf.compat.v1.estimator.add_metrics(estimator, add_eval_metrics) return estimator
def build_estimator(model_dir, nbuckets, hidden_units): '\n Build an estimator starting from INPUT COLUMNS.\n These include feature transformations and synthetic features.\n The model is a wide-and-deep model.\n ' (dayofweek, hourofday, plat, plon, dlat, dlon, pcount, latdiff, londiff, euclidean) = INPUT_COLUMNS latbuckets = np.linspace(38.0, 42.0, nbuckets).tolist() lonbuckets = np.linspace((- 76.0), (- 72.0), nbuckets).tolist() b_plat = tf.feature_column.bucketized_column(plat, latbuckets) b_dlat = tf.feature_column.bucketized_column(dlat, latbuckets) b_plon = tf.feature_column.bucketized_column(plon, lonbuckets) b_dlon = tf.feature_column.bucketized_column(dlon, lonbuckets) ploc = tf.feature_column.crossed_column([b_plat, b_plon], (nbuckets * nbuckets)) dloc = tf.feature_column.crossed_column([b_dlat, b_dlon], (nbuckets * nbuckets)) pd_pair = tf.feature_column.crossed_column([ploc, dloc], (nbuckets ** 4)) day_hr = tf.feature_column.crossed_column([dayofweek, hourofday], (24 * 7)) wide_columns = [dloc, ploc, pd_pair, day_hr, dayofweek, hourofday, pcount] deep_columns = [tf.feature_column.embedding_column(pd_pair, 10), tf.feature_column.embedding_column(day_hr, 10), plat, plon, dlat, dlon, latdiff, londiff, euclidean] run_config = tf.estimator.RunConfig(save_checkpoints_secs=30, keep_checkpoint_max=3) estimator = tf.estimator.DNNLinearCombinedRegressor(model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=hidden_units, config=run_config) estimator = tf.compat.v1.estimator.add_metrics(estimator, add_eval_metrics) return estimator<|docstring|>Build an estimator starting from INPUT COLUMNS. These include feature transformations and synthetic features. The model is a wide-and-deep model.<|endoftext|>
3b38b1764cc5d9d1ab95ebf93f23d3a0902f35ab430bc8ca95d8ceef2aa6ae66
def get_proxies(self, user_package_id): '\n Get the list of proxies available based on the user package id\n\n :param user_package_id:\n :return: list of dictionaries containing the keys active, id, ip,\n modified, port_http, port_socks, proxyserver\n ' api_url = self.PROXIES_URL_ENDPOINT_TEMPLATE.format(user_package_id) data = self._get_api_data(api_url) return self._get_proxies_with_correspondent_auth(data)
Get the list of proxies available based on the user package id :param user_package_id: :return: list of dictionaries containing the keys active, id, ip, modified, port_http, port_socks, proxyserver
proxy_bonanza/client.py
get_proxies
victormartinez/python-proxy-bonanza
2
python
def get_proxies(self, user_package_id): '\n Get the list of proxies available based on the user package id\n\n :param user_package_id:\n :return: list of dictionaries containing the keys active, id, ip,\n modified, port_http, port_socks, proxyserver\n ' api_url = self.PROXIES_URL_ENDPOINT_TEMPLATE.format(user_package_id) data = self._get_api_data(api_url) return self._get_proxies_with_correspondent_auth(data)
def get_proxies(self, user_package_id): '\n Get the list of proxies available based on the user package id\n\n :param user_package_id:\n :return: list of dictionaries containing the keys active, id, ip,\n modified, port_http, port_socks, proxyserver\n ' api_url = self.PROXIES_URL_ENDPOINT_TEMPLATE.format(user_package_id) data = self._get_api_data(api_url) return self._get_proxies_with_correspondent_auth(data)<|docstring|>Get the list of proxies available based on the user package id :param user_package_id: :return: list of dictionaries containing the keys active, id, ip, modified, port_http, port_socks, proxyserver<|endoftext|>
d387efb125252bb5b4cc217e3f65b55b3534d7180a702b861fe0bf037b6a9b86
def _get_api_data(self, api_url): "\n Given an endpoint, it requests the API and return the value inside the 'data' key\n\n :param api_url: api endpoint\n :return: dictionary or list of dictionaries that resides in the data key\n " response = requests.get(api_url, headers={'Authorization': self._api_key}) if (not response.ok): response.raise_for_status() content = response.content if isinstance(content, bytes): content = content.decode('utf-8') json_result = json.loads(content) return json_result['data']
Given an endpoint, it requests the API and return the value inside the 'data' key :param api_url: api endpoint :return: dictionary or list of dictionaries that resides in the data key
proxy_bonanza/client.py
_get_api_data
victormartinez/python-proxy-bonanza
2
python
def _get_api_data(self, api_url): "\n Given an endpoint, it requests the API and return the value inside the 'data' key\n\n :param api_url: api endpoint\n :return: dictionary or list of dictionaries that resides in the data key\n " response = requests.get(api_url, headers={'Authorization': self._api_key}) if (not response.ok): response.raise_for_status() content = response.content if isinstance(content, bytes): content = content.decode('utf-8') json_result = json.loads(content) return json_result['data']
def _get_api_data(self, api_url): "\n Given an endpoint, it requests the API and return the value inside the 'data' key\n\n :param api_url: api endpoint\n :return: dictionary or list of dictionaries that resides in the data key\n " response = requests.get(api_url, headers={'Authorization': self._api_key}) if (not response.ok): response.raise_for_status() content = response.content if isinstance(content, bytes): content = content.decode('utf-8') json_result = json.loads(content) return json_result['data']<|docstring|>Given an endpoint, it requests the API and return the value inside the 'data' key :param api_url: api endpoint :return: dictionary or list of dictionaries that resides in the data key<|endoftext|>
9abc79cbd323abc7cc2fac5244b43e7b36f517a0809c7fa44b12046270bd90f4
def sigmoid(xvec): ' Compute the sigmoid function ' if isinstance(xvec, (list, np.ndarray)): xvec[(xvec < (- 100))] = (- 100) elif (xvec < (- 100)): xvec = (- 100) vecsig = (1.0 / (1.0 + np.exp(np.negative(xvec)))) return vecsig
Compute the sigmoid function
data.py
sigmoid
CherylYueWang/ditou-duplicated
1
python
def sigmoid(xvec): ' ' if isinstance(xvec, (list, np.ndarray)): xvec[(xvec < (- 100))] = (- 100) elif (xvec < (- 100)): xvec = (- 100) vecsig = (1.0 / (1.0 + np.exp(np.negative(xvec)))) return vecsig
def sigmoid(xvec): ' ' if isinstance(xvec, (list, np.ndarray)): xvec[(xvec < (- 100))] = (- 100) elif (xvec < (- 100)): xvec = (- 100) vecsig = (1.0 / (1.0 + np.exp(np.negative(xvec)))) return vecsig<|docstring|>Compute the sigmoid function<|endoftext|>
23830d7d348d5a848b403031cd797bc54f7c9471c48cc8fcc9f65d07cee59301
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))
Function that prints all files in the folder. Prints ------ all_files : str Each file separated by `,` in files.
imagemks/rw/folder.py
print_all_files_
SvenPVoigt/ImageMKS
0
python
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))<|docstring|>Function that prints all files in the folder. Prints ------ all_files : str Each file separated by `,` in files.<|endoftext|>
2d2e640c8a435f889d7a1ab1b6fca105f285758611eff0cf418cd597e5b21dfb
def change_mode(self, mode): '\n Function that changes how the reader loads data.\n\n Parameters\n ----------\n mode : str\n ' assert (mode in {'train', 'predict', 'read'}) self.mode = mode
Function that changes how the reader loads data. Parameters ---------- mode : str
imagemks/rw/folder.py
change_mode
SvenPVoigt/ImageMKS
0
python
def change_mode(self, mode): '\n Function that changes how the reader loads data.\n\n Parameters\n ----------\n mode : str\n ' assert (mode in {'train', 'predict', 'read'}) self.mode = mode
def change_mode(self, mode): '\n Function that changes how the reader loads data.\n\n Parameters\n ----------\n mode : str\n ' assert (mode in {'train', 'predict', 'read'}) self.mode = mode<|docstring|>Function that changes how the reader loads data. Parameters ---------- mode : str<|endoftext|>
3b5b79d755a48eb67b9b84b18fdb1d2a86e61bdc3ad7f495bcbf2ccf90a40184
def update_list(self): '\n If any files were added to or removed from the folder, then this\n function should be run to update files that will be loaded.\n\n Updates\n -------\n files : str\n All files in the folder that meet the prefix and ftype rules.\n ' self.files = listdir(folderpath) self.files = list((i for i in self.files if path.isfile(i))) if ftype: self.files = list((i for i in self.files if (i[(- len(self.ftype)):] == self.ftype))) if prefix: self.files = list((i for i in self.files if (i[:len(self.prefix)] == self.prefix))) self.files = sorted(self.files)
If any files were added to or removed from the folder, then this function should be run to update files that will be loaded. Updates ------- files : str All files in the folder that meet the prefix and ftype rules.
imagemks/rw/folder.py
update_list
SvenPVoigt/ImageMKS
0
python
def update_list(self): '\n If any files were added to or removed from the folder, then this\n function should be run to update files that will be loaded.\n\n Updates\n -------\n files : str\n All files in the folder that meet the prefix and ftype rules.\n ' self.files = listdir(folderpath) self.files = list((i for i in self.files if path.isfile(i))) if ftype: self.files = list((i for i in self.files if (i[(- len(self.ftype)):] == self.ftype))) if prefix: self.files = list((i for i in self.files if (i[:len(self.prefix)] == self.prefix))) self.files = sorted(self.files)
def update_list(self): '\n If any files were added to or removed from the folder, then this\n function should be run to update files that will be loaded.\n\n Updates\n -------\n files : str\n All files in the folder that meet the prefix and ftype rules.\n ' self.files = listdir(folderpath) self.files = list((i for i in self.files if path.isfile(i))) if ftype: self.files = list((i for i in self.files if (i[(- len(self.ftype)):] == self.ftype))) if prefix: self.files = list((i for i in self.files if (i[:len(self.prefix)] == self.prefix))) self.files = sorted(self.files)<|docstring|>If any files were added to or removed from the folder, then this function should be run to update files that will be loaded. Updates ------- files : str All files in the folder that meet the prefix and ftype rules.<|endoftext|>
476967142a12ca92130ddbbb9c652e06306fcbaddf2520dd03a086f1bd1629de
def __len__(self): '\n Finds how many files have been written to the folder or are\n currently in the folder\n ' files = listdir(self.path) files = list((i for i in files if path.isfile(path.join(self.path, i)))) if self.ftype: files = list((i for i in files if (i[(- len(self.ftype)):] == self.ftype))) if self.pre: files = list((i for i in files if (i[:len(self.pre)] == self.pre))) return len(files)
Finds how many files have been written to the folder or are currently in the folder
imagemks/rw/folder.py
__len__
SvenPVoigt/ImageMKS
0
python
def __len__(self): '\n Finds how many files have been written to the folder or are\n currently in the folder\n ' files = listdir(self.path) files = list((i for i in files if path.isfile(path.join(self.path, i)))) if self.ftype: files = list((i for i in files if (i[(- len(self.ftype)):] == self.ftype))) if self.pre: files = list((i for i in files if (i[:len(self.pre)] == self.pre))) return len(files)
def __len__(self): '\n Finds how many files have been written to the folder or are\n currently in the folder\n ' files = listdir(self.path) files = list((i for i in files if path.isfile(path.join(self.path, i)))) if self.ftype: files = list((i for i in files if (i[(- len(self.ftype)):] == self.ftype))) if self.pre: files = list((i for i in files if (i[:len(self.pre)] == self.pre))) return len(files)<|docstring|>Finds how many files have been written to the folder or are currently in the folder<|endoftext|>
23830d7d348d5a848b403031cd797bc54f7c9471c48cc8fcc9f65d07cee59301
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))
Function that prints all files in the folder. Prints ------ all_files : str Each file separated by `,` in files.
imagemks/rw/folder.py
print_all_files_
SvenPVoigt/ImageMKS
0
python
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))
def print_all_files_(self): '\n Function that prints all files in the folder.\n\n Prints\n ------\n all_files : str\n Each file separated by `,` in files.\n ' return ('\n' + ', '.join(self.files))<|docstring|>Function that prints all files in the folder. Prints ------ all_files : str Each file separated by `,` in files.<|endoftext|>
ca6cb2dbed2cbc2c94b584981985a5c939c643e8b3337e8e30de88e1dedb2304
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every value from\n the series, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self)).reset_index(drop=True)
:param func: A function to be applied to every value from the series, converted into pandas.DataFrame. :return: A concatenated pandas.DataFrame
pandas_f/__init__.py
map
dair-targ/pandas_f
0
python
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every value from\n the series, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self)).reset_index(drop=True)
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every value from\n the series, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self)).reset_index(drop=True)<|docstring|>:param func: A function to be applied to every value from the series, converted into pandas.DataFrame. :return: A concatenated pandas.DataFrame<|endoftext|>
0ef65ff5b52a05f56310f9c6ebda3bdde416a1c3964e1387ac69a511957b004c
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every row from\n the dataframe, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self))
:param func: A function to be applied to every row from the dataframe, converted into pandas.DataFrame. :return: A concatenated pandas.DataFrame
pandas_f/__init__.py
map
dair-targ/pandas_f
0
python
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every row from\n the dataframe, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self))
def map(self, func: PandasEndofunctor) -> pd.DataFrame: '\n :param func: A function to be applied to every row from\n the dataframe, converted into pandas.DataFrame.\n :return: A concatenated pandas.DataFrame\n ' return pd.concat(map(func, self))<|docstring|>:param func: A function to be applied to every row from the dataframe, converted into pandas.DataFrame. :return: A concatenated pandas.DataFrame<|endoftext|>
95e1a5a5a2f5158864cde2f8ed9734bfdef5b267f83aafcfacf9697317087235
def extend_true(x, LEFT=0, RIGHT=0): 'If a[x]=True, it will make a[x-LEFT+1:x]=True and a[x,x+RIGHT+1]=True as well.\n ' idx = np.where(x)[0] for i in range(1, (LEFT + 1)): ext_ind = (idx - i) ext_ind[(ext_ind < 0)] = 0 x[ext_ind] = True for i in range(1, (RIGHT + 1)): ext_ind = (idx + i) ext_ind[(ext_ind > (len(x) - 1))] = (len(x) - 1) x[ext_ind] = True return x
If a[x]=True, it will make a[x-LEFT+1:x]=True and a[x,x+RIGHT+1]=True as well.
covertrace/utils/array_handling.py
extend_true
braysia/covertrace
1
python
def extend_true(x, LEFT=0, RIGHT=0): '\n ' idx = np.where(x)[0] for i in range(1, (LEFT + 1)): ext_ind = (idx - i) ext_ind[(ext_ind < 0)] = 0 x[ext_ind] = True for i in range(1, (RIGHT + 1)): ext_ind = (idx + i) ext_ind[(ext_ind > (len(x) - 1))] = (len(x) - 1) x[ext_ind] = True return x
def extend_true(x, LEFT=0, RIGHT=0): '\n ' idx = np.where(x)[0] for i in range(1, (LEFT + 1)): ext_ind = (idx - i) ext_ind[(ext_ind < 0)] = 0 x[ext_ind] = True for i in range(1, (RIGHT + 1)): ext_ind = (idx + i) ext_ind[(ext_ind > (len(x) - 1))] = (len(x) - 1) x[ext_ind] = True return x<|docstring|>If a[x]=True, it will make a[x-LEFT+1:x]=True and a[x,x+RIGHT+1]=True as well.<|endoftext|>
0b429fe132325ac7a1a52a7c194df8ea232b8e2dae39e2ccc25c39309bbd9cca
def convertPdfToHtml(uploadedFileUrl, destinationFile): 'Converts PDF To Html using PDF.co Web API' parameters = {} parameters['name'] = os.path.basename(destinationFile) parameters['password'] = Password parameters['pages'] = Pages parameters['simple'] = PlainHtml parameters['columns'] = ColumnLayout parameters['url'] = uploadedFileUrl url = '{}/pdf/convert/to/html'.format(BASE_URL) response = requests.post(url, data=parameters, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): resultFileUrl = json['url'] r = requests.get(resultFileUrl, stream=True) if (r.status_code == 200): with open(destinationFile, 'wb') as file: for chunk in r: file.write(chunk) print(f'Result file saved as "{destinationFile}" file.') else: print(f'Request error: {response.status_code} {response.reason}') else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}')
Converts PDF To Html using PDF.co Web API
PDF.co Web API/PDF To HTML API/Python/Convert PDF To HTML From Uploaded File/ConvertPdfToHtmlFromUploadedFile.py
convertPdfToHtml
bytescout/ByteScout-SDK-SourceCode
24
python
def convertPdfToHtml(uploadedFileUrl, destinationFile): parameters = {} parameters['name'] = os.path.basename(destinationFile) parameters['password'] = Password parameters['pages'] = Pages parameters['simple'] = PlainHtml parameters['columns'] = ColumnLayout parameters['url'] = uploadedFileUrl url = '{}/pdf/convert/to/html'.format(BASE_URL) response = requests.post(url, data=parameters, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): resultFileUrl = json['url'] r = requests.get(resultFileUrl, stream=True) if (r.status_code == 200): with open(destinationFile, 'wb') as file: for chunk in r: file.write(chunk) print(f'Result file saved as "{destinationFile}" file.') else: print(f'Request error: {response.status_code} {response.reason}') else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}')
def convertPdfToHtml(uploadedFileUrl, destinationFile): parameters = {} parameters['name'] = os.path.basename(destinationFile) parameters['password'] = Password parameters['pages'] = Pages parameters['simple'] = PlainHtml parameters['columns'] = ColumnLayout parameters['url'] = uploadedFileUrl url = '{}/pdf/convert/to/html'.format(BASE_URL) response = requests.post(url, data=parameters, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): resultFileUrl = json['url'] r = requests.get(resultFileUrl, stream=True) if (r.status_code == 200): with open(destinationFile, 'wb') as file: for chunk in r: file.write(chunk) print(f'Result file saved as "{destinationFile}" file.') else: print(f'Request error: {response.status_code} {response.reason}') else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}')<|docstring|>Converts PDF To Html using PDF.co Web API<|endoftext|>
5480461b89f7e988585de5bec2aca0027cfea34d2d0b4c66cf75480fc2969b02
def uploadFile(fileName): 'Uploads file to the cloud' url = '{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}'.format(BASE_URL, os.path.basename(fileName)) response = requests.get(url, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): uploadUrl = json['presignedUrl'] uploadedFileUrl = json['url'] with open(fileName, 'rb') as file: requests.put(uploadUrl, data=file, headers={'x-api-key': API_KEY, 'content-type': 'application/octet-stream'}) return uploadedFileUrl else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}') return None
Uploads file to the cloud
PDF.co Web API/PDF To HTML API/Python/Convert PDF To HTML From Uploaded File/ConvertPdfToHtmlFromUploadedFile.py
uploadFile
bytescout/ByteScout-SDK-SourceCode
24
python
def uploadFile(fileName): url = '{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}'.format(BASE_URL, os.path.basename(fileName)) response = requests.get(url, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): uploadUrl = json['presignedUrl'] uploadedFileUrl = json['url'] with open(fileName, 'rb') as file: requests.put(uploadUrl, data=file, headers={'x-api-key': API_KEY, 'content-type': 'application/octet-stream'}) return uploadedFileUrl else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}') return None
def uploadFile(fileName): url = '{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}'.format(BASE_URL, os.path.basename(fileName)) response = requests.get(url, headers={'x-api-key': API_KEY}) if (response.status_code == 200): json = response.json() if (json['error'] == False): uploadUrl = json['presignedUrl'] uploadedFileUrl = json['url'] with open(fileName, 'rb') as file: requests.put(uploadUrl, data=file, headers={'x-api-key': API_KEY, 'content-type': 'application/octet-stream'}) return uploadedFileUrl else: print(json['message']) else: print(f'Request error: {response.status_code} {response.reason}') return None<|docstring|>Uploads file to the cloud<|endoftext|>
ce406b4eff94096dfb2ecbb65104152fb0e6cef2a7a337c56e8036534a67d393
def initdb_command(self): '\n Initialize the Organice database and apps\n ' self.log(_('Initialize database:')) call_command('migrate', verbosity=self.verbosity) self.log(_('Configure site #1 ...')) (site, created) = Site.objects.get_or_create(id=1) (site.name, site.domain) = ('Organice Demo', 'demo.organice.io') site.save()
Initialize the Organice database and apps
organice/management/commands/mixins/initdb.py
initdb_command
bittner/django-organice
34
python
def initdb_command(self): '\n \n ' self.log(_('Initialize database:')) call_command('migrate', verbosity=self.verbosity) self.log(_('Configure site #1 ...')) (site, created) = Site.objects.get_or_create(id=1) (site.name, site.domain) = ('Organice Demo', 'demo.organice.io') site.save()
def initdb_command(self): '\n \n ' self.log(_('Initialize database:')) call_command('migrate', verbosity=self.verbosity) self.log(_('Configure site #1 ...')) (site, created) = Site.objects.get_or_create(id=1) (site.name, site.domain) = ('Organice Demo', 'demo.organice.io') site.save()<|docstring|>Initialize the Organice database and apps<|endoftext|>
6b1b195bf6ec438e0a012e540103ecffed8e2abb922f86820d240ece5dc93fb4
def must_be(value): 'A constraint that the given variable must matches the value.' def inner(var): return (var == value) return inner
A constraint that the given variable must matches the value.
regparser/tree/depth/rules.py
must_be
cgodwin1/regulations-parser
26
python
def must_be(value): def inner(var): return (var == value) return inner
def must_be(value): def inner(var): return (var == value) return inner<|docstring|>A constraint that the given variable must matches the value.<|endoftext|>
cab1b7a098dfa4999e00375f8d5591d4fe345ff14da8c9ae2a1f6de31dd75214
def type_match(marker): 'The type of the associated variable must match its marker. Lambda\n explanation as in the above rule.' return (lambda typ, idx: ((idx < len(typ)) and (typ[idx] == marker)))
The type of the associated variable must match its marker. Lambda explanation as in the above rule.
regparser/tree/depth/rules.py
type_match
cgodwin1/regulations-parser
26
python
def type_match(marker): 'The type of the associated variable must match its marker. Lambda\n explanation as in the above rule.' return (lambda typ, idx: ((idx < len(typ)) and (typ[idx] == marker)))
def type_match(marker): 'The type of the associated variable must match its marker. Lambda\n explanation as in the above rule.' return (lambda typ, idx: ((idx < len(typ)) and (typ[idx] == marker)))<|docstring|>The type of the associated variable must match its marker. Lambda explanation as in the above rule.<|endoftext|>
4d10cec53c62b502b36c73ec986aea33ac742a817752bf302e417794eeb599c0
def marker_stars_markerless_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): '\n When we have the following symmetry:\n a a a\n STARS vs. STARS vs. STARS\n MARKERLESS MARKERLESS MARKERLESS\n\n Prefer the middle\n ' situation = ((pprev_typ not in (markers.markerless, markers.stars)) and (prev_typ == markers.stars) and (typ == markers.markerless) and (pprev_depth > depth)) preferred_solution = (prev_depth == pprev_depth) return ((not situation) or preferred_solution)
When we have the following symmetry: a a a STARS vs. STARS vs. STARS MARKERLESS MARKERLESS MARKERLESS Prefer the middle
regparser/tree/depth/rules.py
marker_stars_markerless_symmetry
cgodwin1/regulations-parser
26
python
def marker_stars_markerless_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): '\n When we have the following symmetry:\n a a a\n STARS vs. STARS vs. STARS\n MARKERLESS MARKERLESS MARKERLESS\n\n Prefer the middle\n ' situation = ((pprev_typ not in (markers.markerless, markers.stars)) and (prev_typ == markers.stars) and (typ == markers.markerless) and (pprev_depth > depth)) preferred_solution = (prev_depth == pprev_depth) return ((not situation) or preferred_solution)
def marker_stars_markerless_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): '\n When we have the following symmetry:\n a a a\n STARS vs. STARS vs. STARS\n MARKERLESS MARKERLESS MARKERLESS\n\n Prefer the middle\n ' situation = ((pprev_typ not in (markers.markerless, markers.stars)) and (prev_typ == markers.stars) and (typ == markers.markerless) and (pprev_depth > depth)) preferred_solution = (prev_depth == pprev_depth) return ((not situation) or preferred_solution)<|docstring|>When we have the following symmetry: a a a STARS vs. STARS vs. STARS MARKERLESS MARKERLESS MARKERLESS Prefer the middle<|endoftext|>
e2fe32c65f32e87e32ac415dff99c94ab05f553800cd4c374cb1ecc3faadbdb0
def markerless_stars_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): "Given MARKERLESS, STARS, MARKERLESS want to break these symmetries:\n\n MARKERLESS MARKERLESS\n STARS vs. STARS\n MARKERLESS MARKERLESS\n\n Here, we don't really care about the distinction, so we'll opt for the\n former." sandwich = ((pprev_typ == typ == markers.markerless) and (prev_typ == markers.stars)) preferred_solution = (prev_depth <= depth) return ((not sandwich) or preferred_solution)
Given MARKERLESS, STARS, MARKERLESS want to break these symmetries: MARKERLESS MARKERLESS STARS vs. STARS MARKERLESS MARKERLESS Here, we don't really care about the distinction, so we'll opt for the former.
regparser/tree/depth/rules.py
markerless_stars_symmetry
cgodwin1/regulations-parser
26
python
def markerless_stars_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): "Given MARKERLESS, STARS, MARKERLESS want to break these symmetries:\n\n MARKERLESS MARKERLESS\n STARS vs. STARS\n MARKERLESS MARKERLESS\n\n Here, we don't really care about the distinction, so we'll opt for the\n former." sandwich = ((pprev_typ == typ == markers.markerless) and (prev_typ == markers.stars)) preferred_solution = (prev_depth <= depth) return ((not sandwich) or preferred_solution)
def markerless_stars_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): "Given MARKERLESS, STARS, MARKERLESS want to break these symmetries:\n\n MARKERLESS MARKERLESS\n STARS vs. STARS\n MARKERLESS MARKERLESS\n\n Here, we don't really care about the distinction, so we'll opt for the\n former." sandwich = ((pprev_typ == typ == markers.markerless) and (prev_typ == markers.stars)) preferred_solution = (prev_depth <= depth) return ((not sandwich) or preferred_solution)<|docstring|>Given MARKERLESS, STARS, MARKERLESS want to break these symmetries: MARKERLESS MARKERLESS STARS vs. STARS MARKERLESS MARKERLESS Here, we don't really care about the distinction, so we'll opt for the former.<|endoftext|>
b822e9cbf0f48ffbcf8dd16d599ee89f0c536c03c4a8d8e307e84c63201c38f1
def star_sandwich_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): 'Symmetry breaking constraint that places STARS tag at specific depth so\n that the resolution of\n\n c\n ? ? ? ? ? ? <- Potential STARS depths\n 5\n\n can only be one of\n OR\n c c\n STARS STARS\n 5 5\n Stars also cannot be used to skip a level (similar to markerless sandwich,\n above)' sandwich = ((pprev_typ != markers.stars) and (typ != markers.stars) and (prev_typ == markers.stars)) unwinding = ((prev_idx == 0) and (pprev_depth > depth)) bad_unwinding = (unwinding and (prev_depth not in (pprev_depth, depth))) inc_depth = ((depth == (prev_depth + 1)) and (prev_depth == (pprev_depth + 1))) return (not (sandwich and (bad_unwinding or inc_depth)))
Symmetry breaking constraint that places STARS tag at specific depth so that the resolution of c ? ? ? ? ? ? <- Potential STARS depths 5 can only be one of OR c c STARS STARS 5 5 Stars also cannot be used to skip a level (similar to markerless sandwich, above)
regparser/tree/depth/rules.py
star_sandwich_symmetry
cgodwin1/regulations-parser
26
python
def star_sandwich_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): 'Symmetry breaking constraint that places STARS tag at specific depth so\n that the resolution of\n\n c\n ? ? ? ? ? ? <- Potential STARS depths\n 5\n\n can only be one of\n OR\n c c\n STARS STARS\n 5 5\n Stars also cannot be used to skip a level (similar to markerless sandwich,\n above)' sandwich = ((pprev_typ != markers.stars) and (typ != markers.stars) and (prev_typ == markers.stars)) unwinding = ((prev_idx == 0) and (pprev_depth > depth)) bad_unwinding = (unwinding and (prev_depth not in (pprev_depth, depth))) inc_depth = ((depth == (prev_depth + 1)) and (prev_depth == (pprev_depth + 1))) return (not (sandwich and (bad_unwinding or inc_depth)))
def star_sandwich_symmetry(pprev_typ, pprev_idx, pprev_depth, prev_typ, prev_idx, prev_depth, typ, idx, depth): 'Symmetry breaking constraint that places STARS tag at specific depth so\n that the resolution of\n\n c\n ? ? ? ? ? ? <- Potential STARS depths\n 5\n\n can only be one of\n OR\n c c\n STARS STARS\n 5 5\n Stars also cannot be used to skip a level (similar to markerless sandwich,\n above)' sandwich = ((pprev_typ != markers.stars) and (typ != markers.stars) and (prev_typ == markers.stars)) unwinding = ((prev_idx == 0) and (pprev_depth > depth)) bad_unwinding = (unwinding and (prev_depth not in (pprev_depth, depth))) inc_depth = ((depth == (prev_depth + 1)) and (prev_depth == (pprev_depth + 1))) return (not (sandwich and (bad_unwinding or inc_depth)))<|docstring|>Symmetry breaking constraint that places STARS tag at specific depth so that the resolution of c ? ? ? ? ? ? <- Potential STARS depths 5 can only be one of OR c c STARS STARS 5 5 Stars also cannot be used to skip a level (similar to markerless sandwich, above)<|endoftext|>
95708c933d2cdae4536c64810b7224645861666f17369cc2a577098524974448
def triplet_tests(*triplet_seq): 'Run propositions around a sequence of three markers. We combine them\n here so that they act as a single constraint' return (star_sandwich_symmetry(*triplet_seq) and marker_stars_markerless_symmetry(*triplet_seq) and markerless_stars_symmetry(*triplet_seq))
Run propositions around a sequence of three markers. We combine them here so that they act as a single constraint
regparser/tree/depth/rules.py
triplet_tests
cgodwin1/regulations-parser
26
python
def triplet_tests(*triplet_seq): 'Run propositions around a sequence of three markers. We combine them\n here so that they act as a single constraint' return (star_sandwich_symmetry(*triplet_seq) and marker_stars_markerless_symmetry(*triplet_seq) and markerless_stars_symmetry(*triplet_seq))
def triplet_tests(*triplet_seq): 'Run propositions around a sequence of three markers. We combine them\n here so that they act as a single constraint' return (star_sandwich_symmetry(*triplet_seq) and marker_stars_markerless_symmetry(*triplet_seq) and markerless_stars_symmetry(*triplet_seq))<|docstring|>Run propositions around a sequence of three markers. We combine them here so that they act as a single constraint<|endoftext|>
cf69c8cf93c7db9a26c842831e5652204b98b2935bb0cf7c022c9750545eb083
def continue_previous_seq(typ, idx, depth, *all_prev): 'Constrain the current marker based on all markers leading up to it' ancestor_markers = ancestors(all_prev) if (depth < (len(ancestor_markers) - 1)): (prev_typ, prev_idx, prev_depth) = ancestor_markers[depth] return pair_rules(prev_typ, prev_idx, prev_depth, typ, idx, depth) else: return True
Constrain the current marker based on all markers leading up to it
regparser/tree/depth/rules.py
continue_previous_seq
cgodwin1/regulations-parser
26
python
def continue_previous_seq(typ, idx, depth, *all_prev): ancestor_markers = ancestors(all_prev) if (depth < (len(ancestor_markers) - 1)): (prev_typ, prev_idx, prev_depth) = ancestor_markers[depth] return pair_rules(prev_typ, prev_idx, prev_depth, typ, idx, depth) else: return True
def continue_previous_seq(typ, idx, depth, *all_prev): ancestor_markers = ancestors(all_prev) if (depth < (len(ancestor_markers) - 1)): (prev_typ, prev_idx, prev_depth) = ancestor_markers[depth] return pair_rules(prev_typ, prev_idx, prev_depth, typ, idx, depth) else: return True<|docstring|>Constrain the current marker based on all markers leading up to it<|endoftext|>
63a9c902a9cf1ef8c9b0445ac68ac7a5b44d38ace77042e1073a4ef24ab18183
def same_parent_same_type(*all_vars): 'All markers in the same parent should have the same marker type.\n Exceptions for:\n STARS, which can appear at any level\n Sequences which _begin_ with markerless paragraphs' elements = [tuple(all_vars[i:(i + 3)]) for i in range(0, len(all_vars), 3)] def per_level(elements, parent_type=None): (level, grouped_children) = _level_and_children(elements) if (not level): return True types = [typ for (typ, idx, depth) in level if (not (typ == markers.stars))] if (parent_type in types): return False last_type = markers.markerless for typ in types: if ((last_type != typ) and (last_type != markers.markerless)): return False last_type = typ for children in grouped_children: if (not per_level(children, (types[0] if types else None))): return False return True return per_level(elements)
All markers in the same parent should have the same marker type. Exceptions for: STARS, which can appear at any level Sequences which _begin_ with markerless paragraphs
regparser/tree/depth/rules.py
same_parent_same_type
cgodwin1/regulations-parser
26
python
def same_parent_same_type(*all_vars): 'All markers in the same parent should have the same marker type.\n Exceptions for:\n STARS, which can appear at any level\n Sequences which _begin_ with markerless paragraphs' elements = [tuple(all_vars[i:(i + 3)]) for i in range(0, len(all_vars), 3)] def per_level(elements, parent_type=None): (level, grouped_children) = _level_and_children(elements) if (not level): return True types = [typ for (typ, idx, depth) in level if (not (typ == markers.stars))] if (parent_type in types): return False last_type = markers.markerless for typ in types: if ((last_type != typ) and (last_type != markers.markerless)): return False last_type = typ for children in grouped_children: if (not per_level(children, (types[0] if types else None))): return False return True return per_level(elements)
def same_parent_same_type(*all_vars): 'All markers in the same parent should have the same marker type.\n Exceptions for:\n STARS, which can appear at any level\n Sequences which _begin_ with markerless paragraphs' elements = [tuple(all_vars[i:(i + 3)]) for i in range(0, len(all_vars), 3)] def per_level(elements, parent_type=None): (level, grouped_children) = _level_and_children(elements) if (not level): return True types = [typ for (typ, idx, depth) in level if (not (typ == markers.stars))] if (parent_type in types): return False last_type = markers.markerless for typ in types: if ((last_type != typ) and (last_type != markers.markerless)): return False last_type = typ for children in grouped_children: if (not per_level(children, (types[0] if types else None))): return False return True return per_level(elements)<|docstring|>All markers in the same parent should have the same marker type. Exceptions for: STARS, which can appear at any level Sequences which _begin_ with markerless paragraphs<|endoftext|>
fb1d26aeab9b4c982f94679699aa4ba1fae6b3ac2ff329120e91f04518e68516
def depth_type_order(order): "Create a function which constrains paragraphs depths to a particular\n type sequence. For example, we know a priori what regtext and\n interpretation markers' order should be. Adding this constrain speeds up\n solution finding." order = list(order) def inner(constrain, all_variables): for i in range(0, (len(all_variables) // 3)): constrain((lambda t, d: ((d < len(order)) and ((t in (markers.stars, order[d])) or (t in order[d])))), (('type' + str(i)), ('depth' + str(i)))) return inner
Create a function which constrains paragraphs depths to a particular type sequence. For example, we know a priori what regtext and interpretation markers' order should be. Adding this constrain speeds up solution finding.
regparser/tree/depth/rules.py
depth_type_order
cgodwin1/regulations-parser
26
python
def depth_type_order(order): "Create a function which constrains paragraphs depths to a particular\n type sequence. For example, we know a priori what regtext and\n interpretation markers' order should be. Adding this constrain speeds up\n solution finding." order = list(order) def inner(constrain, all_variables): for i in range(0, (len(all_variables) // 3)): constrain((lambda t, d: ((d < len(order)) and ((t in (markers.stars, order[d])) or (t in order[d])))), (('type' + str(i)), ('depth' + str(i)))) return inner
def depth_type_order(order): "Create a function which constrains paragraphs depths to a particular\n type sequence. For example, we know a priori what regtext and\n interpretation markers' order should be. Adding this constrain speeds up\n solution finding." order = list(order) def inner(constrain, all_variables): for i in range(0, (len(all_variables) // 3)): constrain((lambda t, d: ((d < len(order)) and ((t in (markers.stars, order[d])) or (t in order[d])))), (('type' + str(i)), ('depth' + str(i)))) return inner<|docstring|>Create a function which constrains paragraphs depths to a particular type sequence. For example, we know a priori what regtext and interpretation markers' order should be. Adding this constrain speeds up solution finding.<|endoftext|>
aadea59e7df44be3899e287ddabbb411e7ba6c9bd57dad1e92d69d6eb82b35db
def ancestors(all_prev): 'Given an assignment of values, construct a list of the relevant\n parents, e.g. 1, i, a, ii, A gives us 1, ii, A' all_prev = [tuple(all_prev[i:(i + 3)]) for i in range(0, len(all_prev), 3)] result = ([None] * 10) for (prev_type, prev_idx, prev_depth) in all_prev: result[prev_depth] = (prev_type, prev_idx, prev_depth) result[(prev_depth + 1):] = ([None] * (10 - prev_depth)) return [r for r in result if r]
Given an assignment of values, construct a list of the relevant parents, e.g. 1, i, a, ii, A gives us 1, ii, A
regparser/tree/depth/rules.py
ancestors
cgodwin1/regulations-parser
26
python
def ancestors(all_prev): 'Given an assignment of values, construct a list of the relevant\n parents, e.g. 1, i, a, ii, A gives us 1, ii, A' all_prev = [tuple(all_prev[i:(i + 3)]) for i in range(0, len(all_prev), 3)] result = ([None] * 10) for (prev_type, prev_idx, prev_depth) in all_prev: result[prev_depth] = (prev_type, prev_idx, prev_depth) result[(prev_depth + 1):] = ([None] * (10 - prev_depth)) return [r for r in result if r]
def ancestors(all_prev): 'Given an assignment of values, construct a list of the relevant\n parents, e.g. 1, i, a, ii, A gives us 1, ii, A' all_prev = [tuple(all_prev[i:(i + 3)]) for i in range(0, len(all_prev), 3)] result = ([None] * 10) for (prev_type, prev_idx, prev_depth) in all_prev: result[prev_depth] = (prev_type, prev_idx, prev_depth) result[(prev_depth + 1):] = ([None] * (10 - prev_depth)) return [r for r in result if r]<|docstring|>Given an assignment of values, construct a list of the relevant parents, e.g. 1, i, a, ii, A gives us 1, ii, A<|endoftext|>
eade9bc8b5f43c1486ead14b3f60425cfd53da9e3c3ba2fc76dd4d1f416d82f7
def _level_and_children(elements): 'Split a list of elements into elements on the current level (i.e.\n that share the same depth as the first element) and segmented children\n (children of each of those elements)' if (not elements): return ([], []) depth = elements[0][2] level = [] grouped_children = [] children = [] for el in elements: if (el[2] == depth): level.append(el) if children: grouped_children.append(children) children = [] else: children.append(el) if children: grouped_children.append(children) return (level, grouped_children)
Split a list of elements into elements on the current level (i.e. that share the same depth as the first element) and segmented children (children of each of those elements)
regparser/tree/depth/rules.py
_level_and_children
cgodwin1/regulations-parser
26
python
def _level_and_children(elements): 'Split a list of elements into elements on the current level (i.e.\n that share the same depth as the first element) and segmented children\n (children of each of those elements)' if (not elements): return ([], []) depth = elements[0][2] level = [] grouped_children = [] children = [] for el in elements: if (el[2] == depth): level.append(el) if children: grouped_children.append(children) children = [] else: children.append(el) if children: grouped_children.append(children) return (level, grouped_children)
def _level_and_children(elements): 'Split a list of elements into elements on the current level (i.e.\n that share the same depth as the first element) and segmented children\n (children of each of those elements)' if (not elements): return ([], []) depth = elements[0][2] level = [] grouped_children = [] children = [] for el in elements: if (el[2] == depth): level.append(el) if children: grouped_children.append(children) children = [] else: children.append(el) if children: grouped_children.append(children) return (level, grouped_children)<|docstring|>Split a list of elements into elements on the current level (i.e. that share the same depth as the first element) and segmented children (children of each of those elements)<|endoftext|>
3bab394704b23313f63f673940bdfa775df8bba57deb2df74f0c27f679c2ec9b
def lookup2xarray(lookups): '\n Convert list of default lookups to xarray.DataSet.\n\n Parameters\n ----------\n lookups (array): Lookup tables (e.g. from make_los_table).\n\n Returns\n -------\n xarray.DataArray: xarray.DataArray with labeled dims and coords.\n ' names = cfg.LUT_NAMES longnames = cfg.LUT_LONGNAMES for (i, lut) in enumerate(lookups): da = np2xr(lut, name=names[i]) da.attrs['long_name'] = longnames[i] if (i == 0): ds = da.to_dataset() else: ds[names[i]] = da return ds
Convert list of default lookups to xarray.DataSet. Parameters ---------- lookups (array): Lookup tables (e.g. from make_los_table). Returns ------- xarray.DataArray: xarray.DataArray with labeled dims and coords.
roughness/helpers.py
lookup2xarray
NAU-PIXEL/roughness
0
python
def lookup2xarray(lookups): '\n Convert list of default lookups to xarray.DataSet.\n\n Parameters\n ----------\n lookups (array): Lookup tables (e.g. from make_los_table).\n\n Returns\n -------\n xarray.DataArray: xarray.DataArray with labeled dims and coords.\n ' names = cfg.LUT_NAMES longnames = cfg.LUT_LONGNAMES for (i, lut) in enumerate(lookups): da = np2xr(lut, name=names[i]) da.attrs['long_name'] = longnames[i] if (i == 0): ds = da.to_dataset() else: ds[names[i]] = da return ds
def lookup2xarray(lookups): '\n Convert list of default lookups to xarray.DataSet.\n\n Parameters\n ----------\n lookups (array): Lookup tables (e.g. from make_los_table).\n\n Returns\n -------\n xarray.DataArray: xarray.DataArray with labeled dims and coords.\n ' names = cfg.LUT_NAMES longnames = cfg.LUT_LONGNAMES for (i, lut) in enumerate(lookups): da = np2xr(lut, name=names[i]) da.attrs['long_name'] = longnames[i] if (i == 0): ds = da.to_dataset() else: ds[names[i]] = da return ds<|docstring|>Convert list of default lookups to xarray.DataSet. Parameters ---------- lookups (array): Lookup tables (e.g. from make_los_table). Returns ------- xarray.DataArray: xarray.DataArray with labeled dims and coords.<|endoftext|>
713a9381bdb40a9197b071d66761a5f9e6d68d203102b99b9e4df481eeddfb23
def np2xr(arr, dims=None, coords=None, name=None, cnames=None, cunits=None): '\n Convert numpy array to xarray.DataArray.\n\n Parameters\n ----------\n array (np.array): Numpy array to convert to xarray.DataArray.\n dims (list of str): Dimensions name of each param (default: index order).\n coords (list of arr): Coordinate arrays of each dim.\n name (str): Name of xarray.DataArray (default: None)\n cnames (list of str): Coordinate names of each param.\n cunits (list of str): Coordinate units of each param (default: deg).\n\n Returns\n -------\n xarray.DataArray\n ' ndims = len(arr.shape) if (dims is None): dims = cfg.LUT_DIMS[:ndims] if (coords is None): coords = get_lookup_coords(*arr.shape)[:ndims] if (cnames is None): cnames = cfg.LUT_DIMS_LONGNAMES[:ndims] if (cunits is None): cunits = (['deg'] * ndims) coords_xr = list(zip(dims, coords)) da = xr.DataArray(arr, coords=coords_xr, name=name) for (i, coord) in enumerate(da.coords): da.coords[coord].attrs['long_name'] = cnames[i] da.coords[coord].attrs['units'] = cunits[i] return da
Convert numpy array to xarray.DataArray. Parameters ---------- array (np.array): Numpy array to convert to xarray.DataArray. dims (list of str): Dimensions name of each param (default: index order). coords (list of arr): Coordinate arrays of each dim. name (str): Name of xarray.DataArray (default: None) cnames (list of str): Coordinate names of each param. cunits (list of str): Coordinate units of each param (default: deg). Returns ------- xarray.DataArray
roughness/helpers.py
np2xr
NAU-PIXEL/roughness
0
python
def np2xr(arr, dims=None, coords=None, name=None, cnames=None, cunits=None): '\n Convert numpy array to xarray.DataArray.\n\n Parameters\n ----------\n array (np.array): Numpy array to convert to xarray.DataArray.\n dims (list of str): Dimensions name of each param (default: index order).\n coords (list of arr): Coordinate arrays of each dim.\n name (str): Name of xarray.DataArray (default: None)\n cnames (list of str): Coordinate names of each param.\n cunits (list of str): Coordinate units of each param (default: deg).\n\n Returns\n -------\n xarray.DataArray\n ' ndims = len(arr.shape) if (dims is None): dims = cfg.LUT_DIMS[:ndims] if (coords is None): coords = get_lookup_coords(*arr.shape)[:ndims] if (cnames is None): cnames = cfg.LUT_DIMS_LONGNAMES[:ndims] if (cunits is None): cunits = (['deg'] * ndims) coords_xr = list(zip(dims, coords)) da = xr.DataArray(arr, coords=coords_xr, name=name) for (i, coord) in enumerate(da.coords): da.coords[coord].attrs['long_name'] = cnames[i] da.coords[coord].attrs['units'] = cunits[i] return da
def np2xr(arr, dims=None, coords=None, name=None, cnames=None, cunits=None): '\n Convert numpy array to xarray.DataArray.\n\n Parameters\n ----------\n array (np.array): Numpy array to convert to xarray.DataArray.\n dims (list of str): Dimensions name of each param (default: index order).\n coords (list of arr): Coordinate arrays of each dim.\n name (str): Name of xarray.DataArray (default: None)\n cnames (list of str): Coordinate names of each param.\n cunits (list of str): Coordinate units of each param (default: deg).\n\n Returns\n -------\n xarray.DataArray\n ' ndims = len(arr.shape) if (dims is None): dims = cfg.LUT_DIMS[:ndims] if (coords is None): coords = get_lookup_coords(*arr.shape)[:ndims] if (cnames is None): cnames = cfg.LUT_DIMS_LONGNAMES[:ndims] if (cunits is None): cunits = (['deg'] * ndims) coords_xr = list(zip(dims, coords)) da = xr.DataArray(arr, coords=coords_xr, name=name) for (i, coord) in enumerate(da.coords): da.coords[coord].attrs['long_name'] = cnames[i] da.coords[coord].attrs['units'] = cunits[i] return da<|docstring|>Convert numpy array to xarray.DataArray. Parameters ---------- array (np.array): Numpy array to convert to xarray.DataArray. dims (list of str): Dimensions name of each param (default: index order). coords (list of arr): Coordinate arrays of each dim. name (str): Name of xarray.DataArray (default: None) cnames (list of str): Coordinate names of each param. cunits (list of str): Coordinate units of each param (default: deg). Returns ------- xarray.DataArray<|endoftext|>
ff6a6e2ab963a35b5c252195d5770b718aebe3eb7533fbb2762e69b63b3a77c1
def wl2xr(arr, units='microns'): 'Return wavelength numpy array as xarray.' da = xr.DataArray(arr, coords=[('wavelength', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavelength' da.coords['wavelength'].attrs['units'] = units return da
Return wavelength numpy array as xarray.
roughness/helpers.py
wl2xr
NAU-PIXEL/roughness
0
python
def wl2xr(arr, units='microns'): da = xr.DataArray(arr, coords=[('wavelength', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavelength' da.coords['wavelength'].attrs['units'] = units return da
def wl2xr(arr, units='microns'): da = xr.DataArray(arr, coords=[('wavelength', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavelength' da.coords['wavelength'].attrs['units'] = units return da<|docstring|>Return wavelength numpy array as xarray.<|endoftext|>
c523f577f4ca9742bfc8b6e727e1d77a50016ccfbdc8e34a2bdbf50af1ef83fa
def wn2xr(arr, units='cm^-1'): 'Return wavenumber numpy array as xarray.' da = xr.DataArray(arr, coords=[('wavenumber', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavenumber' da.coords['wavelength'].attrs['units'] = units return da
Return wavenumber numpy array as xarray.
roughness/helpers.py
wn2xr
NAU-PIXEL/roughness
0
python
def wn2xr(arr, units='cm^-1'): da = xr.DataArray(arr, coords=[('wavenumber', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavenumber' da.coords['wavelength'].attrs['units'] = units return da
def wn2xr(arr, units='cm^-1'): da = xr.DataArray(arr, coords=[('wavenumber', arr)]) da.coords['wavelength'].attrs['long_name'] = 'Wavenumber' da.coords['wavelength'].attrs['units'] = units return da<|docstring|>Return wavenumber numpy array as xarray.<|endoftext|>
0855dd20f784d76eb5b0a63090c06778106256a4df99134cacde97cae12f727d
def get_lookup_coords(nrms=10, ninc=10, naz=36, ntheta=45): '\n Return coordinate arrays corresponding to number of elements in each axis.\n\n Return lookup axes in the following order with ranges:\n rms: [0, 50] degrees\n inc: [0, 90] degrees\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n nrms (int): Number of RMS slopes in [0, 50) degrees.\n ninc (int): Number of incidence angles in [0, 90) degrees.\n naz (int): Number of facet azimuth bins in [0, 360) degrees.\n ntheta (int): Number of facet slope bins in [0, 90) degrees.\n\n Return\n ------\n lookup_coords (tuple of array): Coordinate arrays (rms, cinc, az, theta)\n ' rms_coords = np.linspace(0, 50, nrms, endpoint=False) cinc_coords = np.linspace(1, 0, ninc, endpoint=True) azim_coords = np.linspace(0, 360, naz, endpoint=False) slope_coords = np.linspace(0, 90, ntheta, endpoint=False) inc_coords = np.rad2deg(np.arccos(cinc_coords)) return (rms_coords, inc_coords, azim_coords, slope_coords)
Return coordinate arrays corresponding to number of elements in each axis. Return lookup axes in the following order with ranges: rms: [0, 50] degrees inc: [0, 90] degrees az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- nrms (int): Number of RMS slopes in [0, 50) degrees. ninc (int): Number of incidence angles in [0, 90) degrees. naz (int): Number of facet azimuth bins in [0, 360) degrees. ntheta (int): Number of facet slope bins in [0, 90) degrees. Return ------ lookup_coords (tuple of array): Coordinate arrays (rms, cinc, az, theta)
roughness/helpers.py
get_lookup_coords
NAU-PIXEL/roughness
0
python
def get_lookup_coords(nrms=10, ninc=10, naz=36, ntheta=45): '\n Return coordinate arrays corresponding to number of elements in each axis.\n\n Return lookup axes in the following order with ranges:\n rms: [0, 50] degrees\n inc: [0, 90] degrees\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n nrms (int): Number of RMS slopes in [0, 50) degrees.\n ninc (int): Number of incidence angles in [0, 90) degrees.\n naz (int): Number of facet azimuth bins in [0, 360) degrees.\n ntheta (int): Number of facet slope bins in [0, 90) degrees.\n\n Return\n ------\n lookup_coords (tuple of array): Coordinate arrays (rms, cinc, az, theta)\n ' rms_coords = np.linspace(0, 50, nrms, endpoint=False) cinc_coords = np.linspace(1, 0, ninc, endpoint=True) azim_coords = np.linspace(0, 360, naz, endpoint=False) slope_coords = np.linspace(0, 90, ntheta, endpoint=False) inc_coords = np.rad2deg(np.arccos(cinc_coords)) return (rms_coords, inc_coords, azim_coords, slope_coords)
def get_lookup_coords(nrms=10, ninc=10, naz=36, ntheta=45): '\n Return coordinate arrays corresponding to number of elements in each axis.\n\n Return lookup axes in the following order with ranges:\n rms: [0, 50] degrees\n inc: [0, 90] degrees\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n nrms (int): Number of RMS slopes in [0, 50) degrees.\n ninc (int): Number of incidence angles in [0, 90) degrees.\n naz (int): Number of facet azimuth bins in [0, 360) degrees.\n ntheta (int): Number of facet slope bins in [0, 90) degrees.\n\n Return\n ------\n lookup_coords (tuple of array): Coordinate arrays (rms, cinc, az, theta)\n ' rms_coords = np.linspace(0, 50, nrms, endpoint=False) cinc_coords = np.linspace(1, 0, ninc, endpoint=True) azim_coords = np.linspace(0, 360, naz, endpoint=False) slope_coords = np.linspace(0, 90, ntheta, endpoint=False) inc_coords = np.rad2deg(np.arccos(cinc_coords)) return (rms_coords, inc_coords, azim_coords, slope_coords)<|docstring|>Return coordinate arrays corresponding to number of elements in each axis. Return lookup axes in the following order with ranges: rms: [0, 50] degrees inc: [0, 90] degrees az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- nrms (int): Number of RMS slopes in [0, 50) degrees. ninc (int): Number of incidence angles in [0, 90) degrees. naz (int): Number of facet azimuth bins in [0, 360) degrees. ntheta (int): Number of facet slope bins in [0, 90) degrees. Return ------ lookup_coords (tuple of array): Coordinate arrays (rms, cinc, az, theta)<|endoftext|>
eac0dbfd2e1693f5dc452c1d94906415d42d358f87068238b5048965bcae8154
def facet_grids(los_table, units='degrees'): "\n Return 2D grids of surface facet slope and azimuth angles of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (arr): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Coordinate grids of facet slope and az\n " if isinstance(los_table, xr.DataArray): az_arr = los_table.az.values theta_arr = los_table.theta.values else: (naz, ntheta) = los_table.shape (_, _, az_arr, theta_arr) = get_lookup_coords(naz=naz, ntheta=ntheta) if (units == 'radians'): az_arr = np.radians(az_arr) theta_arr = np.radians(theta_arr) (theta_grid, az_grid) = np.meshgrid(theta_arr, az_arr) if isinstance(los_table, xr.DataArray): theta_grid = (xr.ones_like(los_table) * theta_grid) theta_grid.name = f'theta [{units}]' az_grid = (xr.ones_like(los_table) * az_grid) az_grid.name = f'azimuth [{units}]' return (theta_grid, az_grid)
Return 2D grids of surface facet slope and azimuth angles of los_table. Assumes los_table axes are (az, theta) with ranges: az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- los_table (arr): Line of sight table (dims: az, theta) units (str): Return grids in specified units ('degrees' or 'radians') Return ------ thetas, azs (tuple of 2D array): Coordinate grids of facet slope and az
roughness/helpers.py
facet_grids
NAU-PIXEL/roughness
0
python
def facet_grids(los_table, units='degrees'): "\n Return 2D grids of surface facet slope and azimuth angles of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (arr): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Coordinate grids of facet slope and az\n " if isinstance(los_table, xr.DataArray): az_arr = los_table.az.values theta_arr = los_table.theta.values else: (naz, ntheta) = los_table.shape (_, _, az_arr, theta_arr) = get_lookup_coords(naz=naz, ntheta=ntheta) if (units == 'radians'): az_arr = np.radians(az_arr) theta_arr = np.radians(theta_arr) (theta_grid, az_grid) = np.meshgrid(theta_arr, az_arr) if isinstance(los_table, xr.DataArray): theta_grid = (xr.ones_like(los_table) * theta_grid) theta_grid.name = f'theta [{units}]' az_grid = (xr.ones_like(los_table) * az_grid) az_grid.name = f'azimuth [{units}]' return (theta_grid, az_grid)
def facet_grids(los_table, units='degrees'): "\n Return 2D grids of surface facet slope and azimuth angles of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (arr): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Coordinate grids of facet slope and az\n " if isinstance(los_table, xr.DataArray): az_arr = los_table.az.values theta_arr = los_table.theta.values else: (naz, ntheta) = los_table.shape (_, _, az_arr, theta_arr) = get_lookup_coords(naz=naz, ntheta=ntheta) if (units == 'radians'): az_arr = np.radians(az_arr) theta_arr = np.radians(theta_arr) (theta_grid, az_grid) = np.meshgrid(theta_arr, az_arr) if isinstance(los_table, xr.DataArray): theta_grid = (xr.ones_like(los_table) * theta_grid) theta_grid.name = f'theta [{units}]' az_grid = (xr.ones_like(los_table) * az_grid) az_grid.name = f'azimuth [{units}]' return (theta_grid, az_grid)<|docstring|>Return 2D grids of surface facet slope and azimuth angles of los_table. Assumes los_table axes are (az, theta) with ranges: az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- los_table (arr): Line of sight table (dims: az, theta) units (str): Return grids in specified units ('degrees' or 'radians') Return ------ thetas, azs (tuple of 2D array): Coordinate grids of facet slope and az<|endoftext|>
7a8fe0a10a1fc9b3a7be7b05118b9f088b38f1d88f8001a2ac2372342b0b6210
def get_facet_bins(naz=36, ntheta=45): "\n Return az, theta bin arrays of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (array): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Bin edges of facet slope and az\n " azim_coords = np.linspace(0, 360, (naz + 1)) slope_coords = np.linspace(0, 90, (ntheta + 1)) return (azim_coords, slope_coords)
Return az, theta bin arrays of los_table. Assumes los_table axes are (az, theta) with ranges: az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- los_table (array): Line of sight table (dims: az, theta) units (str): Return grids in specified units ('degrees' or 'radians') Return ------ thetas, azs (tuple of 2D array): Bin edges of facet slope and az
roughness/helpers.py
get_facet_bins
NAU-PIXEL/roughness
0
python
def get_facet_bins(naz=36, ntheta=45): "\n Return az, theta bin arrays of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (array): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Bin edges of facet slope and az\n " azim_coords = np.linspace(0, 360, (naz + 1)) slope_coords = np.linspace(0, 90, (ntheta + 1)) return (azim_coords, slope_coords)
def get_facet_bins(naz=36, ntheta=45): "\n Return az, theta bin arrays of los_table.\n\n Assumes los_table axes are (az, theta) with ranges:\n az: [0, 360] degrees\n theta: [0, 90] degrees\n\n Parameters\n ----------\n los_table (array): Line of sight table (dims: az, theta)\n units (str): Return grids in specified units ('degrees' or 'radians')\n\n Return\n ------\n thetas, azs (tuple of 2D array): Bin edges of facet slope and az\n " azim_coords = np.linspace(0, 360, (naz + 1)) slope_coords = np.linspace(0, 90, (ntheta + 1)) return (azim_coords, slope_coords)<|docstring|>Return az, theta bin arrays of los_table. Assumes los_table axes are (az, theta) with ranges: az: [0, 360] degrees theta: [0, 90] degrees Parameters ---------- los_table (array): Line of sight table (dims: az, theta) units (str): Return grids in specified units ('degrees' or 'radians') Return ------ thetas, azs (tuple of 2D array): Bin edges of facet slope and az<|endoftext|>
c775375bf7971b306a2ca5ae146ad9b29ecb7a8b3b7ef9feea7c87251a290bb7
def rm_regex(dirpath, regex): 'Remove all files matching regex in dirpath.' dirpath = Path(dirpath) for f in dirpath.rglob(regex): f.unlink()
Remove all files matching regex in dirpath.
roughness/helpers.py
rm_regex
NAU-PIXEL/roughness
0
python
def rm_regex(dirpath, regex): dirpath = Path(dirpath) for f in dirpath.rglob(regex): f.unlink()
def rm_regex(dirpath, regex): dirpath = Path(dirpath) for f in dirpath.rglob(regex): f.unlink()<|docstring|>Remove all files matching regex in dirpath.<|endoftext|>
ff57c7fa37ce3aa4225109b86ba01b2946ac02ae2eea1ccbb887b044fb5c9f1b
def fname_with_demsize(filename, demsize): '\n Return filename with demsize appended to the end.\n\n Parameters\n ----------\n fname (str or Path): Filename to append to.\n demsize (int): Length of dem in pixels.\n\n Returns\n -------\n fname_with_demsize (str): New filename with new demsize appended.\n ' filename = Path(filename) return filename.with_name(f'{filename.stem}_s{demsize}{filename.suffix}')
Return filename with demsize appended to the end. Parameters ---------- fname (str or Path): Filename to append to. demsize (int): Length of dem in pixels. Returns ------- fname_with_demsize (str): New filename with new demsize appended.
roughness/helpers.py
fname_with_demsize
NAU-PIXEL/roughness
0
python
def fname_with_demsize(filename, demsize): '\n Return filename with demsize appended to the end.\n\n Parameters\n ----------\n fname (str or Path): Filename to append to.\n demsize (int): Length of dem in pixels.\n\n Returns\n -------\n fname_with_demsize (str): New filename with new demsize appended.\n ' filename = Path(filename) return filename.with_name(f'{filename.stem}_s{demsize}{filename.suffix}')
def fname_with_demsize(filename, demsize): '\n Return filename with demsize appended to the end.\n\n Parameters\n ----------\n fname (str or Path): Filename to append to.\n demsize (int): Length of dem in pixels.\n\n Returns\n -------\n fname_with_demsize (str): New filename with new demsize appended.\n ' filename = Path(filename) return filename.with_name(f'{filename.stem}_s{demsize}{filename.suffix}')<|docstring|>Return filename with demsize appended to the end. Parameters ---------- fname (str or Path): Filename to append to. demsize (int): Length of dem in pixels. Returns ------- fname_with_demsize (str): New filename with new demsize appended.<|endoftext|>
936bbb6089c6f40234f8598b6bb0d01f997e3af38d0259b8047a7b201dd47276
def versions_match(version_a, version_b, precision=2): "\n Check if semantic versions match to precision (default 2).\n\n Examples\n --------\n >>> versions_match('1.0.0', '1.2.3', precision=1)\n True\n >>> versions_match('1.2.0', '1.2.3', precision=2)\n True\n >>> versions_match('1.2.3', '1.2.3', precision=3)\n True\n " va_split = version_a.split('.') vb_split = version_b.split('.') for i in range(precision): if (va_split[i] != vb_split[i]): return False return True
Check if semantic versions match to precision (default 2). Examples -------- >>> versions_match('1.0.0', '1.2.3', precision=1) True >>> versions_match('1.2.0', '1.2.3', precision=2) True >>> versions_match('1.2.3', '1.2.3', precision=3) True
roughness/helpers.py
versions_match
NAU-PIXEL/roughness
0
python
def versions_match(version_a, version_b, precision=2): "\n Check if semantic versions match to precision (default 2).\n\n Examples\n --------\n >>> versions_match('1.0.0', '1.2.3', precision=1)\n True\n >>> versions_match('1.2.0', '1.2.3', precision=2)\n True\n >>> versions_match('1.2.3', '1.2.3', precision=3)\n True\n " va_split = version_a.split('.') vb_split = version_b.split('.') for i in range(precision): if (va_split[i] != vb_split[i]): return False return True
def versions_match(version_a, version_b, precision=2): "\n Check if semantic versions match to precision (default 2).\n\n Examples\n --------\n >>> versions_match('1.0.0', '1.2.3', precision=1)\n True\n >>> versions_match('1.2.0', '1.2.3', precision=2)\n True\n >>> versions_match('1.2.3', '1.2.3', precision=3)\n True\n " va_split = version_a.split('.') vb_split = version_b.split('.') for i in range(precision): if (va_split[i] != vb_split[i]): return False return True<|docstring|>Check if semantic versions match to precision (default 2). Examples -------- >>> versions_match('1.0.0', '1.2.3', precision=1) True >>> versions_match('1.2.0', '1.2.3', precision=2) True >>> versions_match('1.2.3', '1.2.3', precision=3) True<|endoftext|>
05428ac67edf1b5ce0f02625ba4c04dde0376063fed8e3697461a30d8278c459
def check_data_updated(): 'Check if data version is up to date.' data_version = get_data_version() if ((data_version is None) or (not versions_match(data_version, __version__))): print('WARNING: The roughness/data folder is not up to date!') print('Update to the newest lookup tables with -d flag.') return False return True
Check if data version is up to date.
roughness/helpers.py
check_data_updated
NAU-PIXEL/roughness
0
python
def check_data_updated(): data_version = get_data_version() if ((data_version is None) or (not versions_match(data_version, __version__))): print('WARNING: The roughness/data folder is not up to date!') print('Update to the newest lookup tables with -d flag.') return False return True
def check_data_updated(): data_version = get_data_version() if ((data_version is None) or (not versions_match(data_version, __version__))): print('WARNING: The roughness/data folder is not up to date!') print('Update to the newest lookup tables with -d flag.') return False return True<|docstring|>Check if data version is up to date.<|endoftext|>
28e1c452cea7a29e86b75637b2d1600857411569f212bf37352acd0d8c40e1a0
def get_data_version(data_version_file=cfg.FDATA_VERSION): 'Get data version in data/data_version.txt.' data_version = None try: with open(data_version_file, 'r') as f: data_version = f.readline().strip() except FileNotFoundError: pass return data_version
Get data version in data/data_version.txt.
roughness/helpers.py
get_data_version
NAU-PIXEL/roughness
0
python
def get_data_version(data_version_file=cfg.FDATA_VERSION): data_version = None try: with open(data_version_file, 'r') as f: data_version = f.readline().strip() except FileNotFoundError: pass return data_version
def get_data_version(data_version_file=cfg.FDATA_VERSION): data_version = None try: with open(data_version_file, 'r') as f: data_version = f.readline().strip() except FileNotFoundError: pass return data_version<|docstring|>Get data version in data/data_version.txt.<|endoftext|>
392e4ed10f61412f61bfaefb8871103f04fe2a993f325a52914a9fe89eeb036b
def set_data_version(data_version_file=cfg.FDATA_VERSION): 'Set data version in data/data_version.txt.' with open(data_version_file, 'w') as f: f.write(__version__)
Set data version in data/data_version.txt.
roughness/helpers.py
set_data_version
NAU-PIXEL/roughness
0
python
def set_data_version(data_version_file=cfg.FDATA_VERSION): with open(data_version_file, 'w') as f: f.write(__version__)
def set_data_version(data_version_file=cfg.FDATA_VERSION): with open(data_version_file, 'w') as f: f.write(__version__)<|docstring|>Set data version in data/data_version.txt.<|endoftext|>