text
stringlengths
2
1.04M
meta
dict
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2015 Ant-OS Copyright (C) 2015 The Pure Nexus Project 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. --> <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- Dashboard --> <!-- <string name="header_category_antos">Personalización</string> --> <string name="benzo_kernel_title">Kernel Adiutor</string> <string name="equalizer_settings_title">Viper4Android</string> <!-- Información del Dispositivo --> <string name="antos_version">Ant-OS Build</string> <string name="antos_extras">Ant-OS Extras</string> <!-- Settings --> <string name="antos_tweeks_title">Ant-OS Tweeks</string> <string name="app_version">1.2.01</string> <!-- Otros Ajustes --> <string name="antos_tweeks_other_settings_title">Otros ajustes</string> <string name="antos_tweeks_other_settings_summary">Permite configurar otros ajustes como por ejemplo la autosincronización, la densidad de pantalla, etc.</string> <!-- Opciones de AutoSync --> <string name="autosync_key">autosync_tile</string> <string name="autosync_running">Sincronizando</string> <string name="autosync_title">Auto-Sincronización</string> <string name="autosync_description">Permite realizar la sincronización general automáticamente durante los periodos de tiempo y frecuencia definidos, consiguiendo un ahorro extra de batería.\n</string> <string name="autosync_show_toast_key">autosync_showtoast_key</string> <string name="autosync_show_toast">Mostrar mensajes emergentes para indicar la sincronización</string> <string name="autosync_frecuency_key">autosync_frecuency_key</string> <string name="autosync_frecuency">Frecuencia</string> <string name="autosync_frecuency_summary">Frecuencia con la que se activará la sincronización</string> <string name="autosync_frecuency_defvalue">60</string> <string name="autosync_next">Próxima activación: </string> <string name="autosync_duration_key">autosync_duration_key</string> <string name="autosync_duration">Duración</string> <string name="autosync_duration_summary">Tiempo durante el cual la sincronización estará activa</string> <string name="autosync_duration_defvalue">1</string> <string name="autosync_unit">Minutos</string> <string name="autosync_bt_accept">Aceptar</string> <string name="autosync_bt_cancel">Cancelar</string> <string name="autosync_active_to">Sincronización activa hasta:</string> <string name="autosync_next_sync_key">autosync_next_key</string> <string name="autosync_next_sync">Próx. sincr.:</string> <!-- Opciones DPI --> <string name="dpi_key">dpi_key</string> <string name="dpi_title">Densidad del LCD</string> <!-- Opciones de Pantalla --> <string name="screen_key">screen_key</string> <string name="screen_title">Opciones de Pantalla</string> <string name="screen_taptowake_key">screen_taptowake_key</string> <string name="screen_taptowake_summary">Encender el dispositivo pulsando dos veces sobre la pantalla</string> <!-- Opciones de Reinicio --> <string name="reboot_title">Reinicio</string> <string name="reboot_message">¿Desea reiniciar el dispositivo ahora?</string> <!-- Ant-OS Menu --> <string name="status_bar_screen_title">Barra de Estado</string> <string name="navigation_bar_screen_title">Barra de Navegación</string> <string name="gestures_title">Gestos</string> <string name="lockscreen_title">Pantalla de Bloqueo</string> <string name="power_menu_title">Power Menu</string> <string name="volume_rocker_screen_title">Volume Rocker</string> <string name="volume_rocker_other_title">Misceláneos</string> <string name="battery_title">Batería</string> <string name="battery2_summary">Personalizar los iconos de la batería y porcentaje</string> <string name="recents_panel_settings">Ajustes de aplicaciones recientes</string> <!-- Acerca de... --> <string name="antos_about">Acerca de Ant-OS...</string> <string name="antos_about_summary">Información acerca de la rom y sus desarrolladores</string> <string name="antos_team">Ant-OS Team</string> <string name="antos_leonevo">leonevo</string> <string name="antos_leonevo_sum">Cocina de diseño / Investigador</string> <string name="antos_xurdep">xurdep</string> <string name="antos_xurdep_sum">Pinche de cocina / Desarrollador / Arte gráfico</string> <string name="antos_manuelmagix">manuelmagix</string> <string name="antos_manuelmagix_sum">Pinche de cocina</string> <string name="antos_axel11">axel11</string> <string name="antos_axel11_sum">Arte gráfico</string> <!-- =========================================================================================== --> <!-- TWEEKS --> <!-- =========================================================================================== --> <!-- Categorias --> <string name="interface_cat_title">Interface</string> <string name="button_cat_title">Botones</string> <string name="system_cat_title">Sistema</string> <string name="util_cat_title">Utilidades</string> <!-- Lockscreen Fragment --> <string name="lockscreen_title">Pantalla de Bloqueo</string> <string name="lockscreen_summary">Permite cambiar la imagen de fondo en la pantalla de bloqueo</string> <string name="lockscreen_gen_title">Opciones generales</string> <string name="lockscreen_targets_message">Accesos directos en pantalla de bloqueo</string> <string name="lockscreen_wallpaper_title">Fondo en Pantalla de Bloqueo</string> <string name="lockscreen_wallpaper_set_title">Establecer el fondo de pantalla</string> <string name="lockscreen_wallpaper_clear_title">Restablecer fondo de pantalla</string> <string name="reset_lockscreen_wallpaper">Fondo de pantalla de bloqueo resetado</string> <string name="unlock_scramble_pin_layout_title">Panel de PIN Desordenado</string> <string name="unlock_scramble_pin_layout_summary">Desordena el panel del PIN cuando se desbloquea el telefono.</string> <string name="unlock_quick_unlock_control_title">Desbloqueo rapido</string> <string name="unlock_quick_unlock_control_summary">Desbloquear automaticamemten cuando el PIN es introducido correctamente.</string> <string name="media_art_title">Caratula para estructura multimedia</string> <string name="media_art_summary">Activar caratulas en la pantalla de bloqueo</string> <string name="double_tap_sleep_anywhere_title">Doble pulsacion para apagar pantalla</string> <string name="double_tap_sleep_anywhere_summary">Pulsar dos veces en cualquier sitio de la pantalla de desbloqueo para apagar la pantalla.</string> <!-- Notification drawer fragment --> <string name="notifdraw_title">Panel de Notificationes</string> <string name="notifdraw_summary">Permite cambiar distintos aspectos en el panel de notificaciones</string> <string name="notification_panel_title">Panel de Notificaciones</string> <string name="qs_panel_title">Panel de Ajustes Rápidos</string> <string name="quick_pulldown_title">Desplegado rápido</string> <string name="quick_pulldown_summary">Borde %1$s de la barra de estado bajara los Ajustes Rápidos</string> <string name="quick_pulldown_summary_left">Izquierda</string> <string name="quick_pulldown_summary_right">Derecha</string> <string name="quick_pulldown_off">Desactivado</string> <string name="quick_pulldown_left">Izquierda</string> <string name="quick_pulldown_right">Derecha</string> <string name="status_bar_show_weather_title">Mostrar Clima</string> <string name="status_bar_show_weather_summary">Mostrar clima en la cabecera del panel de notificaciones</string> <string name="notification_force_expand_title">Forzar expandir todas las notificaciones</string> <string name="notification_force_expand_summary">Auto expandir las notificaciones que lo soporten</string> <string name="qs_brightness_slider_title">Deslizador de Brillo</string> <!-- Recents fragment --> <string name="recents_title">Aplicaciones Recientes</string> <string name="recents_summary">Configura los aspectos relacionados con las aplicaciones recientes, así como la colocación del botón para cerrarlas todas, etc.</string> <string name="show_clear_all_recents_button_title">Botton borrar todo</string> <string name="show_clear_all_recents_button_summary">Mostrar botón borrar todo</string> <string name="recents_clear_all_location_title">Borrar todas las localizaciones</string> <string name="recents_clear_all_location_top_right">Arriba a la derecha</string> <string name="recents_clear_all_location_top_left">Arriba a la izquierda</string> <string name="recents_clear_all_location_top_center">Arriba en el centro</string> <string name="recents_clear_all_location_bottom_right">Abajo a la derecha</string> <string name="recents_clear_all_location_bottom_left">Abajo a la izquierda</string> <string name="recents_clear_all_location_bottom_center">Abajo en el centro</string> <string name="recents_clear_all_dismiss_all_title">Borrar todas las tareas</string> <string name="recents_clear_all_dismiss_all_summary">Incluir tareas de fondo al borrar todas las tareas</string> <string name="recents_searchbar_title">Barra de búsqueda</string> <string name="recents_searchbar_summary">Mostrar barra de búsqueda de Google en la ventana de Recientes</string> <!-- statusbar fragment --> <string name="statusbar_title">Barra de Estado</string> <string name="statusbar_summary">Permite realizar ajustes sobre la barra de estado, como por ejemplo el tipo de batería, formato de fecha, control de brillo, etc.</string> <string name="double_tap_to_sleep_title">Doble tap para suspender</string> <string name="double_tap_to_sleep_summary">Doble tap en la barra de estado para suspender</string> <string name="status_bar_toggle_brightness">Contro de brillo</string> <string name="status_bar_toggle_brightness_summary">Ajustar el brillo deslizando por la barra de estado</string> <!-- Navbar fragment --> <string name="navbar_title">Barra de Navegación</string> <string name="navbar_summary">Permite activar/desactivar la barra de navegación, o configurar su tamaño entre otros...</string> <string name="navigation_bar_cus">Personalizar barra de navegación</string> <string name="navigation_bar_opt_cat">Opciones de la barra de navegación</string> <!-- Kill app long-press back --> <string name="kill_app_longpress_back">Botón para matar el proceso</string> <string name="kill_app_longpress_back_summary">Matar la aplicación de fondo dejando pulsado el botón Atrás</string> <!-- Recent longpress last app toggle --> <string name="recents_longpress_title">Pulsación larga en Recientes</string> <string name="recents_longpress_summary">Pulsación larga en Recientes para ir a la última aplicación abierta</string> <string name="ime_switcher_notify">IME Icono Selector</string> <string name="ime_switcher_notify_summary">Mostrar el método de entrada</string> <string name="double_tap_sleep_nav_bar_title">Doble-tap para suspender</string> <string name="double_tap_sleep_nav_bar_summary">Doble tap en la barra de navegación para suspender el dispositivo</string> <string name="navigation_bar_arrow_keys_title">Mostrar teclas de flechas mientras se escribe</string> <string name="navigation_bar_arrow_keys_summary">Mostrar teclas de flechas mientras se escribe. Sobre-escribe el selector IME</string> <string name="navbar_enable_bar">Activar</string> <string name="navbardimenfrag_title">Dimensiones de la barra de navegación</string> <string name="navbar_dimensions_reset_message">¿Restaurar todas las dimensiones por defecto?</string> <string name="navigation_bar_height_title">Altura de barra de navegación</string> <string name="navigation_bar_height_landscape_title">Altura de barra de navegación en apaisado</string> <string name="navigation_bar_width_title">Ancho de la barra de navegación</string> <string name="navigation_bar_size_42_dp_default">42 dp (defecto)</string> <string name="navigation_bar_size_36_dp">36 dp</string> <string name="navigation_bar_size_30_dp">30 dp</string> <string name="navigation_bar_size_24_dp">24 dp</string> <string name="navigation_bar_size_52_dp">52 dp</string> <string name="navigation_bar_size_48_dp_default">48 dp (defecto)</string> <string name="navigation_bar_size_44_dp">44 dp</string> <string name="navigation_bar_size_40_dp">40 dp</string> <string name="navigation_bar_size_42_dp">42 dp</string> <string name="navigation_bar_size_0_dp">0 dp (off)</string> <string name="navbarbuttonfrag_title">Botones y disposición</string> <string name="navigation_bar_help_text">Para empezar, pulsar en el icono de edición para desbloquear la barra de navegación.\n\nPuedes pulsar en el icono para cambiar el acceso directo, o pulsación larga para cambiarlo de posición.\n\Pulsar \'Guardar\' para guardar los cambios, o \'Restaurar por defecto\' para restaurar los ajustes por defecto.</string> <string name="navigation_restore_button_text">Restaurar por \ndefecto</string> <string name="navigation_edit_button_text">Modificar</string> <string name="navigation_save_button_text">Guardar</string> <string name="navigation_bar_reset_message">¿Borrar los ajustes actuales y restaurar la disposición por defecto?</string> <!-- powermenu fragment --> <string name="powermenu_title">Menú de Apagado</string> <string name="powermenu_summary">Permite configurar las distintas opciones que apareceran en el menú de apagado</string> <string name="power_category">Opciones del menú de apagado</string> <string name="actions_category">Elementos del menú de apagado</string> <string name="power_menu_reboot_title">Menú de Reinicio</string> <string name="power_menu_screenshot_title">Captura de Pantalla</string> <string name="power_menu_airplane_title">Modo Avión</string> <string name="power_menu_users_title">Intercambio de Usuario</string> <string name="power_menu_search_title">Búsqueda</string> <string name="power_menu_voice_title">Búsqueda por Voz</string> <string name="power_menu_settings_title">Acceso a Ajustes</string> <string name="power_menu_lockdown_title">Bloquear Dispositivo</string> <string name="power_menu_bug_report_title">Reportar Fallo</string> <string name="power_menu_sound_title">Panel de Sonido</string> <string name="power_menu_bug_report_disabled">Reportar Fallo está desactivado en los ajustes de Desarrollador</string> <string name="lockscreen_enable_power_menu_title">Mostrar menú de apagado en la pantalla de bloqueo</string> <!-- volumerocker fragment --> <string name="volrock_title">Volume Rocker</string> <string name="volrock_summary">Configura las acciones de los botones del volumen</string> <string name="volbtn_wake_device_title">Botón Volume despierta</string> <string name="button_wake_summary">Sobre-escribir el control de música</string> <string name="volbtn_music_controls_title">Control de Música</string> <string name="volbtn_music_controls_summary">Cuando la pantalla está apagada, una pulsación larga en las teclas de volumen cambiará de canción</string> <string name="volbtn_cursor_control_title">Control de cursor en el teclado</string> <string name="volbtn_cursor_control_off">Desactivado</string> <string name="volbtn_cursor_control_on">Volumen arriba/abajo mueve el cursor a izquierda/derecha</string> <string name="volbtn_cursor_control_on_reverse">Volumen arriba/abajo mueve el cursor a derecha/izquierda</string> <string name="volume_keys_control_ring_stream_title">Teclas de volumen controlan el volumen del tono de llamada</string> <string name="volume_keys_control_ring_stream_summary">Si está encendido, las teclas de volumen controlan el tono de llamada. Si está apagado, controlarán el volumen multimedia</string> <string name="swap_volume_buttons_title">Intercambio del botón de Volumen</string> <string name="swap_volume_buttons_summary">Ajustar los botones del volumen en base a la rotación de la pantalla</string> <!-- Display fragment --> <string name="display_title">Pantalla</string> <string name="display_summary">Accede a todas las opciones extra de configuración de pantalla</string> <string name="display_category">Opciones de Pantalla</string> <string name="led_category">Controles de Led</string> <string name="battery_light_title">Luz de batería</string> <string name="notification_light_title">Luz de notificaciones</string> <string name="lcd_density">Densidad LCD</string> <string name="dialog_title_lcd_density">Densidad LCD</string> <string name="lcd_density_value_format">%d DPI</string> <string name="lcd_density_default_value_format">%d DPI (defecto)</string> <string name="restarting_ui">Reiniciando UI\u2026</string> <string name="power_menu_expanded_desktop">Escritorio expandido</string> <string name="wake_when_plugged_or_unplugged_title">Despertar al enchufar</string> <string name="wake_when_plugged_or_unplugged_summary">Enciende la pantalla cuando se conecta/desconecta el dispositivo a una fuente de carga</string> <!-- Notification fragment --> <string name="notif_title">Notificaciones</string> <string name="notif_summary">Permite configurar distintos aspectos de las notificaciones en el dispositivo</string> <string name="battery_saver_notif_title">Notificación de Ahorro de Batería</string> <string name="battery_saver_notif_summary">Mostrar notificación de ahorro de batería cuando esté activado</string> <string name="battery_low_notif_title">Notificación de batería baja</string> <string name="battery_low_notif_summary">Mostrar notificación de batería baja cuando esté activado</string> <!-- cLock date fragment --> <string name="clock_title">cLock</string> <string name="clock_summary">Cambia los ajustes del reloj, clima, etc.</string> <string name="clockdate_frag_title">Reloj y Fecha</string> <string name="clock_frag_summary">Opciones de personalización del Reloj y Fecha</string> <string name="status_bar_clock_style_title">Estilo del reloj</string> <string name="status_bar_am_pm_title">Estilo AM/PM</string> <string name="status_bar_am_pm_info">24-horas está activado</string> <string name="status_bar_clock_style_right">Derecha</string> <string name="status_bar_clock_style_left">Izquierda</string> <string name="status_bar_clock_style_center">Centrado</string> <string name="clock_date_display">Fecha</string> <string name="clock_date_style">Estilo de fecha</string> <string name="clock_date_format">Formado de fecha</string> <string name="clock_date_string_edittext_title">Debe de ser un formato DateFormat ej. MM/dd/yy</string> <string name="clock_date_string_edittext_summary">Introducir cadena</string> <string name="clock_am_pm_date_normal">Normal</string> <string name="clock_am_pm_date_small">Pequeño</string> <string name="clock_am_pm_date_none">Oculto</string> <string name="clock_date_style_lowercase">Minúsculas</string> <string name="clock_date_style_uppercase">Mayúsculas</string> <string name="clock_date_format_custom">Formato personalizado Java</string> <!-- Device Frag strings --> <string name="toolinfo_title">Herramientas e Información</string> <string name="toolinfo_summary">Muestra información acerca del dispositivo y proporciona varias utilidades como por ejemplo un editor de propiedades</string> <string name="device_info_title">Información del teléfono</string> <string name="device_summ">Obtener información general sobre el dispositivo</string> <string name="title_battery_history">Historial de batería</string> <string name="summary_battery_history">Resumen sobre el uso de la batería</string> <string name="title_usage_statistics">Estadísticas de uso</string> <string name="summary_usage_statistics">Resumen de uso por aplicación</string> <string name="wifi_title">Información WiFi</string> <string name="wifi_summary">Información relevante sobre varios bits del WiFi</string> <!-- Battery Fragment --> <string name="battery_frag_title">Ajustes de batería</string> <string name="battery_frag_summary">Cambiar el icono y porcentaje de la batería</string> <string name="status_bar_battery_style_title">Estilo para la batería en la barra de estado</string> <string name="status_bar_battery_style_icon_portrait">Icono vertical</string> <string name="status_bar_battery_style_icon_landscape">Icono horizontal</string> <string name="status_bar_battery_style_circle">Circulo</string> <string name="status_bar_battery_style_dotted_circle">Circulo punteado</string> <string name="status_bar_battery_style_text">Texto</string> <string name="status_bar_battery_style_hidden">Oculto</string> <string name="status_bar_battery_percentage_title">Mostrar porcentaje</string> <string name="status_bar_battery_percentage_default">Oculto</string> <string name="status_bar_battery_percentage_text_inside">Dentro del icono</string> <string name="status_bar_battery_percentage_text_next">Al lado del icono</string> <!-- carrierlabel fragment --> <string name="carrierlabelfrag_title">Etiqueta de Operador</string> <string name="carrier_options_summary">Personalizar la etiqueta del operador</string> <string name="custom_carrier_label_title">Etiqueta del operador personalizada</string> <string name="custom_carrier_label_explain">Introducir nueva etiqueta. Dejar en blanco para revertir los cambios por defecto.</string> <string name="custom_carrier_label_notset">Etiqueta personalizada no está establecida</string> <string name="show_carrier_title">Etiqueta de operador</string> <string name="show_carrier_disabled">Desactivada</string> <string name="show_carrier_keyguard">Sólo en pantalla de bloqueo</string> <string name="show_carrier_statusbar">Sólo en la barra de estado</string> <string name="show_carrier_enabled">En pantalla de bloqueo y barra de estado</string> <!-- Color picker strings --> <string name="dialog_color_picker">Selector de color</string> <string name="press_color_to_apply">Pulsar en Color para aplicar</string> <string name="hex">Hex:</string> <string name="hex_hint">#FFDDDDDD</string> <string name="hex_check_button_text">PREVISUALIZAR</string> <string name="hex_reset_button_text">RESETEAR</string> <string name="colorpicker_summary">Color actual</string> <string name="color_right_arrow">"→"</string> <string name="color_down_arrow">"↓"</string> <string name="longpress_info">Pulsación larga para guardar el color</string> <!-- Content Description --> <string name="desc_list_item_icon">Item Icon</string> <!-- Error strings --> <string name="no_browser_error">Necesitas un navegador instalado!</string> <string name="no_root_error">Root no disponible? Algunas funcione no funcionarán como debieran!</string> <string name="general_error">Ocurrió un error</string> <string name="no_room_error">No queda espacio en \/system - No se puede editar</string> <string name="no_backup_error">Error: Archivo de backup no existe!</string> <!-- General strings --> <string name="ok">OK</string> <string name="reset">Resetear</string> <string name="cancel">Cancelar</string> <!-- Network traffic fragment --> <string name="status_bar_traffic_summary">Opciones del Tráfico de Red</string> <string name="nettraffic_frag_title">Tráfico de Red</string> <string name="show_network_traffic_state">Monitorizar el tráfico de red en la barra de estado</string> <string name="show_network_traffic_unit">Unidades de medida</string> <string name="show_network_traffic_frequency">Intervalo de actualización</string> <string name="show_network_traffic_disable">Desactivado</string> <string name="show_network_traffic_up">Saliente</string> <string name="show_network_traffic_down">Entrante</string> <string name="show_network_traffic_all">Saliente y entrante</string> <string name="show_network_traffic_bit">Bits por segundo</string> <string name="show_network_traffic_byte">Bytes por segundo</string> <string name="show_network_traffic_500">500 ms</string> <string name="show_network_traffic_1000">1000 ms</string> <string name="show_network_traffic_1500">1500 ms</string> <string name="show_network_traffic_2000">2000 ms</string> <string name="network_traffic_autohide">Auto ocultar</string> <string name="network_traffic_autohide_summary">Ocultar el tráfico de red cuando no haya actividad</string> <string name="network_traffic_autohide_threshold">Umbral de Inactividad</string> <!-- toolbar menu strings --> <string name="saveprop">Guardar</string> <string name="discardprop">Descartar</string> <string name="deleteprop">Borrar</string> <string name="cancelprop">Cancelar</string> <!-- =========================================================================================== --> </resources>
{ "content_hash": "706ce69d4ff9c97110ae16cffbc103f8", "timestamp": "", "source": "github", "line_count": 387, "max_line_length": 359, "avg_line_length": 66.89147286821705, "alnum_prop": 0.7290145632943176, "repo_name": "Ant-Droid/android_packages_apps_Settings_OLD", "id": "86a0c20c7b43fb31001adf2c233ad4a698c21180", "size": "26018", "binary": false, "copies": "1", "ref": "refs/heads/mm600", "path": "res/values/antos_strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4780700" }, { "name": "Makefile", "bytes": "4337" }, { "name": "Python", "bytes": "1310" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>TheFuzz v0.2.1 – Documentation</title> <meta http-equiv="refresh" content="0; url=overview.html" /> <meta name="index" content="noindex" /> <meta name="generator" content="ExDoc" /> </head> <body></body> </html>
{ "content_hash": "9c7040495151a0daf8b79e2a14410c0b", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 64, "avg_line_length": 27.272727272727273, "alnum_prop": 0.61, "repo_name": "hashd/the_fuzz", "id": "81e53ec05b624dedaa4a0c6da0e7565d5cdf6b75", "size": "302", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Elixir", "bytes": "58867" } ], "symlink_target": "" }
package models // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "github.com/go-openapi/errors" "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" ) // TraceSelector Context describing a pair of source and destination identity // // swagger:model TraceSelector type TraceSelector struct { // from From *TraceFrom `json:"from,omitempty"` // to To *TraceTo `json:"to,omitempty"` // Enable verbose tracing. // Verbose bool `json:"verbose,omitempty"` } // Validate validates this trace selector func (m *TraceSelector) Validate(formats strfmt.Registry) error { var res []error if err := m.validateFrom(formats); err != nil { res = append(res, err) } if err := m.validateTo(formats); err != nil { res = append(res, err) } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil } func (m *TraceSelector) validateFrom(formats strfmt.Registry) error { if swag.IsZero(m.From) { // not required return nil } if m.From != nil { if err := m.From.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("from") } return err } } return nil } func (m *TraceSelector) validateTo(formats strfmt.Registry) error { if swag.IsZero(m.To) { // not required return nil } if m.To != nil { if err := m.To.Validate(formats); err != nil { if ve, ok := err.(*errors.Validation); ok { return ve.ValidateName("to") } return err } } return nil } // MarshalBinary interface implementation func (m *TraceSelector) MarshalBinary() ([]byte, error) { if m == nil { return nil, nil } return swag.WriteJSON(m) } // UnmarshalBinary interface implementation func (m *TraceSelector) UnmarshalBinary(b []byte) error { var res TraceSelector if err := swag.ReadJSON(b, &res); err != nil { return err } *m = res return nil }
{ "content_hash": "186cfa093376976db478f0e5c4d93f9a", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 84, "avg_line_length": 19.908163265306122, "alnum_prop": 0.6765761148129165, "repo_name": "michi-covalent/cilium", "id": "a7b51f7d34677e021fcb3050b9ff40f2ecaf934b", "size": "2069", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "api/v1/models/trace_selector.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1006139" }, { "name": "Dockerfile", "bytes": "27010" }, { "name": "Go", "bytes": "10616051" }, { "name": "HCL", "bytes": "1394" }, { "name": "Makefile", "bytes": "77713" }, { "name": "Mustache", "bytes": "1457" }, { "name": "Python", "bytes": "14112" }, { "name": "Ruby", "bytes": "394" }, { "name": "Shell", "bytes": "379234" }, { "name": "SmPL", "bytes": "10748" }, { "name": "Smarty", "bytes": "16005" }, { "name": "TeX", "bytes": "416" } ], "symlink_target": "" }
/* $Id: UIGChooserModel.cpp $ */ /** @file * VBox Qt GUI - UIGChooserModel class implementation. */ /* * Copyright (C) 2012-2013 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Qt includes: */ # include <QGraphicsScene> # include <QGraphicsView> # include <QRegExp> # include <QGraphicsSceneMouseEvent> # include <QGraphicsSceneContextMenuEvent> # include <QPropertyAnimation> # include <QScrollBar> # include <QTimer> /* GUI includes: */ # include "UIGChooser.h" # include "UIGChooserModel.h" # include "UIGChooserItemGroup.h" # include "UIGChooserItemMachine.h" # include "UIExtraDataDefs.h" # include "VBoxGlobal.h" # include "UIMessageCenter.h" # include "UIExtraDataManager.h" # include "UIActionPoolSelector.h" # include "UIGChooserHandlerMouse.h" # include "UIGChooserHandlerKeyboard.h" # include "UIWizardNewVM.h" # include "UISelectorWindow.h" # include "UIVirtualBoxEventHandler.h" /* COM includes: */ # include "CVirtualBox.h" # include "CMachine.h" # include "CMedium.h" #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ #include <QParallelAnimationGroup> /* Type defs: */ typedef QSet<QString> UIStringSet; UIGChooserModel::UIGChooserModel(UIGChooser *pParent) : QObject(pParent) , m_pChooser(pParent) , m_pScene(0) , m_fSliding(false) , m_pLeftRoot(0) , m_pRightRoot(0) , m_pAfterSlidingFocus(0) , m_pMouseHandler(0) , m_pKeyboardHandler(0) , m_iScrollingTokenSize(30) , m_fIsScrollingInProgress(false) , m_pContextMenuGroup(0) , m_pContextMenuMachine(0) , m_pLookupTimer(0) { /* Prepare scene: */ prepareScene(); /* Prepare root: */ prepareRoot(); /* Prepare lookup: */ prepareLookup(); /* Prepare context-menu: */ prepareContextMenu(); /* Prepare handlers: */ prepareHandlers(); /* Prepare connections: */ prepareConnections(); } UIGChooserModel::~UIGChooserModel() { /* Cleanup handlers: */ cleanupHandlers(); /* Prepare context-menu: */ cleanupContextMenu(); /* Cleanup lookup: */ cleanupLookup(); /* Cleanup root: */ cleanupRoot(); /* Cleanup scene: */ cleanupScene(); } void UIGChooserModel::prepare() { /* Load group tree: */ loadGroupTree(); /* Update navigation: */ updateNavigation(); /* Update layout: */ updateLayout(); /* Load last selected item: */ loadLastSelectedItem(); } void UIGChooserModel::cleanup() { /* Save last selected item: */ saveLastSelectedItem(); /* Currently we are not saving group descriptors * (which reflecting group toggle-state) on-the-fly * So, for now we are additionally save group orders * when exiting application: */ saveGroupOrders(); /* Make sure all saving steps complete: */ makeSureGroupDefinitionsSaveIsFinished(); makeSureGroupOrdersSaveIsFinished(); } UIActionPool* UIGChooserModel::actionPool() const { return chooser()->actionPool(); } QGraphicsScene* UIGChooserModel::scene() const { return m_pScene; } QPaintDevice* UIGChooserModel::paintDevice() const { if (!m_pScene || m_pScene->views().isEmpty()) return 0; return m_pScene->views().first(); } QGraphicsItem* UIGChooserModel::itemAt(const QPointF &position, const QTransform &deviceTransform /* = QTransform() */) const { return scene()->itemAt(position, deviceTransform); } void UIGChooserModel::updateLayout() { /* No layout updates while sliding: */ if (m_fSliding) return; /* Initialize variables: */ int iSceneMargin = data(ChooserModelData_Margin).toInt(); QSize viewportSize = scene()->views()[0]->viewport()->size(); int iViewportWidth = viewportSize.width() - 2 * iSceneMargin; int iViewportHeight = viewportSize.height() - 2 * iSceneMargin; /* Set root-item position: */ root()->setPos(iSceneMargin, iSceneMargin); /* Set root-item size: */ root()->resize(iViewportWidth, iViewportHeight); /* Relayout root-item: */ root()->updateLayout(); /* Make sure root-item is shown: */ root()->show(); } const QList<UIGChooserItem*>& UIGChooserModel::navigationList() const { return m_navigationList; } void UIGChooserModel::removeFromNavigationList(UIGChooserItem *pItem) { AssertMsg(pItem, ("Passed item is invalid!")); m_navigationList.removeAll(pItem); } void UIGChooserModel::updateNavigation() { m_navigationList.clear(); m_navigationList = createNavigationList(root()); } UIVMItem* UIGChooserModel::currentMachineItem() const { /* Return first machine-item of the current-item: */ return currentItem() ? currentItem()->firstMachineItem() : 0; } QList<UIVMItem*> UIGChooserModel::currentMachineItems() const { /* Gather list of current unique machine-items: */ QList<UIGChooserItemMachine*> currentMachineItemList; UIGChooserItemMachine::enumerateMachineItems(currentItems(), currentMachineItemList, UIGChooserItemMachineEnumerationFlag_Unique); /* Reintegrate machine-items into valid format: */ QList<UIVMItem*> currentMachineList; foreach (UIGChooserItemMachine *pItem, currentMachineItemList) currentMachineList << pItem; return currentMachineList; } UIGChooserItem* UIGChooserModel::currentItem() const { /* Return first of current items, if any: */ return currentItems().isEmpty() ? 0 : currentItems().first(); } const QList<UIGChooserItem*>& UIGChooserModel::currentItems() const { return m_currentItems; } void UIGChooserModel::setCurrentItems(const QList<UIGChooserItem*> &items) { /* Is there something seems to be changed? */ if (m_currentItems == items) return; /* Remember old current-item list: */ QList<UIGChooserItem*> oldCurrentItems = m_currentItems; /* Clear current current-item list: */ m_currentItems.clear(); /* Iterate over all the passed items: */ foreach (UIGChooserItem *pItem, items) { /* If navigation list contains iterated-item: */ if (pItem && navigationList().contains(pItem)) { /* Add that item to current: */ m_currentItems << pItem; } else AssertMsgFailed(("Passed item not in navigation list!")); } /* Is there something really changed? */ if (oldCurrentItems == m_currentItems) return; /* Update all the old items (they are no longer selected): */ foreach (UIGChooserItem *pItem, oldCurrentItems) pItem->update(); /* Update all the new items (they are selected): */ foreach (UIGChooserItem *pItem, m_currentItems) pItem->update(); /* Notify about selection changes: */ notifyCurrentItemChanged(); } void UIGChooserModel::setCurrentItem(UIGChooserItem *pItem) { /* Call for wrapper above: */ QList<UIGChooserItem*> items; if (pItem) items << pItem; setCurrentItems(items); /* Move focus to current-item: */ setFocusItem(currentItem()); } void UIGChooserModel::setCurrentItem(const QString &strDefinition) { /* Ignore if empty definition passed: */ if (strDefinition.isEmpty()) return; /* Parse definition: */ UIGChooserItem *pItem = 0; QString strItemType = strDefinition.section('=', 0, 0); QString strItemDescriptor = strDefinition.section('=', 1, -1); /* Its a group-item definition? */ if (strItemType == "g") { /* Search for group-item with passed descriptor (name): */ pItem = mainRoot()->searchForItem(strItemDescriptor, UIGChooserItemSearchFlag_Group | UIGChooserItemSearchFlag_ExactName); } /* Its a machine-item definition? */ else if (strItemType == "m") { /* Check if machine-item with passed descriptor (name or id) registered: */ CMachine machine = vboxGlobal().virtualBox().FindMachine(strItemDescriptor); if (!machine.isNull()) { /* Search for machine-item with required name: */ pItem = mainRoot()->searchForItem(machine.GetName(), UIGChooserItemSearchFlag_Machine | UIGChooserItemSearchFlag_ExactName); } } /* Make sure found item is in navigation list: */ if (!pItem || !navigationList().contains(pItem)) return; /* Call for wrapper above: */ setCurrentItem(pItem); } void UIGChooserModel::unsetCurrentItem() { /* Call for wrapper above: */ setCurrentItem(0); } void UIGChooserModel::addToCurrentItems(UIGChooserItem *pItem) { /* Call for wrapper above: */ setCurrentItems(QList<UIGChooserItem*>(m_currentItems) << pItem); } void UIGChooserModel::removeFromCurrentItems(UIGChooserItem *pItem) { /* Prepare filtered list: */ QList<UIGChooserItem*> list(m_currentItems); list.removeAll(pItem); /* Call for wrapper above: */ setCurrentItems(list); } void UIGChooserModel::makeSureSomeItemIsSelected() { /* Make sure selection item list is never empty * if at least one item (for example 'focus') present: */ if (!currentItem() && focusItem()) setCurrentItem(focusItem()); } void UIGChooserModel::notifyCurrentItemChanged() { /* Notify listeners about selection change: */ emit sigSelectionChanged(); } bool UIGChooserModel::isSingleGroupSelected() const { return currentItems().size() == 1 && currentItem()->type() == UIGChooserItemType_Group; } bool UIGChooserModel::isAllItemsOfOneGroupSelected() const { /* Make sure at least one item selected: */ if (currentItems().isEmpty()) return false; /* Determine the parent group of the first item: */ UIGChooserItem *pFirstParent = currentItem()->parentItem(); /* Make sure this parent is not main root-item: */ if (pFirstParent == mainRoot()) return false; /* Enumerate current-item set: */ QSet<UIGChooserItem*> currentItemSet; foreach (UIGChooserItem *pCurrentItem, currentItems()) currentItemSet << pCurrentItem; /* Enumerate first parent children set: */ QSet<UIGChooserItem*> firstParentItemSet; foreach (UIGChooserItem *pFirstParentItem, pFirstParent->items()) firstParentItemSet << pFirstParentItem; /* Check if both sets contains the same: */ return currentItemSet == firstParentItemSet; } UIGChooserItem* UIGChooserModel::focusItem() const { return m_pFocusItem; } void UIGChooserModel::setFocusItem(UIGChooserItem *pItem) { /* Make sure real focus unset: */ clearRealFocus(); /* Is there something changed? */ if (m_pFocusItem == pItem) return; /* Remember old focus-item: */ UIGChooserItem *pOldFocusItem = m_pFocusItem; /* Set new focus-item: */ m_pFocusItem = pItem; /* Disconnect old focus-item (if any): */ if (pOldFocusItem) disconnect(pOldFocusItem, SIGNAL(destroyed(QObject*)), this, SLOT(sltFocusItemDestroyed())); /* Connect new focus-item (if any): */ if (m_pFocusItem) connect(m_pFocusItem, SIGNAL(destroyed(QObject*)), this, SLOT(sltFocusItemDestroyed())); /* Notify listeners about focus change: */ emit sigFocusChanged(m_pFocusItem); } UIGChooserItem* UIGChooserModel::mainRoot() const { return m_rootStack.first(); } UIGChooserItem* UIGChooserModel::root() const { return m_rootStack.last(); } void UIGChooserModel::indentRoot(UIGChooserItem *pNewRootItem) { /* Do nothing if sliding already: */ if (m_fSliding) return; /* We are sliding: */ m_fSliding = true; emit sigSlidingStarted(); /* Hiding root: */ root()->hide(); /* Create left root: */ bool fLeftRootIsMain = root() == mainRoot(); m_pLeftRoot = new UIGChooserItemGroup(scene(), root()->toGroupItem(), fLeftRootIsMain); m_pLeftRoot->setPos(0, 0); m_pLeftRoot->resize(root()->geometry().size()); /* Create right root: */ m_pRightRoot = new UIGChooserItemGroup(scene(), pNewRootItem->toGroupItem(), false); m_pRightRoot->setPos(root()->geometry().width(), 0); m_pRightRoot->resize(root()->geometry().size()); /* Indent root: */ m_rootStack << pNewRootItem; root()->setRoot(true); m_pAfterSlidingFocus = root()->items().first(); /* Slide root: */ slideRoot(true); } void UIGChooserModel::unindentRoot() { /* Do nothing if sliding already: */ if (m_fSliding) return; /* We are sliding: */ m_fSliding = true; emit sigSlidingStarted(); /* Hiding root: */ root()->hide(); root()->setRoot(false); /* Create left root: */ bool fLeftRootIsMain = m_rootStack.at(m_rootStack.size() - 2) == mainRoot(); m_pLeftRoot = new UIGChooserItemGroup(scene(), m_rootStack.at(m_rootStack.size() - 2)->toGroupItem(), fLeftRootIsMain); m_pLeftRoot->setPos(- root()->geometry().width(), 0); m_pLeftRoot->resize(root()->geometry().size()); /* Create right root: */ m_pRightRoot = new UIGChooserItemGroup(scene(), root()->toGroupItem(), false); m_pRightRoot->setPos(0, 0); m_pRightRoot->resize(root()->geometry().size()); /* Unindent root: */ m_pAfterSlidingFocus = root(); m_rootStack.removeLast(); /* Slide root: */ slideRoot(false); } bool UIGChooserModel::isSlidingInProgress() const { return m_fSliding; } void UIGChooserModel::startEditingGroupItemName() { sltEditGroupName(); } void UIGChooserModel::cleanupGroupTree() { cleanupGroupTree(mainRoot()); } /* static */ QString UIGChooserModel::uniqueGroupName(UIGChooserItem *pRoot) { /* Enumerate all the group names: */ QStringList groupNames; foreach (UIGChooserItem *pItem, pRoot->items(UIGChooserItemType_Group)) groupNames << pItem->name(); /* Prepare reg-exp: */ QString strMinimumName = tr("New group"); QString strShortTemplate = strMinimumName; QString strFullTemplate = strShortTemplate + QString(" (\\d+)"); QRegExp shortRegExp(strShortTemplate); QRegExp fullRegExp(strFullTemplate); /* Search for the maximum index: */ int iMinimumPossibleNumber = 0; foreach (const QString &strName, groupNames) { if (shortRegExp.exactMatch(strName)) iMinimumPossibleNumber = qMax(iMinimumPossibleNumber, 2); else if (fullRegExp.exactMatch(strName)) iMinimumPossibleNumber = qMax(iMinimumPossibleNumber, fullRegExp.cap(1).toInt() + 1); } /* Prepare result: */ QString strResult = strMinimumName; if (iMinimumPossibleNumber) strResult += " " + QString::number(iMinimumPossibleNumber); return strResult; } void UIGChooserModel::activateMachineItem() { actionPool()->action(UIActionIndexST_M_Machine_M_StartOrShow)->activate(QAction::Trigger); } void UIGChooserModel::setCurrentDragObject(QDrag *pDragObject) { /* Make sure real focus unset: */ clearRealFocus(); /* Remember new drag-object: */ m_pCurrentDragObject = pDragObject; connect(m_pCurrentDragObject, SIGNAL(destroyed(QObject*)), this, SLOT(sltCurrentDragObjectDestroyed())); } void UIGChooserModel::lookFor(const QString &strLookupSymbol) { /* Restart timer to reset lookup-string: */ m_pLookupTimer->start(); /* Prepare item: */ UIGChooserItem *pItem = 0; /* We are starting to look from the current position: */ int iCurrentIndex = navigationList().indexOf(currentItem()); /* Are we looking for the 1. same symbol or for the 2. composed word? */ const QString strLookupString = m_strLookupString.isEmpty() || m_strLookupString == strLookupSymbol ? strLookupSymbol : m_strLookupString + strLookupSymbol; /* Are we looking from the 1. subsequent position or from the 2. same one? */ const int iFirstIndex = m_strLookupString.isEmpty() || m_strLookupString == strLookupSymbol ? iCurrentIndex + 1 : iCurrentIndex; /* If first position feats the bounds: */ if (iFirstIndex < navigationList().size()) { /* We have to look starting from the first position: */ for (int iIndex = iFirstIndex; iIndex < navigationList().size(); ++iIndex) { UIGChooserItem *pIteratedItem = navigationList().at(iIndex); if (pIteratedItem->name().startsWith(strLookupString, Qt::CaseInsensitive)) { pItem = pIteratedItem; break; } } } /* If the item was not found: */ if (!pItem && iFirstIndex > 0) { /* We have to try to look from the beginning of the list: */ for (int iIndex = 0; iIndex < iFirstIndex; ++iIndex) { UIGChooserItem *pIteratedItem = navigationList().at(iIndex); if (pIteratedItem->name().startsWith(strLookupString, Qt::CaseInsensitive)) { pItem = pIteratedItem; break; } } } /* If that item was found: */ if (pItem) { /* Choose it: */ pItem->makeSureItsVisible(); setCurrentItem(pItem); /* Append lookup symbol: */ if (m_strLookupString != strLookupSymbol) m_strLookupString += strLookupSymbol; } } bool UIGChooserModel::isLookupInProgress() const { return m_pLookupTimer->isActive(); } void UIGChooserModel::saveGroupSettings() { emit sigStartGroupSaving(); } bool UIGChooserModel::isGroupSavingInProgress() const { return UIGroupDefinitionSaveThread::instance() || UIGroupOrderSaveThread::instance(); } void UIGChooserModel::sltMachineStateChanged(QString strId, KMachineState) { /* Update machine-items with passed id: */ mainRoot()->updateAll(strId); } void UIGChooserModel::sltMachineDataChanged(QString strId) { /* Update machine-items with passed id: */ mainRoot()->updateAll(strId); } void UIGChooserModel::sltMachineRegistered(QString strId, bool fRegistered) { /* New VM registered? */ if (fRegistered) { /* Search for corresponding machine: */ CMachine machine = vboxGlobal().virtualBox().FindMachine(strId); /* Should we show this machine? */ if (gEDataManager->showMachineInSelectorChooser(strId)) { /* Add new machine-item: */ addMachineIntoTheTree(machine, true); /* And update model: */ updateNavigation(); updateLayout(); setCurrentItem(mainRoot()->searchForItem(machine.GetName(), UIGChooserItemSearchFlag_Machine | UIGChooserItemSearchFlag_ExactName)); } } /* Existing VM unregistered? */ else { /* Remove machine-items with passed id: */ mainRoot()->removeAll(strId); /* Update model: */ cleanupGroupTree(); updateNavigation(); updateLayout(); /* Make sure current-item present, if possible: */ if (!currentItem() && !navigationList().isEmpty()) setCurrentItem(navigationList().first()); /* Make sure focus-item present, if possible: */ else if (!focusItem() && currentItem()) setFocusItem(currentItem()); /* Notify about current-item change: */ notifyCurrentItemChanged(); } } void UIGChooserModel::sltSessionStateChanged(QString strId, KSessionState) { /* Update machine-items with passed id: */ mainRoot()->updateAll(strId); } void UIGChooserModel::sltSnapshotChanged(QString strId, QString) { /* Update machine-items with passed id: */ mainRoot()->updateAll(strId); } void UIGChooserModel::sltHandleViewResized() { /* Relayout: */ updateLayout(); } void UIGChooserModel::sltFocusItemDestroyed() { AssertMsgFailed(("Focus item destroyed!")); } void UIGChooserModel::sltLeftRootSlidingProgress() { /* Update left root: */ m_pLeftRoot->updateGeometry(); m_pLeftRoot->updateLayout(); } void UIGChooserModel::sltRightRootSlidingProgress() { /* Update right root: */ m_pRightRoot->updateGeometry(); m_pRightRoot->updateLayout(); } void UIGChooserModel::sltSlidingComplete() { /* Delete temporary roots: */ delete m_pLeftRoot; m_pLeftRoot = 0; delete m_pRightRoot; m_pRightRoot = 0; /* We are no more sliding: */ m_fSliding = false; /* Update model: */ cleanupGroupTree(); updateNavigation(); updateLayout(); if (m_pAfterSlidingFocus) { setCurrentItem(m_pAfterSlidingFocus); m_pAfterSlidingFocus = 0; } else { if (!navigationList().isEmpty()) setCurrentItem(navigationList().first()); else unsetCurrentItem(); } } void UIGChooserModel::sltEditGroupName() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Group_S_Rename)->isEnabled()) return; /* Only for single selected group: */ if (!isSingleGroupSelected()) return; /* Start editing group name: */ currentItem()->startEditing(); } void UIGChooserModel::sltSortGroup() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Group_S_Sort)->isEnabled()) return; /* Only for single selected group: */ if (!isSingleGroupSelected()) return; /* Sorting group: */ currentItem()->sortItems(); } void UIGChooserModel::sltUngroupSelectedGroup() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Group_S_Remove)->isEnabled()) return; /* Make sure focus item is of group type! */ AssertMsg(focusItem()->type() == UIGChooserItemType_Group, ("This is not group-item!")); /* Check if we have collisions with our siblings: */ UIGChooserItem *pFocusItem = focusItem(); UIGChooserItem *pParentItem = pFocusItem->parentItem(); QList<UIGChooserItem*> siblings = pParentItem->items(); QList<UIGChooserItem*> toBeRenamed; QList<UIGChooserItem*> toBeRemoved; foreach (UIGChooserItem *pItem, pFocusItem->items()) { QString strItemName = pItem->name(); UIGChooserItem *pCollisionSibling = 0; foreach (UIGChooserItem *pSibling, siblings) if (pSibling != pFocusItem && pSibling->name() == strItemName) pCollisionSibling = pSibling; if (pCollisionSibling) { if (pItem->type() == UIGChooserItemType_Machine) { if (pCollisionSibling->type() == UIGChooserItemType_Machine) toBeRemoved << pItem; else if (pCollisionSibling->type() == UIGChooserItemType_Group) { msgCenter().cannotResolveCollisionAutomatically(strItemName, pParentItem->name()); return; } } else if (pItem->type() == UIGChooserItemType_Group) { if (msgCenter().confirmAutomaticCollisionResolve(strItemName, pParentItem->name())) toBeRenamed << pItem; else return; } } } /* Copy all the children into our parent: */ foreach (UIGChooserItem *pItem, pFocusItem->items()) { if (toBeRemoved.contains(pItem)) continue; switch (pItem->type()) { case UIGChooserItemType_Group: { UIGChooserItemGroup *pGroupItem = new UIGChooserItemGroup(pParentItem, pItem->toGroupItem()); if (toBeRenamed.contains(pItem)) pGroupItem->setName(uniqueGroupName(pParentItem)); break; } case UIGChooserItemType_Machine: { new UIGChooserItemMachine(pParentItem, pItem->toMachineItem()); break; } } } /* Delete focus group: */ delete focusItem(); /* And update model: */ updateNavigation(); updateLayout(); setCurrentItem(navigationList().first()); saveGroupSettings(); } void UIGChooserModel::sltCreateNewMachine() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Machine_S_New)->isEnabled()) return; /* Choose the parent: */ UIGChooserItem *pGroup = 0; if (isSingleGroupSelected()) pGroup = currentItem(); else if (!currentItems().isEmpty()) pGroup = currentItem()->parentItem(); QString strGroupName; if (pGroup) strGroupName = pGroup->fullName(); /* Start the new vm wizard: */ UISafePointerWizard pWizard = new UIWizardNewVM(&vboxGlobal().selectorWnd(), strGroupName); pWizard->prepare(); pWizard->exec(); if (pWizard) delete pWizard; } void UIGChooserModel::sltGroupSelectedMachines() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Machine_S_AddGroup)->isEnabled()) return; /* Create new group in the current root: */ UIGChooserItemGroup *pNewGroupItem = new UIGChooserItemGroup(root(), uniqueGroupName(root()), true); /* Enumerate all the currently chosen items: */ QStringList busyGroupNames; QStringList busyMachineNames; QList<UIGChooserItem*> selectedItems = currentItems(); foreach (UIGChooserItem *pItem, selectedItems) { /* For each of known types: */ switch (pItem->type()) { case UIGChooserItemType_Group: { /* Avoid name collisions: */ if (busyGroupNames.contains(pItem->name())) break; /* Add name to busy: */ busyGroupNames << pItem->name(); /* Copy or move group-item: */ new UIGChooserItemGroup(pNewGroupItem, pItem->toGroupItem()); delete pItem; break; } case UIGChooserItemType_Machine: { /* Avoid name collisions: */ if (busyMachineNames.contains(pItem->name())) break; /* Add name to busy: */ busyMachineNames << pItem->name(); /* Copy or move machine item: */ new UIGChooserItemMachine(pNewGroupItem, pItem->toMachineItem()); delete pItem; break; } } } /* Update model: */ cleanupGroupTree(); updateNavigation(); updateLayout(); setCurrentItem(pNewGroupItem); saveGroupSettings(); } void UIGChooserModel::sltReloadMachine(const QString &strId) { /* Remove all the items first: */ mainRoot()->removeAll(strId); /* Wipe out empty groups: */ cleanupGroupTree(); /* Show machine if we should: */ CMachine machine = vboxGlobal().virtualBox().FindMachine(strId); if (gEDataManager->showMachineInSelectorChooser(strId)) addMachineIntoTheTree(machine); /* And update model: */ updateNavigation(); updateLayout(); /* Make sure at least one item selected after that: */ if (!currentItem() && !navigationList().isEmpty()) setCurrentItem(navigationList().first()); /* Notify listeners about selection change: */ emit sigSelectionChanged(); } void UIGChooserModel::sltSortParentGroup() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Machine_S_SortParent)->isEnabled()) return; /* Only if some item selected: */ if (!currentItem()) return; /* Sorting parent group: */ currentItem()->parentItem()->sortItems(); } void UIGChooserModel::sltPerformRefreshAction() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Group_S_Refresh)->isEnabled()) return; /* Gather list of current unique inaccessible machine-items: */ QList<UIGChooserItemMachine*> inaccessibleMachineItemList; UIGChooserItemMachine::enumerateMachineItems(currentItems(), inaccessibleMachineItemList, UIGChooserItemMachineEnumerationFlag_Unique | UIGChooserItemMachineEnumerationFlag_Inaccessible); /* For each machine-item: */ UIGChooserItem *pSelectedItem = 0; foreach (UIGChooserItemMachine *pItem, inaccessibleMachineItemList) { /* Recache: */ pItem->recache(); /* Become accessible? */ if (pItem->accessible()) { /* Machine name: */ QString strMachineName = pItem->name(); /* We should reload this machine: */ sltReloadMachine(pItem->id()); /* Select first of reloaded items: */ if (!pSelectedItem) pSelectedItem = mainRoot()->searchForItem(strMachineName, UIGChooserItemSearchFlag_Machine | UIGChooserItemSearchFlag_ExactName); } } /* Some item to be selected? */ if (pSelectedItem) { pSelectedItem->makeSureItsVisible(); setCurrentItem(pSelectedItem); } } void UIGChooserModel::sltRemoveSelectedMachine() { /* Check if action is enabled: */ if (!actionPool()->action(UIActionIndexST_M_Machine_S_Remove)->isEnabled()) return; /* Enumerate all the selected machine-items: */ QList<UIGChooserItemMachine*> selectedMachineItemList; UIGChooserItemMachine::enumerateMachineItems(currentItems(), selectedMachineItemList); /* Enumerate all the existing machine-items: */ QList<UIGChooserItemMachine*> existingMachineItemList; UIGChooserItemMachine::enumerateMachineItems(mainRoot()->items(), existingMachineItemList); /* Prepare arrays: */ QMap<QString, bool> verdicts; QList<UIGChooserItem*> itemsToRemove; QStringList machinesToUnregister; /* For each selected machine-item: */ foreach (UIGChooserItem *pItem, selectedMachineItemList) { /* Get machine-item id: */ QString strId = pItem->toMachineItem()->id(); /* We already decided for that machine? */ if (verdicts.contains(strId)) { /* To remove similar machine items? */ if (!verdicts[strId]) itemsToRemove << pItem; continue; } /* Selected copy count: */ int iSelectedCopyCount = 0; foreach (UIGChooserItem *pSelectedItem, selectedMachineItemList) if (pSelectedItem->toMachineItem()->id() == strId) ++iSelectedCopyCount; /* Existing copy count: */ int iExistingCopyCount = 0; foreach (UIGChooserItem *pExistingItem, existingMachineItemList) if (pExistingItem->toMachineItem()->id() == strId) ++iExistingCopyCount; /* If selected copy count equal to existing copy count, * we will propose ro unregister machine fully else * we will just propose to remove selected items: */ bool fVerdict = iSelectedCopyCount == iExistingCopyCount; verdicts.insert(strId, fVerdict); if (fVerdict) machinesToUnregister << strId; else itemsToRemove << pItem; } /* If we have something to remove: */ if (!itemsToRemove.isEmpty()) removeItems(itemsToRemove); /* If we have something to unregister: */ if (!machinesToUnregister.isEmpty()) unregisterMachines(machinesToUnregister); } void UIGChooserModel::sltStartScrolling() { /* Should we scroll? */ if (!m_fIsScrollingInProgress) return; /* Reset scrolling progress: */ m_fIsScrollingInProgress = false; /* Get view/scrollbar: */ QGraphicsView *pView = scene()->views()[0]; QScrollBar *pVerticalScrollBar = pView->verticalScrollBar(); /* Request still valid? */ QPoint mousePos = pView->mapFromGlobal(QCursor::pos()); if (mousePos.y() < m_iScrollingTokenSize) { int iValue = mousePos.y(); if (!iValue) iValue = 1; int iDelta = m_iScrollingTokenSize / iValue; if (pVerticalScrollBar->value() > pVerticalScrollBar->minimum()) { /* Backward scrolling: */ pVerticalScrollBar->setValue(pVerticalScrollBar->value() - 2 * iDelta); m_fIsScrollingInProgress = true; QTimer::singleShot(10, this, SLOT(sltStartScrolling())); } } else if (mousePos.y() > pView->height() - m_iScrollingTokenSize) { int iValue = pView->height() - mousePos.y(); if (!iValue) iValue = 1; int iDelta = m_iScrollingTokenSize / iValue; if (pVerticalScrollBar->value() < pVerticalScrollBar->maximum()) { /* Forward scrolling: */ pVerticalScrollBar->setValue(pVerticalScrollBar->value() + 2 * iDelta); m_fIsScrollingInProgress = true; QTimer::singleShot(10, this, SLOT(sltStartScrolling())); } } } void UIGChooserModel::sltCurrentDragObjectDestroyed() { root()->resetDragToken(); } void UIGChooserModel::sltActionHovered(QAction *pAction) { emit sigShowStatusMessage(pAction->statusTip()); } void UIGChooserModel::sltEraseLookupTimer() { m_pLookupTimer->stop(); m_strLookupString = QString(); } void UIGChooserModel::sltGroupSavingStart() { saveGroupDefinitions(); saveGroupOrders(); } void UIGChooserModel::sltGroupDefinitionsSaveComplete() { makeSureGroupDefinitionsSaveIsFinished(); emit sigGroupSavingStateChanged(); } void UIGChooserModel::sltGroupOrdersSaveComplete() { makeSureGroupOrdersSaveIsFinished(); emit sigGroupSavingStateChanged(); } QVariant UIGChooserModel::data(int iKey) const { switch (iKey) { case ChooserModelData_Margin: return 0; default: break; } return QVariant(); } void UIGChooserModel::prepareScene() { m_pScene = new QGraphicsScene(this); m_pScene->installEventFilter(this); } void UIGChooserModel::prepareRoot() { m_rootStack << new UIGChooserItemGroup(scene()); } void UIGChooserModel::prepareLookup() { m_pLookupTimer = new QTimer(this); m_pLookupTimer->setInterval(1000); m_pLookupTimer->setSingleShot(true); connect(m_pLookupTimer, SIGNAL(timeout()), this, SLOT(sltEraseLookupTimer())); } void UIGChooserModel::prepareContextMenu() { /* Context menu for group(s): */ m_pContextMenuGroup = new QMenu; m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_New)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Add)); m_pContextMenuGroup->addSeparator(); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Rename)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Remove)); m_pContextMenuGroup->addSeparator(); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_M_StartOrShow)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_T_Pause)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Reset)); m_pContextMenuGroup->addMenu(actionPool()->action(UIActionIndexST_M_Group_M_Close)->menu()); m_pContextMenuGroup->addSeparator(); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Discard)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_ShowLogDialog)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Refresh)); m_pContextMenuGroup->addSeparator(); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_ShowInFileManager)); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_CreateShortcut)); m_pContextMenuGroup->addSeparator(); m_pContextMenuGroup->addAction(actionPool()->action(UIActionIndexST_M_Group_S_Sort)); /* Context menu for machine(s): */ m_pContextMenuMachine = new QMenu; m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Settings)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Clone)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Remove)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_AddGroup)); m_pContextMenuMachine->addSeparator(); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_M_StartOrShow)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_T_Pause)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Reset)); m_pContextMenuMachine->addMenu(actionPool()->action(UIActionIndexST_M_Machine_M_Close)->menu()); m_pContextMenuMachine->addSeparator(); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Discard)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_ShowLogDialog)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_Refresh)); m_pContextMenuMachine->addSeparator(); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_ShowInFileManager)); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_CreateShortcut)); m_pContextMenuMachine->addSeparator(); m_pContextMenuMachine->addAction(actionPool()->action(UIActionIndexST_M_Machine_S_SortParent)); connect(m_pContextMenuGroup, SIGNAL(hovered(QAction*)), this, SLOT(sltActionHovered(QAction*))); connect(m_pContextMenuMachine, SIGNAL(hovered(QAction*)), this, SLOT(sltActionHovered(QAction*))); connect(actionPool()->action(UIActionIndexST_M_Group_S_New), SIGNAL(triggered()), this, SLOT(sltCreateNewMachine())); connect(actionPool()->action(UIActionIndexST_M_Machine_S_New), SIGNAL(triggered()), this, SLOT(sltCreateNewMachine())); connect(actionPool()->action(UIActionIndexST_M_Group_S_Rename), SIGNAL(triggered()), this, SLOT(sltEditGroupName())); connect(actionPool()->action(UIActionIndexST_M_Group_S_Remove), SIGNAL(triggered()), this, SLOT(sltUngroupSelectedGroup())); connect(actionPool()->action(UIActionIndexST_M_Machine_S_Remove), SIGNAL(triggered()), this, SLOT(sltRemoveSelectedMachine())); connect(actionPool()->action(UIActionIndexST_M_Machine_S_AddGroup), SIGNAL(triggered()), this, SLOT(sltGroupSelectedMachines())); connect(actionPool()->action(UIActionIndexST_M_Group_S_Refresh), SIGNAL(triggered()), this, SLOT(sltPerformRefreshAction())); connect(actionPool()->action(UIActionIndexST_M_Machine_S_Refresh), SIGNAL(triggered()), this, SLOT(sltPerformRefreshAction())); connect(actionPool()->action(UIActionIndexST_M_Machine_S_SortParent), SIGNAL(triggered()), this, SLOT(sltSortParentGroup())); connect(actionPool()->action(UIActionIndexST_M_Group_S_Sort), SIGNAL(triggered()), this, SLOT(sltSortGroup())); connect(this, SIGNAL(sigStartGroupSaving()), this, SLOT(sltGroupSavingStart()), Qt::QueuedConnection); } void UIGChooserModel::prepareHandlers() { m_pMouseHandler = new UIGChooserHandlerMouse(this); m_pKeyboardHandler = new UIGChooserHandlerKeyboard(this); } void UIGChooserModel::prepareConnections() { /* Setup parent connections: */ connect(this, SIGNAL(sigSelectionChanged()), parent(), SIGNAL(sigSelectionChanged())); connect(this, SIGNAL(sigSlidingStarted()), parent(), SIGNAL(sigSlidingStarted())); connect(this, SIGNAL(sigToggleStarted()), parent(), SIGNAL(sigToggleStarted())); connect(this, SIGNAL(sigToggleFinished()), parent(), SIGNAL(sigToggleFinished())); connect(this, SIGNAL(sigGroupSavingStateChanged()), parent(), SIGNAL(sigGroupSavingStateChanged())); /* Setup global connections: */ connect(gVBoxEvents, SIGNAL(sigMachineStateChange(QString, KMachineState)), this, SLOT(sltMachineStateChanged(QString, KMachineState))); connect(gVBoxEvents, SIGNAL(sigMachineDataChange(QString)), this, SLOT(sltMachineDataChanged(QString))); connect(gVBoxEvents, SIGNAL(sigMachineRegistered(QString, bool)), this, SLOT(sltMachineRegistered(QString, bool))); connect(gVBoxEvents, SIGNAL(sigSessionStateChange(QString, KSessionState)), this, SLOT(sltSessionStateChanged(QString, KSessionState))); connect(gVBoxEvents, SIGNAL(sigSnapshotTake(QString, QString)), this, SLOT(sltSnapshotChanged(QString, QString))); connect(gVBoxEvents, SIGNAL(sigSnapshotDelete(QString, QString)), this, SLOT(sltSnapshotChanged(QString, QString))); connect(gVBoxEvents, SIGNAL(sigSnapshotChange(QString, QString)), this, SLOT(sltSnapshotChanged(QString, QString))); connect(gVBoxEvents, SIGNAL(sigSnapshotRestore(QString, QString)), this, SLOT(sltSnapshotChanged(QString, QString))); } void UIGChooserModel::loadLastSelectedItem() { /* Load last selected item (choose first if unable to load): */ setCurrentItem(gEDataManager->selectorWindowLastItemChosen()); if (!currentItem() && !navigationList().isEmpty()) setCurrentItem(navigationList().first()); } void UIGChooserModel::saveLastSelectedItem() { /* Save last selected item: */ gEDataManager->setSelectorWindowLastItemChosen(currentItem() ? currentItem()->definition() : QString()); } void UIGChooserModel::cleanupHandlers() { delete m_pKeyboardHandler; m_pKeyboardHandler = 0; delete m_pMouseHandler; m_pMouseHandler = 0; } void UIGChooserModel::cleanupContextMenu() { delete m_pContextMenuGroup; m_pContextMenuGroup = 0; delete m_pContextMenuMachine; m_pContextMenuMachine = 0; } void UIGChooserModel::cleanupLookup() { delete m_pLookupTimer; m_pLookupTimer = 0; } void UIGChooserModel::cleanupRoot() { delete mainRoot(); m_rootStack.clear(); } void UIGChooserModel::cleanupScene() { delete m_pScene; m_pScene = 0; } bool UIGChooserModel::eventFilter(QObject *pWatched, QEvent *pEvent) { /* Process only scene events: */ if (pWatched != m_pScene) return QObject::eventFilter(pWatched, pEvent); /* Process only item focused by model: */ if (scene()->focusItem()) return QObject::eventFilter(pWatched, pEvent); /* Checking event-type: */ switch (pEvent->type()) { /* Keyboard handler: */ case QEvent::KeyPress: return m_pKeyboardHandler->handle(static_cast<QKeyEvent*>(pEvent), UIKeyboardEventType_Press); case QEvent::KeyRelease: return m_pKeyboardHandler->handle(static_cast<QKeyEvent*>(pEvent), UIKeyboardEventType_Release); /* Mouse handler: */ case QEvent::GraphicsSceneMousePress: return m_pMouseHandler->handle(static_cast<QGraphicsSceneMouseEvent*>(pEvent), UIMouseEventType_Press); case QEvent::GraphicsSceneMouseRelease: return m_pMouseHandler->handle(static_cast<QGraphicsSceneMouseEvent*>(pEvent), UIMouseEventType_Release); case QEvent::GraphicsSceneMouseDoubleClick: return m_pMouseHandler->handle(static_cast<QGraphicsSceneMouseEvent*>(pEvent), UIMouseEventType_DoubleClick); /* Context-menu handler: */ case QEvent::GraphicsSceneContextMenu: return processContextMenuEvent(static_cast<QGraphicsSceneContextMenuEvent*>(pEvent)); /* Drag&drop scroll-event handler: */ case QEvent::GraphicsSceneDragMove: return processDragMoveEvent(static_cast<QGraphicsSceneDragDropEvent*>(pEvent)); } /* Call to base-class: */ return QObject::eventFilter(pWatched, pEvent); } QList<UIGChooserItem*> UIGChooserModel::createNavigationList(UIGChooserItem *pItem) { /* Prepare navigation list: */ QList<UIGChooserItem*> navigationItems; /* Iterate over all the group-items: */ foreach (UIGChooserItem *pGroupItem, pItem->items(UIGChooserItemType_Group)) { navigationItems << pGroupItem; if (pGroupItem->toGroupItem()->isOpened()) navigationItems << createNavigationList(pGroupItem); } /* Iterate over all the machine-items: */ foreach (UIGChooserItem *pMachineItem, pItem->items(UIGChooserItemType_Machine)) navigationItems << pMachineItem; /* Return navigation list: */ return navigationItems; } void UIGChooserModel::clearRealFocus() { /* Set the real focus to null: */ scene()->setFocusItem(0); } void UIGChooserModel::slideRoot(bool fForward) { /* Animation group: */ QParallelAnimationGroup *pAnimation = new QParallelAnimationGroup(this); connect(pAnimation, SIGNAL(finished()), this, SLOT(sltSlidingComplete()), Qt::QueuedConnection); /* Left root animation: */ { QPropertyAnimation *pLeftAnimation = new QPropertyAnimation(m_pLeftRoot, "geometry", this); connect(pLeftAnimation, SIGNAL(valueChanged(const QVariant&)), this, SLOT(sltLeftRootSlidingProgress())); QRectF startGeo = m_pLeftRoot->geometry(); QRectF endGeo = fForward ? startGeo.translated(- startGeo.width(), 0) : startGeo.translated(startGeo.width(), 0); pLeftAnimation->setEasingCurve(QEasingCurve::InCubic); pLeftAnimation->setDuration(500); pLeftAnimation->setStartValue(startGeo); pLeftAnimation->setEndValue(endGeo); pAnimation->addAnimation(pLeftAnimation); } /* Right root animation: */ { QPropertyAnimation *pRightAnimation = new QPropertyAnimation(m_pRightRoot, "geometry", this); connect(pRightAnimation, SIGNAL(valueChanged(const QVariant&)), this, SLOT(sltRightRootSlidingProgress())); QRectF startGeo = m_pRightRoot->geometry(); QRectF endGeo = fForward ? startGeo.translated(- startGeo.width(), 0) : startGeo.translated(startGeo.width(), 0); pRightAnimation->setEasingCurve(QEasingCurve::InCubic); pRightAnimation->setDuration(500); pRightAnimation->setStartValue(startGeo); pRightAnimation->setEndValue(endGeo); pAnimation->addAnimation(pRightAnimation); } /* Start animation: */ pAnimation->start(); } void UIGChooserModel::cleanupGroupTree(UIGChooserItem *pParent) { /* Cleanup all the group-items recursively first: */ foreach (UIGChooserItem *pItem, pParent->items(UIGChooserItemType_Group)) cleanupGroupTree(pItem); /* If parent has no items: */ if (!pParent->hasItems()) { /* Cleanup if that is non-root item: */ if (!pParent->isRoot()) delete pParent; /* Unindent if that is root item: */ else if (root() != mainRoot()) unindentRoot(); } } void UIGChooserModel::removeItems(const QList<UIGChooserItem*> &itemsToRemove) { /* Confirm machine-items removal: */ QStringList names; foreach (UIGChooserItem *pItem, itemsToRemove) names << pItem->name(); if (!msgCenter().confirmMachineItemRemoval(names)) return; /* Remove all the passed items: */ foreach (UIGChooserItem *pItem, itemsToRemove) delete pItem; /* And update model: */ cleanupGroupTree(); updateNavigation(); updateLayout(); if (!navigationList().isEmpty()) setCurrentItem(navigationList().first()); else unsetCurrentItem(); saveGroupSettings(); } void UIGChooserModel::unregisterMachines(const QStringList &ids) { /* Populate machine list: */ QList<CMachine> machines; CVirtualBox vbox = vboxGlobal().virtualBox(); foreach (const QString &strId, ids) { CMachine machine = vbox.FindMachine(strId); if (!machine.isNull()) machines << machine; } /* Confirm machine removal: */ int iResultCode = msgCenter().confirmMachineRemoval(machines); if (iResultCode == AlertButton_Cancel) return; /* Unset current item(s): */ unsetCurrentItem(); /* For every selected item: */ for (int iMachineIndex = 0; iMachineIndex < machines.size(); ++iMachineIndex) { /* Get iterated machine: */ CMachine &machine = machines[iMachineIndex]; if (iResultCode == AlertButton_Choice1) { /* Unregister machine first: */ CMediumVector mediums = machine.Unregister(KCleanupMode_DetachAllReturnHardDisksOnly); if (!machine.isOk()) { msgCenter().cannotRemoveMachine(machine); continue; } /* Prepare cleanup progress: */ CProgress progress = machine.DeleteConfig(mediums); if (!machine.isOk()) { msgCenter().cannotRemoveMachine(machine); continue; } /* And show cleanup progress finally: */ msgCenter().showModalProgressDialog(progress, machine.GetName(), ":/progress_delete_90px.png"); if (!progress.isOk() || progress.GetResultCode() != 0) { msgCenter().cannotRemoveMachine(machine, progress); continue; } } else if (iResultCode == AlertButton_Choice2 || iResultCode == AlertButton_Ok) { /* Unregister machine first: */ CMediumVector mediums = machine.Unregister(KCleanupMode_DetachAllReturnHardDisksOnly); if (!machine.isOk()) { msgCenter().cannotRemoveMachine(machine); continue; } /* Finally close all media, deliberately ignoring errors: */ foreach (CMedium medium, mediums) { if (!medium.isNull()) medium.Close(); } } } } bool UIGChooserModel::processContextMenuEvent(QGraphicsSceneContextMenuEvent *pEvent) { /* Whats the reason? */ switch (pEvent->reason()) { case QGraphicsSceneContextMenuEvent::Mouse: { /* First of all we should look for an item under cursor: */ if (QGraphicsItem *pItem = itemAt(pEvent->scenePos())) { /* If this item of known type? */ switch (pItem->type()) { case UIGChooserItemType_Group: { /* Get group-item: */ UIGChooserItem *pGroupItem = qgraphicsitem_cast<UIGChooserItemGroup*>(pItem); /* Make sure thats not root: */ if (pGroupItem->isRoot()) return false; /* Is this group-item only the one selected? */ if (currentItems().contains(pGroupItem) && currentItems().size() == 1) { /* Group context menu in that case: */ popupContextMenu(UIGraphicsSelectorContextMenuType_Group, pEvent->screenPos()); return true; } } case UIGChooserItemType_Machine: { /* Machine context menu for other Group/Machine cases: */ popupContextMenu(UIGraphicsSelectorContextMenuType_Machine, pEvent->screenPos()); return true; } default: break; } } return true; } case QGraphicsSceneContextMenuEvent::Keyboard: { /* Get first selected item: */ if (UIGChooserItem *pItem = currentItem()) { /* If this item of known type? */ switch (pItem->type()) { case UIGChooserItemType_Group: { /* Is this group-item only the one selected? */ if (currentItems().size() == 1) { /* Group context menu in that case: */ popupContextMenu(UIGraphicsSelectorContextMenuType_Group, pEvent->screenPos()); return true; } } case UIGChooserItemType_Machine: { /* Machine context menu for other Group/Machine cases: */ popupContextMenu(UIGraphicsSelectorContextMenuType_Machine, pEvent->screenPos()); return true; } default: break; } } return true; } default: break; } /* Pass others context menu events: */ return false; } void UIGChooserModel::popupContextMenu(UIGraphicsSelectorContextMenuType type, QPoint point) { /* Which type of context-menu requested? */ switch (type) { /* For group? */ case UIGraphicsSelectorContextMenuType_Group: { m_pContextMenuGroup->exec(point); break; } /* For machine(s)? */ case UIGraphicsSelectorContextMenuType_Machine: { m_pContextMenuMachine->exec(point); break; } } /* Clear status-bar: */ emit sigClearStatusMessage(); } bool UIGChooserModel::processDragMoveEvent(QGraphicsSceneDragDropEvent *pEvent) { /* Do we scrolling already? */ if (m_fIsScrollingInProgress) return false; /* Get view: */ QGraphicsView *pView = scene()->views()[0]; /* Check scroll-area: */ QPoint eventPoint = pView->mapFromGlobal(pEvent->screenPos()); if ((eventPoint.y() < m_iScrollingTokenSize) || (eventPoint.y() > pView->height() - m_iScrollingTokenSize)) { /* Set scrolling in progress: */ m_fIsScrollingInProgress = true; /* Start scrolling: */ QTimer::singleShot(200, this, SLOT(sltStartScrolling())); } /* Pass event: */ return false; } void UIGChooserModel::loadGroupTree() { /* Add all the approved machines we have into the group-tree: */ LogRelFlow(("UIGChooserModel: Loading VMs...\n")); foreach (CMachine machine, vboxGlobal().virtualBox().GetMachines()) { const QString strMachineID = machine.GetId(); if (!strMachineID.isEmpty() && gEDataManager->showMachineInSelectorChooser(strMachineID)) addMachineIntoTheTree(machine); } LogRelFlow(("UIGChooserModel: VMs loaded.\n")); } void UIGChooserModel::addMachineIntoTheTree(const CMachine &machine, bool fMakeItVisible /* = false */) { /* Make sure passed VM is not NULL: */ if (machine.isNull()) LogRelFlow(("UIGChooserModel: ERROR: Passed VM is NULL!\n")); AssertReturnVoid(!machine.isNull()); /* Which VM we are loading: */ LogRelFlow(("UIGChooserModel: Loading VM with ID={%s}...\n", machine.GetId().toAscii().constData())); /* Is that machine accessible? */ if (machine.GetAccessible()) { /* VM is accessible: */ QString strName = machine.GetName(); LogRelFlow(("UIGChooserModel: VM {%s} is accessible.\n", strName.toAscii().constData())); /* Which groups passed machine attached to? */ QVector<QString> groups = machine.GetGroups(); QStringList groupList = groups.toList(); QString strGroups = groupList.join(", "); LogRelFlow(("UIGChooserModel: VM {%s} has groups: {%s}.\n", strName.toAscii().constData(), strGroups.toAscii().constData())); foreach (QString strGroup, groups) { /* Remove last '/' if any: */ if (strGroup.right(1) == "/") strGroup.truncate(strGroup.size() - 1); /* Create machine-item with found group-item as parent: */ LogRelFlow(("UIGChooserModel: Creating item for VM {%s} in group {%s}.\n", strName.toAscii().constData(), strGroup.toAscii().constData())); createMachineItem(machine, getGroupItem(strGroup, mainRoot(), fMakeItVisible)); } /* Update group definitions: */ m_groups[machine.GetId()] = groupList; } /* Inaccessible machine: */ else { /* VM is accessible: */ LogRelFlow(("UIGChooserModel: VM {%s} is inaccessible.\n", machine.GetId().toAscii().constData())); /* Create machine-item with main-root group-item as parent: */ createMachineItem(machine, mainRoot()); } } UIGChooserItem* UIGChooserModel::getGroupItem(const QString &strName, UIGChooserItem *pParentItem, bool fAllGroupsOpened) { /* Check passed stuff: */ if (pParentItem->name() == strName) return pParentItem; /* Prepare variables: */ QString strFirstSubName = strName.section('/', 0, 0); QString strFirstSuffix = strName.section('/', 1, -1); QString strSecondSubName = strFirstSuffix.section('/', 0, 0); QString strSecondSuffix = strFirstSuffix.section('/', 1, -1); /* Passed group name equal to first sub-name: */ if (pParentItem->name() == strFirstSubName) { /* Make sure first-suffix is NOT empty: */ AssertMsg(!strFirstSuffix.isEmpty(), ("Invalid group name!")); /* Trying to get group-item among our children: */ foreach (UIGChooserItem *pGroupItem, pParentItem->items(UIGChooserItemType_Group)) { if (pGroupItem->name() == strSecondSubName) { UIGChooserItem *pFoundItem = getGroupItem(strFirstSuffix, pGroupItem, fAllGroupsOpened); if (UIGChooserItemGroup *pFoundGroupItem = pFoundItem->toGroupItem()) if (fAllGroupsOpened && pFoundGroupItem->isClosed()) pFoundGroupItem->open(false); return pFoundItem; } } } /* Found nothing? Creating: */ UIGChooserItemGroup *pNewGroupItem = new UIGChooserItemGroup(/* Parent item and desired group name: */ pParentItem, strSecondSubName, /* Should be new group opened when created? */ fAllGroupsOpened || shouldBeGroupOpened(pParentItem, strSecondSubName), /* Which position new group-item should be placed in? */ getDesiredPosition(pParentItem, UIGChooserItemType_Group, strSecondSubName)); return strSecondSuffix.isEmpty() ? pNewGroupItem : getGroupItem(strFirstSuffix, pNewGroupItem, fAllGroupsOpened); } bool UIGChooserModel::shouldBeGroupOpened(UIGChooserItem *pParentItem, const QString &strName) { /* Read group definitions: */ const QStringList definitions = gEDataManager->selectorWindowGroupsDefinitions(pParentItem->fullName()); /* Return 'false' if no definitions found: */ if (definitions.isEmpty()) return false; /* Prepare required group definition reg-exp: */ QString strDefinitionTemplate = QString("g(\\S)*=%1").arg(strName); QRegExp definitionRegExp(strDefinitionTemplate); /* For each the group definition: */ foreach (const QString &strDefinition, definitions) { /* Check if this is required definition: */ if (definitionRegExp.indexIn(strDefinition) == 0) { /* Get group descriptor: */ QString strDescriptor(definitionRegExp.cap(1)); if (strDescriptor.contains('o')) return true; } } /* Return 'false' by default: */ return false; } int UIGChooserModel::getDesiredPosition(UIGChooserItem *pParentItem, UIGChooserItemType type, const QString &strName) { /* End of list (by default)? */ int iNewItemDesiredPosition = -1; /* Which position should be new item placed by definitions: */ int iNewItemDefinitionPosition = positionFromDefinitions(pParentItem, type, strName); /* If some position wanted: */ if (iNewItemDefinitionPosition != -1) { /* Start of list if some definition present: */ iNewItemDesiredPosition = 0; /* We have to check all the existing item positions: */ QList<UIGChooserItem*> items = pParentItem->items(type); for (int i = items.size() - 1; i >= 0; --i) { /* Get current item: */ UIGChooserItem *pItem = items[i]; /* Which position should be current item placed by definitions? */ QString strDefinitionName = pItem->type() == UIGChooserItemType_Group ? pItem->name() : pItem->type() == UIGChooserItemType_Machine ? pItem->toMachineItem()->id() : QString(); AssertMsg(!strDefinitionName.isEmpty(), ("Wrong definition name!")); int iItemDefinitionPosition = positionFromDefinitions(pParentItem, type, strDefinitionName); /* If some position wanted: */ if (iItemDefinitionPosition != -1) { AssertMsg(iItemDefinitionPosition != iNewItemDefinitionPosition, ("Incorrect definitions!")); if (iItemDefinitionPosition < iNewItemDefinitionPosition) { iNewItemDesiredPosition = i + 1; break; } } } } /* Return desired item position: */ return iNewItemDesiredPosition; } int UIGChooserModel::positionFromDefinitions(UIGChooserItem *pParentItem, UIGChooserItemType type, const QString &strName) { /* Read group definitions: */ const QStringList definitions = gEDataManager->selectorWindowGroupsDefinitions(pParentItem->fullName()); /* Return 'false' if no definitions found: */ if (definitions.isEmpty()) return -1; /* Prepare definition reg-exp: */ QString strDefinitionTemplateShort; QString strDefinitionTemplateFull; switch (type) { case UIGChooserItemType_Group: strDefinitionTemplateShort = QString("^g(\\S)*="); strDefinitionTemplateFull = QString("^g(\\S)*=%1$").arg(strName); break; case UIGChooserItemType_Machine: strDefinitionTemplateShort = QString("^m="); strDefinitionTemplateFull = QString("^m=%1$").arg(strName); break; default: return -1; } QRegExp definitionRegExpShort(strDefinitionTemplateShort); QRegExp definitionRegExpFull(strDefinitionTemplateFull); /* For each the definition: */ int iDefinitionIndex = -1; foreach (const QString &strDefinition, definitions) { /* Check if this definition is of required type: */ if (definitionRegExpShort.indexIn(strDefinition) == 0) { ++iDefinitionIndex; /* Check if this definition is exactly what we need: */ if (definitionRegExpFull.indexIn(strDefinition) == 0) return iDefinitionIndex; } } /* Return result: */ return -1; } void UIGChooserModel::createMachineItem(const CMachine &machine, UIGChooserItem *pParentItem) { /* Create corresponding item: */ new UIGChooserItemMachine(/* Parent item and corresponding machine: */ pParentItem, machine, /* Which position new group-item should be placed in? */ getDesiredPosition(pParentItem, UIGChooserItemType_Machine, machine.GetId())); } void UIGChooserModel::saveGroupDefinitions() { /* Make sure there is no group save activity: */ if (UIGroupDefinitionSaveThread::instance()) return; /* Prepare full group map: */ QMap<QString, QStringList> groups; gatherGroupDefinitions(groups, mainRoot()); /* Save information in other thread: */ UIGroupDefinitionSaveThread::prepare(); emit sigGroupSavingStateChanged(); connect(UIGroupDefinitionSaveThread::instance(), SIGNAL(sigReload(QString)), this, SLOT(sltReloadMachine(QString))); UIGroupDefinitionSaveThread::instance()->configure(this, m_groups, groups); UIGroupDefinitionSaveThread::instance()->start(); m_groups = groups; } void UIGChooserModel::saveGroupOrders() { /* Make sure there is no group save activity: */ if (UIGroupOrderSaveThread::instance()) return; /* Prepare full group map: */ QMap<QString, QStringList> groups; gatherGroupOrders(groups, mainRoot()); /* Save information in other thread: */ UIGroupOrderSaveThread::prepare(); emit sigGroupSavingStateChanged(); UIGroupOrderSaveThread::instance()->configure(this, groups); UIGroupOrderSaveThread::instance()->start(); } void UIGChooserModel::gatherGroupDefinitions(QMap<QString, QStringList> &groups, UIGChooserItem *pParentGroup) { /* Iterate over all the machine-items: */ foreach (UIGChooserItem *pItem, pParentGroup->items(UIGChooserItemType_Machine)) if (UIGChooserItemMachine *pMachineItem = pItem->toMachineItem()) if (pMachineItem->accessible()) groups[pMachineItem->id()] << pParentGroup->fullName(); /* Iterate over all the group-items: */ foreach (UIGChooserItem *pItem, pParentGroup->items(UIGChooserItemType_Group)) gatherGroupDefinitions(groups, pItem); } void UIGChooserModel::gatherGroupOrders(QMap<QString, QStringList> &groups, UIGChooserItem *pParentItem) { /* Prepare extra-data key for current group: */ const QString strExtraDataKey = pParentItem->fullName(); /* Iterate over all the group-items: */ foreach (UIGChooserItem *pItem, pParentItem->items(UIGChooserItemType_Group)) { QString strGroupDescriptor(pItem->toGroupItem()->isOpened() ? "go" : "gc"); groups[strExtraDataKey] << QString("%1=%2").arg(strGroupDescriptor, pItem->name()); gatherGroupOrders(groups, pItem); } /* Iterate over all the machine-items: */ foreach (UIGChooserItem *pItem, pParentItem->items(UIGChooserItemType_Machine)) groups[strExtraDataKey] << QString("m=%1").arg(pItem->toMachineItem()->id()); } void UIGChooserModel::makeSureGroupDefinitionsSaveIsFinished() { /* Cleanup if necessary: */ if (UIGroupDefinitionSaveThread::instance()) UIGroupDefinitionSaveThread::cleanup(); } void UIGChooserModel::makeSureGroupOrdersSaveIsFinished() { /* Cleanup if necessary: */ if (UIGroupOrderSaveThread::instance()) UIGroupOrderSaveThread::cleanup(); } /* static */ UIGroupDefinitionSaveThread* UIGroupDefinitionSaveThread::m_spInstance = 0; /* static */ UIGroupDefinitionSaveThread* UIGroupDefinitionSaveThread::instance() { return m_spInstance; } /* static */ void UIGroupDefinitionSaveThread::prepare() { /* Make sure instance not prepared: */ if (m_spInstance) return; /* Crate instance: */ new UIGroupDefinitionSaveThread; } /* static */ void UIGroupDefinitionSaveThread::cleanup() { /* Make sure instance prepared: */ if (!m_spInstance) return; /* Crate instance: */ delete m_spInstance; } void UIGroupDefinitionSaveThread::configure(QObject *pParent, const QMap<QString, QStringList> &oldLists, const QMap<QString, QStringList> &newLists) { m_oldLists = oldLists; m_newLists = newLists; connect(this, SIGNAL(sigComplete()), pParent, SLOT(sltGroupDefinitionsSaveComplete())); } UIGroupDefinitionSaveThread::UIGroupDefinitionSaveThread() { /* Assign instance: */ m_spInstance = this; } UIGroupDefinitionSaveThread::~UIGroupDefinitionSaveThread() { /* Wait: */ wait(); /* Erase instance: */ m_spInstance = 0; } void UIGroupDefinitionSaveThread::run() { /* COM prepare: */ COMBase::InitializeCOM(false); /* For every particular machine ID: */ foreach (const QString &strId, m_newLists.keys()) { /* Get new group list/set: */ const QStringList &newGroupList = m_newLists.value(strId); const UIStringSet &newGroupSet = UIStringSet::fromList(newGroupList); /* Get old group list/set: */ const QStringList &oldGroupList = m_oldLists.value(strId); const UIStringSet &oldGroupSet = UIStringSet::fromList(oldGroupList); /* Make sure group set changed: */ if (newGroupSet == oldGroupSet) continue; /* The next steps are subsequent. * Every of them is mandatory in order to continue * with common cleanup in case of failure. * We have to simulate a try-catch block. */ CSession session; CMachine machine; do { /* 1. Open session: */ session = vboxGlobal().openSession(strId); if (session.isNull()) break; /* 2. Get session machine: */ machine = session.GetMachine(); if (machine.isNull()) break; /* 3. Set new groups: */ machine.SetGroups(newGroupList.toVector()); if (!machine.isOk()) { msgCenter().cannotSetGroups(machine); break; } /* 4. Save settings: */ machine.SaveSettings(); if (!machine.isOk()) { msgCenter().cannotSaveMachineSettings(machine); break; } } while (0); /* Cleanup if necessary: */ if (machine.isNull() || !machine.isOk()) emit sigReload(strId); if (!session.isNull()) session.UnlockMachine(); } /* Notify listeners about completeness: */ emit sigComplete(); /* COM cleanup: */ COMBase::CleanupCOM(); } /* static */ UIGroupOrderSaveThread* UIGroupOrderSaveThread::m_spInstance = 0; /* static */ UIGroupOrderSaveThread* UIGroupOrderSaveThread::instance() { return m_spInstance; } /* static */ void UIGroupOrderSaveThread::prepare() { /* Make sure instance not prepared: */ if (m_spInstance) return; /* Crate instance: */ new UIGroupOrderSaveThread; } /* static */ void UIGroupOrderSaveThread::cleanup() { /* Make sure instance prepared: */ if (!m_spInstance) return; /* Crate instance: */ delete m_spInstance; } void UIGroupOrderSaveThread::configure(QObject *pParent, const QMap<QString, QStringList> &groups) { m_groups = groups; connect(this, SIGNAL(sigComplete()), pParent, SLOT(sltGroupOrdersSaveComplete())); } UIGroupOrderSaveThread::UIGroupOrderSaveThread() { /* Assign instance: */ m_spInstance = this; } UIGroupOrderSaveThread::~UIGroupOrderSaveThread() { /* Wait: */ wait(); /* Erase instance: */ m_spInstance = 0; } void UIGroupOrderSaveThread::run() { /* COM prepare: */ COMBase::InitializeCOM(false); /* Clear all the extra-data records related to group definitions: */ gEDataManager->clearSelectorWindowGroupsDefinitions(); /* For every particular group definition: */ foreach (const QString &strId, m_groups.keys()) gEDataManager->setSelectorWindowGroupsDefinitions(strId, m_groups[strId]); /* Notify listeners about completeness: */ emit sigComplete(); /* COM cleanup: */ COMBase::CleanupCOM(); }
{ "content_hash": "b02243d81cf417c43e883469bf1fd28f", "timestamp": "", "source": "github", "line_count": 2170, "max_line_length": 125, "avg_line_length": 33.53041474654378, "alnum_prop": 0.6316433254078421, "repo_name": "egraba/vbox_openbsd", "id": "2648a1acb9954aea72e86bc0472898c6120b9ffa", "size": "72761", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/selector/graphics/chooser/UIGChooserModel.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "88714" }, { "name": "Assembly", "bytes": "4303680" }, { "name": "AutoIt", "bytes": "2187" }, { "name": "Batchfile", "bytes": "95534" }, { "name": "C", "bytes": "192632221" }, { "name": "C#", "bytes": "64255" }, { "name": "C++", "bytes": "83842667" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "6041" }, { "name": "CSS", "bytes": "26756" }, { "name": "D", "bytes": "41844" }, { "name": "DIGITAL Command Language", "bytes": "56579" }, { "name": "DTrace", "bytes": "1466646" }, { "name": "GAP", "bytes": "350327" }, { "name": "Groff", "bytes": "298540" }, { "name": "HTML", "bytes": "467691" }, { "name": "IDL", "bytes": "106734" }, { "name": "Java", "bytes": "261605" }, { "name": "JavaScript", "bytes": "80927" }, { "name": "Lex", "bytes": "25122" }, { "name": "Logos", "bytes": "4941" }, { "name": "Makefile", "bytes": "426902" }, { "name": "Module Management System", "bytes": "2707" }, { "name": "NSIS", "bytes": "177212" }, { "name": "Objective-C", "bytes": "5619792" }, { "name": "Objective-C++", "bytes": "81554" }, { "name": "PHP", "bytes": "58585" }, { "name": "Pascal", "bytes": "69941" }, { "name": "Perl", "bytes": "240063" }, { "name": "PowerShell", "bytes": "10664" }, { "name": "Python", "bytes": "9094160" }, { "name": "QMake", "bytes": "3055" }, { "name": "R", "bytes": "21094" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "1460572" }, { "name": "SourcePawn", "bytes": "4139" }, { "name": "TypeScript", "bytes": "142342" }, { "name": "Visual Basic", "bytes": "7161" }, { "name": "XSLT", "bytes": "1034475" }, { "name": "Yacc", "bytes": "22312" } ], "symlink_target": "" }
<?php /* * All sqlite dbQueries here in this file * SELECT | INSERT | DELETE | UPDATE (curd) * */ //list /* getCourses() getBranches(course) getYearCount(course) getSemCount(course) getBatchCount(course,branch) getRooms(*) getRooms(*roomGroup) getTeachers(*) getTeachers(*deptt) getSubjects(course,branch,sem) getRows(*) getRows(*config) config: (userType,teacher.key | userType,room.key | userType,course.key,branch.key,sem) userType:[t|r|s] ... set..All add..All update..All ... try to write all and generalized queries at single place and a single fxn to execute any query. default values: consider if not/wrong given course: bTech branch: CS userType: s for future: can ignore coding about these roomGroup,deptt(teacher) :all keys are case sensitive */ public function dbAction($aType,$entity,$params) { /* $aType: get/upsert $entity: course/branch/yearCount/semCount/batchCount/room/teacher/subject/rows */ $sqliteDBFile = 'databasev1.db'; ini_set("allow_url_fopen", true); //check php version and sqlite3 library installation $db = new sqlite3($sqliteDBFile); } /* $tbl_configs = 'configs'; getCourses() : select *|ID,key,abbr,fullName from $tbl_configs where `type` = 'course' getBranches(course) : select * from $tbl_configs where `type` = 'courseBranch' and `parentID` = {select ID from $tbl_configs where `type` = 'course' and `key`= $course}; $course='bTech' :: select ID,key,abbr,fullName from configs where `type` = 'courseBranch' and `parentID` = (select ID from configs where `type` = 'course' and `key`= 'bTech') getYearCount(course) : select ID,key,abbr,fullName from configs where type = 'courseYearCount' and parentID = (select ID from configs where type = 'course' and key= 'bTech') getSemCount(course) getBatchCount(course,branch) getRooms(*) getRooms(*roomGroup) getTeachers(*) getTeachers(*deptt) getSubjects(course,branch,sem) getRows(*) getRows(*config) config: (userType,teacher.key | userType,room.key | userType,course.key,branch.key,sem) userType:[t|r|s] ... */ ?>
{ "content_hash": "bf6641ba1536a94b1a8780713082b646", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 197, "avg_line_length": 27.210526315789473, "alnum_prop": 0.7137330754352031, "repo_name": "sushiljainam/tt-save", "id": "26f99ce972d0629cbe1439b162946b012cc76a89", "size": "2068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dbQuery.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "7168" } ], "symlink_target": "" }
/** * DepositoryValueResource.java created on Oct 18, 2013 by Cam Moore. */ package org.wattdepot.core.restlet; import org.restlet.resource.Get; import org.wattdepot.core.datamodel.MeasuredValue; /** * DepositoryValueResource - HTTP Interface for getting the MeasuredValues. <br> * GET /wattdepot/depository/{depository_id}/value/?sensor={sensor_id},time * ={timestamp} or <br> * GET /wattdepot/depository/{depository_id}/value/?sensor={sensor_id * },start={timestamp},end={timestamp} * * @author Cam Moore * */ public interface DepositoryValueResource { /** * Defines GET * /wattdepot/depository/{depository_id}/value/?sensor={sensor_id}, * time={timestamp} or <br>GET * /wattdepot/depository/{depository_id}/value/?sensor= * {sensor_id},start={timestamp},end={timestamp}. * * @return The MeasuredValue. */ @Get("json") // Use JSON ast transport encoding. public MeasuredValue retrieve(); }
{ "content_hash": "61fee1d27133d7e0b513801ab68aecbc", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 80, "avg_line_length": 28.515151515151516, "alnum_prop": 0.7024442082890542, "repo_name": "cammoore/wattdepot3-redesign", "id": "3df1e35fc8eb540a4145397e44eb80605ae5cb35", "size": "941", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wattdepot-core/src/main/java/org/wattdepot/core/restlet/DepositoryValueResource.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "145417" }, { "name": "Java", "bytes": "206685" }, { "name": "JavaScript", "bytes": "257033" } ], "symlink_target": "" }
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.compiler.server; import com.intellij.DynamicBundle; import com.intellij.ProjectTopics; import com.intellij.application.options.RegistryManager; import com.intellij.compiler.CompilerConfiguration; import com.intellij.compiler.CompilerConfigurationImpl; import com.intellij.compiler.CompilerWorkspaceConfiguration; import com.intellij.compiler.YourKitProfilerService; import com.intellij.compiler.cache.CompilerCacheConfigurator; import com.intellij.compiler.cache.CompilerCacheStartupActivity; import com.intellij.compiler.impl.CompilerUtil; import com.intellij.compiler.impl.javaCompiler.BackendCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompilerConfiguration; import com.intellij.compiler.impl.javaCompiler.javac.JavacConfiguration; import com.intellij.compiler.server.impl.BuildProcessClasspathManager; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionListener; import com.intellij.execution.ExecutionManager; import com.intellij.execution.process.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.wsl.WSLDistribution; import com.intellij.execution.wsl.WslDistributionManager; import com.intellij.execution.wsl.WslPath; import com.intellij.ide.IdeEventQueue; import com.intellij.ide.PowerSaveMode; import com.intellij.ide.actions.RevealFileAction; import com.intellij.ide.file.BatchFileChangeListener; import com.intellij.ide.impl.TrustedProjects; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.compiler.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.advanced.AdvancedSettings; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.project.*; import com.intellij.openapi.projectRoots.*; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl; import com.intellij.openapi.roots.*; import com.intellij.openapi.startup.StartupActivity; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.util.text.Strings; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.BulkFileListener; import com.intellij.openapi.vfs.newvfs.events.VFileEvent; import com.intellij.openapi.wm.IdeFrame; import com.intellij.serviceContainer.AlreadyDisposedException; import com.intellij.ui.ComponentUtil; import com.intellij.util.Alarm; import com.intellij.util.ArrayUtilRt; import com.intellij.util.SmartList; import com.intellij.util.SystemProperties; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.concurrency.SequentialTaskExecutor; import com.intellij.util.containers.CollectionFactory; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SLRUCache; import com.intellij.util.io.BaseOutputReader; import com.intellij.util.io.storage.HeavyProcessLatch; import com.intellij.util.lang.JavaVersion; import com.intellij.util.messages.MessageBusConnection; import com.intellij.util.net.NetUtils; import com.intellij.util.text.DateFormatUtil; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.codec.protobuf.ProtobufDecoder; import io.netty.handler.codec.protobuf.ProtobufEncoder; import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.util.internal.ThreadLocalRandom; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.BuiltInServerManager; import org.jetbrains.ide.BuiltInServerManagerImpl; import org.jetbrains.io.ChannelRegistrar; import org.jetbrains.jps.api.*; import org.jetbrains.jps.cmdline.BuildMain; import org.jetbrains.jps.cmdline.ClasspathBootstrap; import org.jetbrains.jps.incremental.Utils; import org.jetbrains.jps.incremental.storage.ProjectStamps; import org.jetbrains.jps.model.java.compiler.JavaCompilers; import org.jvnet.winp.Priority; import org.jvnet.winp.WinProcess; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; import java.awt.*; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.List; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import static org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope; public final class BuildManager implements Disposable { public static final Key<Boolean> ALLOW_AUTOMAKE = Key.create("_allow_automake_when_process_is_active_"); private static final Key<Integer> COMPILER_PROCESS_DEBUG_PORT = Key.create("_compiler_process_debug_port_"); private static final Key<String> FORCE_MODEL_LOADING_PARAMETER = Key.create(BuildParametersKeys.FORCE_MODEL_LOADING); private static final Key<CharSequence> STDERR_OUTPUT = Key.create("_process_launch_errors_"); private static final SimpleDateFormat USAGE_STAMP_DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy"); private static final Logger LOG = Logger.getInstance(BuildManager.class); private static final String COMPILER_PROCESS_JDK_PROPERTY = "compiler.process.jdk"; public static final String SYSTEM_ROOT = "compile-server"; public static final String TEMP_DIR_NAME = "_temp_"; private static final String[] INHERITED_IDE_VM_OPTIONS = { "user.language", "user.country", "user.region", PathManager.PROPERTY_PATHS_SELECTOR, "idea.case.sensitive.fs", "java.net.preferIPv4Stack" }; // do not make static in order not to access application on class load private final boolean IS_UNIT_TEST_MODE; private static final String IWS_EXTENSION = ".iws"; private static final String IPR_EXTENSION = ".ipr"; private static final String IDEA_PROJECT_DIR_PATTERN = "/.idea/"; private static final Function<String, Boolean> PATH_FILTER = SystemInfoRt.isFileSystemCaseSensitive ? s -> !(s.contains(IDEA_PROJECT_DIR_PATTERN) || s.endsWith(IWS_EXTENSION) || s.endsWith(IPR_EXTENSION)) : s -> !(Strings.endsWithIgnoreCase(s, IWS_EXTENSION) || Strings.endsWithIgnoreCase(s, IPR_EXTENSION) || StringUtil.containsIgnoreCase(s, IDEA_PROJECT_DIR_PATTERN)); private final String myFallbackSdkHome; private final String myFallbackSdkVersion; private final Map<TaskFuture<?>, Project> myAutomakeFutures = Collections.synchronizedMap(new HashMap<>()); private final Map<String, RequestFuture<?>> myBuildsInProgress = Collections.synchronizedMap(new HashMap<>()); private final Map<String, Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>>> myPreloadedBuilds = Collections.synchronizedMap(new HashMap<>()); private final BuildProcessClasspathManager myClasspathManager = new BuildProcessClasspathManager(this); private final Executor myRequestsProcessor = AppExecutorUtil.createBoundedApplicationPoolExecutor("BuildManager RequestProcessor Pool", 1); private final List<VFileEvent> myUnprocessedEvents = new ArrayList<>(); private final Executor myAutomakeTrigger = AppExecutorUtil.createBoundedApplicationPoolExecutor("BuildManager Auto-Make Trigger", 1); private final Map<String, ProjectData> myProjectDataMap = Collections.synchronizedMap(new HashMap<>()); private final AtomicInteger mySuspendBackgroundTasksCounter = new AtomicInteger(0); private final BuildManagerPeriodicTask myAutoMakeTask = new BuildManagerPeriodicTask() { @Override protected int getDelay() { return Registry.intValue("compiler.automake.trigger.delay"); } @Override protected void runTask() { runAutoMake(); } @Override protected boolean shouldPostpone() { // Heuristics for automake postpone decision: // 1. There are unsaved documents OR // 2. The IDE is not idle: the last activity happened less than 3 seconds ago (registry-configurable) if (FileDocumentManager.getInstance().getUnsavedDocuments().length > 0) { return true; } final long threshold = Registry.intValue("compiler.automake.postpone.when.idle.less.than", 3000); // todo: UI option instead of registry? final long idleSinceLastActivity = ApplicationManager.getApplication().getIdleTime(); return idleSinceLastActivity < threshold; } }; private final BuildManagerPeriodicTask myDocumentSaveTask = new BuildManagerPeriodicTask() { @Override protected int getDelay() { return Registry.intValue("compiler.document.save.trigger.delay"); } @Override public void runTask() { if (shouldSaveDocuments()) { ApplicationManager.getApplication().invokeAndWait( () -> ((FileDocumentManagerImpl)FileDocumentManager.getInstance()).saveAllDocuments(false) ); } } private boolean shouldSaveDocuments() { final Project contextProject = getCurrentContextProject(); return contextProject != null && canStartAutoMake(contextProject); } }; private final Runnable myGCTask = () -> { // todo: make customizable in UI? final int unusedThresholdDays = Registry.intValue("compiler.build.data.unused.threshold", -1); if (unusedThresholdDays <= 0) { return; } Collection<File> systemDirs = Collections.singleton(getBuildSystemDirectory().toFile()); if (Boolean.parseBoolean(System.getProperty("compiler.build.data.clean.unused.wsl"))) { final List<WSLDistribution> distributions = WslDistributionManager.getInstance().getInstalledDistributions(); if (!distributions.isEmpty()) { systemDirs = new ArrayList<>(systemDirs); for (WSLDistribution distribution : distributions) { final Path wslSystemDir = WslBuildCommandLineBuilder.getWslBuildSystemDirectory(distribution); if (wslSystemDir != null) { systemDirs.add(wslSystemDir.toFile()); } } } } for (File buildSystemDir : systemDirs) { File[] dirs = buildSystemDir.listFiles(pathname -> pathname.isDirectory() && !TEMP_DIR_NAME.equals(pathname.getName())); if (dirs != null) { final Date now = new Date(); for (File buildDataProjectDir : dirs) { File usageFile = getUsageFile(buildDataProjectDir); if (usageFile.exists()) { final Pair<Date, File> usageData = readUsageFile(usageFile); if (usageData != null) { final File projectFile = usageData.second; if (projectFile != null && !projectFile.exists() || DateFormatUtil.getDifferenceInDays(usageData.first, now) > unusedThresholdDays) { LOG.info("Clearing project build data because the project does not exist or was not opened for more than " + unusedThresholdDays + " days: " + buildDataProjectDir); FileUtil.delete(buildDataProjectDir); } } } else { updateUsageFile(null, buildDataProjectDir); // set usage stamp to start countdown } } } } }; private final BuildMessageDispatcher myMessageDispatcher = new BuildMessageDispatcher(); private static class ListeningConnection { private final InetAddress myAddress; private final ChannelRegistrar myChannelRegistrar = new ChannelRegistrar(); private volatile int myListenPort = -1; private ListeningConnection(InetAddress address) { myAddress = address; } } private final List<ListeningConnection> myListeningConnections = new ArrayList<>(); @NotNull private final Charset mySystemCharset = CharsetToolkit.getDefaultSystemCharset(); private volatile boolean myBuildProcessDebuggingEnabled; public BuildManager() { final Application application = ApplicationManager.getApplication(); IS_UNIT_TEST_MODE = application.isUnitTestMode(); String fallbackSdkHome = System.getProperty(GlobalOptions.FALLBACK_JDK_HOME, null); String fallbackSdkVersion = System.getProperty(GlobalOptions.FALLBACK_JDK_VERSION, null); if (fallbackSdkHome == null || fallbackSdkVersion == null) { // default to the IDE's runtime myFallbackSdkHome = getFallbackSdkHome(); myFallbackSdkVersion = SystemInfo.JAVA_VERSION; } else { myFallbackSdkHome = fallbackSdkHome; myFallbackSdkVersion = fallbackSdkVersion; } MessageBusConnection connection = application.getMessageBus().connect(this); connection.subscribe(ProjectManager.TOPIC, new ProjectWatcher()); connection.subscribe(VirtualFileManager.VFS_CHANGES, new BulkFileListener() { @Override public void after(@NotNull List<? extends @NotNull VFileEvent> events) { if (!IS_UNIT_TEST_MODE) { synchronized (myUnprocessedEvents) { myUnprocessedEvents.addAll(events); } myAutomakeTrigger.execute(() -> { if (!application.isDisposed()) { ReadAction.run(()-> { if (application.isDisposed()) { return; } final List<VFileEvent> snapshot; synchronized (myUnprocessedEvents) { if (myUnprocessedEvents.isEmpty()) { return; } snapshot = new ArrayList<>(myUnprocessedEvents); myUnprocessedEvents.clear(); } if (shouldTriggerMake(snapshot)) { scheduleAutoMake(); } }); } else { synchronized (myUnprocessedEvents) { myUnprocessedEvents.clear(); } } }); } } private boolean shouldTriggerMake(List<? extends VFileEvent> events) { if (PowerSaveMode.isEnabled()) { return false; } Project project = null; ProjectFileIndex fileIndex = null; for (VFileEvent event : events) { final VirtualFile eventFile = event.getFile(); if (eventFile == null) { continue; } if (!eventFile.isValid()) { return true; // should be deleted } if (project == null) { // lazy init project = getCurrentContextProject(); if (project == null) { return false; } fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); } if (fileIndex.isInContent(eventFile)) { if (ProjectUtil.isProjectOrWorkspaceFile(eventFile) || GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(eventFile, project)) { // changes in project files or generated stuff should not trigger auto-make continue; } return true; } } return false; } }); connection.subscribe(BatchFileChangeListener.TOPIC, new BatchFileChangeListener() { @Override public void batchChangeStarted(@NotNull Project project, @Nullable String activityName) { postponeBackgroundTasks(); cancelAutoMakeTasks(project); } @Override public void batchChangeCompleted(@NotNull Project project) { allowBackgroundTasks(false); } }); if (!application.isHeadlessEnvironment()) { configureIdleAutomake(); } ShutDownTracker.getInstance().registerShutdownTask(this::stopListening); if (!IS_UNIT_TEST_MODE) { ScheduledFuture<?> future = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(() -> runCommand(myGCTask), 3, 180, TimeUnit.MINUTES); Disposer.register(this, () -> future.cancel(false)); } } private void configureIdleAutomake() { final int idleTimeout = getAutomakeWhileIdleTimeout(); final int listenerTimeout = idleTimeout > 0 ? idleTimeout : 60000; IdeEventQueue.getInstance().addIdleListener(new Runnable() { @Override public void run() { final int currentTimeout = getAutomakeWhileIdleTimeout(); if (idleTimeout != currentTimeout) { // re-schedule with changed period IdeEventQueue.getInstance().removeIdleListener(this); configureIdleAutomake(); } if (currentTimeout > 0 /*is enabled*/ && !myAutoMakeTask.myInProgress.get()) { boolean hasChanges = false; synchronized (myProjectDataMap) { for (ProjectData data : myProjectDataMap.values()) { if (data.hasChanges()) { hasChanges = true; break; } } } if (hasChanges) { // only schedule automake if the feature is enabled, no automake is running at the moment and there is at least one watched project with pending changes scheduleAutoMake(); } } } }, listenerTimeout); } public void postponeBackgroundTasks() { mySuspendBackgroundTasksCounter.incrementAndGet(); } public void allowBackgroundTasks(boolean resetState) { if (resetState) { mySuspendBackgroundTasksCounter.set(0); } else { if (mySuspendBackgroundTasksCounter.decrementAndGet() < 0) { mySuspendBackgroundTasksCounter.incrementAndGet(); } } } private static @NotNull String getFallbackSdkHome() { String home = SystemProperties.getJavaHome(); // should point either to jre or jdk if (!JdkUtil.checkForJdk(home)) { String parent = new File(home).getParent(); if (parent != null && JdkUtil.checkForJdk(parent)) { home = parent; } } return FileUtilRt.toSystemIndependentName(home); } @NotNull private static List<Project> getOpenProjects() { final Project[] projects = ProjectManager.getInstance().getOpenProjects(); if (projects.length == 0) { return Collections.emptyList(); } final List<Project> projectList = new SmartList<>(); for (Project project : projects) { if (isValidProject(project)) { projectList.add(project); } } return projectList; } private static boolean isValidProject(@Nullable Project project) { return project != null && !project.isDisposed() && !project.isDefault() && project.isInitialized(); } public static BuildManager getInstance() { return ApplicationManager.getApplication().getService(BuildManager.class); } public void notifyFilesChanged(final Collection<? extends File> paths) { doNotify(paths, false); } public void notifyFilesDeleted(Collection<? extends File> paths) { doNotify(paths, true); } public void runCommand(@NotNull Runnable command) { myRequestsProcessor.execute(command); } private void doNotify(final Collection<? extends File> paths, final boolean notifyDeletion) { // ensure events processed in the order they arrived runCommand(() -> { final List<String> filtered = new ArrayList<>(paths.size()); for (File file : paths) { final String path = FileUtil.toSystemIndependentName(file.getPath()); if (PATH_FILTER.apply(path)) { filtered.add(path); } } if (filtered.isEmpty()) { return; } synchronized (myProjectDataMap) { //if (IS_UNIT_TEST_MODE) { // if (notifyDeletion) { // LOG.info("Registering deleted paths: " + filtered); // } // else { // LOG.info("Registering changed paths: " + filtered); // } //} for (Map.Entry<String, ProjectData> entry : myProjectDataMap.entrySet()) { final ProjectData data = entry.getValue(); if (notifyDeletion) { data.addDeleted(filtered); } else { data.addChanged(filtered); } RequestFuture<?> future = myBuildsInProgress.get(entry.getKey()); if (future != null && !future.isCancelled() && !future.isDone()) { final UUID sessionId = future.getRequestID(); final Channel channel = myMessageDispatcher.getConnectedChannel(sessionId); if (channel != null) { CmdlineRemoteProto.Message.ControllerMessage.FSEvent event = data.createNextEvent(wslPathMapper(entry.getKey())); final CmdlineRemoteProto.Message.ControllerMessage message = CmdlineRemoteProto.Message.ControllerMessage.newBuilder().setType( CmdlineRemoteProto.Message.ControllerMessage.Type.FS_EVENT ).setFsEvent(event).build(); if (LOG.isDebugEnabled()) { LOG.debug("Sending to running build, ordinal=" + event.getOrdinal()); } channel.writeAndFlush(CmdlineProtoUtil.toMessage(sessionId, message)); } } } } }); } @Nullable private static Project findProjectByProjectPath(@NotNull String projectPath) { return ContainerUtil.find(ProjectManager.getInstance().getOpenProjects(), (project) -> projectPath.equals(getProjectPath(project))); } @NotNull private static Function<String, String> wslPathMapper(@Nullable WSLDistribution distr) { return distr == null? Function.identity() : // interned paths collapse repeated slashes so \\wsl$ ends up /wsl$ path -> path.startsWith("/wsl$")? distr.getWslPath("/" + path) : path; } private static Function<String, String> wslPathMapper(@NotNull String projectPath) { return new Function<>() { private Function<String, String> myImpl; @Override public String apply(String path) { if (myImpl != null) { return myImpl.apply(path); } if (path.startsWith("/wsl$")) { Project project = findProjectByProjectPath(projectPath); myImpl = wslPathMapper(project != null ? findWSLDistributionForBuild(project) : null); return myImpl.apply(path); } return path; } }; } public static void forceModelLoading(CompileContext context) { context.getCompileScope().putUserData(FORCE_MODEL_LOADING_PARAMETER, Boolean.TRUE.toString()); } public void clearState(@NotNull Project project) { String projectPath = getProjectPath(project); cancelPreloadedBuilds(projectPath); boolean clearNameCache = false; synchronized (myProjectDataMap) { ProjectData data = myProjectDataMap.get(projectPath); if (data != null) { data.dropChanges(); clearNameCache = myProjectDataMap.size() == 1; } } if (clearNameCache) { InternedPath.clearCache(); } scheduleAutoMake(); } public void clearState() { final boolean cleared; synchronized (myProjectDataMap) { cleared = !myProjectDataMap.isEmpty(); for (Map.Entry<String, ProjectData> entry : myProjectDataMap.entrySet()) { cancelPreloadedBuilds(entry.getKey()); entry.getValue().dropChanges(); } } if (cleared) { InternedPath.clearCache(); scheduleAutoMake(); } } public boolean isProjectWatched(@NotNull Project project) { return myProjectDataMap.containsKey(getProjectPath(project)); } public @Nullable List<String> getFilesChangedSinceLastCompilation(@NotNull Project project) { String projectPath = getProjectPath(project); synchronized (myProjectDataMap) { ProjectData data = myProjectDataMap.get(projectPath); if (data != null && !data.myNeedRescan) { return convertToStringPaths(data.myChanged); } return null; } } private static @NotNull List<String> convertToStringPaths(@NotNull Collection<? extends InternedPath> interned) { List<String> list = new ArrayList<>(interned.size()); for (InternedPath path : interned) { list.add(path.getValue()); } return list; } private static @NotNull String getProjectPath(@NotNull Project project) { assert !project.isDefault() : BuildManager.class.getName() + " methods should not be called for default project"; return VirtualFileManager.extractPath(Objects.requireNonNull(project.getPresentableUrl())); } public void scheduleAutoMake() { if (!IS_UNIT_TEST_MODE && !PowerSaveMode.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("Automake scheduled:\n" + getThreadTrace(Thread.currentThread(), 10)); } myAutoMakeTask.schedule(); } } @NotNull private static String getThreadTrace(Thread thread, final int depth) { // debugging final StringBuilder buf = new StringBuilder(); final StackTraceElement[] trace = thread.getStackTrace(); for (int i = 0; i < depth && i < trace.length; i++) { final StackTraceElement element = trace[i]; buf.append("\tat ").append(element).append("\n"); } return buf.toString(); } private void scheduleProjectSave() { if (!IS_UNIT_TEST_MODE && !PowerSaveMode.isEnabled()) { if (LOG.isDebugEnabled()) { LOG.debug("Automake canceled; reason: project save scheduled"); } myAutoMakeTask.cancelPendingExecution(); myDocumentSaveTask.schedule(); } } private void runAutoMake() { Collection<Project> projects = Collections.emptyList(); final int appIdleTimeout = getAutomakeWhileIdleTimeout(); if (appIdleTimeout > 0 && ApplicationManager.getApplication().getIdleTime() > appIdleTimeout) { // been idle quite a time, so try to process all open projects while idle projects = getOpenProjects(); } else { final Project project = getCurrentContextProject(); if (project != null) { projects = Collections.singleton(project); } } if (projects.isEmpty()) { return; } final List<Pair<TaskFuture<?>, AutoMakeMessageHandler>> futures = new SmartList<>(); for (Project project : projects) { if (!canStartAutoMake(project)) { continue; } final List<TargetTypeBuildScope> scopes = CmdlineProtoUtil.createAllModulesScopes(false); final AutoMakeMessageHandler handler = new AutoMakeMessageHandler(project); final TaskFuture<?> future = scheduleBuild( project, false, true, false, scopes, Collections.emptyList(), Collections.singletonMap(BuildParametersKeys.IS_AUTOMAKE, "true"), handler ); if (future != null) { myAutomakeFutures.put(future, project); futures.add(Pair.create(future, handler)); } } boolean needAdditionalBuild = false; for (Pair<TaskFuture<?>, AutoMakeMessageHandler> pair : futures) { try { pair.first.waitFor(); } catch (Throwable ignored) { } finally { myAutomakeFutures.remove(pair.first); if (pair.second.unprocessedFSChangesDetected()) { needAdditionalBuild = true; } } } if (needAdditionalBuild) { scheduleAutoMake(); } } private static int getAutomakeWhileIdleTimeout() { return RegistryManager.getInstance().intValue("compiler.automake.build.while.idle.timeout", 60000); } private static boolean canStartAutoMake(@NotNull Project project) { if (project.isDisposed()) { return false; } final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project); if (!config.MAKE_PROJECT_ON_SAVE || !TrustedProjects.isTrusted(project)) { return false; } return config.allowAutoMakeWhileRunningApplication() || !hasRunningProcess(project); } @Nullable private static Project getCurrentContextProject() { final List<Project> openProjects = getOpenProjects(); if (openProjects.isEmpty()) { return null; } if (openProjects.size() == 1) { return openProjects.get(0); } Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow(); if (window == null) { window = ComponentUtil.getActiveWindow(); } final Component comp = ComponentUtil.findUltimateParent(window); Project project = null; if (comp instanceof IdeFrame) { project = ((IdeFrame)comp).getProject(); } return isValidProject(project)? project : null; } private static boolean hasRunningProcess(@NotNull Project project) { for (ProcessHandler handler : ExecutionManager.getInstance(project).getRunningProcesses()) { if (!handler.isProcessTerminated() && !ALLOW_AUTOMAKE.get(handler, Boolean.FALSE)) { // active process return true; } } return false; } @NotNull public Collection<TaskFuture<?>> cancelAutoMakeTasks(@NotNull Project project) { final Collection<TaskFuture<?>> futures = new SmartList<>(); synchronized (myAutomakeFutures) { for (Map.Entry<TaskFuture<?>, Project> entry : myAutomakeFutures.entrySet()) { if (entry.getValue().equals(project)) { TaskFuture<?> future = entry.getKey(); future.cancel(false); futures.add(future); } } } if (LOG.isDebugEnabled() && !futures.isEmpty()) { LOG.debug("Automake cancel (all tasks):\n" + getThreadTrace(Thread.currentThread(), 10)); } return futures; } private void cancelAllPreloadedBuilds() { String[] paths = ArrayUtilRt.toStringArray(myPreloadedBuilds.keySet()); for (String path : paths) { cancelPreloadedBuilds(path); } } private void cancelPreloadedBuilds(@NotNull String projectPath) { if (LOG.isDebugEnabled()) { LOG.debug("Cancel preloaded build for " + projectPath + "\n" + getThreadTrace(Thread.currentThread(), 50)); } runCommand(() -> { Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> pair = takePreloadedProcess(projectPath); if (pair == null) { return; } final RequestFuture<PreloadedProcessMessageHandler> future = pair.first; final OSProcessHandler processHandler = pair.second; myMessageDispatcher.cancelSession(future.getRequestID()); // waiting for preloaded process from project's task queue guarantees no build is started for this project // until this one gracefully exits and closes all its storages getProjectData(projectPath).taskQueue.execute(() -> { Throwable error = null; try { while (!processHandler.waitFor()) { LOG.info("processHandler.waitFor() returned false for session " + future.getRequestID() + ", continue waiting"); } } catch (Throwable e) { error = e; } finally { notifySessionTerminationIfNeeded(future.getRequestID(), error); } }); }); } @Nullable private Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> takePreloadedProcess(String projectPath) { Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> result; final Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> preloadProgress = myPreloadedBuilds.remove(projectPath); try { result = preloadProgress != null ? preloadProgress.get() : null; } catch (Throwable e) { LOG.info(e); result = null; } return result != null && !result.first.isDone()? result : null; } @Nullable public TaskFuture<?> scheduleBuild( final Project project, final boolean isRebuild, final boolean isMake, final boolean onlyCheckUpToDate, final List<TargetTypeBuildScope> scopes, final Collection<String> paths, final Map<String, String> userData, final DefaultMessageHandler messageHandler) { final String projectPath = getProjectPath(project); final boolean isAutomake = messageHandler instanceof AutoMakeMessageHandler; final WSLDistribution wslDistribution = findWSLDistributionForBuild(project); final BuilderMessageHandler handler = new NotifyingMessageHandler(project, messageHandler, wslDistribution != null ? wslDistribution::getWindowsPath : null, isAutomake); try { ensureListening(wslDistribution != null ? wslDistribution.getHostIpAddress() : InetAddress.getLoopbackAddress()); } catch (Exception e) { final UUID sessionId = UUID.randomUUID(); // the actual session did not start, use random UUID handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(e.getMessage(), null)); handler.sessionTerminated(sessionId); return null; } Function<String, String> pathMapper = wslDistribution != null ? wslDistribution::getWslPath : Function.identity(); final DelegateFuture _future = new DelegateFuture(); // by using the same queue that processes events we ensure that // the build will be aware of all events that have happened before this request runCommand(() -> { final Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler> preloaded = takePreloadedProcess(projectPath); final RequestFuture<PreloadedProcessMessageHandler> preloadedFuture = Pair.getFirst(preloaded); final boolean usingPreloadedProcess = preloadedFuture != null; final UUID sessionId; if (usingPreloadedProcess) { LOG.info("Using preloaded build process to compile " + projectPath); sessionId = preloadedFuture.getRequestID(); preloadedFuture.getMessageHandler().setDelegateHandler(handler); } else { sessionId = UUID.randomUUID(); } final RequestFuture<? extends BuilderMessageHandler> future = usingPreloadedProcess? preloadedFuture : new RequestFuture<>(handler, sessionId, new CancelBuildSessionAction<>()); // futures we need to wait for: either just "future" or both "future" and "buildFuture" below List<TaskFuture<?>> delegatesToWait = Collections.singletonList(future); if (!usingPreloadedProcess && (future.isCancelled() || project.isDisposed())) { // in case of preloaded process the process was already running, so the handler will be notified upon process termination handler.sessionTerminated(sessionId); future.setDone(); } else { final CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings globals = CmdlineRemoteProto.Message.ControllerMessage.GlobalSettings.newBuilder().setGlobalOptionsPath(pathMapper.apply(PathManager.getOptionsPath())) .build(); CmdlineRemoteProto.Message.ControllerMessage.FSEvent currentFSChanges; final ExecutorService projectTaskQueue; final boolean needRescan; synchronized (myProjectDataMap) { ProjectData data = getProjectData(projectPath); if (isRebuild) { data.dropChanges(); } if (IS_UNIT_TEST_MODE) { LOG.info("Scheduling build for " + projectPath + "; CHANGED: " + new HashSet<>(convertToStringPaths(data.myChanged)) + "; DELETED: " + new HashSet<>(convertToStringPaths(data.myDeleted))); } needRescan = data.getAndResetRescanFlag(); currentFSChanges = needRescan ? null : data.createNextEvent(wslPathMapper(wslDistribution)); if (LOG.isDebugEnabled()) { LOG.debug("Sending to starting build, ordinal=" + (currentFSChanges == null ? null : currentFSChanges.getOrdinal())); } if (!needRescan && myProjectDataMap.size() == 1) { InternedPath.clearCache(); } projectTaskQueue = data.taskQueue; } String mappedProjectPath = pathMapper.apply(projectPath); List<String> mappedPaths = ContainerUtil.map(paths, (p) -> pathMapper.apply(p)); final CmdlineRemoteProto.Message.ControllerMessage params; if (isRebuild) { params = CmdlineProtoUtil.createBuildRequest(mappedProjectPath, scopes, Collections.emptyList(), userData, globals, null, null); } else if (onlyCheckUpToDate) { params = CmdlineProtoUtil.createUpToDateCheckRequest(mappedProjectPath, scopes, mappedPaths, userData, globals, currentFSChanges); } else { params = CmdlineProtoUtil.createBuildRequest(mappedProjectPath, scopes, isMake ? Collections.emptyList() : mappedPaths, userData, globals, currentFSChanges, isMake ? CompilerCacheConfigurator.getCacheDownloadSettings(project) : null); } if (!usingPreloadedProcess) { myMessageDispatcher.registerBuildMessageHandler(future, params); } try { Future<?> buildFuture = projectTaskQueue.submit(() -> { Throwable execFailure = null; try { if (project.isDisposed()) { if (usingPreloadedProcess) { future.cancel(false); } else { return; } } myBuildsInProgress.put(projectPath, future); final OSProcessHandler processHandler; CharSequence errorsOnLaunch; if (usingPreloadedProcess) { final boolean paramsSent = myMessageDispatcher.sendBuildParameters(future.getRequestID(), params); if (!paramsSent) { myMessageDispatcher.cancelSession(future.getRequestID()); } processHandler = preloaded.second; errorsOnLaunch = STDERR_OUTPUT.get(processHandler); } else { if (isAutomake && needRescan) { // if project state was cleared because of roots changed or this is the first compilation after project opening, // ensure project model is saved on disk, so that automake sees the latest model state. // For ordinary make all project, app settings and unsaved docs are always saved before build starts. try { ApplicationManager.getApplication().invokeAndWait(project::save); } catch (Throwable e) { LOG.info(e); } } processHandler = launchBuildProcess(project, sessionId, false, messageHandler.getProgressIndicator()); errorsOnLaunch = new StringBuffer(); processHandler.addProcessListener(new StdOutputCollector((StringBuffer)errorsOnLaunch)); processHandler.startNotify(); } Integer debugPort = processHandler.getUserData(COMPILER_PROCESS_DEBUG_PORT); if (debugPort != null) { messageHandler.handleCompileMessage( sessionId, CmdlineProtoUtil.createCompileProgressMessageResponse("Build: waiting for debugger connection on port " + debugPort //NON-NLS ).getCompileMessage()); // additional support for debugger auto-attach feature //noinspection UseOfSystemOutOrSystemErr System.out.println("Build: Listening for transport dt_socket at address: " + debugPort.intValue()); //NON-NLS } while (!processHandler.waitFor()) { LOG.info("processHandler.waitFor() returned false for session " + sessionId + ", continue waiting"); } final int exitValue = processHandler.getProcess().exitValue(); if (exitValue != 0) { @Nls final StringBuilder msg = new StringBuilder(); msg.append(JavaCompilerBundle.message("abnormal.build.process.termination")).append(": "); if (errorsOnLaunch != null && errorsOnLaunch.length() > 0) { msg.append("\n").append(errorsOnLaunch); if (StringUtil.contains(errorsOnLaunch, "java.lang.NoSuchMethodError")) { msg.append( "\nThe error may be caused by JARs in Java Extensions directory which conflicts with libraries used by the external build process.") .append( "\nTry adding -Djava.ext.dirs=\"\" argument to 'Build process VM options' in File | Settings | Build, Execution, Deployment | Compiler to fix the problem."); } else if (StringUtil.contains(errorsOnLaunch, "io.netty.channel.ConnectTimeoutException") && wslDistribution != null) { msg.append(JavaCompilerBundle.message("wsl.network.connection.failure")); } } else { msg.append(JavaCompilerBundle.message("unknown.build.process.error")); } handler.handleFailure(sessionId, CmdlineProtoUtil.createFailure(msg.toString(), null)); } } catch (Throwable e) { execFailure = e; } finally { myBuildsInProgress.remove(projectPath); notifySessionTerminationIfNeeded(sessionId, execFailure); if (isProcessPreloadingEnabled(project) && !onlyCheckUpToDate) { runCommand(() -> { if (!myPreloadedBuilds.containsKey(projectPath)) { try { myPreloadedBuilds.put(projectPath, launchPreloadedBuildProcess(project, projectTaskQueue)); } catch (Throwable e) { LOG.info("Error pre-loading build process for project " + projectPath, e); } } }); } } }); delegatesToWait = Arrays.asList(future, new TaskFutureAdapter<>(buildFuture)); } catch (Throwable e) { handleProcessExecutionFailure(sessionId, e); } } boolean set = _future.setDelegates(delegatesToWait); assert set; }); return _future; } private boolean isProcessPreloadingEnabled(Project project) { // automatically disable process preloading when debugging or testing if (IS_UNIT_TEST_MODE || !Registry.is("compiler.process.preload") || myBuildProcessDebuggingEnabled) { return false; } if (project.isDisposed()) { return true; } for (BuildProcessParametersProvider provider : BuildProcessParametersProvider.EP_NAME.getExtensions(project)) { if (!provider.isProcessPreloadingEnabled()) { return false; } } return true; } private void notifySessionTerminationIfNeeded(@NotNull UUID sessionId, @Nullable Throwable execFailure) { if (myMessageDispatcher.getAssociatedChannel(sessionId) == null) { // either the connection has never been established (process not started or execution failed), or no messages were sent from the launched process. // in this case the session cannot be unregistered by the message dispatcher final BuilderMessageHandler unregistered = myMessageDispatcher.unregisterBuildMessageHandler(sessionId); if (unregistered != null) { if (execFailure != null) { unregistered.handleFailure(sessionId, CmdlineProtoUtil.createFailure(execFailure.getMessage(), execFailure)); } unregistered.sessionTerminated(sessionId); } } } private void handleProcessExecutionFailure(@NotNull UUID sessionId, Throwable e) { final BuilderMessageHandler unregistered = myMessageDispatcher.unregisterBuildMessageHandler(sessionId); if (unregistered != null) { unregistered.handleFailure(sessionId, CmdlineProtoUtil.createFailure(e.getMessage(), e)); unregistered.sessionTerminated(sessionId); } } private @NotNull ProjectData getProjectData(@NotNull String projectPath) { synchronized (myProjectDataMap) { return myProjectDataMap.computeIfAbsent(projectPath, __ -> { return new ProjectData(SequentialTaskExecutor.createSequentialApplicationPoolExecutor("BuildManager Pool")); }); } } private synchronized int ensureListening(InetAddress inetAddress) { for (ListeningConnection connection : myListeningConnections) { if (connection.myAddress.equals(inetAddress)) { return connection.myListenPort; } } return startListening(inetAddress); } @Override public void dispose() { stopListening(); } @NotNull public static Pair<Sdk, JavaSdkVersion> getBuildProcessRuntimeSdk(@NotNull Project project) { return getRuntimeSdk(project, 8); } @NotNull public static Pair<Sdk, JavaSdkVersion> getJavacRuntimeSdk(@NotNull Project project) { return getRuntimeSdk(project, 6); } private static @NotNull Pair<Sdk, JavaSdkVersion> getRuntimeSdk(@NotNull Project project, int oldestPossibleVersion) { final Map<Sdk, Integer> candidates = new HashMap<>(); Consumer<Sdk> addSdk = sdk -> { if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) { final Integer count = candidates.putIfAbsent(sdk, 1); if (count != null) { candidates.put(sdk, count + 1); } } }; addSdk.accept(ProjectRootManager.getInstance(project).getProjectSdk()); for (Module module : ModuleManager.getInstance(project).getModules()) { addSdk.accept(ModuleRootManager.getInstance(module).getSdk()); } final JavaSdk javaSdkType = JavaSdk.getInstance(); final CompilerConfigurationImpl configuration = (CompilerConfigurationImpl)CompilerConfiguration.getInstance(project); if (configuration.getJavacCompiler().equals(configuration.getDefaultCompiler()) && JavacConfiguration.getOptions(project, JavacConfiguration.class).PREFER_TARGET_JDK_COMPILER) { // for javac, if compiler from associated SDK instead of cross-compilation is preferred, use a different policy: // select the most frequently used jdk from the sdks that are associated with the project, but not older than <oldestPossibleVersion> // this policy attempts to compile as much modules as possible without spawning a separate javac process final List<Pair<Sdk, JavaSdkVersion>> sortedSdks = candidates.entrySet().stream() .sorted(Map.Entry.<Sdk, Integer>comparingByValue().reversed()) .map(entry -> Pair.create(entry.getKey(), JavaVersion.tryParse(entry.getKey().getVersionString()))) .filter(p -> p.second != null && p.second.isAtLeast(oldestPossibleVersion)) .map(p -> Pair.create(p.first, JavaSdkVersion.fromJavaVersion(p.second))) .filter(p -> p.second != null) .collect(Collectors.toList()); if (!sortedSdks.isEmpty()) { // first try to find most used JDK of version 9 and newer => JRT FS support will be needed final Pair<Sdk, JavaSdkVersion> sdk9_plus = ContainerUtil.find(sortedSdks, p -> p.second.isAtLeast(JavaSdkVersion.JDK_1_9)); return sdk9_plus != null? sdk9_plus : sortedSdks.iterator().next(); // get the most used } } // now select the latest version from the sdks that are used in the project, but not older than <oldestPossibleVersion> return candidates.keySet().stream() .map(sdk -> Pair.create(sdk, JavaVersion.tryParse(sdk.getVersionString()))) .filter(p -> p.second != null && p.second.isAtLeast(oldestPossibleVersion)) .max(Pair.comparingBySecond()) .map(p -> Pair.create(p.first, JavaSdkVersion.fromJavaVersion(p.second))) .filter(p -> p.second != null) .orElseGet(() -> { Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); return Pair.create(internalJdk, javaSdkType.getVersion(internalJdk)); }); } private Future<Pair<RequestFuture<PreloadedProcessMessageHandler>, OSProcessHandler>> launchPreloadedBuildProcess(final Project project, ExecutorService projectTaskQueue) { // launching build process from projectTaskQueue ensures that no other build process for this project is currently running return projectTaskQueue.submit(() -> { if (project.isDisposed()) { return null; } final RequestFuture<PreloadedProcessMessageHandler> future = new RequestFuture<>(new PreloadedProcessMessageHandler(), UUID.randomUUID(), new CancelBuildSessionAction<>()); try { myMessageDispatcher.registerBuildMessageHandler(future, null); final OSProcessHandler processHandler = launchBuildProcess(project, future.getRequestID(), true, null); final StringBuffer errors = new StringBuffer(); processHandler.addProcessListener(new StdOutputCollector(errors)); STDERR_OUTPUT.set(processHandler, errors); processHandler.startNotify(); return Pair.create(future, processHandler); } catch (Throwable e) { handleProcessExecutionFailure(future.getRequestID(), e); throw e instanceof Exception? (Exception)e : new RuntimeException(e); } }); } @Nullable private static WSLDistribution findWSLDistributionForBuild(@NotNull Project project) { final Pair<Sdk, JavaSdkVersion> pair = getBuildProcessRuntimeSdk(project); final Sdk projectJdk = pair.first; final JavaSdkType projectJdkType = (JavaSdkType)projectJdk.getSdkType(); return WslPath.getDistributionByWindowsUncPath(projectJdkType.getVMExecutablePath(projectJdk)); } private OSProcessHandler launchBuildProcess(@NotNull Project project, @NotNull UUID sessionId, boolean requestProjectPreload, @Nullable ProgressIndicator progressIndicator) throws ExecutionException { String compilerPath = null; final String vmExecutablePath; JavaSdkVersion sdkVersion = null; final String forcedCompiledJdkHome = Registry.stringValue(COMPILER_PROCESS_JDK_PROPERTY); if (Strings.isEmptyOrSpaces(forcedCompiledJdkHome)) { // choosing sdk with which the build process should be run final Pair<Sdk, JavaSdkVersion> pair = getBuildProcessRuntimeSdk(project); final Sdk projectJdk = pair.first; sdkVersion = pair.second; final JavaSdkType projectJdkType = (JavaSdkType)projectJdk.getSdkType(); // validate tools.jar presence for jdk8 and older if (!JavaSdkUtil.isJdkAtLeast(projectJdk, JavaSdkVersion.JDK_1_9)) { final Sdk internalJdk = JavaAwareProjectJdkTableImpl.getInstanceEx().getInternalJdk(); if (FileUtil.pathsEqual(projectJdk.getHomePath(), internalJdk.getHomePath())) { // important: because internal JDK can be either JDK or JRE, // this is the most universal way to obtain tools.jar path in this particular case final JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler(); if (systemCompiler == null) { //temporary workaround for IDEA-169747 try { compilerPath = ClasspathBootstrap.getResourcePath(Class.forName("com.sun.tools.javac.api.JavacTool", false, BuildManager.class.getClassLoader())); } catch (Throwable t) { LOG.info(t); compilerPath = null; } if (compilerPath == null) { throw new ExecutionException(JavaCompilerBundle.message("build.process.no.javac.found")); } } else { compilerPath = ClasspathBootstrap.getResourcePath(systemCompiler.getClass()); } } else { compilerPath = projectJdkType.getToolsPath(projectJdk); if (compilerPath == null) { throw new ExecutionException(JavaCompilerBundle.message("build.process.no.javac.path.found", projectJdk.getName(), projectJdk.getHomePath())); } } } vmExecutablePath = projectJdkType.getVMExecutablePath(projectJdk); } else { compilerPath = new File(forcedCompiledJdkHome, "lib/tools.jar").getAbsolutePath(); vmExecutablePath = new File(forcedCompiledJdkHome, "bin/java").getAbsolutePath(); } final CompilerConfiguration projectConfig = CompilerConfiguration.getInstance(project); final CompilerWorkspaceConfiguration config = CompilerWorkspaceConfiguration.getInstance(project); BuildCommandLineBuilder cmdLine; WslPath wslPath = WslPath.parseWindowsUncPath(vmExecutablePath); if (wslPath != null) { cmdLine = new WslBuildCommandLineBuilder(project, wslPath.getDistribution(), wslPath.getLinuxPath(), progressIndicator); } else { cmdLine = new LocalBuildCommandLineBuilder(vmExecutablePath); } int listenPort = ensureListening(cmdLine.getListenAddress()); boolean isProfilingMode = false; String userDefinedHeapSize = null; final List<String> userAdditionalOptionsList = new SmartList<>(); final String userAdditionalVMOptions = config.COMPILER_PROCESS_ADDITIONAL_VM_OPTIONS; final boolean userLocalOptionsActive = !StringUtil.isEmptyOrSpaces(userAdditionalVMOptions); final String additionalOptions = userLocalOptionsActive ? userAdditionalVMOptions : projectConfig.getBuildProcessVMOptions(); if (!StringUtil.isEmptyOrSpaces(additionalOptions)) { final StringTokenizer tokenizer = new StringTokenizer(additionalOptions, " ", false); while (tokenizer.hasMoreTokens()) { final String option = tokenizer.nextToken(); if (StringUtil.startsWithIgnoreCase(option, "-Xmx")) { if (userLocalOptionsActive) { userDefinedHeapSize = option; } } else { if ("-Dprofiling.mode=true".equals(option)) { isProfilingMode = true; } userAdditionalOptionsList.add(option); } } } final int localHeapSize = config.COMPILER_PROCESS_HEAP_SIZE; if (localHeapSize > 0) { cmdLine.addParameter("-Xmx" + localHeapSize + "m"); } else if (userDefinedHeapSize != null) { cmdLine.addParameter(userDefinedHeapSize); } else { final int heapSize = projectConfig.getBuildProcessHeapSize(JavacConfiguration.getOptions(project, JavacConfiguration.class).MAXIMUM_HEAP_SIZE); cmdLine.addParameter("-Xmx" + heapSize + "m"); } cmdLine.addParameter("-Djava.awt.headless=true"); if (sdkVersion != null) { if (sdkVersion.compareTo(JavaSdkVersion.JDK_1_9) < 0) { //-Djava.endorsed.dirs is not supported in JDK 9+, may result in abnormal process termination cmdLine.addParameter("-Djava.endorsed.dirs=\"\""); // turn off all jre customizations for predictable behaviour } if (sdkVersion.isAtLeast(JavaSdkVersion.JDK_16)) { // enable javac-related reflection tricks in JPS ClasspathBootstrap.configureReflectionOpenPackages(p -> cmdLine.addParameter(p)); } } if (IS_UNIT_TEST_MODE) { cmdLine.addParameter("-Dtest.mode=true"); } if (requestProjectPreload) { cmdLine.addPathParameter("-Dpreload.project.path=", FileUtil.toCanonicalPath(getProjectPath(project))); cmdLine.addPathParameter("-Dpreload.config.path=", FileUtil.toCanonicalPath(PathManager.getOptionsPath())); } if (ProjectUtilCore.isExternalStorageEnabled(project)) { cmdLine.addPathParameter("-D" + GlobalOptions.EXTERNAL_PROJECT_CONFIG + "=", ProjectUtil.getExternalConfigurationDir(project)); } cmdLine.addParameter("-D" + GlobalOptions.COMPILE_PARALLEL_OPTION + "=" + projectConfig.isParallelCompilationEnabled()); if (projectConfig.isParallelCompilationEnabled()) { if (!Registry.is("compiler.automake.allow.parallel", true)) { cmdLine.addParameter("-D" + GlobalOptions.ALLOW_PARALLEL_AUTOMAKE_OPTION + "=false"); } } cmdLine.addParameter("-D" + GlobalOptions.REBUILD_ON_DEPENDENCY_CHANGE_OPTION + "=" + config.REBUILD_ON_DEPENDENCY_CHANGE); if (Registry.is("compiler.build.report.statistics")) { cmdLine.addParameter("-D" + GlobalOptions.REPORT_BUILD_STATISTICS + "=true"); } if (Registry.is("compiler.natural.int.multimap.impl")) { // todo: temporary flag to evaluate experimental multimap implementation cmdLine.addParameter("-Djps.mappings.natural.int.multimap.impl=true"); } // third party libraries tweaks cmdLine.addParameter("-Djdt.compiler.useSingleThread=true"); // always run eclipse compiler in single-threaded mode cmdLine.addParameter("-Daether.connector.resumeDownloads=false"); // always re-download maven libraries if partially downloaded cmdLine.addParameter("-Dio.netty.initialSeedUniquifier=" + ThreadLocalRandom.getInitialSeedUniquifier()); // this will make netty initialization faster on some systems for (String option : userAdditionalOptionsList) { cmdLine.addParameter(option); } cmdLine.setupAdditionalVMOptions(); Path hostWorkingDirectory = cmdLine.getHostWorkingDirectory(); if (!FileUtil.createDirectory(hostWorkingDirectory.toFile())) { LOG.warn("Failed to create build working directory " + hostWorkingDirectory); } if (isProfilingMode) { try { YourKitProfilerService yourKitProfilerService = ApplicationManager.getApplication().getService(YourKitProfilerService.class); if (yourKitProfilerService == null) { throw new IOException("Performance Plugin is missing or disabled"); } yourKitProfilerService.copyYKLibraries(hostWorkingDirectory); String buildSnapshotPath = System.getProperty("build.snapshots.path"); String parameters; if (buildSnapshotPath != null) { parameters = "-agentpath:" + cmdLine.getYjpAgentPath(yourKitProfilerService) + "=disablealloc,delay=10000,sessionname=ExternalBuild,dir=" + buildSnapshotPath; } else { parameters = "-agentpath:" + cmdLine.getYjpAgentPath(yourKitProfilerService) + "=disablealloc,delay=10000,sessionname=ExternalBuild"; } cmdLine.addParameter(parameters); showSnapshotNotificationAfterFinish(project); } catch (IOException e) { LOG.warn(e); } } // debugging int debugPort = -1; if (myBuildProcessDebuggingEnabled) { debugPort = Registry.intValue("compiler.process.debug.port"); if (debugPort <= 0) { try { debugPort = NetUtils.findAvailableSocketPort(); } catch (IOException e) { throw new ExecutionException(JavaCompilerBundle.message("build.process.no.free.debug.port"), e); } } if (debugPort > 0) { cmdLine.addParameter("-XX:+HeapDumpOnOutOfMemoryError"); cmdLine.addParameter("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + debugPort); } } // portable caches if (Registry.is("compiler.process.use.portable.caches") && CompilerCacheConfigurator.isServerUrlConfigured(project) && CompilerCacheStartupActivity.isLineEndingsConfiguredCorrectly()) { //cmdLine.addParameter("-Didea.resizeable.file.truncate.on.close=true"); //cmdLine.addParameter("-Dkotlin.jps.non.caching.storage=true"); cmdLine.addParameter("-D" + ProjectStamps.PORTABLE_CACHES_PROPERTY + "=true"); } // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language cmdLine.setCharset(mySystemCharset); cmdLine.addParameter("-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + mySystemCharset.name()); for (String name : INHERITED_IDE_VM_OPTIONS) { final String value = System.getProperty(name); if (value != null) { cmdLine.addParameter("-D" + name + "=" + value); } } final DynamicBundle.LanguageBundleEP languageBundle = DynamicBundle.findLanguageBundle(); if (languageBundle != null) { final PluginDescriptor pluginDescriptor = languageBundle.pluginDescriptor; final ClassLoader loader = pluginDescriptor == null ? null : pluginDescriptor.getClassLoader(); final String bundlePath = loader == null ? null : PathManager.getResourceRoot(loader, "META-INF/plugin.xml"); if (bundlePath != null) { cmdLine.addParameter("-D"+ GlobalOptions.LANGUAGE_BUNDLE + "=" + FileUtil.toSystemIndependentName(bundlePath)); } } cmdLine.addPathParameter("-D" + PathManager.PROPERTY_HOME_PATH + "=", FileUtil.toSystemIndependentName(PathManager.getHomePath())); cmdLine.addPathParameter("-D" + PathManager.PROPERTY_CONFIG_PATH + "=", FileUtil.toSystemIndependentName(PathManager.getConfigPath())); cmdLine.addPathParameter("-D" + PathManager.PROPERTY_PLUGINS_PATH + "=", FileUtil.toSystemIndependentName(PathManager.getPluginsPath())); cmdLine.addPathParameter("-D" + GlobalOptions.LOG_DIR_OPTION + "=", FileUtil.toSystemIndependentName(getBuildLogDirectory().getAbsolutePath())); if (myFallbackSdkHome != null && myFallbackSdkVersion != null) { cmdLine.addPathParameter("-D" + GlobalOptions.FALLBACK_JDK_HOME + "=", myFallbackSdkHome); cmdLine.addParameter("-D" + GlobalOptions.FALLBACK_JDK_VERSION + "=" + myFallbackSdkVersion); } cmdLine.addParameter("-Dio.netty.noUnsafe=true"); final File projectSystemRoot = getProjectSystemDirectory(project); if (projectSystemRoot != null) { cmdLine.addPathParameter("-Djava.io.tmpdir=", FileUtil.toSystemIndependentName(projectSystemRoot.getPath()) + "/" + TEMP_DIR_NAME); } for (BuildProcessParametersProvider provider : BuildProcessParametersProvider.EP_NAME.getExtensions(project)) { for (String arg : provider.getVMArguments()) { cmdLine.addParameter(arg); } for (Pair<String, Path> parameter : provider.getPathParameters()) { cmdLine.addPathParameter(parameter.getFirst(), cmdLine.copyPathToTargetIfRequired(parameter.getSecond())); } } @SuppressWarnings("UnnecessaryFullyQualifiedName") final Class<?> launcherClass = org.jetbrains.jps.cmdline.Launcher.class; final List<String> launcherCp = new ArrayList<>(); launcherCp.add(ClasspathBootstrap.getResourcePath(launcherClass)); launcherCp.addAll(BuildProcessClasspathManager.getLauncherClasspath(project)); if (compilerPath != null) { // can be null in case of jdk9 launcherCp.add(compilerPath); } boolean includeBundledEcj = shouldIncludeEclipseCompiler(projectConfig); File customEcjPath = null; if (includeBundledEcj) { final String path = EclipseCompilerConfiguration.getOptions(project, EclipseCompilerConfiguration.class).ECJ_TOOL_PATH; if (!StringUtil.isEmptyOrSpaces(path)) { customEcjPath = new File(path); if (customEcjPath.exists()) { includeBundledEcj = false; } else { throw new ExecutionException(JavaCompilerBundle.message("build.process.ecj.path.does.not.exist", customEcjPath.getAbsolutePath())); //customEcjPath = null; } } } ClasspathBootstrap.appendJavaCompilerClasspath(launcherCp, includeBundledEcj); if (customEcjPath != null) { launcherCp.add(customEcjPath.getAbsolutePath()); } cmdLine.addParameter("-classpath"); cmdLine.addClasspathParameter(launcherCp, Collections.emptyList()); cmdLine.addParameter(launcherClass.getName()); final List<String> cp = myClasspathManager.getBuildProcessClasspath(project); cmdLine.addClasspathParameter(cp, isProfilingMode ? Collections.singletonList("yjp-controller-api-redist.jar") : Collections.emptyList()); for (BuildProcessParametersProvider buildProcessParametersProvider : BuildProcessParametersProvider.EP_NAME.getExtensions(project)) { for (String path : buildProcessParametersProvider.getAdditionalPluginPaths()) { cmdLine.copyPathToTargetIfRequired(Paths.get(path)); } } cmdLine.addParameter(BuildMain.class.getName()); cmdLine.addParameter(cmdLine.getHostIp()); cmdLine.addParameter(Integer.toString(listenPort)); cmdLine.addParameter(sessionId.toString()); cmdLine.addParameter(cmdLine.getWorkingDirectory()); boolean lowPriority = AdvancedSettings.getBoolean("compiler.lower.process.priority"); if (SystemInfo.isUnix && lowPriority) { cmdLine.setUnixProcessPriority(10); } try { ApplicationManager.getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).beforeBuildProcessStarted(project, sessionId); } catch (Throwable e) { LOG.error(e); } final OSProcessHandler processHandler = new OSProcessHandler(cmdLine.buildCommandLine()) { @Override protected boolean shouldDestroyProcessRecursively() { return true; } @NotNull @Override protected BaseOutputReader.Options readerOptions() { return BaseOutputReader.Options.BLOCKING; } }; processHandler.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { // re-translate builder's output to idea.log final String text = event.getText(); if (!StringUtil.isEmptyOrSpaces(text)) { if (ProcessOutputTypes.SYSTEM.equals(outputType)) { if (LOG.isDebugEnabled()) { LOG.debug("BUILDER_PROCESS [" + outputType + "]: " + text.trim()); } } else { LOG.info("BUILDER_PROCESS [" + outputType + "]: " + text.trim()); } } } }); if (debugPort > 0) { processHandler.putUserData(COMPILER_PROCESS_DEBUG_PORT, debugPort); } if (SystemInfo.isWindows && lowPriority) { final WinProcess winProcess = new WinProcess(OSProcessUtil.getProcessID(processHandler.getProcess())); winProcess.setPriority(Priority.IDLE); } return processHandler; } private static void showSnapshotNotificationAfterFinish(@NotNull Project project) { MessageBusConnection busConnection = project.getMessageBus().connect(); busConnection.subscribe(BuildManagerListener.TOPIC, new BuildManagerListener() { @Override public void buildFinished(@NotNull Project project, @NotNull UUID sessionId, boolean isAutomake) { busConnection.disconnect(); final Notification notification = new Notification( "Build Profiler", JavaCompilerBundle.message("notification.title.cpu.snapshot.build.has.been.captured"), "", NotificationType.INFORMATION ); notification.addAction(new DumbAwareAction(JavaCompilerBundle.message("action.show.snapshot.location.text")) { @Override public void actionPerformed(@NotNull AnActionEvent e) { RevealFileAction.openDirectory(new File(SystemProperties.getUserHome(), "snapshots")); notification.expire(); } }); Notifications.Bus.notify(notification, project); } }); } private static boolean shouldIncludeEclipseCompiler(CompilerConfiguration config) { if (config instanceof CompilerConfigurationImpl) { final BackendCompiler javaCompiler = ((CompilerConfigurationImpl)config).getDefaultCompiler(); final String compilerId = javaCompiler != null ? javaCompiler.getId() : null; return JavaCompilers.ECLIPSE_ID.equals(compilerId) || JavaCompilers.ECLIPSE_EMBEDDED_ID.equals(compilerId); } return true; } /** * @deprecated use {@link #getBuildSystemDirectory(Project)} */ @Deprecated(forRemoval = true) @NotNull public Path getBuildSystemDirectory() { return LocalBuildCommandLineBuilder.getLocalBuildSystemDirectory(); } @NotNull public Path getBuildSystemDirectory(Project project) { final WslPath wslPath = WslPath.parseWindowsUncPath(getProjectPath(project)); if (wslPath != null) { Path buildDir = WslBuildCommandLineBuilder.getWslBuildSystemDirectory(wslPath.getDistribution()); if (buildDir != null) { return buildDir; } } return LocalBuildCommandLineBuilder.getLocalBuildSystemDirectory(); } @NotNull public static File getBuildLogDirectory() { return new File(PathManager.getLogPath(), "build-log"); } @Nullable public File getProjectSystemDirectory(Project project) { String projectPath = getProjectPath(project); WslPath wslPath = WslPath.parseWindowsUncPath(projectPath); Function<String, Integer> hashFunction; if (wslPath == null) { hashFunction = String::hashCode; } else { hashFunction = s -> wslPath.getDistribution().getWslPath(s).hashCode(); } return Utils.getDataStorageRoot(getBuildSystemDirectory(project).toFile(), projectPath, hashFunction); } private static File getUsageFile(@NotNull File projectSystemDir) { return new File(projectSystemDir, "ustamp"); } private static void updateUsageFile(@Nullable Project project, @NotNull File projectSystemDir) { File usageFile = getUsageFile(projectSystemDir); StringBuilder content = new StringBuilder(); try { synchronized (USAGE_STAMP_DATE_FORMAT) { content.append(USAGE_STAMP_DATE_FORMAT.format(System.currentTimeMillis())); } if (project != null && !project.isDisposed()) { final String projectFilePath = project.getProjectFilePath(); if (!StringUtil.isEmptyOrSpaces(projectFilePath)) { content.append("\n").append(FileUtil.toCanonicalPath(projectFilePath)); } } FileUtil.writeToFile(usageFile, content.toString()); } catch (Throwable e) { LOG.info(e); } } @Nullable private static Pair<Date, File> readUsageFile(File usageFile) { try { List<String> lines = FileUtil.loadLines(usageFile, StandardCharsets.UTF_8.name()); if (!lines.isEmpty()) { final String dateString = lines.get(0); final Date date; synchronized (USAGE_STAMP_DATE_FORMAT) { date = USAGE_STAMP_DATE_FORMAT.parse(dateString); } final File projectFile = lines.size() > 1? new File(lines.get(1)) : null; return Pair.create(date, projectFile); } } catch (Throwable e) { LOG.info(e); } return null; } private void stopListening() { for (ListeningConnection connection : myListeningConnections) { connection.myChannelRegistrar.close(); } myListeningConnections.clear(); } private int startListening(InetAddress address) { ListeningConnection listeningConnection = new ListeningConnection(address); BuiltInServerManager builtInServerManager = BuiltInServerManager.getInstance(); builtInServerManager.waitForStart(); ServerBootstrap bootstrap = ((BuiltInServerManagerImpl)builtInServerManager).createServerBootstrap(); bootstrap.childHandler(new ChannelInitializer<>() { @Override protected void initChannel(@NotNull Channel channel) { channel.pipeline().addLast(listeningConnection.myChannelRegistrar, new ProtobufVarint32FrameDecoder(), new ProtobufDecoder(CmdlineRemoteProto.Message.getDefaultInstance()), new ProtobufVarint32LengthFieldPrepender(), new ProtobufEncoder(), myMessageDispatcher); } }); Channel serverChannel = bootstrap.bind(address, 0).syncUninterruptibly().channel(); listeningConnection.myChannelRegistrar.setServerChannel(serverChannel, false); int port = ((InetSocketAddress)serverChannel.localAddress()).getPort(); listeningConnection.myListenPort = port; myListeningConnections.add(listeningConnection); return port; } public boolean isBuildProcessDebuggingEnabled() { return myBuildProcessDebuggingEnabled; } public void setBuildProcessDebuggingEnabled(boolean buildProcessDebuggingEnabled) { myBuildProcessDebuggingEnabled = buildProcessDebuggingEnabled; if (myBuildProcessDebuggingEnabled) { cancelAllPreloadedBuilds(); } } private abstract class BuildManagerPeriodicTask implements Runnable { private final Alarm myAlarm; private final AtomicBoolean myInProgress = new AtomicBoolean(false); private final Runnable myTaskRunnable = () -> { try { runTask(); } finally { myInProgress.set(false); } }; BuildManagerPeriodicTask() { myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, BuildManager.this); } final void schedule() { schedule(false); } private void schedule(boolean increasedDelay) { cancelPendingExecution(); myAlarm.addRequest(this, Math.max(100, increasedDelay ? 10 * getDelay() : getDelay())); } void cancelPendingExecution() { myAlarm.cancelAllRequests(); } protected boolean shouldPostpone() { return false; } protected abstract int getDelay(); protected abstract void runTask(); @Override public final void run() { final boolean shouldPostponeAllTasks = HeavyProcessLatch.INSTANCE.isRunning() || mySuspendBackgroundTasksCounter.get() > 0; if (!shouldPostponeAllTasks && !shouldPostpone() && !myInProgress.getAndSet(true)) { try { ApplicationManager.getApplication().executeOnPooledThread(myTaskRunnable); } catch (RejectedExecutionException ignored) { // we were shut down myInProgress.set(false); } catch (Throwable e) { myInProgress.set(false); throw new RuntimeException(e); } } else { schedule(shouldPostponeAllTasks); } } } private static final class NotifyingMessageHandler extends DelegatingMessageHandler { private final Project myProject; private final BuilderMessageHandler myDelegateHandler; @Nullable private final Function<String, String> myPathMapper; private final boolean myIsAutomake; NotifyingMessageHandler(@NotNull Project project, @NotNull BuilderMessageHandler delegateHandler, @Nullable Function<String, String> pathMapper, final boolean isAutomake) { myProject = project; myDelegateHandler = delegateHandler; myPathMapper = pathMapper; myIsAutomake = isAutomake; } @Override protected BuilderMessageHandler getDelegateHandler() { return myDelegateHandler; } @Override public void buildStarted(@NotNull UUID sessionId) { super.buildStarted(sessionId); try { ApplicationManager .getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).buildStarted(myProject, sessionId, myIsAutomake); } catch (Throwable e) { LOG.error(e); } } @Override public void sessionTerminated(@NotNull UUID sessionId) { try { super.sessionTerminated(sessionId); } finally { try { ApplicationManager.getApplication().getMessageBus().syncPublisher(BuildManagerListener.TOPIC).buildFinished(myProject, sessionId, myIsAutomake); } catch (AlreadyDisposedException e) { LOG.warn(e); } catch (Throwable e) { LOG.error(e); } } } @Override public void handleBuildMessage(Channel channel, UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage msg) { CmdlineRemoteProto.Message.BuilderMessage _message = msg; if (myPathMapper != null) { if (_message.hasCompileMessage()) { final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage compileMessage = _message.getCompileMessage(); if (compileMessage.hasSourceFilePath()) { final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Builder builder = CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.newBuilder(compileMessage); builder.setSourceFilePath(myPathMapper.apply(compileMessage.getSourceFilePath())); _message = CmdlineRemoteProto.Message.BuilderMessage.newBuilder(_message).setCompileMessage(builder).build(); } } if (_message.hasBuildEvent()) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent buildEvent = _message.getBuildEvent(); final int filesCount = buildEvent.getGeneratedFilesCount(); if (filesCount > 0) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Builder builder = CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.newBuilder(buildEvent); for (int idx = 0; idx < filesCount; idx++) { final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile file = buildEvent.getGeneratedFiles(idx); builder.setGeneratedFiles(idx, CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile.newBuilder(file).setOutputRoot(myPathMapper.apply(file.getOutputRoot()))); } _message = CmdlineRemoteProto.Message.BuilderMessage.newBuilder(_message).setBuildEvent(builder).build(); } } } super.handleBuildMessage(channel, sessionId, _message); } } private static final class StdOutputCollector extends ProcessAdapter { private final Appendable myOutput; private int myStoredLength; StdOutputCollector(@NotNull Appendable outputSink) { myOutput = outputSink; } @Override public void onTextAvailable(@NotNull ProcessEvent event, @NotNull Key outputType) { String text; synchronized (this) { if (myStoredLength > 16384) { return; } text = event.getText(); if (StringUtil.isEmptyOrSpaces(text)) { return; } myStoredLength += text.length(); } try { myOutput.append(text); } catch (IOException ignored) { } } } static final class BuildManagerStartupActivity implements StartupActivity.DumbAware { @Override public void runActivity(@NotNull Project project) { if (ApplicationManager.getApplication().isHeadlessEnvironment()) { return; } MessageBusConnection connection = project.getMessageBus().connect(); connection.subscribe(ProjectTopics.PROJECT_ROOTS, new ModuleRootListener() { @Override public void rootsChanged(@NotNull ModuleRootEvent event) { Object source = event.getSource(); if (source instanceof Project && !((Project)source).isDefault()) { getInstance().clearState((Project)source); } } }); connection.subscribe(ExecutionManager.EXECUTION_TOPIC, new ExecutionListener() { @Override public void processStarting(@NotNull String executorId, @NotNull ExecutionEnvironment env) { getInstance().cancelAutoMakeTasks(env.getProject()); // make sure to cancel all automakes waiting in the build queue } @Override public void processStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler) { // make sure to cancel all automakes added to the build queue after processStaring and before this event getInstance().cancelAutoMakeTasks(env.getProject()); } @Override public void processNotStarted(@NotNull String executorId, @NotNull ExecutionEnvironment env) { // augmenting reaction to processTerminated(): in case any automakes were canceled before process start getInstance().scheduleAutoMake(); } @Override public void processTerminated(@NotNull String executorId, @NotNull ExecutionEnvironment env, @NotNull ProcessHandler handler, int exitCode) { getInstance().scheduleAutoMake(); } }); connection.subscribe(CompilerTopics.COMPILATION_STATUS, new CompilationStatusListener() { private final Set<String> myRootsToRefresh = CollectionFactory.createFilePathSet(); @Override public void automakeCompilationFinished(int errors, int warnings, @NotNull CompileContext compileContext) { if (!compileContext.getProgressIndicator().isCanceled()) { refreshSources(compileContext); } } @Override public void compilationFinished(boolean aborted, int errors, int warnings, @NotNull CompileContext compileContext) { refreshSources(compileContext); } private void refreshSources(CompileContext compileContext) { if (project.isDisposed()) { return; } final Set<String> candidates = CollectionFactory.createFilePathSet(); synchronized (myRootsToRefresh) { candidates.addAll(myRootsToRefresh); myRootsToRefresh.clear(); } if (compileContext.isAnnotationProcessorsEnabled()) { // annotation processors may have re-generated code final CompilerConfiguration config = CompilerConfiguration.getInstance(project); for (Module module : compileContext.getCompileScope().getAffectedModules()) { if (config.getAnnotationProcessingConfiguration(module).isEnabled()) { final String productionPath = CompilerPaths.getAnnotationProcessorsGenerationPath(module, false); if (productionPath != null) { candidates.add(productionPath); } final String testsPath = CompilerPaths.getAnnotationProcessorsGenerationPath(module, true); if (testsPath != null) { candidates.add(testsPath); } } } } if (!candidates.isEmpty()) { ApplicationManager.getApplication().executeOnPooledThread(() -> { if (project.isDisposed()) { return; } CompilerUtil.refreshOutputRoots(candidates); LocalFileSystem lfs = LocalFileSystem.getInstance(); Set<VirtualFile> toRefresh = ReadAction.compute(() -> { if (project.isDisposed()) { return Collections.emptySet(); } else { ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); return candidates.stream() .map(lfs::findFileByPath) .filter(root -> root != null && fileIndex.isInSourceContent(root)) .collect(Collectors.toSet()); } }); if (!toRefresh.isEmpty()) { lfs.refreshFiles(toRefresh, true, true, null); } }); } } @Override public void fileGenerated(@NotNull String outputRoot, @NotNull String relativePath) { synchronized (myRootsToRefresh) { myRootsToRefresh.add(outputRoot); } } }); String projectPath = getProjectPath(project); Disposer.register(project, () -> { BuildManager buildManager = getInstance(); buildManager.cancelPreloadedBuilds(projectPath); buildManager.myProjectDataMap.remove(projectPath); }); BuildProcessParametersProvider.EP_NAME.addChangeListener(project, () -> getInstance().cancelAllPreloadedBuilds(), null); getInstance().runCommand(() -> { File projectSystemDir = getInstance().getProjectSystemDirectory(project); if (projectSystemDir != null) { updateUsageFile(project, projectSystemDir); } }); // run automake after project opened getInstance().scheduleAutoMake(); } } private final class ProjectWatcher implements ProjectManagerListener { private final Map<Project, MessageBusConnection> myConnections = new HashMap<>(); @Override public void projectClosingBeforeSave(@NotNull Project project) { myAutoMakeTask.cancelPendingExecution(); cancelAutoMakeTasks(project); } @Override public void projectClosing(@NotNull Project project) { String projectPath = Objects.requireNonNull(getProjectPath(project)); ProgressManager.getInstance().run(new Task.Modal(project, JavaCompilerBundle.message("progress.title.cancelling.auto.make.builds"), false) { @Override public void run(@NotNull ProgressIndicator indicator) { myAutoMakeTask.cancelPendingExecution(); cancelPreloadedBuilds(projectPath); for (TaskFuture<?> future : cancelAutoMakeTasks(getProject())) { future.waitFor(500, TimeUnit.MILLISECONDS); } } }); } @Override public void projectClosed(@NotNull Project project) { if (myProjectDataMap.remove(getProjectPath(project)) != null) { if (myProjectDataMap.isEmpty()) { InternedPath.clearCache(); } } MessageBusConnection connection = myConnections.remove(project); if (connection != null) { connection.disconnect(); } } } private static final class ProjectData { @NotNull final ExecutorService taskQueue; private final Set<InternedPath> myChanged = new HashSet<>(); private final Set<InternedPath> myDeleted = new HashSet<>(); private long myNextEventOrdinal; private boolean myNeedRescan = true; private ProjectData(@NotNull ExecutorService taskQueue) { this.taskQueue = taskQueue; } boolean hasChanges() { return myNeedRescan || !myChanged.isEmpty() || !myDeleted.isEmpty(); } void addChanged(Collection<String> paths) { if (!myNeedRescan) { for (String path : paths) { final InternedPath _path = InternedPath.create(path); myDeleted.remove(_path); myChanged.add(_path); } } } void addDeleted(Collection<String> paths) { if (!myNeedRescan) { for (String path : paths) { final InternedPath _path = InternedPath.create(path); myChanged.remove(_path); myDeleted.add(_path); } } } CmdlineRemoteProto.Message.ControllerMessage.FSEvent createNextEvent(Function<String, String> pathMapper) { final CmdlineRemoteProto.Message.ControllerMessage.FSEvent.Builder builder = CmdlineRemoteProto.Message.ControllerMessage.FSEvent.newBuilder(); builder.setOrdinal(++myNextEventOrdinal); for (InternedPath path : myChanged) { builder.addChangedPaths(pathMapper.apply(path.getValue())); } myChanged.clear(); for (InternedPath path : myDeleted) { builder.addDeletedPaths(pathMapper.apply(path.getValue())); } myDeleted.clear(); return builder.build(); } boolean getAndResetRescanFlag() { final boolean rescan = myNeedRescan; myNeedRescan = false; return rescan; } void dropChanges() { if (LOG.isDebugEnabled()) { LOG.debug("Project build state cleared: " + getThreadTrace(Thread.currentThread(), 20)); } myNeedRescan = true; myNextEventOrdinal = 0L; myChanged.clear(); myDeleted.clear(); } } private abstract static class InternedPath { private static final SLRUCache<CharSequence, CharSequence> ourNamesCache = SLRUCache.create(1024, 1024, key -> key); protected final CharSequence[] myPath; /** * @param path assuming system-independent path with forward slashes */ InternedPath(String path) { final List<CharSequence> list = new ArrayList<>(); final StringTokenizer tokenizer = new StringTokenizer(path, "/", false); synchronized (ourNamesCache) { while(tokenizer.hasMoreTokens()) { list.add(ourNamesCache.get(tokenizer.nextToken())); } } myPath = list.toArray(CharSequence[]::new); } public abstract String getValue(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; InternedPath path = (InternedPath)o; return Arrays.equals(myPath, path.myPath); } @Override public int hashCode() { return Arrays.hashCode(myPath); } public static void clearCache() { synchronized (ourNamesCache) { ourNamesCache.clear(); } } public static InternedPath create(String path) { return path.startsWith("/")? new XInternedPath(path) : new WinInternedPath(path); } } private static final class WinInternedPath extends InternedPath { private WinInternedPath(String path) { super(path); } @Override public String getValue() { if (myPath.length == 1) { final String name = myPath[0].toString(); // handle case of windows drive letter return name.length() == 2 && name.endsWith(":")? name + "/" : name; } final StringBuilder buf = new StringBuilder(); for (CharSequence element : myPath) { if (buf.length() > 0) { buf.append("/"); } buf.append(element); } return buf.toString(); } } private static final class XInternedPath extends InternedPath { private XInternedPath(String path) { super(path); } @Override public String getValue() { if (myPath.length > 0) { final StringBuilder buf = new StringBuilder(); for (CharSequence element : myPath) { buf.append("/").append(element); } return buf.toString(); } return "/"; } } private static final class DelegateFuture implements TaskFuture { private List<TaskFuture<?>> myDelegates; private Boolean myRequestedCancelState; private synchronized @NotNull List<TaskFuture<?>> getDelegates() { List<TaskFuture<?>> delegates = myDelegates; while (delegates == null) { try { wait(); } catch (InterruptedException ignored) { } delegates = myDelegates; } return delegates; } private synchronized boolean setDelegates(@NotNull List<TaskFuture<?>> delegates) { if (myDelegates == null) { try { myDelegates = delegates; if (myRequestedCancelState != null) { for (TaskFuture<?> delegate : delegates) { delegate.cancel(myRequestedCancelState); } } } finally { notifyAll(); } return true; } return false; } @Override public synchronized boolean cancel(boolean mayInterruptIfRunning) { List<TaskFuture<?>> delegates = myDelegates; if (delegates == null) { myRequestedCancelState = mayInterruptIfRunning; return true; } for (TaskFuture<?> delegate : getDelegates()) { delegate.cancel(mayInterruptIfRunning); } return isDone(); } @Override public void waitFor() { for (TaskFuture<?> delegate : getDelegates()) { delegate.waitFor(); } } @Override public boolean waitFor(long timeout, TimeUnit unit) { for (TaskFuture<?> delegate : getDelegates()) { delegate.waitFor(timeout, unit); } return isDone(); } @Override public boolean isCancelled() { List<TaskFuture<?>> delegates; synchronized (this) { delegates = myDelegates; if (delegates == null) { return myRequestedCancelState != null; } } for (TaskFuture<?> delegate : delegates) { if (delegate.isCancelled()) { return true; } } return false; } @Override public boolean isDone() { List<TaskFuture<?>> delegates; synchronized (this) { delegates = myDelegates; if (delegates == null) { return false; } } for (TaskFuture<?> delegate : delegates) { if (!delegate.isDone()) { return false; } } return true; } @Override public Object get() throws InterruptedException, java.util.concurrent.ExecutionException { for (Future<?> delegate : getDelegates()) { delegate.get(); } return null; } @Override public Object get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, java.util.concurrent.ExecutionException, TimeoutException { for (Future<?> delegate : getDelegates()) { delegate.get(timeout, unit); } return null; } } private class CancelBuildSessionAction<T extends BuilderMessageHandler> implements RequestFuture.CancelAction<T> { @Override public void cancel(RequestFuture<T> future) { myMessageDispatcher.cancelSession(future.getRequestID()); notifySessionTerminationIfNeeded(future.getRequestID(), null); } } static final class MyDocumentListener implements DocumentListener { @Override public void documentChanged(@NotNull DocumentEvent e) { if (ApplicationManager.getApplication().isUnitTestMode() || !Registry.is("compiler.document.save.enabled", false)) { return; } Document document = e.getDocument(); if (!FileDocumentManager.getInstance().isDocumentUnsaved(document)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file != null && file.isInLocalFileSystem()) { getInstance().scheduleProjectSave(); } } } }
{ "content_hash": "026f7d71944b6d2ad4b5004a418dabfe", "timestamp": "", "source": "github", "line_count": 2368, "max_line_length": 202, "avg_line_length": 40.220861486486484, "alnum_prop": 0.6760706823598585, "repo_name": "jwren/intellij-community", "id": "47849845dcd51bd1715c1ad4acb819216671ea6b", "size": "95243", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /* * Name: LogLevel.php (UTF-8) * Language: PHP 5.5 * Date: 2014-11-14 * Author: Hauke Schulz <hauke27@googlemail.com> */ namespace hschulz\PSR3; /** * This is the reference implementation of the PSR-3 log levels. * * @author Hauke Schulz <hauke27@googlemail.com> * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @version 1.0 * @link https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md PSR-3 Standard */ interface LogLevel { const EMERGENCY = 'emergency'; const ALERT = 'alert'; const CRITICAL = 'critical'; const ERROR = 'error'; const WARNING = 'warning'; const NOTICE = 'notice'; const INFO = 'info'; const DEBUG = 'debug'; }
{ "content_hash": "511118fcd0e1e11d6b8f32dbacdb62fa", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 111, "avg_line_length": 25.766666666666666, "alnum_prop": 0.6390685640362225, "repo_name": "hschulz/PSR3", "id": "94c4390932b49b4cb05c2293b15bfcd2ef1c9ad1", "size": "773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/LogLevel.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "4719" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- **************************************************************** --> <!-- * PLEASE KEEP COMPLICATED EXPRESSIONS OUT OF THESE TEMPLATES, * --> <!-- * i.e. only iterate & print data where possible. Thanks, Jez. * --> <!-- **************************************************************** --> <html> <head> <!-- Generated by groovydoc (2.4.4) on Thu Jul 09 20:59:25 CEST 2015 --> <title>BuilderASTTransformation.BuilderStrategy (groovy 2.4.4 API)</title> <meta name="date" content="2015-07-09"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="../../../../groovy.ico" type="image/x-icon" rel="shortcut icon"> <link href="../../../../groovy.ico" type="image/x-icon" rel="icon"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <body class="center"> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="BuilderASTTransformation.BuilderStrategy (groovy 2.4.4 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../index.html?org/codehaus/groovy/transform/BuilderASTTransformation.BuilderStrategy" target="_top">Frames</a></li> <li><a href="BuilderASTTransformation.BuilderStrategy.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_summary">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_detail">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">Package: <strong>org.codehaus.groovy.transform</strong></div> <h2 title="[Java] Interface BuilderStrategy" class="title">[Java] Interface BuilderStrategy</h2> </div> <div class="contentContainer"> <ul class="inheritance"> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== NESTED CLASS SUMMARY =========== --> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <!-- =========== FIELD SUMMARY =========== --> <!-- =========== PROPERTY SUMMARY =========== --> <!-- =========== ELEMENT SUMMARY =========== --> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"><!-- --></a> <h3>Methods Summary</h3> <ul class="blockList"> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Methods Summary table"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Type</th> <th class="colLast" scope="col">Name and description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</strong></code></td> <td class="colLast"><code><strong><a href="#build(org.codehaus.groovy.transform.BuilderASTTransformation, org.codehaus.groovy.ast.AnnotatedNode, org.codehaus.groovy.ast.AnnotationNode)">build</a></strong>(<a href='../../../../org/codehaus/groovy/transform/BuilderASTTransformation.html'>BuilderASTTransformation</a> transform, <a href='../../../../org/codehaus/groovy/ast/AnnotatedNode.html'>AnnotatedNode</a> annotatedNode, <a href='../../../../org/codehaus/groovy/ast/AnnotationNode.html'>AnnotationNode</a> anno)</code><br></td> </tr> </table> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- =========== METHOD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="build(org.codehaus.groovy.transform.BuilderASTTransformation, org.codehaus.groovy.ast.AnnotatedNode, org.codehaus.groovy.ast.AnnotationNode)"><!-- --></a> <ul class="blockListLast"> <li class="blockList"> <h4>public&nbsp;void <strong>build</strong>(<a href='../../../../org/codehaus/groovy/transform/BuilderASTTransformation.html'>BuilderASTTransformation</a> transform, <a href='../../../../org/codehaus/groovy/ast/AnnotatedNode.html'>AnnotatedNode</a> annotatedNode, <a href='../../../../org/codehaus/groovy/ast/AnnotationNode.html'>AnnotationNode</a> anno)</h4> <p></p> </li> </ul> </li> </ul> </li> </ul> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <div> <ul class="navList"> <li><a href="../../../../index.html?org/codehaus/groovy/transform/BuilderASTTransformation.BuilderStrategy" target="_top">Frames</a></li> <li><a href="BuilderASTTransformation.BuilderStrategy.html" target="_top">No Frames</a></li> </ul> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> Nested&nbsp;&nbsp;&nbsp;Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_summary">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> <ul class="subNavList"> <li>&nbsp;|&nbsp;Detail:&nbsp;</li> Field&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<li><a href="#method_detail">Method</a></li>&nbsp;&nbsp;&nbsp; </ul> </div> <p>Copyright &copy; 2003-2015 The Apache Software Foundation. All rights reserved.</p> <a name="skip-navbar_bottom"> <!-- --> </a> </div> </div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "85f72c049a0b518e663433ee243e517a", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 559, "avg_line_length": 39.71120689655172, "alnum_prop": 0.5197004233148812, "repo_name": "OpenBEL/kam-nav", "id": "bf5afde672a20f50d886f20e9299b4ff321f837d", "size": "9213", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/groovy/doc/html/gapi/org/codehaus/groovy/transform/BuilderASTTransformation.BuilderStrategy.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "163791" }, { "name": "Shell", "bytes": "8325" } ], "symlink_target": "" }
package cloud.artik.websocket; public enum ConnectionStatus { CONNECTING, CONNECTED, CLOSING, CLOSED }
{ "content_hash": "59d8bf7699aa26954c510e4f3d936df4", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 42, "avg_line_length": 21.6, "alnum_prop": 0.7777777777777778, "repo_name": "artikcloud/artikcloud-java", "id": "f8986e59a5f06c462b1c645d693b52c6bcf1e4c9", "size": "108", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cloud/artik/websocket/ConnectionStatus.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1410484" }, { "name": "Scala", "bytes": "779" }, { "name": "Shell", "bytes": "1630" } ], "symlink_target": "" }
'use strict'; const expect = require('expect'); const remove = require('../remove'); const { init, ls, write, open } = require('../../filer'); describe('remove methods', function(){ const filepath = 'test.txt'; const data = 'this is sample text'; beforeEach(function(){ return init() .then(() => write(filepath, { data, type: 'text/plain'})); }); after(function(){ return init() .then(() => ls('/')); }); it('removes a file at a given filepath', function(){ const errName = 'NOT_FOUND_ERR'; return remove(filepath) .then(() => open(filepath)) .catch((err) => { expect(err.name).toEqual(errName); }); }); });
{ "content_hash": "d2027d554f602da57c837df5886045fd", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 64, "avg_line_length": 19.771428571428572, "alnum_prop": 0.5578034682080925, "repo_name": "iceddev/frylord", "id": "9c5de675bd519d1b12c7555e4b50c7b0b422fd36", "size": "692", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/methods/__tests__/remove.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "83384" } ], "symlink_target": "" }
module.exports = org.slf4j.LoggerFactory;
{ "content_hash": "e051f6f44ca0a25d996b0e29c0bbc1df", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 41, "avg_line_length": 41, "alnum_prop": 0.8292682926829268, "repo_name": "rec-framework/rec-core", "id": "d195ab66fb7703dc6fccfcbc5da415d98c8d9240", "size": "42", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/rec/logging.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "82954" }, { "name": "JavaScript", "bytes": "4489" }, { "name": "Shell", "bytes": "380" } ], "symlink_target": "" }
ActiveRecord::Schema.define(version: 20140226235544) do create_table "pills", force: true do |t| t.string "name" t.string "hormone" t.string "phase" t.datetime "created_at" t.datetime "updated_at" end end
{ "content_hash": "e2968fb760abb8619034b02715d62dd9", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 55, "avg_line_length": 21.545454545454547, "alnum_prop": 0.6497890295358649, "repo_name": "ajosepha/sinatra_angular_pills", "id": "701063d476a13ef66384bcca69ab2dec58b13a63", "size": "960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/schema.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1131" }, { "name": "JavaScript", "bytes": "12119" }, { "name": "Ruby", "bytes": "3678" }, { "name": "Shell", "bytes": "2722" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2020 The Android Open Source Project 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. --> <resources> <string name="app_name">Donut Tracker</string> <string name="action_settings">Settings</string> <!-- Strings used for fragments for navigation --> <string name="static_shortcut_label_short">New Donut</string> <string name="static_shortcut_label_long">Create New Donut</string> <string name="static_shortcut_disabled_message">New Donut Shortcut Disabled</string> <string name="donut_name">Donut name</string> <string name="donut_description">Description</string> <string name="donut_rating">Rating</string> <string name="delete">delete</string> <string name="defaultChannel">DonutTracker default channel</string> <string name="notificationDescription">Notifications from DonutTracker</string> <string name="addDonutInfo">Add more donut info!</string> <string name="deepLinkNotificationTitle">Deep Link</string> <string name="donutName">donutName</string> <string name="donutPicture">Picture of donut</string> <string name="name">Name</string> <string name="done">Done</string> <string name="rating">Rating</string> </resources>
{ "content_hash": "3053d3643f0d0dd51e6b41772ff02cd3", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 88, "avg_line_length": 47.13157894736842, "alnum_prop": 0.7174762702400893, "repo_name": "android/architecture-components-samples", "id": "2604e13295d6496e275439d008bd5bfc1c8fc49a", "size": "1791", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "MADSkillsNavigationSample/app/src/main/res/values/strings.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "240380" }, { "name": "Kotlin", "bytes": "520626" }, { "name": "RenderScript", "bytes": "2642" }, { "name": "Shell", "bytes": "2978" } ], "symlink_target": "" }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Keen.Test { /// <summary> /// Wraps an <see cref="IHttpMessageHandler"/> and allows for using it as a DelegatingHandler. /// If the IHttpMessageHandler doesn't already have a default action set, we'll have it call /// our own base SendAsync() which will forward the request down the handler chain. /// </summary> internal class DelegatingHandlerMock : DelegatingHandler { private readonly IHttpMessageHandler _handler; internal DelegatingHandlerMock(IHttpMessageHandler handler) { _handler = handler; _handler.DefaultAsync = (_handler.DefaultAsync ?? base.SendAsync); } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return _handler.SendAsync(request, cancellationToken); } } }
{ "content_hash": "95d00c0ff3c44c3423f8f924f3af6b97", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 99, "avg_line_length": 35.55172413793103, "alnum_prop": 0.6479146459747818, "repo_name": "keenlabs/keen-sdk-net", "id": "b31079dd5bfdf4bc4d2bc3bc456e63c357290ba8", "size": "1031", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Keen.Test/DelegatingHandlerMock.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "459783" }, { "name": "PowerShell", "bytes": "2082" } ], "symlink_target": "" }
<!DOCTYPE html> <html > <head> <!--[if lt IE 9]> <style>body {display: none; background: none !important} </style> <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" /> <![endif]--> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <meta name="format-detection" content="telephone=no" /> <meta name="author" content="xiaoyou" /> <meta property="og:type" content="website"> <meta property="og:title" content="Lost Youth"> <meta property="og:url" content="http://yoursite.com/tags/Tomcat/index.html"> <meta property="og:site_name" content="Lost Youth"> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="Lost Youth"> <link rel="apple-touch-icon" href= "/apple-touch-icon.png"> <link rel="alternate" href="/atom.xml" title="Lost Youth" type="application/atom+xml"> <link rel="shortcut icon" href="/favicon.png"> <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet"> <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet"> <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script> <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet"> <link rel="stylesheet" href="/css/style.css"> <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"> <title>Tag: Tomcat | Lost Youth</title> <script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script> <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script> <script> var yiliaConfig = { fancybox: true, animate: true, isHome: false, isPost: false, isArchive: false, isTag: true, isCategory: false, fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js", scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js", search: undefined } </script> <script> yiliaConfig.jquery_ui = [false]; </script> <script> yiliaConfig.rootUrl = "\/";</script> </head> <body> <div id="container"> <div class="left-col"> <div class="overlay"></div> <div class="intrude-less"> <header id="header" class="inner"> <a href="/" class="profilepic"> <img src="/img/avatar.png" class="animated zoomIn"> </a> <hgroup> <h1 class="header-author"><a href="/">xiaoyou</a></h1> </hgroup> <div id="switch-btn" class="switch-btn"> <div class="icon"> <div class="icon-ctn"> <div class="icon-wrap icon-house" data-idx="0"> <div class="birdhouse"></div> <div class="birdhouse_holes"></div> </div> <div class="icon-wrap icon-ribbon hide" data-idx="1"> <div class="ribbon"></div> </div> <div class="icon-wrap icon-link hide" data-idx="2"> <div class="loopback_l"></div> <div class="loopback_r"></div> </div> <div class="icon-wrap icon-me hide" data-idx="3"> <div class="user"></div> <div class="shoulder"></div> </div> </div> </div> <div class="tips-box hide"> <div class="tips-arrow"></div> <ul class="tips-inner"> <li>菜单</li> <li>标签</li> <li>友情链接</li> <li>关于我</li> </ul> </div> </div> <div id="switch-area" class="switch-area"> <div class="switch-wrap"> <section class="switch-part switch-part1"> <nav class="header-menu"> <ul> <li><a href="/">Home</a></li> <li><a href="/archives">Archives</a></li> <li><a href="/tools">Tools</a></li> <li><a href="/about">About</a></li> </ul> </nav> <nav class="header-nav"> <ul class="social"> <a class="fa Email" href="mailto:123@123.com" title="Email"></a> <a class="fa GitHub" href="#" title="GitHub"></a> <a class="fa RSS" href="/atom.xml" title="RSS"></a> </ul> </nav> </section> <section class="switch-part switch-part2"> <div class="widget tagcloud" id="js-tagcloud"> <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Git/">Git</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Java8/">Java8</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/MySql/">MySql</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/RocketMQ/">RocketMQ</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Spring-Boot/">Spring Boot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Tomcat/">Tomcat</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/分布式-服务化/">分布式 服务化</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/唯一ID/">唯一ID</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/微服务/">微服务</a></li></ul> </div> </section> <section class="switch-part switch-part3"> <div id="js-friends"> <a class="main-nav-link switch-friends-link" href="https://hexo.io">Hexo</a> <a class="main-nav-link switch-friends-link" href="https://pages.github.com/">GitHub</a> <a class="main-nav-link switch-friends-link" href="http://moxfive.xyz/">MOxFIVE</a> </div> </section> <section class="switch-part switch-part4"> <div id="js-aboutme">Man</div> </section> </div> </div> </header> </div> </div> <div class="mid-col"> <nav id="mobile-nav"> <div class="overlay"> <div class="slider-trigger"></div> <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">xiaoyou</a></h1> </div> <div class="intrude-less"> <header id="header" class="inner"> <a href="/" class="profilepic"> <img src="/img/avatar.png" class="animated zoomIn"> </a> <hgroup> <h1 class="header-author"><a href="/" title="回到主页">xiaoyou</a></h1> </hgroup> <nav class="header-menu"> <ul> <li><a href="/">Home</a></li> <li><a href="/archives">Archives</a></li> <li><a href="/tools">Tools</a></li> <li><a href="/about">About</a></li> <div class="clearfix"></div> </ul> </nav> <nav class="header-nav"> <ul class="social"> <a class="fa Email" target="_blank" href="mailto:123@123.com" title="Email"></a> <a class="fa GitHub" target="_blank" href="#" title="GitHub"></a> <a class="fa RSS" target="_blank" href="/atom.xml" title="RSS"></a> </ul> </nav> </header> </div> <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/> </nav> <div class="body-wrap"> <section class="archives-wrap"> <div class="archive-year-wrap"> <a href="/archives/2017" class="archive-year">2017</a> </div> <div class="archives"> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2017/04/10/tomcat-principle/" class="archive-article-date"> <time datetime="2017-04-10T14:44:00.000Z" itemprop="datePublished">04-10</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2017/04/10/tomcat-principle/">Tomcat组成与工作原理</a> </h1> <div class="article-info info-on-archive"> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Tomcat/">Tomcat</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> <article class="archive-article archive-type-post"> <div class="archive-article-inner"> <header class="archive-article-header"> <div class="article-meta"> <a href="/2017/04/10/tomcat-cluster/" class="archive-article-date"> <time datetime="2017-04-10T00:56:00.000Z" itemprop="datePublished">04-10</time> </a> </div> <h1 itemprop="name"> <a class="archive-article-title" href="/2017/04/10/tomcat-cluster/">Tomcat 集群实现源码级别剖析</a> </h1> <div class="article-info info-on-archive"> <div class="article-tag tagcloud"> <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Tomcat/">Tomcat</a></li></ul> </div> </div> <div class="clearfix"></div> </header> </div> </article> </div></section> </div> <footer id="footer"> <div class="outer"> <div id="footer-info"> <div class="footer-left"> <i class="fa fa-copyright"></i> 2016-2017 xiaoyou </div> <div class="footer-right"> <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a> Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题 v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i> </div> </div> <div class="visit"> <span id="busuanzi_container_site_pv" style='display:none'> <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span> </span> </span> <span>| </span> <span id="busuanzi_container_page_pv" style='display:none'> <span id="page-visit" title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span> </span> </span> </div> </div> </footer> </div> <script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script> <script> $(document).ready(function() { var iPad = window.navigator.userAgent.indexOf('iPad'); if (iPad > -1 || $(".left-col").css("display") === "none") { var bgColorList = ["#9db3f4", "#414141", "#e5a859", "#f5dfc6", "#c084a0", "#847e72", "#cd8390", "#996731"]; var bgColor = Math.ceil(Math.random() * (bgColorList.length - 1)); $("body").css({"background-color": bgColorList[bgColor], "background-size": "cover"}); } else { var backgroundnum = 5; var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum)); $("body").css({"background": backgroundimg, "background-attachment": "fixed", "background-size": "cover"}); } }) </script> <div class="scroll" id="scroll"> <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a> <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a> <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a> </div> <script> // Open in New Window var oOpenInNew = { archives: ".archive-article-title", miniArchives: "a.post-list-link", friends: "#js-friends a", socail: ".social a" } for (var x in oOpenInNew) { $(oOpenInNew[x]).attr("target", "_blank"); } </script> <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"> </script> </div> </body> </html>
{ "content_hash": "31e60ff983504cea29259ee14ae6eab9", "timestamp": "", "source": "github", "line_count": 426, "max_line_length": 829, "avg_line_length": 33.83098591549296, "alnum_prop": 0.46523730224812654, "repo_name": "shiyouxu/shiyouxu.github.io", "id": "3c3fa0d7674a68479691786796c99e1969842cb8", "size": "14636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tags/Tomcat/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "65386" }, { "name": "HTML", "bytes": "977617" }, { "name": "JavaScript", "bytes": "57700" } ], "symlink_target": "" }
package org.mazhuang.guanggoo.util; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; /** * 软键盘操作工具类。 * * @author mazhuang * @date 2018/4/30 */ public class SoftInputUtil { private SoftInputUtil() {} /** * Show soft input. * * @param context the context */ public static void showSoftInput(Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } } /** * Hide soft input. * * @param context the context */ public static void hideSoftInput(Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); boolean isOpen = (imm != null && imm.isActive()); if (isOpen) { imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); } } /** * Hide soft input from window. * * @param context the context * @param v the v */ public static void hideSoftInputFromWindow(Context context, View v) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } }
{ "content_hash": "87d54932dca8a79377bed97c7b4ebb89", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 109, "avg_line_length": 27.566037735849058, "alnum_prop": 0.6344969199178645, "repo_name": "mzlogin/guanggoo-android", "id": "19d829daf1506683b0859c48d3dea95199cef58f", "size": "1479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/org/mazhuang/guanggoo/util/SoftInputUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "302367" } ], "symlink_target": "" }
ButtonSwitcher::ButtonSwitcher(HGE *hge, byte key, bool active) { bActive = active; this->key = key; this->hge = hge; } ButtonSwitcher::~ButtonSwitcher() { } bool ButtonSwitcher::isActive() { return this->bActive; } byte ButtonSwitcher::getKey() { return this->key; } void ButtonSwitcher::check() { if (this->hge->Input_GetKeyState(this->key)) { if (!this->bPressed) { this->bPressed = true; this->switchState(); this->pressed(); } } else { if (this->bPressed) { this->bPressed = false; this->released(); } } } void ButtonSwitcher::switchState() { this->bActive = !this->bActive; } void ButtonListeners::addListener(ButtonSwitcher *listener) { this->listeners.insert(this->listeners.begin(), listener); } void ButtonListeners::check() { for (int i = 0; i < (int) this->listeners.size(); i++) { this->listeners[i]->check(); } } bool ButtonListeners::isActive(int key) { for (int i = 0; i < (int) this->listeners.size(); i++) { if (this->listeners[i]->getKey() == key) { return this->listeners[i]->isActive(); } } return false; } void ButtonListeners::destruct() { for (std::vector<ButtonSwitcher*>::iterator it = this->listeners.begin(); it != this->listeners.end(); it++) { delete (*it); (*it) = nullptr; } }
{ "content_hash": "1a9c61e1239c7450512f7b155f1df3a8", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 109, "avg_line_length": 15.670731707317072, "alnum_prop": 0.6350194552529183, "repo_name": "RuWhyNot/stealthgame", "id": "c531dcdacbe11fa80a4eec1de105a8a4f76a7d04", "size": "1312", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/HgeInterface/Input/KeyListeners.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "55738" }, { "name": "C++", "bytes": "587954" }, { "name": "Lua", "bytes": "542" }, { "name": "Objective-C", "bytes": "349" } ], "symlink_target": "" }
package com.amazonaws.services.devicefarm.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.devicefarm.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ListInstanceProfilesRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ListInstanceProfilesRequestMarshaller { private static final MarshallingInfo<Integer> MAXRESULTS_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("maxResults").build(); private static final MarshallingInfo<String> NEXTTOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("nextToken").build(); private static final ListInstanceProfilesRequestMarshaller instance = new ListInstanceProfilesRequestMarshaller(); public static ListInstanceProfilesRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(ListInstanceProfilesRequest listInstanceProfilesRequest, ProtocolMarshaller protocolMarshaller) { if (listInstanceProfilesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listInstanceProfilesRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listInstanceProfilesRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
{ "content_hash": "f4c6426e15a787ac43f6d547c0b5c8ce", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 159, "avg_line_length": 38.638297872340424, "alnum_prop": 0.7544052863436124, "repo_name": "aws/aws-sdk-java", "id": "e8230dc3697b3897fef635c69cf09516d0b4eb59", "size": "2396", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-devicefarm/src/main/java/com/amazonaws/services/devicefarm/model/transform/ListInstanceProfilesRequestMarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package site import ( "regexp" "github.com/robpike/filter" ) /* Fuzzy select to domains by name */ func SelectDomains(name string) []string { return filter.Choose(DOMAINS, func(d string) bool { return regexp.MustCompile(d).MatchString(name) }).([]string) }
{ "content_hash": "146d30c171e5eea6597958f86330a5d6", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 52, "avg_line_length": 16.6875, "alnum_prop": 0.7078651685393258, "repo_name": "ikeikeikeike/gocuration", "id": "d24a5d63c91e3610143bc8dfccd21c7549a51f1c", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/site/utils.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "304291" }, { "name": "Shell", "bytes": "368" } ], "symlink_target": "" }
class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() result = [] do_subsets_with_dup(nums, 0, [], result) return result def do_subsets_with_dup(nums, i, bk, result): if i == len(nums): result.append(bk[:]) return nbk = bk[:] nbk.append(nums[i]) # If current element is same as last element in bookkeeping, then # the current element must be included; otherwise we duplicate one entry. if len(bk) > 0 and bk[-1] == nums[i]: do_subsets_with_dup(nums, i + 1, nbk, result) else: do_subsets_with_dup(nums, i + 1, bk, result) do_subsets_with_dup(nums, i + 1, nbk, result)
{ "content_hash": "a56fdb7e01a45f05a6e595a6e1e6623c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 77, "avg_line_length": 29.76923076923077, "alnum_prop": 0.562015503875969, "repo_name": "kingsamchen/Eureka", "id": "9264bc598b812cadfff9d02c2b22b8314026a7b3", "size": "774", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "crack-data-structures-and-algorithms/leetcode/subsets_II_q90.py", "mode": "33188", "license": "mit", "language": [ { "name": "AIDL", "bytes": "320" }, { "name": "Assembly", "bytes": "1523" }, { "name": "C", "bytes": "115900" }, { "name": "C#", "bytes": "21241" }, { "name": "C++", "bytes": "1125565" }, { "name": "CMake", "bytes": "645800" }, { "name": "Dockerfile", "bytes": "717" }, { "name": "Go", "bytes": "111089" }, { "name": "HTML", "bytes": "3869" }, { "name": "Java", "bytes": "101720" }, { "name": "Makefile", "bytes": "110" }, { "name": "PowerShell", "bytes": "9136" }, { "name": "Python", "bytes": "210011" }, { "name": "Shell", "bytes": "9338" } ], "symlink_target": "" }
using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { var random = new Random(); Parallel.For(0, 10, (i) => { Task.Delay(random.Next(2000)).Wait(); Console.Write(i); }); } }
{ "content_hash": "e83e0d51d96425af5f7a62ad775dd2d6", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 49, "avg_line_length": 18.933333333333334, "alnum_prop": 0.5105633802816901, "repo_name": "autumn009/TanoCSharpSamples", "id": "1039601d5ad3449881cfb9de30553025d0e98779", "size": "286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Chap25/C25Q5/C25Q5/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1318330" } ], "symlink_target": "" }
<<<<<<< HEAD <<<<<<< HEAD import sys import unittest import tkinter from tkinter import ttk from test.support import requires, run_unittest, swap_attr from tkinter.test.support import AbstractTkTest, destroy_default_root requires('gui') class LabeledScaleTest(AbstractTkTest, unittest.TestCase): def tearDown(self): self.root.update_idletasks() super().tearDown() def test_widget_destroy(self): # automatically created variable x = ttk.LabeledScale(self.root) var = x._variable._name x.destroy() self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var) # manually created variable myvar = tkinter.DoubleVar(self.root) name = myvar._name x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() if self.wantobjects: self.assertEqual(x.tk.globalgetvar(name), myvar.get()) else: self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) del myvar self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name) # checking that the tracing callback is properly removed myvar = tkinter.IntVar(self.root) # LabeledScale will start tracing myvar x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() # Unless the tracing callback was removed, creating a new # LabeledScale with the same var will cause an error now. This # happens because the variable will be set to (possibly) a new # value which causes the tracing callback to be called and then # it tries calling instance attributes not yet defined. ttk.LabeledScale(self.root, variable=myvar) if hasattr(sys, 'last_type'): self.assertNotEqual(sys.last_type, tkinter.TclError) def test_initialization_no_master(self): # no master passing with swap_attr(tkinter, '_default_root', None), \ swap_attr(tkinter, '_support_default_root', True): try: x = ttk.LabeledScale() self.assertIsNotNone(tkinter._default_root) self.assertEqual(x.master, tkinter._default_root) self.assertEqual(x.tk, tkinter._default_root.tk) x.destroy() finally: destroy_default_root() def test_initialization(self): # master passing master = tkinter.Frame(self.root) x = ttk.LabeledScale(master) self.assertEqual(x.master, master) x.destroy() # variable initialization/passing passed_expected = (('0', 0), (0, 0), (10, 10), (-1, -1), (sys.maxsize + 1, sys.maxsize + 1)) if self.wantobjects: passed_expected += ((2.5, 2),) for pair in passed_expected: x = ttk.LabeledScale(self.root, from_=pair[0]) self.assertEqual(x.value, pair[1]) x.destroy() x = ttk.LabeledScale(self.root, from_='2.5') self.assertRaises(ValueError, x._variable.get) x.destroy() x = ttk.LabeledScale(self.root, from_=None) self.assertRaises(ValueError, x._variable.get) x.destroy() # variable should have its default value set to the from_ value myvar = tkinter.DoubleVar(self.root, value=20) x = ttk.LabeledScale(self.root, variable=myvar) self.assertEqual(x.value, 0) x.destroy() # check that it is really using a DoubleVar x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5) self.assertEqual(x.value, 0.5) self.assertEqual(x._variable._name, myvar._name) x.destroy() # widget positionment def check_positions(scale, scale_pos, label, label_pos): self.assertEqual(scale.pack_info()['side'], scale_pos) self.assertEqual(label.place_info()['anchor'], label_pos) x = ttk.LabeledScale(self.root, compound='top') check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() x = ttk.LabeledScale(self.root, compound='bottom') check_positions(x.scale, 'top', x.label, 's') x.destroy() # invert default positions x = ttk.LabeledScale(self.root, compound='unknown') check_positions(x.scale, 'top', x.label, 's') x.destroy() x = ttk.LabeledScale(self.root) # take default positions check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() # extra, and invalid, kwargs self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b') def test_horizontal_range(self): lscale = ttk.LabeledScale(self.root, from_=0, to=10) lscale.pack() lscale.wait_visibility() lscale.update() linfo_1 = lscale.label.place_info() prev_xcoord = lscale.scale.coords()[0] self.assertEqual(prev_xcoord, int(linfo_1['x'])) # change range to: from -5 to 5. This should change the x coord of # the scale widget, since 0 is at the middle of the new # range. lscale.scale.configure(from_=-5, to=5) # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome lscale.update() curr_xcoord = lscale.scale.coords()[0] self.assertNotEqual(prev_xcoord, curr_xcoord) # the label widget should have been repositioned too linfo_2 = lscale.label.place_info() self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0') self.assertEqual(curr_xcoord, int(linfo_2['x'])) # change the range back lscale.scale.configure(from_=0, to=10) self.assertNotEqual(prev_xcoord, curr_xcoord) self.assertEqual(prev_xcoord, int(linfo_1['x'])) lscale.destroy() def test_variable_change(self): x = ttk.LabeledScale(self.root) x.pack() x.wait_visibility() x.update() curr_xcoord = x.scale.coords()[0] newval = x.value + 1 x.value = newval # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome x.update() self.assertEqual(x.label['text'], newval if self.wantobjects else str(newval)) self.assertGreater(x.scale.coords()[0], curr_xcoord) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # value outside range if self.wantobjects: conv = lambda x: x else: conv = int x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen x.update() self.assertEqual(conv(x.label['text']), newval) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) x.destroy() def test_resize(self): x = ttk.LabeledScale(self.root) x.pack(expand=True, fill='both') x.wait_visibility() x.update() width, height = x.master.winfo_width(), x.master.winfo_height() width_new, height_new = width * 2, height * 2 x.value = 3 x.update() x.master.wm_geometry("%dx%d" % (width_new, height_new)) self.assertEqual(int(x.label.place_info()['x']), x.scale.coords()[0]) # Reset geometry x.master.wm_geometry("%dx%d" % (width, height)) x.destroy() class OptionMenuTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.textvar = tkinter.StringVar(self.root) def tearDown(self): del self.textvar super().tearDown() def test_widget_destroy(self): var = tkinter.StringVar(self.root) optmenu = ttk.OptionMenu(self.root, var) name = var._name optmenu.update_idletasks() optmenu.destroy() self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) del var self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) def test_initialization(self): self.assertRaises(tkinter.TclError, ttk.OptionMenu, self.root, self.textvar, invalid='thing') optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b') self.assertEqual(optmenu._variable.get(), 'b') self.assertTrue(optmenu['menu']) self.assertTrue(optmenu['textvariable']) optmenu.destroy() def test_menu(self): items = ('a', 'b', 'c') default = 'a' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) found_default = False for i in range(len(items)): value = optmenu['menu'].entrycget(i, 'value') self.assertEqual(value, items[i]) if value == default: found_default = True self.assertTrue(found_default) optmenu.destroy() # default shouldn't be in menu if it is not part of values default = 'd' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) curr = None i = 0 while True: last, curr = curr, optmenu['menu'].entryconfigure(i, 'value') if last == curr: # no more menu entries break self.assertNotEqual(curr, default) i += 1 self.assertEqual(i, len(items)) # check that variable is updated correctly optmenu.pack() optmenu.wait_visibility() optmenu['menu'].invoke(0) self.assertEqual(optmenu._variable.get(), items[0]) # changing to an invalid index shouldn't change the variable self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1) self.assertEqual(optmenu._variable.get(), items[0]) optmenu.destroy() # specifying a callback success = [] def cb_test(item): self.assertEqual(item, items[1]) success.append(True) optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test, *items) optmenu['menu'].invoke(1) if not success: self.fail("Menu callback not invoked") optmenu.destroy() tests_gui = (LabeledScaleTest, OptionMenuTest) if __name__ == "__main__": run_unittest(*tests_gui) ======= import sys import unittest import tkinter from tkinter import ttk from test.support import requires, run_unittest, swap_attr from tkinter.test.support import AbstractTkTest, destroy_default_root requires('gui') class LabeledScaleTest(AbstractTkTest, unittest.TestCase): def tearDown(self): self.root.update_idletasks() super().tearDown() def test_widget_destroy(self): # automatically created variable x = ttk.LabeledScale(self.root) var = x._variable._name x.destroy() self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var) # manually created variable myvar = tkinter.DoubleVar(self.root) name = myvar._name x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() if self.wantobjects: self.assertEqual(x.tk.globalgetvar(name), myvar.get()) else: self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) del myvar self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name) # checking that the tracing callback is properly removed myvar = tkinter.IntVar(self.root) # LabeledScale will start tracing myvar x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() # Unless the tracing callback was removed, creating a new # LabeledScale with the same var will cause an error now. This # happens because the variable will be set to (possibly) a new # value which causes the tracing callback to be called and then # it tries calling instance attributes not yet defined. ttk.LabeledScale(self.root, variable=myvar) if hasattr(sys, 'last_type'): self.assertNotEqual(sys.last_type, tkinter.TclError) def test_initialization_no_master(self): # no master passing with swap_attr(tkinter, '_default_root', None), \ swap_attr(tkinter, '_support_default_root', True): try: x = ttk.LabeledScale() self.assertIsNotNone(tkinter._default_root) self.assertEqual(x.master, tkinter._default_root) self.assertEqual(x.tk, tkinter._default_root.tk) x.destroy() finally: destroy_default_root() def test_initialization(self): # master passing master = tkinter.Frame(self.root) x = ttk.LabeledScale(master) self.assertEqual(x.master, master) x.destroy() # variable initialization/passing passed_expected = (('0', 0), (0, 0), (10, 10), (-1, -1), (sys.maxsize + 1, sys.maxsize + 1)) if self.wantobjects: passed_expected += ((2.5, 2),) for pair in passed_expected: x = ttk.LabeledScale(self.root, from_=pair[0]) self.assertEqual(x.value, pair[1]) x.destroy() x = ttk.LabeledScale(self.root, from_='2.5') self.assertRaises(ValueError, x._variable.get) x.destroy() x = ttk.LabeledScale(self.root, from_=None) self.assertRaises(ValueError, x._variable.get) x.destroy() # variable should have its default value set to the from_ value myvar = tkinter.DoubleVar(self.root, value=20) x = ttk.LabeledScale(self.root, variable=myvar) self.assertEqual(x.value, 0) x.destroy() # check that it is really using a DoubleVar x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5) self.assertEqual(x.value, 0.5) self.assertEqual(x._variable._name, myvar._name) x.destroy() # widget positionment def check_positions(scale, scale_pos, label, label_pos): self.assertEqual(scale.pack_info()['side'], scale_pos) self.assertEqual(label.place_info()['anchor'], label_pos) x = ttk.LabeledScale(self.root, compound='top') check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() x = ttk.LabeledScale(self.root, compound='bottom') check_positions(x.scale, 'top', x.label, 's') x.destroy() # invert default positions x = ttk.LabeledScale(self.root, compound='unknown') check_positions(x.scale, 'top', x.label, 's') x.destroy() x = ttk.LabeledScale(self.root) # take default positions check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() # extra, and invalid, kwargs self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b') def test_horizontal_range(self): lscale = ttk.LabeledScale(self.root, from_=0, to=10) lscale.pack() lscale.wait_visibility() lscale.update() linfo_1 = lscale.label.place_info() prev_xcoord = lscale.scale.coords()[0] self.assertEqual(prev_xcoord, int(linfo_1['x'])) # change range to: from -5 to 5. This should change the x coord of # the scale widget, since 0 is at the middle of the new # range. lscale.scale.configure(from_=-5, to=5) # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome lscale.update() curr_xcoord = lscale.scale.coords()[0] self.assertNotEqual(prev_xcoord, curr_xcoord) # the label widget should have been repositioned too linfo_2 = lscale.label.place_info() self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0') self.assertEqual(curr_xcoord, int(linfo_2['x'])) # change the range back lscale.scale.configure(from_=0, to=10) self.assertNotEqual(prev_xcoord, curr_xcoord) self.assertEqual(prev_xcoord, int(linfo_1['x'])) lscale.destroy() def test_variable_change(self): x = ttk.LabeledScale(self.root) x.pack() x.wait_visibility() x.update() curr_xcoord = x.scale.coords()[0] newval = x.value + 1 x.value = newval # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome x.update() self.assertEqual(x.label['text'], newval if self.wantobjects else str(newval)) self.assertGreater(x.scale.coords()[0], curr_xcoord) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # value outside range if self.wantobjects: conv = lambda x: x else: conv = int x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen x.update() self.assertEqual(conv(x.label['text']), newval) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) x.destroy() def test_resize(self): x = ttk.LabeledScale(self.root) x.pack(expand=True, fill='both') x.wait_visibility() x.update() width, height = x.master.winfo_width(), x.master.winfo_height() width_new, height_new = width * 2, height * 2 x.value = 3 x.update() x.master.wm_geometry("%dx%d" % (width_new, height_new)) self.assertEqual(int(x.label.place_info()['x']), x.scale.coords()[0]) # Reset geometry x.master.wm_geometry("%dx%d" % (width, height)) x.destroy() class OptionMenuTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.textvar = tkinter.StringVar(self.root) def tearDown(self): del self.textvar super().tearDown() def test_widget_destroy(self): var = tkinter.StringVar(self.root) optmenu = ttk.OptionMenu(self.root, var) name = var._name optmenu.update_idletasks() optmenu.destroy() self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) del var self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) def test_initialization(self): self.assertRaises(tkinter.TclError, ttk.OptionMenu, self.root, self.textvar, invalid='thing') optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b') self.assertEqual(optmenu._variable.get(), 'b') self.assertTrue(optmenu['menu']) self.assertTrue(optmenu['textvariable']) optmenu.destroy() def test_menu(self): items = ('a', 'b', 'c') default = 'a' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) found_default = False for i in range(len(items)): value = optmenu['menu'].entrycget(i, 'value') self.assertEqual(value, items[i]) if value == default: found_default = True self.assertTrue(found_default) optmenu.destroy() # default shouldn't be in menu if it is not part of values default = 'd' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) curr = None i = 0 while True: last, curr = curr, optmenu['menu'].entryconfigure(i, 'value') if last == curr: # no more menu entries break self.assertNotEqual(curr, default) i += 1 self.assertEqual(i, len(items)) # check that variable is updated correctly optmenu.pack() optmenu.wait_visibility() optmenu['menu'].invoke(0) self.assertEqual(optmenu._variable.get(), items[0]) # changing to an invalid index shouldn't change the variable self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1) self.assertEqual(optmenu._variable.get(), items[0]) optmenu.destroy() # specifying a callback success = [] def cb_test(item): self.assertEqual(item, items[1]) success.append(True) optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test, *items) optmenu['menu'].invoke(1) if not success: self.fail("Menu callback not invoked") optmenu.destroy() tests_gui = (LabeledScaleTest, OptionMenuTest) if __name__ == "__main__": run_unittest(*tests_gui) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= import sys import unittest import tkinter from tkinter import ttk from test.support import requires, run_unittest, swap_attr from tkinter.test.support import AbstractTkTest, destroy_default_root requires('gui') class LabeledScaleTest(AbstractTkTest, unittest.TestCase): def tearDown(self): self.root.update_idletasks() super().tearDown() def test_widget_destroy(self): # automatically created variable x = ttk.LabeledScale(self.root) var = x._variable._name x.destroy() self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var) # manually created variable myvar = tkinter.DoubleVar(self.root) name = myvar._name x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() if self.wantobjects: self.assertEqual(x.tk.globalgetvar(name), myvar.get()) else: self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) del myvar self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name) # checking that the tracing callback is properly removed myvar = tkinter.IntVar(self.root) # LabeledScale will start tracing myvar x = ttk.LabeledScale(self.root, variable=myvar) x.destroy() # Unless the tracing callback was removed, creating a new # LabeledScale with the same var will cause an error now. This # happens because the variable will be set to (possibly) a new # value which causes the tracing callback to be called and then # it tries calling instance attributes not yet defined. ttk.LabeledScale(self.root, variable=myvar) if hasattr(sys, 'last_type'): self.assertNotEqual(sys.last_type, tkinter.TclError) def test_initialization_no_master(self): # no master passing with swap_attr(tkinter, '_default_root', None), \ swap_attr(tkinter, '_support_default_root', True): try: x = ttk.LabeledScale() self.assertIsNotNone(tkinter._default_root) self.assertEqual(x.master, tkinter._default_root) self.assertEqual(x.tk, tkinter._default_root.tk) x.destroy() finally: destroy_default_root() def test_initialization(self): # master passing master = tkinter.Frame(self.root) x = ttk.LabeledScale(master) self.assertEqual(x.master, master) x.destroy() # variable initialization/passing passed_expected = (('0', 0), (0, 0), (10, 10), (-1, -1), (sys.maxsize + 1, sys.maxsize + 1)) if self.wantobjects: passed_expected += ((2.5, 2),) for pair in passed_expected: x = ttk.LabeledScale(self.root, from_=pair[0]) self.assertEqual(x.value, pair[1]) x.destroy() x = ttk.LabeledScale(self.root, from_='2.5') self.assertRaises(ValueError, x._variable.get) x.destroy() x = ttk.LabeledScale(self.root, from_=None) self.assertRaises(ValueError, x._variable.get) x.destroy() # variable should have its default value set to the from_ value myvar = tkinter.DoubleVar(self.root, value=20) x = ttk.LabeledScale(self.root, variable=myvar) self.assertEqual(x.value, 0) x.destroy() # check that it is really using a DoubleVar x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5) self.assertEqual(x.value, 0.5) self.assertEqual(x._variable._name, myvar._name) x.destroy() # widget positionment def check_positions(scale, scale_pos, label, label_pos): self.assertEqual(scale.pack_info()['side'], scale_pos) self.assertEqual(label.place_info()['anchor'], label_pos) x = ttk.LabeledScale(self.root, compound='top') check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() x = ttk.LabeledScale(self.root, compound='bottom') check_positions(x.scale, 'top', x.label, 's') x.destroy() # invert default positions x = ttk.LabeledScale(self.root, compound='unknown') check_positions(x.scale, 'top', x.label, 's') x.destroy() x = ttk.LabeledScale(self.root) # take default positions check_positions(x.scale, 'bottom', x.label, 'n') x.destroy() # extra, and invalid, kwargs self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b') def test_horizontal_range(self): lscale = ttk.LabeledScale(self.root, from_=0, to=10) lscale.pack() lscale.wait_visibility() lscale.update() linfo_1 = lscale.label.place_info() prev_xcoord = lscale.scale.coords()[0] self.assertEqual(prev_xcoord, int(linfo_1['x'])) # change range to: from -5 to 5. This should change the x coord of # the scale widget, since 0 is at the middle of the new # range. lscale.scale.configure(from_=-5, to=5) # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome lscale.update() curr_xcoord = lscale.scale.coords()[0] self.assertNotEqual(prev_xcoord, curr_xcoord) # the label widget should have been repositioned too linfo_2 = lscale.label.place_info() self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0') self.assertEqual(curr_xcoord, int(linfo_2['x'])) # change the range back lscale.scale.configure(from_=0, to=10) self.assertNotEqual(prev_xcoord, curr_xcoord) self.assertEqual(prev_xcoord, int(linfo_1['x'])) lscale.destroy() def test_variable_change(self): x = ttk.LabeledScale(self.root) x.pack() x.wait_visibility() x.update() curr_xcoord = x.scale.coords()[0] newval = x.value + 1 x.value = newval # The following update is needed since the test doesn't use mainloop, # at the same time this shouldn't affect test outcome x.update() self.assertEqual(x.label['text'], newval if self.wantobjects else str(newval)) self.assertGreater(x.scale.coords()[0], curr_xcoord) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) # value outside range if self.wantobjects: conv = lambda x: x else: conv = int x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen x.update() self.assertEqual(conv(x.label['text']), newval) self.assertEqual(x.scale.coords()[0], int(x.label.place_info()['x'])) x.destroy() def test_resize(self): x = ttk.LabeledScale(self.root) x.pack(expand=True, fill='both') x.wait_visibility() x.update() width, height = x.master.winfo_width(), x.master.winfo_height() width_new, height_new = width * 2, height * 2 x.value = 3 x.update() x.master.wm_geometry("%dx%d" % (width_new, height_new)) self.assertEqual(int(x.label.place_info()['x']), x.scale.coords()[0]) # Reset geometry x.master.wm_geometry("%dx%d" % (width, height)) x.destroy() class OptionMenuTest(AbstractTkTest, unittest.TestCase): def setUp(self): super().setUp() self.textvar = tkinter.StringVar(self.root) def tearDown(self): del self.textvar super().tearDown() def test_widget_destroy(self): var = tkinter.StringVar(self.root) optmenu = ttk.OptionMenu(self.root, var) name = var._name optmenu.update_idletasks() optmenu.destroy() self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) del var self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) def test_initialization(self): self.assertRaises(tkinter.TclError, ttk.OptionMenu, self.root, self.textvar, invalid='thing') optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b') self.assertEqual(optmenu._variable.get(), 'b') self.assertTrue(optmenu['menu']) self.assertTrue(optmenu['textvariable']) optmenu.destroy() def test_menu(self): items = ('a', 'b', 'c') default = 'a' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) found_default = False for i in range(len(items)): value = optmenu['menu'].entrycget(i, 'value') self.assertEqual(value, items[i]) if value == default: found_default = True self.assertTrue(found_default) optmenu.destroy() # default shouldn't be in menu if it is not part of values default = 'd' optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) curr = None i = 0 while True: last, curr = curr, optmenu['menu'].entryconfigure(i, 'value') if last == curr: # no more menu entries break self.assertNotEqual(curr, default) i += 1 self.assertEqual(i, len(items)) # check that variable is updated correctly optmenu.pack() optmenu.wait_visibility() optmenu['menu'].invoke(0) self.assertEqual(optmenu._variable.get(), items[0]) # changing to an invalid index shouldn't change the variable self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1) self.assertEqual(optmenu._variable.get(), items[0]) optmenu.destroy() # specifying a callback success = [] def cb_test(item): self.assertEqual(item, items[1]) success.append(True) optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test, *items) optmenu['menu'].invoke(1) if not success: self.fail("Menu callback not invoked") optmenu.destroy() tests_gui = (LabeledScaleTest, OptionMenuTest) if __name__ == "__main__": run_unittest(*tests_gui) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
{ "content_hash": "0a1c98146f8a7cb6916656a190b0b746", "timestamp": "", "source": "github", "line_count": 879, "max_line_length": 79, "avg_line_length": 35.44254835039818, "alnum_prop": 0.5959106374783334, "repo_name": "ArcherSys/ArcherSys", "id": "598add8849d01262e1c0c3b2e103b8e6d4d2125f", "size": "31154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lib/tkinter/test/test_ttk/test_extensions.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
load ../lib/detik # The client function. DETIK_CLIENT_NAME="kubectl" ######################################### # Counting objects ######################################### # Basic examples verify "there are 1 service named 'nginx'" verify "there are 4 pods named 'nginx'" # The same thing (it is case insensitive) verify "There are 4 pods naMed 'nginx'" # Use short names for resources ('po' instead of 'pods') # See https://kubernetes.io/docs/reference/kubectl/overview/#resource-types verify "there are 4 po named 'nginx'" # Use a regular expression for the name verify "there are 4 po named 'nginx.*'" ######################################### # Verifying properties ######################################### # Basic example verify "'status' is 'running' for pods named 'nginx'" # The same thing (it is case insensitive) verify "'status' is 'RUNNING' for pods naMed 'nginx'" # Use short names for resources ('po' instead of 'pods') # See https://kubernetes.io/docs/reference/kubectl/overview/#resource-types verify "'status' is 'running' for po named 'nginx'" # Use a regular expression for the name verify "'status' is 'running' for pods named 'nginx.*'" # You can also use column names # Use kubectl get <resource> -o custom-columns=ALL:* to find column names. verify "'.status.phase' is 'running' for pods named 'nginx'" verify "'.spec.ports[*].targetPort' is '8484' for services named 'nginx'" ######################################### # Verifying properties (with retries) ######################################### # Basic example try "at most 5 times every 5s to get pods named 'nginx' and verify that 'status' is 'running'" # The same thing (it is case insensitive) try "at most 5 times every 15s to GET pods named 'nginx' and verify that 'status' is 'RUNNING'" # Use short names for resources ('po' instead of 'pods') # See https://kubernetes.io/docs/reference/kubectl/overview/#resource-types try "at most 5 times every 5s to get po named 'nginx' and verify that 'status' is 'running'" # Use a regular expression for the name try "at most 2 times every 30s to get po named '^ng.*nx' and verify that 'status' is 'running'" # You can also use column names # Use kubectl get <resource> -o custom-columns=ALL:* to find column names. try "at most 2 times every 30s to get po named 'nginx' and verify that '.status.phase' is 'running'" try "at most 2 times every 30s to get svc named 'nginx' and verify that '.spec.ports[*].targetPort' is '8484'" ######################################### # Formatting ######################################### # Splitting a request over several lines try "at most 2 times every 30s "\ "to get svc named 'nginx' and "\ "verify that '.spec.ports[*].targetPort' is '8484'" # Using quotes differently # (make sure to surround single quotes by double ones) try at most 2 times every 30s \ to get svc named "'nginx'" and \ verify that "'.spec.ports[*].targetPort'" is "'8484'"
{ "content_hash": "a226706e6c7ca53c9754e4e20844f43e", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 110, "avg_line_length": 34.33720930232558, "alnum_prop": 0.6359634270233661, "repo_name": "n13l/openaaa", "id": "4fa9b9d33f8c28eeb88ca77d83073c5b14eb66d8", "size": "3098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/bats-detik/examples/bats/test_kubectl_and_oc.sh", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5151250" }, { "name": "C++", "bytes": "290713" }, { "name": "Java", "bytes": "1037" }, { "name": "Lex", "bytes": "6704" }, { "name": "Makefile", "bytes": "129008" }, { "name": "Perl", "bytes": "449131" }, { "name": "Python", "bytes": "162762" }, { "name": "Shell", "bytes": "86743" }, { "name": "Vim script", "bytes": "539183" }, { "name": "Yacc", "bytes": "15415" } ], "symlink_target": "" }
from main import app, db from flask.ext.security import Security, SQLAlchemyUserDatastore, \ UserMixin, RoleMixin, login_required, roles_accepted from flask_security.utils import encrypt_password from flask_login import current_user # Define models class RoleUsers(db.Model): # save table to security database __bind_key__ = 'security' __tablename__ = 'roles_users' id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('users.id')) role_id = db.Column(db.Integer(), db.ForeignKey('roles.id')) class Role(db.Model, RoleMixin): __bind_key__ = 'security' __tablename__ = 'roles' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): __bind_key__ = 'security' __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary='roles_users', backref=db.backref('users',lazy='dynamic')) # used by flask-blogging to get name to display on post def get_name(self): return self.email # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) # Create any database tables that don't exist yet. db.create_all() def configure_security(): # Create the Roles "admin" and "end-user" -- unless they already exist user_datastore.find_or_create_role(name='admin', description='Administrator') user_datastore.find_or_create_role(name='end-user', description='End user') # Create two Users for testing purposes -- unless they already exists. # In each case, use Flask-Security utility function to encrypt the password. pw = encrypt_password('password') # pw = 'password' if not user_datastore.get_user('someone@example.com'): user_datastore.create_user(email='someone@example.com', password=pw) if not user_datastore.get_user('admin@example.com'): user_datastore.create_user(email='admin@example.com', password=pw) # Give one User has the "end-user" role, while the other has the "admin" role. #(This will have no effect if the # Users already have these Roles.) Again, commit any database changes. user_datastore.add_role_to_user('someone@example.com', 'end-user') user_datastore.add_role_to_user('admin@example.com', 'admin') db.session.commit()
{ "content_hash": "7c797ed225fe5c7e26f2d8a25845bc66", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 83, "avg_line_length": 37.563380281690144, "alnum_prop": 0.6842894638170228, "repo_name": "slippers/blogging_security", "id": "165f3888066b2745ed80146bb5de7d5b518543ab", "size": "2667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main/security.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1388" }, { "name": "Python", "bytes": "8802" } ], "symlink_target": "" }
var kodetokenizer = require('../..'), fs = require('fs'); var Types = kodetokenizer.Types; var input = fs.readFileSync(process.argv[2]).toString(); var tokens = kodetokenizer.getTokens(input); var anagrams = { }; var words = []; var ntokens = tokens.length; for (var k = 0; k < ntokens; k++) { var token = tokens[k]; if (token.type != Types.Digits && token.type != Types.Word) continue; var word = token.value.toLowerCase(); var anagram = toanagram(word); if (anagrams[anagram] && anagrams[anagram].indexOf(word) >= 0) continue; var list = anagrams[anagram]; if (!list) { anagrams[anagram] = list = []; words.push(anagram); } list.push(word); } words.forEach(function (k) { var anagram = anagrams[k]; if (anagram.length < 2) return; console.log(anagram.join(' ')); }); function toanagram(text) { var letters = []; for (var n in text) letters.push(text[n]); letters.sort(); return letters.join(''); }
{ "content_hash": "80dd6dec90a51af822e58473cb09aa60", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 66, "avg_line_length": 19.839285714285715, "alnum_prop": 0.5472547254725473, "repo_name": "ajlopez/KodeTokenizer", "id": "455d201158376866ac7428496059170137cbafba", "size": "1112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/anagrams/run.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "13551" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- Released for free under a Creative Commons Attribution 3.0 License --> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Atomic_www.cssmoban.com模板之家</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link href="style.css" rel="stylesheet" type="text/css" /> <!-- CuFon: Enables smooth pretty custom font rendering. 100% SEO friendly. To disable, remove this section --> <script type="text/javascript" src="js/cufon-yui.js"></script> <script type="text/javascript" src="js/arial.js"></script> <script type="text/javascript" src="js/cuf_run.js"></script> <!-- CuFon ends --> </head> <body> <div class="main"> <div class="header"> <div class="header_resize"> <div class="logo"> <h1><a href="index.html"><span> web </span> business </a><small>Simple web template</small></h1> </div> <div class="search"> <form id="form" name="form" method="post" action=""> <span> <input name="q" type="text" class="keywords" id="textfield" maxlength="50" value="Search..." /> <input name="b" type="image" src="images/search.gif" class="button" /> </span> </form> </div> <!--/search --> <div class="clr"></div> <div class="menu_nav"> <ul> <li class="active"><a href="index.html">Home</a></li> <li><a href="support.html">Support</a></li> <li><a href="about.html">About Us</a></li> <li><a href="blog.html">Blog</a></li> <li><a href="contact.html">Contact Us</a></li> </ul> </div> <div class="clr"></div> </div> </div> <div class="clr"></div> <div class="content"> <div class="content_resize"> <div class="mainbar"> <div class="article"> <h2><span>Template License</span></h2> <div class="clr"></div> <p>Posted on 18. Sep, 2015 by Sara in Filed under templates, internet, with<a href="#"> Comments 18</a></p> <img src="images/img_1.jpg" width="613" height="193" alt="image" /> <div class="clr"></div> <p>This is a free CSS website collect from <a href="http://www.cssmoban.com/" title="模板之家">模板之家</a>. This work is distributed under the Creative Commons Attribution 3.0 License, which means that you are free to use it for any personal or commercial purpose provided you credit me in the form of a link back to www.cssmoban.com.</p> <p>Maecenas dignissim mauris in arcu congue tincidunt. Vestibulum elit nunc, accumsan vitae faucibus vel, scelerisque a quam. Aenean at metus id elit bibendum faucibus. Curabitur ultrices ante nec neque consectetur a aliquet libero lobortis. Ut nibh sem, pellentesque in dictum eu, convallis blandit erat. Cras vehicula tellus nec purus sagittis id scelerisque risus congue. Quisque sed semper massa. Donec id lacus mauris, vitae pretium risus. Fusce sed tempor erat. </p> <p class="links"><a href="#">Read more </a></p> </div> <div class="article"> <h2><span>Aliquam Risus</span> Justo</h2> <div class="clr"></div> <p>Posted on 18. Sep, 2015 by Sara in Filed under templates, internet, with <a href="#">Comments 18</a></p> <img src="images/img_2.jpg" width="613" height="193" alt="image" /> <div class="clr"></div> <p>Pellentesque posuere enim et ipsum dignissim convallis. Proin quis molestie mauris. Nunc eget quam at nulla tempus tincidunt quis a mi. Aliquam ornare turpis non tellus molestie imperdiet. Phasellus sit amet neque vitae purus venenatis hendrerit. Phasellus non mi ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse potenti. Aenean vel varius sapien. Etiam leo quam, sodales vel ullamcorper ut, viverra a risus.</p> <p>Maecenas dignissim mauris in arcu congue tincidunt. Vestibulum elit nunc, accumsan vitae faucibus vel, scelerisque a quam. Aenean at metus id elit bibendum faucibus. Curabitur ultrices ante nec neque consectetur a aliquet libero lobortis. Ut nibh sem, pellentesque in dictum eu, convallis blandit erat. Cras vehicula tellus nec purus sagittis id scelerisque risus congue. Quisque sed semper massa. Donec id lacus mauris, vitae pretium risus. Fusce sed tempor erat. </p> <p class="links"><a href="#">Read more </a></p> </div> <div class="article" style="padding:5px 20px 2px 20px; background:none; border:0;"> <p>Page 1 of 2 <span class="butons"><a href="#">3</a><a href="#">2</a> <a href="#" class="active">1</a></span></p> </div> </div> <div class="sidebar"> <div class="gadget"> <h2>Sidebar Menu</h2> <div class="clr"></div> <ul class="sb_menu"> <li><a href="#">Home</a></li> <li><a href="#">TemplateInfo</a></li> <li><a href="#">Style Demo</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Archives</a></li> <li><a href="#" title="Website Templates">Web Templates</a></li> </ul> </div> <div class="gadget"> <h2><span>Sponsors</span></h2> <div class="clr"></div> <ul class="ex_menu"> <li><a href="#" title="Website Templates">DreamTemplate</a><br /> Over 6,000+ Premium Web Templates</li> <li><a href="#" title="WordPress Themes">TemplateSOLD</a><br /> Premium WordPress &amp; Joomla Themes</li> <li><a href="#" title="Affordable Hosting">ImHosted.com</a><br /> Affordable Web Hosting Provider</li> <li><a href="#" title="Stock Icons">MyVectorStore</a><br /> Royalty Free Stock Icons</li> <li><a href="#" title="Website Builder">Evrsoft</a><br /> Website Builder Software &amp; Tools</li> <li><a href="#" title="CSS Templates">CSS Hub</a><br /> Premium CSS Templates</li> </ul> </div> <div class="gadget"> <h2>Wise Words</h2> <div class="clr"></div> <p> <img src="images/test_1.gif" alt="image" width="20" height="18" /> <em>We can let circumstances rule us, or we can take charge and rule our lives from within </em>.<img src="images/test_2.gif" alt="image" width="20" height="18" /></p> <p style="float:right;"><strong>Earl Nightingale</strong></p> </div> </div> <div class="clr"></div> </div> </div> <div class="fbg"> <div class="fbg_resize"> <div class="col c1"> <h2><span>Image Gallery</span></h2> <a href="#"><img src="images/gallery_1.jpg" width="58" height="58" alt="pix" /></a> <a href="#"><img src="images/gallery_2.jpg" width="58" height="58" alt="pix" /></a> <a href="#"><img src="images/gallery_3.jpg" width="58" height="58" alt="pix" /></a> <a href="#"><img src="images/gallery_4.jpg" width="58" height="58" alt="pix" /></a> <a href="#"><img src="images/gallery_5.jpg" width="58" height="58" alt="pix" /></a> <a href="#"><img src="images/gallery_6.jpg" width="58" height="58" alt="pix" /></a> </div> <div class="col c2"> <h2><span>Lorem Ipsum</span></h2> <p>Lorem ipsum dolor<br /> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum. Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum odio, ac blandit ante orci ut diam.</p> </div> <div class="col c3"> <h2><span>Contact</span></h2> <p>Nullam quam lorem, tristique non vestibulum nec, consectetur in risus. Aliquam a quam vel leo gravida gravida eu porttitor dui. Nulla pharetra, mauris vitae interdum dignissim, justo nunc suscipit ipsum. <a href="#">mail@example.com</a><br /> <a href="#">+1 (123) 444-5677</a></p> </div> <div class="clr"></div> </div> <div class="footer"> <p class="lr">© Copyright <a href="#">MyWebSite</a>.</p> <p class="lf">Collect From <a href="http://www.cssmoban.com/" title="网页模板">网页模板</a></p> <div class="clr"></div> </div> </div> </div> </body> </html>
{ "content_hash": "9abbde8f97a866c8b7fa2478777f7417", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 518, "avg_line_length": 58.479166666666664, "alnum_prop": 0.6052725329533309, "repo_name": "wjwu/blog", "id": "6885988d7f8e1dc89bec5d50ad1f48cc9edc54e7", "size": "8462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/app/template/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9296" }, { "name": "HTML", "bytes": "40281" }, { "name": "JavaScript", "bytes": "155349" } ], "symlink_target": "" }
defaults write com.apple.dock expose-animation-duration -float 0.1 # Automatically rearrange Spaces based on most recent use defaults write com.apple.dock mru-spaces -bool false # When switching to an application, switch to a Space with open windows for the application defaults write NSGlobalDomain AppleSpacesSwitchOnActivate -bool true # Group windows by application in Mission Control # (i.e. use the old Exposé behavior instead) defaults write com.apple.dock expose-group-by-app -bool false # Disaplays have sererate Spaces defaults write com.apple.spaces spans-displays -bool false # Disable the Launchpad gesture (pinch with thumb and three fingers) #defaults write com.apple.dock showLaunchpadGestureEnabled -int 0 # Reset Launchpad find "${HOME}/Library/Application Support/Dock" -name "*-*.db" -maxdepth 1 -delete # Add iOS Simulator to Launchpad # if [ -e "/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app" ]; then # sudo ln -sf "/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app" \ # "/Applications/Simulator.app" # fi # Hot corners # 0 : NOP # 2 : Mission Control # 3 : Show application windows # 4 : Desktop # 5 : Start screen saver # 6 : Disable screen saver # 7 : Dashboard # 10 : Put display to sleep # 11 : Launchpad # 12 : Notification Center # Top left screen corner defaults write com.apple.dock wvous-tl-corner -int 0 defaults write com.apple.dock wvous-tl-modifier -int 0 # Top right screen corner defaults write com.apple.dock wvous-tr-corner -int 0 defaults write com.apple.dock wvous-tr-modifier -int 0 # Bottom left screen corner defaults write com.apple.dock wvous-bl-corner -int 0 defaults write com.apple.dock wvous-bl-modifier -int 0 # Bottom right screen corner defaults write com.apple.dock wvous-br-corner -int 0 defaults write com.apple.dock wvous-br-modifier -int 0
{ "content_hash": "5ba77b529f66a5aeabf7000d280d7775", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 91, "avg_line_length": 37.72, "alnum_prop": 0.7619300106044539, "repo_name": "semenovDL/dotfiles", "id": "ae85eb3d8da2abde899e3484355920817946289d", "size": "2186", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "system/mission_control.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5189" }, { "name": "Shell", "bytes": "98236" } ], "symlink_target": "" }
/*搜索框*/ .mui-search .mui-placeholder .mui-icon {font-size: 20px;color: #a08255;} .mui-search { background: #fff; height: 40px; position: fixed; z-index: 9; top: 0px; width: 100%; } #slider{padding-top: 40px;} .mui-search .search-logo{width: 56.25px;height: 17.5px;position: absolute;left: 50%;top: 12px;margin-left: -32px;} /*banner*/ #slider .mui-slider-indicator { position: absolute; bottom: 8px; width: 100%; text-align: right; background: 0 0; padding-right: 11px; } /*左右滚动*/ #new-arrival .new-arrival-inner{color: #4a4a4a;font-weight: bold;} #new-arrival .new-arrival-span{color: #a08255;} #new-arrival .new-arrival-span2{color: #4a4a4a;font-weight: normal;} #new-arrival{padding-top: 35px;overflow: hidden;padding-bottom: 40px;} #new-arrival .over-silder{width: 1000px;} #new-arrival .swiper-container ,#new-arrival2 .swiper-container {width: 100%;margin: 20px auto;padding-left: 12px;} #new-arrival .swiper-slide,#new-arrival2 .swiper-slide{text-align: center;font-size: 18px;background: #fff;width: 150px; /* Center slide text vertically */ display: -webkit-box;display: -ms-flexbox;display: -webkit-flex; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; -webkit-justify-content: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; -webkit-align-items: center; align-items: center; } .swiper-wrapper-p1{padding-top: 15px;max-height: 60px;display: -webkit-box;-webkit-line-clamp: 2; -webkit-box-orient: vertical;font-size: 12px;line-height: 18px; overflow: hidden;} .swiper-wrapper-p2{color: #e75058;padding-top: 10px;} .new-arrival-a{color: #5d5d5d;font-size: 16px;} /*春节专场*/ #special-performance{background: #fbfbfb;} #slider2{padding-top: 20px;} #new-arrival2{padding:20px 0px;} #special-performance{padding: 0px 15px;padding-top: 40px;padding-bottom: 33px;} /*达人推荐*/ .recommend{background: #fbfbfb;padding: 20px 20px;} .new-arrival-inner{padding-bottom: 6px;} .describe-title{text-align: left;font-size: 15px;padding-top: 10px;color: #4a4a4a;font-weight: bold;} .describe-content{text-align: left;font-size: 13px;color: #777777; display: -webkit-box; -webkit-line-clamp: 2; padding-top: 6px; -webkit-box-orient: vertical; overflow: hidden;line-height: 16px; } .describe-price{text-align: left;color: #e75058;font-size: 17px;float: left;margin-top: 10px;} .shop-cart{border: 1px solid #232220;color: #232220;float: right;padding: 4px 10px;font-size: 14px;} .shop-buy{background: #a08255;color: #fff;float: right;padding: 5px 20px;margin-left: 10px;line-height: 21px;font-size: 14px;} .describe{overflow: hidden;} .describe-price-out{overflow: hidden;padding-top: 8px;} /*猜你喜欢*/ .mui-table-view{margin: 20px 15px;overflow: hidden;} .mui-table-view:before{background-color: #fff;} .swiper-container2,.swiper-container3{position: relative;} .swiper-container2 .swiper-slide img{width: auto; height: auto; max-width: 100%; max-height: 100%; } #pullrefresh{background: #fbfbfb;padding-bottom: 40px;} /*.recommend .new-arrival-inner{padding-top: 20px;padding-bottom: 0px;}*/ .recommend-content{padding-bottom: 15px;padding-top: 15px;background: #fbfbfb;} .load-more{background: #4a4a4a;padding: 8px 10px;width: 100%;margin: 0 auto;font-size: 14px;text-align: center;line-height: 20px;color: #fff;} .swiper-pagination-bullet-active {background:#a08255;} .swiper-pagination-bullet{border-radius: 0px;width: 6px;height: 6px;} .mui-slider-indicator .mui-indicator{border-radius: 0px; box-shadow:0px 0px 0px 0px;} .swiper-pagination-bullet {opacity: 1;} .new-arrival-inner {color: #4a4a4a;font-weight: bold;font-size: 16px;} .new-arrival-span2{color: #4a4a4a;font-weight: normal;} .new-arrival-span{color: #a08255;} .swiper-container-horizontal>.swiper-pagination-bullets .swiper-pagination-bullet{margin: 0 2px;} .describe-title{display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;} .mui-icon-search{font-size: 20px;font-weight: bold;color: #232220;} .search-icon{width: 19px;position: absolute;top: 12px;right: 8px;} #pullrefresh .mui-table-view{margin: 0px;} #pullrefresh{padding: 0px 15px;padding-bottom: 70px;} #new-arrival .mui-text-center img{width: 100%;} #new-arrival2 .mui-text-center img{width: 100%;} .recommend-content .mui-indicator{margin-right: 4px;}
{ "content_hash": "298f744862518b2c1ba85311127c0591", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 142, "avg_line_length": 44.39, "alnum_prop": 0.7141248028835323, "repo_name": "chahualao/shop", "id": "77c20ba159abd199988d7b4b3e4b1e223592beb5", "size": "4477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Public/static/mobile/css/homePage.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "203" }, { "name": "CSS", "bytes": "2534384" }, { "name": "HTML", "bytes": "4926157" }, { "name": "JavaScript", "bytes": "2665687" }, { "name": "Nginx", "bytes": "1177" }, { "name": "PHP", "bytes": "2371755" }, { "name": "Smarty", "bytes": "8297" } ], "symlink_target": "" }
set -e -o pipefail command_exists () { type "$1" &> /dev/null ; } echo "Copying configuration files" cp -rT configuration ~ echo "Copy visual studio code settings" cp code/* ~/.config/Code\ -\ OSS/User if ! command_exists yay; then echo "Install yay" sudo pacman -Sy sudo pacman -Fy # sync packages sudo pacman -S yay fi if ! command_exists emacs; then echo "Install default packages" yay -S google-chrome ack vim tmux curl wget emacs fi if ! command_exists zsh ; then echo "Installing zsh" sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" chsh -s /bin/zsh fi if [ ! -d ~/.fzf ]; then echo "Installing fzf" git clone --depth 1 https://github.com/junegunn/fzf.git ~/.fzf ~/.fzf/install fi if [ ! -d ~/.emacs.d ]; then echo "Installing Spacemacs" git clone https://github.com/syl20bnr/spacemacs ~/.emacs.d fi if [ ! -d ~/.vim ]; then echo "Installing Vundle" git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim fi if ! command_exists docker; then echo "Installing Docker" sudo pacman -S docker docker-compose fi # Install emacs daemon as systemd unit #cp -r ~/devel/dotfiles/.config ~/ #systemctl enable emacs-daemon --user #sudo cp emacs.desktop /usr/share/applications # Install asdf # https://github.com/asdf-vm/asdf # Install rbenv # https://github.com/rbenv/rbenv if ! command_exists rbenv ; then echo "Installing rbenv" yay -S rbenv fi if ! command_exists fuck ; then echo "Installing thefuck" # https://github.com/nvbn/thefuck sudo pacman -S thefuck fi if ! command_exists openfortivpn ; then # https://albertlauncher.github.io/installing/ echo "Installing Albert" mkdir -p ~/.config/albert/ yay -S albert cp albert/albert.conf ~/.config/albert/albert.conf fi if ! command_exists openfortivpn ; then echo "Installing openforti VPN" yay -S openfortivpn fi # Install zoom # https://zoom.us/download?os=linux if ! command_exists openfortivpn ; then echo "Install flatplak" pamac install flatpak libpamac-flatpak-plugin fi if ! command_exists code; then echo "Install VSCode" pamac install code fi # if ! command_exists spotify; then # echo "Install spotify" # flatpak install spotify # fi
{ "content_hash": "438ed9d2e18276b786a47f105db6d21b", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 86, "avg_line_length": 21.27358490566038, "alnum_prop": 0.7055432372505543, "repo_name": "digaoddc/dotfiles", "id": "375c2ae53c2a4b68b1a80ffe54c044a68892866b", "size": "2267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "install.sh", "mode": "33261", "license": "mit", "language": [ { "name": "Emacs Lisp", "bytes": "29476" }, { "name": "Ruby", "bytes": "340" }, { "name": "Shell", "bytes": "6748" }, { "name": "Vim Script", "bytes": "3132" }, { "name": "YASnippet", "bytes": "732" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BuildingManager.Loggers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("BuildingManager.Loggers")] [assembly: AssemblyCopyright("Copyright © Microsoft 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d9d69701-a51b-49cb-9eaf-206f835a83ee")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "5c0da612a6639611b3ff9e5cff28739e", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.77777777777778, "alnum_prop": 0.7534916201117319, "repo_name": "stoyanov7/TelerikAcademy", "id": "bdb218efe673d5d062294f5c6eb6a9156dd8129b", "size": "1435", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProgrammingWithC#/07.DesignPatterns/03.DependencyInjectionPatterns/BuildingManager/BuildingManager.Loggers/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "106" }, { "name": "C#", "bytes": "1882051" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5636" }, { "name": "JavaScript", "bytes": "13878" }, { "name": "XSLT", "bytes": "781" } ], "symlink_target": "" }
drop index ACT_IDX_HI_PRO_INST_END; drop index ACT_IDX_HI_PRO_I_BUSKEY; drop index ACT_IDX_HI_ACT_INST_START; drop index ACT_IDX_HI_ACT_INST_END; drop index ACT_IDX_HI_DETAIL_PROC_INST; drop index ACT_IDX_HI_DETAIL_ACT_INST; drop index ACT_IDX_HI_DETAIL_TIME; drop index ACT_IDX_HI_DETAIL_NAME; drop index ACT_IDX_HI_DETAIL_TASK_ID; drop index ACT_IDX_HI_PROCVAR_PROC_INST; drop index ACT_IDX_HI_PROCVAR_NAME_TYPE; drop index ACT_IDX_HI_ACT_INST_PROCINST; drop table ACT_HI_PROCINST; drop table ACT_HI_ACTINST; drop table ACT_HI_VARINST; drop table ACT_HI_TASKINST; drop table ACT_HI_DETAIL; drop table ACT_HI_COMMENT; drop table ACT_HI_ATTACHMENT;
{ "content_hash": "f1417ad06d4c6d267719f0c51d880807", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 40, "avg_line_length": 33.5, "alnum_prop": 0.7477611940298508, "repo_name": "zhangzuoqiang/jeesite", "id": "b27b8abe5745f583e011641e7b7c84d4cbc552d6", "size": "670", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "bin/refresh-db/activiti5.12.1/database/drop/activiti.db2.drop.history.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "3753" }, { "name": "Java", "bytes": "476015" }, { "name": "JavaScript", "bytes": "4994138" }, { "name": "PHP", "bytes": "6972" }, { "name": "Shell", "bytes": "3139" } ], "symlink_target": "" }
@implementation ObjUserPhone -(id) initWithDirectory:(NSDictionary *) data{ self = [super initWithDirectory:data]; if (self) { self.country_code = [self readNumberField:data fieldName:@"country_code"]; self.national_number = [self readNumberField:data fieldName:@"national_number"]; } return self; } @end
{ "content_hash": "932cb28f01c50328ee187ed18585748b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 88, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6823529411764706, "repo_name": "wenghengcong/JSBProjectBase", "id": "ee5984546de8b509d5c4585c6ec779202da02460", "size": "511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "JSBProjectBase/Model/ModelJsonUsage/ObjUserPhone.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1366192" }, { "name": "C++", "bytes": "98860" }, { "name": "HTML", "bytes": "4555" }, { "name": "Objective-C", "bytes": "906442" }, { "name": "Ruby", "bytes": "375" } ], "symlink_target": "" }
TODO: Write a gem description ## Installation Add this line to your application's Gemfile: gem 'eta' And then execute: $ bundle Or install it yourself as: $ gem install eta ## Usage There are 2 ways to use Eta: around an `Eta::Process`, or with an `Eta::Estimator`. ### Eta::Process TODO: Write usage instructions for `Eta::Process` here ### Eta::Estimator If you have a task, and can calculate what percentage of the task you're finished with, you can use an `Eta::Estimator` to estimate how much time is left, and when the task will be done. Use it like this: files_to_delete = Dir.glob('junk/*') estimator = Eta::Estimator.new estimator.start! files_to_delete.each_with_index do |file, i| File.delete(file) estimator.percent_done = i.to_f / files_to_delete.size puts "Should be done in #{estimator.time_left} seconds, by #{estimator.eta}" end ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
{ "content_hash": "74cc6eafec211c52e0839dfef67293ec", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 79, "avg_line_length": 22.979591836734695, "alnum_prop": 0.7087033747779752, "repo_name": "AndrewVos/eta", "id": "cc61994fcc811577bf740a22c50c27e284afe6ef", "size": "1133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5487" } ], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: jjuszkiewicz * Date: 24.06.2014 * Time: 10:04 */ namespace Nokaut\ApiKit\ClientApi\Rest\Query; use Nokaut\ApiKit\ClientApi\Rest\Query\Filter; class ProductsQuery extends QueryBuilderAbstract { /** * @var string */ private $baseUrl; /** * @var array */ private $order = array(); /** * @var array */ private $fields = array(); /** * @var array */ private $facets = array(); /** * @var string */ private $phrase; /** * @var int */ private $quality; /** * @var int */ private $limit; /** * @var int */ private $offset; /** * @var array */ private $facetsRange = array(); public function __construct($baseUrl = '') { $this->baseUrl = $baseUrl; } public function setFilterPriceMinFrom($value) { $this->addFilter(new Filter\SingleWithIndexAndOperator('price_min', 0, 'min', $value)); } public function setFilterPriceMinTo($value) { $this->addFilter(new Filter\SingleWithIndexAndOperator('price_min', 0, 'max', $value)); } public function setOrder($field, $order) { $this->order[$field] = $order; } public function addFacet($name, $value = 'true') { $this->facets[$name] = $value; } /** * @param array $fields * @param bool $addMetadataField */ public function setFields(array $fields, $addMetadataField = true) { $this->fields = $fields; if ($addMetadataField) { $this->fields[] = "_metadata"; } } public function setProducerName($producerName) { $this->addFilter(new Filter\Single('producer_name', $producerName)); } public function setCategoryIds(array $categoryIds) { $this->addFilter(new Filter\MultipleWithOperator('category_ids', 'in', $categoryIds)); } /** * @param string $phrase */ public function setPhrase($phrase) { $this->phrase = $phrase; } /** * @param int $quality */ public function setQuality($quality) { $this->quality = $quality; } /** * @param int $limit */ public function setLimit($limit) { $this->limit = (int)$limit; } /** * @param int $offset */ public function setOffset($offset) { if ($offset > 10000) { $offset = 10000; } $this->offset = $offset; } public function addFacetRange($name, $value) { $this->facetsRange[$name] = $value; } public function createRequestPath() { $query = $this->baseUrl . 'products?' . $this->createFieldsPart() . $this->createQualityPart() . $this->createPhrasePart() . ($this->createFilterPart() ? '&' . $this->createFilterPart() : '') . $this->createFacetsPart() . $this->createFacetsRangePart() . $this->createSortPart() . $this->createLimitPart() . $this->createOffsetPart(); return $query; } /** * @return string * @throws \InvalidArgumentException */ private function createFieldsPart() { if (empty($this->fields)) { throw new \InvalidArgumentException("fields can't be empty"); } return "fields=" . implode(',', $this->fields); } private function createSortPart() { $result = ""; foreach ($this->order as $field => $value) { $result .= "&sort[{$field}]={$value}"; } return $result; } private function createFacetsPart() { $result = ""; foreach ($this->facets as $name => $value) { $result .= "&facet[{$name}]={$value}"; } return $result; } private function createFacetsRangePart() { $result = ""; foreach ($this->facetsRange as $name => $value) { $result .= "&facet_range[{$name}]={$value}"; } return $result; } private function createPhrasePart() { if (empty($this->phrase)) { return ""; } return "&phrase=" . urlencode($this->phrase); } private function createQualityPart() { if (empty($this->quality)) { return ""; } return "&quality=" . $this->quality; } private function createLimitPart() { if (!is_numeric($this->limit)) { return ""; } return "&limit={$this->limit}"; } private function createOffsetPart() { if (empty($this->offset)) { return ""; } return "&offset={$this->offset}"; } }
{ "content_hash": "5a0f2637a9d92877a770131835f4d6f3", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 95, "avg_line_length": 21.228070175438596, "alnum_prop": 0.5132231404958678, "repo_name": "nokaut/api-kit", "id": "1fbc3cae61c2c6cbd3805e33d67aeede42e7b012", "size": "4840", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ClientApi/Rest/Query/ProductsQuery.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "364" }, { "name": "PHP", "bytes": "617046" } ], "symlink_target": "" }
""" Created on Fri Jan 16 16:42:40 2015 @author: Talha """ import pandas as pd df = pd.read_csv('data/TR-tweeps.csv',encoding='utf-8') # df = pd.read_csv('TR-commentators.csv',encoding='utf-8',skiprows=[143914]) # order commentators by total number of comments in two years df.groupby(by='twhandle')['twtext'].count().order(ascending=False).to_csv('US-tweep-comment-counts.csv',header=True)
{ "content_hash": "183a4ca21e1f62cd4508607e5d88c845", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 116, "avg_line_length": 35.63636363636363, "alnum_prop": 0.7219387755102041, "repo_name": "oztalha/TR-2014", "id": "de9bb604f8c65555be167f35bd39d012e24b0aa1", "size": "416", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "analysis/stats.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "12810" }, { "name": "Python", "bytes": "7608" } ], "symlink_target": "" }
/** * Represents the application api. If the variable is already defined use it, * otherwise create an empty object. * * @type {EScreeningDashboardApp|*|EScreeningDashboardApp|*|{}|{}} */ var EScreeningDashboardApp = EScreeningDashboardApp || {}; /** * Represents the application static variable. Use existing static variable, if one already exists, * otherwise create a new one. * * @static * @type {*|EScreeningDashboardApp.models|*|EScreeningDashboardApp.models|Object|*|Object|*} */ EScreeningDashboardApp.models = EScreeningDashboardApp.models || EScreeningDashboardApp.namespace("gov.va.escreening.models"); /** * Constructor method for the Template class. The properties of this class can be initialized with * the jsonTemplateObject. * Please Note: This is used for both instantiating new objects and for extending Restangular models. Because of this there cannot * be any fields defined unless we are creating a new instance. Currently if we are creating an instance the templateCondig must be * given with the type of the template so we can save it. When that happens the fields will have default values set. * * @class * @classdesc This class is a domain model class; which means it has both behavior and state * information about Template Types. * @param {JSON} templateConfig Represents the JSON representation of a Template object. * @constructor * @author Robin Carnow */ EScreeningDashboardApp.models.Template = function (templateConfig) { if(Object.isDefined(templateConfig)){ this.id = Object.isDefined(templateConfig.id)? templateConfig.id : null; this.isGraphical = (Object.isBoolean(templateConfig.isGraphical))? templateConfig.isGraphical : false; this.type = (Object.isDefined(templateConfig.type))? templateConfig.type: null; this.name = (Object.isDefined(templateConfig.type) && Object.isDefined(templateConfig.type.name))? templateConfig.type.name: null; this.blocks = (Object.isArray(templateConfig.blocks))? EScreeningDashboardApp.models.TemplateBlock.createTemplateBlockArray(templateConfig.blocks): []; } /** * Runs any initialization tasks after a model extend */ this.init = function(){ if(Object.isArray(this.blocks)){ this.blocks = EScreeningDashboardApp.models.TemplateBlock.createTemplateBlockArray(this.blocks); } }; /** * Because of some of the awkward nature of our endpoints and pre-restangular, UI code we have to do this for now * @param related object is the object which is associated with the template being saved. The related object * can be either a battery or a survey. The related object parameter should look like this: * { * id : [surveyId | batteryId], * name : the display name of the related object, * type : ["module" | "battery"] * } * */ this.saveFor = function(relatedObject){ var isPostable = Object.isDefined(this.type.customPOST); if(Object.isDefined(this.id) && this.id != -1 && (parseInt(this.id) == this.id || this.id.length > 0)){ //this is an update return this.put(); } else if(isPostable && relatedObject.type == "module"){ //this is a new template console.log("Saving new template of type " + this.type.id + " for survey with ID: " + relatedObject.id) //TODO: if/when we move to a more OO restful end point structure we should remove this in favor of: // var templateTypes = module.getList('templateTypes'); // ... at some point: new EScreeningDashboardApp.models.Template({type: selectedTemplateType}); // this.type.post(this); // The goal would be to have "this" sent to either: // - POST: /services/surveys/{surveyId}/templateTypes/{templateTypeId} // or this: // - POST: /services/batteries/{batteryId}/templateTypes/{templateTypeId} return this.type.customPOST(this, "surveys/" + relatedObject.id); } else if(isPostable && relatedObject.type == "battery"){ //this is a new template console.log("Saving new template of type " + this.type.id + " for battery with ID: " + relatedObject.id); return this.type.customPOST(this, "batteries/" + relatedObject.id); } var logMsg = "State was lost for the currently edited template. No ID was found but it is also not a new template."; var userMsg = "Editor state was lost. Call support."; if(isPostable){ logMsg = "Unsupported operation. Template is new and related object is unsupported: " + JSON.stringify(relatedObject); userMsg = "Unsupported operation. Call support."; } console.error(logMsg); var deferred = $q.defer(); deferred.reject(userMsg); return deferred.promise; }; /** * Updates the section numbering of all blocks as well as each block's parent field */ this.updateSections = function(){ function updateSection(children, parent){ if(Object.isDefined(children)){ for (var i = 0; i < children.length; i++){ var sectionIndex = i + 1; children[i].setParent(parent); children[i].section = parent ? parent.section + "." + sectionIndex : "" + sectionIndex; updateSection(children[i].children, children[i]); } } } return updateSection(this.blocks); }; this.toString = function () { return "Template {id: " + this.id + ", type: " + this.type + ", isGraphical: " + this.isGraphical + ", with " + blocks.length + " blocks.}"; }; };
{ "content_hash": "b42d8aa4ba8a873077aeb140b07f4c01", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 159, "avg_line_length": 48.18852459016394, "alnum_prop": 0.6431365878550774, "repo_name": "efloto/Mental-Health-eScreening", "id": "ece01b470f51d4281a8a03f2b719b5a32696455d", "size": "5879", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "escreening/src/main/webapp/resources/editors/js/app/domains/Template.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8420" }, { "name": "CSS", "bytes": "5863912" }, { "name": "FreeMarker", "bytes": "95953" }, { "name": "HTML", "bytes": "6925871" }, { "name": "Java", "bytes": "3630764" }, { "name": "JavaScript", "bytes": "4323611" }, { "name": "PLSQL", "bytes": "1476" }, { "name": "SQLPL", "bytes": "93612" }, { "name": "Scala", "bytes": "3339" }, { "name": "Shell", "bytes": "6295" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a31a09c62ea3fad945f5787aa4ca2181", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 18, "avg_line_length": 8.384615384615385, "alnum_prop": 0.6788990825688074, "repo_name": "mdoering/backbone", "id": "21dd9c298047e9aa8913837d0ad76947296777be", "size": "156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Massalongiaceae/Pilonema/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace ZfeggTest\Db\TableGateway\Factory; use Laminas\Db\Adapter\AdapterAbstractServiceFactory; use Laminas\Db\TableGateway\TableGateway; use Laminas\ServiceManager\ServiceManager; use Zfegg\Db\TableGateway\Factory\TableGatewayAbstractServiceFactory; use ZfeggTest\Db\TableGateway\ContainerStatic; /** * Class TestTableGatewayAbstractServiceFactory * @package ZfeggTest\Db\TableGateway\Factory * @author Xiemaomao * @version $Id$ */ class TableGatewayAbstractServiceFactoryTest extends \PHPUnit_Framework_TestCase { /** @var ServiceManager */ protected $container; public function setUp() { $this->container = ContainerStatic::getInstance(); } public function testCanCreateAndInvoke() { $this->assertTrue($this->container->has('TestTable')); $this->assertInstanceOf(TableGateway::class, $this->container->get('TestTable')); } public function testServiceManagerV2() { $asf = new TableGatewayAbstractServiceFactory(); $this->assertTrue($asf->canCreateServiceWithName($this->container, '', 'TestTable')); $this->assertInstanceOf(TableGateway::class, $asf->createServiceWithName($this->container, '', 'TestTable')); } }
{ "content_hash": "43cae3e960e6b7f26ad0d8044892617d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 117, "avg_line_length": 31.512820512820515, "alnum_prop": 0.7290480065093572, "repo_name": "zfegg/zend-db-feature", "id": "52ec4c20234066518e642170afbd3b246714b1b1", "size": "1229", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/Factory/TableGatewayAbstractServiceFactoryTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "18212" } ], "symlink_target": "" }
'use strict'; var freeze = require( './../utilities/freeze.js' ); function getMainProperties( definitions ) { var main = { }; // Collect the non-segment properties from definitions. for (var property in definitions) { if (property.indexOf( '$-' ) !== 0 && property.indexOf( 'segment.' ) !== 0) main[ property ] = definitions[ property ]; } return main; } function getSegmentProperties( definitions ) { var segments = { }; // Collect the segment properties from definitions. for (var property in definitions) { if (property.indexOf( '$-') === 0) segments[ property.substring( 2 ) ] = definitions[ property ]; if (property.indexOf( 'segment.') === 0) segments[ property.substring( 8 ) ] = definitions[ property ]; } return segments; } /** * Represents the metadata of a content. * @param {object} definitions - A collection of properties. * @param {string} path - The path of the current content. * @constructor */ var Metadata = function( definitions, path ) { //region Search engine properties /** * Gets the title of the document. * @type {string} * @readonly */ this.title = ''; /** * Gets the keywords of the document. * @type {string} * @readonly */ this.keywords = ''; /** * Gets the description of the document. * @type {string} * @readonly */ this.description = ''; //endregion //region Menu properties /** * Gets the text of the menu item. * @type {string} * @readonly */ this.text = ''; /** * Gets the order of the menu item. * @type {string} * @readonly */ this.order = 0; /** * Indicates whether the menu item is displayed. * @type {Boolean} * @readonly */ this.hidden = false; /** * Indicates whether the menu item is a leaf with hidden children, * i.e. a truncated menu node. * @type {Boolean} * @readonly */ this.umbel = false; //endregion //region Page properties /** * Gets the identifier of the content, it defaults to the path. * @type {string} * @readonly */ this.id = ''; /** * Gets the path of the content. * @type {string} * @readonly */ this.path = path; /** * Gets the name of a custom document for the content. * @type {string} * @readonly */ this.document = ''; /** * Gets the name of a custom layout for the content. * @type {string} * @readonly */ this.layout = ''; /** * Gets the token collection for the segments found on the content. * @type {object} * @readonly */ this.segments = { }; /** * Indicates whether the content is enabled for search. * @type {Boolean} * @readonly */ this.searchable = true; //endregion // Set the defined properties of the content. Object.assign( this, getMainProperties( definitions ) ); Object.assign( this.segments, getSegmentProperties( definitions ) ); // Set default identity. if (!this.id) this.id = path; // Immutable object. freeze( this ); }; module.exports = Metadata;
{ "content_hash": "f270436c01bcc82177a4d762cc55fa7d", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 79, "avg_line_length": 20.03267973856209, "alnum_prop": 0.6065252854812399, "repo_name": "logikum/md-site-engine", "id": "fc9967ff0a1a28a38fd4e90e4bae63990b0f42bc", "size": "3065", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/models/metadata.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "326" }, { "name": "JavaScript", "bytes": "131996" } ], "symlink_target": "" }
package org.datacontract.schemas._2004._07.EEN_Merlin_Backend_Core_BO_PODService; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlType; import com.microsoft.schemas._2003_10.Serialization.Arrays.ArrayOfstring; /** * <p>Java class for ProfileQueryRequest complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ProfileQueryRequest"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="ContractId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="CountriesForDissemination" type="{http://schemas.microsoft.com/2003/10/Serialization/Arrays}ArrayOfstring" minOccurs="0"/&gt; * &lt;element name="DeadlineDateAfter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="DeadlineDateBefore" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="IncludeImages" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="OrganisationCountryName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="OrganisationIdentifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="OrganisationName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="Password" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="ProfileTypes" type="{http://schemas.microsoft.com/2003/10/Serialization/Arrays}ArrayOfstring" minOccurs="0"/&gt; * &lt;element name="PublishedDateAfter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="PublishedDateBefore" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="SubmitDateAfter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="SubmitDateBefore" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="UpdateDateAfter" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="UpdateDateBefore" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="Username" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ProfileQueryRequest", propOrder = { "contractId", "countriesForDissemination", "deadlineDateAfter", "deadlineDateBefore", "includeImages", "organisationCountryName", "organisationIdentifier", "organisationName", "password", "profileTypes", "publishedDateAfter", "publishedDateBefore", "submitDateAfter", "submitDateBefore", "updateDateAfter", "updateDateBefore", "username" }) public class ProfileQueryRequest { @XmlElementRef(name = "ContractId", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> contractId; @XmlElementRef(name = "CountriesForDissemination", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<ArrayOfstring> countriesForDissemination; @XmlElementRef(name = "DeadlineDateAfter", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> deadlineDateAfter; @XmlElementRef(name = "DeadlineDateBefore", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> deadlineDateBefore; @XmlElementRef(name = "IncludeImages", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> includeImages; @XmlElementRef(name = "OrganisationCountryName", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> organisationCountryName; @XmlElementRef(name = "OrganisationIdentifier", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> organisationIdentifier; @XmlElementRef(name = "OrganisationName", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> organisationName; @XmlElement(name = "Password", required = true, nillable = true) protected String password; @XmlElementRef(name = "ProfileTypes", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<ArrayOfstring> profileTypes; @XmlElementRef(name = "PublishedDateAfter", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> publishedDateAfter; @XmlElementRef(name = "PublishedDateBefore", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> publishedDateBefore; @XmlElementRef(name = "SubmitDateAfter", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> submitDateAfter; @XmlElementRef(name = "SubmitDateBefore", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> submitDateBefore; @XmlElementRef(name = "UpdateDateAfter", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> updateDateAfter; @XmlElementRef(name = "UpdateDateBefore", namespace = "http://schemas.datacontract.org/2004/07/EEN.Merlin.Backend.Core.BO.PODService", type = JAXBElement.class, required = false) protected JAXBElement<String> updateDateBefore; @XmlElement(name = "Username", required = true, nillable = true) protected String username; /** * Gets the value of the contractId property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getContractId() { return contractId; } /** * Sets the value of the contractId property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setContractId(JAXBElement<String> value) { this.contractId = value; } /** * Gets the value of the countriesForDissemination property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link ArrayOfstring }{@code >} * */ public JAXBElement<ArrayOfstring> getCountriesForDissemination() { return countriesForDissemination; } /** * Sets the value of the countriesForDissemination property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link ArrayOfstring }{@code >} * */ public void setCountriesForDissemination(JAXBElement<ArrayOfstring> value) { this.countriesForDissemination = value; } /** * Gets the value of the deadlineDateAfter property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getDeadlineDateAfter() { return deadlineDateAfter; } /** * Sets the value of the deadlineDateAfter property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setDeadlineDateAfter(JAXBElement<String> value) { this.deadlineDateAfter = value; } /** * Gets the value of the deadlineDateBefore property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getDeadlineDateBefore() { return deadlineDateBefore; } /** * Sets the value of the deadlineDateBefore property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setDeadlineDateBefore(JAXBElement<String> value) { this.deadlineDateBefore = value; } /** * Gets the value of the includeImages property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getIncludeImages() { return includeImages; } /** * Sets the value of the includeImages property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setIncludeImages(JAXBElement<String> value) { this.includeImages = value; } /** * Gets the value of the organisationCountryName property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getOrganisationCountryName() { return organisationCountryName; } /** * Sets the value of the organisationCountryName property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setOrganisationCountryName(JAXBElement<String> value) { this.organisationCountryName = value; } /** * Gets the value of the organisationIdentifier property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getOrganisationIdentifier() { return organisationIdentifier; } /** * Sets the value of the organisationIdentifier property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setOrganisationIdentifier(JAXBElement<String> value) { this.organisationIdentifier = value; } /** * Gets the value of the organisationName property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getOrganisationName() { return organisationName; } /** * Sets the value of the organisationName property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setOrganisationName(JAXBElement<String> value) { this.organisationName = value; } /** * Gets the value of the password property. * * @return * possible object is * {@link String } * */ public String getPassword() { return password; } /** * Sets the value of the password property. * * @param value * allowed object is * {@link String } * */ public void setPassword(String value) { this.password = value; } /** * Gets the value of the profileTypes property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link ArrayOfstring }{@code >} * */ public JAXBElement<ArrayOfstring> getProfileTypes() { return profileTypes; } /** * Sets the value of the profileTypes property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link ArrayOfstring }{@code >} * */ public void setProfileTypes(JAXBElement<ArrayOfstring> value) { this.profileTypes = value; } /** * Gets the value of the publishedDateAfter property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPublishedDateAfter() { return publishedDateAfter; } /** * Sets the value of the publishedDateAfter property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPublishedDateAfter(JAXBElement<String> value) { this.publishedDateAfter = value; } /** * Gets the value of the publishedDateBefore property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getPublishedDateBefore() { return publishedDateBefore; } /** * Sets the value of the publishedDateBefore property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setPublishedDateBefore(JAXBElement<String> value) { this.publishedDateBefore = value; } /** * Gets the value of the submitDateAfter property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSubmitDateAfter() { return submitDateAfter; } /** * Sets the value of the submitDateAfter property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSubmitDateAfter(JAXBElement<String> value) { this.submitDateAfter = value; } /** * Gets the value of the submitDateBefore property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getSubmitDateBefore() { return submitDateBefore; } /** * Sets the value of the submitDateBefore property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setSubmitDateBefore(JAXBElement<String> value) { this.submitDateBefore = value; } /** * Gets the value of the updateDateAfter property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getUpdateDateAfter() { return updateDateAfter; } /** * Sets the value of the updateDateAfter property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setUpdateDateAfter(JAXBElement<String> value) { this.updateDateAfter = value; } /** * Gets the value of the updateDateBefore property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getUpdateDateBefore() { return updateDateBefore; } /** * Sets the value of the updateDateBefore property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setUpdateDateBefore(JAXBElement<String> value) { this.updateDateBefore = value; } /** * Gets the value of the username property. * * @return * possible object is * {@link String } * */ public String getUsername() { return username; } /** * Sets the value of the username property. * * @param value * allowed object is * {@link String } * */ public void setUsername(String value) { this.username = value; } }
{ "content_hash": "93301f370bbdc7a359396c0c090cea93", "timestamp": "", "source": "github", "line_count": 513, "max_line_length": 191, "avg_line_length": 34.06432748538012, "alnum_prop": 0.6222031473533619, "repo_name": "eSCT/oppfin", "id": "dcc261a65cad22bf5ffddad5b5678453fb7ea493", "size": "17475", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/datacontract/schemas/_2004/_07/EEN_Merlin_Backend_Core_BO_PODService/ProfileQueryRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "29538" }, { "name": "Java", "bytes": "1205886" }, { "name": "JavaScript", "bytes": "16606" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.wildfly.swarm.testsuite</groupId> <artifactId>testsuite-parent</artifactId> <version>2017.8.0-SNAPSHOT</version> <relativePath>../</relativePath> </parent> <artifactId>testsuite-spring</artifactId> <name>Test Suite: Spring</name> <description>Test Suite: Spring</description> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.wildfly.swarm</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.wildfly.swarm</groupId> <artifactId>arquillian</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.jboss.arquillian.junit</groupId> <artifactId>arquillian-junit-container</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "57fe1976d753a1c1208bf3a5bcca6132", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 204, "avg_line_length": 31.083333333333332, "alnum_prop": 0.6863270777479893, "repo_name": "gastaldi/wildfly-swarm", "id": "fdaedc44d708b739b72c8c28928ecd4c93c1ee98", "size": "1119", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testsuite/testsuite-spring/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5821" }, { "name": "HTML", "bytes": "7818" }, { "name": "Java", "bytes": "2589371" }, { "name": "JavaScript", "bytes": "13143" }, { "name": "Ruby", "bytes": "5349" }, { "name": "Shell", "bytes": "8275" }, { "name": "XSLT", "bytes": "917" } ], "symlink_target": "" }
jumplink.cms.service('ConfigService', function ($sailsSocket, $filter, $log) { var resolve = function(page) { return $sailsSocket.get('/config/find').then (function (data) { return data.data; }, function error (resp){ $log.error("Error on resolve "+page, resp); }); }; return { resolve: resolve }; });
{ "content_hash": "34ff221ef38b8e25596f6edaf9bb9b1f", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 78, "avg_line_length": 22.666666666666668, "alnum_prop": 0.611764705882353, "repo_name": "JumpLink/cms-bootstrap-theme", "id": "e562ef7a994c84bec8100370043e6dd656a3e8fe", "size": "340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/js/services/ConfigService.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "18342" }, { "name": "HTML", "bytes": "113426" }, { "name": "JavaScript", "bytes": "160046" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Marionette Boilerplate App</title> <!-- UIKit CSS --> <link rel="stylesheet" href="public/uikit/css/uikit.gradient.min.css"> <!-- Custom CSS --> <link rel="stylesheet" href="public/styles.css"> </head> <body class="uk-height-1-1"> <div id="container" class="uk-height-1-1"> <p>Loading application...</p> </div> <!-- Javascript --> <script src="public/vendor.js"></script> <script src="public/uikit/js/uikit.min.js"></script> <script src="public/app.js"></script> </body> </html>
{ "content_hash": "578c2a726ed8d46ddf5d4222062a7e86", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 78, "avg_line_length": 33.65, "alnum_prop": 0.5453194650817236, "repo_name": "emaphp/marionette-boilerplate-app", "id": "328d8f6b45a0cdd1de24ee9dcb47eef723bbd4f7", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "194" }, { "name": "HTML", "bytes": "673" }, { "name": "Handlebars", "bytes": "1113" }, { "name": "JavaScript", "bytes": "5738" } ], "symlink_target": "" }
#import "Platforms/CCGL.h" #import "ccTypes.h" #import "CCProtocols.h" #import "ccConfig.h" #import "ccGLStateCache.h" #import "Support/CCArray.h" #import "kazmath/kazmath.h" enum { kCCNodeTagInvalid = -1, }; @class CCCamera; @class CCGridBase; @class CCGLProgram; @class CCScheduler; @class CCActionManager; @class CCAction; /** CCNode is the main element. Anything thats gets drawn or contains things that get drawn is a CCNode. The most popular CCNodes are: CCScene, CCLayer, CCSprite, CCMenu. The main features of a CCNode are: - They can contain other CCNode nodes (addChild, getChildByTag, removeChild, etc) - They can schedule periodic callback (schedule, unschedule, etc) - They can execute actions (runAction, stopAction, etc) Some CCNode nodes provide extra functionality for them or their children. Subclassing a CCNode usually means (one/all) of: - overriding init to initialize resources and schedule callbacks - create callbacks to handle the advancement of time - overriding draw to render the node Features of CCNode: - position - scale (x, y) - rotation (in degrees, clockwise) - CCCamera (an interface to gluLookAt ) - CCGridBase (to do mesh transformations) - anchor point - size - visible - z-order - openGL z position Default values: - rotation: 0 - position: (x=0,y=0) - scale: (x=1,y=1) - contentSize: (x=0,y=0) - anchorPoint: (x=0,y=0) Limitations: - A CCNode is a "void" object. It doesn't have a texture Order in transformations with grid disabled -# The node will be translated (position) -# The node will be rotated (rotation) -# The node will be skewed (skewX, skewY) -# The node will be scaled (scale, scaleX, scaleY) -# The node will be moved according to the camera values (camera) Order in transformations with grid enabled -# The node will be translated (position) -# The node will be rotated (rotation, rotationX, rotationY) -# The node will be skewed (skewX, skewY) -# The node will be scaled (scale, scaleX, scaleY) -# The grid will capture the screen -# The node will be moved according to the camera values (camera) -# The grid will render the captured screen Camera: - Each node has a camera. By default it points to the center of the CCNode. */ @interface CCNode : NSObject { // rotation angle float _rotationX, _rotationY; // scaling factors float _scaleX, _scaleY; // openGL real Z vertex float _vertexZ; // position of the node CGPoint _position; // skew angles float _skewX, _skewY; // anchor point in points CGPoint _anchorPointInPoints; // anchor point normalized (NOT in points) CGPoint _anchorPoint; // untransformed size of the node CGSize _contentSize; // transform CGAffineTransform _transform, _inverse; BOOL _isTransformDirty; BOOL _isInverseDirty; // a Camera CCCamera *_camera; // a Grid CCGridBase *_grid; // z-order value NSInteger _zOrder; // array of children CCArray *_children; // weak ref to parent CCNode *_parent; // a tag. any number you want to assign to the node NSInteger _tag; // user data field void *_userData; id _userObject; // Shader CCGLProgram *_shaderProgram; // Server side state ccGLServerState _glServerState; // used to preserve sequence while sorting children with the same zOrder NSUInteger _orderOfArrival; // scheduler used to schedule timers and updates CCScheduler *_scheduler; // ActionManager used to handle all the actions CCActionManager *_actionManager; // Is running BOOL _isRunning; // is visible BOOL _visible; // If YES, the Anchor Point will be (0,0) when you position the CCNode. // Used by CCLayer and CCScene BOOL _ignoreAnchorPointForPosition; BOOL _isReorderChildDirty; NSString* _name; NSString* _varComment; BOOL _canDragMove; BOOL _canSetAnchorPoint; BOOL _isValidNode; CCArray* _children1; } @property(nonatomic,assign) BOOL isCopyText; @property(nonatomic,copy) NSString* oldCopyTextKey; @property(nonatomic,assign) BOOL isValidNode; @property(nonatomic,retain) NSString* name; @property(nonatomic,assign) BOOL canSetAnchorPoint; @property(nonatomic,retain) NSString* varComment; @property(nonatomic,assign) BOOL canDragMove; /** The z order of the node relative to its "siblings": children of the same parent */ @property(nonatomic,assign) NSInteger zOrder; /** The real openGL Z vertex. Differences between openGL Z vertex and cocos2d Z order: - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - OpenGL Z might require to set 2D projection - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0 @warning: Use it at your own risk since it might break the cocos2d parent-children z order @since v0.8 */ @property (nonatomic,readwrite) float vertexZ; /** The X skew angle of the node in degrees. This angle describes the shear distortion in the X direction. Thus, it is the angle between the Y axis and the left edge of the shape The default skewX angle is 0. Positive values distort the node in a CW direction. */ @property(nonatomic,readwrite,assign) float skewX; /** The Y skew angle of the node in degrees. This angle describes the shear distortion in the Y direction. Thus, it is the angle between the X axis and the bottom edge of the shape The default skewY angle is 0. Positive values distort the node in a CCW direction. */ @property(nonatomic,readwrite,assign) float skewY; /** The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. */ @property(nonatomic,readwrite,assign) float rotation; /** The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. It only modifies the X rotation performing a horizontal rotational skew . */ @property(nonatomic,readwrite,assign) float rotationX; /** The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW. It only modifies the Y rotation performing a vertical rotational skew . */ @property(nonatomic,readwrite,assign) float rotationY; /** The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time. */ @property(nonatomic,readwrite,assign) float scale; /** The scale factor of the node. 1.0 is the default scale factor. It only modifies the X scale factor. */ @property(nonatomic,readwrite,assign) float scaleX; /** The scale factor of the node. 1.0 is the default scale factor. It only modifies the Y scale factor. */ @property(nonatomic,readwrite,assign) float scaleY; /** Position (x,y) of the node in points. (0,0) is the left-bottom corner. */ @property(nonatomic,readwrite,assign) CGPoint position; /** A CCCamera object that lets you move the node using a gluLookAt */ @property(nonatomic,readonly) CCCamera* camera; /** Array of children */ @property(nonatomic,readonly) CCArray *children; /** A CCGrid object that is used when applying effects */ @property(nonatomic,readwrite,retain) CCGridBase* grid; /** Whether of not the node is visible. Default is YES */ @property(nonatomic,readwrite,assign) BOOL visible; /** anchorPoint is the point around which all transformations and positioning manipulations take place. It's like a pin in the node where it is "attached" to its parent. The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. But you can use values higher than (1,1) and lower than (0,0) too. The default anchorPoint is (0,0). It starts in the bottom-left corner. CCSprite and other subclasses have a different default anchorPoint. @since v0.8 */ @property(nonatomic,readwrite) CGPoint anchorPoint; /** The anchorPoint in absolute pixels. Since v0.8 you can only read it. If you wish to modify it, use anchorPoint instead */ @property(nonatomic,readonly) CGPoint anchorPointInPoints; /** The untransformed size of the node in Points The contentSize remains the same no matter the node is scaled or rotated. All nodes has a size. Layer and Scene has the same size of the screen. @since v0.8 */ @property (nonatomic,readwrite) CGSize contentSize; /** whether or not the node is running */ @property(nonatomic,readonly) BOOL isRunning; /** A weak reference to the parent */ @property(nonatomic,readwrite,assign) CCNode* parent; /** If YES, the Anchor Point will be (0,0) when you position the CCNode. Used by CCLayer and CCScene. */ @property(nonatomic,readwrite,assign) BOOL ignoreAnchorPointForPosition; /** A tag used to identify the node easily */ @property(nonatomic,readwrite,assign) NSInteger tag; /** A custom user data pointer */ @property(nonatomic,readwrite,assign) void* userData; /** Similar to userData, but instead of holding a void* it holds an id */ @property(nonatomic,readwrite,retain) id userObject; /** Shader Program @since v2.0 */ @property(nonatomic,readwrite,retain) CCGLProgram *shaderProgram; /** used internally for zOrder sorting, don't change this manually */ @property(nonatomic,readwrite) NSUInteger orderOfArrival; /** GL server side state @since v2.0 */ @property (nonatomic, readwrite) ccGLServerState glServerState; /** CCActionManager used by all the actions. IMPORTANT: If you set a new CCActionManager, then previously created actions are going to be removed. @since v2.0 */ @property (nonatomic, readwrite, retain) CCActionManager *actionManager; /** CCScheduler used to schedule all "updates" and timers. IMPORTANT: If you set a new CCScheduler, then previously created timers/update are going to be removed. @since v2.0 */ @property (nonatomic, readwrite, retain) CCScheduler *scheduler; // initializators /** allocates and initializes a node. The node will be created as "autorelease". */ +(id) node; /** initializes the node */ -(id) init; // scene management /** Event that is called every time the CCNode enters the 'stage'. If the CCNode enters the 'stage' with a transition, this event is called when the transition starts. During onEnter you can't access a sibling node. If you override onEnter, you shall call [super onEnter]. */ -(void) onEnter; /** Event that is called when the CCNode enters in the 'stage'. If the CCNode enters the 'stage' with a transition, this event is called when the transition finishes. If you override onEnterTransitionDidFinish, you shall call [super onEnterTransitionDidFinish]. @since v0.8 */ -(void) onEnterTransitionDidFinish; /** Event that is called every time the CCNode leaves the 'stage'. If the CCNode leaves the 'stage' with a transition, this event is called when the transition finishes. During onExit you can't access a sibling node. If you override onExit, you shall call [super onExit]. */ -(void) onExit; /** callback that is called every time the CCNode leaves the 'stage'. If the CCNode leaves the 'stage' with a transition, this callback is called when the transition starts. */ -(void) onExitTransitionDidStart; // composition: ADD /** Adds a child to the container with z-order as 0. If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. @since v0.7.1 */ -(void) addChild: (CCNode*)node; /** Adds a child to the container with a z-order. If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. @since v0.7.1 */ -(void) addChild: (CCNode*)node z:(NSInteger)z; /** Adds a child to the container with z order and tag. If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. @since v0.7.1 */ -(void) addChild: (CCNode*)node z:(NSInteger)z tag:(NSInteger)tag; // composition: REMOVE /** Remove itself from its parent node forcing a cleanup. If the node orphan, then nothing happens. @since v2.1 */ -(void) removeFromParent; /** Remove itself from its parent node. If cleanup is YES, then also remove all actions and callbacks. If the node orphan, then nothing happens. @since v0.99.3 */ -(void) removeFromParentAndCleanup:(BOOL)cleanup; /** Removes a child from the container forcing a cleanup @since v2.1 */ -(void) removeChild:(CCNode*)child; /** Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter. @since v0.7.1 */ -(void) removeChild: (CCNode*)node cleanup:(BOOL)cleanup; /** Removes a child from the container by tag value forcing a cleanup. @since v2.1 */ -(void) removeChildByTag:(NSInteger) tag; /** Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter @since v0.7.1 */ -(void) removeChildByTag:(NSInteger) tag cleanup:(BOOL)cleanup; /** Removes all children from the container forcing a cleanup. @since v2.1 */ -(void) removeAllChildren; /** Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter. @since v0.7.1 */ -(void) removeAllChildrenWithCleanup:(BOOL)cleanup; // composition: GET /** Gets a child from the container given its tag @return returns a CCNode object @since v0.7.1 */ -(CCNode*) getChildByTag:(NSInteger) tag; /** Reorders a child according to a new z value. * The child MUST be already added. */ -(void) reorderChild:(CCNode*)child z:(NSInteger)zOrder; /** performance improvement, Sort the children array once before drawing, instead of every time when a child is added or reordered don't call this manually unless a child added needs to be removed in the same frame */ - (void) sortAllChildren; /** Event that is called when the running node is no longer running (eg: its CCScene is being removed from the "stage" ). On cleanup you should break any possible circular references. CCNode's cleanup removes any possible scheduled timer and/or any possible action. If you override cleanup, you shall call [super cleanup] @since v0.8 */ -(void) cleanup; // draw /** Override this method to draw your own node. You should use cocos2d's GL API to enable/disable the GL state / shaders. For further info, please see ccGLstate.h. You shall NOT call [super draw]; */ -(void) draw; /** recursive method that visit its children and draw them */ -(void) visit; // transformations /** performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes. */ -(void) transform; /** performs OpenGL view-matrix transformation of its ancestors. Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO) it is necessary to transform the ancestors again. @since v0.7.2 */ -(void) transformAncestors; /** returns a "local" axis aligned bounding box of the node in points. The returned box is relative only to its parent. The returned box is in Points. @since v0.8.2 */ - (CGRect) boundingBox; // actions /** Executes an action, and returns the action that is executed. The node becomes the action's target. @warning Starting from v0.8 actions don't retain their target anymore. @since v0.7.1 @return An Action pointer */ -(CCAction*) runAction: (CCAction*) action; /** Removes all actions from the running action list */ -(void) stopAllActions; /** Removes an action from the running action list */ -(void) stopAction: (CCAction*) action; /** Removes an action from the running action list given its tag @since v0.7.1 */ -(void) stopActionByTag:(NSInteger) tag; /** Gets an action from the running action list given its tag @since v0.7.1 @return the Action the with the given tag */ -(CCAction*) getActionByTag:(NSInteger) tag; /** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays). * Composable actions are counted as 1 action. Example: * If you are running 1 Sequence of 7 actions, it will return 1. * If you are running 7 Sequences of 2 actions, it will return 7. */ -(NSUInteger) numberOfRunningActions; // timers /** check whether a selector is scheduled. */ //-(BOOL) isScheduled: (SEL) selector; /** schedules the "update" method. It will use the order number 0. This method will be called every frame. Scheduled methods with a lower order value will be called before the ones that have a higher order value. Only one "update" method could be scheduled per node. @since v0.99.3 */ -(void) scheduleUpdate; /** schedules the "update" selector with a custom priority. This selector will be called every frame. Scheduled selectors with a lower priority will be called before the ones that have a higher value. Only one "update" selector could be scheduled per node (You can't have 2 'update' selectors). @since v0.99.3 */ -(void) scheduleUpdateWithPriority:(NSInteger)priority; /* unschedules the "update" method. @since v0.99.3 */ -(void) unscheduleUpdate; /** schedules a selector. The scheduled selector will be ticked every frame */ -(void) schedule: (SEL) s; /** schedules a custom selector with an interval time in seconds. If time is 0 it will be ticked every frame. If time is 0, it is recommended to use 'scheduleUpdate' instead. If the selector is already scheduled, then the interval parameter will be updated without scheduling it again. */ -(void) schedule: (SEL) s interval:(ccTime)seconds; /** repeat will execute the action repeat + 1 times, for a continues action use kCCRepeatForever delay is the amount of time the action will wait before execution */ -(void) schedule:(SEL)selector interval:(ccTime)interval repeat: (uint) repeat delay:(ccTime) delay; /** Schedules a selector that runs only once, with a delay of 0 or larger */ - (void) scheduleOnce:(SEL) selector delay:(ccTime) delay; /** unschedules a custom selector.*/ -(void) unschedule: (SEL) s; /** unschedule all scheduled selectors: custom selectors, and the 'update' selector. Actions are not affected by this method. @since v0.99.3 */ -(void) unscheduleAllSelectors; /** resumes all scheduled selectors and actions. Called internally by onEnter */ -(void) resumeSchedulerAndActions; /** pauses all scheduled selectors and actions. Called internally by onExit */ -(void) pauseSchedulerAndActions; /* Update will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" */ -(void) update:(ccTime)delta; // transformation methods /** Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates. The matrix is in Pixels. @since v0.7.1 */ - (CGAffineTransform)nodeToParentTransform; /** Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. The matrix is in Pixels. @since v0.7.1 */ - (CGAffineTransform)parentToNodeTransform; /** Returns the world affine transform matrix. The matrix is in Pixels. @since v0.7.1 */ - (CGAffineTransform)nodeToWorldTransform; /** Returns the inverse world affine transform matrix. The matrix is in Pixels. @since v0.7.1 */ - (CGAffineTransform)worldToNodeTransform; /** Converts a Point to node (local) space coordinates. The result is in Points. @since v0.7.1 */ - (CGPoint)convertToNodeSpace:(CGPoint)worldPoint; /** Converts a Point to world space coordinates. The result is in Points. @since v0.7.1 */ - (CGPoint)convertToWorldSpace:(CGPoint)nodePoint; /** Converts a Point to node (local) space coordinates. The result is in Points. treating the returned/received node point as anchor relative. @since v0.7.1 */ - (CGPoint)convertToNodeSpaceAR:(CGPoint)worldPoint; /** Converts a local Point to world space coordinates.The result is in Points. treating the returned/received node point as anchor relative. @since v0.7.1 */ - (CGPoint)convertToWorldSpaceAR:(CGPoint)nodePoint; #ifdef __CC_PLATFORM_IOS /** Converts a UITouch to node (local) space coordinates. The result is in Points. @since v0.7.1 */ - (CGPoint)convertTouchToNodeSpace:(UITouch *)touch; /** Converts a UITouch to node (local) space coordinates. The result is in Points. This method is AR (Anchor Relative).. @since v0.7.1 */ - (CGPoint)convertTouchToNodeSpaceAR:(UITouch *)touch; #endif // __CC_PLATFORM_IOS @end #pragma mark - CCNodeRGBA /** CCNodeRGBA is a subclass of CCNode that implements the CCRGBAProtocol protocol. All features from CCNode are valid, plus the following new features: - opacity - RGB colors Opacity/Color propagates into children that conform to the CCRGBAProtocol if cascadeOpacity/cascadeColor is enabled. @since v2.1 */ @interface CCNodeRGBA : CCNode <CCRGBAProtocol> { GLubyte _displayedOpacity, _realOpacity; ccColor3B _displayedColor, _realColor; BOOL _cascadeColorEnabled, _cascadeOpacityEnabled; } // XXX To make BridgeSupport happy -(GLubyte) opacity; @end
{ "content_hash": "29871eab5d0a0d368957bda18470e3bd", "timestamp": "", "source": "github", "line_count": 612, "max_line_length": 190, "avg_line_length": 34.99183006535948, "alnum_prop": 0.7241653046929722, "repo_name": "zjfzjf/CocosBuilder-master", "id": "06f463b181c32496302d1935c0f6a550cdc369ab", "size": "22693", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cocos2d-iphone/cocos2d/CCNode.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "485521" }, { "name": "C++", "bytes": "85738" }, { "name": "DTrace", "bytes": "12324" }, { "name": "Groff", "bytes": "19312" }, { "name": "HTML", "bytes": "17681003" }, { "name": "JavaScript", "bytes": "216369" }, { "name": "Objective-C", "bytes": "4442379" }, { "name": "Objective-C++", "bytes": "58347" }, { "name": "PHP", "bytes": "81020" }, { "name": "Shell", "bytes": "1569" } ], "symlink_target": "" }
<?php require(__DIR__ . '/vendor/autoload.php'); Httpful\Bootstrap::init(); RESTful\Bootstrap::init(); Balanced\Bootstrap::init(); Balanced\Settings::$api_key = "ak-test-25ZY8HQwZPuQtDecrxb671LilUya5t5G0"; $callback = \Balanced\Callback::get("/callbacks/CB2xCnObyAUU1V658GVuRyCI"); $callback->unstore(); ?>
{ "content_hash": "9ce17aafeede7e8a29fc625814ba6a43", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 75, "avg_line_length": 22.214285714285715, "alnum_prop": 0.729903536977492, "repo_name": "joelgarciajr84/balanced-php", "id": "42ff7bc6d688fb3baec114ac4ce98748537e4e57", "size": "311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scenarios/callback_delete/executable.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "123482" } ], "symlink_target": "" }
import copy from hearthbreaker.cards.base import ChoiceCard, SpellCard from hearthbreaker.tags.action import Summon from hearthbreaker.tags.base import Deathrattle from hearthbreaker.tags.selector import PlayerSelector import hearthbreaker.targeting from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY class Innervate(SpellCard): def __init__(self): super().__init__("Innervate", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.FREE) def use(self, player, game): super().use(player, game) if player.mana < 8: player.mana += 2 else: player.mana = 10 class Moonfire(SpellCard): def __init__(self): super().__init__("Moonfire", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_spell_target) def use(self, player, game): super().use(player, game) self.target.damage(player.effective_spell_damage(1), self) class Claw(SpellCard): def __init__(self): super().__init__("Claw", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.FREE) def use(self, player, game): super().use(player, game) player.hero.change_temp_attack(2) player.hero.increase_armor(2) class Naturalize(SpellCard): def __init__(self): super().__init__("Naturalize", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): super().use(player, game) self.target.die(self) game.other_player.draw() game.other_player.draw() class Savagery(SpellCard): def __init__(self): super().__init__("Savagery", 1, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): super().use(player, game) self.target.damage(player.effective_spell_damage(player.hero.calculate_attack()), self) class MarkOfTheWild(SpellCard): def __init__(self): super().__init__("Mark of the Wild", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.FREE, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): super().use(player, game) self.target.change_attack(2) self.target.increase_health(2) self.target.taunt = True class LeaderOfThePack(ChoiceCard): def __init__(self): super().__init__("Leader of the Pack", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def use(self, player, game): for minion in player.minions: minion.change_attack(1) minion.increase_health(1) class SummonPanther(ChoiceCard): def __init__(self): super().__init__("Summon a Panther", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def use(self, player, game): from hearthbreaker.cards.minions.druid import Panther panther = Panther() panther.summon(player, game, len(player.minions)) def can_use(self, player, game): return super().can_use(player, game) and len(player.minions) < 7 class PowerOfTheWild(SpellCard): def __init__(self): super().__init__("Power of the Wild", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def use(self, player, game): super().use(player, game) option = player.agent.choose_option([LeaderOfThePack(), SummonPanther()], player) option.use(player, game) class WildGrowth(SpellCard): def __init__(self): super().__init__("Wild Growth", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.FREE) def use(self, player, game): super().use(player, game) if player.max_mana < 10: player.max_mana += 1 else: player.hand.append(ExcessMana()) player.hand[-1].player = player # Special card that only appears in tandem with Wild Growth class ExcessMana(SpellCard): def __init__(self): super().__init__("Excess Mana", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def use(self, player, game): super().use(player, game) player.draw() class Wrath(SpellCard): def __init__(self): super().__init__("Wrath", 2, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): class WrathOne(ChoiceCard): def __init__(self): super().__init__("Wrath 1 Damage", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): target.damage(player.effective_spell_damage(1), wrath) player.draw() class WrathThree(ChoiceCard): def __init__(self): super().__init__("Wrath 3 Damage", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): target.damage(player.effective_spell_damage(3), wrath) super().use(player, game) option = game.current_player.agent.choose_option([WrathOne(), WrathThree()], player) target = self.target wrath = self option.use(player, game) class HealingTouch(SpellCard): def __init__(self): super().__init__("Healing Touch", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.FREE, target_func=hearthbreaker.targeting.find_spell_target) def use(self, player, game): super().use(player, game) self.target.heal(player.effective_heal_power(8), self) class MarkOfNature(SpellCard): def __init__(self): super().__init__("Mark of Nature", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): class MarkOfNatureAttack(ChoiceCard): def __init__(self): super().__init__("Mark of Nature +4 Attack", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): target.change_attack(4) class MarkOfNatureHealth(ChoiceCard): def __init__(self): super().__init__("Mark of Nature +4 Health", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False, target_func=hearthbreaker.targeting.find_minion_spell_target) def use(self, player, game): target.increase_health(4) target.taunt = True super().use(player, game) target = self.target option = game.current_player.agent.choose_option([MarkOfNatureAttack(), MarkOfNatureHealth()], player) option.use(player, game) class SavageRoar(SpellCard): def __init__(self): super().__init__("Savage Roar", 3, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def use(self, player, game): super().use(player, game) for minion in player.minions: minion.change_temp_attack(2) player.hero.change_temp_attack(2) class Bite(SpellCard): def __init__(self): super().__init__("Bite", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE) def use(self, player, game): super().use(player, game) player.hero.change_temp_attack(4) player.hero.increase_armor(4) class SoulOfTheForest(SpellCard): def __init__(self): super().__init__("Soul of the Forest", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def use(self, player, game): super().use(player, game) from hearthbreaker.cards.minions.druid import Treant # Can stack as many deathrattles as we want, so no need to check if this has already been given # See http://hearthstone.gamepedia.com/Soul_of_the_Forest for minion in player.minions: minion.deathrattle.append(Deathrattle(Summon(Treant()), PlayerSelector())) class Swipe(SpellCard): def __init__(self): super().__init__("Swipe", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_enemy_spell_target) def use(self, player, game): super().use(player, game) self.target.damage(4, self) for minion in copy.copy(game.other_player.minions): if minion is not self.target: minion.damage(player.effective_spell_damage(1), self) if self.target is not game.other_player.hero: game.other_player.hero.damage(player.effective_spell_damage(1), self) class Nourish(SpellCard): def __init__(self): super().__init__("Nourish", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE) def use(self, player, game): super().use(player, game) class Gain2(ChoiceCard): def __init__(self): super().__init__("Gain 2 mana crystals", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def use(self, player, game): if player.max_mana < 8: player.max_mana += 2 player.mana += 2 else: player.max_mana = 10 player.mana += 2 class Draw3(ChoiceCard): def __init__(self): super().__init__("Draw three cards", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def use(self, player, game): player.draw() player.draw() player.draw() option = player.agent.choose_option([Gain2(), Draw3()], player) option.use(player, game) class DamageAll(ChoiceCard): def __init__(self): super().__init__("Do two damage to all enemy minions", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def use(self, player, game): for minion in copy.copy(game.other_player.minions): minion.damage(player.effective_spell_damage(2), self) class DamageOne(ChoiceCard): def __init__(self): super().__init__("Do five damage to an enemy minion", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def can_use(self, player, game): return super().can_use(player, game) and len(hearthbreaker.targeting.find_minion_spell_target( game, lambda t: t.spell_targetable())) > 0 def use(self, player, game): targets = hearthbreaker.targeting.find_minion_spell_target(game, lambda t: t.spell_targetable()) target = player.agent.choose_target(targets) target.damage(player.effective_spell_damage(5), self) class Starfall(SpellCard): def __init__(self): super().__init__("Starfall", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE) def can_use(self, player, game): return super().can_use(player, game) and len(game.other_player.minions) > 0 def use(self, player, game): super().use(player, game) option = player.agent.choose_option([DamageAll(), DamageOne()], player) option.use(player, game) class ForceOfNature(SpellCard): def __init__(self): super().__init__("Force of Nature", 5, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC) def use(self, player, game): super().use(player, game) from hearthbreaker.cards.minions.druid import Treant for i in [0, 1, 2]: treant_card = Treant() treant_card.summon(player, game, len(player.minions)) def can_use(self, player, game): return super().can_use(player, game) and len(player.minions) < 7 class Starfire(SpellCard): def __init__(self): super().__init__("Starfire", 6, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, target_func=hearthbreaker.targeting.find_spell_target) def use(self, player, game): super().use(player, game) self.target.damage(player.effective_spell_damage(5), self) player.draw() class PoisonSeeds(SpellCard): def __init__(self): super().__init__("Poison Seeds", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON) def use(self, player, game): super().use(player, game) from hearthbreaker.cards.minions.druid import PoisonSeedsTreant targets = hearthbreaker.targeting.find_minion_spell_target(game, lambda m: True) for target in targets: target.die(None) game.check_delayed() for target in targets: PoisonSeedsTreant().summon(target.player, target.game, len(target.player.minions)) class DarkWispers(SpellCard): def __init__(self): super().__init__("Dark Wispers", 6, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC) def can_use(self, player, game): return (super().can_use(player, game) and (len(player.minions) < 7 or hearthbreaker.targeting.find_minion_spell_target(game, lambda t: t.spell_targetable()) is not None)) def use(self, player, game): super().use(player, game) class Buff5(ChoiceCard): def __init__(self): super().__init__("Give a minion +5/+5 and Taunt", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def can_use(self, player, game): return hearthbreaker.targeting.find_minion_spell_target(game, lambda t: t.spell_targetable()) is not None def use(self, player, game): targets = hearthbreaker.targeting.find_minion_spell_target(game, lambda t: t.spell_targetable()) target = player.agent.choose_target(targets) target.change_attack(5) target.increase_health(5) target.taunt = True class Wisps5(ChoiceCard): def __init__(self): super().__init__("Summon 5 Wisps", 0, CHARACTER_CLASS.DRUID, CARD_RARITY.COMMON, False) def can_use(self, player, game): return len(player.minions) < 7 def use(self, player, game): from hearthbreaker.cards.minions.neutral import Wisp for i in range(0, 5): wisp = Wisp() wisp.summon(player, game, len(player.minions)) # In the official interface, both options are shown, but only one is highlighted. if len(hearthbreaker.targeting.find_minion_spell_target(game, lambda t: t.spell_targetable())) == 0: option = Wisps5() else: option = player.agent.choose_option([Wisps5(), Buff5()], player) option.use(player, game) class Recycle(SpellCard): def __init__(self): super().__init__("Recycle", 6, CHARACTER_CLASS.DRUID, CARD_RARITY.RARE, target_func=hearthbreaker.targeting.find_enemy_minion_spell_target) def use(self, player, game): super().use(player, game) player.opponent.deck.put_back(self.target) self.target.remove_from_board() class TreeOfLife(SpellCard): def __init__(self): super().__init__("Tree of Life", 9, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC) def use(self, player, game): super().use(player, game) targets = copy.copy(game.other_player.minions) targets.extend(game.current_player.minions) targets.append(game.other_player.hero) targets.append(game.current_player.hero) for target in targets: target.heal(player.effective_heal_power(target.calculate_max_health()), self) class AstralCommunion(SpellCard): def __init__(self): super().__init__("Astral Communion", 4, CHARACTER_CLASS.DRUID, CARD_RARITY.EPIC) def use(self, player, game): super().use(player, game) for card in player.hand: card.unattach() player.trigger("card_discarded", card) player.hand = [] player.max_mana = 10 player.mana = 10
{ "content_hash": "23a14f95ed42f69b37f10b136b2a0354", "timestamp": "", "source": "github", "line_count": 451, "max_line_length": 118, "avg_line_length": 36.13747228381375, "alnum_prop": 0.600809915327034, "repo_name": "danielyule/hearthbreaker", "id": "5a119995ee020da88c8f12aeb0cea519cde9bd02", "size": "16298", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "hearthbreaker/cards/spells/druid.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "1391687" } ], "symlink_target": "" }
"use strict"; const assert = require("assert"); const ngAnnotate = require("../src/ng-annotate-main"); const fs = require("fs"); const os = require("os"); const diff = require("diff"); const SourceMapConsumer = require("source-map").SourceMapConsumer; const coffee = require("coffeescript"); const convertSourceMap = require("convert-source-map"); // optionals const ngAnnotateAdfPlugin = require("../src/optionals/angular-dashboard-framework.js"); function slurp(filename) { return String(fs.readFileSync(filename)); } function time(name, fn) { const t0 = Date.now(); fn(); const t1 = Date.now(); console.log(` [${t1 - t0}ms] ${name}`); } function test(correct, got, name) { if (normalizeLineEndings(got) !== normalizeLineEndings(correct)) { const patch = diff.createPatch(name, correct, got); process.stderr.write(patch); process.exit(-1); } } function normalizeLineEndings(str) { return str.replace(/\r?\n/g, "\r\n"); } function findLineColumn(content, index) { let line = 1; let col = 0; let i = 0; for (const ch of content) { if (i === index) { return {line, col}; } if (ch === "\n") { line += 1; col = 0; } else { col += 1; } i += 1; } assert(index < content.length); } const renameOptions = [ {"from": "$a", "to": "$aRenamed"}, {"from": "$b", "to": "$bRenamed"}, {"from": "$c", "to": "$cRenamed"}, {"from": "$d", "to": "$dRenamed"}, {"from": "$e", "to": "$eRenamed"}, {"from": "$f", "to": "$fRenamed"}, {"from": "$g", "to": "$gRenamed"}, {"from": "$h", "to": "$hRenamed"}, {"from": "$i", "to": "$iRenamed"}, ]; function testSourcemap(original, got, sourcemap) { const smc = new SourceMapConsumer(sourcemap); function stringRegExp(commentText) { return new RegExp("\"" + commentText + "\""); } function functionRegExp(functionName) { return new RegExp("(function)?\\(" + functionName + "_param1, " + functionName + "_param2\\)") } function testMapping(needle) { const gotResult = needle.exec(got); if (gotResult == null) { process.stderr.write(`Couldn't find ${needle} in output source`); process.exit(-1); } const expectedResult = needle.exec(original); if (expectedResult == null) { process.stderr.write(`Couldn't find ${needle} in expected source`); process.exit(-1); } const gotPosition = findLineColumn(got, gotResult.index); const originalPosition = smc.originalPositionFor({ line: gotPosition.line, column: gotPosition.col }); const expectedPosition = findLineColumn(original, expectedResult.index); if (originalPosition.line !== expectedPosition.line || originalPosition.column !== expectedPosition.col) { const expected = `(${expectedPosition.line},${expectedPosition.col})`; const got = `(${gotPosition.line},${gotPosition.col})`; const original = `(${originalPosition.line},${originalPosition.column})`; process.stderr.write(`Sourcemap mapping error for ${needle}. Expected: ${expected} => ${got}. Got: ${original} => ${got}.`); process.exit(-1); } } testMapping(stringRegExp("before")); for (let i = 1; i <= 4; i++) { testMapping(functionRegExp("ctrl" + i)); testMapping(stringRegExp("ctrl" + i + " body")); } testMapping(stringRegExp("after")); } function run(ngAnnotate) { const original = slurp("tests/original.js"); console.log("testing adding annotations"); const annotated = ngAnnotate(original, {add: true}).src; test(slurp("tests/with_annotations.js"), annotated, "with_annotations.js"); console.log("testing adding annotations with arrow functions"); const arrowFunctions = slurp("tests/arrow-functions.js"); const arrowFunctionsAnnotated = ngAnnotate(arrowFunctions, {add: true}).src; test(slurp("tests/arrow-functions.annotated.js"), arrowFunctionsAnnotated, "arrow-functions.annotated.js"); const rename = slurp("tests/rename.js"); console.log("testing adding annotations and renaming"); const annotatedRenamed = ngAnnotate(rename, { add: true, rename: renameOptions, }).src; test(slurp("tests/rename.annotated.js"), annotatedRenamed, "rename.annotated.js"); console.log("testing removing annotations"); test(original, ngAnnotate(annotated, {remove: true}).src, "original.js"); console.log("testing adding annotations twice"); test(annotated, ngAnnotate(annotated, {add: true}).src, "with_annotations.js"); console.log("testing rebuilding annotations"); test(annotated, ngAnnotate(annotated, {add: true, remove: true}).src, "with_annotations.js"); console.log("testing adding existing $inject annotations (no change)"); test(slurp("tests/has_inject.js"), ngAnnotate(slurp("tests/has_inject.js"), {add: true}).src); console.log("testing removing existing $inject annotations"); test(slurp("tests/has_inject_removed.js"), ngAnnotate(slurp("tests/has_inject.js"), {remove: true}).src); console.log("testing sourcemaps"); const originalSourcemaps = slurp("tests/sourcemaps.coffee"); const compiledSourcemaps = coffee.compile(originalSourcemaps, { sourceFiles: ["sourcemaps.coffee"], generatedFile: "sourcemaps.js", sourceMap: true }); const annotatedSourcemaps = ngAnnotate(compiledSourcemaps.js, {remove: true, add: true, map: { sourceRoot: "/source/root/dir" }}); test(slurp("tests/sourcemaps.annotated.js"), annotatedSourcemaps.src, "sourcemaps.annotated.js"); testSourcemap(compiledSourcemaps.js, annotatedSourcemaps.src, annotatedSourcemaps.map); console.log("testing sourcemap combination"); const inlinedCompiledSourcemaps = compiledSourcemaps.js + os.EOL + convertSourceMap.fromJSON(compiledSourcemaps.v3SourceMap).toComment(); const combinedSourcemaps = ngAnnotate(inlinedCompiledSourcemaps, {remove: true, add: true, map: { inline: true, inFile: "sourcemaps.js", sourceRoot: "/source/root/dir" }}); const combinedSourcemapsSrc = convertSourceMap.removeMapFileComments(combinedSourcemaps.src); const combinedSourcemapsMap = convertSourceMap.fromSource(combinedSourcemaps.src).toJSON(); testSourcemap(originalSourcemaps, combinedSourcemapsSrc, combinedSourcemapsMap); const ngminOriginal = slurp("tests/ngmin-tests/ngmin_original.js"); console.log("testing adding annotations (imported tests)"); const ngminAnnotated = ngAnnotate(ngminOriginal, {add: true, regexp: "^myMod"}).src; test(slurp("tests/ngmin-tests/ngmin_with_annotations.js"), ngminAnnotated, "ngmin_with_annotations.js"); console.log("testing removing annotations (imported tests)"); test(ngminOriginal, ngAnnotate(ngminAnnotated, {remove: true, regexp: "^myMod"}).src, "ngmin_original.js"); // TODO generic test-runner code for finding and testing all optionals automatically // optionals angular-dashboard-framework adding annotations console.log("testing optionals/angular-dashboard-framework.js (adding annotations)"); const adf = slurp("tests/optionals/angular-dashboard-framework.js"); const adfAnnotated = ngAnnotate(adf, {add: true, plugin: [ngAnnotateAdfPlugin]}).src; test(slurp("tests/optionals/angular-dashboard-framework.annotated.js"), adfAnnotated, "optionals/angular-dashboard-framework.annotated.js"); // optionals angular-dashboard-framework removing annotations console.log("testing optionals/angular-dashboard-framework.js (removing annotations)"); test(adf, ngAnnotate(adfAnnotated, {remove: true, plugin: [ngAnnotateAdfPlugin]}).src, "optionals/angular-dashboard-framework.js"); // issue #3 (ng-annotate-patched) - Support for ES6 Classes console.log("testing es6 classes"); const es6Classes = slurp("tests/es6-classes.js"); const es6ClassesAnnotated = ngAnnotate(es6Classes, {add: true}).src; test(slurp("tests/es6-classes.annotated.js"), es6ClassesAnnotated, "tests/es6-classes.annotated.js"); console.log("testing performance"); const ng1 = String(fs.readFileSync("tests/angular.js")); // const ng5 = ng1 + ng1 + ng1 + ng1 + ng1; time("ng1", function() { ngAnnotate(ng1, {add: true}) }); time("ng1 with sourcemaps", function() { ngAnnotate(ng1, {add: true, map: true}) }); //time(" ng5 processed in {0} ms", function() { ngAnnotate(ng5, {add: true}) }); //time(" ng5 processed with sourcemaps in {0} ms", function() { ngAnnotate(ng5, {add: true, map: true}) }); console.log("all ok"); } run(ngAnnotate);
{ "content_hash": "089ec99909ae48490b541c3c58bdef74", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 176, "avg_line_length": 42.81372549019608, "alnum_prop": 0.666017861231967, "repo_name": "bluetech/ng-annotate-patched", "id": "f6204bb104fdd266b6e2cc824300032e034d049e", "size": "8848", "binary": false, "copies": "1", "ref": "refs/heads/fork", "path": "tests/run-tests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "400" }, { "name": "JavaScript", "bytes": "249415" } ], "symlink_target": "" }
from django.shortcuts import render def home(request): return render( request, "main.html", {} ) def log_in(request): return render( request, "main.html", {} ) def log_out(request): request.session.flush() return render(request, 'logout.html', {}) def test(request): x = request.session['meetup_session'] y = x.get('2/member/self', params={'page': '20'}) r = x.get('2/groups', params={'group_id': 1606258}) return render( request, "main.html", {} )
{ "content_hash": "2034fa71b53dfa17f20011a54a1bab64", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 55, "avg_line_length": 16.4, "alnum_prop": 0.5348432055749129, "repo_name": "joeybrown/MeetupRestApp", "id": "b0dd4037fd3e6cadd824ac63112c15a78c72976e", "size": "574", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "App/views.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "435293" }, { "name": "JavaScript", "bytes": "1724947" }, { "name": "Python", "bytes": "13137" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DND.Services.Skyscanner.Model { public partial class Segment { public int Id { get; set; } public int OriginStation { get; set; } public int DestinationStation { get; set; } public string DepartureDateTime { get; set; } public string ArrivalDateTime { get; set; } public int Carrier { get; set; } public int OperatingCarrier { get; set; } public int Duration { get; set; } public string FlightNumber { get; set; } public string JourneyMode { get; set; } public string Directionality { get; set; } } }
{ "content_hash": "f02b5bcc5d9a34bbb1f1d36b85dbce63", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 53, "avg_line_length": 31.695652173913043, "alnum_prop": 0.6419753086419753, "repo_name": "davidikin45/DigitalNomadDave", "id": "9f8a883842128ca5e59071c346f46aca57e1c5d6", "size": "731", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DND.Services/Skyscanner/Model/Segment.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "94" }, { "name": "Batchfile", "bytes": "351" }, { "name": "C#", "bytes": "1699602" }, { "name": "CSS", "bytes": "87216" }, { "name": "HTML", "bytes": "27831" }, { "name": "JavaScript", "bytes": "382201" }, { "name": "Makefile", "bytes": "316" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "1030" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Gimnasio Polideportivo Recoleta - Condor Rojas</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="<?php echo base_url();?>assets/vendor/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="<?php echo base_url();?>assets/vendor/bootstrap/css/bootstrap-social.css"> <script type="text/javascript"> $('#myModal').on('shown.bs.modal', function () { $('#myInput').focus() }) </script> </head> <body style="background-image: url('<?php echo base_url();?>images/CANCHA.png'); background-attachment: fixed; background-position: center;"> <header> <div class="container"> <h1>Gimnasio Polideportivo Recoleta - Condor Rojas</h1> </div> </header> <div class="container"> <!-- Botonera --> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <ul class="nav navbar-nav"><li><a class="navbar-brand" href="<?php echo base_url();?>index.php">Inicio</a></li></ul> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Recintos<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="<?php echo base_url();?>index.php/condor">Condor Rojas Norte</a></li> <li><a href="<?php echo base_url();?>index.php/phelps">El Phelps</a></li> <li><a href="<?php echo base_url();?>index.php/massu">Massu</a></li> <li><a href="<?php echo base_url();?>index.php/nba">NBA</a></li> </ul> <li><a href="<?php echo base_url();?>index.php/contacto">Contacto</a></li> </li> </ul> <ul class="nav navbar-nav navbar-right"> <?php if($this->session->userdata('logueado')){?> <a class="btn btn-default navbar-btn" href="<?php echo base_url();?>index.php/reserva">Reservas</a> <a href="<?php echo base_url();?>index.php/logout">Cerrar Sesion</a> <?php } else { ?> <a class="btn btn-default navbar-btn" href="<?php echo base_url();?>index.php/login">Iniciar sesion</a> <?php } ?> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <!--Fin Botonera--> <!--Contenido--> <div class="main row"> <div class="text-center col-md-12"> <h2>Condor Rojas Norte</h2> <div class="col-md-offset-3 col-md-6" align="left" > <p> <h3>Condor Rojas Norte</h3> Recinto dedicado para la practica del futbol-sala en la Comuna de Recoleta <h4>Encargo: Juan Soto</h4> <h4>Equipamiento</h4> <ul> <li> Posee de canchas de superficie sintetica con dimensiones de 20 x 40 mts </li> <li>Capacidad 23.456 personas sentadas </li> <li>6 camarines para los equipos </li> <li>4 camarines para los arbitros</li> </ul> <h4>Informaciones: +56 9 3487 7623</h4> </p> </div> </div> <!--Imagen--> <div class="text-center col-xs-12 col-sm-6 col-md-6 col-lg-6"> <img src="<?php echo base_url(); ?>images/football.jpg"> </div> <!-- Canchas --> <div class="text-center col-xs-12 col-sm-6 col-md-6 col-lg-6"> <p><br> <h2>Football</h2> <h3>Horario</h3> Lunes-Martes: 10:00-15:30hrs<br> Miercoles-Viernes: 11:00-19:30hrs<br> Sabado: 10:30-16:30hrs </p> </div> </div> <div class="main row"> <!--Imagen--> <div class="text-center col-xs-12 col-sm-6 col-md-6 col-lg-6"> <img src="<?php echo base_url(); ?>images/football.jpg"> </div> <!-- Calendario --> <div class="text-center col-xs-12 col-sm-6 col-md-6 col-lg-6"> <p><br> <h2>Football2</h2> <h3>Horario</h3> Lunes-Martes: 10:00-14:00hrs<br> Miercoles-Viernes: 12:00-19:00hrs<br> Sabado: 10:00-15:00hrs </p> </div> </div> <!--Fin Contenido--> <!--Footer--> <div class="footer text-center col-lg-12"> <h4>&copy; Todos los derechos reservados.<br>Valparaiso, Chile.<br>2017</h4> </div> </div> <div id="reservas" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="gridSystemModalLabel">Reservas</h4> </div> <div class="modal-body"> <div class="row col-md-12"> <form> <div class="form-group"> <label>*Nombre Completo</label> <input type="text" class="form-control" id="exampleInputName1" placeholder="Nombre"> </div> <div class="form-group"> <label for="exampleInputEmail1">*Email</label> <input type="email" class="form-control" id="exampleInputPassword1" placeholder="Email"> </div> </form> </div> <div class="row col-md-12"> <label>*Recinto</label> <select class="form-control"> <option>Elija una opcion...</option> <option>Condor Rojas Norte</option> <option>El Phelps</option> <option>Massu</option> <option>NBA</option> </select><br> </div> <div class="row col-md-4"> <label>*Dia</label> <select class="form-control"> <option>Elija una opcion...</option> <option>Lunes</option> <option>Martes</option> <option>Miercoles</option> <option>Jueves</option> <option>Viernes</option> <option>Sabado</option> </select><br> </div> <div class="row col-md-offset-1 col-md-4"> <label>*Hora</label> <select class="form-control"> <option>Elija una opcion...</option> <option>10:00hrs</option> <option>11:00hrs</option> <option>12:00hrs</option> <option>13:00hrs</option> <option>14:00hrs</option> <option>15:00hrs</option> <option>16:00hrs</option> <option>17:00hrs</option> <option>18:00hrs</option> <option>19:00hrs</option> </select><br> </div> </div> <div class="modal-footer"> <div class="col-sm-12"> <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button> <button type="submit" class="btn btn-primary">Enviar</button> </div> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> <script src="<?php echo base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script src="<?php echo base_url(); ?>assets/vendor/bootstrap/js/bootstrap.min.js"></script> </body> </html>
{ "content_hash": "f52edc8fe3071c51504cf72669cd39d1", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 190, "avg_line_length": 40.5735294117647, "alnum_prop": 0.5286939712456203, "repo_name": "grupoku/GitHub1", "id": "2cf5a0e01ba11874d6f61c50c57c9756bda909b7", "size": "8277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fis/application/views/condor.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "35403" }, { "name": "HTML", "bytes": "8981088" }, { "name": "JavaScript", "bytes": "103395" }, { "name": "PHP", "bytes": "1835366" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2012 Sonatype, Inc. ~ All rights reserved. This program and the accompanying materials ~ are made available under the terms of the Eclipse Public License v1.0 ~ which accompanies this distribution, and is available at ~ http://www.eclipse.org/legal/epl-v10.html ~ ~ Contributors: ~ Sonatype, Inc. - initial API and implementation --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.eclipse.aether</groupId> <artifactId>aether-update-site</artifactId> <version>1.0.1.v20141111</version> </parent> <artifactId>org.eclipse.aether.feature</artifactId> <packaging>eclipse-feature</packaging> </project>
{ "content_hash": "1e58c74a3b3baa1eb105baae4da3aae2", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 204, "avg_line_length": 36.36, "alnum_prop": 0.7194719471947195, "repo_name": "TitasNandi/Summer_Project", "id": "2c9905ad71283f7124e928ccf6c0e11a8be12465", "size": "909", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "eclipse/features/org.eclipse.aether.feature_1.0.1.v20141111/META-INF/maven/org.eclipse.aether/org.eclipse.aether.feature/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "291" }, { "name": "Batchfile", "bytes": "119331" }, { "name": "C", "bytes": "620" }, { "name": "CSS", "bytes": "746530" }, { "name": "Groff", "bytes": "8389332" }, { "name": "Groovy", "bytes": "887" }, { "name": "HTML", "bytes": "84461564" }, { "name": "Java", "bytes": "22523686" }, { "name": "JavaScript", "bytes": "1254038" }, { "name": "Jupyter Notebook", "bytes": "413571" }, { "name": "Makefile", "bytes": "4287" }, { "name": "Perl", "bytes": "15597" }, { "name": "Python", "bytes": "1888984" }, { "name": "Shell", "bytes": "177570" }, { "name": "XQuery", "bytes": "11244" }, { "name": "XSLT", "bytes": "390648" } ], "symlink_target": "" }
package uploadService // FileForm is used when creating or updating a file. type FileForm struct { Id int64 `form:"id"` UserId int64 `form:"userId"` Name string `form:"name" binding:"required"` Size int `form:"size" binding:"required"` } // FilesForm is used when creating or updating multiple files. type FilesForm struct { Files []FileForm `form:"json" binding:"required"` }
{ "content_hash": "dc1b16ccbcb21ce2a9067317fdde4953", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 62, "avg_line_length": 28.357142857142858, "alnum_prop": 0.707808564231738, "repo_name": "tka/goyangi", "id": "b5471e2bc31d37692b061b835b3b29ef5088d1ce", "size": "397", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "service/uploadService/form.go", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "29947" }, { "name": "CSS", "bytes": "669374" }, { "name": "Go", "bytes": "265644" }, { "name": "HTML", "bytes": "411028" }, { "name": "JavaScript", "bytes": "1334314" }, { "name": "Shell", "bytes": "945" } ], "symlink_target": "" }
name "github.com/gsmake/clang" plugin "github.com/gsmake/lua"
{ "content_hash": "2fcf00c406f926f9565e93e6c666e537", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 30, "avg_line_length": 13, "alnum_prop": 0.7384615384615385, "repo_name": "gsmake/gsmake", "id": "93945ccd1c6be8668260fee161476b93ad10f3e5", "size": "65", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/gsmake/plugin/github.com/gsmake/clang/.gsmake.lua", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6439037" }, { "name": "C++", "bytes": "561390" }, { "name": "CMake", "bytes": "4042" }, { "name": "Lua", "bytes": "131006" }, { "name": "Smarty", "bytes": "3413" } ], "symlink_target": "" }
<?php /** * @author Vojta Biberle * @since 12.1.15 */ namespace QueueManager\Adapter; use QueueManager\IAdapter; use QueueManager\Utils; class Mongo implements IAdapter { private $dsn = null; private $dataDatabase = null; /** * @var \MongoClient $client */ private $client = null; /** * @var \MongoDB $collection */ private $db = null; /** * @var \MongoCollection $collection */ private $collection = null; /** * @param string $dsn */ public function __construct($dsn, $dataDatabase = null) { $this->dsn = $dsn; $this->dataDatabase = $dataDatabase; } /** * Method must make connection to DB, when disconnect. * * @author Vojta Biberle * */ public function connect() { if(is_null($this->client)) { $this->client = new \MongoClient($this->dsn); $parsedDsn = Utils::ParseDsn($this->dsn); if(is_null($this->dataDatabase)) { $this->db = $this->client->{$parsedDsn['database']}; }else{ $this->db = $this->client->{$this->dataDatabase}; } //$this->collection = $this->client->selectCollection($this->dsn['database'], $this->dsn['table']); } } /*public function setCollection($name) { $this->collection = $this->db->{$name}; }*/ /** * Check if adapter is connected. * * @author Vojta Biberle * * @return bool */ public function isConnected() { return !is_null($this->client); } public function insert($collection, $data, $options = []) { $this->connect(); return $this->db->{$collection}->insert($data, $options); } public function update($collection, $criteria, $data, $options = []) { $this->connect(); return $this->db->{$collection}->update($criteria, $data, $options); } public function count($collection, $query = []) { $this->connect(); return $this->db->{$collection}->count($query); } public function remove($collection, $criteria = [], $options = []) { $this->connect(); return $this->db->{$collection}->remove($criteria, $options); } public function drop($collection) { $this->connect(); return $this->db->{$collection}->drop(); } public function find($collection, $query = [], $fields = []) { $this->connect(); return $this->db->{$collection}->find($query, $fields); } public function findOne($collection, $query = [], $fields = []) { $this->connect(); return $this->db->{$collection}->findOne($query, $fields); } public function findAndModify($collection, $query = [], $update = [], $fields = [], $options = []) { $this->connect(); return $this->db->{$collection}->findAndModify($query, $update, $fields, $options); } }
{ "content_hash": "d0e0047dfbf9e09b4bb4953ddfc5ed9d", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 111, "avg_line_length": 23.944444444444443, "alnum_prop": 0.5316539608882996, "repo_name": "vojtabiberle/QueueRunner", "id": "c5b2ad193409c732dee21735f52dbca1fc0fd1df", "size": "3017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/QueueManager/Adapter/Mongo.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "63693" }, { "name": "Perl", "bytes": "733" }, { "name": "Shell", "bytes": "1675" } ], "symlink_target": "" }
layout : default type : content title : Cookie policy date : 2016-06-01 permalink : /cookie-policy/ --- Mediasmart’s website uses “session cookies” for, amongst others, the purpose of permitting and enabling the identification of users and their interaction with the website. Furthermore, the statistical services of Mediasmart -or third parties’- used by Mediasmart’s website may use “cookies” for the purpose of establishing metrics and patterns of site usage and for other reasons. ## What are “cookies”? A “cookie” is a small text file that your computer downloads when you access certain websites. Cookies allow websites to store and retrieve information over the web surfing habits of an individual or her computer and depending on the kinds of information that they may store, they can be used to help the website identify the user. What sort of cookies does Mediasmart use? Session cookies: They keep the user identified before the website, helping her interaction with it. Language: Name: pll_language Web: mediasmart.es Type: Session cookie Description: Used for website usability Notice: Name: cdp-cookies-plugin-wp Web: mediasmart.es Type: Cookie usage notice Description: Used for cookie usage notice You can configure your browser to allow, block or delete cookies from websites. Most browsers offer help for cookie settings in the Help menu. You can also find specific information about configuring your cookie preferences through the following links: - [Firefox](http://support.mozilla.org/es/kb/habilitar-y-deshabilitar-cookies-que-los-sitios-we) - [Chrome](https://support.google.com/accounts/answer/61416?hl=es) - [Internet Explorer]( http://windows.microsoft.com/es-es/windows7/how-to-manage-cookies-in-internet-explorer-9) - [Safari](http://support.apple.com/kb/ph5042) - [Opera](http://help.opera.com/Windows/11.50/es-ES/cookies.html) ## Data gathered through Mediasmart Console mediasmart is the programmatic media buying platform that mediasmart uses to serve mobile advertising campaigns in its network of supply partners. mediasmart does not gather personal data of users who see mediasmart ads. On the contrary, it only gathers non personal information that cannot be used to univocally identify a user, for example, IP address, mobile carrier, connection type (WiFi vs 3G), advertising ID (IDFA and GAID) or operating system. The information gathered is used to serve more relevant advertising, making advertising more effective and helping many applications and websites to monitize, so that they can offer free content and services. In some cases, we can also use the obtained information to combine it with non personal information from third parties and improve mediasmart´s capabiities. For example, thanks to the IO and a third party database, we can infer the región a user is seeing an ad in. Aggregated information, never individual, can be shared with our clients and our suppliers for business purposes, such as reporting, invoicing, etc… mediasmart shall also share user data if so required by law. Or to share with a related entity as a result of a corporate transaction, such as a merger, an acquisition, total or parcial asset sale, bankrupcy, etc… mediasmart uses cookies and other similar storage methods to identify users and offer them interest-based advertising. In compliance with article 22 of the LSSI, mediasmart´s supply partners shall get agreement from their publishers to inform their users that, in case they accept in the corresponding checkbox, those storage devices will be used. At mediasmart we commit to respecting the user selection and we do not use any storage device that can ignore the privacy options defined by the user in her device. Cookie list: Ads Mediasmart: Name: ms_udid_token & ms_udid_imp Web: ads.mediasmart.es Type: Cookie publicitaria Description: Used for interest based advertising How to Opt Out of Interest-based Advertising Your iOS or Android mobile device may provide a “Limit Ad Tracking” or “Opt out of interest-based advertising” setting. When you have opted out using this setting on a device, Mediasmart will not use information collected from that device to infer your interests or serve ads to that device that are targeted based on your inferred interests. Mediasmart requires its advertising customers to honor opt-out preferences expressed using these controls. You can find the setting for your mobile device by following the directions below. iOS Device iOS 7 or Higher Go to your Settings > Select Privacy > Select Advertising > Enable the “Limit Ad Tracking” setting iOS 6 Go to your Settings >Select General > Select About > Select Advertising > Enable the “Limit Ads Tracking” setting More information about the iOS setting can be found here. Android Device For Android devices with OS 2.2 and up and Google Play Services version 4.0 and up: Open your Google Settings app > Ads > Enable “Opt out of interest-based advertising” If you’ve turned on Limit Ad Tracking on your iOS device or the Opt out of interest-based ads on your Android device, you can restore interest-based ads by turning the settings off. When you opt out, you may still see the same number of ads from Mediasmart on your mobile device; however, these ads may be less relevant because they won’t be based on your interests. Mediasmart may continue to serve you ads based on other non-personal information, such as ads related to the content of the application you are using.
{ "content_hash": "91e97ae6bcaae342b7631740a9423aa9", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 512, "avg_line_length": 80.95588235294117, "alnum_prop": 0.7965485921889192, "repo_name": "mediasmart/site", "id": "0f0a8a4eb05caa6942bfc48aa8ba735c69e01bd9", "size": "5562", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "cookie-policy/index.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "34987" }, { "name": "HTML", "bytes": "33668" }, { "name": "JavaScript", "bytes": "2395" }, { "name": "Ruby", "bytes": "6778" } ], "symlink_target": "" }
'use strict'; var forms = require('../forms'); var helpers = require('../helpers'); /** * This controller initializes the 'password reset' workflow for a user who has * forgotten his password. * * This will render a view, which prompts the user for their email address, then * sends a password reset email. * * The URL this controller is bound to, and the view used to render this page * can all be controlled via express-stormpath settings. * * @method * * @param {Object} req - The http request. * @param {Object} res - The http response. * @param {function} next - The next callback. */ module.exports = function (req, res, next) { var application = req.app.get('stormpathApplication'); var config = req.app.get('stormpathConfig'); var logger = req.app.get('stormpathLogger'); var view = config.web.forgotPassword.view; res.locals.status = req.query.status; helpers.handleAcceptRequest(req, res, { 'application/json': function () { if (req.method !== 'POST') { return next(); } return application.sendPasswordResetEmail(req.body.email, function (err) { if (err) { logger.info('A user tried to reset their password, but supplied an invalid email address: ' + req.body.email + '.'); } res.end(); }); }, 'text/html': function () { if (req.method !== 'GET' && req.method !== 'POST') { return next(); } var formActionUri = config.web.forgotPassword.uri; return helpers.organizationResolutionGuard(req, res, formActionUri, function () { forms.forgotPasswordForm.handle(req, { // If we get here, it means the user is submitting a password reset // request, so we should attempt to send the user a password reset email. success: function (form) { var data = { email: form.data.email }; if (req.organization) { data.accountStore = { href: req.organization.href }; } application.sendPasswordResetEmail(data, function (err) { if (err) { logger.info('A user tried to reset their password, but supplied an invalid email address: ' + form.data.email + '.'); } res.redirect(config.web.forgotPassword.nextUri); }); }, // If we get here, it means the user didn't supply required form fields. error: function (form) { var viewData = { form: form, organization: req.organization }; // https://github.com/caolan/forms/issues/96 if (req.query.status === 'invalid_sptoken') { viewData.status = req.query.status; return helpers.render(req, res, view, viewData); } viewData.formErrors = helpers.collectFormErrors(form); helpers.render(req, res, view, viewData); }, // If we get here, it means the user is doing a simple GET request, so we // should just render the forgot password template. empty: function (form) { helpers.render(req, res, view, { form: form, organization: req.organization }); } }); }); } }, next); };
{ "content_hash": "1acb1e7422744c0d04d7fda3a53e4c8c", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 133, "avg_line_length": 33.29, "alnum_prop": 0.5815560228296786, "repo_name": "nikhil-ahuja/Express-React", "id": "c325f21c84ee7af8cfde6a016b458b4f4ea196c6", "size": "3329", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node_modules/express-stormpath/lib/controllers/forgot-password.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12358" }, { "name": "HTML", "bytes": "707" }, { "name": "JavaScript", "bytes": "45659" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="Matt Makai"> <meta name="description" content="Full Stack Python explains each layer of the web application stack, from the server up through the rendering in a user's browser."> <link rel="shortcut icon" href="theme/img/fsp-fav.png"> <title>Web Servers - Full Stack Python</title> <link href="theme/css/fsp.css" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.css" rel="stylesheet"> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-19910497-7']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <a href="https://github.com/makaimc/fullstackpython.github.com" class="github"> <img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /> </a> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="logo-header-section"> <a href="/" style="text-decoration: none; border: none;"><img src="theme/img/fsp-logo.png" height="52" width="52" class="logo-image" style="padding-top: 1px;"/></a> <span class="logo-title"><a href="/">Full Stack Python</a></span> </div> </div> </div> <div class="row"> <div class="col-md-8"> <h1>Web servers</h1> <p>Web servers respond to <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol">Hypertext Transfer Protocol</a> (HTTP) requests from clients and send back a response containing a status code and often content such as HTML, XML or JSON as well.</p> <h2>Why are web servers necessary?</h2> <p>Web servers are the ying to the web client's yang. The server and client speak the standardized language of the World Wide Web. This standard language is why an old Mozilla Netscape browser can still talk to a modern Apache or Nginx web server, even if it cannot properly render the page design like a modern web browser can. </p> <p>The basic language of the Web with the request and response cycle from client to server then server back to client remains the same as it was when the Web was invented by <a href="http://www.w3.org/People/Berners-Lee/">Tim Berners-Lee</a> at CERN in 1989. Modern browsers and web servers have simply extended the language of the Web to incorporate new standards.</p> <h2>Client requests</h2> <p>A client that sends a request to a web server is usually a browser such as Internet Explorer, Firefox, or Chrome, but it can also be a</p> <ul> <li>headless browser, commonly use for testing, such as <a href="http://phantomjs.org/">phantomjs</a></li> <li>commandline utility, for example <a href="https://www.gnu.org/software/wget/">wget</a> and <a href="http://curl.haxx.se/">curl</a></li> <li>text-based web browser such as <a href="http://lynx.browser.org/">Lynx</a></li> <li>web crawler. </li> </ul> <p>Web server process requests from the above clients. The result of the web server's processing is a <a href="https://developer.mozilla.org/en-US/docs/HTTP/Response_codes">response code</a> and commonly a content response. Some status codes, such as 204 (No content) and 403 (Forbidden), do not have content responses.</p> <p>In a simple case, the client will request a static asset such as a picture or JavaScript file. The file sits on the file system in a location the web server is authorized to access and the web server sends the file to the client with a 200 status code. If the client already requested the file and the file has not changed, the web server will pass back a 304 "Not modified" response indicating the client already has the latest version of that file.</p> <p><img src="theme/img/web-browser-server-requests.png" width="100%" class="technical-diagram" alt="Web server and web browser request-response cycle" /></p> <p>A web server sends files to a web browser based on the web browser's request. In the first request, the browser accessed the "www.fullstackpython.com" address and the server responded with the index.html HTML-formatted file. That HTML file contained references to other files, such as style.css and script.js that the browser then requested from the server.</p> <p>Sending static assets (such as CSS and JavaScript files) can eat up a large amount of bandwidth which is why using a Content Delivery Network (CDN) is important when possible (see the content delivery network section for a more detailed explanation).</p> <h2>Web server resources</h2> <ul> <li> <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP/1.1 Specification</a></p> </li> <li> <p><a href="http://arstechnica.com/gadgets/2012/11/how-to-set-up-a-safe-and-secure-web-server/">How to set up a safe and secure Web server</a></p> </li> <li> <p><a href="http://library.linode.com/web-servers/apache/mod-wsgi/ubuntu-10.04-lucid">Apache and mod_wsgi on Ubuntu 10.04</a></p> </li> <li> <p><a href="http://articles.slicehost.com/nginx">Nginx web server tutorials</a></p> </li> <li> <p><a href="http://carrot.is/coding/nginx_introduction">Nginx for Developers: An Introduction</a></p> </li> <li> <p>An example of an <a href="http://tautt.com/best-nginx-configuration-for-security/">Nginx security configuration</a>.</p> </li> <li> <p>A reference with the full list of <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">HTTP status codes</a> is provided by W3C.</p> </li> <li> <p>An optimization guide for "<a href="http://blog.zachorr.com/nginx-setup/">battle ready Nginx</a>."</p> </li> <li> <p><a href="http://arstechnica.com/business/2011/11/a-faster-web-server-ripping-out-apache-for-nginx/">A faster Web server: ripping out Apache for Nginx</a></p> </li> <li> <p><a href="http://ibuildings.nl/blog/2013/03/4-http-security-headers-you-should-always-be-using">4 HTTP Security Headers You Should Always Be Using</a></p> </li> </ul> <h2>Web servers learning checklist</h2> <p><i class="fa fa-check-square-o"></i> Choose a web server. <a href="http://nginx.org/en/">Nginx</a> is recommended although <a href="http://httpd.apache.org/">Apache</a> is also a great choice.</p> <p><i class="fa fa-check-square-o"></i> Create an SSL certificate. For testing use a self-signed certificate and for a production app buy one from <a href="http://www.digicert.com/">Digicert</a>. Configure the web server to serve traffic over SSL. You'll need SSL for serving only HTTPS traffic and preventing security issues that occur with unencrypted user input.</p> <p><i class="fa fa-check-square-o"></i> Configure the web server to serve up static files such as CSS, JavaScript and images.</p> <p><i class="fa fa-check-square-o"></i> Once you set up the <a href="/wsgi-servers.html">WSGI server</a> you'll need to configure the web server as a pass through for dynamic content.</p> <h3>What do you want to learn after the web server is set up?</h3> <div class="row"> <div class="col-md-3"> <div class="well select-next"> <a href="/wsgi-servers.html" class="btn btn-success btn-full"><i class="fa fa-play fa-inverse fa-2x"></i></a> <p class="under-btn"> How do I execute Python since the web server doesn't do that? </p> </div> </div> <div class="col-md-3"> <div class="well select-next"> <a href="/application-dependencies.html" class="btn btn-success btn-full"><i class="fa fa-archive fa-inverse fa-2x"></i></a> </a> <p class="under-btn"> How should I install Python libraries on the server? </p> </div> </div> <div class="col-md-3"> <div class="well select-next"> <a href="/static-content.html" class="btn btn-success btn-full"><i class="fa fa-spinner fa-2x"></i></a> <p class="under-btn"> What other ways can be used to host static content? </p> </div> </div> <div class="col-md-3"> <div class="well select-next"> <a href="/platform-as-a-service.html" class="btn btn-success btn-full"><i class="fa fa-puzzle-piece fa-inverse fa-2x"></i></a> <p class="under-btn"> Forget servers. Tell me about platforms-as-a-service. </p> </div> </div> </div> <style type="text/css"> #mc_embed_signup{background:#fff; clear:left; font:12px "Helvetica Neue",Arial,sans-serif; } /* Add your own MailChimp form style overrides in your site stylesheet or in this style block. We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */ </style> <hr/> <div id="mc_embed_signup"> <form action="http://mattmakai.us2.list-manage.com/subscribe/post?u=b7e774f0c4f05dcebbfee183d&amp;id=b22335388d" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate> <h4>Interested in a complete Full Stack Python book with detailed tutorials and example code? Sign up here and you'll get an alert email if a book is created. No other emails will be sent other than sign up confirmation.</h4> <div class="row"> <div class="col-md-9"> <label for="mce-EMAIL">Email Address</label> <input type="email" value="" name="EMAIL" class="required email form-control" id="mce-EMAIL"> </div> <div class="col-md-3"> <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="btn btn-success" style="margin-top: 20px;"> </div> <div id="mce-responses" class="clear"> <div class="response" id="mce-error-response" style="display:none"></div> <div class="response" id="mce-success-response" style="display:none"></div> </div> <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups--> <div style="position: absolute; left: -5000px;"><input type="text" name="b_b7e774f0c4f05dcebbfee183d_b22335388d" value=""></div> </div> </form> </div> <script type="text/javascript"> var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text'; try { var jqueryLoaded=jQuery; jqueryLoaded=true; } catch(err) { var jqueryLoaded=false; } var head= document.getElementsByTagName('head')[0]; if (!jqueryLoaded) { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'; head.appendChild(script); if (script.readyState && script.onload!==null){ script.onreadystatechange= function () { if (this.readyState == 'complete') mce_preload_check(); } } } var err_style = ''; try{ err_style = mc_custom_error_style; } catch(e){ err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}'; } var head= document.getElementsByTagName('head')[0]; var style= document.createElement('style'); style.type= 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = err_style; } else { style.appendChild(document.createTextNode(err_style)); } head.appendChild(style); setTimeout('mce_preload_check();', 250); var mce_preload_checks = 0; function mce_preload_check(){ if (mce_preload_checks>40) return; mce_preload_checks++; try { var jqueryLoaded=jQuery; } catch(err) { setTimeout('mce_preload_check();', 250); return; } var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js'; head.appendChild(script); try { var validatorLoaded=jQuery("#fake-form").validate({}); } catch(err) { setTimeout('mce_preload_check();', 250); return; } mce_init_form(); } function mce_init_form(){ jQuery(document).ready( function($) { var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){} }; var mce_validator = $("#mc-embedded-subscribe-form").validate(options); $("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator options = { url: 'http://mattmakai.us2.list-manage.com/subscribe/post-json?u=b7e774f0c4f05dcebbfee183d&id=b22335388d&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8", beforeSubmit: function(){ $('#mce_tmp_error_msg').remove(); $('.datefield','#mc_embed_signup').each( function(){ var txt = 'filled'; var fields = new Array(); var i = 0; $(':text', this).each( function(){ fields[i] = this; i++; }); $(':hidden', this).each( function(){ var bday = false; if (fields.length == 2){ bday = true; fields[2] = {'value':1970};//trick birthdays into having years } if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){ this.value = ''; } else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){ this.value = ''; } else { if (/\[day\]/.test(fields[0].name)){ this.value = fields[1].value+'/'+fields[0].value+'/'+fields[2].value; } else { this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value; } } }); }); $('.phonefield-us','#mc_embed_signup').each( function(){ var fields = new Array(); var i = 0; $(':text', this).each( function(){ fields[i] = this; i++; }); $(':hidden', this).each( function(){ if ( fields[0].value.length != 3 || fields[1].value.length!=3 || fields[2].value.length!=4 ){ this.value = ''; } else { this.value = 'filled'; } }); }); return mce_validator.form(); }, success: mce_success_cb }; $('#mc-embedded-subscribe-form').ajaxForm(options); }); } function mce_success_cb(resp){ $('#mce-success-response').hide(); $('#mce-error-response').hide(); if (resp.result=="success"){ $('#mce-'+resp.result+'-response').show(); $('#mce-'+resp.result+'-response').html(resp.msg); $('#mc-embedded-subscribe-form').each(function(){ this.reset(); }); } else { var index = -1; var msg; try { var parts = resp.msg.split(' - ',2); if (parts[1]==undefined){ msg = resp.msg; } else { i = parseInt(parts[0]); if (i.toString() == parts[0]){ index = parts[0]; msg = parts[1]; } else { index = -1; msg = resp.msg; } } } catch(e){ index = -1; msg = resp.msg; } try{ if (index== -1){ $('#mce-'+resp.result+'-response').show(); $('#mce-'+resp.result+'-response').html(msg); } else { err_id = 'mce_tmp_error_msg'; html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>'; var input_id = '#mc_embed_signup'; var f = $(input_id); if (ftypes[index]=='address'){ input_id = '#mce-'+fnames[index]+'-addr1'; f = $(input_id).parent().parent().get(0); } else if (ftypes[index]=='date'){ input_id = '#mce-'+fnames[index]+'-month'; f = $(input_id).parent().parent().get(0); } else { input_id = '#mce-'+fnames[index]; f = $().parent(input_id).get(0); } if (f){ $(f).append(html); $(input_id).focus(); } else { $('#mce-'+resp.result+'-response').show(); $('#mce-'+resp.result+'-response').html(msg); } } } catch(e){ $('#mce-'+resp.result+'-response').show(); $('#mce-'+resp.result+'-response').html(msg); } } } </script> <!--End mc_embed_signup--> </div> <div class="col-md-offset-1 col-md-3" id="sidebar"> <div class="panel panel-success"> <div class="panel-heading"><h3 class="panel-head">Web Servers</h3></div> <div class="panel-body"> <a href="/">Full Stack Python</a> is an open book that explains each Python web application stack layer and provides the best web resources for those topics. <hr/> There's a work-in-progress <a href="/full-stack-python-map.pdf">subjects map (.pdf)</a> that visually lays out each chapter in addition to the table of contents found below. <hr/> Need more detailed tutorials and walkthroughs than what is presented here? <a href="/email.html">Sign up for an email alert when that content is created.</a> <hr/> <a href="http://twitter.com/mattmakai">Matt Makai</a> built this site with assistance from community pull requests. On GitHub you can <a href="https://github.com/makaimc">follow Matt</a> to see the daily changes. </div> </div> <div class="panel panel-success"> <div class="panel-heading"> <h3 class="panel-head">Table of Contents</h3> </div> <div class="list-group"> <a href="/introduction.html" class="list-group-item smaller-item ">Introduction</a> <a href="/web-frameworks.html" class="list-group-item smaller-item ">Web Frameworks</a> <a href="/django.html" class="list-group-item smaller-item ">Django</a> <a href="/flask.html" class="list-group-item smaller-item ">Flask</a> <a href="/bottle.html" class="list-group-item smaller-item ">Bottle</a> <a href="/other-web-frameworks.html" class="list-group-item smaller-item ">Other Web Frameworks</a> <a href="/deployment.html" class="list-group-item smaller-item ">Deployment</a> <a href="/servers.html" class="list-group-item smaller-item ">Servers</a> <a href="/operating-systems.html" class="list-group-item smaller-item ">Operating Systems</a> <a href="/web-servers.html" class="list-group-item smaller-item active">Web Servers</a> <a href="/platform-as-a-service.html" class="list-group-item smaller-item ">Platform-as-a-service</a> <a href="/wsgi-servers.html" class="list-group-item smaller-item ">WSGI Servers</a> <a href="/source-control.html" class="list-group-item smaller-item ">Source Control</a> <a href="/application-dependencies.html" class="list-group-item smaller-item ">Application Dependencies</a> <a href="/configuration-management.html" class="list-group-item smaller-item ">Configuration Management</a> <a href="/databases.html" class="list-group-item smaller-item ">Databases</a> <a href="/no-sql-datastore.html" class="list-group-item smaller-item ">NoSQL Data Stores</a> <a href="/cascading-style-sheets.html" class="list-group-item smaller-item ">Cascading Style Sheets</a> <a href="/javascript.html" class="list-group-item smaller-item ">JavaScript</a> <a href="/application-programming-interfaces.html" class="list-group-item smaller-item ">Application Programming Interfaces</a> <a href="/api-integration.html" class="list-group-item smaller-item ">API Integration</a> <a href="/api-creation.html" class="list-group-item smaller-item ">API Creation</a> <a href="/static-content.html" class="list-group-item smaller-item ">Static Content</a> <a href="/caching.html" class="list-group-item smaller-item ">Caching</a> <a href="/task-queues.html" class="list-group-item smaller-item ">Task Queues</a> <a href="/logging.html" class="list-group-item smaller-item ">Logging</a> <a href="/monitoring.html" class="list-group-item smaller-item ">Monitoring</a> <a href="/web-analytics.html" class="list-group-item smaller-item ">Web Analytics</a> <a href="/web-application-security.html" class="list-group-item smaller-item ">Web Application Security</a> <a href="/best-python-resources.html" class="list-group-item smaller-item ">Best Python Resources</a> <a href="/about-author.html" class="list-group-item smaller-item ">About the Author</a> <a href="/change-log.html" class="list-group-item smaller-item ">Change Log</a> <a href="/future-directions.html" class="list-group-item smaller-item ">Future Directions</a> </div> </div> </div></div> <hr/> <div class="footer pull-right"> <a href="http://www.mattmakai.com/" class="underline">Matt Makai</a> 2014 </div> </div> <script type="text/javascript"> setTimeout(function(){var a=document.createElement("script"); var b=document.getElementsByTagName("script")[0]; a.src=document.location.protocol+"//dnn506yrbagrg.cloudfront.net/pages/scripts/0016/5846.js?"+Math.floor(new Date().getTime()/3600000); a.async=true;a.type="text/javascript";b.parentNode.insertBefore(a,b)}, 1); </script></body> </html>
{ "content_hash": "030dbf43354360cd42eb064ab9e53d61", "timestamp": "", "source": "github", "line_count": 473, "max_line_length": 237, "avg_line_length": 52.59408033826639, "alnum_prop": 0.5701652128472082, "repo_name": "Eisforinnovate/fullstackpython.github.com", "id": "4a356f3f5ce959a19564dc0f86ebdc0de05d1891", "size": "24877", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "web-servers.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright 2017 Google Inc. // // 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. // //////////////////////////////////////////////////////////////////////////////// package com.google.crypto.tink.subtle; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.fail; import com.google.crypto.tink.DeterministicAead; import com.google.crypto.tink.config.TinkFips; import com.google.crypto.tink.mac.internal.AesUtil; import com.google.crypto.tink.testing.WycheproofTestUtil; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.util.Arrays; import javax.crypto.AEADBadTagException; import javax.crypto.Cipher; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for AesSiv */ @RunWith(JUnit4.class) public class AesSivTest { private Integer[] keySizeInBytes; @Before public void setUp() throws Exception { if (Cipher.getMaxAllowedKeyLength("AES") < 256) { System.out.println( "Unlimited Strength Jurisdiction Policy Files are required" + " but not installed. Skip most AesSiv tests."); keySizeInBytes = new Integer[] {}; } else { keySizeInBytes = new Integer[] {64}; } } @Test public void testWycheproofVectors() throws Exception { Assume.assumeFalse(TinkFips.useOnlyFips()); JsonObject json = WycheproofTestUtil.readJson("../wycheproof/testvectors/aes_siv_cmac_test.json"); JsonArray testGroups = json.getAsJsonArray("testGroups"); int cntSkippedTests = 0; for (int i = 0; i < testGroups.size(); i++) { JsonObject group = testGroups.get(i).getAsJsonObject(); int keySize = group.get("keySize").getAsInt(); JsonArray tests = group.getAsJsonArray("tests"); if (!Arrays.asList(keySizeInBytes).contains(keySize / 8)) { cntSkippedTests += tests.size(); continue; } for (int j = 0; j < tests.size(); j++) { JsonObject testcase = tests.get(j).getAsJsonObject(); String tcId = String.format( "testcase %d (%s)", testcase.get("tcId").getAsInt(), testcase.get("comment").getAsString()); byte[] key = Hex.decode(testcase.get("key").getAsString()); byte[] msg = Hex.decode(testcase.get("msg").getAsString()); byte[] aad = Hex.decode(testcase.get("aad").getAsString()); byte[] ct = Hex.decode(testcase.get("ct").getAsString()); // Result is one of "valid" and "invalid". // "valid" are test vectors with matching plaintext and ciphertext. // "invalid" are test vectors with invalid parameters or invalid ciphertext. String result = testcase.get("result").getAsString(); DeterministicAead daead = new AesSiv(key); if (result.equals("valid")) { byte[] ciphertext = daead.encryptDeterministically(msg, aad); assertEquals(tcId, Hex.encode(ct), Hex.encode(ciphertext)); byte[] plaintext = daead.decryptDeterministically(ct, aad); assertEquals(tcId, Hex.encode(msg), Hex.encode(plaintext)); } else { assertThrows( String.format("FAIL %s: decrypted invalid ciphertext", tcId), GeneralSecurityException.class, () -> daead.decryptDeterministically(ct, aad)); } } } System.out.printf("Number of tests skipped: %d", cntSkippedTests); } @Test public void testEncryptDecryptWithEmptyPlaintext() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = new byte[0]; byte[] aad = Random.randBytes(Random.randInt(128) + 1); byte[] ciphertext = dead.encryptDeterministically(plaintext, aad); byte[] rebuiltPlaintext = dead.decryptDeterministically(ciphertext, aad); assertThat(ciphertext).hasLength(AesUtil.BLOCK_SIZE); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } @Test public void testEncryptDecryptWithEmptyAssociatedData() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = Random.randBytes(Random.randInt(1024) + 1); byte[] aad = new byte[0]; byte[] rebuiltPlaintext = dead.decryptDeterministically(dead.encryptDeterministically(plaintext, aad), aad); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } @Test public void testEncryptDecryptWithEmptyPlaintextAndEmptyAssociatedData() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = new byte[0]; byte[] aad = new byte[0]; byte[] rebuiltPlaintext = dead.decryptDeterministically(dead.encryptDeterministically(plaintext, aad), aad); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } @Test public void testEncryptDecryptWithNullAssociatedData() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = Random.randBytes(Random.randInt(1024) + 1); byte[] rebuiltPlaintext = dead.decryptDeterministically(dead.encryptDeterministically(plaintext, null), null); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } @Test public void testEncryptDecryptWithNullAndEmptyAssociatedDataEquivalent() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = Random.randBytes(Random.randInt(1024) + 1); byte[] emptyAad = new byte[0]; byte[] emptyAadCiphertext = dead.encryptDeterministically(plaintext, emptyAad); byte[] emptyAadRebuiltPlaintext = dead.decryptDeterministically(emptyAadCiphertext, emptyAad); byte[] nullAadCipherText = dead.encryptDeterministically(plaintext, null); byte[] nullAadRebuiltPlaintext = dead.decryptDeterministically(nullAadCipherText, null); assertEquals(Hex.encode(plaintext), Hex.encode(emptyAadRebuiltPlaintext)); assertEquals(Hex.encode(plaintext), Hex.encode(nullAadRebuiltPlaintext)); assertEquals(Hex.encode(emptyAadCiphertext), Hex.encode(nullAadCipherText)); } } } @Test public void testEncryptDecryptWithEmptyPlaintextAndNullAssociatedData() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = new byte[0]; byte[] rebuiltPlaintext = dead.decryptDeterministically(dead.encryptDeterministically(plaintext, null), null); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } @Test public void testEncryptDecrypt() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { DeterministicAead dead = new AesSiv(Random.randBytes(keySize)); for (int triesPlaintext = 0; triesPlaintext < 100; triesPlaintext++) { byte[] plaintext = Random.randBytes(Random.randInt(1024) + 1); byte[] aad = Random.randBytes(Random.randInt(128) + 1); byte[] rebuiltPlaintext = dead.decryptDeterministically(dead.encryptDeterministically(plaintext, aad), aad); assertEquals(Hex.encode(plaintext), Hex.encode(rebuiltPlaintext)); } } } private static void testModifiedCiphertext(int keySize) throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); byte[] key = Random.randBytes(keySize); DeterministicAead crypter = new AesSiv(key); byte[] plaintext = Random.randBytes(10); byte[] aad = Random.randBytes(10); byte[] ciphertext = crypter.encryptDeterministically(plaintext, aad); // Flipping bits of ciphertext. for (int b = 0; b < ciphertext.length; b++) { for (int bit = 0; bit < 8; bit++) { byte[] modified = Arrays.copyOf(ciphertext, ciphertext.length); modified[b] ^= (byte) (1 << bit); try { byte[] unused = crypter.decryptDeterministically(modified, aad); fail("Decrypting modified ciphertext should fail"); } catch (AEADBadTagException ex) { // This is expected. } } } // Truncate the message. for (int length = 0; length < ciphertext.length; length++) { byte[] modified = Arrays.copyOf(ciphertext, length); try { byte[] unused = crypter.decryptDeterministically(modified, aad); fail("Decrypting modified ciphertext should fail"); } catch (GeneralSecurityException ex) { // This is expected. // This could be a AeadBadTagException when the tag verification // fails or some not yet specified Exception when the ciphertext is too short. // In all cases a GeneralSecurityException or a subclass of it must be thrown. } } } @Test public void testModifiedCiphertext() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { testModifiedCiphertext(keySize); } } private static void testModifiedAssociatedData(int keySize) throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); byte[] key = Random.randBytes(keySize); DeterministicAead crypter = new AesSiv(key); byte[] plaintext = Random.randBytes(10); byte[] aad = Random.randBytes(10); byte[] ciphertext = crypter.encryptDeterministically(plaintext, aad); // Flipping bits of aad. for (int b = 0; b < aad.length; b++) { for (int bit = 0; bit < 8; bit++) { byte[] modified = Arrays.copyOf(aad, aad.length); modified[b] ^= (byte) (1 << bit); try { byte[] unused = crypter.decryptDeterministically(ciphertext, modified); fail("Decrypting modified aad should fail"); } catch (AEADBadTagException ex) { // This is expected. } } } } @Test public void testModifiedAssociatedData() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); for (int keySize : keySizeInBytes) { testModifiedAssociatedData(keySize); } } @Test public void testInvalidKeySizes() throws GeneralSecurityException { Assume.assumeFalse(TinkFips.useOnlyFips()); assertThrows(InvalidKeyException.class, () -> new AesSiv(Random.randBytes(32))); for (int i = 0; i < 100; i++) { final int j = i; if (j == 48 || j == 64) { continue; } assertThrows( "Keys with invalid size should not be accepted: " + j, InvalidKeyException.class, () -> new AesSiv(Random.randBytes(j))); } } @Test public void testFailIfFipsModuleNotAvailable() throws Exception { Assume.assumeTrue(TinkFips.useOnlyFips()); byte[] key = Random.randBytes(16); assertThrows(GeneralSecurityException.class, () -> new AesSiv(key)); } }
{ "content_hash": "fab7f837c7f07bfa1e9693f2d60be8f9", "timestamp": "", "source": "github", "line_count": 333, "max_line_length": 100, "avg_line_length": 38.77777777777778, "alnum_prop": 0.672655463486409, "repo_name": "google/tink", "id": "4b03ae686e35ddebf100487fc36b46d85f636f5c", "size": "12913", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java_src/src/test/java/com/google/crypto/tink/subtle/AesSivTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "17279" }, { "name": "C++", "bytes": "5210061" }, { "name": "CMake", "bytes": "232537" }, { "name": "Go", "bytes": "2748716" }, { "name": "Java", "bytes": "5065479" }, { "name": "Objective-C", "bytes": "109729" }, { "name": "Objective-C++", "bytes": "171502" }, { "name": "Python", "bytes": "1412727" }, { "name": "Ruby", "bytes": "637" }, { "name": "Shell", "bytes": "263940" }, { "name": "Starlark", "bytes": "1263006" }, { "name": "TypeScript", "bytes": "636683" } ], "symlink_target": "" }
var services = angular.module('services'); /** * Provides the list of services (compiled.json) */ services.factory('PopupBuilder', ['$translate', function ($translate) { return { buildPopup: function(feature) { // TODO: incredible hack here, just pasting in what's from the old app so we can render the popup var partnerName = feature.properties.partnerName; var logoUrl = './src/images/partner/' + partnerName.toLowerCase().replace(' ', '') + '.jpg'; // we add an onerror callback so that if the image 404's we just set it to display:none var logo = '<img src="' + logoUrl + '" alt="' + partnerName + '" onError="this.onerror=null;this.style.display=\'none\'" />'; // Prepare the office hours output. var hours = '<strong>' + $translate.instant('HOURS') + ':</strong> '; var hourOpen = ''; var hourClosed = ''; for (var hoItem in feature.properties[$translate.instant('OFFICE_OPEN_AT')]) { if (feature.properties[$translate.instant('OFFICE_OPEN_AT')][hoItem] === true) { hourOpen = hoItem; } } for (var hcItem in feature.properties[$translate.instant('OFFICE_CLOSE_AT')]) { if (feature.properties[$translate.instant('OFFICE_CLOSE_AT')][hcItem] === true) { hourClosed = hcItem; } } // If we have hours, show them as compact as possible. if (hourOpen) { // TODO: translate // If we have open time but no close time, say "Open at X o'clock"; if we // have both, show "X o'clock to X o'clock". hours = hourClosed ? hours += hourOpen + ' - ' + hourClosed.replace('Close at', '') : hours + 'Open at ' + hourOpen; } else { // If we have no open time but yes close time, show close time only; if we have // neither, say "unknown". hours = hourClosed ? hours += hourClosed : hours + $translate.instant('UNKNOWN'); } // Create meta-field for better display of indicators. feature.properties["x. Activity Details"] = feature.properties.indicators; // Make a list of the fields we want to show - lots of fields for this list view, // not so many for the map-marker-popup view. var fields = { "x. Activity Details": {'section': 'header'}, "10. Referral Method": {'section': 'header'} }; // Loop through our list of fields, preparing output for display. var headerOutput = ''; var contentOutput = ''; for (var field in fields) { // Get the field items values = feature.properties[field]; var fieldOutput = ''; // Strip the leading numeral from the field name. var fieldName = field.substr(field.indexOf(" ") + 1); // Skip empty fields. if (values) { // Some fields have object values. These we must loop through. if (typeof values === 'object') { if (Object.getOwnPropertyNames(values).length) { // Loop through items, and if value is TRUE, add label to the output. for (var lineItem in values) { // Checking if the line item value is TRUE if (values[lineItem]) { fieldOutput += lineItem + ' '; } } } // Other fields have a string for a value. } else if (typeof values === 'string') { fieldName = fields[field].label; fieldOutput = values; } } // Wrap the output with a label. If no output, say unknown. if (fieldOutput === '') { fieldOutput = $translate.instant('UNKNOWN'); } fieldOutput = '<p><strong>' + $translate.instant(fieldName) + ':</strong> ' + fieldOutput + '</p>'; // Add the field output to the appropriate section. if (fields[field].section == 'header') { headerOutput += fieldOutput; } else { contentOutput += fieldOutput; } } // Get the activity-category icon. activityCategory = feature.properties.activityCategory; // eg "CASH" var glyph = '<i class="glyphicon icon-' + iconGlyphs[activityCategory].glyph + '"></i>'; // In the list view only, the articles must have unique IDs so that we can scroll directly to them // when someone clicks the "Show details" link in a map marker. var articleIDattribute = ''; // Assemble the article header. var header = '<header>' + logo + '<h3>' + glyph + feature.properties.locationName + ': ' + feature.properties.activityName + '</h3>' + '<p class="hours">' + hours + '</p>' + headerOutput + '</header>'; return '<article class="serviceText"' + articleIDattribute + '>' + header + '</article>'; } } }]);
{ "content_hash": "3e79a875281d60ec5f86e4d2512c6267", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 213, "avg_line_length": 51.00925925925926, "alnum_prop": 0.5069885641677255, "repo_name": "lkysow/services-advisor", "id": "92fda7a7691a623214ff42d8b4f23bb9869c8f0d", "size": "5509", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/angular/Services/popupbuilder.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24603" }, { "name": "CSS", "bytes": "257303" }, { "name": "HTML", "bytes": "80365" }, { "name": "JavaScript", "bytes": "41640" } ], "symlink_target": "" }
using namespace ::threescanner; using namespace ::testing; class RealProjectorInstance: public testing::Test { public: Config cfg { Config("threescanner.json").getChild("projector") }; ProjectorPtr projector { ProjectorFactory::create("threephase", cfg) }; RealProjector* realProjector { dynamic_cast<RealProjector*>(projector.get()) }; }; TEST_F(RealProjectorInstance, ShouldAcceptValidAction) { ASSERT_NO_THROW(realProjector->handleAction("quit")); } TEST_F(RealProjectorInstance, ShouldThrowExceptionWithWrongAction) { ASSERT_THROW(realProjector->handleAction("wrongAction!"), std::invalid_argument); }
{ "content_hash": "5cfbd3e4c34b632d3828f2c51d3b001a", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 82, "avg_line_length": 36.11764705882353, "alnum_prop": 0.7801302931596091, "repo_name": "alessandro-pezzato/threescanner", "id": "8fb15d5405fc9c7bdaf64e8d89a36f10a6df69ed", "size": "815", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/unit/projector/RealProjector_test.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1235" }, { "name": "C++", "bytes": "74145" }, { "name": "Shell", "bytes": "1399" } ], "symlink_target": "" }
/** * @module natron-core */ import type {Thing, Task} from "./task"; type EventAggregator = { emit?: publish; publish?: publish; trigger?: publish; } type publish = (type: string, e: any) => void; export class TaskContext { stack: Array<Task>; args: Array<any>; original: TaskContext; eventAggregator: EventAggregator|publish; static create(context?: TaskContext|Object, init?: Object): TaskContext { if (context instanceof TaskContext) { return init ? context.clone(init) : context; } if (init) { context = Object.assign({}, context, init); } return new TaskContext(context); } constructor(init?: Object) { let init_ = init || {}; if (!init_.stack) { init_.stack = []; } else if (!(init_.stack instanceof Array)) { throw new TypeError(`${init_.stack} is not an array`); } if (!init_.args) { init_.args = []; } else if (!(init_.args instanceof Array)) { throw new TypeError(`${init_.args} is not an array`); } Object.assign(this, init_); } get depth(): number { return this.stack.length - 1; } get root(): Task { return this.stack[0]; } get task(): Task { return this.stack[this.depth]; } clone(init?: Object): TaskContext { let proto = Object.getPrototypeOf(this); let cntx_ = Object.create(proto); let init_ = { original: this, }; if (init) { init_ = Object.assign({}, init, init_); if (init_.stack === true) { init_.stack = this.stack.slice(); } if (init_.args === true) { init_.args = this.args.slice(); } } Object.assign(cntx_, this, init_); return cntx_; } publish(type: string, e: any): void { if (this.eventAggregator) { let ea = this.eventAggregator; if (ea instanceof Function) { return ea(type, e); } let fn = ea.emit || ea.publish || ea.trigger; if (fn) { return fn.call(ea, type, e); } } } resolve(name: string): Thing { let task, depth = this.depth; while ((task = this.stack[depth--])) { if (task.resolver) { let rs = task.resolver; if (rs instanceof Function) { return rs(name, this); } let fn = rs.resolve; if (fn) { return fn.call(rs, name, this); } return null; } } } }
{ "content_hash": "603618a6db84abcd5949cc55f24f4d3e", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 75, "avg_line_length": 22.58490566037736, "alnum_prop": 0.5509607351712615, "repo_name": "natronjs/natron-core", "id": "c11a41be3ca355370c2818e39a5026c452b088ad", "size": "2394", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/context.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "75949" } ], "symlink_target": "" }
package com.sugaronrest.tests; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sugaronrest.utils.JsonObjectMapper; public final class TestAccount { // public static String Url = "http://demo.suiteondemand.com/service/v4_1/rest.php"; public static String Url = "http://191.101.224.189/sugar/service/v4_1/rest.php"; public static String Username = "will"; public static String Password = "will"; public static void printJsonObject(Object obj) throws JsonProcessingException { printJsonObject(obj.getClass().getSimpleName(), obj); } public static void printJsonObject(String title, Object obj) throws JsonProcessingException { System.out.println("---------" + title + "-------------"); ObjectMapper mapper = JsonObjectMapper.getMapper(); String jsonError = mapper.writeValueAsString(obj); System.out.println(jsonError); } }
{ "content_hash": "6e224b449c343602eb1c5c67af5e8f69", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 97, "avg_line_length": 42.21739130434783, "alnum_prop": 0.7147270854788877, "repo_name": "Frankst2/SugarOnRest", "id": "c08854bdaf4a284a0203676b9f7b8f71dd0223fc", "size": "971", "binary": false, "copies": "2", "ref": "refs/heads/createlinkedentries", "path": "sugaronrest/src/test/java/com/sugaronrest/tests/TestAccount.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "97" }, { "name": "Java", "bytes": "968270" } ], "symlink_target": "" }
namespace std { template< typename K, typename V > std::ostream& operator<<(std::ostream&, const std::map< K, V >&); template< typename T1, typename T2 > std::ostream& operator<<(std::ostream&, const std::pair< T1, T2 >&); template< typename T > std::ostream& operator<<(std::ostream&, const std::shared_ptr< T >); template< typename T > std::ostream& operator<<(std::ostream&, const std::set< T >&); template< typename T > std::ostream& operator<<(std::ostream&, const std::vector< T >&); } // namespace std #endif // !defined(UTILS_FORMAT_CONTAINERS_HPP)
{ "content_hash": "7884db324670f365810d5b410a17f6b7", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 68, "avg_line_length": 25.818181818181817, "alnum_prop": 0.6672535211267606, "repo_name": "jmmv/kyua", "id": "7334c250de4e4986f3addb022ae37ba6dce29e49", "size": "2510", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "utils/format/containers.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "3624" }, { "name": "Awk", "bytes": "11128" }, { "name": "C++", "bytes": "2702705" }, { "name": "CSS", "bytes": "2190" }, { "name": "HTML", "bytes": "9095" }, { "name": "M4", "bytes": "64824" }, { "name": "Makefile", "bytes": "6324" }, { "name": "PHP", "bytes": "3770" }, { "name": "PLpgSQL", "bytes": "90892" }, { "name": "Shell", "bytes": "148290" }, { "name": "SourcePawn", "bytes": "78231" } ], "symlink_target": "" }
include Warden::Test::Helpers module FeatureHelpers def login user = FactoryGirl.create(:user) login_as user, scope: :user user end end RSpec.configure do |config| config.include FeatureHelpers, type: :feature end
{ "content_hash": "2522a6e184ff497f3e28051ad7d80896", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 47, "avg_line_length": 17.923076923076923, "alnum_prop": 0.7296137339055794, "repo_name": "sevenview/sevenpages", "id": "ec21ad9b278a9f89ab93b10ed9755528546eb225", "size": "233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/support/feature_helpers.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "316" }, { "name": "JavaScript", "bytes": "1924" }, { "name": "Ruby", "bytes": "65964" } ], "symlink_target": "" }
<?php namespace JansenFelipe\CnpjGratis; use PHPUnit_Framework_TestCase; class CnpjGratisTest extends PHPUnit_Framework_TestCase { private $params; public function testGetParams() { $this->params = CnpjGratis::getParams(); $this->assertEquals(true, isset($this->params['captchaBase64'])); $this->assertEquals(true, isset($this->params['cookie'])); } }
{ "content_hash": "df12280f37d9530c9bf8339893d9a967", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 73, "avg_line_length": 21.68421052631579, "alnum_prop": 0.6529126213592233, "repo_name": "whmcsred/Valid-Account", "id": "63543b7875ab0cb2bc7209c6ae0d693124717600", "size": "412", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "valid_account/vendor/jansenfelipe/cnpj-gratis/tests/CnpjGratisTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "30689" }, { "name": "PHP", "bytes": "141262" }, { "name": "Smarty", "bytes": "15245" } ], "symlink_target": "" }
import React from 'react'; import { shallow } from 'enzyme'; import LocationBadge from '../../app/components/LocationBadge'; describe('LocationBadge', () => { it('renders properly', () => { const result = shallow( <LocationBadge city="milano" country="Italia" weather="sunny" temp={30} /> ); expect(result).toMatchSnapshot(); }); });
{ "content_hash": "d609e5b5a384839b9923332a53d232fb", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 63, "avg_line_length": 22, "alnum_prop": 0.5782828282828283, "repo_name": "Byte-Code/lm-digitalstore", "id": "8127b06998d6dd86e5515675748938da8980e1f0", "size": "396", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/components/LocationBadge.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10419" }, { "name": "HTML", "bytes": "1897" }, { "name": "JavaScript", "bytes": "407567" } ], "symlink_target": "" }
package com.google.teampot.servlet.task; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.teampot.GoogleServices; import com.google.teampot.model.Project; import com.google.teampot.service.ProjectService; public class WatchFolderChangesServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WatchFolderChangesServlet.class.getSimpleName()); @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String projectKey = req.getParameter("project"); Project project = ProjectService.getInstance().get(projectKey); try { ProjectService.getInstance().watchFolderChanges(GoogleServices.getDriveService(project.getOwner().get()), project); } catch (GeneralSecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
{ "content_hash": "9ded2573d74c9aaeaae1c23e138c9780", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 118, "avg_line_length": 31.771428571428572, "alnum_prop": 0.7940647482014388, "repo_name": "andryfailli/teampot", "id": "153563d99f5cc4526f8e41af6dd92c0421349cd4", "size": "1112", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/google/teampot/servlet/task/WatchFolderChangesServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12132" }, { "name": "HTML", "bytes": "62827" }, { "name": "Java", "bytes": "180542" }, { "name": "JavaScript", "bytes": "52950" } ], "symlink_target": "" }
/* Thread - Show People In Conversation */ $(document).on('click', '.show-thread-people', function() { $('#modal-full .modal-title').html($('#thread-people').data('modal_title')); $('#modal-full .modal-body').html($('#thread-people').html()); $('#modal-full').modal(Mailpile.UI.ModalOptions); }); /* Thread - Show Tags In Converstation */ $(document).on('click', '.show-thread-tags', function() { $('#modal-full .modal-title').html($('#thread-tags').data('modal_title')); $('#modal-full .modal-body').html($('#thread-tags').html()); $('#modal-full').modal(Mailpile.UI.ModalOptions); }); /* Thread - Show Metadata Info */ $(document).on('click', '.thread-message-metadata-details-toggle', function() { var mid = $(this).data('mid'); var target = '#metadata-details-' + mid; if ($(target).css('display') === 'none') { $(target).show('fast').addClass('border-bottom'); $(this).css('color', '#4d4d4d'); } else { $(target).hide('fast').removeClass('border-bottom'); $(this).css('color', '#ccc'); } }); /* Thread - Expand Snippet */ $(document).on('click', 'div.thread-snippet', function(e) { var mid = $(this).data('mid'); if (e.target.href === undefined && $(e.target).data('expand') !== 'no' && $(e.target).hasClass('show-thread-message-metadata-details') === false) { Mailpile.UI.Message.ShowMessage(mid); } }); /* Thread - Message Quote */ $(document).on('click', '.thread-message-actions-quote', function() { var mid = $(this).parent().parent().data('mid'); $('#message-' + mid).find('.thread-item-quote').removeClass('hide'); $('#message-' + mid).find('.thread-item-signature').removeClass('hide'); $(this).parent().hide(); }); /* Thread - Might Move to Global Location / Abstraction */ $(document).on('click', '.dropdown-toggle', function() { $(this).find('.icon-arrow-right').removeClass('icon-arrow-right').addClass('icon-arrow-down'); }); $(document).on('click', '.thread-message-toggle-html', function(e) { var state = $(this).data('state'); var mid = $(this).data('mid'); if (state === 'plain') { $(this).data('state', 'html'); $(this).html('{{_("Plain Text")}}'); Mailpile.Message.ShowHTML(mid); } else { $(this).data('state', 'plain'); $(this).html('HTML'); Mailpile.Message.ShowPlain(mid); } });
{ "content_hash": "d31061ff5fbe7d3f2a7d41ce2e56a0b5", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 149, "avg_line_length": 33.9264705882353, "alnum_prop": 0.6051148677936714, "repo_name": "jparyani/Mailpile", "id": "56416e95f3b8ce8114f4e902286309afee44d2eb", "size": "2307", "binary": false, "copies": "1", "ref": "refs/heads/sandstorm", "path": "mailpile/www/default/html/jsapi/message/events.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "130573" }, { "name": "Cap'n Proto", "bytes": "1254" }, { "name": "JavaScript", "bytes": "577920" }, { "name": "Makefile", "bytes": "6768" }, { "name": "Python", "bytes": "1310077" }, { "name": "Shell", "bytes": "19360" } ], "symlink_target": "" }
/*** Creating and destroying ***/ /* Feel free to read the struct's members, but don't write them, except through the accessors below such as meshSetTriangle, meshSetVertex. */ typedef struct meshMesh meshMesh; struct meshMesh { GLuint triNum, vertNum, attrDim; GLuint *tri; /* triNum * 3 GLuints */ GLdouble *vert; /* vertNum * attrDim GLdoubles */ }; /* Initializes a mesh with enough memory to hold its triangles and vertices. Does not actually fill in those triangles or vertices with useful data. When you are finished with the mesh, you must call meshDestroy to deallocate its backing resources. */ int meshInitialize(meshMesh *mesh, GLuint triNum, GLuint vertNum, GLuint attrDim) { mesh->tri = (GLuint *)malloc(triNum * 3 * sizeof(GLuint) + vertNum * attrDim * sizeof(GLdouble)); if (mesh->tri != NULL) { mesh->vert = (GLdouble *)&(mesh->tri[triNum * 3]); mesh->triNum = triNum; mesh->vertNum = vertNum; mesh->attrDim = attrDim; } return (mesh->tri == NULL); } /* Sets the trith triangle to have vertex indices i, j, k. */ void meshSetTriangle(meshMesh *mesh, GLuint tri, GLuint i, GLuint j, GLuint k) { if (tri < mesh->triNum) { mesh->tri[3 * tri] = i; mesh->tri[3 * tri + 1] = j; mesh->tri[3 * tri + 2] = k; } } /* Returns a pointer to the trith triangle. For example: GLuint *triangle13 = meshGetTrianglePointer(&mesh, 13); printf("%d, %d, %d\n", triangle13[0], triangle13[1], triangle13[2]); */ GLuint *meshGetTrianglePointer(meshMesh *mesh, GLuint tri) { if (tri < mesh->triNum) return &mesh->tri[tri * 3]; else return NULL; } /* Sets the vertth vertex to have attributes attr. */ void meshSetVertex(meshMesh *mesh, GLuint vert, GLdouble attr[]) { GLuint k; if (vert < mesh->vertNum) for (k = 0; k < mesh->attrDim; k += 1) mesh->vert[mesh->attrDim * vert + k] = attr[k]; } /* Returns a pointer to the vertth vertex. For example: GLdouble *vertex13 = meshGetVertexPointer(&mesh, 13); printf("x = %f, y = %f\n", vertex13[0], vertex13[1]); */ GLdouble *meshGetVertexPointer(meshMesh *mesh, GLuint vert) { if (vert < mesh->vertNum) return &mesh->vert[vert * mesh->attrDim]; else return NULL; } /* Deallocates the resources backing the mesh. This function must be called when you are finished using a mesh. */ void meshDestroy(meshMesh *mesh) { free(mesh->tri); } /*** OpenGL ***/ /* Feel free to read from this struct's members, but don't write to them, except through accessor functions. */ typedef struct meshGLMesh meshGLMesh; struct meshGLMesh { GLuint triNum, vertNum, attrDim; GLuint buffers[2]; }; /* Initializes an OpenGL mesh from a non-OpenGL mesh. */ void meshGLInitialize(meshGLMesh *meshGL, meshMesh *mesh) { meshGL->triNum = mesh->triNum; meshGL->vertNum = mesh->vertNum; meshGL->attrDim = mesh->attrDim; glGenBuffers(2, meshGL->buffers); glBindBuffer(GL_ARRAY_BUFFER, meshGL->buffers[0]); glBufferData(GL_ARRAY_BUFFER, mesh->vertNum * mesh->attrDim * sizeof(GLdouble), (GLvoid *)mesh->vert, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshGL->buffers[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, mesh->triNum * 3 * sizeof(GLuint), (GLvoid *)mesh->tri, GL_STATIC_DRAW); } #define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes)) /* Renders the already-initialized OpenGL mesh. attrDims is an array of length attrNum. For each i, its ith entry is the dimension of the ith attribute vector. Similarly, attrLocs is an array of length attrNum, giving the location of the ith attribute in the active OpenGL shader program. */ void meshGLRender(meshGLMesh *meshGL, GLuint attrNum, GLuint attrDims[], GLint attrLocs[]) { int offset = 0; //enable the buffer array for (int i = 0; i < attrNum; i++){ glEnableVertexAttribArray(attrLocs[i]); } //bind buffer for arrays glBindBuffer(GL_ARRAY_BUFFER, meshGL->buffers[0]); for (int i = 0; i < attrNum; i++){ //copy array over to buffer glVertexAttribPointer(attrLocs[i], attrDims[i], GL_DOUBLE, GL_FALSE, meshGL->attrDim * sizeof(GLdouble), BUFFER_OFFSET(offset * sizeof(GLdouble))); offset += attrDims[i]; } //bind buffer for elements glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshGL->buffers[1]); glDrawElements(GL_TRIANGLES, meshGL->triNum * 3, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); //destroy the arrays for (int i = 0; i < attrNum; i++){ glDisableVertexAttribArray(attrLocs[i]); } } /* Deallocates the resources backing the initialized OpenGL mesh. */ void meshGLDestroy(meshGLMesh *meshGL) { glDeleteBuffers(2, meshGL->buffers); } /*** Convenience initializers: 2D ***/ /* Initializes a mesh to two triangles forming a rectangle of the given sides. The four attributes are X, Y, S, T. Do not call meshInitialize separately; it is called inside this function. Don't forget to call meshDestroy when done. */ int meshInitializeRectangle(meshMesh *mesh, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top) { GLuint error = meshInitialize(mesh, 2, 4, 2 + 2); if (error == 0) { meshSetTriangle(mesh, 0, 0, 1, 2); meshSetTriangle(mesh, 1, 0, 2, 3); GLdouble attr[4]; vecSet(4, attr, left, bottom, 0.0, 0.0); meshSetVertex(mesh, 0, attr); vecSet(4, attr, right, bottom, 1.0, 0.0); meshSetVertex(mesh, 1, attr); vecSet(4, attr, right, top, 1.0, 1.0); meshSetVertex(mesh, 2, attr); vecSet(4, attr, left, top, 0.0, 1.0); meshSetVertex(mesh, 3, attr); } return error; } /* Initializes a mesh to sideNum triangles forming an ellipse of the given center (x, y) and radii rx, ry. The four attributes are X, Y, S, T. Do not call meshInitialize separately; it is called inside this function. Don't forget to call meshDestroy when done. */ int meshInitializeEllipse(meshMesh *mesh, GLdouble x, GLdouble y, GLdouble rx, GLdouble ry, GLuint sideNum) { GLuint i, error; GLdouble theta, cosTheta, sinTheta, attr[4] = {x, y, 0.5, 0.5}; error = meshInitialize(mesh, sideNum, sideNum + 1, 2 + 2); if (error == 0) { meshSetVertex(mesh, 0, attr); for (i = 0; i < sideNum; i += 1) { meshSetTriangle(mesh, i, 0, i + 1, (i + 1) % sideNum + 1); theta = i * 2.0 * M_PI / sideNum; cosTheta = cos(theta); sinTheta = sin(theta); vecSet(4, attr, x + rx * cosTheta, y + ry * sinTheta, 0.5 * cosTheta + 0.5, 0.5 * sinTheta + 0.5); meshSetVertex(mesh, i + 1, attr); } } return error; } /*** Convenience initializers: 3D ***/ /* Assumes that attributes 0, 1, 2 are XYZ. Assumes that the vertices of the triangle are in counter-clockwise order when viewed from 'outside' the triangle. Computes the outward-pointing unit normal vector for the triangle. */ void meshTrueNormal(GLdouble a[], GLdouble b[], GLdouble c[], GLdouble normal[3]) { GLdouble bMinusA[3], cMinusA[3]; vecSubtract(3, b, a, bMinusA); vecSubtract(3, c, a, cMinusA); vec3Cross(bMinusA, cMinusA, normal); vecUnit(3, normal, normal); } /* Assumes that attributes 0, 1, 2 are XYZ. Sets attributes n, n + 1, n + 2 to flat-shaded normals. If a vertex belongs to more than triangle, then some unspecified triangle's normal wins. */ void meshFlatNormals(meshMesh *mesh, GLuint n) { GLuint i, *tri; GLdouble *a, *b, *c, normal[3]; for (i = 0; i < mesh->triNum; i += 1) { tri = meshGetTrianglePointer(mesh, i); a = meshGetVertexPointer(mesh, tri[0]); b = meshGetVertexPointer(mesh, tri[1]); c = meshGetVertexPointer(mesh, tri[2]); meshTrueNormal(a, b, c, normal); vecCopy(3, normal, &a[n]); vecCopy(3, normal, &b[n]); vecCopy(3, normal, &c[n]); } } /* Assumes that attributes 0, 1, 2 are XYZ. Sets attributes n, n + 1, n + 2 to smooth-shaded normals. Does not do anything special to handle multiple vertices with the same coordinates. */ void meshSmoothNormals(meshMesh *mesh, GLuint n) { GLuint i, *tri; GLdouble *a, *b, *c, normal[3] = {0.0, 0.0, 0.0}; /* Zero the normals. */ for (i = 0; i < mesh->vertNum; i += 1) { a = meshGetVertexPointer(mesh, i); vecCopy(3, normal, &a[n]); } /* For each triangle, add onto the normal at each of its vertices. */ for (i = 0; i < mesh->triNum; i += 1) { tri = meshGetTrianglePointer(mesh, i); a = meshGetVertexPointer(mesh, tri[0]); b = meshGetVertexPointer(mesh, tri[1]); c = meshGetVertexPointer(mesh, tri[2]); meshTrueNormal(a, b, c, normal); vecAdd(3, normal, &a[n], &a[n]); vecAdd(3, normal, &b[n], &b[n]); vecAdd(3, normal, &c[n], &c[n]); } /* Normalize the normals. */ for (i = 0; i < mesh->vertNum; i += 1) { a = meshGetVertexPointer(mesh, i); vecUnit(3, &a[n], &a[n]); } } /* Builds a mesh for a parallelepiped (box) of the given size. The attributes are XYZ position, ST texture, and NOP unit normal vector. The normals are discontinuous at the edges (flat shading, not smooth). To facilitate this, some vertices have equal XYZ but different NOP, for 24 vertices in all. Don't forget to meshDestroy when finished. */ int meshInitializeBox(meshMesh *mesh, GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble base, GLdouble lid) { GLuint error = meshInitialize(mesh, 12, 24, 3 + 2 + 3); if (error == 0) { /* Make the triangles. */ meshSetTriangle(mesh, 0, 0, 2, 1); meshSetTriangle(mesh, 1, 0, 3, 2); meshSetTriangle(mesh, 2, 4, 5, 6); meshSetTriangle(mesh, 3, 4, 6, 7); meshSetTriangle(mesh, 4, 8, 10, 9); meshSetTriangle(mesh, 5, 8, 11, 10); meshSetTriangle(mesh, 6, 12, 13, 14); meshSetTriangle(mesh, 7, 12, 14, 15); meshSetTriangle(mesh, 8, 16, 18, 17); meshSetTriangle(mesh, 9, 16, 19, 18); meshSetTriangle(mesh, 10, 20, 21, 22); meshSetTriangle(mesh, 11, 20, 22, 23); /* Make the vertices after 0, using vertex 0 as temporary storage. */ GLdouble *v = mesh->vert; vecSet(8, v, right, bottom, base, 1.0, 0.0, 0.0, 0.0, -1.0); meshSetVertex(mesh, 1, v); vecSet(8, v, right, top, base, 1.0, 1.0, 0.0, 0.0, -1.0); meshSetVertex(mesh, 2, v); vecSet(8, v, left, top, base, 0.0, 1.0, 0.0, 0.0, -1.0); meshSetVertex(mesh, 3, v); vecSet(8, v, left, bottom, lid, 0.0, 0.0, 0.0, 0.0, 1.0); meshSetVertex(mesh, 4, v); vecSet(8, v, right, bottom, lid, 1.0, 0.0, 0.0, 0.0, 1.0); meshSetVertex(mesh, 5, v); vecSet(8, v, right, top, lid, 1.0, 1.0, 0.0, 0.0, 1.0); meshSetVertex(mesh, 6, v); vecSet(8, v, left, top, lid, 0.0, 1.0, 0.0, 0.0, 1.0); meshSetVertex(mesh, 7, v); vecSet(8, v, left, top, base, 0.0, 1.0, 0.0, 1.0, 0.0); meshSetVertex(mesh, 8, v); vecSet(8, v, right, top, base, 1.0, 1.0, 0.0, 1.0, 0.0); meshSetVertex(mesh, 9, v); vecSet(8, v, right, top, lid, 1.0, 1.0, 0.0, 1.0, 0.0); meshSetVertex(mesh, 10, v); vecSet(8, v, left, top, lid, 0.0, 1.0, 0.0, 1.0, 0.0); meshSetVertex(mesh, 11, v); vecSet(8, v, left, bottom, base, 0.0, 0.0, 0.0, -1.0, 0.0); meshSetVertex(mesh, 12, v); vecSet(8, v, right, bottom, base, 1.0, 0.0, 0.0, -1.0, 0.0); meshSetVertex(mesh, 13, v); vecSet(8, v, right, bottom, lid, 1.0, 0.0, 0.0, -1.0, 0.0); meshSetVertex(mesh, 14, v); vecSet(8, v, left, bottom, lid, 0.0, 0.0, 0.0, -1.0, 0.0); meshSetVertex(mesh, 15, v); vecSet(8, v, right, top, base, 1.0, 1.0, 1.0, 0.0, 0.0); meshSetVertex(mesh, 16, v); vecSet(8, v, right, bottom, base, 1.0, 0.0, 1.0, 0.0, 0.0); meshSetVertex(mesh, 17, v); vecSet(8, v, right, bottom, lid, 1.0, 0.0, 1.0, 0.0, 0.0); meshSetVertex(mesh, 18, v); vecSet(8, v, right, top, lid, 1.0, 1.0, 1.0, 0.0, 0.0); meshSetVertex(mesh, 19, v); vecSet(8, v, left, top, base, 0.0, 1.0, -1.0, 0.0, 0.0); meshSetVertex(mesh, 20, v); vecSet(8, v, left, bottom, base, 0.0, 0.0, -1.0, 0.0, 0.0); meshSetVertex(mesh, 21, v); vecSet(8, v, left, bottom, lid, 0.0, 0.0, -1.0, 0.0, 0.0); meshSetVertex(mesh, 22, v); vecSet(8, v, left, top, lid, 0.0, 1.0, -1.0, 0.0, 0.0); meshSetVertex(mesh, 23, v); /* Now make vertex 0 for realsies. */ vecSet(8, v, left, bottom, base, 0.0, 0.0, 0.0, 0.0, -1.0); } return error; } /* Rotates a 2-dimensional vector through an angle. The input can safely alias the output. */ void meshRotateVector(GLdouble theta, GLdouble v[2], GLdouble vRot[2]) { GLdouble cosTheta = cos(theta); GLdouble sinTheta = sin(theta); GLdouble vRot0 = cosTheta * v[0] - sinTheta * v[1]; vRot[1] = sinTheta * v[0] + cosTheta * v[1]; vRot[0] = vRot0; } /* Rotate a curve about the Z-axis. Can be used to make a sphere, spheroid, capsule, circular cone, circular cylinder, box, etc. The z-values should be in ascending order --- or at least the first z should be less than the last. The first and last r-values should be 0.0, and no others. Probably the t-values should be in ascending or descending order. The sideNum parameter controls the fineness of the mesh. The attributes are XYZ position, ST texture, and NOP unit normal vector. The normals are smooth. Don't forget to meshDestroy when finished. */ int meshInitializeRevolution(meshMesh *mesh, GLuint zNum, GLdouble z[], GLdouble r[], GLdouble t[], GLuint sideNum) { GLuint i, j, error; error = meshInitialize(mesh, (zNum - 2) * sideNum * 2, (zNum - 2) * (sideNum + 1) + 2, 3 + 2 + 3); if (error == 0) { /* Make the bottom triangles. */ for (i = 0; i < sideNum; i += 1) meshSetTriangle(mesh, i, 0, i + 2, i + 1); /* Make the top triangles. */ for (i = 0; i < sideNum; i += 1) meshSetTriangle(mesh, sideNum + i, mesh->vertNum - 1, mesh->vertNum - 1 - (sideNum + 1) + i, mesh->vertNum - 1 - (sideNum + 1) + i + 1); /* Make the middle triangles. */ for (j = 1; j <= zNum - 3; j += 1) for (i = 0; i < sideNum; i += 1) { meshSetTriangle(mesh, 2 * sideNum * j + 2 * i, (j - 1) * (sideNum + 1) + 1 + i, j * (sideNum + 1) + 1 + i + 1, j * (sideNum + 1) + 1 + i); meshSetTriangle(mesh, 2 * sideNum * j + 2 * i + 1, (j - 1) * (sideNum + 1) + 1 + i, (j - 1) * (sideNum + 1) + 1 + i + 1, j * (sideNum + 1) + 1 + i + 1); } /* Make the vertices, using vertex 0 as temporary storage. */ GLdouble *v = mesh->vert; GLdouble p[3], q[3], o[3]; for (j = 1; j <= zNum - 2; j += 1) { // Form the sideNum + 1 vertices in the jth layer. vecSet(3, p, z[j + 1] - z[j], 0.0, r[j] - r[j + 1]); vecUnit(3, p, p); vecSet(3, q, z[j] - z[j - 1], 0.0, r[j - 1] - r[j]); vecUnit(3, q, q); vecAdd(3, p, q, o); vecUnit(3, o, o); vecSet(8, v, r[j], 0.0, z[j], 1.0, t[j], o[0], o[1], o[2]); meshSetVertex(mesh, j * (sideNum + 1), v); v[3] = 0.0; meshSetVertex(mesh, (j - 1) * (sideNum + 1) + 1, v); for (i = 1; i < sideNum; i += 1) { meshRotateVector(2 * M_PI / sideNum, v, v); v[3] += 1.0 / sideNum; meshRotateVector(2 * M_PI / sideNum, &v[5], &v[5]); meshSetVertex(mesh, (j - 1) * (sideNum + 1) + 1 + i, v); } } /* Form the top vertex. */ vecSet(8, v, 0.0, 0.0, z[zNum - 1], 0.0, 0.0, 0.0, 0.0, 1.0); meshSetVertex(mesh, mesh->vertNum - 1, v); /* Finally form the bottom vertex. */ vecSet(8, v, 0.0, 0.0, z[0], 0.0, 0.0, 0.0, 0.0, -1.0); } return error; } /* Builds a mesh for a sphere, centered at the origin, of radius r. The sideNum and layerNum parameters control the fineness of the mesh. The attributes are XYZ position, ST texture, and NOP unit normal vector. The normals are smooth. Don't forget to meshDestroy when finished. */ int meshInitializeSphere(meshMesh *mesh, GLdouble r, GLuint layerNum, GLuint sideNum) { GLuint error, i; GLdouble *ts = (GLdouble *)malloc((layerNum + 1) * 3 * sizeof(GLdouble)); if (ts == NULL) return 1; else { GLdouble *zs = &ts[layerNum + 1]; GLdouble *rs = &ts[2 * layerNum + 2]; for (i = 0; i <= layerNum; i += 1) { ts[i] = (GLdouble)i / layerNum; zs[i] = -r * cos(ts[i] * M_PI); rs[i] = r * sin(ts[i] * M_PI); } error = meshInitializeRevolution(mesh, layerNum + 1, zs, rs, ts, sideNum); free(ts); return error; } } /* Builds a mesh for a circular cylinder with spherical caps, centered at the origin, of radius r and length l > 2 * r. The sideNum and layerNum parameters control the fineness of the mesh. The attributes are XYZ position, ST texture, and NOP unit normal vector. The normals are smooth. Don't forget to meshDestroy when finished. */ int meshInitializeCapsule(meshMesh *mesh, GLdouble r, GLdouble l, GLuint layerNum, GLuint sideNum) { GLuint error, i; GLdouble theta; GLdouble *ts = (GLdouble *)malloc((6 * layerNum + 6) * sizeof(GLdouble)); if (ts == NULL) return 1; else { GLdouble *zs = &ts[2 * layerNum + 2]; GLdouble *rs = &ts[4 * layerNum + 4]; zs[0] = -l / 2.0; rs[0] = 0.0; ts[0] = 0.0; for (i = 1; i <= layerNum; i += 1) { theta = M_PI / 2.0 * (3 + i / (GLdouble)layerNum); zs[i] = -l / 2.0 + r + r * sin(theta); rs[i] = r * cos(theta); ts[i] = (zs[i] + l / 2.0) / l; } for (i = 0; i < layerNum; i += 1) { theta = M_PI / 2.0 * i / (GLdouble)layerNum; zs[layerNum + 1 + i] = l / 2.0 - r + r * sin(theta); rs[layerNum + 1 + i] = r * cos(theta); ts[layerNum + 1 + i] = (zs[layerNum + 1 + i] + l / 2.0) / l; } zs[2 * layerNum + 1] = l / 2.0; rs[2 * layerNum + 1] = 0.0; ts[2 * layerNum + 1] = 1.0; error = meshInitializeRevolution(mesh, 2 * layerNum + 2, zs, rs, ts, sideNum); free(ts); return error; } } /* Builds a non-closed 'landscape' mesh based on a grid of Z-values. There are width * height Z-values, which arrive in the data parameter. The mesh is made of (width - 1) * (height - 1) squares, each made of two triangles. The spacing parameter controls the spacing of the X- and Y-coordinates of the vertices. The attributes are XYZ position, ST texture, and NOP unit normal vector. Don't forget to call meshDestroy when finished with the mesh. To understand the exact layout of the data, try this example code: GLdouble zs[3][4] = { {10.0, 9.0, 7.0, 6.0}, {6.0, 5.0, 3.0, 1.0}, {4.0, 3.0, -1.0, -2.0}}; int error = meshInitializeLandscape(&mesh, 3, 4, 20.0, (GLdouble *)zs); */ int meshInitializeLandscape(meshMesh *mesh, GLuint width, GLuint height, GLdouble spacing, GLdouble *data) { GLuint i, j, error; GLuint a, b, c, d; GLdouble *vert, diffSWNE, diffSENW; error = meshInitialize(mesh, 2 * (width - 1) * (height - 1), width * height, 3 + 2 + 3); if (error == 0) { /* Build the vertices with normals set to 0. */ for (i = 0; i < width; i += 1) for (j = 0; j < height; j += 1) { vert = meshGetVertexPointer(mesh, i * height + j); vecSet(3 + 2 + 3, vert, i * spacing, j * spacing, data[i * height + j], (GLdouble)i, (GLdouble)j, 0.0, 0.0, 0.0); } /* Build the triangles. */ for (i = 0; i < width - 1; i += 1) for (j = 0; j < height - 1; j += 1) { GLuint index = 2 * (i * (height - 1) + j); a = i * height + j; b = (i + 1) * height + j; c = (i + 1) * height + (j + 1); d = i * height + (j + 1); diffSWNE = fabs(meshGetVertexPointer(mesh, a)[2] - meshGetVertexPointer(mesh, c)[2]); diffSENW = fabs(meshGetVertexPointer(mesh, b)[2] - meshGetVertexPointer(mesh, d)[2]); if (diffSENW < diffSWNE) { meshSetTriangle(mesh, index, d, a, b); meshSetTriangle(mesh, index + 1, b, c, d); } else { meshSetTriangle(mesh, index, a, b, c); meshSetTriangle(mesh, index + 1, a, c, d); } } /* Set the normals. */ meshSmoothNormals(mesh, 5); } return error; } /* Given a landscape, such as that built by meshInitializeLandscape. Builds a new landscape mesh by extracting triangles based on how horizontal they are. If noMoreThan is true, then triangles are kept that deviate from horizontal by no more than angle. If noMoreThan is false, then triangles are kept that deviate from horizontal by more than angle. Don't forget to call meshDestroy when finished. Warning: May contain extraneous vertices not used by any triangle. */ int meshInitializeDissectedLandscape(meshMesh *mesh, meshMesh *land, GLdouble angle, GLuint noMoreThan) { GLuint error, i, j = 0, triNum = 0; GLuint *tri, *newTri; GLdouble normal[3]; /* Count the triangles that are nearly horizontal. */ for (i = 0; i < land->triNum; i += 1) { tri = meshGetTrianglePointer(land, i); meshTrueNormal(meshGetVertexPointer(land, tri[0]), meshGetVertexPointer(land, tri[1]), meshGetVertexPointer(land, tri[2]), normal); if ((noMoreThan && normal[2] >= cos(angle)) || (!noMoreThan && normal[2] < cos(angle))) triNum += 1; } error = meshInitialize(mesh, triNum, land->vertNum, 3 + 2 + 3); if (error == 0) { /* Copy all of the vertices. */ vecCopy(land->vertNum * (3 + 2 + 3), land->vert, mesh->vert); /* Copy just the horizontal triangles. */ for (i = 0; i < land->triNum; i += 1) { tri = meshGetTrianglePointer(land, i); meshTrueNormal(meshGetVertexPointer(land, tri[0]), meshGetVertexPointer(land, tri[1]), meshGetVertexPointer(land, tri[2]), normal); if ((noMoreThan && normal[2] >= cos(angle)) || (!noMoreThan && normal[2] < cos(angle))) { newTri = meshGetTrianglePointer(mesh, j); newTri[0] = tri[0]; newTri[1] = tri[1]; newTri[2] = tri[2]; j += 1; } } /* Reset the normals, to make the cliff edges appear sharper. */ meshSmoothNormals(mesh, 5); } return error; }
{ "content_hash": "ef5929a44ec95f8f09e97fd044f253d1", "timestamp": "", "source": "github", "line_count": 565, "max_line_length": 157, "avg_line_length": 37.290265486725666, "alnum_prop": 0.635863116426978, "repo_name": "xxf1995/CS311-Computer-Graphics", "id": "2d14a0491cf57991b1278e923722120e8fe47e1b", "size": "21069", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Second Half/520 Camera/510mesh.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4340265" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_45) on Wed Mar 04 22:48:15 CET 2015 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.optaplanner.examples.cheaptime.swingui.CheapTimePanel (OptaPlanner distribution 6.2.0.Final API) </TITLE> <META NAME="date" CONTENT="2015-03-04"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.optaplanner.examples.cheaptime.swingui.CheapTimePanel (OptaPlanner distribution 6.2.0.Final API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/optaplanner/examples/cheaptime/swingui/CheapTimePanel.html" title="class in org.optaplanner.examples.cheaptime.swingui"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>OptaPlanner distribution 6.2.0.Final</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/optaplanner/examples/cheaptime/swingui//class-useCheapTimePanel.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CheapTimePanel.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.optaplanner.examples.cheaptime.swingui.CheapTimePanel</B></H2> </CENTER> No usage of org.optaplanner.examples.cheaptime.swingui.CheapTimePanel <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/optaplanner/examples/cheaptime/swingui/CheapTimePanel.html" title="class in org.optaplanner.examples.cheaptime.swingui"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> <b>OptaPlanner distribution 6.2.0.Final</b></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/optaplanner/examples/cheaptime/swingui//class-useCheapTimePanel.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="CheapTimePanel.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2006-2015 <a href="http://www.jboss.org/">JBoss by Red Hat</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "c647114b0a45ceb7ea9439a60b3b2f3d", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 259, "avg_line_length": 44.73103448275862, "alnum_prop": 0.6262719703977798, "repo_name": "jormunmor/doctorado", "id": "f96f286d1a66bfce22feff1e64a51cc0cf35c469", "size": "6486", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "optaplanner-distribution-6.2.0.Final/javadocs/org/optaplanner/examples/cheaptime/swingui/class-use/CheapTimePanel.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2671" }, { "name": "C", "bytes": "14433" }, { "name": "C#", "bytes": "18659" }, { "name": "C++", "bytes": "2923396" }, { "name": "CMake", "bytes": "38809" }, { "name": "CSS", "bytes": "949322" }, { "name": "GAP", "bytes": "24568" }, { "name": "HTML", "bytes": "62229389" }, { "name": "Java", "bytes": "2437530" }, { "name": "JavaScript", "bytes": "8047306" }, { "name": "Makefile", "bytes": "293709" }, { "name": "Objective-C++", "bytes": "7535732" }, { "name": "PostScript", "bytes": "13039" }, { "name": "Python", "bytes": "4330" }, { "name": "QMake", "bytes": "5527" }, { "name": "Shell", "bytes": "2037" }, { "name": "TeX", "bytes": "2066789" } ], "symlink_target": "" }
WATCHER_DASHBOARD_DIR=$(cd $(dirname $BASH_SOURCE)/.. && pwd) function install_watcher_dashboard { setup_develop ${WATCHER_DASHBOARD_DIR} } function configure_watcher_dashboard { cp -a ${WATCHER_DASHBOARD_DIR}/watcher_dashboard/local/enabled/* ${DEST}/horizon/openstack_dashboard/local/enabled/ cp -a ${WATCHER_DASHBOARD_DIR}/watcher_dashboard/conf/* ${DEST}/horizon/openstack_dashboard/conf/ } function init_watcher_dashboard { # Setup alias for django-admin which could be different depending on distro python3 ${DEST}/horizon/manage.py collectstatic --noinput python3 ${DEST}/horizon/manage.py compress --force } # check for service enabled if is_service_enabled watcher-dashboard; then if [[ "$1" == "stack" && "$2" == "pre-install" ]]; then # Set up system services # no-op : elif [[ "$1" == "stack" && "$2" == "install" ]]; then # Perform installation of service source echo_summary "Installing Watcher Dashboard" install_watcher_dashboard elif [[ "$1" == "stack" && "$2" == "post-config" ]]; then # Configure after the other layer 1 and 2 services have been configured echo_summary "Configurng Watcher Dashboard" configure_watcher_dashboard init_watcher_dashboard elif [[ "$1" == "stack" && "$2" == "extra" ]]; then # no-op : fi if [[ "$1" == "unstack" ]]; then rm -f ${DEST}/horizon/openstack_dashboard/local/enabled/_310* rm -f ${DEST}/horizon/openstack_dashboard/conf/watcher* fi if [[ "$1" == "clean" ]]; then # Remove state and transient data # Remember clean.sh first calls unstack.sh # no-op : fi fi
{ "content_hash": "a309c5066869446d2cb862bc6fd3e903", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 119, "avg_line_length": 32.129629629629626, "alnum_prop": 0.6207492795389049, "repo_name": "openstack/watcher-dashboard", "id": "3cb20d84b92e43c07ae472703533c35da743ddf0", "size": "1803", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "devstack/plugin.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "34377" }, { "name": "JavaScript", "bytes": "2386" }, { "name": "Python", "bytes": "181244" }, { "name": "SCSS", "bytes": "131" }, { "name": "Shell", "bytes": "21121" } ], "symlink_target": "" }
package com.jme3.system.jopenvr; import com.sun.jna.Callback; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; /** * <i>native declaration : headers\openvr_capi.h:1918</i><br> * This file was autogenerated by <a href="http://jnaerator.googlecode.com/">JNAerator</a>,<br> * a tool written by <a href="http://ochafik.com/">Olivier Chafik</a> that <a href="http://code.google.com/p/jnaerator/wiki/CreditsAndLicense">uses a few opensource projects.</a>.<br> * For help, please visit <a href="http://nativelibs4java.googlecode.com/">NativeLibs4Java</a> , <a href="http://rococoa.dev.java.net/">Rococoa</a>, or <a href="http://jna.dev.java.net/">JNA</a>. */ public class VR_IVRDriverManager_FnTable extends Structure { /** C type : GetDriverCount_callback* */ public VR_IVRDriverManager_FnTable.GetDriverCount_callback GetDriverCount; /** C type : GetDriverName_callback* */ public VR_IVRDriverManager_FnTable.GetDriverName_callback GetDriverName; /** <i>native declaration : headers\openvr_capi.h:1916</i> */ public interface GetDriverCount_callback extends Callback { int apply(); }; /** <i>native declaration : headers\openvr_capi.h:1917</i> */ public interface GetDriverName_callback extends Callback { int apply(int nDriver, Pointer pchValue, int unBufferSize); }; public VR_IVRDriverManager_FnTable() { super(); } protected List<String> getFieldOrder() { return Arrays.asList("GetDriverCount", "GetDriverName"); } /** * @param GetDriverCount C type : GetDriverCount_callback*<br> * @param GetDriverName C type : GetDriverName_callback* */ public VR_IVRDriverManager_FnTable(VR_IVRDriverManager_FnTable.GetDriverCount_callback GetDriverCount, VR_IVRDriverManager_FnTable.GetDriverName_callback GetDriverName) { super(); this.GetDriverCount = GetDriverCount; this.GetDriverName = GetDriverName; } public VR_IVRDriverManager_FnTable(Pointer peer) { super(peer); } public static class ByReference extends VR_IVRDriverManager_FnTable implements Structure.ByReference { }; public static class ByValue extends VR_IVRDriverManager_FnTable implements Structure.ByValue { }; }
{ "content_hash": "233d813118815aa487c14b8002648154", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 195, "avg_line_length": 44.6, "alnum_prop": 0.7336322869955157, "repo_name": "atomixnmc/jmonkeyengine", "id": "4bd9188599618f1ac934aa42f9616849958f45a9", "size": "2230", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jme3-vr/src/main/java/com/jme3/system/jopenvr/VR_IVRDriverManager_FnTable.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "36480" }, { "name": "C++", "bytes": "336392" }, { "name": "GLSL", "bytes": "215258" }, { "name": "HTML", "bytes": "1599217" }, { "name": "Java", "bytes": "15010790" }, { "name": "Makefile", "bytes": "6895" }, { "name": "Python", "bytes": "307608" }, { "name": "Shell", "bytes": "1442" } ], "symlink_target": "" }
/* eslint-disable */ var assert = require('chai').assert; var randtoken = require('rand-token'); var taskManager = require(__js+'/taskManager'); var refAddr; var testTask = { id: "test0", title: "TestTitle_taskManager", desc: "Test Description", status: "To Do", complete: "0/?", reward: "200", participants: ["bkrem_", "yellouw", "drBombo"], creator: "Ben", createdAt: String(Date.now()), token: randtoken.generate(8) }; // Establish proper task type by adding `address` key, // which is added on by the chain automagically var taskType = Object.keys(testTask); taskType.push('address'); describe("Task Manager", function () { this.timeout(3000); describe("addTask", function () { it("adds the given task object to the chain and returns the registered task's hex address", function(done) { taskManager.addTask(testTask, function (error, address) { assert.isNull(error); assert.isString(address, "`address` should be the registered task's hex address"); done(); }); }); }); describe("getTaskAtIndex", function () { it("returns the address of the task at the passed index and its `nextIndex` indicator", function (done) { taskManager.getTaskAtIndex(0, function (error, data) { assert.isNull(error); assert.notEqual(data[0], null, "returned address should never be null"); assert.notEqual(data[1], null, "returned nextIdx should never be null"); done(); }) }) }) describe("getTaskListSize", function () { it("returns the current total size of the task list map", function (done) { taskManager.getTaskListSize(function (error, size) { assert.isNull(error); assert.notEqual(size, null, "`size` should return 0 or greater"); done(); }) }) }); describe("getAllTasks", function () { it("retrieves all tasks from the given start index onwards", function (done) { taskManager.getAllTaskAddresses(function (err, addresses) { assert.isNull(err); assert.isNotNull(addresses, "`addresses` array should not be null"); assert.isAtLeast(addresses.length, 1, "There should be at least 1 element from running the `addTask` test"); // address of `mockTest` is the latest addition to array refAddr = addresses[addresses.length-1]; done(); }); }) }); describe("getTaskAtAddress", function () { it("retrieves the task contract registered at the passed address and transforms it into a task object", function (done) { taskManager.getTaskAtAddress(refAddr, function (err, task) { assert.isNull(err); assert.notDeepEqual(task, {}, "returned task object should not be empty"); assert.sameMembers(Object.keys(task), taskType, "returned task object's keys should adhere to Task type"); assert.strictEqual(task.id, testTask.id) // can't deepEqual whole object since `address` can't be predicted for (var prop in task) { if ({}.hasOwnProperty.call(task, prop)) assert.notStrictEqual(task[prop], "", "returned task object should have no empty string values"); } done(); }); }); }); describe("getTaskAddressFromToken", function () { it("retrieves a task address that matches the passed attachment token", function (done) { taskManager.getTaskAddressFromToken(testTask.token, function (err, taskAddr) { assert.isNull(err); assert.strictEqual(taskAddr, refAddr); done(); }); }); }); describe("markTaskCompleted", function () { it("marks the task associated to the passed address as complete and returns a success bool", function (done) { taskManager.markTaskCompleted(refAddr, function (err, success) { assert.isNull(err); assert.strictEqual(success, true); done(); }); }); }); }); require('./userManager_test');
{ "content_hash": "6d13a126bc2d1d2747202d91d93b969a", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 129, "avg_line_length": 38.690265486725664, "alnum_prop": 0.5832570905763952, "repo_name": "bkrem/educhain", "id": "d942c130fb720a27deef40beb8c2f9c5ffdf5c63", "size": "4372", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chain/test/taskManager_test.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1125" }, { "name": "JavaScript", "bytes": "40435" }, { "name": "Objective-C", "bytes": "5229" }, { "name": "Python", "bytes": "1646" }, { "name": "Shell", "bytes": "833" } ], "symlink_target": "" }
<?php namespace Application\Controller; use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; class IndexController extends AbstractActionController { private $config; public function indexAction() { $this->getConfig(); $titulo = $this->config['parametros']['mvc']['application']['index']['titulo']; return $this->redirect()->toRoute('usuarios', array( 'controller' => 'index', 'action' => 'index' )); } public function getConfig(){ if(!$this->config){ $sm = $this->getServiceLocator(); $this->config = $sm->get('ConfigIni'); } return $this->config; } }
{ "content_hash": "f4ed11e457ed0ee680cbaa85221f0a33", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 87, "avg_line_length": 24.387096774193548, "alnum_prop": 0.5515873015873016, "repo_name": "jpcodezur/tesisenlinea", "id": "6dfab6bb9a2c66d37283f57699bea01338391879", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/Application/src/Application/Controller/IndexController.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "711" }, { "name": "CSS", "bytes": "249892" }, { "name": "HTML", "bytes": "608152" }, { "name": "JavaScript", "bytes": "501630" }, { "name": "PHP", "bytes": "279300" } ], "symlink_target": "" }
"use strict"; function mergeOTLTables(dst, src, priorizeSrc) { if (!dst || !src) return; for (const fid in src.features) { dst.features[fid] = src.features[fid]; } for (const lid in src.lookups) { dst.lookups[lid] = src.lookups[lid]; } for (const lid in src.languages) { if (dst.languages[lid]) { dst.languages[lid].features = dst.languages[lid].features.concat( src.languages[lid].features ); } else { dst.languages[lid] = src.languages[lid]; } } if (priorizeSrc) { dst.lookupOrder = [src.lookupOrder || [], dst.lookupOrder || []]; } else { dst.lookupOrder = [dst.lookupOrder || [], src.lookupOrder || []]; } } exports.mergeOTLTables = mergeOTLTables; exports.mergeGDEF = function(first, second) { return { markAttachClassDef: Object.assign({}, first.markAttachClassDef, second.markAttachClassDef), glyphClassDef: Object.assign({}, first.glyphClassDef, second.glyphClassDef), ligCarets: Object.assign({}, first.ligCarets, second.ligCarets) }; };
{ "content_hash": "afb12f56a60dadcff217345d4514ecbd", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 93, "avg_line_length": 30.235294117647058, "alnum_prop": 0.6614785992217899, "repo_name": "caryll/Megaminx", "id": "a0baa672966d6635ae82ec0525f276a80a13f1f3", "size": "1028", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "procs/merge/mergeOTL.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "43341" } ], "symlink_target": "" }
<readable><title>3726076549_0efb38854b</title><content> A boy in jeans , black t-shirt , and blue cap on a bike , leaps over steps . An Asian man in a black shirt and jeans rides his black and red bicycle down a railing . A teenager performs a railgrind on his bicycle . Man sliding down stair handrails on a bike . This man has balanced his bicycle on a handrail . </content></readable>
{ "content_hash": "fe452feddba9c74c6f5aebbd75a78465", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 88, "avg_line_length": 55.285714285714285, "alnum_prop": 0.7622739018087855, "repo_name": "kevint2u/audio-collector", "id": "eae1b14ac561888f8069d80bf942e87e8443d5d5", "size": "387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "captions/xml/3726076549_0efb38854b.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1015" }, { "name": "HTML", "bytes": "18349" }, { "name": "JavaScript", "bytes": "109819" }, { "name": "Python", "bytes": "3260" }, { "name": "Shell", "bytes": "4319" } ], "symlink_target": "" }
<?php namespace Doctrine\ODM\MongoDB\Tests\Functional; use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM; class DocumentPersisterTest extends \Doctrine\ODM\MongoDB\Tests\BaseTest { private $class; private $documentPersister; public function setUp() { parent::setUp(); $this->class = __NAMESPACE__ . '\DocumentPersisterTestDocument'; $collection = $this->dm->getDocumentCollection($this->class); $collection->drop(); foreach (array('a', 'b', 'c', 'd') as $name) { $document = array('dbName' => $name); $collection->insert($document); } $this->documentPersister = $this->uow->getDocumentPersister($this->class); } public function testExecuteUpsertShouldNeverReplaceDocuments() { $originalData = $this->dm->getDocumentCollection($this->class)->findOne(); $document = new DocumentPersisterTestDocument(); $document->id = $originalData['_id']; $this->dm->persist($document); $this->dm->flush(); $updatedData = $this->dm->getDocumentCollection($this->class)->findOne(array('_id' => $originalData['_id'])); $this->assertEquals($originalData, $updatedData); } public function testLoadPreparesCriteriaAndSort() { $criteria = array('name' => array('$in' => array('a', 'b'))); $sort = array('name' => -1); $document = $this->documentPersister->load($criteria, null, array(), 0, $sort); $this->assertInstanceOf($this->class, $document); $this->assertEquals('b', $document->name); } public function testLoadAllPreparesCriteriaAndSort() { $criteria = array('name' => array('$in' => array('a', 'b'))); $sort = array('name' => -1); $cursor = $this->documentPersister->loadAll($criteria, $sort); $documents = iterator_to_array($cursor, false); $this->assertInstanceOf($this->class, $documents[0]); $this->assertEquals('b', $documents[0]->name); $this->assertInstanceOf($this->class, $documents[1]); $this->assertEquals('a', $documents[1]->name); } public function testLoadAllWithSortLimitAndSkip() { $sort = array('name' => -1); $cursor = $this->documentPersister->loadAll(array(), $sort, 1, 2); $documents = iterator_to_array($cursor, false); $this->assertInstanceOf($this->class, $documents[0]); $this->assertEquals('b', $documents[0]->name); $this->assertCount(1, $documents); } public function testLoadAllWithSortLimitAndSkipAndRecreatedCursor() { $sort = array('name' => -1); $cursor = $this->documentPersister->loadAll(array(), $sort, 1, 2); $cursor = clone $cursor; $cursor->recreate(); $documents = iterator_to_array($cursor, false); $this->assertInstanceOf($this->class, $documents[0]); $this->assertEquals('b', $documents[0]->name); $this->assertCount(1, $documents); } /** * @dataProvider getTestPrepareFieldNameData */ public function testPrepareFieldName($fieldName, $expected) { $this->assertEquals($expected, $this->documentPersister->prepareFieldName($fieldName)); } public function getTestPrepareFieldNameData() { return array( array('name', 'dbName'), array('association', 'associationName'), array('association.id', 'associationName._id'), array('association.nested', 'associationName.nestedName'), array('association.nested.$id', 'associationName.nestedName.$id'), array('association.nested._id', 'associationName.nestedName._id'), array('association.nested.id', 'associationName.nestedName._id'), array('association.nested.association.nested.$id', 'associationName.nestedName.associationName.nestedName.$id'), array('association.nested.association.nested.id', 'associationName.nestedName.associationName.nestedName._id'), array('association.nested.association.nested.firstName', 'associationName.nestedName.associationName.nestedName.firstName'), ); } /** * @dataProvider provideHashIdentifiers */ public function testPrepareQueryOrNewObjWithHashId($hashId) { $class = __NAMESPACE__ . '\DocumentPersisterTestHashIdDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $value = array('_id' => $hashId); $expected = array('_id' => (object) $hashId); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } /** * @dataProvider provideHashIdentifiers */ public function testPrepareQueryOrNewObjWithHashIdAndInOperators($hashId) { $class = __NAMESPACE__ . '\DocumentPersisterTestHashIdDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $value = array('_id' => array('$exists' => true)); $expected = array('_id' => array('$exists' => true)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('_id' => array('$elemMatch' => $hashId)); $expected = array('_id' => array('$elemMatch' => (object) $hashId)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('_id' => array('$in' => array($hashId))); $expected = array('_id' => array('$in' => array((object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('_id' => array('$not' => array('$elemMatch' => $hashId))); $expected = array('_id' => array('$not' => array('$elemMatch' => (object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('_id' => array('$not' => array('$in' => array($hashId)))); $expected = array('_id' => array('$not' => array('$in' => array((object) $hashId)))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } public function provideHashIdentifiers() { return array( array(array('key' => 'value')), array(array(0 => 'first', 1 => 'second')), array(array('$ref' => 'ref', '$id' => 'id')), ); } public function testPrepareQueryOrNewObjWithSimpleReferenceToTargetDocumentWithNormalIdType() { $class = __NAMESPACE__ . '\DocumentPersisterTestHashIdDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $id = new \MongoId(); $value = array('simpleRef' => (string) $id); $expected = array('simpleRef' => $id); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$exists' => true)); $expected = array('simpleRef' => array('$exists' => true)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$elemMatch' => (string) $id)); $expected = array('simpleRef' => array('$elemMatch' => $id)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$in' => array((string) $id))); $expected = array('simpleRef' => array('$in' => array($id))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$not' => array('$elemMatch' => (string) $id))); $expected = array('simpleRef' => array('$not' => array('$elemMatch' => $id))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$not' => array('$in' => array((string) $id)))); $expected = array('simpleRef' => array('$not' => array('$in' => array($id)))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } /** * @dataProvider provideHashIdentifiers */ public function testPrepareQueryOrNewObjWithSimpleReferenceToTargetDocumentWithHashIdType($hashId) { $class = __NAMESPACE__ . '\DocumentPersisterTestDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $value = array('simpleRef' => $hashId); $expected = array('simpleRef' => (object) $hashId); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$exists' => true)); $expected = array('simpleRef' => array('$exists' => true)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$elemMatch' => $hashId)); $expected = array('simpleRef' => array('$elemMatch' => (object) $hashId)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$in' => array($hashId))); $expected = array('simpleRef' => array('$in' => array((object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$not' => array('$elemMatch' => $hashId))); $expected = array('simpleRef' => array('$not' => array('$elemMatch' => (object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('simpleRef' => array('$not' => array('$in' => array($hashId)))); $expected = array('simpleRef' => array('$not' => array('$in' => array((object) $hashId)))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } public function testPrepareQueryOrNewObjWithDBRefReferenceToTargetDocumentWithNormalIdType() { $class = __NAMESPACE__ . '\DocumentPersisterTestHashIdDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $id = new \MongoId(); $value = array('complexRef.id' => (string) $id); $expected = array('complexRef.$id' => $id); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$exists' => true)); $expected = array('complexRef.$id' => array('$exists' => true)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$elemMatch' => (string) $id)); $expected = array('complexRef.$id' => array('$elemMatch' => $id)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$in' => array((string) $id))); $expected = array('complexRef.$id' => array('$in' => array($id))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$not' => array('$elemMatch' => (string) $id))); $expected = array('complexRef.$id' => array('$not' => array('$elemMatch' => $id))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$not' => array('$in' => array((string) $id)))); $expected = array('complexRef.$id' => array('$not' => array('$in' => array($id)))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } /** * @dataProvider provideHashIdentifiers */ public function testPrepareQueryOrNewObjWithDBRefReferenceToTargetDocumentWithHashIdType($hashId) { $class = __NAMESPACE__ . '\DocumentPersisterTestDocument'; $documentPersister = $this->uow->getDocumentPersister($class); $value = array('complexRef.id' => $hashId); $expected = array('complexRef.$id' => (object) $hashId); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$exists' => true)); $expected = array('complexRef.$id' => array('$exists' => true)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$elemMatch' => $hashId)); $expected = array('complexRef.$id' => array('$elemMatch' => (object) $hashId)); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$in' => array($hashId))); $expected = array('complexRef.$id' => array('$in' => array((object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$not' => array('$elemMatch' => $hashId))); $expected = array('complexRef.$id' => array('$not' => array('$elemMatch' => (object) $hashId))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); $value = array('complexRef.id' => array('$not' => array('$in' => array($hashId)))); $expected = array('complexRef.$id' => array('$not' => array('$in' => array((object) $hashId)))); $this->assertEquals($expected, $documentPersister->prepareQueryOrNewObj($value)); } } /** @ODM\Document */ class DocumentPersisterTestDocument { /** @ODM\Id */ public $id; /** @ODM\String(name="dbName") */ public $name; /** * @ODM\EmbedOne( * targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\AbstractDocumentPersisterTestDocumentAssociation", * discriminatorField="type", * discriminatorMap={ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference", * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed" * }, * name="associationName" * ) */ public $association; /** @ODM\ReferenceOne(targetDocument="DocumentPersisterTestHashIdDocument", simple=true) */ public $simpleRef; /** @ODM\ReferenceOne(targetDocument="DocumentPersisterTestHashIdDocument") */ public $complexRef; } /** * @ODM\EmbeddedDocument * @ODM\InheritanceType("SINGLE_COLLECTION") * @ODM\DiscriminatorField(fieldName="type") * @ODM\DiscriminatorMap({ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference", * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed" * }) */ abstract class AbstractDocumentPersisterTestDocumentAssociation { /** @ODM\Id */ public $id; /** @ODM\EmbedOne(name="nestedName") */ public $nested; /** * @ODM\EmbedOne( * targetDocument="Doctrine\ODM\MongoDB\Tests\Functional\AbstractDocumentPersisterTestDocumentAssociation", * discriminatorField="type", * discriminatorMap={ * "reference"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentReference", * "embed"="Doctrine\ODM\MongoDB\Tests\Functional\DocumentPersisterTestDocumentEmbed" * }, * name="associationName" * ) */ public $association; } /** @ODM\EmbeddedDocument */ class DocumentPersisterTestDocumentReference extends AbstractDocumentPersisterTestDocumentAssociation { /** @ODM\Id */ public $id; /** @ODM\ReferenceOne(name="nestedName") */ public $nested; } /** @ODM\EmbeddedDocument */ class DocumentPersisterTestDocumentEmbed extends AbstractDocumentPersisterTestDocumentAssociation { /** @ODM\Id */ public $id; /** @ODM\EmbedOne(name="nestedName") */ public $nested; } /** @ODM\Document */ class DocumentPersisterTestHashIdDocument { /** @ODM\Id(strategy="none", options={"type"="hash"}) */ public $id; /** @ODM\ReferenceOne(targetDocument="DocumentPersisterTestDocument", simple=true) */ public $simpleRef; /** @ODM\ReferenceOne(targetDocument="DocumentPersisterTestDocument") */ public $complexRef; }
{ "content_hash": "42b4f8dba695d74b6d766ef7b30daebd", "timestamp": "", "source": "github", "line_count": 425, "max_line_length": 136, "avg_line_length": 38.39058823529412, "alnum_prop": 0.62515322382937, "repo_name": "Dpezz/tucv", "id": "be84cbec293d42f78464fca9a368a10378648398", "size": "16316", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/doctrine/mongodb-odm/tests/Doctrine/ODM/MongoDB/Tests/Functional/DocumentPersisterTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2930" }, { "name": "CSS", "bytes": "153233" }, { "name": "HTML", "bytes": "333540" }, { "name": "JavaScript", "bytes": "1001923" }, { "name": "PHP", "bytes": "202380" } ], "symlink_target": "" }
@interface TWTestViewController () @property (weak, nonatomic) IBOutlet UISlider *slider; @property (weak, nonatomic) IBOutlet UIView *contentView; @property (nonatomic, weak) CAShapeLayer *shapeLayer; @end @implementation TWTestViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self commonInit]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)valueChanged:(UISlider*)slider{ NSLog(@"slider = %@",@(slider.value)); self.shapeLayer.strokeEnd = slider.value; } - (void)commonInit{ [self.slider addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged]; CAShapeLayer *shapeLayer = [CAShapeLayer layer]; shapeLayer.bounds = CGRectMake(0, 0, 24, 24); // #EE4F52 shapeLayer.strokeColor = [UIColor colorWithRed:0xee/255.0 green:0x4f/255.0 blue:0x52/255.0 alpha:1].CGColor; shapeLayer.lineWidth = 1.5; shapeLayer.strokeStart = 0; shapeLayer.strokeEnd = 0; shapeLayer.fillColor = [UIColor clearColor].CGColor; self.shapeLayer = shapeLayer; UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(12, 12) radius:12 startAngle:0 endAngle:2 *M_PI clockwise:YES]; shapeLayer.path = path.CGPath; [self.contentView.layer addSublayer:shapeLayer]; } @end
{ "content_hash": "57fccb0de652628c200adf4e70c1c697", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 138, "avg_line_length": 27.185185185185187, "alnum_prop": 0.7064032697547684, "repo_name": "wangdxnum1/MyTestProject", "id": "4e5034b3c55124324ea3af781f941535f8f2b590", "size": "1646", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TWMyScrollView/TWMyScrollView/TWTestViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "52236" }, { "name": "C++", "bytes": "14662" }, { "name": "DTrace", "bytes": "412" }, { "name": "HTML", "bytes": "218" }, { "name": "Makefile", "bytes": "86" }, { "name": "Objective-C", "bytes": "2566813" }, { "name": "Perl", "bytes": "799" }, { "name": "Python", "bytes": "4019" }, { "name": "QMake", "bytes": "450" }, { "name": "Ruby", "bytes": "2609" }, { "name": "Shell", "bytes": "73398" }, { "name": "Swift", "bytes": "180449" } ], "symlink_target": "" }
package org.apache.storm; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.storm.generated.StormTopology; import org.apache.storm.testing.CompleteTopologyParam; import org.apache.storm.testing.FixedTuple; import org.apache.storm.testing.MockedSources; import org.apache.storm.testing.TestGlobalCount; import org.apache.storm.testing.TestWordSpout; import org.apache.storm.topology.TopologyBuilder; import org.junit.Assert; import org.junit.Test; public class MessagingTest { @Test public void testLocalTransport() throws Exception { Config topoConf = new Config(); topoConf.put(Config.TOPOLOGY_WORKERS, 2); topoConf.put(Config.STORM_MESSAGING_TRANSPORT, "org.apache.storm.messaging.netty.Context"); try (ILocalCluster cluster = new LocalCluster.Builder().withSimulatedTime() .withSupervisors(1).withPortsPerSupervisor(2) .withDaemonConf(topoConf).build()) { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("1", new TestWordSpout(true), 2); builder.setBolt("2", new TestGlobalCount(), 6).shuffleGrouping("1"); StormTopology stormTopology = builder.createTopology(); List<FixedTuple> fixedTuples = new ArrayList<>(); for (int i = 0; i < 12; i++) { fixedTuples.add(new FixedTuple(Collections.singletonList("a"))); fixedTuples.add(new FixedTuple(Collections.singletonList("b"))); } Map<String, List<FixedTuple>> data = new HashMap<>(); data.put("1", fixedTuples); MockedSources mockedSources = new MockedSources(data); CompleteTopologyParam completeTopologyParam = new CompleteTopologyParam(); completeTopologyParam.setMockedSources(mockedSources); Map<String, List<FixedTuple>> results = Testing.completeTopology(cluster, stormTopology, completeTopologyParam); Assert.assertEquals(6 * 4, Testing.readTuples(results, "2").size()); } } }
{ "content_hash": "5197afe58538e47d46fdfcea0a876322", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 124, "avg_line_length": 43.8235294117647, "alnum_prop": 0.6590604026845638, "repo_name": "srdo/storm", "id": "18cfc373ebecbf347950a579b2b2f220fa834d87", "size": "3019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "storm-server/src/test/java/org/apache/storm/MessagingTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "53871" }, { "name": "CSS", "bytes": "12597" }, { "name": "Clojure", "bytes": "494628" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "HTML", "bytes": "187245" }, { "name": "Java", "bytes": "11668041" }, { "name": "JavaScript", "bytes": "74069" }, { "name": "M4", "bytes": "1522" }, { "name": "Makefile", "bytes": "1302" }, { "name": "PowerShell", "bytes": "3405" }, { "name": "Python", "bytes": "954624" }, { "name": "Ruby", "bytes": "15777" }, { "name": "Shell", "bytes": "23774" }, { "name": "Thrift", "bytes": "31552" }, { "name": "XSLT", "bytes": "1365" } ], "symlink_target": "" }
date: '2016-10-31 23:59:59 GMT-2' excerpt: "Being able to upgrade from one release to another is a certainty openSUSE users have. For 3 years now I use openSUSE Linux and I always upgraded without an issue. I started to use openSUSE when it was 12.2, shortly before the 12.3 release in May 2013. Since then I went through 5 upgrades: from 12.2 to 12.3, to 13.1, to 13.2, to Leap 42.1 (in fact, there was a leap, as we have seen on that release's announcement) and this week to 42.2, even before it was officially launched." layout: post published: true title: 'How to upgrade from openSUSE Leap 42.1 to 42.2' image: /files/2016/10/upgrade.png nickname: 'how-to-upgrade' --- {% include image.html src="/files/2016/10/upgrade.png" caption="Source: [openSUSE News](https://news.opensuse.org/2016/09/22/new-leap-beta-adds-plasma-5-8-beta/)" %} Being able to upgrade from one release to another is a certainty [openSUSE][opensuse] users have. For 3 years now I use openSUSE Linux and I always upgraded without an issue. I started to use openSUSE when it was 12.2, shortly before the [12.3 release in May 2013][opensuse-123]. Since then I went through 5 upgrades: from 12.2 to 12.3, to 13.1, to 13.2, to Leap 42.1 (in fact, there was a leap, as we have seen on [that release's announcement]({% post_url en/2015-11-04-opensuse-leap-42-1-becomes-first-hybrid-distribution %})) and this week to 42.2, even before it was officially launched. The next openSUSE Leap release, 42.2, already passed alfa and beta phases and had its first release candidate (RC) launched on [October 18][opensuse-422-rc1]. That means most of the tests have ended. That release is very close to the final one, scheduled to [November 16][opensuse-roadmap]. Until then, openSUSE Leap should receive no more than a few finishing touches. Checkout this post to know beforehand how to upgrade your openSUSE Leap installation from 42.1 to 42.2. If you are the kind of person who prefers safety to adventure, here you are going to see what you will do on November 16, after the official release of openSUSE Leap 42.2. If you prefer adventure, like me, you are going to see what you can do to get the coming 42.2 right now. At least both the computers I use at home and work are now working well with openSUSE Leap 42.2 RC 1. To better organize the text, I split the upgrade process in 6 steps. ## A few notes The how-to I present here is based on the openSUSE wiki's [SDB:System upgrade][system-upgrade] page, whose instructions I followed to upgrade my system. That page has changed little since I started using openSUSE. It presents a safe upgrade procedure, which should work for most cases, but requires some things be observed. **You must be using the immediately previous openSUSE release.** It means that if you want to upgrade to 42.2, now you must be using 42.1. Hopping over one or more releases is not supported and probably will not work. So if you use openSUSE 13.2, for example, you must first upgrade to Leap 42.1, and then to Leap 42.2 (note that the leap here is just in numbers, [the Leap 42.1 release is indeed the successor of 13.2]({% post_url en/2015-11-04-opensuse-leap-42-1-becomes-first-hybrid-distribution %})). **Your openSUSE installation must be up to date** with the latest updates for the release you are currently running. To learn how to update your system, read the [previous post]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}). **You should read about the openSUSE release you are going to install.** Read the [list of annoying bugs][most-annoying-bugs] to be prepared for upcoming problems, how to prevent and/or solve them. Also, read the [release notes][release-notes], which list changes and glitches in the new release. **You must backup all important data.** Even though upgrading openSUSE is a safe procedure, that resembles upgrading [Debian][debian], it is not perfect. Winning the lottery is difficult, but eventually someone wins. Something may go wrong during upgrade, but it is difficult, even more if you do things cautiously. Anyway, it never hurts to make a backup of your personal files as a precaution, especially if the `/home` directory is not on a dedicated partition. If the computer is one that should not be down for long (a server, for example), consider backing up the entire system, so you will be able to restore it immediately if something does not work as expected. **You should not use third party repositories during upgrade.** Before upgrading, we are going to remove all third party repositories. Doing that may cause third party software to be removed during upgrade. If that happens, you may try to reinstall it later. It does not mean that you cannot upgrade with third party repositories enabled, but using only the official repositories is more guaranteed. That way, the base system will be upgraded to a new stable, solid and reliable base. Then, on top of that base, you can install whatever you want. Do different only if you know what you are doing. I also recommend that you read this entire page before you actually upgrade. Once you know the whole process, you will be able to better schedule it. You can even use your computer while downloading packages, but after you start upgrading, your computer will become usable again only after upgrading is completed. Before we begin, I would like to make one more note, for those who want to upgrade to openSUSE Leap 42.2 before the final release date. If that is your case, please note that you will need to repeat the steps "download packages" and "upgrade your system", the last two steps in this tutorial (5 and 6), for each new release of this version. So, you will repeat those steps on November 2, when Leap 42.2 RC 2 is scheduled to be released, and on November 16, after the final release of Leap 42.2. ## 1) Update your current system Before beginning, make sure your openSUSE installation is up to date. As we have seen in the [previous post]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}), if your system is up to date, the **Software Updates** icon informs that to you: {% include image.html src="/files/2016/10/sw-updates-05-en.jpg" %} Or, if you prefer using the command line interface (CLI), you can check if your system is up to date running `zypper up` as root. If that is the case, it returns "Nothing to do": {% include image.html src="/files/2016/10/sw-updates-cmd-05-en.jpg" %} Take a look at [that post]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}) to see how to update your openSUSE. Let me clarify something, in case it sounds confusing: by **update** we mean update just a few packages without actually moving from one release to another (e.g. from 42.1 to 42.2). By **upgrade** we mean update the whole system to move to the next release. I use the graphical user interface (GUI) whenever possible, but using the CLI brings us some advantages: **zypper** allows us to only download updates in a first moment and then install them later. If you are not familiar with the CLI, you will realize that it is not difficult to use. Note that, almost always, you can use the CLI without actually leaving the desktop environment through the [**Konsole**][konsole] application. To start it, open the **Application Menu**, point to **System**, and then click **Konsole**: {% include image.html src="/files/2016/10/upgrade-01-en.jpg" %} If you are familiar with [Windows][windows], perhaps you think Konsole resembles Windows' **Command Prompt**. ## 2) Backup your current repositories Actually, this step is optional. You may want to back up your current list of repositories to return them after upgrading. openSUSE saves repository settings in the `/etc/zypp/repos.d` folder. It has some text files, one for each repository. Let's backup that folder using the CLI. Get root privileges running `su` (if you are not familiar with the CLI, by "running `su`", we mean "type `su` and hit **Enter**"). You will be asked the root password, which you must provide to continue (type the root password and hit **Enter**, note that the password is not displayed, not even masked as ******, this is normal). Then, order the copy running `cp -Rv /etc/zypp/repos.d /etc/zypp/repos.d.old`: {% include image.html src="/files/2016/10/upgrade-02-en.jpg" %} That command copies the `repos.d` folder, in `/etc/zypp`, to another folder in the same place, called `repos.d.old`. If you have not made a backup of your data yet, consider doing that now. ## 3) Clean up repositories As already mentioned, for upgrade we use only the [official repositories][official-repos]. To be more precise, just two of them: - **openSUSE-Leap-42.2-OSS**: the main repository, contains [open source software][oss] only. URL: [http://download.opensuse.org/distribution/leap/42.2/repo/oss/][repo-oss] - **openSUSE-Leap-42.2-Update**: contains official updates for OSS packages. URL: [http://download.opensuse.org/update/leap/42.2/oss/][repo-update] Let's clean up our repositories removing any repository we won't need (including any [third party repositories][third-party-repos]). Start the YaST Control Center by opening the **Application Menu**, pointing to **System**, and then clicking on **YaST**: {% include image.html src="/files/2016/10/linux-ntp-01.jpg" %} You will be asked the root password. Select the **Software** category, then click on **Software Repositories**: {% include image.html src="/files/2016/10/upgrade-03-en.png" %} You are presented to your system's repository list: {% include image.html src="/files/2016/10/upgrade-04-en.jpg" %} For each repository that is neither **openSUSE-Leap-42.1-OSS** nor **openSUSE-Leap-42.1-Update**, select it in the list and click on **Delete** (no typo, we are managing old repositories, the 42.1 ones, we are going to switch to the new ones soon). YaST will ask you for confirmation. Click on **Yes**: {% include image.html src="/files/2016/10/upgrade-05-en.jpg" %} Do that with all repositories, until the list has only **openSUSE-Leap-42.1-OSS** and **openSUSE-Leap-42.1-Update**: {% include image.html src="/files/2016/10/upgrade-06-en.jpg" %} Maybe those repositories are named differently on your system. If that is the case, try to recognize them by their [URL][url] instead of their name. If you don't find them, there is no problem: delete all repositories and add just the new ones. ## 4) Switch to the new repositories Now let's move to the new release's repositories. Select the **openSUSE-42.1-Leap-OSS** repository and click on **Edit**. Replace `42.1` by `42.2` where necessary and click on **OK**: {% include image.html src="/files/2016/10/upgrade-07-en.jpg" %} You are presented to the [openSUSE Leap 42.2 license][opensuse-license]. You can read it to know your rights as an openSUSE user. When you are finished, click on **Next**: {% include image.html src="/files/2016/10/upgrade-08-en.jpg" %} Do the same for the **openSUSE-Leap-42.1-Update** repository. At the end, your system's repository list should look like this: {% include image.html src="/files/2016/10/upgrade-09-en.jpg" %} Click on **OK** to save changes. You can close YaST. ## 5) Download packages We can start downloading the packages of the new openSUSE release. Back to CLI, run `zypper ref` to retrieve the list of available packages from the new repositories. Then, run `zypper dup --download-only` (`dup` is an acronym for *distribution upgrade*): {% include image.html src="/files/2016/10/upgrade-10-en.jpg" %} **zypper** spends some time "thinking". Soon after, it shows what it needs to do in order to upgrade openSUSE to the next release and asks if you want to continue: {% include image.html src="/files/2016/10/upgrade-11-en.jpg" %} That list of actions is similar to that produced by `zypper up`, presented in the [previous post]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}). However, as we are now doing a distribution upgrade, and not an ordinary update, the list of what needs to be done is much bigger. Review that list carefully. You can go up or down using the scrollbar at the right of the window or the mouse wheel (scroll wheel) if you are using Konsole, or the **Shift + Page Up** / **Shift + Page Down** key combinations if you are using a purely textual interface (they also work in Konsole). The default option is to continue (**s**). If you agree, you can just hit **Enter** and downloading of the new packages will start. Meanwhile, you can use your computer normally. The upgrade itself has not started yet. Note that **zypper** only downloads packages, it does not start upgrading: {% include image.html src="/files/2016/10/upgrade-12-en.jpg" %} That's because we invoked it with the `--download-only` option. Finish what you are doing and save any open files so we can start upgrading. Note that upgrading may take several minutes and you will be able to continue using your computer only after it is complete. ## 6) Upgrade your system Now that we have already downloaded all the packages needed to update our openSUSE Leap 42.1 to 42.2, we need to leave the desktop environment and use the pure textual interface to perform the upgrade. Here on, you cannot use Konsole. That is necessary because the desktop itself will be upgraded. If we run the upgrade while still using the desktop, it may stop/crash, causing the upgrade to abort, which in turn left the system in an inconsistent, unpredictable state. Consider open this page on another computer (or on a mobile device), print it or take note of the next actions. If you are upgrading a laptop system, make sure its battery is fully charged and its AC adapter is plugged in. Do not remove the battery or unplug the AC adapter during the upgrade. We want to prevent any possibility of problem. Logout by opening the **Application Menu**, pointing to **Power / Session** and clicking on **Logout**: {% include image.html src="/files/2016/10/logout-kde-en.jpg" %} You are presented to the login screen where you could enter your username and password to start a new desktop session: {% include image.html src="/files/2016/10/upgrade-13-en.jpg" %} But that's not what we want. Press the **Ctrl + Alt + F1** key combination to switch to a purely textual interface: {% include image.html src="/files/2016/10/upgrade-14.jpg" %} If that was new to you, know that Linux provides six [consoles][terminal] besides the graphical interface. You can use the keys F1 to F6 in that same combination (**Ctrl + Alt + F1**, **Ctrl + Alt + F2** and so on) to switch between consoles, pressing **Ctrl + Alt + F7** you can return to the graphical interface. But let's stand on the first console. Login as root (to do that, type `root` and press **Enter**, then enter the root password and press **Enter** again). Let's switch from [runlevel][runlevel] 5, the default runlevel, in which the system provides the GUI, to the runlevel 3, in which we have only the CLI and network connection. To [change to runlevel][switch-runlevel] 3, run `init 3`. Finally, we are going to start the distribution upgrade itself. Run `zypper --no-refresh dup`: {% include image.html src="/files/2016/10/upgrade-15.jpg" %} The `--no-refresh` option makes **zypper** not retrieve the list of packages from repositories. Using that option, we ensure that **zypper** won't try to download any package in addition to those we have already downloaded. That can be useful especially for laptops, which may lose the Wi-Fi connection when leaving the GUI. As before, **zipper** will compute the upgrade and show what it will do: {% include image.html src="/files/2016/10/upgrade-16.jpg" %} Note that all the needed packages have already been downloaded: at the end, **zypper**'s report shows "Overall download size: 0 B. Already cached: 1.62 GiB". Just press **Enter** to start upgrading. **zypper** skips downloading packages and goes straight to upgrading: {% include image.html src="/files/2016/10/upgrade-17.jpg" %} Distribution upgrade may take several minutes. When it finishes, as happened in the [previous post]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}), **zypper** suggests to restart. Let's do that by running `reboot`: {% include image.html src="/files/2016/10/upgrade-18.jpg" %} ## Have a lot of fun! If you did everything up to here, now your computer is running openSUSE 42.2 Leap. You can see the [GRUB][grub] menu, the one that allows you to choose which operating system to boot when the computer turns on (useful especially if you have Windows and Linux installed on the same machine), is already different: {% include image.html src="/files/2016/10/upgrade-19.jpg" %} And *voilà*! openSUSE Leap 42.2 is installed and ready for use! {% include image.html src="/files/2016/10/upgrade-20-en.jpg" %} Make sure everything is in place. Now you may return any repositories you removed. Remember to make the appropriate adjustments with respect to the openSUSE version, changing from `42.1` to `42.2` where necessary. You may also try to install any program that perhaps has been removed during the upgrade. Remember to regularly [check for updates]({% post_url en/2016-10-22-keep-your-system-always-up-to-date %}) for your new distribution. If you find any difficulty during the upgrade or have any questions, don't hesitate to comment! [opensuse]: https://www.opensuse.org [opensuse-123]: https://news.opensuse.org/2013/03/13/opensuse-12-3-free-open-and-awesome/ [opensuse-422-rc1]: https://news.opensuse.org/2016/10/18/release-candidate-available-for-opensuse-leap-42-2/ [opensuse-roadmap]: https://en.opensuse.org/openSUSE:Roadmap [system-upgrade]: https://en.opensuse.org/SDB:System_upgrade [debian]: https://www.debian.org/ [most-annoying-bugs]: https://en.opensuse.org/openSUSE:Most_annoying_bugs [release-notes]: https://en.opensuse.org/openSUSE:Release_Notes [konsole]: https://www.kde.org/applications/system/konsole/ [windows]: https://www.microsoft.com/windows/ [official-repos]: https://en.opensuse.org/Package_repositories#Official_Repositories [third-party-repos]: https://en.opensuse.org/Additional_package_repositories [oss]: https://opensource.org/osd-annotated [repo-oss]: http://download.opensuse.org/distribution/leap/42.2/repo/oss/ [repo-update]: http://download.opensuse.org/update/leap/42.2/oss/ [url]: https://en.wikipedia.org/wiki/Uniform_Resource_Locator [opensuse-license]: https://en.opensuse.org/openSUSE:License [terminal]: http://opensuse-guide.org/command.php [runlevel]: https://en.wikipedia.org/wiki/Runlevel [switch-runlevel]: https://en.opensuse.org/SDB:Switch_runlevel [grub]: https://www.gnu.org/software/grub/
{ "content_hash": "9d89772b3af84053e38889945a0e47f1", "timestamp": "", "source": "github", "line_count": 260, "max_line_length": 670, "avg_line_length": 72.74615384615385, "alnum_prop": 0.7464840858623242, "repo_name": "kamarada/kamarada-website", "id": "2c87c1ff9abee260d6a76b7fa7ab40b15547138f", "size": "18919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "en/_posts/2016-10-31-how-to-upgrade-from-opensuse-leap-421-to-422.md", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "20787" }, { "name": "HTML", "bytes": "89693" }, { "name": "JavaScript", "bytes": "563002" }, { "name": "Ruby", "bytes": "4383" }, { "name": "Shell", "bytes": "970" } ], "symlink_target": "" }
export { default } from './ObserverItem';
{ "content_hash": "8c8910ad602813eec7c3631d503addb3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 41, "avg_line_length": 42, "alnum_prop": 0.6904761904761905, "repo_name": "ok2ju/holly-core", "id": "62acdf3a1a944926c13b29d1a0b71689be873b77", "size": "42", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "client/components/ObserverItem/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1430" }, { "name": "HTML", "bytes": "327" }, { "name": "JavaScript", "bytes": "9576" } ], "symlink_target": "" }
#pragma once #include "Core/src/EnvisionPlugin.h" #include "cppimport_api.h" namespace Logger { class Log; } namespace CppImport { /** * Implements the interface between the CppImport plug-in and Envision. * * The Envision core will use this interface to communicate with the plug-in. The plug-in will be initialized before * any other operations are performed. * * The plug-in can use the supplied EnvisionManager object to find out more about the running environment. */ class CPPIMPORT_API CppImportPlugin : public QObject, public Core::EnvisionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "EnvisionPlugin/1.0") Q_INTERFACES(Core::EnvisionPlugin) public: virtual bool initialize(Core::EnvisionManager&) override; virtual void unload() override; virtual void selfTest(QString testid) override; static Logger::Log& log(); }; }
{ "content_hash": "599437eb20387715263131a261b609e8", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 116, "avg_line_length": 23.63888888888889, "alnum_prop": 0.7555816686251469, "repo_name": "mgalbier/Envision", "id": "c29911afb2c5dfe1d319b7bb543b98466a906076", "size": "2680", "binary": false, "copies": "3", "ref": "refs/heads/development", "path": "CppImport/src/CppImportPlugin.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "780" }, { "name": "C", "bytes": "79038" }, { "name": "C++", "bytes": "8004777" }, { "name": "CMake", "bytes": "77874" }, { "name": "CSS", "bytes": "31" }, { "name": "HTML", "bytes": "2314" }, { "name": "Java", "bytes": "135892" }, { "name": "Python", "bytes": "45530" }, { "name": "Shell", "bytes": "22567" } ], "symlink_target": "" }
package cl.pkto.core.security.util; import cl.pkto.core.security.dto.JwtUser; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.apache.commons.lang3.math.NumberUtils; import org.springframework.mobile.device.Device; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; /** * Created by Bennu on 03-12-2016. */ @Component public class JwtTokenUtil implements Serializable { private static final long serialVersionUID = -3301605591108950415L; static final String CLAIM_KEY_USERNAME = "sub"; static final String CLAIM_KEY_AUDIENCE = "audience"; static final String CLAIM_KEY_CREATED = "created"; private static final String AUDIENCE_UNKNOWN = "unknown"; private static final String AUDIENCE_WEB = "web"; private static final String AUDIENCE_MOBILE = "mobile"; private static final String AUDIENCE_TABLET = "tablet"; private String secret; private Long expiration; public JwtTokenUtil() { ResourceBundle resourceBundle = ResourceBundle.getBundle("application"); this.expiration = NumberUtils.createLong(resourceBundle.getString("jwt.expiration").trim()); this.secret = resourceBundle.getString("jwt.secret").trim(); } public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; } public Date getCreatedDateFromToken(String token) { Date created; try { final Claims claims = getClaimsFromToken(token); created = new Date((Long) claims.get(CLAIM_KEY_CREATED)); } catch (Exception e) { created = null; } return created; } public Date getExpirationDateFromToken(String token) { Date expiration; try { final Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; } public String getAudienceFromToken(String token) { String audience; try { final Claims claims = getClaimsFromToken(token); audience = (String) claims.get(CLAIM_KEY_AUDIENCE); } catch (Exception e) { audience = null; } return audience; } private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; } return claims; } private Date generateExpirationDate() { return new Date(System.currentTimeMillis() + expiration * 1000); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) { return (lastPasswordReset != null && created.before(lastPasswordReset)); } private String generateAudience(Device device) { String audience = AUDIENCE_UNKNOWN; if (device.isNormal()) { audience = AUDIENCE_WEB; } else if (device.isTablet()) { audience = AUDIENCE_TABLET; } else if (device.isMobile()) { audience = AUDIENCE_MOBILE; } return audience; } private Boolean ignoreTokenExpiration(String token) { String audience = getAudienceFromToken(token); return (AUDIENCE_TABLET.equals(audience) || AUDIENCE_MOBILE.equals(audience)); } public String generateToken(UserDetails userDetails, Device device) { Map<String, Object> claims = new HashMap<>(); claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); claims.put(CLAIM_KEY_AUDIENCE, generateAudience(device)); claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) { final Date created = getCreatedDateFromToken(token); return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset) && (!isTokenExpired(token) || ignoreTokenExpiration(token)); } public String refreshToken(String token) { String refreshedToken; try { final Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; } public Boolean validateToken(String token, JwtUser jwtUser) { final String username = getUsernameFromToken(token); final Date created = getCreatedDateFromToken(token); return ( username.equals(jwtUser.getUsername()) && !isTokenExpired(token) && !isCreatedBeforeLastPasswordReset(created, jwtUser.getLastPasswordResetDate())); } }
{ "content_hash": "6979e2c5a9998c9fcb13056033ad4a0c", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 107, "avg_line_length": 33.59770114942529, "alnum_prop": 0.6395826205952788, "repo_name": "roceledon/pkto-back", "id": "7c8c59614f18d21a02f484b0ca762c66a117db5b", "size": "5846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/cl/pkto/core/security/util/JwtTokenUtil.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "47156" } ], "symlink_target": "" }
package redis.clients.jedis; import redis.clients.jedis.exceptions.JedisException; @Deprecated /** * This class is deprecated due to its error prone * and will be removed on next major release * @see https://github.com/xetorthio/jedis/pull/498 */ public abstract class TransactionBlock extends Transaction { public TransactionBlock(Client client) { super(client); } public TransactionBlock() { } public abstract void execute() throws JedisException; public void setClient(Client client) { this.client = client; } }
{ "content_hash": "926a8f79f5fbfb9f7474db70d9fd32f3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 60, "avg_line_length": 22.75, "alnum_prop": 0.73992673992674, "repo_name": "flasheryu/RedisTest", "id": "6de7f92459c39c9983020d0c6489625bfbb836c2", "size": "546", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/main/java/redis/clients/jedis/TransactionBlock.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "895260" }, { "name": "Makefile", "bytes": "6963" } ], "symlink_target": "" }
package com.didichuxing.doraemonkit.kit.timecounter.bean; /** * @desc: 统计耗时的Bean */ public class CounterInfo { public static final int ACTIVITY_COST_FAST = 500; public static final int ACTIVITY_COST_SLOW = 1000; public static final int TYPE_APP = 0; public static final int TYPE_ACTIVITY = 1; public long time; public int type; public String title; /** * 单位为ms */ public long totalCost; public long pauseCost; public long launchCost; public long renderCost; public long otherCost; public boolean show; @Override public String toString() { return "CounterInfo{" + "time=" + time + ", type=" + type + ", title='" + title + '\'' + ", totalCost=" + totalCost + ", pauseCost=" + pauseCost + ", launchCost=" + launchCost + ", renderCost=" + renderCost + ", otherCost=" + otherCost + ", show=" + show + '}'; } }
{ "content_hash": "2cf05d9cf82a3c74c21bf93bd69e8c9d", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 57, "avg_line_length": 25.804878048780488, "alnum_prop": 0.5302457466918714, "repo_name": "didi/DoraemonKit", "id": "94df6adffca8236387f8ce792c09c2b0a8ae107d", "size": "1074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/timecounter/bean/CounterInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "570" }, { "name": "C", "bytes": "31596" }, { "name": "C++", "bytes": "11759" }, { "name": "CMake", "bytes": "1598" }, { "name": "Dart", "bytes": "271190" }, { "name": "HTML", "bytes": "34347" }, { "name": "Java", "bytes": "4256090" }, { "name": "JavaScript", "bytes": "207266" }, { "name": "Kotlin", "bytes": "1450043" }, { "name": "Less", "bytes": "372" }, { "name": "Objective-C", "bytes": "1788521" }, { "name": "Objective-C++", "bytes": "12589" }, { "name": "Ruby", "bytes": "9059" }, { "name": "Shell", "bytes": "10258" }, { "name": "Swift", "bytes": "41938" }, { "name": "Vue", "bytes": "231621" } ], "symlink_target": "" }
import { Canvas } from "terminal-canvas"; import { Text } from ".."; const canvas = new Canvas().reset(); const shape = new Text({ text: "Hello, World!" }); shape.render(canvas); canvas.flush();
{ "content_hash": "dce559879a3591753fea27804a7c03bf", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 50, "avg_line_length": 24.625, "alnum_prop": 0.649746192893401, "repo_name": "kittikjs/kittik", "id": "905aaa8321be2fb87a36da26c49ac049e24427d9", "size": "197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/shapes/kittik-shape-text/examples/simple.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "20507" } ], "symlink_target": "" }
package com.cloudera.hoop; import com.cloudera.lib.wsrs.LongParam; /** * Class for offset parameter. */ public class OffsetParam extends LongParam { /** * Parameter name. */ public static final String NAME = "offset"; /** * Default parameter value. */ public static final String DEFAULT = "0"; /** * Constructor. * * @param str parameter value. */ public OffsetParam(String str) { super(NAME, str); } }
{ "content_hash": "2d52be7e333da4632d5289862986f19a", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 45, "avg_line_length": 15.620689655172415, "alnum_prop": 0.6291390728476821, "repo_name": "showyou/hoop-webhdfs-hue", "id": "73178626d983af6bd072d9d514fc003d1cb23df1", "size": "1021", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hoop-server/src/main/java/com/cloudera/hoop/OffsetParam.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "457574" }, { "name": "Shell", "bytes": "8011" } ], "symlink_target": "" }
package com.fastjson; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; import java.util.HashMap; import java.util.LongSummaryStatistics; import java.util.Map; import java.util.function.Function; import java.util.stream.IntStream; /** * Created by Deepak on 13/06/2015. */ public class JsonPerformance { private Map<String, Object> testdata = new HashMap<>(); private FastJson fastJson = new FastJson(); private ObjectMapper mapper = new ObjectMapper(); @Before public void setUp() { testdata.put("String", "Name"); testdata.put("long", System.currentTimeMillis()); testdata.put("double", 34.5); testdata.put("double2", 3.0); testdata.put("boolean_f", false); testdata.put("boolean_t", true); testdata.put("Stringwithcomma", "Name, Lastname"); testdata.put("StringwithspeechMark", "Name, \"Lastname\""); testdata.putAll(System.getenv()); // mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, false); } @Test public void runTest() { System.out.println("All time in micro seconds"); runTests("Jackson", this::readValue, this::writeValue); runTests("FastJson", fastJson::toMap, fastJson::toJson); } private Map<String, Object> readValue(String input) { try { return mapper.readValue(input, Map.class); } catch (IOException e) { e.printStackTrace(); } return null; } private String writeValue(Map<String, Object> input) { try { return mapper.writeValueAsString(input); } catch (IOException e) { e.printStackTrace(); } return null; } private void runTests(String name, Function<String, Map<String, Object>> decodeFunction, Function<Map<String, Object>, String> encodeFunction) { String testJson = encodeFunction.apply(testdata); Map<String, Object> testDecoded = decodeFunction.apply(testJson); // assertEquals(testdata, testDecoded); testDecoded.entrySet().forEach(e -> { Object oldValue = testdata.get(e.getKey()); assertEquals("Comparing " + e.getKey(), oldValue, e.getValue()); }); IntStream intStream = IntStream.rangeClosed(0, 1001000); LongSummaryStatistics encodeStats = new LongSummaryStatistics(); LongSummaryStatistics decodeStats = new LongSummaryStatistics(); intStream.forEach(i -> { long startTime = System.nanoTime(); String json = encodeFunction.apply(testdata); long timeToCreateJson = System.nanoTime(); Map<String, Object> decoded = decodeFunction.apply(json); long timeToCreateMap = System.nanoTime(); if (i > 1000) { encodeStats.accept((timeToCreateJson - startTime) / 1000); decodeStats.accept((timeToCreateMap - timeToCreateJson) / 1000); } }); System.out.println(name + " Encoding " + encodeStats); System.out.println(name + " Decoding " + decodeStats); } }
{ "content_hash": "dbc2d156ff05b90e9c34f831a4bf8e71", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 92, "avg_line_length": 35.358695652173914, "alnum_prop": 0.6295727021211189, "repo_name": "deepakcdo/fastjson", "id": "efec2d129620ddaa52be9d33047c687c9660cedd", "size": "3253", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/com/fastjson/JsonPerformance.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8001" } ], "symlink_target": "" }
layout: proj title: Social Media Privacy desc: How to bridge advertising and privacy in Social Media? --- # Social Media Privacy <hr> ### ABSTRACT Social Media is being used as a key platform by advertisers to improve business by providing targeted and personalized advertising. There exist a trade-off between productivity in advertising and invasion of user's privacy in the existing approaches. Due to these privacy concerns, there were many law suits filed against the Beacon advertising model used by Facebook resulting in its discontinuation. The similar cases has been also observed with other social media giants. ### WHY? Currently new approaches tends to address targeted audience while preserving the privacy in order to build appropriate revenue model for their operations but they do not balance them and finally social media owners might suffer loses and can run out of business. In this project, we propose an innovative model that leverage the trade-off between privacy and advertising. The model effectively interacts with user's linked data present in the web structured format(RDF), retrieve it and integrate this data with marketing partner's one. Then it broadcasts the advertisement in social graph with flexible sentences for targeted advertising. Our model maintains interaction records among users in virtual containers for finding tie-strength and also active friends 1 by Association Rules Mining [ARM] algorithm. We applied and validated our approach using a real data set obtained from 506 active social media users. ### PAPER The paper got accepted at <a href="http://ieeexplore.ieee.org/document/6779371/"> Advance Computing Conference (IACC), 2014 IEEE International. I have the draft copy of paper. Click <a href="{{ site.url }}/assets/pdf/nmsant.pdf" target="_blank">here</a> to read. ### Mentor 1. [Prof. O.P. Vyas](https://scholar.google.co.in/citations?user=9-NwhCAAAAAJ)
{ "content_hash": "062b3940bf6ddec88405ec08bb0d05a2", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 914, "avg_line_length": 87.04545454545455, "alnum_prop": 0.8, "repo_name": "rahulrrixe/rahulrrixe.github.io", "id": "d3a31d3953d5d4fd414c2091569c6ebca5e3f1a4", "size": "1919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_project/research-bites/social-media-privacy.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "23497" }, { "name": "HTML", "bytes": "18919" }, { "name": "JavaScript", "bytes": "12526" }, { "name": "Ruby", "bytes": "344" } ], "symlink_target": "" }
""" Module for management commands (command-line tools) for the IX Login application .. moduleauthor:: Infoxchange Development Team <development@infoxchange.net.au> """
{ "content_hash": "83b6e5c8e3904d54c2105928a2bed9f5", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 79, "avg_line_length": 24.428571428571427, "alnum_prop": 0.7719298245614035, "repo_name": "infoxchange/ixdjango", "id": "1a9263efbbe0b25525340f84a03093d03a539733", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ixdjango/management/commands/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "32473" } ], "symlink_target": "" }
#ifndef TRCharts_Impl_PointSeriesImpl_cpp #define TRCharts_Impl_PointSeriesImpl_cpp #include <TRCharts/Impl/PointSeriesImpl.hpp> #include <TRCharts/Impl/Utils.hpp> #include <TR3DUtils/RenderProgram.hpp> #include <TR3DUtils/RenderBuffer.hpp> #include <TR3DUtils/RenderVAO.hpp> #include <TR3DUtils/Utils.hpp> Charts::PointSeries::PointSeries(void) :pointStyle(1.0) { } Charts::PointSeries::~PointSeries(void) { } const Charts::PointStyle & Charts::PointSeries::getPointStyle(void) const { return this->pointStyle; } void Charts::PointSeries::setPointStyle(const Charts::PointStyle & value) { if(this->pointStyle != value) { newVersion(); this->pointStyle = value; } } void Charts::PointSeries::createVertices(std::vector<glm::vec2> & vertices) { for(const ScalarDatum & value : data) { vertices.push_back(createVertex(value.abscissa, value.ordinate)); } } void Charts::PointSeries::createDatumColors(std::vector<glm::vec4> & colors) { colors = datumColors; } void Charts::PointSeries::preRenderImpl(TR3DUtils::RenderContext & context, const RenderArgs & args) { std::vector<glm::vec2> values; createVertices(values); std::vector<std::shared_ptr<const TR3DUtils::RenderBuffer>> buffers; buffers.push_back(context.createBuffer(2, values.size(), glm::value_ptr(values[0]))); if(useDatumColors) { std::vector<glm::vec4> colors; createDatumColors(colors); if(TR_VERIFY(values.size() == colors.size())) { buffers.push_back(context.createBuffer(4, colors.size(), glm::value_ptr(colors[0]))); } else { useDatumColors = false; } } vao = context.createVAO(buffers, GL_POINTS); TR3DUtils::RenderProgram::DefineMap defineMap; defineMap.insert(Series::getConstantPointSizeProgramDefine()); if(useDatumColors) { defineMap.insert(Series::getDatumColorsProgramDefine()); } program = context.getNamedProgram(Series::getSimpleSeriesProgramName(), defineMap); } void Charts::PointSeries::render(TR3DUtils::RenderContext & context, const RenderArgs & args) const { if(TR_VERIFY(vao && program)) { beforeRender(context, args); program->bind(); program->bindUniform("modelViewProjection", args.projection); program->bindUniform("color", Utils::colorToVec4(getColor())); program->bindUniform("offset", getRenderOffset()); program->bindUniform("abscissaAxis", abscissaAxisDirection); program->bindUniform("ordinateAxis", ordinateAxisDirection); program->bindUniform("valueScale", getRenderValueScale()); program->bindUniform("valueOffset", getRenderValueOffset()); program->bindUniform("opacity", glm::float_t(getOpacity() / 255.0)); program->bindUniform("pointSize", glm::float_t(this->pointStyle.diameter * args.contentScaleFactor)); vao->draw(); afterRender(context, args); } } Charts::Range Charts::PointSeries::getAbscissaRange(void) const { Range result = Range::identity(); for(const ScalarDatum & datum : data) { result.min = std::min(result.min, datum.abscissa); result.max = std::max(result.max, datum.abscissa); } return result; } Charts::Range Charts::PointSeries::getOrdinateRange(void) const { Range result = Range::identity(); for(const ScalarDatum & datum : data) { result.min = std::min(result.min, datum.ordinate); result.max = std::max(result.max, datum.ordinate); } return result; } glm::float_t Charts::PointSeries::getDatumScreenDistanceSquared(const glm::vec2 & position, size_t index, const glm::vec2 & proj) const { if(TR_VERIFY(index < data.size())) { const ScalarDatum & datum = data[index]; const glm::vec2 datumPosition = dataToScreenRaw(glm::dvec2(datum.abscissa, datum.ordinate)); return Utils::distanceSquaredProj(datumPosition, position, proj); } else { return std::numeric_limits<glm::float_t>::max(); } } Charts::ScalarDatum Charts::PointSeries::blendDatums(const Charts::ScalarDatum & a, const Charts::ScalarDatum & b, const double t) const { return a; } Charts::Range Charts::PointSeries::getDatumOrdinateRange(const Charts::ScalarDatum & datum) const { return Range(datum.ordinate, datum.ordinate); } void Charts::PointSeries::dispose(void) { GeneratedPointSeries::dispose(); vao.reset(); program.reset(); } #endif
{ "content_hash": "2b03647f160251e39fcd525d113ab5b8", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 136, "avg_line_length": 31.37323943661972, "alnum_prop": 0.6882154882154882, "repo_name": "thomsonreuters/TRCharts", "id": "f74ff8f4f666a797d7650ed8ae6b6b0ef314d47c", "size": "5208", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Charts/TRCharts/TRCharts/Impl/PointSeriesImpl.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5418" }, { "name": "C++", "bytes": "3313416" }, { "name": "CMake", "bytes": "1566" }, { "name": "Java", "bytes": "421721" }, { "name": "Makefile", "bytes": "2679" }, { "name": "Objective-C", "bytes": "334981" }, { "name": "Objective-C++", "bytes": "510699" }, { "name": "Shell", "bytes": "2273" } ], "symlink_target": "" }
/** * Spring Security configuration. */ package com.readthisstuff.rts.security;
{ "content_hash": "93c57ae47a53d9d6b25cd384a6806d58", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 39, "avg_line_length": 20.5, "alnum_prop": 0.7439024390243902, "repo_name": "EnricoSchw/readthisstuff.com", "id": "6e30e2aa3865cc8b25921086169b6bbfb5b5e993", "size": "82", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/readthisstuff/rts/security/package-info.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "227832" }, { "name": "Cucumber", "bytes": "161" }, { "name": "HTML", "bytes": "171236" }, { "name": "Java", "bytes": "398982" }, { "name": "JavaScript", "bytes": "262361" }, { "name": "Scala", "bytes": "13634" } ], "symlink_target": "" }
package com.lamfire.utils; import java.io.IOException; import java.util.*; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; public class SimpleMailSender { private String smtpHost = null; // SMTP服务器地址 private String smtpAccount = null; // SMTP服务器账户 private String smtpPassword = null; // SMTP服务器密码 private boolean smtpAuthEnable = true; // SMTP服务器是否验证 private String mailContentType = "text/html; charset=UTF-8"; // 邮件类型 private boolean debug = false; // 是否采用调试方式 private String mailFrom = null; // 发送者地址 private Set<InternetAddress> mailTo = new HashSet<InternetAddress>(); // 接收者地址 private Set<InternetAddress> mailCCTo = new HashSet<InternetAddress>(); private Set<InternetAddress> mailBCCTo = new HashSet<InternetAddress>(); private String subject = null; // 邮件标题 private String mailContent = ""; // 邮件内容 private final List<String> attachedFiles = Lists.newArrayList(); // 附件列表 public void addMailTo(String mailAddress) throws AddressException { mailTo.add(new InternetAddress(mailAddress)); } public void addMailCCTo(String mailAddress) throws AddressException { mailCCTo.add(new InternetAddress(mailAddress)); } public void addMailBCCTo(String mailAddress) throws AddressException { mailBCCTo.add(new InternetAddress(mailAddress)); } protected MimeMessage makeMessage(Session session) throws IOException, MessagingException { if (mailFrom == null) { throw new MessagingException("Mail from not found."); } if (mailTo.isEmpty()) { throw new MessagingException("Mail to not found."); } MimeMessage message = new MimeMessage(session); // 设置收件人 InternetAddress[] address = new InternetAddress[mailTo.size()]; mailTo.toArray(address); message.setRecipients(Message.RecipientType.TO, address); // 设置CC if (!mailCCTo.isEmpty()) { InternetAddress[] ccaddress = new InternetAddress[mailCCTo.size()]; mailCCTo.toArray(ccaddress); message.setRecipients(Message.RecipientType.CC, ccaddress); } // 设置BCC if (!mailBCCTo.isEmpty()) { InternetAddress[] bccaddress = new InternetAddress[mailBCCTo.size()]; mailBCCTo.toArray(bccaddress); message.setRecipients(Message.RecipientType.BCC, bccaddress); } // 设置回复地址 InternetAddress[] replyAddress = { new InternetAddress(mailFrom) }; message.setReplyTo(replyAddress); // 设置内容正文 MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(mailContent, mailContentType); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); // 添加附件 for (int i = 0; i < attachedFiles.size(); i++) { String file = (String) attachedFiles.get(i); MimeBodyPart mBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mBodyPart.setDataHandler(new DataHandler(fds)); mBodyPart.setFileName(file); multipart.addBodyPart(mBodyPart); } message.setFrom(new InternetAddress(mailFrom)); message.setSubject(subject); message.setContent(multipart); message.setSentDate(new Date()); return message; } public void addAttachment(String file) { this.attachedFiles.add(file); } /** * 发送邮件 * * @throws java.io.IOException * @throws MessagingException * @return void */ public void send() throws IOException, MessagingException { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.auth", String.valueOf(smtpAuthEnable)); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpAccount, smtpPassword); } }; Session session = Session.getInstance(props, auth); session.setDebug(debug); MimeMessage message = makeMessage(session); Transport.send(message); } public void setDebug(boolean debug) { this.debug = debug; } public void setMailContent(String mailContent) { this.mailContent = mailContent; } public void setMailContentType(String mailContentType) { this.mailContentType = mailContentType; } public void setMailFrom(String mailFrom) { this.mailFrom = mailFrom; } public void setSmtpAccount(String smtpAccount) { this.smtpAccount = smtpAccount; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } public void setSmtpPassword(String smtpPassword) { this.smtpPassword = smtpPassword; } public void setSubject(String subject) { this.subject = subject; } public boolean isSmtpAuthEnable() { return smtpAuthEnable; } public void setSmtpAuthEnable(boolean smtpAuthEnable) { this.smtpAuthEnable = smtpAuthEnable; } }
{ "content_hash": "2ef69f8dd0b0125ce5a254c3f5390c7b", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 96, "avg_line_length": 32.64088397790055, "alnum_prop": 0.586662153012864, "repo_name": "MOBX/Foundation", "id": "80313ed4e334bd8361143559fbe469970ca8b208", "size": "6078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/lamfire/utils/SimpleMailSender.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1232876" } ], "symlink_target": "" }
package com.google.gerrit.sshd.commands; import com.google.common.collect.Sets; import com.google.gerrit.common.data.GlobalCapability; import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.server.plugins.PluginInstallException; import com.google.gerrit.server.plugins.PluginLoader; import com.google.gerrit.sshd.CommandMetaData; import com.google.gerrit.sshd.SshCommand; import com.google.inject.Inject; import org.kohsuke.args4j.Argument; import java.util.List; @RequiresCapability(GlobalCapability.ADMINISTRATE_SERVER) @CommandMetaData(name = "enable", description = "Enable plugins") final class PluginEnableCommand extends SshCommand { @Argument(index = 0, metaVar = "NAME", required = true, usage = "plugin(s) to enable") List<String> names; @Inject private PluginLoader loader; @Override protected void run() throws UnloggedFailure { if (names != null && !names.isEmpty()) { try { loader.enablePlugins(Sets.newHashSet(names)); } catch (PluginInstallException e) { e.printStackTrace(stderr); throw die("plugin failed to enable"); } } } }
{ "content_hash": "d6d8b920df5cd90957c00e2c52bbf71f", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 88, "avg_line_length": 32, "alnum_prop": 0.7482638888888888, "repo_name": "gracefullife/gerrit", "id": "47c2d685888f3c82288ae2e8b8f27eb9d6af4e4a", "size": "1761", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gerrit-sshd/src/main/java/com/google/gerrit/sshd/commands/PluginEnableCommand.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50650" }, { "name": "Java", "bytes": "6732973" }, { "name": "JavaScript", "bytes": "1590" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17712" }, { "name": "Python", "bytes": "22132" }, { "name": "Shell", "bytes": "36343" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Serializer\Tests\Normalizer; use Doctrine\Common\Annotations\AnnotationReader; use PHPUnit\Framework\TestCase; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Exception\LogicException; use Symfony\Component\Serializer\Exception\RuntimeException; use Symfony\Component\Serializer\Exception\UnexpectedValueException; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\SerializerInterface; use Symfony\Component\Serializer\Tests\Fixtures\Annotations\GroupDummy; use Symfony\Component\Serializer\Tests\Fixtures\CircularReferenceDummy; use Symfony\Component\Serializer\Tests\Fixtures\DummyPrivatePropertyWithoutGetter; use Symfony\Component\Serializer\Tests\Fixtures\OtherSerializedNameDummy; use Symfony\Component\Serializer\Tests\Fixtures\Php74Dummy; use Symfony\Component\Serializer\Tests\Fixtures\Php74DummyPrivate; use Symfony\Component\Serializer\Tests\Fixtures\SiblingHolder; use Symfony\Component\Serializer\Tests\Normalizer\Features\AttributesTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\CallbacksTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\CircularReferenceTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\ConstructorArgumentsTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\ContextMetadataTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\GroupsTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\IgnoredAttributesTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\MaxDepthTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\ObjectDummy; use Symfony\Component\Serializer\Tests\Normalizer\Features\ObjectToPopulateTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\SkipNullValuesTestTrait; use Symfony\Component\Serializer\Tests\Normalizer\Features\TypeEnforcementTestTrait; /** * @author Kévin Dunglas <dunglas@gmail.com> */ class ObjectNormalizerTest extends TestCase { use AttributesTestTrait; use CallbacksTestTrait; use CircularReferenceTestTrait; use ConstructorArgumentsTestTrait; use ContextMetadataTestTrait; use GroupsTestTrait; use IgnoredAttributesTestTrait; use MaxDepthTestTrait; use ObjectToPopulateTestTrait; use SkipNullValuesTestTrait; use TypeEnforcementTestTrait; /** * @var ObjectNormalizer */ private $normalizer; /** * @var SerializerInterface */ private $serializer; protected function setUp(): void { $this->createNormalizer(); } private function createNormalizer(array $defaultContext = [], ClassMetadataFactoryInterface $classMetadataFactory = null) { $this->serializer = $this->createMock(ObjectSerializerNormalizer::class); $this->normalizer = new ObjectNormalizer($classMetadataFactory, null, null, null, null, null, $defaultContext); $this->normalizer->setSerializer($this->serializer); } public function testNormalize() { $obj = new ObjectDummy(); $object = new \stdClass(); $obj->setFoo('foo'); $obj->bar = 'bar'; $obj->setBaz(true); $obj->setCamelCase('camelcase'); $obj->setObject($object); $this->serializer ->expects($this->once()) ->method('normalize') ->with($object, 'any') ->willReturn('string_object') ; $this->assertEquals( [ 'foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar', 'camelCase' => 'camelcase', 'object' => 'string_object', ], $this->normalizer->normalize($obj, 'any') ); } public function testNormalizeObjectWithUninitializedProperties() { $obj = new Php74Dummy(); $this->assertEquals( ['initializedProperty' => 'defaultValue'], $this->normalizer->normalize($obj, 'any') ); } public function testNormalizeObjectWithUninitializedPrivateProperties() { $obj = new Php74DummyPrivate(); $this->assertEquals( ['initializedProperty' => 'defaultValue'], $this->normalizer->normalize($obj, 'any') ); } public function testNormalizeObjectWithPrivatePropertyWithoutGetter() { $obj = new DummyPrivatePropertyWithoutGetter(); $this->assertEquals( ['bar' => 'bar'], $this->normalizer->normalize($obj, 'any') ); } public function testDenormalize() { $obj = $this->normalizer->denormalize( ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], ObjectDummy::class, 'any' ); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->bar); $this->assertTrue($obj->isBaz()); } public function testDenormalizeWithObject() { $data = new \stdClass(); $data->foo = 'foo'; $data->bar = 'bar'; $data->fooBar = 'foobar'; $obj = $this->normalizer->denormalize($data, ObjectDummy::class, 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->bar); } public function testDenormalizeNull() { $this->assertEquals(new ObjectDummy(), $this->normalizer->denormalize(null, ObjectDummy::class)); } public function testConstructorDenormalize() { $obj = $this->normalizer->denormalize( ['foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar'], ObjectConstructorDummy::class, 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->bar); $this->assertTrue($obj->isBaz()); } public function testConstructorDenormalizeWithNullArgument() { $obj = $this->normalizer->denormalize( ['foo' => 'foo', 'bar' => null, 'baz' => true], ObjectConstructorDummy::class, 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertNull($obj->bar); $this->assertTrue($obj->isBaz()); } public function testConstructorDenormalizeWithMissingOptionalArgument() { $obj = $this->normalizer->denormalize( ['foo' => 'test', 'baz' => [1, 2, 3]], ObjectConstructorOptionalArgsDummy::class, 'any'); $this->assertEquals('test', $obj->getFoo()); $this->assertEquals([], $obj->bar); $this->assertEquals([1, 2, 3], $obj->getBaz()); } public function testConstructorDenormalizeWithOptionalDefaultArgument() { $obj = $this->normalizer->denormalize( ['bar' => 'test'], ObjectConstructorArgsWithDefaultValueDummy::class, 'any'); $this->assertEquals([], $obj->getFoo()); $this->assertEquals('test', $obj->getBar()); } public function testConstructorWithObjectDenormalize() { $data = new \stdClass(); $data->foo = 'foo'; $data->bar = 'bar'; $data->baz = true; $data->fooBar = 'foobar'; $obj = $this->normalizer->denormalize($data, ObjectConstructorDummy::class, 'any'); $this->assertEquals('foo', $obj->getFoo()); $this->assertEquals('bar', $obj->bar); } public function testConstructorWithObjectTypeHintDenormalize() { $data = [ 'id' => 10, 'inner' => [ 'foo' => 'oof', 'bar' => 'rab', ], ]; $normalizer = new ObjectNormalizer(); $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $obj = $normalizer->denormalize($data, DummyWithConstructorObject::class); $this->assertInstanceOf(DummyWithConstructorObject::class, $obj); $this->assertEquals(10, $obj->getId()); $this->assertInstanceOf(ObjectInner::class, $obj->getInner()); $this->assertEquals('oof', $obj->getInner()->foo); $this->assertEquals('rab', $obj->getInner()->bar); } public function testConstructorWithUnconstructableNullableObjectTypeHintDenormalize() { $data = [ 'id' => 10, 'inner' => null, ]; $normalizer = new ObjectNormalizer(); $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $obj = $normalizer->denormalize($data, DummyWithNullableConstructorObject::class); $this->assertInstanceOf(DummyWithNullableConstructorObject::class, $obj); $this->assertEquals(10, $obj->getId()); $this->assertNull($obj->getInner()); } public function testConstructorWithUnknownObjectTypeHintDenormalize() { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('Could not determine the class of the parameter "unknown".'); $data = [ 'id' => 10, 'unknown' => [ 'foo' => 'oof', 'bar' => 'rab', ], ]; $normalizer = new ObjectNormalizer(); $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); $normalizer->denormalize($data, DummyWithConstructorInexistingObject::class); } // attributes protected function getNormalizerForAttributes(): ObjectNormalizer { $normalizer = new ObjectNormalizer(); // instantiate a serializer with the normalizer to handle normalizing recursive structures new Serializer([$normalizer]); return $normalizer; } protected function getDenormalizerForAttributes(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new ReflectionExtractor()); new Serializer([$normalizer]); return $normalizer; } public function testAttributesContextDenormalizeConstructor() { $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); $serializer = new Serializer([$normalizer]); $objectInner = new ObjectInner(); $objectInner->bar = 'bar'; $obj = new DummyWithConstructorObjectAndDefaultValue('a', $objectInner); $context = ['attributes' => ['inner' => ['bar']]]; $this->assertEquals($obj, $serializer->denormalize([ 'foo' => 'b', 'inner' => ['foo' => 'foo', 'bar' => 'bar'], ], DummyWithConstructorObjectAndDefaultValue::class, null, $context)); } public function testNormalizeSameObjectWithDifferentAttributes() { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new ObjectNormalizer($classMetadataFactory); $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $dummy = new ObjectOuter(); $dummy->foo = new ObjectInner(); $dummy->foo->foo = 'foo.foo'; $dummy->foo->bar = 'foo.bar'; $dummy->bar = new ObjectInner(); $dummy->bar->foo = 'bar.foo'; $dummy->bar->bar = 'bar.bar'; $this->assertEquals([ 'foo' => [ 'bar' => 'foo.bar', ], 'bar' => [ 'foo' => 'bar.foo', ], ], $this->normalizer->normalize($dummy, 'json', [ 'attributes' => [ 'foo' => ['bar'], 'bar' => ['foo'], ], ])); } // callbacks protected function getNormalizerForCallbacks(): ObjectNormalizer { return new ObjectNormalizer(); } // circular reference protected function getNormalizerForCircularReference(array $defaultContext): ObjectNormalizer { $normalizer = new ObjectNormalizer(null, null, null, null, null, null, $defaultContext); new Serializer([$normalizer]); return $normalizer; } protected function getSelfReferencingModel() { return new CircularReferenceDummy(); } public function testSiblingReference() { $serializer = new Serializer([$this->normalizer]); $this->normalizer->setSerializer($serializer); $siblingHolder = new SiblingHolder(); $expected = [ 'sibling0' => ['coopTilleuls' => 'Les-Tilleuls.coop'], 'sibling1' => ['coopTilleuls' => 'Les-Tilleuls.coop'], 'sibling2' => ['coopTilleuls' => 'Les-Tilleuls.coop'], ]; $this->assertEquals($expected, $this->normalizer->normalize($siblingHolder)); } // constructor arguments protected function getDenormalizerForConstructArguments(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $denormalizer = new ObjectNormalizer($classMetadataFactory, new MetadataAwareNameConverter($classMetadataFactory)); $serializer = new Serializer([$denormalizer]); $denormalizer->setSerializer($serializer); return $denormalizer; } // groups protected function getNormalizerForGroups(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory); // instantiate a serializer with the normalizer to handle normalizing recursive structures new Serializer([$normalizer]); return $normalizer; } protected function getDenormalizerForGroups(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); return new ObjectNormalizer($classMetadataFactory); } public function testGroupsNormalizeWithNameConverter() { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new ObjectNormalizer($classMetadataFactory, new CamelCaseToSnakeCaseNameConverter()); $this->normalizer->setSerializer($this->serializer); $obj = new GroupDummy(); $obj->setFooBar('@dunglas'); $obj->setSymfony('@coopTilleuls'); $obj->setCoopTilleuls('les-tilleuls.coop'); $this->assertEquals( [ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', ], $this->normalizer->normalize($obj, null, [ObjectNormalizer::GROUPS => ['name_converter']]) ); } public function testGroupsDenormalizeWithNameConverter() { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new ObjectNormalizer($classMetadataFactory, new CamelCaseToSnakeCaseNameConverter()); $this->normalizer->setSerializer($this->serializer); $obj = new GroupDummy(); $obj->setFooBar('@dunglas'); $obj->setSymfony('@coopTilleuls'); $this->assertEquals( $obj, $this->normalizer->denormalize([ 'bar' => null, 'foo_bar' => '@dunglas', 'symfony' => '@coopTilleuls', 'coop_tilleuls' => 'les-tilleuls.coop', ], 'Symfony\Component\Serializer\Tests\Fixtures\Annotations\GroupDummy', null, [ObjectNormalizer::GROUPS => ['name_converter']]) ); } public function testGroupsDenormalizeWithMetaDataNameConverter() { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $this->normalizer = new ObjectNormalizer($classMetadataFactory, new MetadataAwareNameConverter($classMetadataFactory)); $this->normalizer->setSerializer($this->serializer); $obj = new OtherSerializedNameDummy(); $obj->setBuz('Aldrin'); $this->assertEquals( $obj, $this->normalizer->denormalize([ 'buz' => 'Aldrin', ], 'Symfony\Component\Serializer\Tests\Fixtures\OtherSerializedNameDummy', null, [ObjectNormalizer::GROUPS => ['a']]) ); } // ignored attributes protected function getNormalizerForIgnoredAttributes(): ObjectNormalizer { $normalizer = new ObjectNormalizer(); // instantiate a serializer with the normalizer to handle normalizing recursive structures new Serializer([$normalizer]); return $normalizer; } protected function getDenormalizerForIgnoredAttributes(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new ReflectionExtractor()); new Serializer([$normalizer]); return $normalizer; } // max depth protected function getNormalizerForMaxDepth(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory); $serializer = new Serializer([$normalizer]); $normalizer->setSerializer($serializer); return $normalizer; } // object to populate protected function getDenormalizerForObjectToPopulate(): ObjectNormalizer { $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())); $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor()); new Serializer([$normalizer]); return $normalizer; } // skip null protected function getNormalizerForSkipNullValues(): ObjectNormalizer { return new ObjectNormalizer(); } // type enforcement protected function getDenormalizerForTypeEnforcement(): ObjectNormalizer { $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); new Serializer([new ArrayDenormalizer(), $normalizer]); return $normalizer; } public function testUnableToNormalizeObjectAttribute() { $this->expectException(LogicException::class); $this->expectExceptionMessage('Cannot normalize attribute "object" because the injected serializer is not a normalizer'); $serializer = $this->createMock(SerializerInterface::class); $this->normalizer->setSerializer($serializer); $obj = new ObjectDummy(); $object = new \stdClass(); $obj->setObject($object); $this->normalizer->normalize($obj, 'any'); } public function testDenormalizeNonExistingAttribute() { $this->assertEquals( new ObjectDummy(), $this->normalizer->denormalize(['non_existing' => true], ObjectDummy::class) ); } public function testNoTraversableSupport() { $this->assertFalse($this->normalizer->supportsNormalization(new \ArrayObject())); } public function testNormalizeStatic() { $this->assertEquals(['foo' => 'K'], $this->normalizer->normalize(new ObjectWithStaticPropertiesAndMethods())); } public function testNormalizeUpperCaseAttributes() { $this->assertEquals(['Foo' => 'Foo', 'Bar' => 'BarBar'], $this->normalizer->normalize(new ObjectWithUpperCaseAttributeNames())); } public function testNormalizeNotSerializableContext() { $objectDummy = new ObjectDummy(); $expected = [ 'foo' => null, 'baz' => null, 'fooBar' => '', 'camelCase' => null, 'object' => null, 'bar' => null, ]; $this->assertEquals($expected, $this->normalizer->normalize($objectDummy, null, ['not_serializable' => function () { }])); } public function testDefaultExcludeFromCacheKey() { $normalizer = new class(null, null, null, null, null, null, [ObjectNormalizer::EXCLUDE_FROM_CACHE_KEY => ['foo']]) extends ObjectNormalizer { protected function isCircularReference($object, &$context) { ObjectNormalizerTest::assertContains('foo', $this->defaultContext[ObjectNormalizer::EXCLUDE_FROM_CACHE_KEY]); } }; $normalizer->normalize(new ObjectDummy()); } public function testThrowUnexpectedValueException() { $this->expectException(UnexpectedValueException::class); $this->normalizer->denormalize(['foo' => 'bar'], ObjectTypeHinted::class); } public function testDenomalizeRecursive() { $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); $serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]); $obj = $serializer->denormalize([ 'inner' => ['foo' => 'foo', 'bar' => 'bar'], 'date' => '1988/01/21', 'inners' => [['foo' => 1], ['foo' => 2]], ], ObjectOuter::class); $this->assertSame('foo', $obj->getInner()->foo); $this->assertSame('bar', $obj->getInner()->bar); $this->assertSame('1988-01-21', $obj->getDate()->format('Y-m-d')); $this->assertSame(1, $obj->getInners()[0]->foo); $this->assertSame(2, $obj->getInners()[1]->foo); } public function testAcceptJsonNumber() { $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); $normalizer = new ObjectNormalizer(null, null, null, $extractor); $serializer = new Serializer([new ArrayDenormalizer(), new DateTimeNormalizer(), $normalizer]); $this->assertSame(10.0, $serializer->denormalize(['number' => 10], JsonNumber::class, 'json')->number); $this->assertSame(10.0, $serializer->denormalize(['number' => 10], JsonNumber::class, 'jsonld')->number); } public function testExtractAttributesRespectsFormat() { $normalizer = new FormatAndContextAwareNormalizer(); $data = new ObjectDummy(); $data->setFoo('bar'); $data->bar = 'foo'; $this->assertSame(['foo' => 'bar', 'bar' => 'foo'], $normalizer->normalize($data, 'foo_and_bar_included')); } public function testExtractAttributesRespectsContext() { $normalizer = new FormatAndContextAwareNormalizer(); $data = new ObjectDummy(); $data->setFoo('bar'); $data->bar = 'foo'; $this->assertSame(['foo' => 'bar', 'bar' => 'foo'], $normalizer->normalize($data, null, ['include_foo_and_bar' => true])); } public function testAdvancedNameConverter() { $nameConverter = new class() implements AdvancedNameConverterInterface { public function normalize(string $propertyName, string $class = null, string $format = null, array $context = []): string { return sprintf('%s-%s-%s-%s', $propertyName, $class, $format, $context['foo']); } public function denormalize(string $propertyName, string $class = null, string $format = null, array $context = []): string { return sprintf('%s-%s-%s-%s', $propertyName, $class, $format, $context['foo']); } }; $normalizer = new ObjectNormalizer(null, $nameConverter); $this->assertArrayHasKey('foo-Symfony\Component\Serializer\Tests\Normalizer\Features\ObjectDummy-json-bar', $normalizer->normalize(new ObjectDummy(), 'json', ['foo' => 'bar'])); } public function testDefaultObjectClassResolver() { $normalizer = new ObjectNormalizer(); $obj = new ObjectDummy(); $obj->setFoo('foo'); $obj->bar = 'bar'; $obj->setBaz(true); $obj->setCamelCase('camelcase'); $obj->unwantedProperty = 'notwanted'; $this->assertEquals( [ 'foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar', 'camelCase' => 'camelcase', 'object' => null, ], $normalizer->normalize($obj, 'any') ); } public function testObjectClassResolver() { $classResolver = function ($object) { return ObjectDummy::class; }; $normalizer = new ObjectNormalizer(null, null, null, null, null, $classResolver); $obj = new ProxyObjectDummy(); $obj->setFoo('foo'); $obj->bar = 'bar'; $obj->setBaz(true); $obj->setCamelCase('camelcase'); $obj->unwantedProperty = 'notwanted'; $this->assertEquals( [ 'foo' => 'foo', 'bar' => 'bar', 'baz' => true, 'fooBar' => 'foobar', 'camelCase' => 'camelcase', 'object' => null, ], $normalizer->normalize($obj, 'any') ); } public function testNormalizeStdClass() { $o1 = new \stdClass(); $o1->foo = 'f'; $o1->bar = 'b'; $this->assertSame(['foo' => 'f', 'bar' => 'b'], $this->normalizer->normalize($o1)); $o2 = new \stdClass(); $o2->baz = 'baz'; $this->assertSame(['baz' => 'baz'], $this->normalizer->normalize($o2)); } } class ProxyObjectDummy extends ObjectDummy { public $unwantedProperty; } class ObjectConstructorDummy { protected $foo; public $bar; private $baz; public function __construct($foo, $bar, $baz) { $this->foo = $foo; $this->bar = $bar; $this->baz = $baz; } public function getFoo() { return $this->foo; } public function isBaz() { return $this->baz; } public function otherMethod() { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } } abstract class ObjectSerializerNormalizer implements SerializerInterface, NormalizerInterface { } class ObjectConstructorOptionalArgsDummy { protected $foo; public $bar; private $baz; public function __construct($foo, $bar = [], $baz = []) { $this->foo = $foo; $this->bar = $bar; $this->baz = $baz; } public function getFoo() { return $this->foo; } public function getBaz() { return $this->baz; } public function otherMethod() { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } } class ObjectConstructorArgsWithDefaultValueDummy { protected $foo; protected $bar; public function __construct($foo = [], $bar = null) { $this->foo = $foo; $this->bar = $bar; } public function getFoo() { return $this->foo; } public function getBar() { return $this->bar; } public function otherMethod() { throw new \RuntimeException('Dummy::otherMethod() should not be called'); } } class ObjectWithStaticPropertiesAndMethods { public $foo = 'K'; public static $bar = 'A'; public static function getBaz() { return 'L'; } } class ObjectTypeHinted { public function setFoo(array $f) { } } class ObjectOuter { public $foo; public $bar; /** * @var ObjectInner */ private $inner; private $date; /** * @var ObjectInner[] */ private $inners; public function getInner() { return $this->inner; } public function setInner(ObjectInner $inner) { $this->inner = $inner; } public function setDate(\DateTimeInterface $date) { $this->date = $date; } public function getDate() { return $this->date; } public function setInners(array $inners) { $this->inners = $inners; } public function getInners() { return $this->inners; } } class ObjectInner { public $foo; public $bar; } class FormatAndContextAwareNormalizer extends ObjectNormalizer { protected function isAllowedAttribute($classOrObject, string $attribute, string $format = null, array $context = []): bool { if (\in_array($attribute, ['foo', 'bar']) && 'foo_and_bar_included' === $format) { return true; } if (\in_array($attribute, ['foo', 'bar']) && isset($context['include_foo_and_bar']) && true === $context['include_foo_and_bar']) { return true; } return false; } } class DummyWithConstructorObject { private $id; private $inner; public function __construct($id, ObjectInner $inner) { $this->id = $id; $this->inner = $inner; } public function getId() { return $this->id; } public function getInner() { return $this->inner; } } class DummyWithConstructorInexistingObject { public function __construct($id, Unknown $unknown) { } } class JsonNumber { /** * @var float */ public $number; } class DummyWithConstructorObjectAndDefaultValue { private $foo; private $inner; public function __construct($foo = 'a', ObjectInner $inner = null) { $this->foo = $foo; $this->inner = $inner; } public function getFoo() { return $this->foo; } public function getInner() { return $this->inner; } } class ObjectWithUpperCaseAttributeNames { private $Foo = 'Foo'; public $Bar = 'BarBar'; public function getFoo() { return $this->Foo; } } class DummyWithNullableConstructorObject { private $id; private $inner; public function __construct($id, ?ObjectConstructorDummy $inner) { $this->id = $id; $this->inner = $inner; } public function getId() { return $this->id; } public function getInner() { return $this->inner; } }
{ "content_hash": "ad1eb9c16d56721837edba83c2beafbb", "timestamp": "", "source": "github", "line_count": 1011, "max_line_length": 185, "avg_line_length": 31.042532146389714, "alnum_prop": 0.6165243436145806, "repo_name": "symfony/Serializer", "id": "c1126910bb965833272f6d1041b63aa68bc6dfd2", "size": "31614", "binary": false, "copies": "1", "ref": "refs/heads/6.0", "path": "Tests/Normalizer/ObjectNormalizerTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "299846" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Examples - Country Data</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <!-- Le styles --> <link href="../lib/bootstrap/css/bootstrap.css" rel="stylesheet"> <style> body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } #map { background-image: url(http://subtlepatterns.com/patterns/noisy_net.png); } .leaflet-tile-pane { opacity: 0.2; } </style> <link rel="stylesheet" href="../lib/bootstrap/css/bootstrap-responsive.css" > <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../dist/css/dvf.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../css/example.css" type="text/css" media="screen" /> </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="#">Country Data</a> <div class="nav-collapse collapse"> <ul class="nav"> <li class="active"><a href="http://humangeo.github.io/leaflet-dvf">Home</a></li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div id="map" class="span9"></div> <div id="legend" class="span3"></div> </div> </div> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','http://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-42733116-1', 'humangeo.github.io'); ga('send', 'pageview'); </script> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="../lib/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js"></script> <script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.2.3"></script> <script type="text/javascript" src="../lib/jsts/javascript.util.js"></script> <script type="text/javascript" src="../lib/jsts/jsts.js"></script> <script type="text/javascript" src="../lib/date.format.js"></script> <script type="text/javascript" src="../lib/geohash.js"></script> <script type="text/javascript" src="../../dist/leaflet-dvf.min.js"></script> <script type="text/javascript" src="../data/incomesData.js"></script> <script type="text/javascript" src="../data/telephoneLines.js"></script> <script type="text/javascript" src="../data/solidFuels.js"></script> <script type="text/javascript" src="../../dist/data/countryData.min.js"></script> <script type="text/javascript" src="../js/incomelevels.js"></script> </body> </html>
{ "content_hash": "46252bdbbaed986d38798f92f59bc160", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 118, "avg_line_length": 42.170731707317074, "alnum_prop": 0.6171197223828803, "repo_name": "Group2000/cellmapping-frontend", "id": "9f33e9d419fb6d7d10c893639bbc3f28a59450cf", "size": "3458", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/bower_components/leaflet-dvf/examples/html/incomelevels.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10765" }, { "name": "HTML", "bytes": "92021" }, { "name": "JavaScript", "bytes": "145619" } ], "symlink_target": "" }
// ex: se sts=4 sw=4 expandtab: package yeti.lang; /** Yeti core library - Map list. */ final class MapList extends LList { private AList rest; private AIter src; private final Fun f; public MapList(AIter src, Fun f) { super(f.apply(src.first()), null); this.src = src; this.f = f; } public synchronized AList rest() { if (src != null) { AIter i = src.next(); if (i != null) rest = new MapList(i, f); src = null; } return rest; } }
{ "content_hash": "d59e5c79db24fd76b9d6b958e95f81cf", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 42, "avg_line_length": 20.925925925925927, "alnum_prop": 0.5061946902654867, "repo_name": "chrisichris/yetiscript", "id": "f589f4b09b87e6df0db76a58895bdfb88c14d6e3", "size": "2060", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "srclib/yeti/lang/MapList.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "688" }, { "name": "CSS", "bytes": "2467" }, { "name": "Emacs Lisp", "bytes": "4450" }, { "name": "Java", "bytes": "954785" }, { "name": "JavaScript", "bytes": "556" }, { "name": "TeX", "bytes": "72" }, { "name": "VimL", "bytes": "11063" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `B921600` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, B921600"> <title>libc::B921600 - Rust</title> <link rel="stylesheet" type="text/css" href="../normalize.css"> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc constant"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'B921600', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"> <h1 class='fqn'><span class='in-band'>Constant <a href='index.html'>libc</a>::<wbr><a class="constant" href=''>B921600</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../src/libc/unix/notbsd/linux/other/b64/x86_64.rs.html#471' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const B921600: <a class="type" href="../libc/type.speed_t.html" title="type libc::speed_t">speed_t</a><code> = </code><code>4103</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
{ "content_hash": "9bcc141d2276ec9e3262780ceffb003a", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 195, "avg_line_length": 38.11504424778761, "alnum_prop": 0.5112607383329464, "repo_name": "nitro-devs/nitro-game-engine", "id": "34cb7e0a5e9da58475801bf5d6539f4d7131c8a6", "size": "4317", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/libc/constant.B921600.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ], "symlink_target": "" }
renderspec ========== `renderspec` is a python program to render RPM spec file templates to a usable spec file. Distribution specifics like different policies for package naming in openSUSE or Fedora are handled. Contents: .. toctree:: :maxdepth: 2 installation usage Testing ======= renderspec has currently a couple of unittests. The preferred way to run tests is using ``tox``. To run the testsuite for python 2.7, do: .. code-block:: shell tox -epy27 Contributing ============ Code is hosted at `opendev.org`_. Submit bugs to the renderspec project on `Launchpad`_. Submit code to the openstack/renderspec project using `Gerrit`_. .. _opendev.org: https://opendev.org/openstack/renderspec .. _Launchpad: https://launchpad.net/renderspec .. _Gerrit: https://docs.openstack.org/infra/manual/developers.html#development-workflow Indices and tables ================== * :ref:`genindex` * :ref:`search`
{ "content_hash": "a11037bf2275e2d5bbf95db7acd6cce3", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 88, "avg_line_length": 22.095238095238095, "alnum_prop": 0.7112068965517241, "repo_name": "openstack/renderspec", "id": "e70e316b1fd2b1ecc023c414475fa1967eef4dc0", "size": "928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/source/index.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Jinja", "bytes": "415" }, { "name": "Python", "bytes": "54974" } ], "symlink_target": "" }