text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string name="abc_action_bar_home_description">Navigate home</string>
  <string name="abc_action_bar_up_description">Navigate up</string>
  <string name="abc_action_menu_overflow_description">More options</string>
  <string name="abc_action_mode_done">Done</string>
  <string name="abc_activity_chooser_view_see_all">See all</string>
  <string name="abc_activitychooserview_choose_application">Choose an app</string>
  <string name="abc_capital_off">OFF</string>
  <string name="abc_capital_on">ON</string>
  <string name="abc_font_family_body_1_material">sans-serif</string>
  <string name="abc_font_family_body_2_material">sans-serif-medium</string>
  <string name="abc_font_family_button_material">sans-serif-medium</string>
  <string name="abc_font_family_caption_material">sans-serif</string>
  <string name="abc_font_family_display_1_material">sans-serif</string>
  <string name="abc_font_family_display_2_material">sans-serif</string>
  <string name="abc_font_family_display_3_material">sans-serif</string>
  <string name="abc_font_family_display_4_material">sans-serif-light</string>
  <string name="abc_font_family_headline_material">sans-serif</string>
  <string name="abc_font_family_menu_material">sans-serif</string>
  <string name="abc_font_family_subhead_material">sans-serif</string>
  <string name="abc_font_family_title_material">sans-serif-medium</string>
  <string name="abc_search_hint">Search…</string>
  <string name="abc_searchview_description_clear">Clear query</string>
  <string name="abc_searchview_description_query">Search query</string>
  <string name="abc_searchview_description_search">Search</string>
  <string name="abc_searchview_description_submit">Submit query</string>
  <string name="abc_searchview_description_voice">Voice search</string>
  <string name="abc_shareactionprovider_share_with">Share with</string>
  <string name="abc_shareactionprovider_share_with_application">Share with %s</string>
  <string name="abc_toolbar_collapse_description">Collapse</string>
  <string name="accessibility_call_muted">Call muted.</string>
  <string name="accessibility_display_daltonizer_preference_subtitle">This feature is experimental and may affect performance.</string>
  <string name="accessibility_display_daltonizer_preference_title">Color correction</string>
  <string name="accessibility_no_wifi">Wifi disconnected.</string>
  <string name="accessibility_speakerphone_enabled">Speakerphone enabled.</string>
  <string name="accessibility_wifi_off">Wifi off.</string>
  <string name="accessibility_wifi_one_bar">Wifi one bar.</string>
  <string name="accessibility_wifi_security_type_none">Open network</string>
  <string name="accessibility_wifi_security_type_secured">Secure network</string>
  <string name="accessibility_wifi_signal_full">Wifi signal full.</string>
  <string name="accessibility_wifi_three_bars">Wifi three bars.</string>
  <string name="accessibility_wifi_two_bars">Wifi two bars.</string>
  <string name="active_input_method_subtypes">Active input methods</string>
  <string name="adb_keys_warning_message">Revoke access to USB debugging from all computers you've previously authorized?</string>
  <string name="adb_warning_message">USB debugging is intended for development purposes only. Use it to copy data between your computer and your device, install apps on your device without notification, and read log data.</string>
  <string name="adb_warning_title">Allow USB debugging?</string>
  <string name="add_blocked_dialog_body">Block calls and texts from</string>
  <string name="add_blocked_number_hint">Phone number</string>
  <string name="add_vm_number_str">Add number</string>
  <string name="alert_outgoing_call">Placing this call will end your %1$s call.</string>
  <string name="allow_mock_location">Allow mock locations</string>
  <string name="allow_mock_location_summary">Allow mock locations</string>
  <string name="animator_duration_scale_title">Animator duration scale</string>
  <string name="answer_incoming_call">Answer</string>
  <string name="answering_ends_other_call">Answering will end your %1$s call</string>
  <string name="answering_ends_other_calls">Answering will end your %1$s calls</string>
  <string name="answering_ends_other_managed_call">Answering will end your ongoing call</string>
  <string name="answering_ends_other_managed_calls">Answering will end your ongoing calls</string>
  <string name="answering_ends_other_managed_video_call">Answering will end your ongoing video call</string>
  <string name="answering_ends_other_video_call">Answering will end your %1$s video call</string>
  <string name="apn_settings_not_available">Access Point Name settings are not available for this user</string>
  <string name="app_process_limit_title">Background process limit</string>
  <string name="available_via_carrier">Available via %1$s</string>
  <string name="available_via_passpoint">Available via %1$s</string>
  <string name="battery_info_status_charging">Charging</string>
  <string name="battery_info_status_charging_lower">charging</string>
  <string name="battery_info_status_discharging">Not charging</string>
  <string name="battery_info_status_full">Full</string>
  <string name="battery_info_status_not_charging">"Plugged in, can't charge right now"</string>
  <string name="battery_info_status_unknown">Unknown</string>
  <string name="battery_meter_very_low_overlay_symbol">!</string>
  <string name="block_button">Block</string>
  <string name="block_number">Add a number</string>
  <string name="blocked_numbers">Blocked numbers</string>
  <string name="blocked_numbers_block_emergency_number_message">Unable to block emergency number.</string>
  <string name="blocked_numbers_butter_bar_body">After you dial or text an emergency number, blocking is turned off to ensure that emergency services can contact you.</string>
  <string name="blocked_numbers_butter_bar_button">Re-enable now</string>
  <string name="blocked_numbers_butter_bar_title">Blocking temporarily off</string>
  <string name="blocked_numbers_msg">"You won't receive calls or texts from blocked numbers."</string>
  <string name="blocked_numbers_number_already_blocked_message">%1$s is already blocked.</string>
  <string name="blocked_numbers_number_blocked_message">%1$s blocked</string>
  <string name="blocked_numbers_number_unblocked_message">%1$s unblocked</string>
  <string name="bluetooth_a2dp_profile_summary_connected">Connected to media audio</string>
  <string name="bluetooth_a2dp_profile_summary_use_for">Use for media audio</string>
  <string name="bluetooth_connected">Connected</string>
  <string name="bluetooth_connected_battery_level">Connected, battery %1$s</string>
  <string name="bluetooth_connected_no_a2dp">Connected (no media)</string>
  <string name="bluetooth_connected_no_a2dp_battery_level">Connected (no media), battery %1$s</string>
  <string name="bluetooth_connected_no_headset">Connected (no phone)</string>
  <string name="bluetooth_connected_no_headset_battery_level">Connected (no phone), battery %1$s</string>
  <string name="bluetooth_connected_no_headset_no_a2dp">Connected (no phone or media)</string>
  <string name="bluetooth_connected_no_headset_no_a2dp_battery_level">Connected (no phone or media), battery %1$s</string>
  <string name="bluetooth_connected_no_map">Connected (no message access)</string>
  <string name="bluetooth_connecting">Connecting…</string>
  <string name="bluetooth_disable_absolute_volume">Disable absolute volume</string>
  <string name="bluetooth_disable_absolute_volume_summary">Disables the Bluetooth absolute volume feature in case of volume issues with remote devices such as unacceptably loud volume or lack of control.</string>
  <string name="bluetooth_disconnected">Disconnected</string>
  <string name="bluetooth_disconnecting">Disconnecting…</string>
  <string name="bluetooth_dun_profile_summary_connected">Connected to Dun Server</string>
  <string name="bluetooth_dun_profile_summary_use_for">Use for Dial-up Network access</string>
  <string name="bluetooth_enable_inband_ringing">Enable in-band ringing</string>
  <string name="bluetooth_enable_inband_ringing_summary">Allow ringtones on the phone to be played on Bluetooth headsets</string>
  <string name="bluetooth_headset_profile_summary_connected">Connected to phone audio</string>
  <string name="bluetooth_headset_profile_summary_use_for">Use for phone audio</string>
  <string name="bluetooth_hid_profile_summary_connected">Connected to input device</string>
  <string name="bluetooth_hid_profile_summary_use_for">Use for input</string>
  <string name="bluetooth_map_profile_summary_connected">Connected to map</string>
  <string name="bluetooth_map_profile_summary_use_for">Use for map</string>
  <string name="bluetooth_opp_profile_summary_connected">Connected to file transfer server</string>
  <string name="bluetooth_opp_profile_summary_not_connected">Not connected to file transfer server</string>
  <string name="bluetooth_opp_profile_summary_use_for">Use for file transfer</string>
  <string name="bluetooth_pairing">Pairing…</string>
  <string name="bluetooth_pairing_accept">Pair</string>
  <string name="bluetooth_pairing_accept_all_caps">PAIR</string>
  <string name="bluetooth_pairing_decline">Cancel</string>
  <string name="bluetooth_pairing_device_down_error_message">"Can't communicate with %1$s."</string>
  <string name="bluetooth_pairing_error_message">"Couldn't pair with %1$s."</string>
  <string name="bluetooth_pairing_pin_error_message">"Couldn't pair with %1$s because of an incorrect PIN or passkey."</string>
  <string name="bluetooth_pairing_rejected_error_message">Pairing rejected by %1$s.</string>
  <string name="bluetooth_pairing_will_share_phonebook">Pairing grants access to your contacts and call history when connected.</string>
  <string name="bluetooth_pan_nap_profile_summary_connected">Sharing local Internet connection with device</string>
  <string name="bluetooth_pan_profile_summary_use_for">Use for Internet access</string>
  <string name="bluetooth_pan_user_profile_summary_connected">Connected to device for Internet access</string>
  <string name="bluetooth_profile_a2dp">Media audio</string>
  <string name="bluetooth_profile_a2dp_high_quality">HD audio: %1$s</string>
  <string name="bluetooth_profile_a2dp_high_quality_unknown_codec">HD audio</string>
  <string name="bluetooth_profile_dun">Dial-up Network Access</string>
  <string name="bluetooth_profile_headset">Phone calls</string>
  <string name="bluetooth_profile_hid">Input device</string>
  <string name="bluetooth_profile_map">Text Messages</string>
  <string name="bluetooth_profile_opp">File transfer</string>
  <string name="bluetooth_profile_pan">Internet access</string>
  <string name="bluetooth_profile_pan_nap">Internet connection sharing</string>
  <string name="bluetooth_profile_pbap">Contact sharing</string>
  <string name="bluetooth_profile_pbap_summary">Use for contact sharing</string>
  <string name="bluetooth_profile_sap">SIM Access</string>
  <string name="bluetooth_sap_profile_summary_connected">Connected to SAP</string>
  <string name="bluetooth_sap_profile_summary_use_for">Use for SIM access</string>
  <string name="bluetooth_select_a2dp_codec_bits_per_sample">Bluetooth Audio Bits Per Sample</string>
  <string name="bluetooth_select_a2dp_codec_bits_per_sample_dialog_title">"Select Bluetooth Audio Codec:
Bits Per Sample"</string>
  <string name="bluetooth_select_a2dp_codec_channel_mode">Bluetooth Audio Channel Mode</string>
  <string name="bluetooth_select_a2dp_codec_channel_mode_dialog_title">"Select Bluetooth Audio Codec:
Channel Mode"</string>
  <string name="bluetooth_select_a2dp_codec_ldac_playback_quality">Bluetooth Audio LDAC Codec: Playback Quality</string>
  <string name="bluetooth_select_a2dp_codec_ldac_playback_quality_dialog_title">"Select Bluetooth Audio LDAC Codec:
Playback Quality"</string>
  <string name="bluetooth_select_a2dp_codec_sample_rate">Bluetooth Audio Sample Rate</string>
  <string name="bluetooth_select_a2dp_codec_sample_rate_dialog_title">"Select Bluetooth Audio Codec:
Sample Rate"</string>
  <string name="bluetooth_select_a2dp_codec_streaming_label">Streaming: %1$s</string>
  <string name="bluetooth_select_a2dp_codec_type">Bluetooth Audio Codec</string>
  <string name="bluetooth_select_a2dp_codec_type_dialog_title">Select Bluetooth Audio Codec</string>
  <string name="bluetooth_select_avrcp_version_dialog_title">Select Bluetooth AVRCP Version</string>
  <string name="bluetooth_select_avrcp_version_string">Bluetooth AVRCP Version</string>
  <string name="bluetooth_show_devices_without_names">Show Bluetooth devices without names</string>
  <string name="bluetooth_show_devices_without_names_summary">Bluetooth devices without names (MAC addresses only) will be displayed</string>
  <string name="bt_hci_snoop_log">Enable Bluetooth HCI snoop log</string>
  <string name="bt_hci_snoop_log_summary">Capture all bluetooth HCI packets in a file</string>
  <string name="bugreport_in_power">Bug report shortcut</string>
  <string name="bugreport_in_power_summary">Show a button in the power menu for taking a bug report</string>
  <string name="button_convert_fbe">Wipe and convert…</string>
  <string name="callFailed_simError">SIM card error</string>
  <string name="can_not_dial_vt_while_voice_prompt">"Can't make a video call while a voice call is in progress"</string>
  <string name="can_not_dial_while_vt_prompt">"Can't dial while a video call in process"</string>
  <string name="cant_call_due_to_ongoing_call">Call cannot be placed due to your %1$s call.</string>
  <string name="cant_call_due_to_ongoing_calls">Call cannot be placed due to your %1$s calls.</string>
  <string name="cant_call_due_to_ongoing_unknown_call">Call cannot be placed due to a call in another app.</string>
  <string name="category_personal">Personal</string>
  <string name="category_work">Work</string>
  <string name="certinstaller_package">com.android.certinstaller</string>
  <string name="change_default_dialer_dialog_affirmative">Set Default</string>
  <string name="change_default_dialer_dialog_negative">Cancel</string>
  <string name="change_default_dialer_dialog_title">Make %s your default Phone app?</string>
  <string name="change_default_dialer_warning_message">%s will be able to place and control all aspects of calls. Only apps you trust should be set as the default Phone app.</string>
  <string name="charge_length_format">%1$s ago</string>
  <string name="choose_profile">Choose profile</string>
  <string name="clear_adb_keys">Revoke USB debugging authorizations</string>
  <string name="close">Close</string>
  <string name="confirm_enable_oem_unlock_text">WARNING: Device protection features will not work on this device while this setting is turned on.</string>
  <string name="confirm_enable_oem_unlock_title">Allow OEM unlocking?</string>
  <string name="connected_via_carrier">Connected via %1$s</string>
  <string name="connected_via_network_scorer">Automatically connected via %1$s</string>
  <string name="connected_via_network_scorer_default">Automatically connected via network rating provider</string>
  <string name="connected_via_passpoint">Connected via %1$s</string>
  <string name="content_description_menu_button">Menu</string>
  <string name="convert_to_fbe_warning">"Convert data partition to file based encryption.
 !!Warning!! This will erase all your data.
 This feature is alpha, and may not work correctly.
 Press 'Wipe and convert…' to continue."</string>
  <string name="convert_to_file_encryption">Convert to file encryption</string>
  <string name="convert_to_file_encryption_done">Already file encrypted</string>
  <string name="convert_to_file_encryption_enabled">Convert…</string>
  <string name="daltonizer_mode_deuteranomaly">Deuteranomaly (red-green)</string>
  <string name="daltonizer_mode_disabled">Disabled</string>
  <string name="daltonizer_mode_monochromacy">Monochromacy</string>
  <string name="daltonizer_mode_protanomaly">Protanomaly (red-green)</string>
  <string name="daltonizer_mode_tritanomaly">Tritanomaly (blue-yellow)</string>
  <string name="daltonizer_type_overridden">Overridden by %1$s</string>
  <string name="data_usage_uninstalled_apps">Removed apps</string>
  <string name="data_usage_uninstalled_apps_users">Removed apps and users</string>
  <string name="debug_app">Select debug app</string>
  <string name="debug_app_not_set">No debug application set</string>
  <string name="debug_app_set">Debugging application: %1$s</string>
  <string name="debug_applications_category">Apps</string>
  <string name="debug_debugging_category">Debugging</string>
  <string name="debug_drawing_category">Drawing</string>
  <string name="debug_hw_drawing_category">Hardware accelerated rendering</string>
  <string name="debug_hw_overdraw">Debug GPU overdraw</string>
  <string name="debug_hw_renderer">Set GPU Renderer</string>
  <string name="debug_input_category">Input</string>
  <string name="debug_layout">Show layout bounds</string>
  <string name="debug_layout_summary">Show clip bounds, margins, etc.</string>
  <string name="debug_monitoring_category">Monitoring</string>
  <string name="debug_networking_category">Networking</string>
  <string name="debug_view_attributes">Enable view attribute inspection</string>
  <string name="decline_incoming_call">Decline</string>
  <string name="delete_icon_description">Unblock</string>
  <string name="dev_logpersist_clear_warning_message">When we no longer are monitoring with the persistent logger, we are required to erase the logger data resident on your device.</string>
  <string name="dev_logpersist_clear_warning_title">Clear logger persistent storage?</string>
  <string name="dev_settings_warning_message">These settings are intended for development use only. They can cause your device and the applications on it to break or misbehave.</string>
  <string name="dev_settings_warning_title">Allow development settings?</string>
  <string name="development_settings_enable">Enable developer options</string>
  <string name="development_settings_not_available">Developer options are not available for this user</string>
  <string name="development_settings_summary">Set options for app development</string>
  <string name="development_settings_title">Developer options</string>
  <string name="dial_conference_fail_prompt">"Can't dial conference directly because current network doesn't support VoLTE."</string>
  <string name="dial_vt_fail_prompt">"Current network doesn't support VoLTE. Switch to regular voice call?"</string>
  <string name="dialer_default_class">com.android.contacts.activities.TwelveKeyDialer</string>
  <string name="direct_boot_unaware_dialog_message">"Note: After a reboot, this app can't start until you unlock your phone"</string>
  <string name="disable_overlays">Disable HW overlays</string>
  <string name="disable_overlays_summary">Always use GPU for screen compositing</string>
  <string name="disabled">Disabled</string>
  <string name="disabled_by_admin">Disabled by admin</string>
  <string name="disabled_by_admin_summary_text">Controlled by admin</string>
  <string name="duplicate_video_call_not_allowed">Call cannot be added at this time.</string>
  <string name="enable_account_preference_title">Calling accounts</string>
  <string name="enable_adb">USB debugging</string>
  <string name="enable_adb_summary">Debug mode when USB is connected</string>
  <string name="enable_freeform_support">Enable freeform windows</string>
  <string name="enable_freeform_support_summary">Enable support for experimental freeform windows.</string>
  <string name="enable_opengl_traces_title">Enable OpenGL traces</string>
  <string name="enable_terminal_summary">Enable terminal app that offers local shell access</string>
  <string name="enable_terminal_title">Local terminal</string>
  <string name="enabled_by_admin">Enabled by admin</string>
  <string name="external_source_trusted">Allowed</string>
  <string name="external_source_untrusted">Not allowed</string>
  <string name="failed_to_open_app_settings_toast">Failed to open settings for %1$s</string>
  <string name="force_allow_on_external">Force allow apps on external</string>
  <string name="force_allow_on_external_summary">Makes any app eligible to be written to external storage, regardless of manifest values</string>
  <string name="force_hw_ui">Force GPU rendering</string>
  <string name="force_hw_ui_summary">Force use of GPU for 2d drawing</string>
  <string name="force_msaa">Force 4x MSAA</string>
  <string name="force_msaa_summary">Enable 4x MSAA in OpenGL ES 2.0 apps</string>
  <string name="force_resizable_activities">Force activities to be resizable</string>
  <string name="force_resizable_activities_summary">Make all activities resizable for multi-window, regardless of manifest values.</string>
  <string name="force_rtl_layout_all_locales">Force RTL layout direction</string>
  <string name="force_rtl_layout_all_locales_summary">Force screen layout direction to RTL for all locales</string>
  <string name="handle_restricted">RESTRICTED</string>
  <string name="hdcp_checking_dialog_title">Set HDCP checking behavior</string>
  <string name="hdcp_checking_title">HDCP checking</string>
  <string name="help_feedback_label">Help & feedback</string>
  <string name="home">Settings Home</string>
  <string name="ime_security_warning">This input method may be able to collect all the text you type, including personal data like passwords and credit card numbers. It comes from the app %1$s. Use this input method?</string>
  <string name="immediately_destroy_activities">Don't keep activities</string>
  <string name="immediately_destroy_activities_summary">Destroy every activity as soon as the user leaves it</string>
  <string name="inactive_app_active_summary">Active. Tap to toggle.</string>
  <string name="inactive_app_inactive_summary">Inactive. Tap to toggle.</string>
  <string name="inactive_apps_title">Inactive apps</string>
  <string name="incall_default_class">com.android.incallui.InCallServiceImpl</string>
  <string name="incall_error_call_failed">"Couldn't make call."</string>
  <string name="incall_error_power_off">Turn off airplane mode to make a call.</string>
  <string name="incall_error_supp_service_unknown">"This service isn't supported."</string>
  <string name="install_other_apps">Install unknown apps</string>
  <string name="keep_screen_on">Stay awake</string>
  <string name="keep_screen_on_summary">Screen will never sleep while charging</string>
  <string name="launch_defaults_none">No defaults set</string>
  <string name="launch_defaults_some">Some defaults set</string>
  <string name="local_backup_password_summary_change">Tap to change or remove the password for desktop full backups</string>
  <string name="local_backup_password_summary_none">Desktop full backups aren't currently protected</string>
  <string name="local_backup_password_title">Desktop backup password</string>
  <string name="local_backup_password_toast_confirmation_mismatch">New password and confirmation don't match</string>
  <string name="local_backup_password_toast_success">New backup password set</string>
  <string name="local_backup_password_toast_validation_failure">Failure setting backup password</string>
  <string name="managed_user_title">All work apps</string>
  <string name="media_category">Media</string>
  <string name="mobile_data_always_on">Mobile data always active</string>
  <string name="mobile_data_always_on_summary">Always keep mobile data active, even when WLAN is active (for fast network switching).</string>
  <string name="mock_location_app">Select mock location app</string>
  <string name="mock_location_app_not_set">No mock location app set</string>
  <string name="mock_location_app_set">Mock location app: %1$s</string>
  <string name="no_application">Nothing</string>
  <string name="no_vm_number">Missing voicemail number</string>
  <string name="no_vm_number_msg">No voicemail number is stored on the SIM card.</string>
  <string name="non_primary_user">Only the device owner can view and manage blocked numbers.</string>
  <string name="notification_AllMissedCallTitle">All missed calls</string>
  <string name="notification_channel_incoming_call">Incoming calls</string>
  <string name="notification_channel_missed_call">Missed calls</string>
  <string name="notification_incoming_call">%1$s call from %2$s</string>
  <string name="notification_incoming_video_call">%1$s video call from %2$s</string>
  <string name="notification_missedCallTicker">Missed call from %s</string>
  <string name="notification_missedCallTitle">Missed call</string>
  <string name="notification_missedCall_call_back">Call back</string>
  <string name="notification_missedCall_call_back_miui">Call</string>
  <string name="notification_missedCall_message">Message</string>
  <string name="notification_missedCallsMsg">%s missed calls</string>
  <string name="notification_missedCallsTitle">Missed calls</string>
  <string name="notification_missedWorkCallTitle">Missed work call</string>
  <string name="oem_preferred_feedback_reporter"/>
  <string name="oem_unlock_enable">OEM unlocking</string>
  <string name="oem_unlock_enable_summary">Allow the bootloader to be unlocked</string>
  <string name="outgoing_call_error_no_phone_number_supplied">To place a call, enter a valid number.</string>
  <string name="outgoing_call_not_allowed_no_permission">This application cannot make outgoing calls without the Phone permission.</string>
  <string name="outgoing_call_not_allowed_user_restriction">Only emergency calls are allowed.</string>
  <string name="overlay_display_devices_title">Simulate secondary displays</string>
  <string name="picture_color_mode">Picture color mode</string>
  <string name="picture_color_mode_desc">Use sRGB</string>
  <string name="pointer_location">Pointer location</string>
  <string name="pointer_location_summary">Screen overlay showing current touch data</string>
  <string name="power_charging">%1$s - %2$s</string>
  <string name="power_charging_duration">^1 - ^2 until fully charged</string>
  <string name="power_discharging_duration">^1 - about ^2 left</string>
  <string name="power_discharging_duration_enhanced">^1 - about ^2 left based on your usage</string>
  <string name="power_discharging_duration_short">^1 - ^2 left</string>
  <string name="power_remaining_charging_duration_only">^1 left until fully charged</string>
  <string name="power_remaining_duration_only">About ^1 left</string>
  <string name="power_remaining_duration_only_enhanced">About ^1 left based on your usage</string>
  <string name="power_remaining_duration_only_short">^1 left</string>
  <string name="power_remaining_duration_only_short_enhanced">^1 left based on your usage</string>
  <string name="preference_summary_default_combination">%1$s / %2$s</string>
  <string name="process_kernel_label">Android OS</string>
  <string name="proxy_exclusionlist_hint">example.com,mycomp.test.com,localhost</string>
  <string name="proxy_hostname_hint">proxy.example.com</string>
  <string name="proxy_port_hint">8080</string>
  <string name="proxy_url_hint">https://www.example.com/proxy.pac</string>
  <string name="remaining_length_format">%1$s left</string>
  <string name="respond_via_sms_canned_response_1">"Can't talk now. What's up?"</string>
  <string name="respond_via_sms_canned_response_2">"I'll call you right back."</string>
  <string name="respond_via_sms_canned_response_3">"I'll call you later."</string>
  <string name="respond_via_sms_canned_response_4">"Can't talk now. Call me later?"</string>
  <string name="respond_via_sms_confirmation_format">Message sent to %s.</string>
  <string name="respond_via_sms_edittext_dialog_title">Quick response</string>
  <string name="respond_via_sms_setting_summary"/>
  <string name="respond_via_sms_setting_title">Quick responses</string>
  <string name="respond_via_sms_setting_title_2">Edit quick responses</string>
  <string name="retail_demo_reset_message">Enter password to perform factory reset in demo mode</string>
  <string name="retail_demo_reset_next">Next</string>
  <string name="retail_demo_reset_title">Password required</string>
  <string name="running_process_item_user_label">User: %1$s</string>
  <string name="runningservices_settings_summary">View and control currently running services</string>
  <string name="runningservices_settings_title">Running services</string>
  <string name="saved_network">Saved by %1$s</string>
  <string name="screen_zoom_summary_custom">Custom (%d)</string>
  <string name="screen_zoom_summary_default">Default</string>
  <string name="screen_zoom_summary_extremely_large">Largest</string>
  <string name="screen_zoom_summary_large">Large</string>
  <string name="screen_zoom_summary_small">Small</string>
  <string name="screen_zoom_summary_very_large">Larger</string>
  <string name="search_menu_title">Search</string>
  <string name="select_application">Select application</string>
  <string name="select_logd_size_dialog_title">Select Logger sizes per log buffer</string>
  <string name="select_logd_size_title">Logger buffer sizes</string>
  <string name="select_logpersist_dialog_title">Select log buffers to store persistently on device</string>
  <string name="select_logpersist_title">Store logger data persistently on device</string>
  <string name="select_usb_configuration_dialog_title">Select USB Configuration</string>
  <string name="select_usb_configuration_title">Select USB Configuration</string>
  <string name="select_webview_provider_dialog_title">Set WebView implementation</string>
  <string name="select_webview_provider_title">WebView implementation</string>
  <string name="select_webview_provider_toast_text">This choice is no longer valid. Try again.</string>
  <string name="settings_package">com.android.settings</string>
  <string name="show_all_anrs">Show all ANRs</string>
  <string name="show_all_anrs_summary">Show App Not Responding dialog for background apps</string>
  <string name="show_hw_layers_updates">Show hardware layers updates</string>
  <string name="show_hw_layers_updates_summary">Flash hardware layers green when they update</string>
  <string name="show_hw_screen_updates">Show GPU view updates</string>
  <string name="show_hw_screen_updates_summary">Flash views inside windows when drawn with the GPU</string>
  <string name="show_non_rect_clip">Debug non-rectangular clip operations</string>
  <string name="show_notification_channel_warnings">Show notification channel warnings</string>
  <string name="show_notification_channel_warnings_summary">Displays on-screen warning when an app posts a notification without a valid channel</string>
  <string name="show_screen_updates">Show surface updates</string>
  <string name="show_screen_updates_summary">Flash entire window surfaces when they update</string>
  <string name="show_touches">Show taps</string>
  <string name="show_touches_summary">Show visual feedback for taps</string>
  <string name="simulate_color_space">Simulate color space</string>
  <string name="speed_label_fast">Fast</string>
  <string name="speed_label_medium">Medium</string>
  <string name="speed_label_okay">OK</string>
  <string name="speed_label_slow">Slow</string>
  <string name="speed_label_very_fast">Very Fast</string>
  <string name="speed_label_very_slow">Very Slow</string>
  <string name="strict_mode">Strict mode enabled</string>
  <string name="strict_mode_summary">Flash screen when apps do long operations on main thread</string>
  <string name="telecommAppLabel">Call Management</string>
  <string name="telephony_monitor_switch">Telephony Monitor</string>
  <string name="telephony_monitor_switch_summary">TelephonyMonitor will collect logs when it detects a problem with telephony/modem functionality and prompt notification to user to file a bug</string>
  <string name="test_account_0_label">Q Mobile</string>
  <string name="test_account_0_short_description">Account with Q Mobile</string>
  <string name="test_account_1_label">Market Wireless</string>
  <string name="test_account_1_short_description">Account with Market Wireless</string>
  <string name="test_account_2_label">Sonoma Circles Talk Plus</string>
  <string name="test_account_2_short_description">Talk to everyone in your Circles!</string>
  <string name="test_account_3_label">Bay Voice Chat Pro</string>
  <string name="test_account_3_short_description">Chat with Chat Network users</string>
  <string name="tether_settings_title_all">Tethering & portable hotspot</string>
  <string name="tether_settings_title_bluetooth">Bluetooth tethering</string>
  <string name="tether_settings_title_usb">USB tethering</string>
  <string name="tether_settings_title_usb_bluetooth">Tethering</string>
  <string name="tether_settings_title_wifi">Portable hotspot</string>
  <string name="tethering_hardware_offload">Tethering hardware acceleration</string>
  <string name="tethering_hardware_offload_summary">Use tethering hardware acceleration if available</string>
  <string name="tethering_settings_not_available">Tethering settings are not available for this user</string>
  <string name="title_convert_fbe">Converting to file based encryption</string>
  <string name="toast_personal_call_msg">Using the personal dialer to make the call</string>
  <string name="track_frame_time">Profile GPU rendering</string>
  <string name="transition_animation_scale_title">Transition animation scale</string>
  <string name="tts_default_lang_summary">Sets the language-specific voice for the spoken text</string>
  <string name="tts_default_lang_title">Language</string>
  <string name="tts_default_pitch_summary">Affects the tone of the synthesized speech</string>
  <string name="tts_default_pitch_title">Pitch</string>
  <string name="tts_default_rate_summary">Speed at which the text is spoken</string>
  <string name="tts_default_rate_title">Speech rate</string>
  <string name="tts_default_sample_string">This is an example of speech synthesis</string>
  <string name="tts_engine_network_required">This language requires a working network connection for text-to-speech output.</string>
  <string name="tts_engine_preference_section_title">Preferred engine</string>
  <string name="tts_engine_security_warning">This speech synthesis engine may be able to collect all the text that will be spoken, including personal data like passwords and credit card numbers. It comes from the %s engine. Enable the use of this speech synthesis engine?</string>
  <string name="tts_engine_settings_button">Launch engine settings</string>
  <string name="tts_engine_settings_title">Settings for %s</string>
  <string name="tts_general_section_title">General</string>
  <string name="tts_install_data_summary">Install the voice data required for speech synthesis</string>
  <string name="tts_install_data_title">Install voice data</string>
  <string name="tts_lang_not_selected">Language not selected</string>
  <string name="tts_lang_use_system">Use system language</string>
  <string name="tts_play_example_summary">Play a short demonstration of speech synthesis</string>
  <string name="tts_play_example_title">Listen to an example</string>
  <string name="tts_reset_speech_pitch_summary">Reset the pitch at which the text is spoken to default.</string>
  <string name="tts_reset_speech_pitch_title">Reset speech pitch</string>
  <string name="tts_settings">Text-to-speech settings</string>
  <string name="tts_settings_title">Text-to-speech output</string>
  <string name="tts_status_checking">Checking…</string>
  <string name="tts_status_not_supported">%1$s is not supported</string>
  <string name="tts_status_ok">%1$s is fully supported</string>
  <string name="tts_status_requires_network">%1$s requires network connection</string>
  <string name="tts_status_title">Default language status</string>
  <string name="ui_default_package">com.android.incallui</string>
  <string name="ui_default_package_dialer">com.android.contacts</string>
  <string name="unblock_button">Unblock</string>
  <string name="unblock_dialog_body">Unblock %1$s?</string>
  <string name="unknown">Unknown</string>
  <string name="usb_audio_disable_routing">Disable USB audio routing</string>
  <string name="usb_audio_disable_routing_summary">Disable automatic routing to USB audio peripherals</string>
  <string name="use_system_language_to_select_input_method_subtypes">Use system languages</string>
  <string name="userCallActivityLabel">Phone</string>
  <string name="user_guest">Guest</string>
  <string name="v7_preference_off">OFF</string>
  <string name="v7_preference_on">ON</string>
  <string name="verify_apps_over_usb_summary">Check apps installed via ADB/ADT for harmful behavior.</string>
  <string name="verify_apps_over_usb_title">Verify apps over USB</string>
  <string name="voice_dial_out">Voice call</string>
  <string name="voice_report_incoming_call">Incoming call</string>
  <string name="voice_report_unknown_num">Unknown number</string>
  <string name="vpn_settings_not_available">VPN settings are not available for this user</string>
  <string name="wait_for_debugger">Wait for debugger</string>
  <string name="wait_for_debugger_summary">Debugged application waits for debugger to attach before executing</string>
  <string name="wapi_all_sel_mode">Select mode</string>
  <string name="wapi_auto_sel_cert_fail">Can not select certificate automatically. Please select a certificate from the list, and then try to connect.</string>
  <string name="wapi_cert_is_not_exist">No available certificate, please install the certificate first</string>
  <string name="wapi_cert_is_not_selected">Please select the certificate first</string>
  <string name="wapi_cert_manage_error">Faild to setting the WAPI certificate.</string>
  <string name="wapi_cert_manage_summary">Add or delete the WAPI certificate</string>
  <string name="wapi_cert_manage_title">WAPI certificate management</string>
  <string name="wapi_cert_roaming">Connecting…</string>
  <string name="wapi_no">no</string>
  <string name="wapi_no_vaild_cert">No available certificates, install it now?</string>
  <string name="wapi_password_hex_format_add">The count of hexadecimal characters can not be odd number</string>
  <string name="wapi_password_is_empty">Password field can not be left blank</string>
  <string name="wapi_password_is_not_hex_format">Invalid hexadecimal characters</string>
  <string name="wapi_password_length_is_max">Password can not exceed 64 characters in length</string>
  <string name="wapi_password_length_is_min">Password can not less than 8 characters in length</string>
  <string name="wapi_password_length_is_min_to_max">The password must be: 8-64 characters</string>
  <string name="wapi_yes">yes</string>
  <string name="wifi_aggressive_handover">Aggressive WLAN to mobile handover</string>
  <string name="wifi_aggressive_handover_summary">When enabled, WLAN will be more aggressive in handing over the data connection to mobile, when WLAN signal is low</string>
  <string name="wifi_allow_scan_with_traffic">Always allow WLAN Roam Scans</string>
  <string name="wifi_allow_scan_with_traffic_summary">Allow/Disallow WLAN Roam Scans based on the amount of data traffic present at the interface</string>
  <string name="wifi_ap_unable_to_handle_new_sta">Access point temporarily full</string>
  <string name="wifi_auth_password_wrong">Password may be incorrect</string>
  <string name="wifi_auto_sel_wapi_cert">Select automatically</string>
  <string name="wifi_cant_connect">"Can't connect"</string>
  <string name="wifi_cant_connect_to_ap">"Can't connect to '%1$s'"</string>
  <string name="wifi_check_password_try_again">Check password and try again</string>
  <string name="wifi_connected_no_internet">Connected, no Internet</string>
  <string name="wifi_disabled_by_recommendation_provider">Not connected due to low quality network</string>
  <string name="wifi_disabled_generic">Disabled</string>
  <string name="wifi_disabled_network_failure">IP Configuration Failure</string>
  <string name="wifi_disabled_password_failure">Authentication problem</string>
  <string name="wifi_disabled_wifi_failure">WLAN Connection Failure</string>
  <string name="wifi_display_certification">Wireless display certification</string>
  <string name="wifi_display_certification_summary">Show options for wireless display certification</string>
  <string name="wifi_dns1_hint">8.8.8.8</string>
  <string name="wifi_dns2_hint">8.8.4.4</string>
  <string name="wifi_fail_to_scan">"Can't scan for networks"</string>
  <string name="wifi_gateway_hint">192.168.1.1</string>
  <string name="wifi_hand_sel_wapi_cert">WAPI certificate</string>
  <string name="wifi_ip_address_hint">192.168.1.128</string>
  <string name="wifi_network_prefix_length_hint">24</string>
  <string name="wifi_no_internet">No Internet access</string>
  <string name="wifi_no_internet_no_reconnect">"Won't automatically connect"</string>
  <string name="wifi_not_in_range">Not in range</string>
  <string name="wifi_p2p_allow_passive_listen">Allow WLAN P2p Passive Listen</string>
  <string name="wifi_p2p_allow_passive_listen_summary">Allow/Disallow WLAN P2p passive listen, the device can not scan other devices, but other devices can scan the current device</string>
  <string name="wifi_remembered">Saved</string>
  <string name="wifi_security_eap">802.1x EAP</string>
  <string name="wifi_security_none">None</string>
  <string name="wifi_security_passpoint">Passpoint</string>
  <string name="wifi_security_psk_generic">@string/wifi_security_wpa_wpa2</string>
  <string name="wifi_security_short_eap">802.1x</string>
  <string name="wifi_security_short_psk_generic">@string/wifi_security_short_wpa_wpa2</string>
  <string name="wifi_security_short_wep">WEP</string>
  <string name="wifi_security_short_wpa">WPA</string>
  <string name="wifi_security_short_wpa2">WPA2</string>
  <string name="wifi_security_short_wpa_wpa2">WPA/WPA2</string>
  <string name="wifi_security_wapi_cert">WAPI-Cert</string>
  <string name="wifi_security_wapi_psk">WAPI-PSK</string>
  <string name="wifi_security_wapi_psk_ascii">ASCII</string>
  <string name="wifi_security_wapi_psk_hexadecimal">Hexadecimal</string>
  <string name="wifi_security_wep">WEP</string>
  <string name="wifi_security_wpa">WPA PSK</string>
  <string name="wifi_security_wpa2">WPA2 PSK</string>
  <string name="wifi_security_wpa_wpa2">WPA/WPA2 PSK</string>
  <string name="wifi_ssid_is_empty">Ssid field can not be left blank</string>
  <string name="wifi_ssid_length_is_max">Ssid can not exceed 32 characters in length</string>
  <string name="wifi_verbose_logging">Enable WLAN Verbose Logging</string>
  <string name="wifi_verbose_logging_summary">Increase WLAN logging level, show per SSID RSSI in WLAN Picker</string>
  <string name="wifi_wapi_as_certificate">AS certificate</string>
  <string name="wifi_wapi_cert_mode_hand_text">Hand select the certificate</string>
  <string name="wifi_wapi_certification_dont_exist">The WAPI certificates does not exist. Please intall them.</string>
  <string name="wifi_wapi_fail_to_auth">"WAPI authentication failed
Please check validity of certificates"</string>
  <string name="wifi_wapi_fail_to_init">"Unable to open WAPI certificates
Credential storage might not enable"</string>
  <string name="wifi_wapi_psk_type">Password type</string>
  <string name="wifi_wapi_user_certificate">User certificate</string>
  <string name="window_animation_scale_title">Window animation scale</string>
</resources>


text:
namespace gpopt
{
	class CMDAccessor;
}

struct Query;
struct RangeTblEntry;
struct GroupingClause;
struct SortClause;
typedef SortClause GroupClause;
struct Const;
struct List;

namespace gpdxl
{
	//---------------------------------------------------------------------------
	//	@class:
	//		CQueryMutators
	//
	//	@doc:
	//		Class providing methods for translating a GPDB Query object into a
	//      DXL Tree.
	//
	//---------------------------------------------------------------------------
	class CQueryMutators
	{
		typedef Node *(*Pfnode) ();
		typedef BOOL (*PfFallback) ();

		typedef struct SContextHavingQualMutator
		{
			public:
				// memory pool
				IMemoryPool *m_pmp;

				// MD accessor for function names
				CMDAccessor *m_pmda;

				// the counter for Query's total number of target entries
				ULONG m_ulTECount;

				// the target list of the new group by query
				List *m_plTENewGroupByQuery;

				// the current query level
				ULONG m_ulCurrLevelsUp;

		 	 	// indicate whether we are mutating the argument of an aggregate
				BOOL m_fAggregateArg;

				// indicate the levels up of the aggregate we are mutating
				ULONG m_ulAggregateLevelUp;

				// fall back to the planner by raising an expression since we encountered an
				// expression / attribute that we could not resolve
				BOOL m_fFallbackToPlanner;

				// ctor
				SContextHavingQualMutator
					(
					IMemoryPool *pmp,
					CMDAccessor *pmda,
					ULONG ulTECount,
					List *plTENewGroupByQuery
					)
					:
					m_pmp(pmp),
					m_pmda(pmda),
					m_ulTECount(ulTECount),
					m_plTENewGroupByQuery(plTENewGroupByQuery),
					m_ulCurrLevelsUp(0),
					m_fAggregateArg(false),
					m_ulAggregateLevelUp(ULONG_MAX),
					m_fFallbackToPlanner(false)
				{
					GPOS_ASSERT(NULL != plTENewGroupByQuery);
				}

				// dtor
				~SContextHavingQualMutator()
				{}

		} CContextHavingQualMutator;

		typedef struct SContextGrpbyPlMutator
		{
			public:

				// memory pool
				IMemoryPool *m_pmp;

				// MD accessor to get the function name
				CMDAccessor *m_pmda;

				// original query
				Query *m_pquery;

				// the new target list of the group by query
				List *m_plTENewGroupByQuery;

				// the current query level
				ULONG m_ulCurrLevelsUp;

				// the sorting / grouping reference of the original target list entry
				ULONG m_ulRessortgroupref;

				// indicate whether we are mutating the argument of an aggregate
				BOOL m_fAggregateArg;

				// ctor
				SContextGrpbyPlMutator
					(
					IMemoryPool *pmp,
					CMDAccessor *pmda,
					Query *pquery,
					List *plTENewGroupByQuery
					)
					:
					m_pmp(pmp),
					m_pmda(pmda),
					m_pquery(pquery),
					m_plTENewGroupByQuery(plTENewGroupByQuery),
					m_ulCurrLevelsUp(0),
					m_ulRessortgroupref(0),
					m_fAggregateArg(false)
				{
				}

				// dtor
				~SContextGrpbyPlMutator()
				{}

		} CContextGrpbyPlMutator;

		typedef struct SContextIncLevelsupMutator
		{
			public:

				// the current query level
				ULONG m_ulCurrLevelsUp;

				// fix target list entry of the top level
				BOOL m_fFixTargetListTopLevel;

				// ctor
				SContextIncLevelsupMutator
					(
					ULONG ulCurrLevelsUp,
					BOOL fFixTargetListTopLevel
					)
					:
					m_ulCurrLevelsUp(ulCurrLevelsUp),
					m_fFixTargetListTopLevel(fFixTargetListTopLevel)
				{
				}

				// dtor
				~SContextIncLevelsupMutator()
				{}

		} CContextIncLevelsupMutator;

		// context for walker that iterates over the expression in the target entry
		typedef struct SContextTLWalker
				{
					public:

						// list of target list entries in the query
						List *m_plTE;

						// list of grouping clauses
						List *m_groupClause;

						// ctor
						SContextTLWalker
							(
							List *plTE,
							List *groupClause
							)
							:
							m_plTE(plTE),
							m_groupClause(groupClause)
						{
						}

						// dtor
						~SContextTLWalker()
						{}

				} CContextTLWalker;

		private:

			// check if the cte levels up needs to be corrected
			static
			BOOL FNeedsLevelsUpCorrection(SContextIncLevelsupMutator *pctxinclvlmutator, Index idxCtelevelsup);

		public:

			// fall back during since the target list refers to a attribute which algebrizer at this point cannot resolve
			static
			BOOL FNeedsToFallback(Node *pnode, void *pctx);

			// check if the project list contains expressions on aggregates thereby needing normalization
			static
			BOOL FNeedsPrLNormalization(const Query *pquery);

			// normalize query
			static
			Query *PqueryNormalize(IMemoryPool *pmp, CMDAccessor *pmda, const Query *pquery, ULONG ulQueryLevel);

			// check if the project list contains expressions on window operators thereby needing normalization
			static
			BOOL FNeedsWindowPrLNormalization(const Query *pquery);

			// flatten expressions in window operation project list
			static
			Query *PqueryNormalizeWindowPrL(IMemoryPool *pmp, CMDAccessor *pmda, const Query *pquery);

			// traverse the project list to extract all window functions in an arbitrarily complex project element
			static
			Node *PnodeWindowPrLMutator(Node *pnode, void *ctx);

			// flatten expressions in project list
			static
			Query *PqueryNormalizeGrpByPrL(IMemoryPool *pmp, CMDAccessor *pmda, const Query *pquery);

			// make a copy of the aggref (minus the arguments)
			static
			Aggref *PaggrefFlatCopy(Aggref *paggrefOld);

			// create a new entry in the derived table and return its corresponding var
			static
			Var *PvarInsertIntoDerivedTable(Node *pnode, SContextHavingQualMutator *context);

			// check if a matching node exists in the list of target entries
			static
			Node *PnodeFind(Node *pnode, SContextHavingQualMutator *pctx);

			// increment the levels up of outer references
			static
			Var *PvarOuterReferenceIncrLevelsUp(Var *pvar);

			// pull up having clause into a select
			static
			Query *PqueryNormalizeHaving(IMemoryPool *pmp, CMDAccessor *pmda, const Query *pquery);

			// traverse the expression and fix the levels up of any outer reference
			static
			Node *PnodeIncrementLevelsupMutator(Node *pnode, void *ctx);

			// traverse the expression and fix the levels up of any CTE
			static
			Node *PnodeFixCTELevelsupMutator(Node *pnode, void *ctx);

			// traverse the project list of a groupby operator, to
			// extract all aggregate functions in an arbitrarily complex project element,
			static
			Node *PnodeGrpbyPrLMutator(Node *pnode, void *ctx);

			// mutate the grouping columns, fix levels up when necessary
			static
			Node *PnodeGrpColMutator(Node *pnode, void *pctx);

			// fix the level up of grouping columns when necessary
			static
			Node *PnodeFixGrpCol(Node *pnode, TargetEntry *pteOriginal, SContextGrpbyPlMutator *pctxGrpByMutator);

			// return a target entry for the aggregate or percentile expression
			static
			TargetEntry *PteAggregateOrPercentileExpr(IMemoryPool *pmp, CMDAccessor *pmda, Node *pnode, ULONG ulAttno);

			// traverse the having qual to extract all aggregate functions,
			// fix correlated vars and return the modified having qual
			static
			Node *PnodeHavingQualMutator(Node *pnode, void *ctx);

			// for a given an TE in the derived table, create a new TE to be added to the top level query
			static
			TargetEntry *Pte(TargetEntry *pte, ULONG ulVarAttno);

			// return the column name of the target entry
			static
			CHAR* SzTEName(TargetEntry *pte, Query *pquery);

			// make the input query into a derived table and return a new root query
			static
			Query *PqueryConvertToDerivedTable(const Query *pquery, BOOL fFixTargetList, BOOL fFixHavingQual);

			// eliminate distinct clause
			static
			Query *PqueryEliminateDistinctClause(const Query *pquery);

			// reassign the sorting clause from the derived table to the new top-level query
			static
			void ReassignSortClause(Query *pqueryNew, Query *pqueryDrdTbl);

			// fix window frame edge boundary when its value is defined by a subquery
			static
			Query *PqueryFixWindowFrameEdgeBoundary(const Query *pquery);
	};
}
#endif // GPDXL_CWalkerUtils_H

//EOF

redpajama_set_name: RedPajamaGithub


text:
import * as chai from 'chai';
const { assert } = chai;

import mockNetworkInterface from './mocks/mockNetworkInterface';
import ApolloClient from '../src';
import { MutationQueryReducersMap } from '../src/data/mutationResults';
import { NormalizedCache, StoreObject } from '../src/data/storeUtils';

import { assign, cloneDeep} from 'lodash';

import { Subscription } from '../src/util/Observable';

import gql from 'graphql-tag';

import {
  addTypenameToDocument,
} from '../src/queries/queryTransform';

import {
  isMutationResultAction,
} from '../src/actions';

describe('optimistic mutation results', () => {
  const query = gql`
    query todoList {
      __typename
      todoList(id: 5) {
        __typename
        id
        todos {
          id
          __typename
          text
          completed
        }
        filteredTodos: todos(completed: true) {
          id
          __typename
          text
          completed
        }
      }
      noIdList: todoList(id: 6) {
        __typename
        id
        todos {
          __typename
          text
          completed
        }
      }
    }
  `;

  const result: any = {
    data: {
      __typename: 'Query',
      todoList: {
        __typename: 'TodoList',
        id: '5',
        todos: [
          {
            __typename: 'Todo',
            id: '3',
            text: 'Hello world',
            completed: false,
          },
          {
            __typename: 'Todo',
            id: '6',
            text: 'Second task',
            completed: false,
          },
          {
            __typename: 'Todo',
            id: '12',
            text: 'Do other stuff',
            completed: false,
          },
        ],
        filteredTodos: [],
      },
      noIdList: {
        __typename: 'TodoList',
        id: '7',
        todos: [
          {
            __typename: 'Todo',
            text: 'Hello world',
            completed: false,
          },
          {
            __typename: 'Todo',
            text: 'Second task',
            completed: false,
          },
          {
            __typename: 'Todo',
            text: 'Do other stuff',
            completed: false,
          },
        ],
      },
    },
  };

  let client: ApolloClient;
  let networkInterface: any;

  type CustomMutationBehavior = {
    type: 'CUSTOM_MUTATION_RESULT',
    dataId: string,
    field: string,
    value: any,
  };

  function setup(...mockedResponses: any[]) {
    networkInterface = mockNetworkInterface({
      request: { query },
      result,
    }, ...mockedResponses);

    client = new ApolloClient({
      networkInterface,
      dataIdFromObject: (obj: any) => {
        if (obj.id && obj.__typename) {
          return obj.__typename + obj.id;
        }
        return null;
      },
    });

    const obsHandle = client.watchQuery({
      query,
    });

    return obsHandle.result();
  };

  describe('error handling', () => {
    const mutation = gql`
      mutation createTodo {
        # skipping arguments in the test since they don't matter
        createTodo {
          id
          text
          completed
          __typename
        }
        __typename
      }
    `;

    const mutationResult = {
      data: {
        __typename: 'Mutation',
        createTodo: {
          __typename: 'Todo',
          id: '99',
          text: 'This one was created with a mutation.',
          completed: true,
        },
      },
    };

    const mutationResult2 = {
      data: assign({}, mutationResult.data, {
        createTodo: assign({}, mutationResult.data.createTodo, {
          id: '66',
          text: 'Second mutation.',
        }),
      }),
    };

    const optimisticResponse = {
      __typename: 'Mutation',
      createTodo: {
        __typename: 'Todo',
        id: '99',
        text: 'Optimistically generated',
        completed: true,
      },
    };

    const optimisticResponse2 = assign({}, optimisticResponse, {
      createTodo: assign({}, optimisticResponse.createTodo, {
        id: '66',
        text: 'Optimistically generated 2',
      }),
    });

    const updateQueries = {
      todoList: (prev: any, options: any) => {
        const state = cloneDeep(prev);
        state.todoList.todos.unshift(options.mutationResult.data.createTodo);
        return state;
      },
    };

    it('handles a single error for a single mutation', () => {
      return setup({
        request: { query: mutation },
        error: new Error('forbidden (test error)'),
      })
      .then(() => {
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries,
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 4);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');

        return promise;
      })
      .catch((err) => {
        assert.instanceOf(err, Error);
        assert.equal(err.message, 'Network error: forbidden (test error)');

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 3);
        assert.notProperty(dataInStore, 'Todo99');
      });
    });

    it('handles errors produced by one mutation in a series', () => {
      let subscriptionHandle: Subscription;
      return setup({
        request: { query: mutation },
        error: new Error('forbidden (test error)'),
      }, {
        request: { query: mutation },
        result: mutationResult2,
      })
      .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
      .then(() => {
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries,
        }).catch((err) => {
          // it is ok to fail here
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'Network error: forbidden (test error)');
          return null;
        });

        const promise2 = client.mutate({
          mutation,
          optimisticResponse: optimisticResponse2,
          updateQueries,
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 5);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');
        assert.equal((dataInStore['Todo66'] as any).text, 'Optimistically generated 2');

        return Promise.all([promise, promise2]);
      })
      .then(() => {
        subscriptionHandle.unsubscribe();
        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 4);
        assert.notProperty(dataInStore, 'Todo99');
        assert.property(dataInStore, 'Todo66');
        assert.include((dataInStore['TodoList5'] as any).todos, realIdValue('Todo66'));
        assert.notInclude((dataInStore['TodoList5'] as any).todos, realIdValue('Todo99'));
      });
    });

    it('can run 2 mutations concurrently and handles all intermediate states well', () => {
      function checkBothMutationsAreApplied(expectedText1: any, expectedText2: any) {
        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 5);
        assert.property(dataInStore, 'Todo99');
        assert.property(dataInStore, 'Todo66');
        assert.include((dataInStore['TodoList5'] as any).todos, realIdValue('Todo66'));
        assert.include((dataInStore['TodoList5'] as any).todos, realIdValue('Todo99'));
        assert.equal((dataInStore['Todo99'] as any).text, expectedText1);
        assert.equal((dataInStore['Todo66'] as any).text, expectedText2);
      }
      let subscriptionHandle: Subscription;
      return setup({
        request: { query: mutation },
        result: mutationResult,
      }, {
        request: { query: mutation },
        result: mutationResult2,
        // make sure it always happens later
        delay: 100,
      })
      .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
      .then(() => {
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries,
        }).then((res) => {
          checkBothMutationsAreApplied('This one was created with a mutation.', 'Optimistically generated 2');
          const mutationsState = client.store.getState().apollo.mutations;
          assert.equal(mutationsState['5'].loading, false);
          assert.equal(mutationsState['6'].loading, true);

          return res;
        });

        const promise2 = client.mutate({
          mutation,
          optimisticResponse: optimisticResponse2,
          updateQueries,
        }).then((res) => {
          checkBothMutationsAreApplied('This one was created with a mutation.', 'Second mutation.');
          const mutationsState = client.store.getState().apollo.mutations;
          assert.equal(mutationsState[5].loading, false);
          assert.equal(mutationsState[6].loading, false);

          return res;
        });

        const mutationsState = client.store.getState().apollo.mutations;
        assert.equal(mutationsState[5].loading, true);
        assert.equal(mutationsState[6].loading, true);

        checkBothMutationsAreApplied('Optimistically generated', 'Optimistically generated 2');

        return Promise.all([promise, promise2]);
      })
      .then(() => {
        subscriptionHandle.unsubscribe();
        checkBothMutationsAreApplied('This one was created with a mutation.', 'Second mutation.');
      });
    });
  });

  describe('optimistic updates using updateQueries', () => {
    const mutation = gql`
      mutation createTodo {
        # skipping arguments in the test since they don't matter
        createTodo {
          id
          text
          completed
          __typename
        }
        __typename
      }
    `;

    const mutationResult = {
      data: {
        __typename: 'Mutation',
        createTodo: {
          id: '99',
          __typename: 'Todo',
          text: 'This one was created with a mutation.',
          completed: true,
        },
      },
    };

    const optimisticResponse = {
      __typename: 'Mutation',
      createTodo: {
        __typename: 'Todo',
        id: '99',
        text: 'Optimistically generated',
        completed: true,
      },
    };

    const mutationResult2 = {
      data: assign({}, mutationResult.data, {
        createTodo: assign({}, mutationResult.data.createTodo, {
          id: '66',
          text: 'Second mutation.',
        }),
      }),
    };

    const optimisticResponse2 = {
      __typename: 'Mutation',
      createTodo: {
        __typename: 'Todo',
        id: '66',
        text: 'Optimistically generated 2',
        completed: true,
      },
    };

    it('will insert a single item to the beginning', () => {
      let subscriptionHandle: Subscription;
      return setup({
        request: { query: mutation },
        result: mutationResult,
      })
      .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
      .then(() => {
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries: {
            todoList: (prev, options) => {
              const mResult = options.mutationResult as any;
              assert.equal(mResult.data.createTodo.id, '99');

              const state = cloneDeep(prev) as any;
              state.todoList.todos.unshift(mResult.data.createTodo);
              return state;
            },
          },
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 4);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');

        return promise;
      })
      .then(() => {
        return client.query({ query });
      })
      .then((newResult: any) => {
        subscriptionHandle.unsubscribe();
        // There should be one more todo item than before
        assert.equal(newResult.data.todoList.todos.length, 4);

        // Since we used `prepend` it should be at the front
        assert.equal(newResult.data.todoList.todos[0].text, 'This one was created with a mutation.');
      });
    });

    it('two array insert like mutations', () => {
      let subscriptionHandle: Subscription;
      return setup({
        request: { query: mutation },
        result: mutationResult,
      }, {
        request: { query: mutation },
        result: mutationResult2,
        delay: 50,
      })
      .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
      .then(() => {
        const updateQueries = {
          todoList: (prev, options) => {
            const mResult = options.mutationResult as any;

            const state = cloneDeep(prev) as any;
            state.todoList.todos.unshift(mResult.data.createTodo);
            return state;
          },
        } as MutationQueryReducersMap;
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries,
        }).then((res) => {
          const dataInStore = client.queryManager.getDataWithOptimisticResults();
          assert.equal((dataInStore['TodoList5'] as any).todos.length, 5);
          assert.equal((dataInStore['Todo99'] as any).text, 'This one was created with a mutation.');
          assert.equal((dataInStore['Todo66'] as any).text, 'Optimistically generated 2');
          return res;
        });

        const promise2 = client.mutate({
          mutation,
          optimisticResponse: optimisticResponse2,
          updateQueries,
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 5);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');
        assert.equal((dataInStore['Todo66'] as any).text, 'Optimistically generated 2');

        return Promise.all([promise, promise2]);
      })
      .then(() => {
        return client.query({ query });
      })
      .then((newResult: any) => {
        subscriptionHandle.unsubscribe();
        // There should be one more todo item than before
        assert.equal(newResult.data.todoList.todos.length, 5);

        // Since we used `prepend` it should be at the front
        assert.equal(newResult.data.todoList.todos[0].text, 'Second mutation.');
        assert.equal(newResult.data.todoList.todos[1].text, 'This one was created with a mutation.');
      });
    });

    it('two mutations, one fails', () => {
      let subscriptionHandle: Subscription;
      return setup({
        request: { query: mutation },
        error: new Error('forbidden (test error)'),
        delay: 20,
      }, {
        request: { query: mutation },
        result: mutationResult2,
        // XXX this test will uncover a flaw in the design of optimistic responses combined with
        // updateQueries or result reducers if you un-comment the line below. The issue is that
        // optimistic updates are not commutative but are treated as such. When undoing an
        // optimistic update, other optimistic updates should be rolled back and re-applied in the
        // same order as before, otherwise the store can end up in an inconsistent state.
        // delay: 50,
      })
      .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
      .then(() => {
        const updateQueries = {
          todoList: (prev, options) => {
            const mResult = options.mutationResult as any;

            const state = cloneDeep(prev) as any;
            state.todoList.todos.unshift(mResult.data.createTodo);
            return state;
          },
        } as MutationQueryReducersMap;
        const promise = client.mutate({
          mutation,
          optimisticResponse,
          updateQueries,
        }).catch((err) => {
          // it is ok to fail here
          assert.instanceOf(err, Error);
          assert.equal(err.message, 'Network error: forbidden (test error)');
          return null;
        });

        const promise2 = client.mutate({
          mutation,
          optimisticResponse: optimisticResponse2,
          updateQueries,
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 5);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');
        assert.equal((dataInStore['Todo66'] as any).text, 'Optimistically generated 2');

        return Promise.all([promise, promise2]);
      })
      .then(() => {
        subscriptionHandle.unsubscribe();
        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 4);
        assert.notProperty(dataInStore, 'Todo99');
        assert.property(dataInStore, 'Todo66');
        assert.include((dataInStore['TodoList5'] as any).todos, realIdValue('Todo66'));
        assert.notInclude((dataInStore['TodoList5'] as any).todos, realIdValue('Todo99'));
      });
    });

    it('will handle dependent updates', done => {
      networkInterface = mockNetworkInterface({
        request: { query },
        result,
      }, {
        request: { query: mutation },
        result: mutationResult,
        delay: 10,
      }, {
        request: { query: mutation },
        result: mutationResult2,
        delay: 20,
      });

      const customOptimisticResponse1 = {
        __typename: 'Mutation',
        createTodo: {
          __typename: 'Todo',
          id: 'optimistic-99',
          text: 'Optimistically generated',
          completed: true,
        },
      };

      const customOptimisticResponse2 = {
        __typename: 'Mutation',
        createTodo: {
          __typename: 'Todo',
          id: 'optimistic-66',
          text: 'Optimistically generated 2',
          completed: true,
        },
      };

      const updateQueries = {
        todoList: (prev, options) => {
          const mResult = options.mutationResult as any;

          const state = cloneDeep(prev) as any;
          state.todoList.todos.unshift(mResult.data.createTodo);
          return state;
        },
      } as MutationQueryReducersMap;

      client = new ApolloClient({
        networkInterface,
        dataIdFromObject: (obj: any) => {
          if (obj.id && obj.__typename) {
            return obj.__typename + obj.id;
          }
          return null;
        },
      });

      const defaultTodos = result.data.todoList.todos;
      let count = 0;

      client.watchQuery({ query }).subscribe({
        next: (value: any) => {
          const todos = value.data.todoList.todos;
          switch (count++) {
            case 0:
              assert.deepEqual(defaultTodos, todos);
              twoMutations();
              break;
            case 1:
              assert.deepEqual([customOptimisticResponse1.createTodo, ...defaultTodos], todos);
              break;
            case 2:
              assert.deepEqual([customOptimisticResponse2.createTodo, customOptimisticResponse1.createTodo, ...defaultTodos], todos);
              break;
            case 3:
              assert.deepEqual([customOptimisticResponse2.createTodo, mutationResult.data.createTodo, ...defaultTodos], todos);
              break;
            case 4:
              assert.deepEqual([mutationResult2.data.createTodo, mutationResult.data.createTodo, ...defaultTodos], todos);
              done();
              break;
            default:
              done(new Error('Next should not have been called again.'));
          }
        },
        error: error => done(error),
      });

      function twoMutations () {
        client.mutate({
          mutation,
          optimisticResponse: customOptimisticResponse1,
          updateQueries,
        })
          .catch(error => done(error));

        client.mutate({
          mutation,
          optimisticResponse: customOptimisticResponse2,
          updateQueries,
        })
          .catch(error => done(error));
      }
    });
  });

  describe('optimistic updates with result reducer', () => {
    const mutation = gql`
      mutation createTodo {
        # skipping arguments in the test since they don't matter
        createTodo {
          id
          text
          completed
          __typename
        }
        __typename
      }
    `;

    const mutationResult = {
      data: {
        __typename: 'Mutation',
        createTodo: {
          id: '99',
          __typename: 'Todo',
          text: 'This one was created with a mutation.',
          completed: true,
        },
      },
    };

    const optimisticResponse = {
      __typename: 'Mutation',
      createTodo: {
        __typename: 'Todo',
        id: '99',
        text: 'Optimistically generated',
        completed: true,
      },
    };

    /*
    const mutationResult2 = {
      data: assign({}, mutationResult.data, {
        createTodo: assign({}, mutationResult.data.createTodo, {
          id: '66',
          text: 'Second mutation.',
        }),
      }),
    };

    const optimisticResponse2 = {
      __typename: 'Mutation',
      createTodo: {
        __typename: 'Todo',
        id: '66',
        text: 'Optimistically generated 2',
        completed: true,
      },
    };
    */

    /*
    .then(() => {
        observableQuery = client.watchQuery({
          query,
          reducer: (previousResult, action) => {
            counter++;
            if (isMutationResultAction(action)) {
              const newResult = cloneDeep(previousResult) as any;
              newResult.todoList.todos.unshift(action.result.data.createTodo);
              return newResult;
            }
            return previousResult;
          },
        }).subscribe({
          next: () => null, // TODO: we should actually check the new result
        });
        return client.mutate({
          mutation,
        });
      })
    */

    it('can add an item to an array', () => {
      let observableQuery: any;
      let counter = 0;
      return setup({
        request: { query: mutation },
        result: mutationResult,
      })
      .then(() => {
        observableQuery = client.watchQuery({
          query,
          reducer: (previousResult, action) => {
            counter++;
            if (isMutationResultAction(action)) {
              const newResult = cloneDeep(previousResult) as any;
              newResult.todoList.todos.unshift(action.result.data!['createTodo']);
              return newResult;
            }
            return previousResult;
          },
        }).subscribe({
          next: () => null, // TODO: we should actually check the new result
        });
      })
      .then(() => {
        const promise = client.mutate({
          mutation,
          optimisticResponse,
        });

        const dataInStore = client.queryManager.getDataWithOptimisticResults();
        assert.equal((dataInStore['TodoList5'] as any).todos.length, 4);
        assert.equal((dataInStore['Todo99'] as any).text, 'Optimistically generated');

        return promise;
      })
      .then(() => {
        return client.query({ query });
      })
      .then((newResult: any) => {
        // There should be one more todo item than before
        assert.equal(newResult.data.todoList.todos.length, 4);

        // Since we used `prepend` it should be at the front
        assert.equal(newResult.data.todoList.todos[0].text, 'This one was created with a mutation.');
      });
    });

    it('will handle dependent updates', done => {
      const customMutationResult1 = {
        data: {
          __typename: 'Mutation',
          createTodo: {
            id: '99',
            __typename: 'Todo',
            text: 'This one was created with a mutation.',
            completed: true,
          },
        },
      };

      const customMutationResult2 = {
        data: {
          __typename: 'Mutation',
          createTodo: {
            id: '66',
            __typename: 'Todo',
            text: 'Second mutation.',
            completed: true,
          },
        },
      };

      const customOptimisticResponse1 = {
        __typename: 'Mutation',
        createTodo: {
          __typename: 'Todo',
          id: 'optimistic-99',
          text: 'Optimistically generated',
          completed: true,
        },
      };

      const customOptimisticResponse2 = {
        __typename: 'Mutation',
        createTodo: {
          __typename: 'Todo',
          id: 'optimistic-66',
          text: 'Optimistically generated 2',
          completed: true,
        },
      };

      networkInterface = mockNetworkInterface({
        request: { query },
        result,
      }, {
        request: { query: mutation },
        result: customMutationResult1,
        delay: 10,
      }, {
        request: { query: mutation },
        result: customMutationResult2,
        delay: 20,
      });

      client = new ApolloClient({
        networkInterface,
        dataIdFromObject: (obj: any) => {
          if (obj.id && obj.__typename) {
            return obj.__typename + obj.id;
          }
          return null;
        },
      });

      const defaultTodos = result.data.todoList.todos;
      let count = 0;

      client.watchQuery({
        query,
        reducer: (previousResult, action) => {
          if (isMutationResultAction(action)) {
            const newResult = cloneDeep(previousResult) as any;
            newResult.todoList.todos.unshift(action.result.data!['createTodo']);
            return newResult;
          }
          return previousResult;
        },
      }).subscribe({
        next: (value: any) => {
          const todos = value.data.todoList.todos;
          switch (count++) {
            case 0:
              assert.deepEqual(defaultTodos, todos);
              twoMutations();
              break;
            case 1:
              assert.deepEqual([customOptimisticResponse1.createTodo, ...defaultTodos], todos);
              break;
            case 2:
              assert.deepEqual([customOptimisticResponse2.createTodo, customOptimisticResponse1.createTodo, ...defaultTodos], todos);
              break;
            case 3:
              assert.deepEqual([customOptimisticResponse2.createTodo, customMutationResult1.data.createTodo, ...defaultTodos], todos);
              break;
            case 4:
              assert.deepEqual([customMutationResult2.data.createTodo, customMutationResult1.data.createTodo, ...defaultTodos], todos);
              done();
              break;
            default:
              done(new Error('Next should not have been called again.'));
          }
        },
        error: error => done(error),
      });

      function twoMutations () {
        client.mutate({
          mutation,
          optimisticResponse: customOptimisticResponse1,
        })
          .catch(error => done(error));

        client.mutate({
          mutation,
          optimisticResponse: customOptimisticResponse2,
        })
          .catch(error => done(error));
      }
    });
  });
});

describe('optimistic mutation - githunt comments', () => {
  const query = gql`
    query Comment($repoName: String!) {
      entry(repoFullName: $repoName) {
        comments {
          postedBy {
            login
            html_url
          }
        }
      }
    }
  `;
  const queryWithFragment = gql`
    query Comment($repoName: String!) {
      entry(repoFullName: $repoName) {
        comments {
          ...authorFields
        }
      }
    }

    fragment authorFields on User {
      postedBy {
        login
        html_url
      }
    }
  `;
  const variables = {
    repoName: 'org/repo',
  };
  const userDoc = {
    __typename: 'User',
    login: 'stubailo',
    html_url: 'http://avatar.com/stubailo.png',
  };

  const result = {
    data: {
      __typename: 'Query',
      entry: {
        __typename: 'Entry',
        comments: [
          {
            __typename: 'Comment',
            postedBy: userDoc,
          },
        ],
      },
    },
  };

  let client: ApolloClient;
  let networkInterface: any;

  function setup(...mockedResponses: any[]) {
    networkInterface = mockNetworkInterface({
      request: {
        query: addTypenameToDocument(query),
        variables,
      },
      result,
    }, {
      request: {
        query: addTypenameToDocument(queryWithFragment),
        variables,
      },
      result,
    }, ...mockedResponses);

    client = new ApolloClient({
      networkInterface,
      dataIdFromObject: (obj: any) => {
        if (obj.id && obj.__typename) {
          return obj.__typename + obj.id;
        }
        return null;
      },
    });

    const obsHandle = client.watchQuery({
      query,
      variables,
    });

    return obsHandle.result();
  };

  const mutation = gql`
    mutation submitComment($repoFullName: String!, $commentContent: String!) {
      submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
        postedBy {
          login
          html_url
        }
      }
    }
  `;

  const mutationWithFragment = gql`
    mutation submitComment($repoFullName: String!, $commentContent: String!) {
      submitComment(repoFullName: $repoFullName, commentContent: $commentContent) {
        ...authorFields
      }
    }
  `;

  const mutationResult = {
    data: {
      __typename: 'Mutation',
      submitComment: {
        __typename: 'Comment',
        postedBy: userDoc,
      },
    },
  };
  const updateQueries = {
    Comment: (prev, { mutationResult: mutationResultArg }) => {
      const newComment = (mutationResultArg as any).data.submitComment;
      const state = cloneDeep(prev);
      (state as any).entry.comments.unshift(newComment);
      return state;
    },
  } as MutationQueryReducersMap;
  const optimisticResponse = {
    __typename: 'Mutation',
    submitComment: {
      __typename: 'Comment',
      postedBy: userDoc,
    },
  };

  it('can post a new comment', () => {
    const mutationVariables = {
      repoFullName: 'org/repo',
      commentContent: 'New Comment',
    };

    let subscriptionHandle: Subscription;
    return setup({
      request: {
        query: addTypenameToDocument(mutation),
        variables: mutationVariables,
      },
      result: mutationResult,
    })
    .then(() => {
        // we have to actually subscribe to the query to be able to update it
        return new Promise( (resolve, reject) => {
          const handle = client.watchQuery({ query, variables });
          subscriptionHandle = handle.subscribe({
            next(res) { resolve(res); },
          });
        });
      })
    .then(() => {
      return client.mutate({
        mutation,
        optimisticResponse,
        variables: mutationVariables,
        updateQueries,
      });
    }).then(() => {
      return client.query({ query, variables });
    }).then((newResult: any) => {
      subscriptionHandle.unsubscribe();
      assert.equal(newResult.data.entry.comments.length, 2);
    });
  });
});

function realIdValue(id: string) {
  return {
    type: 'id',
    generated: false,
    id,
  };
}


text:
package com.tribbloids.spookystuff.extractors

import com.tribbloids.spookystuff.extractors.GenExtractor.Static
import com.tribbloids.spookystuff.row.{Field, TypedField};

case class GenResolved[T, +R](
    partialFunction: PartialFunction[T, R],
    typedField: TypedField
) extends Static[T, R]
    with Alias[T, R] {

  def field: Field = typedField.self

  override val dataType: DataType = typedField.dataType
}


text:
Este plugin es capaz de analizar los informes XML de JMeter y de  SOAPUI en formato JUnit.

El plugin no realiza el análisis de rendimiento, únicamente muestra información útil de los
resultados del análisis como son la media en el tiempo de respuesta, tendencia del rendimiento a lo largo de las distintas
ejecuciones, páginas y gráficos para ver los resultados de análisis.

Para utilizar esta funcionalidad, primero debes configurar tu proyecto para ejecutar tests de rendimiento, después debes
elegir el tipo de ficheros de informe a analizar (JMeter o JUnit), y finalmente la ubicación de estos ficheros.
Por defecto el plugin utilizará el patrón <tt>**/*.jtl</tt> para ficheros JMeter y <tt>**/TEST*.xml</tt> en el caso de JUnit.


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date %highlight(%-5level [%thread]) %-16X{traceId} %-25logger{10} %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>


text:
var TagInput = Vue.extend({
    data: {
        tags: []
    },
    methods: {
        addTag : function(e) {
            if (this.tagText){
                var tag = this.tagText.trim().toLowerCase();
                if (this.tags.map(function(e) { return e.name; }).indexOf(tag) >= 0) {
                    alert("duplicated");
                    return;
                }
                this.tags.push({name: tag});
                this.tagText = '';
            }
        },
        removeTag : function(tagToRemove) {
            var index = this.tags.indexOf(tagToRemove);
            if (index < 0) return;
            this.tags.splice(index, 1);
        },
        getTags : function() {
            var tags = this.tags.map(function(e) { return e.name; });
            $('.result').append('<li>' + tags +'</li>');
            return tags;
        },
        getTagsSerialize : function() {
            return this.tags.map(function(e) { return e.name; }).join(',');
        },
        input : function(e) {
            this.addTag();
        }
    }
});


text:
namespace OpenInVS2019Professional
{
    static class Vsix
    {
        public const string Id = "6962FBF6-8B06-4884-97DA-E07D208D89C5";
        public const string Name = "Open in Visual Studio 2019 Professional";
        public const string Description = @"Open multiple files simultaneously in Visual Studio 2019 Professional Edition directly from Solution Explorer or Code Editor window.";
        public const string Language = "en-US";
        public const string Version = "1.1.53";
        public const string Author = "Greg Trevellick";
        public const string Tags = "VS2019, Visual Studio 2019, Professional";
    }
}


text:
require 'vips-process/base'
require 'vips-process/quality'

class MyImage < Vips::Process::Base
  include Vips::Process::Quality
end

MyImage.new('/path/to/src.jpg').quality(50).process!


text:
package com.youzu.clan.base.json.act;

import java.util.ArrayList;

/**
 * Created by wjwu on 2015/11/25.
 */
public class ActPublishInfo {
    public String fid;
    public String subject;
    public String starttimefrom;
    public String activityplace;
    public String activitycity;
    public String activityclass;
    public ArrayList<String> userfields;
    public String extfield;
    public String activityaid;
    public String activityaid_url;
    public String message;
}


text:
package documentdb

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/to"
	"net/http"
)

// DatabaseAccountKind enumerates the values for database account kind.
type DatabaseAccountKind string

const (
	// GlobalDocumentDB specifies the global document db state for database account kind.
	GlobalDocumentDB DatabaseAccountKind = "GlobalDocumentDB"
	// MongoDB specifies the mongo db state for database account kind.
	MongoDB DatabaseAccountKind = "MongoDB"
	// Parse specifies the parse state for database account kind.
	Parse DatabaseAccountKind = "Parse"
)

// DatabaseAccountOfferType enumerates the values for database account offer type.
type DatabaseAccountOfferType string

const (
	// Standard specifies the standard state for database account offer type.
	Standard DatabaseAccountOfferType = "Standard"
)

// DefaultConsistencyLevel enumerates the values for default consistency level.
type DefaultConsistencyLevel string

const (
	// BoundedStaleness specifies the bounded staleness state for default consistency level.
	BoundedStaleness DefaultConsistencyLevel = "BoundedStaleness"
	// ConsistentPrefix specifies the consistent prefix state for default consistency level.
	ConsistentPrefix DefaultConsistencyLevel = "ConsistentPrefix"
	// Eventual specifies the eventual state for default consistency level.
	Eventual DefaultConsistencyLevel = "Eventual"
	// Session specifies the session state for default consistency level.
	Session DefaultConsistencyLevel = "Session"
	// Strong specifies the strong state for default consistency level.
	Strong DefaultConsistencyLevel = "Strong"
)

// KeyKind enumerates the values for key kind.
type KeyKind string

const (
	// Primary specifies the primary state for key kind.
	Primary KeyKind = "primary"
	// PrimaryReadonly specifies the primary readonly state for key kind.
	PrimaryReadonly KeyKind = "primaryReadonly"
	// Secondary specifies the secondary state for key kind.
	Secondary KeyKind = "secondary"
	// SecondaryReadonly specifies the secondary readonly state for key kind.
	SecondaryReadonly KeyKind = "secondaryReadonly"
)

// ConsistencyPolicy is the consistency policy for the Cosmos DB database account.
type ConsistencyPolicy struct {
	DefaultConsistencyLevel DefaultConsistencyLevel `json:"defaultConsistencyLevel,omitempty"`
	MaxStalenessPrefix      *int64                  `json:"maxStalenessPrefix,omitempty"`
	MaxIntervalInSeconds    *int32                  `json:"maxIntervalInSeconds,omitempty"`
}

// DatabaseAccount is an Azure Cosmos DB database account.
type DatabaseAccount struct {
	autorest.Response          `json:"-"`
	ID                         *string             `json:"id,omitempty"`
	Name                       *string             `json:"name,omitempty"`
	Type                       *string             `json:"type,omitempty"`
	Location                   *string             `json:"location,omitempty"`
	Tags                       *map[string]*string `json:"tags,omitempty"`
	Kind                       DatabaseAccountKind `json:"kind,omitempty"`
	*DatabaseAccountProperties `json:"properties,omitempty"`
}

// DatabaseAccountConnectionString is connection string for the Cosmos DB account
type DatabaseAccountConnectionString struct {
	ConnectionString *string `json:"connectionString,omitempty"`
	Description      *string `json:"description,omitempty"`
}

// DatabaseAccountCreateUpdateParameters is parameters to create and update Cosmos DB database accounts.
type DatabaseAccountCreateUpdateParameters struct {
	ID                                     *string             `json:"id,omitempty"`
	Name                                   *string             `json:"name,omitempty"`
	Type                                   *string             `json:"type,omitempty"`
	Location                               *string             `json:"location,omitempty"`
	Tags                                   *map[string]*string `json:"tags,omitempty"`
	Kind                                   DatabaseAccountKind `json:"kind,omitempty"`
	*DatabaseAccountCreateUpdateProperties `json:"properties,omitempty"`
}

// DatabaseAccountCreateUpdateProperties is properties to create and update Azure Cosmos DB database accounts.
type DatabaseAccountCreateUpdateProperties struct {
	ConsistencyPolicy        *ConsistencyPolicy `json:"consistencyPolicy,omitempty"`
	Locations                *[]Location        `json:"locations,omitempty"`
	DatabaseAccountOfferType *string            `json:"databaseAccountOfferType,omitempty"`
	IPRangeFilter            *string            `json:"ipRangeFilter,omitempty"`
	EnableAutomaticFailover  *bool              `json:"enableAutomaticFailover,omitempty"`
}

// DatabaseAccountListConnectionStringsResult is the connection strings for the given database account.
type DatabaseAccountListConnectionStringsResult struct {
	autorest.Response `json:"-"`
	ConnectionStrings *[]DatabaseAccountConnectionString `json:"connectionStrings,omitempty"`
}

// DatabaseAccountListKeysResult is the access keys for the given database account.
type DatabaseAccountListKeysResult struct {
	autorest.Response                      `json:"-"`
	PrimaryMasterKey                       *string `json:"primaryMasterKey,omitempty"`
	SecondaryMasterKey                     *string `json:"secondaryMasterKey,omitempty"`
	*DatabaseAccountListReadOnlyKeysResult `json:"properties,omitempty"`
}

// DatabaseAccountListReadOnlyKeysResult is the read-only access keys for the given database account.
type DatabaseAccountListReadOnlyKeysResult struct {
	autorest.Response          `json:"-"`
	PrimaryReadonlyMasterKey   *string `json:"primaryReadonlyMasterKey,omitempty"`
	SecondaryReadonlyMasterKey *string `json:"secondaryReadonlyMasterKey,omitempty"`
}

// DatabaseAccountPatchParameters is parameters for patching Azure Cosmos DB database account properties.
type DatabaseAccountPatchParameters struct {
	Tags *map[string]*string `json:"tags,omitempty"`
}

// DatabaseAccountProperties is properties for the database account.
type DatabaseAccountProperties struct {
	ProvisioningState        *string                  `json:"provisioningState,omitempty"`
	DocumentEndpoint         *string                  `json:"documentEndpoint,omitempty"`
	DatabaseAccountOfferType DatabaseAccountOfferType `json:"databaseAccountOfferType,omitempty"`
	IPRangeFilter            *string                  `json:"ipRangeFilter,omitempty"`
	EnableAutomaticFailover  *bool                    `json:"enableAutomaticFailover,omitempty"`
	ConsistencyPolicy        *ConsistencyPolicy       `json:"consistencyPolicy,omitempty"`
	WriteLocations           *[]Location              `json:"writeLocations,omitempty"`
	ReadLocations            *[]Location              `json:"readLocations,omitempty"`
	FailoverPolicies         *[]FailoverPolicy        `json:"failoverPolicies,omitempty"`
}

// DatabaseAccountRegenerateKeyParameters is parameters to regenerate the keys within the database account.
type DatabaseAccountRegenerateKeyParameters struct {
	KeyKind KeyKind `json:"keyKind,omitempty"`
}

// DatabaseAccountsListResult is the List operation response, that contains the database accounts and their properties.
type DatabaseAccountsListResult struct {
	autorest.Response `json:"-"`
	Value             *[]DatabaseAccount `json:"value,omitempty"`
}

// FailoverPolicies is the list of new failover policies for the failover priority change.
type FailoverPolicies struct {
	FailoverPolicies *[]FailoverPolicy `json:"failoverPolicies,omitempty"`
}

// FailoverPolicy is the failover policy for a given region of a database account.
type FailoverPolicy struct {
	ID               *string `json:"id,omitempty"`
	LocationName     *string `json:"locationName,omitempty"`
	FailoverPriority *int32  `json:"failoverPriority,omitempty"`
}

// Location is a region in which the Azure Cosmos DB database account is deployed.
type Location struct {
	ID                *string `json:"id,omitempty"`
	LocationName      *string `json:"locationName,omitempty"`
	DocumentEndpoint  *string `json:"documentEndpoint,omitempty"`
	ProvisioningState *string `json:"provisioningState,omitempty"`
	FailoverPriority  *int32  `json:"failoverPriority,omitempty"`
}

// Operation is REST API operation
type Operation struct {
	Name    *string           `json:"name,omitempty"`
	Display *OperationDisplay `json:"display,omitempty"`
}

// OperationDisplay is the object that represents the operation.
type OperationDisplay struct {
	Provider    *string `json:"Provider,omitempty"`
	Resource    *string `json:"Resource,omitempty"`
	Operation   *string `json:"Operation,omitempty"`
	Description *string `json:"Description,omitempty"`
}

// OperationListResult is result of the request to list Resource Provider operations. It contains a list of operations
// and a URL link to get the next set of results.
type OperationListResult struct {
	autorest.Response `json:"-"`
	Value             *[]Operation `json:"value,omitempty"`
	NextLink          *string      `json:"nextLink,omitempty"`
}

// OperationListResultPreparer prepares a request to retrieve the next set of results. It returns
// nil if no more results exist.
func (client OperationListResult) OperationListResultPreparer() (*http.Request, error) {
	if client.NextLink == nil || len(to.String(client.NextLink)) <= 0 {
		return nil, nil
	}
	return autorest.Prepare(&http.Request{},
		autorest.AsJSON(),
		autorest.AsGet(),
		autorest.WithBaseURL(to.String(client.NextLink)))
}

// Resource is a database account resource.
type Resource struct {
	ID       *string             `json:"id,omitempty"`
	Name     *string             `json:"name,omitempty"`
	Type     *string             `json:"type,omitempty"`
	Location *string             `json:"location,omitempty"`
	Tags     *map[string]*string `json:"tags,omitempty"`
}


text:
var mongoose = require('mongoose');
var logger = require('./logging').logger;

var makeUrl = function(mongo){
    //var authPart = settings.username + ':' + settings.password + '@';
    //var auth = settings.username ? authPart : '';
    //return 'mongodb://' + auth + mongo.host + ':' + mongo.port + '/' + mongo.db;
};

//var url = makeUrl(settings);
var url = 'mongodb://127.0.0.1:27017/test';
var options = {};

mongoose.connect(url, options, function(err){
    logger.info('Mongoose is connected to ' + url);
});
mongoose.connection.on('error', function(err){
    logger.error('Mongoose error happens:' + err);
});

module.exports = mongoose;


text:
[Checkout Website](https://rxjs-playground.github.io/#/)

![Rxjs playground Screenshot](assets/screenshot.png "Title")

### A playground to test Rx

Explore use cases for Rx and play around with them.

License
**MIT**