text
stringlengths
2
1.04M
meta
dict
@implementation LPTime - (id)initWithCoder:(NSCoder *)coder { self = [LPTime new]; if (self) { self.text = [coder decodeObjectForKey:@"text"]; self.timeZone = [coder decodeObjectForKey:@"timeZone"]; self.value = [coder decodeFloatForKey:@"value"]; self.formattedTime = [coder decodeObjectForKey:@"formattedTime"]; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.text forKey:@"text"]; [coder encodeObject:self.timeZone forKey:@"timeZone"]; [coder encodeFloat:self.value forKey:@"value"]; [coder encodeObject:self.formattedTime forKey:@"formattedTime"]; } + (id)timeWithObjects:(NSDictionary *)dictionary { LPTime *new = [LPTime new]; if (![dictionary isKindOfClass:[NSNull class]]) { if (![[dictionary objectForKey:@"text"] isKindOfClass:[NSNull class]] && [dictionary objectForKey:@"text"]) { new.text = [dictionary objectForKey:@"text"]; } if (![[dictionary objectForKey:@"time_zone"] isKindOfClass:[NSNull class]] && [dictionary objectForKey:@"time_zone"]) { new.timeZone = [dictionary objectForKey:@"time_zone"]; } if (![[dictionary objectForKey:@"value"] isKindOfClass:[NSNull class]] && [dictionary objectForKey:@"value"]) { new.value = [[dictionary objectForKey:@"value"] floatValue]; } if (new.text && new.timeZone) { new.formattedTime = [NSDate dateWithTimeIntervalSince1970:new.value]; } } return new; } - (NSDictionary *)dictionary { NSMutableDictionary *dictionary = [NSMutableDictionary new]; [dictionary setObject:[NSString stringWithFormat:@"%@", self.text] forKey:@"text"]; [dictionary setObject:[NSString stringWithFormat:@"%@", self.timeZone] forKey:@"timeZone"]; [dictionary setObject:[NSString stringWithFormat:@"%f", self.value] forKey:@"value"]; [dictionary setObject:[NSString stringWithFormat:@"%@", self.formattedTime.description] forKey:@"formattedTime"]; return dictionary; } - (NSString *)description { return [self dictionary].description; } - (id)copyWithZone:(NSZone *)zone { LPTime *new = [LPTime new]; [new setText:[self text]]; [new setTimeZone:[self timeZone]]; [new setValue:[self value]]; [new setFormattedTime:[self formattedTime]]; return new; } @end
{ "content_hash": "018b553d605e46c1d6433338a8b1f9b7", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 127, "avg_line_length": 31.153846153846153, "alnum_prop": 0.642798353909465, "repo_name": "luka1995/LPGoogleFunctions", "id": "ae4078ac72547ee53726eaf59a238f2fea53ee48", "size": "2570", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "LPGoogleFunctions/LPGoogleObjects/LPTime.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "206558" }, { "name": "Ruby", "bytes": "701" } ], "symlink_target": "" }
using System; using System.Xml; using Google.GData.Client; using System.Globalization; namespace Google.GData.Extensions.AppControl { /// <summary> /// app:control schema extension /// </summary> public class AppControl : SimpleContainer { /// <summary> /// default constructor for app:control /// </summary> public AppControl() : this(BaseNameTable.AppPublishingNamespace(null)) { } /// <summary> /// app:control constructor with namespace as parameter /// </summary> public AppControl(string ns) : base(BaseNameTable.XmlElementPubControl, BaseNameTable.gAppPublishingPrefix, ns) { this.ExtensionFactories.Add(new AppDraft()); } /// <summary> /// returns the app:draft element /// </summary> public AppDraft Draft { get { return FindExtension(BaseNameTable.XmlElementPubDraft, BaseNameTable.AppPublishingNamespace(this)) as AppDraft; } set { ReplaceExtension(BaseNameTable.XmlElementPubDraft, BaseNameTable.AppPublishingNamespace(this), value); } } /// <summary> /// need so setup the namespace based on the version information /// </summary> protected override void VersionInfoChanged() { base.VersionInfoChanged(); this.SetXmlNamespace(BaseNameTable.AppPublishingNamespace(this)); } } /// <summary> /// app:draft schema extension describing that an entry is in draft mode /// it's a child of app:control /// </summary> public class AppDraft : SimpleElement { /// <summary> /// default constructor for app:draft /// </summary> public AppDraft() : base(BaseNameTable.XmlElementPubDraft, BaseNameTable.gAppPublishingPrefix, BaseNameTable.AppPublishingNamespace(null)) { } /// <summary> /// default constructor for app:draft /// </summary> public AppDraft(bool isDraft) : base(BaseNameTable.XmlElementPubDraft, BaseNameTable.gAppPublishingPrefix, BaseNameTable.AppPublishingNamespace(null), isDraft ? "yes" : "no") { } /// <summary> /// Accessor Method for the value as integer /// </summary> public override bool BooleanValue { get { return this.Value == "yes" ? true : false; } set { this.Value = value ? "yes" : "no"; } } /// <summary> /// need so setup the namespace based on the version information /// changes /// </summary> protected override void VersionInfoChanged() { base.VersionInfoChanged(); this.SetXmlNamespace(BaseNameTable.AppPublishingNamespace(this)); } } /// <summary> /// The "app:edited" element is a Date construct (as defined by /// [RFC4287]), whose content indicates the last time an Entry was /// edited. If the entry has not been edited yet, the content indicates /// the time it was created. Atom Entry elements in Collection Documents /// SHOULD contain one app:edited element, and MUST NOT contain more than /// one. /// The server SHOULD change the value of this element every time an /// Entry Resource or an associated Media Resource has been edited /// </summary> public class AppEdited : SimpleElement { /// <summary> /// creates a default app:edited element /// </summary> public AppEdited() : base(BaseNameTable.XmlElementPubEdited, BaseNameTable.gAppPublishingPrefix, BaseNameTable.NSAppPublishingFinal) { } /// <summary> /// creates a default app:edited element with the given datetime value /// </summary> public AppEdited(DateTime dateValue) : base(BaseNameTable.XmlElementPubEdited, BaseNameTable.gAppPublishingPrefix, BaseNameTable.NSAppPublishingFinal) { this.Value = Utilities.LocalDateTimeInUTC(dateValue); } /// <summary> /// creates an app:edited element with the string as it's /// default value. The string has to conform to RFC4287 /// </summary> /// <param name="dateInUtc"></param> public AppEdited(string dateInUtc) : base(BaseNameTable.XmlElementPubEdited, BaseNameTable.gAppPublishingPrefix, BaseNameTable.NSAppPublishingFinal, dateInUtc) { } /// <summary> /// Accessor Method for the value as a DateTime /// </summary> public DateTime DateValue { get { return DateTime.Parse(this.Value, CultureInfo.InvariantCulture); } set { this.Value = Utilities.LocalDateTimeInUTC(value); } } } }
{ "content_hash": "f0cf31b5e04184cf4daafa8128ba3d5e", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 80, "avg_line_length": 34.49324324324324, "alnum_prop": 0.5843290891283056, "repo_name": "alexbikfalvi/GoogleApi", "id": "275d865aa751be5b8731dd8dd180cd21ecd5465d", "size": "5699", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/GoogleData.Core/AppControl.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "8155016" } ], "symlink_target": "" }
package com.streamsets.pipeline.stage.processor.controlHub; import com.streamsets.pipeline.api.base.BaseEnumChooserValues; /** * Chooser values for HTTP method configuration */ public class HttpMethodChooserValues extends BaseEnumChooserValues<HttpMethod> { public HttpMethodChooserValues() { super(HttpMethod.class); } }
{ "content_hash": "0807989f20da9226b1f6973a24b96daa", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 80, "avg_line_length": 25.76923076923077, "alnum_prop": 0.7970149253731343, "repo_name": "streamsets/datacollector", "id": "6bfa25886e19e2854ac3604384c018c00fa998ee", "size": "933", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "orchestrator-lib/src/main/java/com/streamsets/pipeline/stage/processor/controlHub/HttpMethodChooserValues.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "101291" }, { "name": "CSS", "bytes": "125357" }, { "name": "Groovy", "bytes": "27033" }, { "name": "HTML", "bytes": "558399" }, { "name": "Java", "bytes": "23349126" }, { "name": "JavaScript", "bytes": "1126994" }, { "name": "Python", "bytes": "26996" }, { "name": "Scala", "bytes": "6646" }, { "name": "Shell", "bytes": "30118" }, { "name": "TSQL", "bytes": "3632" } ], "symlink_target": "" }
Language.es = { "block_Tri_LED":"Led tricolor (Slot 1) R (Slot 2) % G (Slot 3) % B (Slot 4) %", "port":"Puerto", "block_LED":"LED (Slot 1) (Slot 2) %", "block_Position_Servo":"Servo de posicion (Slot 1) (Slot 2) °", "block_Rotation_Servo":"Servo de rotacion (Slot 1) (Slot 2) %", "block_Play_Note":"Emitir un sonido (Slot 1) por (Slot 2) pulsos", "Light":"Luz", "Distance":"Distancia", "Dial":"Dial", "Other":"Otro", "Accelerometer":"Acelerometro", "Magnetometer":"Magnetometro", "block_LED_Display":"Monitor", "block_Print":"Imprimir (Slot 1 = Hola)", "block_Button":"Pulsador (Slot 1)", "Screen_Up":"Subir la pantalla", "Screen_Down":"Bajar la pantalla", "Tilt_Left":"Ladear hacia la izquierda", "Tilt_Right":"Ladear hacia la derecha", "Logo_Up":"Logo arriba", "Logo_Down":"Logo abajo", "Shake":"Sacudir", "block_Compass":"Brujula", "block_Servo":"Servo (Slot 1)(Slot 2)", "block_Vibration":"Vibracion (Slot 1)(Slot 2)", "block_Motor":"Motor (Slot 1)(Slot 2)", "block_Temperature_C":"Temperatura C (Slot 1)", "block_Temperature_F":"Temperatura F (Slot 1)", "block_write":"Escribir (Slot 1) (Slot 2) %", "pin":"Pinche", "block_read":"Leer (Slot 1)", "block_Device_Shaken":"Sacudir la tableta", "block_Device_LatLong":"Tableta (Slot 1)", "Latitude":"Latitud", "Longitude":"Longitudd", "block_Device_SSID":"SSID de la tableta", "block_Device_Pressure":"Presion de la tableta", "block_Device_Relative_Altitude":"Altitud relativa de la tableta", "block_Acceleration":"Tableta (Slot 1) aceleracion", "Total":"Total", "block_Device_Orientation":"Orientacion de la tableta", "faceup":"Cara arriba", "facedown":"Cara abajo", "portrait_bottom":"Portaretrato: Camara inferior", "portrait_top":"Portaretrato: Camara superior", "landscape_left":"Paisaje: Camara en la izquierda", "landscape_right":"Paisaje: Camara en la derecha", "block_Display":"Monitor (Slot 1 = Hola) en (Slot 2)", "position":"Posicion", "block_ask":"Preguntar (Slot 1 = Cual es tu nombre?) Y esperar", "block_answer":"Responder", "block_reset_timer":"Reiniciar el temporizador", "block_timer":"Temporizador", "block_current":"Actual (Slot 1)", "date":"Fecha", "year":"Año", "month":"Mes", "hour":"Hora", "minute":"Minuto", "second":"Segundo", "day_of_the_week":"Dia de la semana", "time_in_milliseconds":"Tiempo en milisegundos", "block_mod":"(Slot 1) modo (Slot 2)", "block_round":"Vuelta (Slot 1)", "block_pick_random":" Eleccion aleatoria (Slot 1) a (Slot 2)", "block_and":"(Slot 1) y (Slot 2)", "block_or":"(Slot 1) o (Slot 2)", "block_not":"No (Slot 1)", "true":"Verdadero", "false":"Falso", "block_letter":"Letra (Slot 1) de (Slot 2 = mundo)", "block_length":"Longitud de (Slot 1 = mundo)", "block_join":"Unir (Slot 1 = hola) y (Slot 2 = mundo)", "block_split":"Dividir (Slot 1 = Hola mundo) en (Slot 2)", "letter":"Letra", "whitespace":"Espacio en blanco", "block_validate":"Es (Slot 1 = 5) un (Slot 2)?", "number":"Numero", "text":"Texto", "boolean":"Booleano", "list":"Lista", "invalid_number":"Numero invalido", "block_when_flag_tapped":"Cuando (Icon) es presionado", "block_when_I_receive":"Cuando recibo (Slot 1)", "any_message":"Cualquier mensaje", "new":"nuevo", "block_when":"Cuando (Slot 1)", "block_broadcast":"Transmitir (Slot 1)", "block_broadcast_and_wait":"Transmitir (Slot 1) y esperar", "block_message":"mensaje", "block_wait":"esperar (Slot 1) segundos", "block_wait_until":"esperar hasta (Slot 1)", "block_repeat_forever":"Repetir por siempre", "block_repeat":"repetir (Slot 1)", "block_repeat_until":"repetir hasta (Slot 1)", "block_if":"si (Slot 1)", "block_if_else":"si (Slot 1)", "else":"caso contrario", "block_stop":"detener (Slot 1)", "all":"todo", "this_script":"este esquema", "all_but_this_script":"todo menos este esquema", "Record_sound":"Grabar sonido", "block_play_recording":"Reproducir grabacion (Slot 1)", "block_play_recording_until_done":"Reproducir grabacion hasta el final (Slot 1)", "block_play_sound":"Reproducir sonido (Slot 1)", "block_play_sound_until_done":"Reproducir sonido hasta el final (Slot 1)", "block_stop_all_sounds":"Finalizar todos los sonidos", "block_rest_for":"descansar por (Slot 1) pulsos", "block_change_tempo_by":"cambiar el temporizador en (Slot 1)", "block_set_tempo_to":"configurar el temporizador a (Slot 1)", "block_tempo":"Temporizador", "block_set_variable":"configurar (Slot 1) a (Slot 2)", "Create_Variable":"Crear Variable", "block_change_variable":"cambiar (Slot 1) en (Slot 2)", "Rename":"Cambiar nombre", "Delete":"Borrar", "block_add_to_list":"agregar (Slot 1 = objeto) a (Slot 2)", "Create_List":"Crear Lista", "block_delete_from_list":"borrar (Slot 1) de (Slot 2) ", "block_insert_into_list":"insertar (Slot 1 = objeto) en (Slot 2) de (Slot 3)", "block_replace_list_item":"reemplazar item (Slot 1) de (Slot 2) con (Slot 3 = objeto)", "block_copy_list":"copiar (Slot 1) a (Slot 2)", "block_list_item":"item (Slot 1) a (Slot 2)", "block_list_length":"Longitud de (Slot 1)", "block_list_contains":"(Slot 1) contiene (Slot 2 = objeto)", "last":"Ultimo", "random":"Aleatorio", "Robots":"Robots", "Operators":"Operadores", "Sound":"Sonido", "Tablet":"Tableta", "Control":"Control", "Variables":"Variables", "Zoom_in":"Acercar zoom", "Zoom_out":"Alejar zoom", "Reset_zoom":"Reiniciar zoom", "Disable_snap_noise":"Deshabilitar sonido snap", "Enable_snap_noise":"Habilitar sonido snap", "CompassCalibrate":"Calibrar la brujula", "Send_debug_log":"Enviar registro del debug", "Show_debug_menu":"Mostrar resultados del debug", "Connect_Device":"Conectar dispositivo", "Connect_Multiple":"Coneccion multiple", "Disconnect_Device":"Desconectar dispositivo", "Tap":"Presionar + para conectar", "Scanning_for_devices":"Escaneando dispositivos", "Open":"Abrir", "No_saved_programs":"Programas no guardados", "New":"Nuevo", "Saving":"Guardando", "On_Device":"En el dispositivo", "Cloud":"Nube", "Loading":"Cargando", "Sign_in":"Ingresar", "New_program":"Programa nuevo", "Share":"Compartir", "Recordings":"Grabaciones", "Discard":"Descartar", "Stop":"Detener", "Pause":"Pausa", "remaining":"restante", "Record":"Grabar", "Tap_record_to_start":"Presionar grabar para iniciar", "Done":"Hecho", "Delete":"Borrar", "Delete_question":"Esta seguro que quiere borrar esto?", "Cancel":"Cancelar", "OK":"Aceptar", "Dont_delete":"No borrar", "Rename":"Cambiar nombre", "Enter_new_name":"Ingrese un nombre nuevo", "Duplicate":"Duplicar", "Name_duplicate_file":"Ingrese un nombre para el archivo duplicado", "Name_error_invalid_characters":"Los siguientes caracteres no pueden ser utilizados en los nombres de los archivos: \n", "Name_error_already_exists":"\" ya existe. Entre un nombre diferente", "Permission_denied":"Permiso denegado", "Grant_permission":"Permiso especial de grabacion en la configuracion del BirdBlox", "Dismiss":"Descartar", "Name":"Nombre", "Enter_file_name":"Ingresar el nombre del archivo", "Name_error_blank":"El nombre no puede estar vacio. Ingrese un nombre para el archivo", "Edit_text":"Editar texto", "Question":"Pregunta", "Connection_Failure":"Coneccion fallada", "Connection_failed_try_again":"Coneccion fallada, por favor intente de nuevo", "Disconnect_account":"Desconectar la cuenta", "Disconnect_account_question":"Desconectar la cuenta?", "Dont_disconnect":"No desconectar", "Disconnect":"Desconectar", "not_connected":"(Device) no conectado", "not_a_valid_number":"Este numero no es valido", "Intensity":"Intensidad", "Angle":"Angulo", "Speed":"Velocidad", "Note":"Nota", "Beats":"Pulsos", "Firmware_incompatible":"El firmware es incompatible", "Update_firmware":"Actualizar firmware", "Device_firmware":"Version del firmware del dispositivo:", "Required_firmware":"Version del firmware requerida:", "block_math_of_number":"(Slot 1) (Slot 2 = 10)", "ceiling":"ceiling", "floor":"floor", "abs":"abs", "sqrt":"sqrt", "CM":"CM", "Inch":"Inch", "block_subtract":"(Slot 1) – (Slot 2)", "block_divide":"(Slot 1) / (Slot 2)" }
{ "content_hash": "8859083652a367dd90e0e75b49342e4d", "timestamp": "", "source": "github", "line_count": 212, "max_line_length": 120, "avg_line_length": 38.382075471698116, "alnum_prop": 0.6728524026053828, "repo_name": "BirdBrainTechnologies/HummingbirdDragAndDrop-", "id": "938b744e666fdc58a711352b17db595f19ef01c1", "size": "8163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Language/Language.es.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3089" }, { "name": "HTML", "bytes": "25811" }, { "name": "JavaScript", "bytes": "3155678" }, { "name": "Python", "bytes": "4528" }, { "name": "TeX", "bytes": "58660" } ], "symlink_target": "" }
<?php # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/compute/v1/compute.proto namespace Google\Cloud\Compute\V1\InstanceProperties; use UnexpectedValueException; /** * The private IPv6 google access type for VMs. If not specified, use INHERIT_FROM_SUBNETWORK as default. * * Protobuf type <code>google.cloud.compute.v1.InstanceProperties.PrivateIpv6GoogleAccess</code> */ class PrivateIpv6GoogleAccess { /** * A value indicating that the enum field is not set. * * Generated from protobuf enum <code>UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0;</code> */ const UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS = 0; /** * Bidirectional private IPv6 access to/from Google services. If specified, the subnetwork who is attached to the instance's default network interface will be assigned an internal IPv6 prefix if it doesn't have before. * * Generated from protobuf enum <code>ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994;</code> */ const ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE = 427975994; /** * Outbound private IPv6 access from VMs in this subnet to Google services. If specified, the subnetwork who is attached to the instance's default network interface will be assigned an internal IPv6 prefix if it doesn't have before. * * Generated from protobuf enum <code>ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263;</code> */ const ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE = 288210263; /** * Each network interface inherits PrivateIpv6GoogleAccess from its subnetwork. * * Generated from protobuf enum <code>INHERIT_FROM_SUBNETWORK = 530256959;</code> */ const INHERIT_FROM_SUBNETWORK = 530256959; private static $valueToName = [ self::UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS => 'UNDEFINED_PRIVATE_IPV6_GOOGLE_ACCESS', self::ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE => 'ENABLE_BIDIRECTIONAL_ACCESS_TO_GOOGLE', self::ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE => 'ENABLE_OUTBOUND_VM_ACCESS_TO_GOOGLE', self::INHERIT_FROM_SUBNETWORK => 'INHERIT_FROM_SUBNETWORK', ]; public static function name($value) { if (!isset(self::$valueToName[$value])) { throw new UnexpectedValueException(sprintf( 'Enum %s has no name defined for value %s', __CLASS__, $value)); } return self::$valueToName[$value]; } public static function value($name) { $const = __CLASS__ . '::' . strtoupper($name); if (!defined($const)) { throw new UnexpectedValueException(sprintf( 'Enum %s has no value defined for name %s', __CLASS__, $name)); } return constant($const); } }
{ "content_hash": "04f477e468f7f149cf8be5d3779df78d", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 236, "avg_line_length": 39.89855072463768, "alnum_prop": 0.6767163094805666, "repo_name": "chingor13/google-cloud-php", "id": "fb2d4a1ae8a525d0db4f81e78f3e2cd35228d86c", "size": "2753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Compute/src/V1/InstanceProperties/PrivateIpv6GoogleAccess.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "670" }, { "name": "PHP", "bytes": "34466701" }, { "name": "Python", "bytes": "321175" }, { "name": "Shell", "bytes": "8827" } ], "symlink_target": "" }
package com.taobao.weex.bridge; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import com.taobao.weex.WXSDKInstance; import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; /** * Created by lixinke on 16/2/24. */ @RunWith(RobolectricTestRunner.class) public class WXBridgeManagerTest extends TestCase { public void setUp() throws Exception { super.setUp(); } @Test public void testGetJSHander() throws Exception { Handler handler=WXBridgeManager.getInstance().getJSHandler(); assertNotNull(handler); } public void testGetInstance() throws Exception { WXBridgeManager instance = WXBridgeManager.getInstance(); assertNotNull(instance); } public void testRestart() throws Exception { } public void testSetStackTopInstance() throws Exception { WXBridgeManager.getInstance().setStackTopInstance(""); } public void testCallNative() throws Exception { } public void testInitScriptsFramework() throws Exception { } public void testFireEvent() throws Exception { } public void testCallback() throws Exception { } public void testCallback1() throws Exception { } public void testRefreshInstance() throws Exception { } public void testCreateInstance() throws Exception { } public void testDestroyInstance() throws Exception { } public void testRegisterComponents() throws Exception { } public void testRegisterModules() throws Exception { } public void testHandleMessage() throws Exception { } public void testDestroy() throws Exception { } public void testReportJSException() throws Exception { } public void testCommitJSBridgeAlarmMonitor() throws Exception { } }
{ "content_hash": "2b737e9e831b5b5383011d44c093fc55", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 69, "avg_line_length": 19.48076923076923, "alnum_prop": 0.707305034550839, "repo_name": "houfeng0923/weex", "id": "6e54ef9778e7ad9ad62ec3a9208e65e3515c2a4a", "size": "13950", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "android/sdk/src/test/java/com/taobao/weex/bridge/WXBridgeManagerTest.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "54186" }, { "name": "CSS", "bytes": "19569" }, { "name": "HTML", "bytes": "6747" }, { "name": "IDL", "bytes": "85" }, { "name": "Java", "bytes": "5566911" }, { "name": "JavaScript", "bytes": "3720731" }, { "name": "Objective-C", "bytes": "1209782" }, { "name": "Ruby", "bytes": "2294" }, { "name": "Shell", "bytes": "6289" } ], "symlink_target": "" }
export default () => <h1>This is the CONTACT page.</h1>
{ "content_hash": "4141d1c0d4926bdb3f7ed44524592715", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 55, "avg_line_length": 56, "alnum_prop": 0.6607142857142857, "repo_name": "BlancheXu/test", "id": "0bc89f9b3fe9d2044e11caf53a6eba3eb06d15ca", "size": "56", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/with-prefetching/pages/contact.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1007" }, { "name": "JavaScript", "bytes": "681828" }, { "name": "Shell", "bytes": "1294" }, { "name": "TypeScript", "bytes": "445811" } ], "symlink_target": "" }
package io.getlime.security.powerauth.integration.support.model; public enum ActivationOtpValidation { NONE, ON_KEY_EXCHANGE, ON_COMMIT }
{ "content_hash": "794b7ddde79827a938159871a5123a18", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 17, "alnum_prop": 0.7450980392156863, "repo_name": "lime-company/lime-security-powerauth-mobile-sdk", "id": "ae7793bec7826cff7e461de5cbfc56091987cc3f", "size": "745", "binary": false, "copies": "1", "ref": "refs/heads/issues/361-disable-encrypted-keychain", "path": "proj-android/PowerAuthLibrary/src/androidTest/java/io/getlime/security/powerauth/integration/support/model/ActivationOtpValidation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3344" }, { "name": "C++", "bytes": "615810" }, { "name": "Java", "bytes": "271771" }, { "name": "Makefile", "bytes": "6363" }, { "name": "Objective-C", "bytes": "435644" }, { "name": "Objective-C++", "bytes": "36082" }, { "name": "Ruby", "bytes": "4771" }, { "name": "Shell", "bytes": "25930" } ], "symlink_target": "" }
import Vue from 'vue'; import VueResource from 'vue-resource'; import localforage from 'localforage'; import { USER_MODULES_KEY, MODULES_LIST_KEY, USER_SETTINGS_KEY, userOnboardModule, } from '../constants'; Vue.use(VueResource); // Vue.http.options.crossOrigin = true; // Vue.http.options.xhr = { withCredentials: true }; const API_ROOT = 'https://api.modify.sg/'; const ModulesListResource = Vue.resource(`${API_ROOT}modulesList/{school}/{year}/{sem}`); const ModuleResource = Vue.resource(`${API_ROOT}modules/{school}/{year}/{sem}/{moduleCode}`); function getFromForage(key, apiCall) { return localforage.getItem(key).then((value) => { if (value) { const differenceInSeconds = (new Date() - value.date) / 1000; // cache for one day if (Math.abs(differenceInSeconds) < 86400) { return Promise.resolve(value.data); } } return apiCall.then((response) => { const data = response.json(); const object = { data, date: new Date(), }; // save to local forage with date localforage.setItem(key, object); return data; }); }); } /** * Returns either user modules if they are present, or retrieve onboard module */ function getUserModulesOrOnboardModules(combinedKey) { return localforage.getItem(combinedKey).then((value) => { if (value) { return Promise.resolve(value); } // check all keys, and check if user has ANY previous usage return localforage.keys().then((keys) => { // do some clean up on this step if (keys.length > 50) { keys.forEach((key) => { if (key.indexOf('-') === -1 && key.indexOf('user') === -1) { localforage.removeItem(key); } }); } // user has used modify before if (keys.some(key => key.indexOf(USER_MODULES_KEY) !== -1)) { return Promise.resolve(null); // but not this particular set } return Promise.resolve(userOnboardModule); }); }); } export default { getDefault() { return localforage.getItem(USER_SETTINGS_KEY); }, getModulesList(school, year, sem) { return getFromForage( MODULES_LIST_KEY + school + year + sem, ModulesListResource.get({ school, year, sem }), ); }, getUserModules(school, year, sem) { return getUserModulesOrOnboardModules(USER_MODULES_KEY + school + year + sem); }, getModule(school, year, sem, moduleCode) { return getFromForage( moduleCode, ModuleResource.get({ school, year, sem, moduleCode }) ); }, };
{ "content_hash": "12f833c1fa00be117626196634bcb02a", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 93, "avg_line_length": 29.767441860465116, "alnum_prop": 0.625390625, "repo_name": "li-kai/modify", "id": "4537497d586b0fb217cd06eaacef978b97235b0e", "size": "2560", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/api/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8621" }, { "name": "HTML", "bytes": "1795" }, { "name": "JavaScript", "bytes": "40511" }, { "name": "Vue", "bytes": "45093" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Thu Mar 08 14:17:36 MST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>CustomRealmMapperSupplier (BOM: * : All 2018.3.3 API)</title> <meta name="date" content="2018-03-08"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="CustomRealmMapperSupplier (BOM: * : All 2018.3.3 API)"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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="class-use/CustomRealmMapperSupplier.html">Use</a></li> <li><a href="package-tree.html">Tree</a></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 class="aboutLanguage">WildFly Swarm API, 2018.3.3</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html" target="_top">Frames</a></li> <li><a href="CustomRealmMapperSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.wildfly.swarm.config.elytron</div> <h2 title="Interface CustomRealmMapperSupplier" class="title">Interface CustomRealmMapperSupplier&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a>&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Functional Interface:</dt> <dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd> </dl> <hr> <br> <pre><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a> public interface <span class="typeNameLabel">CustomRealmMapperSupplier&lt;T extends <a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a>&gt;</span></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html#get--">get</a></span>()</code> <div class="block">Constructed instance of CustomRealmMapper resource</div> </td> </tr> </table> </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="get--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>get</h4> <pre><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapper.html" title="class in org.wildfly.swarm.config.elytron">CustomRealmMapper</a>&nbsp;get()</pre> <div class="block">Constructed instance of CustomRealmMapper resource</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>The instance</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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="class-use/CustomRealmMapperSupplier.html">Use</a></li> <li><a href="package-tree.html">Tree</a></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 class="aboutLanguage">WildFly Swarm API, 2018.3.3</div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmMapperConsumer.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../org/wildfly/swarm/config/elytron/CustomRealmSupplier.html" title="interface in org.wildfly.swarm.config.elytron"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html" target="_top">Frames</a></li> <li><a href="CustomRealmMapperSupplier.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p> </body> </html>
{ "content_hash": "fbad6f2c0d4d21896aeeeb29c6ec9a10", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 391, "avg_line_length": 39.56962025316456, "alnum_prop": 0.6470462785242056, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "4610ae131caff5b70af86a6bb89ccdb23c398cd5", "size": "9378", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2018.3.3/apidocs/org/wildfly/swarm/config/elytron/CustomRealmMapperSupplier.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* eslint-env mocha */ import Controller from '../Controller' import assert from 'assert' import {set} from './' import {input, state, string} from '../tags' describe('operator.set', () => { it('should set value to model', () => { const controller = Controller({ state: { foo: 'bar' }, signals: { test: [ set(state`foo`, 'bar2') ] } }) controller.getSignal('test')() assert.deepEqual(controller.getState(), {foo: 'bar2'}) }) it('should set value to input', () => { const controller = Controller({ signals: { test: [ set(input`foo`, 'bar'), ({input}) => { assert.equal(input.foo, 'bar') } ] } }) controller.getSignal('test')() }) it('should set deep value to input', () => { const controller = Controller({ signals: { test: [ set(input`foo`, {bing: 'bor'}), set(input`foo.bar`, 'baz'), ({input}) => { assert.equal(input.foo.bar, 'baz') assert.equal(input.foo.bing, 'bor') } ] } }) controller.getSignal('test')() }) it('should set non string value to model', () => { const controller = Controller({ state: { foo: 'bar' }, signals: { test: [ set(state`foo`, {bar: 'baz'}) ] } }) controller.getSignal('test')() assert.deepEqual(controller.getState(), {foo: {bar: 'baz'}}) }) it('should set value to model from input', () => { const controller = Controller({ state: { foo: 'bar' }, signals: { test: [ set(state`foo`, input`value`) ] } }) controller.getSignal('test')({ value: 'bar2' }) assert.deepEqual(controller.getState(), {foo: 'bar2'}) }) it('should set value to model from model', () => { const controller = Controller({ state: { foo: 'bar', grabValue: 'bar2' }, signals: { test: [ set(state`foo`, state`grabValue`) ] } }) controller.getSignal('test')() assert.equal(controller.getState().foo, 'bar2') }) it('should throw on bad argument', () => { const controller = Controller({ state: { }, signals: { test: [ set(string`foo`, 'bar') ] } }) assert.throws(() => { controller.getSignal('test')() }, /operator.set/) }) })
{ "content_hash": "2445a1cace5117c39a5df9c2e673ddb8", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 64, "avg_line_length": 23.137614678899084, "alnum_prop": 0.4809674861221253, "repo_name": "idream3/cerebral", "id": "0be9951cc4c077a5b4b4ffbf704abb80ea745c70", "size": "2522", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/cerebral/src/operators/set.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29368" }, { "name": "HTML", "bytes": "25398" }, { "name": "JavaScript", "bytes": "665363" } ], "symlink_target": "" }
package underground_test import ( "testing" "strings" . "github.com/futoase/underground" ) func TestUnderground(t *testing.T) { if !strings.EqualFold(WelcomeToUnderground(), "Welcome to underground...\n") { t.Errorf("Oh! this is heaven!") } }
{ "content_hash": "d5152c22bc13747d75e6249f835f5759", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 80, "avg_line_length": 18.571428571428573, "alnum_prop": 0.6807692307692308, "repo_name": "futoase/underground", "id": "0301dd1eb15098443790b7449b9d866092abb33d", "size": "260", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "underground_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "359" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace RaftLib.Protocol { class XDRStream : XDRFormatter { System.IO.Stream mStream; byte[] buffer = new byte[BytesPerXDRUnit]; public XDRStream(System.IO.Stream stream, XDROp xdrOp) { this.mStream = stream; this.xdrOp = xdrOp; } protected override void GetInt32(ref int value) { mStream.Read(buffer, 0, BytesPerXDRUnit); value = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0)); } protected override void PutInt32(int value) { mStream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(value)), 0, BytesPerXDRUnit); } protected override void GetBytes(byte[] value, int start, int length) { mStream.Read(value, start, length); } protected override void PutBytes(byte[] value, int start, int length) { mStream.Write(value, start, length); } protected override int GetPos() { return (int) mStream.Position; } protected override void SetPos(int pos) { mStream.Seek(pos, System.IO.SeekOrigin.Begin); } } }
{ "content_hash": "2c922918b95389b3b4ec9222f1480aca", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 106, "avg_line_length": 24.98181818181818, "alnum_prop": 0.5975254730713246, "repo_name": "traviolia/ThatchedHut", "id": "13d840e1abc146b277afe979110284ed25d3504a", "size": "3216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "RaftLib/Protocol/XDRStream.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1148" }, { "name": "C#", "bytes": "260571" }, { "name": "C++", "bytes": "1092989" }, { "name": "Python", "bytes": "2074" } ], "symlink_target": "" }
'use strict'; /* * Manages the AST representation of the specs for fold status * and other meta information about the specs tree */ SwaggerEditor.service('ASTManager', function ASTManager() { var MAP_TAG = 'tag:yaml.org,2002:map'; var SEQ_TAG = 'tag:yaml.org,2002:seq'; var INDENT = 2; // TODO: make indent dynamic based on document var ast = {}; var changeListeners = []; var yamlBuffer = ''; /* ** Update ast with changes from editor */ function refreshAST(value) { value = value || ''; try { yamlBuffer = value; ast = yaml.compose(value); emitChanges(); } catch (err) { console.warn('Failed to refresh line numbers', err); } } /* ** Let event listeners know there was a change in fold status */ function emitChanges() { changeListeners.forEach(function (fn) { fn(); }); } /* * Walk the ast for a given path * @param {array} path - list of keys to follow to reach to reach a node * @param {object} current - only used for recursive calls * @returns {object} - the node that path is pointing to */ function walk(path, current) { var key; current = current || ast; if (!current) { return current; } if (!Array.isArray(path)) { throw new Error('Need path to find the node in the AST'); } if (!path.length) { return current; } key = path.shift(); // If current is a map, search in mapping tuples and find the // one that it's first member equals the one if (current.tag === MAP_TAG) { for (var i = 0; i < current.value.length; i++) { var val = current.value[i]; if (val[0].value === key) { return walk(path, val[1]); } } // If current is a sequence (array), return item with index // that is equal to key. `key` should be an int } else if (current.tag === SEQ_TAG) { key = parseInt(key, 10); current = current.value[key]; return walk(path, current); } return current; } /* * Beneath first search the AST and finds the node that has the same * start line number * @param {object} current - optional, AST o search in it. used for * recursive calls * @returns {object} - the node that has the same start line or null * if node wasn't found */ function scan(current, start) { var val; current = current || ast; if (!angular.isObject(current) || !current.value) { return current; } /* jshint camelcase: false */ if (current.start_mark.line === start) { return current; } for (var i = 0; i < current.value.length; i++) { if (current.tag === MAP_TAG) { val = scan(current.value[i][1], start); } else if (current.tag === SEQ_TAG) { val = scan(current.value[i], start); } if (val) { return val; } } return null; } /* * return back line number of an specific node with given path */ function lineForPath(path) { var node = walk(path); if (node) { /* jshint camelcase: false */ return node.start_mark.line; } return null; } /* * @param {number} line - line number to loop up * @param {number} row - row number to loop up * @param {object} current - used for recursive call * @param {array} path - used for recursive call * @returns {array} - an array of strings (path) to the node * in line of the code in the editor */ function pathForPosition(line, row) { /* jshint camelcase: false */ var result = []; var start; var end; var yamlLines = yamlBuffer.split('\n'); var buffer = null; // If pointer is not at the end of document, strip down the rest of document // from below this line and use AST from the stripped document // We don't do this stripping when pointer is at beginning of a line // or line is a key-value map if (line !== yamlLines.length - 1 && row !== 0 && !/.\: ./.test(yamlLines[line])) { // Get a copy of full YAML buffer = _.clone(yamlBuffer); // Trim down yaml to the line var yaml = yamlLines.slice(0, line).join('\n') + '\n'; // Add indentation to yaml var lastLine = yamlLines[line]; var lastLineChars = lastLine.split(''); while (lastLineChars.length && lastLineChars.pop() !== ' ') { yaml += ' '; } refreshAST(yaml); } if (line === undefined) { return result; } recurse ([], ast); function recurse(path, current) { if (!current) { return; } start = current.start_mark; end = current.end_mark; // if node is the same line as `line` and row falls between node's start // and end columns we found the node if (start.line === line && end.line === line && start.column <= row && end.column >= row) { result = path; // if this node is a map, loop throw and recurse both keys and value } else if (current.tag === MAP_TAG) { current.value.forEach(function (keyValuePair) { recurse(path, keyValuePair[0]); // key recurse(path.concat(keyValuePair[0].value), keyValuePair[1]); // value }); // if this node is a sequence, loop throw values and recurse } else if (current.tag === SEQ_TAG) { current.value.forEach(function (value, index) { recurse(path.concat(index), value); }); } } // if pointer is at end of file depending on indentation, select the parent // node if (ast && ast.end_mark.line === line && result.length === 0) { var current = ast; // Select last key of the map for each indent while (row > 0) { if (current.tag === MAP_TAG) { result.push(current.value[current.value.length - 1][0].value); current = current.value[current.value.length - 1][1]; } row -= INDENT; } } // Put back yamlBuffer if (buffer) { refreshAST(buffer); } return result; } /* * Toggles a node's fold * @param {object} node - a node object * @param {boolean} value - optional. if provided overrides node's folded * value */ function toggleNodeFold(Editor, node, value) { /* jshint camelcase: false */ if (typeof value === 'undefined') { value = node.folded; } else { value = !value; } // Remove the fold from the editor if node is folded if (value) { Editor.removeFold(node.start_mark.line); node.folded = false; // Add fold to editor if node is not folded } else { Editor.addFold(node.start_mark.line - 1, node.end_mark.line - 1); node.folded = true; } } /* * Listen to fold changes in editor and reflect it in the AST * then emit AST change event to trigger rendering in the preview * pane */ this.onFoldChanged = function onFoldChanged(change) { var row = change.data.start.row + 1; var folded = change.action !== 'remove'; var node = scan(ast, row); if (node) { node.folded = folded; } emitChanges(); }; /* * Toggle a fold status and reflect it in the editor * @param {array} path - an array of string that is path to a node * in the AST */ this.toggleFold = function (path, Editor) { var node = walk(path, ast); /* jshint camelcase: false */ // Guard against when walk fails if (!node || !node.start_mark) { return; } toggleNodeFold(Editor, node); // Let other components know changes happened emitChanges(); }; /* * Sets fold status for all direct children of a given path * @param {array} path - list of strings keys pointing to a node in AST * @param {boolean} value - true if all nodes should get folded, * false otherwise */ this.setFoldAll = function (path, value, Editor) { var node = walk(path, ast); var subNode; for (var i = 0; i < node.value.length; i++) { if (node.tag === MAP_TAG) { subNode = node.value[i][1]; } else if (node.tag === SEQ_TAG) { subNode = node.value[i]; } toggleNodeFold(Editor, subNode, value); } emitChanges(); }; /* * Return status of a fold with given path parameters * @param {array} path - an array of string that is path to a node * in the AST * @return {boolean} - true if the node is folded, false otherwise */ this.isFolded = function (path) { var node = walk(path, ast); return angular.isObject(node) && !!node.folded; }; /* * Checks to see if all direct children of a node are folded * @param {array} path path - an array of string that is path to a node * in the AST * @returns {boolean} - true if all nodes are folded, false, otherwise */ this.isAllFolded = function (path) { var node = walk(path); var subNode; if (!node || !Array.isArray(node.value)) { return false; } for (var i = 0; i < node.value.length; i++) { if (node.tag === MAP_TAG) { subNode = node.value[i][1]; } else if (node.tag === SEQ_TAG) { subNode = node.value[i]; } if (!subNode.folded) { return false; } } return true; }; /* ** Fold status change listener installer */ this.onFoldStatusChanged = function (fn) { changeListeners.push(fn); }; // Expose the methods externally this.refresh = refreshAST; this.lineForPath = lineForPath; this.pathForPosition = pathForPosition; });
{ "content_hash": "3c56b91efe4391edf08081776725a8b6", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 80, "avg_line_length": 25.875338753387535, "alnum_prop": 0.5866149979053205, "repo_name": "mko-x/docker-swagger-editor", "id": "6e39ad9deed455c309440996e98932b3b0fc6cea", "size": "9548", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/scripts/services/ast-manager.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "35474" }, { "name": "HTML", "bytes": "42647" }, { "name": "JavaScript", "bytes": "129038" } ], "symlink_target": "" }
// For more information on how to configure a task runner, please visit: // https://github.com/gulpjs/gulp var gulp = require('gulp'); var gutil = require('gulp-util'); var gulpif = require('gulp-if'); var clean = require('gulp-clean'); var concat = require('gulp-concat'); var rename = require('gulp-rename'); var jshint = require('gulp-jshint'); var uglify = require('gulp-uglifyjs'); var sass = require('gulp-sass'); var csso = require('gulp-csso'); var es = require('event-stream'); var http = require('http'); var browserify = require('gulp-browserify'); var sprite = require('css-sprite').stream; gulp.task('clean', function () { // Clear the destination folder gulp.src('dist/**/*.*', { read: false }) .pipe(clean({ force: true })); }); gulp.task('copy-html', function () { return gulp.src('./src/**/*.html', { base: './src' }) .pipe(gulp.dest('./dist')); }); gulp.task('copy', ['copy-html'], function () { // Copy all application files except *.less and .js into the `dist` folder return es.concat( gulp.src(['src/scss/fontello/**']) .pipe(gulp.dest('dist/css/fontello')), gulp.src(['src/scss/opensans/**']) .pipe(gulp.dest('dist/css/opensans')), gulp.src(['src/img/**']) .pipe(gulp.dest('dist/img')), gulp.src(['src/js/vendor/**']) .pipe(gulp.dest('dist/js/vendor')), gulp.src(['src/*.*', 'src/CNAME']) .pipe(gulp.dest('dist')) ); }); gulp.task('scripts', function () { return es.concat( // Detect errors and potential problems in your JavaScript code // You can enable or disable default JSHint options in the .jshintrc file gulp.src(['src/js/**/*.js', '!src/js/vendor/**']) .pipe(jshint('.jshintrc')) .pipe(jshint.reporter(require('jshint-stylish'))), // Concatenate, minify and copy all JavaScript (except vendor scripts) gulp.src('src/js/app.js') .pipe(browserify({ insertGlobals: true, debug: false // true })) .pipe(uglify({ outSourceMap: true, basePath: '/js/' })) .pipe(gulp.dest('./dist/js')) // pipe it to the output DIR ); }); gulp.task('sprites', function () { return gulp.src('./src/img/communities/gray/*.png') .pipe(sprite({ name: 'communities.png', style: '_sprite.scss', cssPath: '/img/communities/', processor: 'scss', prefix: 'community', retina: true })) .pipe(gulpif('*.png', gulp.dest('./src/img/communities/'))) .pipe(gulpif('*.scss', gulp.dest('./src/scss/'))); }); gulp.task('styles', function () { return gulp.src('src/scss/app.scss') .pipe(sass()) .pipe(rename('app.css')) .pipe(csso()) .pipe(gulp.dest('dist/css')) }); gulp.task('watch', function () { // Watch .js files and run tasks if they change gulp.watch('src/js/**/*.js', ['scripts']); // Watch .less files and run tasks if they change gulp.watch('src/scss/**/*.scss', ['styles']); // Watch .html files gulp.watch('./src/**/*.html', ['copy-html']); }); // The dist task (used to store all files that will go to the server) gulp.task('dist', ['clean', 'copy', 'scripts', 'sprites', 'styles']); // The default task (called when you run `gulp`) gulp.task('default', ['dist', 'watch']);
{ "content_hash": "e4c7990d3482870bbc222ade3773ddfa", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 77, "avg_line_length": 30.8411214953271, "alnum_prop": 0.5927272727272728, "repo_name": "icoloma/web-codemotion", "id": "ac69672a394a85dc0c69faa11c6df87960575164", "size": "3300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "346094" }, { "name": "JavaScript", "bytes": "36250" }, { "name": "Shell", "bytes": "1513" } ], "symlink_target": "" }
![SendGrid Logo](https://uiux.s3.amazonaws.com/2016-logos/email-logo%402x.png) This folder contains various examples on using the SUPPRESSION endpoint of SendGrid with Java: * [Retrieve all blocks (GET /suppression/blocks)](GetAllBlocks.java) * [Delete blocks (DELETE /suppression/blocks)](DeleteBlocks.java) * [Retrieve a specific block (GET /suppression/blocks/{email})](GetSpecificBlock.java) * [Delete a specific block (DELETE /suppression/blocks/{email})](DeleteSpecificBlock.java) * [Retrieve all bounces (GET /suppression/bounces)](GetAllBounces.java) * [Delete bounces (DELETE /suppression/bounces)](DeleteBounces.java) * [Retrieve a Bounce (GET /suppression/bounces/{email})](GetBounce.java) * [Delete a bounce (DELETE /suppression/bounces/{email})](DeleteBounce.java) * [Retrieve all invalid emails (GET /suppression/invalid_emails)](GetAllInvalidEmails.java) * [Delete invalid emails (DELETE /suppression/invalid_emails)](DeleteInvalidEmails.java) * [Retrieve a specific invalid email (GET /suppression/invalid_emails/{email})](GetSpecificInvalidEmail.java) * [Delete a specific invalid email (DELETE /suppression/invalid_emails/{email})](DeleteSpecificInvalidEmail.java) * [Retrieve a specific spam report (GET /suppression/spam_report/{email})](GetSpecificSpamReport.java) * [Delete a specific spam report (DELETE /suppression/spam_report/{email})](DeleteSpecificSpamReport.java) * [Retrieve all spam reports (GET /suppression/spam_reports)](GetAllSpamReports.java) * [Delete spam reports (DELETE /suppression/spam_reports)](DeleteSpamReports.java) * [Retrieve all global suppressions (GET /suppression/unsubscribes)](GetAllGlobalSuppressions.java)
{ "content_hash": "b6ee4c87946b72ecadda6f56ec0325dd", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 113, "avg_line_length": 79.19047619047619, "alnum_prop": 0.7895369813589898, "repo_name": "pushkyn/sendgrid-java", "id": "ca686a4bf8c01cf4d9bf04d966d29861e58723cf", "size": "1663", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/suppression/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "619" }, { "name": "Java", "bytes": "219675" }, { "name": "Shell", "bytes": "3669" } ], "symlink_target": "" }
package org.janusz.steven.myoverflow.stackoverflow.data; import com.google.gson.annotations.SerializedName; /** * Created by marek on 03.10.14. */ public class Owner { private long reputation; @SerializedName("user_id") private long userId; @SerializedName("user_type") private String userType; @SerializedName("accept_rate") private long acceptRate; @SerializedName("profile_image") private String profileImageURL; @SerializedName("display_name") private String displayName; private String link; public Owner() {} public long getReputation() { return reputation; } public void setReputation(long reputation) { this.reputation = reputation; } public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public long getAcceptRate() { return acceptRate; } public void setAcceptRate(long acceptRate) { this.acceptRate = acceptRate; } public String getProfileImageURL() { return profileImageURL; } public void setProfileImageURL(String profileImageURL) { this.profileImageURL = profileImageURL; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } }
{ "content_hash": "2ea08ee52ffdb6e38de4d6263b6cccdc", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 68, "avg_line_length": 22.554054054054053, "alnum_prop": 0.6518873576992211, "repo_name": "07steven01/MyOverflow", "id": "0d25e7a0f7d2d1563ef8732aab596a3c09f77388", "size": "1669", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "app/src/main/java/org/janusz/steven/myoverflow/stackoverflow/data/Owner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "1176" }, { "name": "Java", "bytes": "16105" } ], "symlink_target": "" }
ARG REPO=mcr.microsoft.com/dotnet/aspnet FROM $REPO:5.0-buster-slim-amd64 ENV \ # Unset ASPNETCORE_URLS from aspnet base image ASPNETCORE_URLS= \ DOTNET_SDK_VERSION=5.0.300 \ # Enable correct mode for dotnet watch (only mode supported in a container) DOTNET_USE_POLLING_FILE_WATCHER=true \ # Skip extraction of XML docs - generally not useful within an image/container - helps performance NUGET_XMLDOC_MODE=skip \ # PowerShell telemetry for docker image usage POWERSHELL_DISTRIBUTION_CHANNEL=PSDocker-DotnetSDK-Debian-10 # Install Java (required to run tests) RUN apt-get update \ && apt-get install -y --no-install-recommends \ curl \ git \ procps \ wget \ tofrodos \ && mkdir -p /usr/share/man/man1 \ && apt-get install -y --no-install-recommends \ openjdk-11-jdk ca-certificates-java \ && rm -rf /var/lib/apt/lists/* # Install .NET SDK v2.1 RUN dotnet_sdk_version=2.1.816 \ && curl -SL --output dotnet.tar.gz https://dotnetcli.azureedge.net/dotnet/Sdk/$dotnet_sdk_version/dotnet-sdk-$dotnet_sdk_version-linux-x64.tar.gz \ && dotnet_sha512='58f0bc1f67de034ffd0dafb9c0fdb082786fc5057e89396ff574428d57331cd8d5b3e944e103918e05f7b66e354d56cdb242350a6ef932906c9c3d4b08d177e9' \ && echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \ && mkdir -p /usr/share/dotnet \ && tar -zxf dotnet.tar.gz -C /usr/share/dotnet \ && rm dotnet.tar.gz # Install .NET SDK v3.1 RUN dotnet_sdk_version=3.1.409 \ && curl -SL --output dotnet.tar.gz https://dotnetcli.azureedge.net/dotnet/Sdk/$dotnet_sdk_version/dotnet-sdk-$dotnet_sdk_version-linux-x64.tar.gz \ && dotnet_sha512='63d24f1039f68abc46bf40a521f19720ca74a4d89a2b99d91dfd6216b43a81d74f672f74708efa6f6320058aa49bf13995638e3b8057efcfc84a2877527d56b6' \ && echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \ && mkdir -p /usr/share/dotnet \ && tar -ozxf dotnet.tar.gz -C /usr/share/dotnet \ && rm dotnet.tar.gz # Install .NET SDK v5.0 RUN dotnet_sdk_version=$DOTNET_SDK_VERSION \ && curl -SL --output dotnet.tar.gz https://dotnetcli.azureedge.net/dotnet/Sdk/$dotnet_sdk_version/dotnet-sdk-$dotnet_sdk_version-linux-x64.tar.gz \ && dotnet_sha512='724a8e6ed77d2d3b957b8e5eda82ca8c99152d8691d1779b4a637d9ff781775f983468ee46b0bc8ad0ddbfd9d537dd8decb6784f43edae72c9529a90767310d2' \ && echo "$dotnet_sha512 dotnet.tar.gz" | sha512sum -c - \ && mkdir -p /usr/share/dotnet \ && tar -C /usr/share/dotnet -oxzf dotnet.tar.gz ./packs ./sdk ./templates ./LICENSE.txt ./ThirdPartyNotices.txt \ && rm dotnet.tar.gz \ #&& ln -s /usr/share/dotnet/dotnet /usr/bin/dotnet \ # Trigger first run experience by running arbitrary cmd && dotnet help # Install PowerShell global tool RUN powershell_version=7.1.3 \ && curl -SL --output PowerShell.Linux.x64.$powershell_version.nupkg https://pwshtool.blob.core.windows.net/tool/$powershell_version/PowerShell.Linux.x64.$powershell_version.nupkg \ && powershell_sha512='537d885b79dd1cd183d14b5f5e71046558fb015f562bb817ee90fbabaa9b1039c822949b7e1a5c9b69a976eae09786e3b2c0f0586c01c822868cc48ea7e36620' \ && echo "$powershell_sha512 PowerShell.Linux.x64.$powershell_version.nupkg" | sha512sum -c - \ && mkdir -p /usr/share/powershell \ && dotnet tool install --add-source / --tool-path /usr/share/powershell --version $powershell_version PowerShell.Linux.x64 \ && dotnet nuget locals all --clear \ && rm PowerShell.Linux.x64.$powershell_version.nupkg \ && ln -s /usr/share/powershell/pwsh /usr/bin/pwsh \ && chmod 755 /usr/share/powershell/pwsh \ # To reduce image size, remove the copy nupkg that nuget keeps. && find /usr/share/powershell -print | grep -i '.*[.]nupkg$' | xargs rm # Our GitHub Actions entry point ADD entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh \ && fromdos /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] #eof
{ "content_hash": "2864740a48e094ce4e328820787dcceb", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 184, "avg_line_length": 49.88607594936709, "alnum_prop": 0.7160619132199949, "repo_name": "asimarslan/hazelcast-csharp-client", "id": "8b7e8b345ef805c0fdb5dd3956564929997e46d3", "size": "4553", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".github/actions/hz/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "7109601" }, { "name": "PowerShell", "bytes": "115235" }, { "name": "Shell", "bytes": "484" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!--L Copyright Oracle Inc Distributed under the OSI-approved BSD 3-Clause License. See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details. L--> <cgMDR:Non_Enumerated_Value_Domain xmlns:cgMDR="http://www.cancergrid.org/schema/cgMDR" item_registration_authority_identifier="GB-CANCERGRID" data_identifier="D1E544504" version="0.1"> <cgMDR:administered_item_administration_record> <cgMDR:administrative_note>Auto generated during protege import</cgMDR:administrative_note> <cgMDR:administrative_status>noPendingChanges</cgMDR:administrative_status> <cgMDR:change_description/> <cgMDR:creation_date>2006-08-08</cgMDR:creation_date> <cgMDR:effective_date>2006-08-08</cgMDR:effective_date> <cgMDR:explanatory_comment/> <cgMDR:last_change_date>2006-08-08</cgMDR:last_change_date> <cgMDR:until_date>2006-11-27</cgMDR:until_date> <cgMDR:origin/> <cgMDR:registration_status>Superseded</cgMDR:registration_status> <cgMDR:unresolved_issue/> </cgMDR:administered_item_administration_record> <cgMDR:administered_by>GB-CANCERGRID-000005-1</cgMDR:administered_by> <cgMDR:registered_by>GB-CANCERGRID-000009-1</cgMDR:registered_by> <cgMDR:submitted_by>GB-CANCERGRID-000006-1</cgMDR:submitted_by> <cgMDR:described_by>KNCSJG1HE</cgMDR:described_by> <cgMDR:classified_by>http://www.cancergrid.org/ontologies/data-element-classification#D1E14212</cgMDR:classified_by> <cgMDR:classified_by>http://www.cancergrid.org/ontologies/data-element-classification#D1E9011</cgMDR:classified_by> <cgMDR:having> <cgMDR:context_identifier>GB-CANCERGRID-000001-1</cgMDR:context_identifier> <cgMDR:containing> <cgMDR:language_section_language_identifier> <cgMDR:country_identifier>GB</cgMDR:country_identifier> <cgMDR:language_identifier>eng</cgMDR:language_identifier> </cgMDR:language_section_language_identifier> <cgMDR:name>Patient Body Surface Area (DuBois) value domain</cgMDR:name> <cgMDR:definition_text>BSA (m?) = 0.20247 x Height(m)0.725 x Weight(kg)0.425</cgMDR:definition_text> <cgMDR:preferred_designation>true</cgMDR:preferred_designation> <cgMDR:definition_source_reference/> </cgMDR:containing> </cgMDR:having> <cgMDR:typed_by>GB-CANCERGRID-000018-1</cgMDR:typed_by> <cgMDR:value_domain_datatype>SMWJLQ091</cgMDR:value_domain_datatype> <cgMDR:value_domain_unit_of_measure/> <cgMDR:related_to> <cgMDR:value_domain_relationship_type_description>useInstead</cgMDR:value_domain_relationship_type_description> <cgMDR:related_to>GB-CANCERGRID-D1E544504-0.12</cgMDR:related_to> </cgMDR:related_to> <cgMDR:representing>GB-CANCERGRID-D1E544503-0.12</cgMDR:representing> </cgMDR:Non_Enumerated_Value_Domain>
{ "content_hash": "6d018b214ad20e048b08f1386af39a90", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 185, "avg_line_length": 57.568627450980394, "alnum_prop": 0.717983651226158, "repo_name": "NCIP/cadsr-cgmdr-nci-uk", "id": "c5775aa6c15dddbb4a5008e26027e06624bf3023", "size": "2936", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cancergrid/datasets/cancergrid-dataset/data/value_domain/GB-CANCERGRID-D1E544504-0.1.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "291811" }, { "name": "CSS", "bytes": "46374" }, { "name": "Emacs Lisp", "bytes": "1302" }, { "name": "Java", "bytes": "12447025" }, { "name": "JavaScript", "bytes": "659235" }, { "name": "Perl", "bytes": "14339" }, { "name": "Python", "bytes": "8079" }, { "name": "Shell", "bytes": "47723" }, { "name": "XQuery", "bytes": "592174" }, { "name": "XSLT", "bytes": "441742" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.Null { public class NullEstateStore : IEstateDataStore { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private string m_connectionString; private Dictionary<uint, EstateSettings> m_knownEstates = new Dictionary<uint, EstateSettings>(); private EstateSettings m_estate = null; private EstateSettings GetEstate() { if (m_estate == null) { // This fools the initialization caller into thinking an estate was fetched (a check in OpenSimBase). // The estate info is pretty empty so don't try banning anyone. m_estate = new EstateSettings(); m_estate.EstateID = 1; m_estate.OnSave += StoreEstateSettings; } return m_estate; } protected virtual Assembly Assembly { get { return GetType().Assembly; } } public NullEstateStore() { } public NullEstateStore(string connectionString) { Initialise(connectionString); } public void Initialise(string connectionString) { // m_connectionString = connectionString; } private string[] FieldList { get { return new string[0]; } } public EstateSettings LoadEstateSettings(UUID regionID, bool create) { return GetEstate(); } public void StoreEstateSettings(EstateSettings es) { m_estate = es; return; } public EstateSettings LoadEstateSettings(int estateID) { return GetEstate(); } public EstateSettings CreateNewEstate() { return new EstateSettings(); } public List<EstateSettings> LoadEstateSettingsAll() { List<EstateSettings> allEstateSettings = new List<EstateSettings>(); allEstateSettings.Add(GetEstate()); return allEstateSettings; } public List<int> GetEstatesAll() { List<int> result = new List<int>(); result.Add((int)GetEstate().EstateID); return result; } public List<int> GetEstates(string search) { List<int> result = new List<int>(); return result; } public bool LinkRegion(UUID regionID, int estateID) { return false; } public List<UUID> GetRegions(int estateID) { List<UUID> result = new List<UUID>(); return result; } public bool DeleteEstate(int estateID) { return false; } #region IEstateDataStore Members public List<int> GetEstatesByOwner(UUID ownerID) { return new List<int>(); } #endregion } }
{ "content_hash": "96c793ee041bf045b6c25bc6943ad3e1", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 117, "avg_line_length": 25.62204724409449, "alnum_prop": 0.560540872771973, "repo_name": "bravelittlescientist/opensim-performance", "id": "1df397d94365b9a17539eeb5eaf7562ced4384fe", "size": "4871", "binary": false, "copies": "3", "ref": "refs/heads/interaction-evaluation-post-fixes", "path": "OpenSim/Data/Null/NullEstateData.cs", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "19143519" }, { "name": "CSS", "bytes": "1683" }, { "name": "JavaScript", "bytes": "556" }, { "name": "Perl", "bytes": "3578" }, { "name": "Python", "bytes": "5053" }, { "name": "Ruby", "bytes": "1111" }, { "name": "Shell", "bytes": "5412" } ], "symlink_target": "" }
<?xml version="1.0"?> <h:html xmlns:h="http://www.w3.org/1999/xhtml" xmlns:orx="http://openrosa.org/jr/xforms" xmlns="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:jr="http://openrosa.org/javarosa"> <h:head> <h:title>New Form</h:title> <model> <instance> <data xmlns:jrm="http://dev.commcarehq.org/jr/xforms" xmlns="http://openrosa.org/formdesigner/A22A5D53-037A-48DE-979B-BAA54734194E" uiVersion="1" version="5" name="New Form"> <question1/> <case xmlns="http://commcarehq.org/case/transaction/v2" case_id="" user_id="" date_modified=""> <create> <case_name/> <owner_id/> <case_type>person</case_type> </create> <update> <question1/> </update> </case> <orx:meta xmlns:cc="http://commcarehq.org/xforms"> <orx:deviceID/> <orx:timeStart/> <orx:timeEnd/> <orx:username/> <orx:userID/> <orx:instanceID/> <cc:appVersion/> <orx:drift/> </orx:meta> </data> </instance> <instance src="jr://instance/session" id="commcaresession"/> <instance src="jr://instance/selected-entities" id="selected_cases"/> <bind nodeset="/data/question1" type="xsd:string" required="true()"/> <itext> <translation lang="en" default=""> <text id="question1-label"> <value>question1</value> </text> </translation> </itext> <bind nodeset="/data/case/@date_modified" type="xsd:dateTime" calculate="/data/meta/timeEnd"/> <bind nodeset="/data/case/@user_id" calculate="/data/meta/userID"/> <setvalue ref="/data/case/@case_id" event="xforms-ready" value="instance('commcaresession')/session/data/case_id_new_person_0"/> <bind nodeset="/data/case/create/case_name" calculate="/data/question1"/> <bind nodeset="/data/case/create/owner_id" calculate="/data/meta/userID"/> <bind nodeset="/data/case/update/question1" relevant="count(/data/question1) &gt; 0" calculate="/data/question1"/> <setvalue ref="/data/meta/deviceID" event="xforms-ready" value="instance('commcaresession')/session/context/deviceid"/> <setvalue ref="/data/meta/timeStart" event="xforms-ready" value="now()"/> <bind nodeset="/data/meta/timeStart" type="xsd:dateTime"/> <setvalue ref="/data/meta/timeEnd" event="xforms-revalidate" value="now()"/> <bind nodeset="/data/meta/timeEnd" type="xsd:dateTime"/> <setvalue ref="/data/meta/username" event="xforms-ready" value="instance('commcaresession')/session/context/username"/> <setvalue ref="/data/meta/userID" event="xforms-ready" value="instance('commcaresession')/session/context/userid"/> <setvalue ref="/data/meta/instanceID" event="xforms-ready" value="uuid()"/> <setvalue ref="/data/meta/appVersion" event="xforms-ready" value="instance('commcaresession')/session/context/appversion"/> <setvalue event="xforms-revalidate" ref="/data/meta/drift" value="if(count(instance('commcaresession')/session/context/drift) = 1, instance('commcaresession')/session/context/drift, '')"/> </model> </h:head> <h:body> <input ref="/data/question1"> <label ref="jr:itext('question1-label')"/> </input> </h:body> </h:html>
{ "content_hash": "15b1cca85c284229d6375300c21caa36", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 212, "avg_line_length": 59.96923076923077, "alnum_prop": 0.5410466906105695, "repo_name": "dimagi/commcare-hq", "id": "61d7307e54f9cf6c8a935ff815dc73e964607d2f", "size": "3898", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/apps/app_manager/tests/data/form_preparation_v2/multi_open_update_case.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
npm install grunt --save-dev; npm install grunt-contrib-watch --save-dev; npm install grunt-contrib-uglify --save-dev; npm install grunt-contrib-jshint --save-dev; npm install grunt-contrib-qunit --save-dev; npm install qunitjs --save-dev; mkdir --parents js/test; mkdir --parents js/lib; mkdir --parents js/prod; cp node_modules/qunitjs/qunit/qunit.js js/test/qunit.js; cp node_modules/qunitjs/qunit/qunit.css js/test/qunit.css; cat <<EOF>js/test/test.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QUnit Example</title> <link rel="stylesheet" href="qunit.css"> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"></div> <script src="qunit.js"></script> <script src="tests.js"></script> </body> </html> EOF cat <<EOF>js/test/tests.js QUnit.test( "hello test", function() { ok( 1 == "1", "QUnit is working!" ); }); EOF npm init; cat <<EOF>Gruntfile.js module.exports = function(grunt){ grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today() %> */\n' }, build: { src: ['js/lib/*.js', 'js/*.js'], dest: 'js/prod/script.min.js' } }, jshint: { files: 'js/*.js', options: { // Define globals exposed by modern browsers. "browser": true, // Define globals exposed by jQuery. "jquery": true, // Define globals exposed by Node.js. "node": true, // Force all variable names to use either camelCase style or UPPER_CASE // with underscores. "camelcase": false, // Prohibit use of == and != in favor of === and !==. "eqeqeq": false, // Suppress warnings about == null comparisons. "eqnull": true, // Prohibit use of a variable before it is defined. "latedef": true, // Require capitalized names for constructor functions. "newcap": true, // Enforce use of single quotation marks for strings. "quotmark": "single", // Prohibit trailing whitespace. "trailing": true, // Prohibit use of explicitly undeclared variables. "undef": true, // Warn when variables are defined but never used. "unused": true, "force": true } }, qunit: { all: ['js/test/test.html'] }, watch: { files: ['js/lib/*.js', 'js/*.js', 'js/test/tests.js'], tasks: ['jshint','uglify:build', 'qunit'] } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.registerTask('default', ['watch']); }; EOF echo "You may now use grunt!"
{ "content_hash": "b94b98d3f1316c56490b3809f1fd772b", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 75, "avg_line_length": 26.41, "alnum_prop": 0.6338508140855736, "repo_name": "gavinblair/weather", "id": "706b2483371d043892c346f51018be010773e758", "size": "2641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.sh", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "75169" }, { "name": "Shell", "bytes": "2880" } ], "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="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.multivariate.factor_rotation.procrustes &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="../_static/material.css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="../_static/plot_directive.css" /> <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="../_static/doctools.js"></script> <script src="../_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script>window.MathJax = {"tex": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true}, "options": {"ignoreHtmlClass": "tex2jax_ignore|mathjax_ignore|document", "processHtmlClass": "tex2jax_process|mathjax_process|math|output_area"}}</script> <script defer="defer" src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.multivariate.factor_rotation.promax" href="statsmodels.multivariate.factor_rotation.promax.html" /> <link rel="prev" title="statsmodels.multivariate.factor_rotation.target_rotation" href="statsmodels.multivariate.factor_rotation.target_rotation.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.multivariate.factor_rotation.procrustes" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.13.4</span> <span class="md-header-nav__topic"> statsmodels.multivariate.factor_rotation.procrustes </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../../versions-v2.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../multivariate.html" class="md-tabs__link">Multivariate Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">multivariate</span></code></a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.13.4</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../duration.html" class="md-nav__link">Methods for Survival and Duration Analysis</a> </li> <li class="md-nav__item"> <a href="../nonparametric.html" class="md-nav__link">Nonparametric Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">nonparametric</span></code></a> </li> <li class="md-nav__item"> <a href="../gmm.html" class="md-nav__link">Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a> </li> <li class="md-nav__item"> <a href="../miscmodels.html" class="md-nav__link">Other Models <code class="xref py py-mod docutils literal notranslate"><span class="pre">miscmodels</span></code></a> </li> <li class="md-nav__item"> <a href="../multivariate.html" class="md-nav__link">Multivariate Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">multivariate</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#generated-statsmodels-multivariate-factor-rotation-procrustes--page-root" class="md-nav__link">statsmodels.multivariate.factor_rotation.procrustes</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#statsmodels.multivariate.factor_rotation.procrustes" class="md-nav__link"><code class="docutils literal notranslate"><span class="pre">procrustes</span></code></a> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.multivariate.factor_rotation.procrustes.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <section id="statsmodels-multivariate-factor-rotation-procrustes"> <h1 id="generated-statsmodels-multivariate-factor-rotation-procrustes--page-root">statsmodels.multivariate.factor_rotation.procrustes<a class="headerlink" href="#generated-statsmodels-multivariate-factor-rotation-procrustes--page-root" title="Permalink to this heading">¶</a></h1> <dl class="py function"> <dt class="sig sig-object py" id="statsmodels.multivariate.factor_rotation.procrustes"> <span class="sig-prename descclassname"><span class="pre">statsmodels.multivariate.factor_rotation.</span></span><span class="sig-name descname"><span class="pre">procrustes</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">A</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">H</span></span></em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/multivariate/factor_rotation/_analytic_rotation.html#procrustes"><span class="viewcode-link"><span class="pre">[source]</span></span></a><a class="headerlink" href="#statsmodels.multivariate.factor_rotation.procrustes" title="Permalink to this definition">¶</a></dt> <dd><p>Analytically solves the following Procrustes problem:</p> <div class="math notranslate nohighlight"> \[\phi(L) =\frac{1}{2}\|AT-H\|^2.\]</div> <p>(With no further conditions on <span class="math notranslate nohighlight">\(H\)</span>)</p> <p>Under the assumption that <span class="math notranslate nohighlight">\(A^*H\)</span> has full rank, the analytical solution <span class="math notranslate nohighlight">\(T\)</span> is given by:</p> <div class="math notranslate nohighlight"> \[T = (A^*HH^*A)^{-\frac{1}{2}}A^*H,\]</div> <p>see Navarra, Simoncini (2010).</p> <dl class="field-list"> <dt class="field-odd">Parameters<span class="colon">:</span></dt> <dd class="field-odd"><dl> <dt><strong>A</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/reference/index.html#module-numpy" title="(in NumPy v1.23)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy</span></code></a> <code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix</span></code></span></dt><dd><p>non rotated factors</p> </dd> <dt><strong>H</strong><span class="classifier"><a class="reference external" href="https://numpy.org/doc/stable/reference/index.html#module-numpy" title="(in NumPy v1.23)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy</span></code></a> <code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix</span></code></span></dt><dd><p>target matrix</p> </dd> <dt><strong>full_rank</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/stdtypes.html#bltin-boolean-values" title="(in Python v3.11)"><span class="xref std std-ref">bool</span></a> (<code class="xref py py-obj docutils literal notranslate"><span class="pre">default</span></code> <a class="reference external" href="https://docs.python.org/3/library/constants.html#False" title="(in Python v3.11)"><code class="docutils literal notranslate"><span class="pre">False</span></code></a>)</span></dt><dd><p>if set to true full rank is assumed</p> </dd> </dl> </dd> <dt class="field-even">Returns<span class="colon">:</span></dt> <dd class="field-even"><dl class="simple"> <dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">The</span></code> <code class="xref py py-obj docutils literal notranslate"><span class="pre">matrix</span></code> <span class="math notranslate nohighlight">\(T\)</span>.</dt><dd></dd> </dl> </dd> </dl> <p class="rubric">References</p> <p>[1] Navarra, Simoncini (2010) - A guide to empirical orthogonal functions for climate data analysis</p> </dd></dl> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.multivariate.factor_rotation.target_rotation.html" title="statsmodels.multivariate.factor_rotation.target_rotation" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.multivariate.factor_rotation.target_rotation </span> </div> </a> <a href="statsmodels.multivariate.factor_rotation.promax.html" title="statsmodels.multivariate.factor_rotation.promax" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.multivariate.factor_rotation.promax </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 01, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "9d432459e72fdd62e30d26ed5bcf3a86", "timestamp": "", "source": "github", "line_count": 500, "max_line_length": 999, "avg_line_length": 43.956, "alnum_prop": 0.6186186186186187, "repo_name": "statsmodels/statsmodels.github.io", "id": "95f42cd4bd468b35c7b1ef0147b241a33994f882", "size": "21982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.13.4/generated/statsmodels.multivariate.factor_rotation.procrustes.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.ait.toolkit.sencha.touch.client.core; import com.ait.toolkit.sencha.touch.client.ui.Button.IconAlign; public interface HasIcon { /** * A css class which sets a background image to be used as the icon for this * button (defaults to undefined). * * @param value */ public void setIconCls(Icons value); /** * Returns the value of icon. * * @return */ public String getIcon(); /** * Returns the value of iconAlign. * * @return */ public String getIconAlign(); /** * @return the icon CSS class for this Button */ public String getIconCls(); /** * @return the value of iconMask. */ public String getIconMaskCls(); /** * Sets the value of icon. * * @param value */ public void setIcon(String value); /** * Sets the value of iconAlign. * * @param value */ public void setIconAlign(String value); public void setIconAlign(IconAlign align); /** * Sets the value of iconMask. * * @param value */ public void setIconMask(boolean value); /** * Sets the value of iconMaskCls. * * @param value */ public void setIconMaskCls(String value); }
{ "content_hash": "2e07d31b40f08de25878d489c5b4fbca", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 80, "avg_line_length": 19.62857142857143, "alnum_prop": 0.5385735080058224, "repo_name": "ahome-it/ahome-touch", "id": "a3887eb39e097456321c43f127930be2c3b4e94a", "size": "1997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ahome-touch/src/main/java/com/ait/toolkit/sencha/touch/client/core/HasIcon.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1066675" } ], "symlink_target": "" }
/// /// \package astlib /// \file TypedValueDecoder.h /// /// \author Marian Krivos <[email protected]> /// \date 7Feb.,2017 /// /// (C) Copyright 2017 R-SYS s.r.o /// All rights reserved. /// #pragma once #include "ValueDecoder.h" namespace astlib { /** * Wrapper for easy value type handling. * Implements decode() method, converts value to apropriate type and call its typed callback. */ class ASTLIB_API TypedValueDecoder : public ValueDecoder { public: virtual void decode(const CodecContext& ctx, Poco::UInt64 value, int index); virtual void decodeBoolean(const CodecContext& ctx, bool value, int index) = 0; virtual void decodeSigned(const CodecContext& ctx, Poco::Int64 value, int index) = 0; virtual void decodeUnsigned(const CodecContext& ctx, Poco::UInt64 value, int index) = 0; virtual void decodeReal(const CodecContext& ctx, double value, int index) = 0; virtual void decodeString(const CodecContext& ctx, const std::string& value, int index) = 0; }; }
{ "content_hash": "9ad68803de3796388404b69e0f1bcb6b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 96, "avg_line_length": 25.175, "alnum_prop": 0.70506454816286, "repo_name": "mkrivos/astlib", "id": "7bb2ebd7eef91c49faa2fda1fe7684c4b2d39e06", "size": "1007", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "astlib/decoder/TypedValueDecoder.h", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "220990" }, { "name": "CMake", "bytes": "5600" }, { "name": "JavaScript", "bytes": "21583" }, { "name": "Shell", "bytes": "60" } ], "symlink_target": "" }
/* * * * (c) 2009-2021 Øystein Moseng * * Accessibility component for the range selector. * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import RangeSelector from '../../Extensions/RangeSelector.js'; import AccessibilityComponent from '../AccessibilityComponent.js'; import ChartUtilities from '../Utils/ChartUtilities.js'; var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getAxisRangeDescription = ChartUtilities.getAxisRangeDescription; import Announcer from '../Utils/Announcer.js'; import KeyboardNavigationHandler from '../KeyboardNavigationHandler.js'; import U from '../../Core/Utilities.js'; var addEvent = U.addEvent, attr = U.attr; /* * * * Functions * * */ /* eslint-disable valid-jsdoc */ /** * @private */ function shouldRunInputNavigation(chart) { return Boolean(chart.rangeSelector && chart.rangeSelector.inputGroup && chart.rangeSelector.inputGroup.element.style.visibility !== 'hidden' && chart.options.rangeSelector.inputEnabled !== false && chart.rangeSelector.minInput && chart.rangeSelector.maxInput); } /* * * * Class * * */ /** * The RangeSelectorComponent class * * @private * @class * @name Highcharts.RangeSelectorComponent */ var RangeSelectorComponent = /** @class */ (function (_super) { __extends(RangeSelectorComponent, _super); function RangeSelectorComponent() { /* * * * Properties * * */ var _this = _super !== null && _super.apply(this, arguments) || this; _this.announcer = void 0; return _this; } /* * * * Functions * * */ /* eslint-disable valid-jsdoc */ /** * Init the component * @private */ RangeSelectorComponent.prototype.init = function () { var chart = this.chart; this.announcer = new Announcer(chart, 'polite'); }; /** * Called on first render/updates to the chart, including options changes. */ RangeSelectorComponent.prototype.onChartUpdate = function () { var chart = this.chart, component = this, rangeSelector = chart.rangeSelector; if (!rangeSelector) { return; } this.updateSelectorVisibility(); this.setDropdownAttrs(); if (rangeSelector.buttons && rangeSelector.buttons.length) { rangeSelector.buttons.forEach(function (button) { component.setRangeButtonAttrs(button); }); } // Make sure input boxes are accessible and focusable if (rangeSelector.maxInput && rangeSelector.minInput) { ['minInput', 'maxInput'].forEach(function (key, i) { var input = rangeSelector[key]; if (input) { unhideChartElementFromAT(chart, input); component.setRangeInputAttrs(input, 'accessibility.rangeSelector.' + (i ? 'max' : 'min') + 'InputLabel'); } }); } }; /** * Hide buttons from AT when showing dropdown, and vice versa. * @private */ RangeSelectorComponent.prototype.updateSelectorVisibility = function () { var chart = this.chart; var rangeSelector = chart.rangeSelector; var dropdown = (rangeSelector && rangeSelector.dropdown); var buttons = (rangeSelector && rangeSelector.buttons || []); var hideFromAT = function (el) { return el.setAttribute('aria-hidden', true); }; if (rangeSelector && rangeSelector.hasVisibleDropdown && dropdown) { unhideChartElementFromAT(chart, dropdown); buttons.forEach(function (btn) { return hideFromAT(btn.element); }); } else { if (dropdown) { hideFromAT(dropdown); } buttons.forEach(function (btn) { return unhideChartElementFromAT(chart, btn.element); }); } }; /** * Set accessibility related attributes on dropdown element. * @private */ RangeSelectorComponent.prototype.setDropdownAttrs = function () { var chart = this.chart; var dropdown = (chart.rangeSelector && chart.rangeSelector.dropdown); if (dropdown) { var label = chart.langFormat('accessibility.rangeSelector.dropdownLabel', { rangeTitle: chart.options.lang.rangeSelectorZoom }); dropdown.setAttribute('aria-label', label); dropdown.setAttribute('tabindex', -1); } }; /** * @private * @param {Highcharts.SVGElement} button */ RangeSelectorComponent.prototype.setRangeButtonAttrs = function (button) { attr(button.element, { tabindex: -1, role: 'button' }); }; /** * @private */ RangeSelectorComponent.prototype.setRangeInputAttrs = function (input, langKey) { var chart = this.chart; attr(input, { tabindex: -1, 'aria-label': chart.langFormat(langKey, { chart: chart }) }); }; /** * @private * @param {Highcharts.KeyboardNavigationHandler} keyboardNavigationHandler * @param {number} keyCode * @return {number} Response code */ RangeSelectorComponent.prototype.onButtonNavKbdArrowKey = function (keyboardNavigationHandler, keyCode) { var response = keyboardNavigationHandler.response, keys = this.keyCodes, chart = this.chart, wrapAround = chart.options.accessibility .keyboardNavigation.wrapAround, direction = (keyCode === keys.left || keyCode === keys.up) ? -1 : 1, didHighlight = chart.highlightRangeSelectorButton(chart.highlightedRangeSelectorItemIx + direction); if (!didHighlight) { if (wrapAround) { keyboardNavigationHandler.init(direction); return response.success; } return response[direction > 0 ? 'next' : 'prev']; } return response.success; }; /** * @private */ RangeSelectorComponent.prototype.onButtonNavKbdClick = function (keyboardNavigationHandler) { var response = keyboardNavigationHandler.response, chart = this.chart, wasDisabled = chart.oldRangeSelectorItemState === 3; if (!wasDisabled) { this.fakeClickEvent(chart.rangeSelector.buttons[chart.highlightedRangeSelectorItemIx].element); } return response.success; }; /** * Called whenever a range selector button has been clicked, either by * mouse, touch, or kbd/voice/other. * @private */ RangeSelectorComponent.prototype.onAfterBtnClick = function () { var chart = this.chart; var axisRangeDescription = getAxisRangeDescription(chart.xAxis[0]); var announcement = chart.langFormat('accessibility.rangeSelector.clickButtonAnnouncement', { chart: chart, axisRangeDescription: axisRangeDescription }); if (announcement) { this.announcer.announce(announcement); } }; /** * @private */ RangeSelectorComponent.prototype.onInputKbdMove = function (direction) { var chart = this.chart; var rangeSel = chart.rangeSelector; var newIx = chart.highlightedInputRangeIx = (chart.highlightedInputRangeIx || 0) + direction; var newIxOutOfRange = newIx > 1 || newIx < 0; if (newIxOutOfRange) { if (chart.accessibility) { chart.accessibility.keyboardNavigation.tabindexContainer .focus(); chart.accessibility.keyboardNavigation.move(direction); } } else if (rangeSel) { var svgEl = rangeSel[newIx ? 'maxDateBox' : 'minDateBox']; var inputEl = rangeSel[newIx ? 'maxInput' : 'minInput']; if (svgEl && inputEl) { chart.setFocusToElement(svgEl, inputEl); } } }; /** * @private * @param {number} direction */ RangeSelectorComponent.prototype.onInputNavInit = function (direction) { var _this = this; var component = this; var chart = this.chart; var buttonIxToHighlight = direction > 0 ? 0 : 1; var rangeSel = chart.rangeSelector; var svgEl = (rangeSel && rangeSel[buttonIxToHighlight ? 'maxDateBox' : 'minDateBox']); var minInput = (rangeSel && rangeSel.minInput); var maxInput = (rangeSel && rangeSel.maxInput); var inputEl = buttonIxToHighlight ? maxInput : minInput; chart.highlightedInputRangeIx = buttonIxToHighlight; if (svgEl && minInput && maxInput) { chart.setFocusToElement(svgEl, inputEl); // Tab-press with the input focused does not propagate to chart // automatically, so we manually catch and handle it when relevant. if (this.removeInputKeydownHandler) { this.removeInputKeydownHandler(); } var keydownHandler = function (e) { var isTab = (e.which || e.keyCode) === _this.keyCodes.tab; if (isTab) { e.preventDefault(); e.stopPropagation(); component.onInputKbdMove(e.shiftKey ? -1 : 1); } }; var minRemover_1 = addEvent(minInput, 'keydown', keydownHandler); var maxRemover_1 = addEvent(maxInput, 'keydown', keydownHandler); this.removeInputKeydownHandler = function () { minRemover_1(); maxRemover_1(); }; } }; /** * @private */ RangeSelectorComponent.prototype.onInputNavTerminate = function () { var rangeSel = (this.chart.rangeSelector || {}); if (rangeSel.maxInput) { rangeSel.hideInput('max'); } if (rangeSel.minInput) { rangeSel.hideInput('min'); } if (this.removeInputKeydownHandler) { this.removeInputKeydownHandler(); delete this.removeInputKeydownHandler; } }; /** * @private */ RangeSelectorComponent.prototype.initDropdownNav = function () { var _this = this; var chart = this.chart; var rangeSelector = chart.rangeSelector; var dropdown = (rangeSelector && rangeSelector.dropdown); if (rangeSelector && dropdown) { chart.setFocusToElement(rangeSelector.buttonGroup, dropdown); if (this.removeDropdownKeydownHandler) { this.removeDropdownKeydownHandler(); } // Tab-press with dropdown focused does not propagate to chart // automatically, so we manually catch and handle it when relevant. this.removeDropdownKeydownHandler = addEvent(dropdown, 'keydown', function (e) { var isTab = (e.which || e.keyCode) === _this.keyCodes.tab, a11y = chart.accessibility; if (isTab) { e.preventDefault(); e.stopPropagation(); if (a11y) { a11y.keyboardNavigation.tabindexContainer.focus(); a11y.keyboardNavigation.move(e.shiftKey ? -1 : 1); } } }); } }; /** * Get navigation for the range selector buttons. * @private * @return {Highcharts.KeyboardNavigationHandler} The module object. */ RangeSelectorComponent.prototype.getRangeSelectorButtonNavigation = function () { var chart = this.chart; var keys = this.keyCodes; var component = this; return new KeyboardNavigationHandler(chart, { keyCodeMap: [ [ [keys.left, keys.right, keys.up, keys.down], function (keyCode) { return component.onButtonNavKbdArrowKey(this, keyCode); } ], [ [keys.enter, keys.space], function () { return component.onButtonNavKbdClick(this); } ] ], validate: function () { return !!(chart.rangeSelector && chart.rangeSelector.buttons && chart.rangeSelector.buttons.length); }, init: function (direction) { var rangeSelector = chart.rangeSelector; if (rangeSelector && rangeSelector.hasVisibleDropdown) { component.initDropdownNav(); } else if (rangeSelector) { var lastButtonIx = rangeSelector.buttons.length - 1; chart.highlightRangeSelectorButton(direction > 0 ? 0 : lastButtonIx); } }, terminate: function () { if (component.removeDropdownKeydownHandler) { component.removeDropdownKeydownHandler(); delete component.removeDropdownKeydownHandler; } } }); }; /** * Get navigation for the range selector input boxes. * @private * @return {Highcharts.KeyboardNavigationHandler} * The module object. */ RangeSelectorComponent.prototype.getRangeSelectorInputNavigation = function () { var chart = this.chart; var component = this; return new KeyboardNavigationHandler(chart, { keyCodeMap: [], validate: function () { return shouldRunInputNavigation(chart); }, init: function (direction) { component.onInputNavInit(direction); }, terminate: function () { component.onInputNavTerminate(); } }); }; /** * Get keyboard navigation handlers for this component. * @return {Array<Highcharts.KeyboardNavigationHandler>} * List of module objects. */ RangeSelectorComponent.prototype.getKeyboardNavigation = function () { return [ this.getRangeSelectorButtonNavigation(), this.getRangeSelectorInputNavigation() ]; }; /** * Remove component traces */ RangeSelectorComponent.prototype.destroy = function () { if (this.removeDropdownKeydownHandler) { this.removeDropdownKeydownHandler(); } if (this.removeInputKeydownHandler) { this.removeInputKeydownHandler(); } if (this.announcer) { this.announcer.destroy(); } }; return RangeSelectorComponent; }(AccessibilityComponent)); /* * * * Class Namespace * * */ (function (RangeSelectorComponent) { /* * * * Declarations * * */ /* * * * Constants * * */ var composedClasses = []; /* * * * Functions * * */ /* eslint-disable valid-jsdoc */ /** * Highlight range selector button by index. * * @private * @function Highcharts.Chart#highlightRangeSelectorButton */ function chartHighlightRangeSelectorButton(ix) { var buttons = (this.rangeSelector && this.rangeSelector.buttons || []); var curHighlightedIx = this.highlightedRangeSelectorItemIx; var curSelectedIx = (this.rangeSelector && this.rangeSelector.selected); // Deselect old if (typeof curHighlightedIx !== 'undefined' && buttons[curHighlightedIx] && curHighlightedIx !== curSelectedIx) { buttons[curHighlightedIx].setState(this.oldRangeSelectorItemState || 0); } // Select new this.highlightedRangeSelectorItemIx = ix; if (buttons[ix]) { this.setFocusToElement(buttons[ix].box, buttons[ix].element); if (ix !== curSelectedIx) { this.oldRangeSelectorItemState = buttons[ix].state; buttons[ix].setState(1); } return true; } return false; } /** * @private */ function compose(ChartClass, RangeSelectorClass) { if (composedClasses.indexOf(ChartClass) === -1) { composedClasses.push(ChartClass); var chartProto = ChartClass.prototype; chartProto.highlightRangeSelectorButton = (chartHighlightRangeSelectorButton); } if (composedClasses.indexOf(RangeSelectorClass) === -1) { composedClasses.push(RangeSelectorClass); addEvent(RangeSelector, 'afterBtnClick', rangeSelectorAfterBtnClick); } } RangeSelectorComponent.compose = compose; /** * Range selector does not have destroy-setup for class instance events - so * we set it on the class and call the component from here. * @private */ function rangeSelectorAfterBtnClick() { var a11y = this.chart.accessibility; if (a11y && a11y.components.rangeSelector) { return a11y.components.rangeSelector.onAfterBtnClick(); } } })(RangeSelectorComponent || (RangeSelectorComponent = {})); /* * * * Export Default * * */ export default RangeSelectorComponent;
{ "content_hash": "e0cdef46bb5e446bf7656a46f3c04dec", "timestamp": "", "source": "github", "line_count": 506, "max_line_length": 213, "avg_line_length": 35.8102766798419, "alnum_prop": 0.5766556291390729, "repo_name": "cdnjs/cdnjs", "id": "1e8a51d90be5b502d95d00f0210599ad9708abd8", "size": "18121", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ajax/libs/highcharts/10.1.0/es-modules/Accessibility/Components/RangeSelectorComponent.js", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
/*! * numbro.js language configuration * language : Slovak * locale : Slovakia * author : Ahmed Al Hafoudh : http://www.freevision.sk */ (function () { 'use strict'; var language = { langLocaleCode: 'sk-SK', delimiters: { thousands: ' ', decimal: ',' }, abbreviations: { thousand: 'tis.', million: 'mil.', billion: 'b', trillion: 't' }, ordinal: function () { return '.'; }, currency: { symbol: '€', position: 'postfix', spaceSeparated: true }, defaults: { currencyFormat: ',0000 a' }, formats: { fourDigits: '0000 a', fullWithTwoDecimals: ',0.00 $', fullWithTwoDecimalsNoCurrency: ',0.00', fullWithNoDecimals: ',0 $' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && window.numbro && window.numbro.language) { window.numbro.language(language.langLocaleCode, language); } }.call(typeof window === 'undefined' ? this : window));
{ "content_hash": "74d5e00fad6f3aa18356c0a1ae5725b2", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 83, "avg_line_length": 25.836734693877553, "alnum_prop": 0.4873617693522907, "repo_name": "matthieuprat/numbro", "id": "4e42bfc94b52215d49c57fb165cf78b822b759ca", "size": "1268", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "languages/sk-SK.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "283941" } ], "symlink_target": "" }
#import "GPUImageFilter.h" /** Transforms the colors of an image by applying a matrix to them */ @interface GPUImageColorMatrixFilter : GPUImageFilter { GLint colorMatrixUniform; GLint intensityUniform; } /** A 4x4 matrix used to transform each color in an image */ @property(readwrite, nonatomic) GPUMatrix4x4 colorMatrix; /** The degree to which the new transformed color replaces the original color for each pixel */ @property(readwrite, nonatomic) GLfloat intensity; @end
{ "content_hash": "ce3627243c7595c4347d31d5c428da76", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 92, "avg_line_length": 25.842105263157894, "alnum_prop": 0.7637474541751528, "repo_name": "roundme/Roundme-GPUImage", "id": "cd9dc77b25218bea5699facf9efd23b48a3dd7f4", "size": "491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "framework/Source/GPUImageColorMatrixFilter.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "1090470" }, { "name": "Ruby", "bytes": "1384" }, { "name": "Shell", "bytes": "1159" } ], "symlink_target": "" }
namespace g{namespace Android{namespace android{namespace graphics{namespace drawable{struct LayerDrawable;}}}}} namespace g{namespace Android{namespace android{namespace graphics{namespace drawable{struct ShapeDrawable;}}}}} namespace g{namespace Android{namespace android{namespace view{struct View;}}}} namespace g{namespace Fuse{namespace Android{namespace Controls{struct Shape;}}}} namespace g{namespace Fuse{namespace Drawing{struct Brush;}}} namespace g{namespace Fuse{namespace Drawing{struct Stroke;}}} namespace g{ namespace Fuse{ namespace Android{ namespace Controls{ // public abstract extern class Shape<T> :1423 // { struct Shape_type : ::g::Fuse::Android::Controls::Control_type { void(*fp_UpdateShapeDrawable)(::g::Fuse::Android::Controls::Shape*, ::g::Android::android::graphics::drawable::ShapeDrawable*); }; Shape_type* Shape_typeof(); void Shape__ctor_3_fn(Shape* __this); void Shape__Attach_fn(Shape* __this); void Shape__CreateInternal_fn(Shape* __this, ::g::Android::android::view::View** __retval); void Shape__Detach_fn(Shape* __this); void Shape__GetLayer_fn(Shape* __this, int* index, ::g::Android::android::graphics::drawable::ShapeDrawable** __retval); void Shape__OnShapeChanged_fn(Shape* __this); void Shape__SetBrush_fn(Shape* __this, ::g::Android::android::graphics::drawable::ShapeDrawable* drawable, ::g::Fuse::Drawing::Brush* brush); void Shape__SetStroke_fn(Shape* __this, ::g::Android::android::graphics::drawable::ShapeDrawable* drawable, ::g::Fuse::Drawing::Stroke* stroke); struct Shape : ::g::Fuse::Android::Controls::Control { uStrong< ::g::Android::android::graphics::drawable::LayerDrawable*> _drawable; uStrong< ::g::Android::android::view::View*> _shapeView; void ctor_3(); ::g::Android::android::graphics::drawable::ShapeDrawable* GetLayer(int index); void OnShapeChanged(); void SetBrush(::g::Android::android::graphics::drawable::ShapeDrawable* drawable, ::g::Fuse::Drawing::Brush* brush); void SetStroke(::g::Android::android::graphics::drawable::ShapeDrawable* drawable, ::g::Fuse::Drawing::Stroke* stroke); void UpdateShapeDrawable(::g::Android::android::graphics::drawable::ShapeDrawable* shape) { (((Shape_type*)__type)->fp_UpdateShapeDrawable)(this, shape); } }; // } }}}} // ::g::Fuse::Android::Controls
{ "content_hash": "997fbbfdd95525c9270e01f776872bc5", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 159, "avg_line_length": 52.38636363636363, "alnum_prop": 0.7262472885032538, "repo_name": "blyk/BlackCode-Fuse", "id": "62e994afbc8fdb36d53ef4f8770bf58de26ea519", "size": "2604", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "AndroidUX/.build/Simulator/Android/include/Fuse.Android.Controls.Shape-1.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "31111" }, { "name": "C", "bytes": "22885804" }, { "name": "C++", "bytes": "197750292" }, { "name": "Java", "bytes": "951083" }, { "name": "JavaScript", "bytes": "578555" }, { "name": "Logos", "bytes": "48297" }, { "name": "Makefile", "bytes": "6592573" }, { "name": "Shell", "bytes": "19985" } ], "symlink_target": "" }
import abc import copy import datetime import mock from oslo_config import fixture as fixture_config from oslotest import mockpatch import six from stevedore import extension from ceilometer.agent import plugin_base from ceilometer import pipeline from ceilometer import publisher from ceilometer.publisher import test as test_publisher from ceilometer import sample from ceilometer.tests import base from ceilometer import utils class TestSample(sample.Sample): def __init__(self, name, type, unit, volume, user_id, project_id, resource_id, timestamp, resource_metadata, source=None): super(TestSample, self).__init__(name, type, unit, volume, user_id, project_id, resource_id, timestamp, resource_metadata, source) def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other): return not self.__eq__(other) default_test_data = TestSample( name='test', type=sample.TYPE_CUMULATIVE, unit='', volume=1, user_id='test', project_id='test', resource_id='test_run_tasks', timestamp=datetime.datetime.utcnow().isoformat(), resource_metadata={'name': 'Pollster'}, ) class TestPollster(plugin_base.PollsterBase): test_data = default_test_data discovery = None @property def default_discovery(self): return self.discovery def get_samples(self, manager, cache, resources): resources = resources or [] self.samples.append((manager, resources)) self.resources.extend(resources) c = copy.deepcopy(self.test_data) c.resource_metadata['resources'] = resources return [c] class TestPollsterException(TestPollster): def get_samples(self, manager, cache, resources): resources = resources or [] self.samples.append((manager, resources)) self.resources.extend(resources) raise Exception() class TestDiscovery(plugin_base.DiscoveryBase): def discover(self, manager, param=None): self.params.append(param) return self.resources class TestDiscoveryException(plugin_base.DiscoveryBase): def discover(self, manager, param=None): self.params.append(param) raise Exception() @six.add_metaclass(abc.ABCMeta) class BaseAgentManagerTestCase(base.BaseTestCase): class Pollster(TestPollster): samples = [] resources = [] test_data = default_test_data class PollsterAnother(TestPollster): samples = [] resources = [] test_data = TestSample( name='testanother', type=default_test_data.type, unit=default_test_data.unit, volume=default_test_data.volume, user_id=default_test_data.user_id, project_id=default_test_data.project_id, resource_id=default_test_data.resource_id, timestamp=default_test_data.timestamp, resource_metadata=default_test_data.resource_metadata) class PollsterException(TestPollsterException): samples = [] resources = [] test_data = TestSample( name='testexception', type=default_test_data.type, unit=default_test_data.unit, volume=default_test_data.volume, user_id=default_test_data.user_id, project_id=default_test_data.project_id, resource_id=default_test_data.resource_id, timestamp=default_test_data.timestamp, resource_metadata=default_test_data.resource_metadata) class PollsterExceptionAnother(TestPollsterException): samples = [] resources = [] test_data = TestSample( name='testexceptionanother', type=default_test_data.type, unit=default_test_data.unit, volume=default_test_data.volume, user_id=default_test_data.user_id, project_id=default_test_data.project_id, resource_id=default_test_data.resource_id, timestamp=default_test_data.timestamp, resource_metadata=default_test_data.resource_metadata) class Discovery(TestDiscovery): params = [] resources = [] class DiscoveryAnother(TestDiscovery): params = [] resources = [] @property def group_id(self): return 'another_group' class DiscoveryException(TestDiscoveryException): params = [] def setup_polling(self): self.mgr.polling_manager = pipeline.PollingManager(self.pipeline_cfg) def create_extension_list(self): return [extension.Extension('test', None, None, self.Pollster(), ), extension.Extension('testanother', None, None, self.PollsterAnother(), ), extension.Extension('testexception', None, None, self.PollsterException(), ), extension.Extension('testexceptionanother', None, None, self.PollsterExceptionAnother(), )] def create_discovery_manager(self): return extension.ExtensionManager.make_test_instance( [ extension.Extension( 'testdiscovery', None, None, self.Discovery(), ), extension.Extension( 'testdiscoveryanother', None, None, self.DiscoveryAnother(), ), extension.Extension( 'testdiscoveryexception', None, None, self.DiscoveryException(), ), ], ) @abc.abstractmethod def create_manager(self): """Return subclass specific manager.""" @mock.patch('ceilometer.pipeline.setup_polling', mock.MagicMock()) def setUp(self): super(BaseAgentManagerTestCase, self).setUp() self.mgr = self.create_manager() self.mgr.extensions = self.create_extension_list() self.mgr.partition_coordinator = mock.MagicMock() fake_subset = lambda _, x: x p_coord = self.mgr.partition_coordinator p_coord.extract_my_subset.side_effect = fake_subset self.mgr.tg = mock.MagicMock() self.pipeline_cfg = { 'sources': [{ 'name': 'test_pipeline', 'interval': 60, 'meters': ['test'], 'resources': ['test://'] if self.source_resources else [], 'sinks': ['test_sink']}], 'sinks': [{ 'name': 'test_sink', 'transformers': [], 'publishers': ["test"]}] } self.setup_polling() self.CONF = self.useFixture(fixture_config.Config()).conf self.CONF.set_override( 'pipeline_cfg_file', self.path_get('etc/ceilometer/pipeline.yaml') ) self.useFixture(mockpatch.PatchObject( publisher, 'get_publisher', side_effect=self.get_publisher)) @staticmethod def get_publisher(url, namespace=''): fake_drivers = {'test://': test_publisher.TestPublisher, 'new://': test_publisher.TestPublisher, 'rpc://': test_publisher.TestPublisher} return fake_drivers[url](url) def tearDown(self): self.Pollster.samples = [] self.Pollster.discovery = [] self.PollsterAnother.samples = [] self.PollsterAnother.discovery = [] self.PollsterException.samples = [] self.PollsterException.discovery = [] self.PollsterExceptionAnother.samples = [] self.PollsterExceptionAnother.discovery = [] self.Pollster.resources = [] self.PollsterAnother.resources = [] self.PollsterException.resources = [] self.PollsterExceptionAnother.resources = [] self.Discovery.params = [] self.DiscoveryAnother.params = [] self.DiscoveryException.params = [] self.Discovery.resources = [] self.DiscoveryAnother.resources = [] super(BaseAgentManagerTestCase, self).tearDown() @mock.patch('ceilometer.pipeline.setup_polling') def test_start(self, setup_polling): self.mgr.join_partitioning_groups = mock.MagicMock() self.mgr.setup_polling_tasks = mock.MagicMock() self.CONF.set_override('heartbeat', 1.0, group='coordination') self.mgr.start() setup_polling.assert_called_once_with() self.mgr.partition_coordinator.start.assert_called_once_with() self.mgr.join_partitioning_groups.assert_called_once_with() self.mgr.setup_polling_tasks.assert_called_once_with() timer_call = mock.call(1.0, self.mgr.partition_coordinator.heartbeat) self.assertEqual([timer_call], self.mgr.tg.add_timer.call_args_list) self.mgr.stop() self.mgr.partition_coordinator.stop.assert_called_once_with() @mock.patch('ceilometer.pipeline.setup_polling') def test_start_with_pipeline_poller(self, setup_polling): self.mgr.join_partitioning_groups = mock.MagicMock() self.mgr.setup_polling_tasks = mock.MagicMock() self.CONF.set_override('heartbeat', 1.0, group='coordination') self.CONF.set_override('refresh_pipeline_cfg', True) self.CONF.set_override('pipeline_polling_interval', 5) self.mgr.start() setup_polling.assert_called_once_with() self.mgr.partition_coordinator.start.assert_called_once_with() self.mgr.join_partitioning_groups.assert_called_once_with() self.mgr.setup_polling_tasks.assert_called_once_with() timer_call = mock.call(1.0, self.mgr.partition_coordinator.heartbeat) pipeline_poller_call = mock.call(5, self.mgr.refresh_pipeline) self.assertEqual([timer_call, pipeline_poller_call], self.mgr.tg.add_timer.call_args_list) def test_join_partitioning_groups(self): self.mgr.discovery_manager = self.create_discovery_manager() self.mgr.join_partitioning_groups() p_coord = self.mgr.partition_coordinator static_group_ids = [utils.hash_of_set(p['resources']) for p in self.pipeline_cfg['sources'] if p['resources']] expected = [mock.call(self.mgr.construct_group_id(g)) for g in ['another_group', 'global'] + static_group_ids] self.assertEqual(len(expected), len(p_coord.join_group.call_args_list)) for c in expected: self.assertIn(c, p_coord.join_group.call_args_list) def test_setup_polling_tasks(self): polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(1, len(polling_tasks)) self.assertTrue('test_pipeline' in polling_tasks.keys()) per_task_resources = polling_tasks['test_pipeline']['task'].resources self.assertEqual(1, len(per_task_resources)) self.assertEqual(set(self.pipeline_cfg['sources'][0]['resources']), set(per_task_resources['test_pipeline-test'].get({}))) def test_setup_polling_tasks_multiple_interval(self): self.pipeline_cfg['sources'].append({ 'name': 'test_pipeline_1', 'interval': 10, 'meters': ['test'], 'resources': ['test://'] if self.source_resources else [], 'sinks': ['test_sink'] }) self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(2, len(polling_tasks)) self.assertTrue('test_pipeline' in polling_tasks.keys()) self.assertTrue('test_pipeline_1' in polling_tasks.keys()) def test_setup_polling_tasks_mismatch_counter(self): self.pipeline_cfg['sources'].append({ 'name': 'test_pipeline_1', 'interval': 10, 'meters': ['test_invalid'], 'resources': ['invalid://'], 'sinks': ['test_sink'] }) polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(1, len(polling_tasks)) self.assertTrue('test_pipeline' in polling_tasks.keys()) self.assertFalse('test_pipeline_1' in polling_tasks.keys()) def test_agent_manager_start(self): mgr = self.create_manager() mgr.extensions = self.mgr.extensions mgr.create_polling_task = mock.MagicMock() mgr.tg = mock.MagicMock() mgr.start() self.assertTrue(mgr.tg.add_timer.called) def test_manager_exception_persistency(self): self.pipeline_cfg['sources'].append({ 'name': 'test_pipeline_1', 'interval': 60, 'meters': ['testanother'], 'sinks': ['test_sink'] }) self.setup_polling() def _verify_discovery_params(self, expected): self.assertEqual(expected, self.Discovery.params) self.assertEqual(expected, self.DiscoveryAnother.params) self.assertEqual(expected, self.DiscoveryException.params) def _do_test_per_pollster_discovery(self, discovered_resources, static_resources): self.Pollster.discovery = 'testdiscovery' self.mgr.discovery_manager = self.create_discovery_manager() self.Discovery.resources = discovered_resources self.DiscoveryAnother.resources = [d[::-1] for d in discovered_resources] if static_resources: # just so we can test that static + pre_pipeline amalgamated # override per_pollster self.pipeline_cfg['sources'][0]['discovery'] = [ 'testdiscoveryanother', 'testdiscoverynonexistent', 'testdiscoveryexception'] self.pipeline_cfg['sources'][0]['resources'] = static_resources self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.mgr.interval_task(polling_tasks['test_pipeline']['task']) if static_resources: self.assertEqual(set(static_resources + self.DiscoveryAnother.resources), set(self.Pollster.resources)) else: self.assertEqual(set(self.Discovery.resources), set(self.Pollster.resources)) # Make sure no duplicated resource from discovery for x in self.Pollster.resources: self.assertEqual(1, self.Pollster.resources.count(x)) def test_per_pollster_discovery(self): self._do_test_per_pollster_discovery(['discovered_1', 'discovered_2'], []) def test_per_pollster_discovery_overridden_by_per_pipeline_discovery(self): # ensure static+per_source_discovery overrides per_pollster_discovery self._do_test_per_pollster_discovery(['discovered_1', 'discovered_2'], ['static_1', 'static_2']) def test_per_pollster_discovery_duplicated(self): self._do_test_per_pollster_discovery(['dup', 'discovered_1', 'dup'], []) def test_per_pollster_discovery_overridden_by_duplicated_static(self): self._do_test_per_pollster_discovery(['discovered_1', 'discovered_2'], ['static_1', 'dup', 'dup']) def test_per_pollster_discovery_caching(self): # ensure single discovery associated with multiple pollsters # only called once per polling cycle discovered_resources = ['discovered_1', 'discovered_2'] self.Pollster.discovery = 'testdiscovery' self.PollsterAnother.discovery = 'testdiscovery' self.mgr.discovery_manager = self.create_discovery_manager() self.Discovery.resources = discovered_resources self.pipeline_cfg['sources'][0]['meters'].append('testanother') self.pipeline_cfg['sources'][0]['resources'] = [] self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.mgr.interval_task(polling_tasks['test_pipeline']['task']) self.assertEqual(1, len(self.Discovery.params)) self.assertEqual(discovered_resources, self.Pollster.resources) self.assertEqual(discovered_resources, self.PollsterAnother.resources) def _do_test_per_pipeline_discovery(self, discovered_resources, static_resources): self.mgr.discovery_manager = self.create_discovery_manager() self.Discovery.resources = discovered_resources self.DiscoveryAnother.resources = [d[::-1] for d in discovered_resources] self.pipeline_cfg['sources'][0]['discovery'] = [ 'testdiscovery', 'testdiscoveryanother', 'testdiscoverynonexistent', 'testdiscoveryexception'] self.pipeline_cfg['sources'][0]['resources'] = static_resources self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.mgr.interval_task(polling_tasks['test_pipeline']['task']) discovery = self.Discovery.resources + self.DiscoveryAnother.resources # compare resource lists modulo ordering self.assertEqual(set(static_resources + discovery), set(self.Pollster.resources)) # Make sure no duplicated resource from discovery for x in self.Pollster.resources: self.assertEqual(1, self.Pollster.resources.count(x)) def test_per_pipeline_discovery_discovered_only(self): self._do_test_per_pipeline_discovery(['discovered_1', 'discovered_2'], []) def test_per_pipeline_discovery_static_only(self): self._do_test_per_pipeline_discovery([], ['static_1', 'static_2']) def test_per_pipeline_discovery_discovered_augmented_by_static(self): self._do_test_per_pipeline_discovery(['discovered_1', 'discovered_2'], ['static_1', 'static_2']) def test_per_pipeline_discovery_discovered_duplicated_static(self): self._do_test_per_pipeline_discovery(['discovered_1', 'pud'], ['dup', 'static_1', 'dup']) def test_multiple_pipelines_different_static_resources(self): # assert that the individual lists of static and discovered resources # for each pipeline with a common interval are passed to individual # pollsters matching each pipeline self.pipeline_cfg['sources'][0]['resources'] = ['test://'] self.pipeline_cfg['sources'][0]['discovery'] = ['testdiscovery'] self.pipeline_cfg['sources'].append({ 'name': 'another_pipeline', 'interval': 60, 'meters': ['test'], 'resources': ['another://'], 'discovery': ['testdiscoveryanother'], 'sinks': ['test_sink_new'] }) self.mgr.discovery_manager = self.create_discovery_manager() self.Discovery.resources = ['discovered_1', 'discovered_2'] self.DiscoveryAnother.resources = ['discovered_3', 'discovered_4'] self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(2, len(polling_tasks)) self.assertTrue('another_pipeline' in polling_tasks.keys()) self.assertTrue('test_pipeline' in polling_tasks.keys()) self.mgr.interval_task(polling_tasks['another_pipeline']['task']) self.mgr.interval_task(polling_tasks['test_pipeline']['task']) self.assertEqual([None], self.Discovery.params) self.assertEqual([None], self.DiscoveryAnother.params) self.assertEqual(2, len(self.Pollster.samples)) samples = self.Pollster.samples test_resources = ['test://', 'discovered_1', 'discovered_2'] another_resources = ['another://', 'discovered_3', 'discovered_4'] if samples[0][1] == test_resources: self.assertEqual(another_resources, samples[1][1]) elif samples[0][1] == another_resources: self.assertEqual(test_resources, samples[1][1]) else: self.fail('unexpected sample resources %s' % samples) def test_multiple_sources_different_discoverers(self): self.Discovery.resources = ['discovered_1', 'discovered_2'] self.DiscoveryAnother.resources = ['discovered_3', 'discovered_4'] sources = [{'name': 'test_source_1', 'interval': 60, 'meters': ['test'], 'discovery': ['testdiscovery'], 'sinks': ['test_sink_1']}, {'name': 'test_source_2', 'interval': 60, 'meters': ['testanother'], 'discovery': ['testdiscoveryanother'], 'sinks': ['test_sink_2']}] sinks = [{'name': 'test_sink_1', 'transformers': [], 'publishers': ['test://']}, {'name': 'test_sink_2', 'transformers': [], 'publishers': ['test://']}] self.pipeline_cfg = {'sources': sources, 'sinks': sinks} self.mgr.discovery_manager = self.create_discovery_manager() self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(2, len(polling_tasks)) self.assertTrue('test_source_1' in polling_tasks.keys()) self.assertTrue('test_source_2' in polling_tasks.keys()) self.mgr.interval_task(polling_tasks['test_source_1']['task']) self.mgr.interval_task(polling_tasks['test_source_2']['task']) self.assertEqual(1, len(self.Pollster.samples)) self.assertEqual(['discovered_1', 'discovered_2'], self.Pollster.resources) self.assertEqual(1, len(self.PollsterAnother.samples)) self.assertEqual(['discovered_3', 'discovered_4'], self.PollsterAnother.resources) def test_multiple_sinks_same_discoverer(self): self.Discovery.resources = ['discovered_1', 'discovered_2'] sources = [{'name': 'test_source_1', 'interval': 60, 'meters': ['test'], 'discovery': ['testdiscovery'], 'sinks': ['test_sink_1', 'test_sink_2']}] sinks = [{'name': 'test_sink_1', 'transformers': [], 'publishers': ['test://']}, {'name': 'test_sink_2', 'transformers': [], 'publishers': ['test://']}] self.pipeline_cfg = {'sources': sources, 'sinks': sinks} self.mgr.discovery_manager = self.create_discovery_manager() self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.assertEqual(1, len(polling_tasks)) self.assertTrue('test_source_1' in polling_tasks.keys()) self.mgr.interval_task(polling_tasks['test_source_1']['task']) self.assertEqual(1, len(self.Pollster.samples)) self.assertEqual(['discovered_1', 'discovered_2'], self.Pollster.resources) def test_discovery_partitioning(self): self.mgr.discovery_manager = self.create_discovery_manager() p_coord = self.mgr.partition_coordinator self.pipeline_cfg['sources'][0]['discovery'] = [ 'testdiscovery', 'testdiscoveryanother', 'testdiscoverynonexistent', 'testdiscoveryexception'] self.pipeline_cfg['sources'][0]['resources'] = [] self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() self.mgr.interval_task(polling_tasks['test_pipeline']['task']) expected = [mock.call(self.mgr.construct_group_id(d.obj.group_id), d.obj.resources) for d in self.mgr.discovery_manager if hasattr(d.obj, 'resources')] self.assertEqual(len(expected), len(p_coord.extract_my_subset.call_args_list)) for c in expected: self.assertIn(c, p_coord.extract_my_subset.call_args_list) def test_static_resources_partitioning(self): p_coord = self.mgr.partition_coordinator static_resources = ['static_1', 'static_2'] static_resources2 = ['static_3', 'static_4'] self.pipeline_cfg['sources'][0]['resources'] = static_resources self.pipeline_cfg['sources'].append({ 'name': 'test_pipeline2', 'interval': 60, 'meters': ['test', 'test2'], 'resources': static_resources2, 'sinks': ['test_sink'] }) # have one pipeline without static resources defined self.pipeline_cfg['sources'].append({ 'name': 'test_pipeline3', 'interval': 60, 'meters': ['test', 'test2'], 'resources': [], 'sinks': ['test_sink'] }) self.setup_polling() polling_tasks = self.mgr.setup_polling_tasks() for meter_name in polling_tasks: self.mgr.interval_task(polling_tasks[meter_name]['task']) # Only two groups need to be created, one for each pipeline, # even though counter test is used twice expected = [mock.call(self.mgr.construct_group_id( utils.hash_of_set(resources)), resources) for resources in [static_resources, static_resources2]] self.assertEqual(len(expected), len(p_coord.extract_my_subset.call_args_list)) for c in expected: self.assertIn(c, p_coord.extract_my_subset.call_args_list)
{ "content_hash": "5080a499beedf8c88b0a4ca531d3d920", "timestamp": "", "source": "github", "line_count": 611, "max_line_length": 79, "avg_line_length": 43.3518821603928, "alnum_prop": 0.58131984294775, "repo_name": "r-mibu/ceilometer", "id": "4fd2920f2f3e6e80e17b847f4cc92244b45b27dc", "size": "27358", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ceilometer/tests/agent/agentbase.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "2911624" }, { "name": "Shell", "bytes": "23274" } ], "symlink_target": "" }
Reforge your feeds **Recipes moved to separate [Repository](https://github.com/feediron/feediron-recipes)** About |Table Of Contents :---- | -------- This is a plugin for [Tiny Tiny RSS (tt-rss)](https://tt-rss.org/).<br>It allows you to replace an article's contents by the contents of an element on the linked URL's page<br><br>i.e. create a "full feed".<br><br>Keep up to date by subscribing to the [Release Feed](https://github.com/feediron/ttrss_plugin-feediron/releases.atom)|<ul><li>[Installation](#installation)</li><li>[Configuration tab](#configuration-tab)</li><ul><li>[Usage](#usage)</li><li>[Filters](#filters)</li><li>[General Options](#general-options)</li><li>[Global Options](#global-options)</li></ul><li>[Testing Tab](#testing-tab)</li><li>[Full configuration example](#full-configuration-example)</li><li>[Xpath General Information](#xpath-general-information)</li></ul> ## Installation Checkout the directory into your plugins folder like this (from tt-RSS root directory): ```sh $ cd /var/www/ttrss $ git clone git://github.com/m42e/ttrss_plugin-feediron.git plugins.local/feediron ``` Then enable the plugin in TT-RSS preferences. ### Optional Install [Readability.php](https://github.com/andreskrey/readability.php) using [composer](https://getcomposer.org/). Assuming composer is installed, navigate to the FeeIron plugin filter folder `filters/fi_mod_readability` with `composer.json` present and run: ``` $ composer install ``` ___ # Layout After install in the TinyTinyRSS preferences menu you will find new tab called FeedIron. Under this tab you will have access to the FeedIron Configuration tab and the FeedIron Testing tab. # Configuration tab The configuration for FeedIron is done in [JSON format](https://json.org/) and will be displayed in the large configuration text field. Use the large field to enter/modify the configuration data and click the Save button to store it. Additionally you can load predefined rules submitted by the community or export your own rules. To submit your own rules you can submit a pull request through Github. ![](./screenshots/config.png) ## Usage There are three (3) types of [Filters](#filters), five (5) [general options](#general-options) and one (1) [global option](#global-options). Note: The rule `type` Must be defined and has to be one of the following: `xpath`, `split` or `readability`. The best way to understand Feediron is to read the [Full configuration example](#full-configuration-example) ### Basic Configuration: A Basic Configuration must define: 1. The site string. e.g. `example.com` * Use the same configuration for multiple URL's by seperating them with the `|` Delimiter. e.g. `"example.com|example.net"` * The configuration will be applied when the site string matches the `<link>` or `<author>` tag of the RSS feed item. * The `<link>` takes precedence over the `<author>` * `<author>` based configurations will **NOT** automatically show in the Testing Tab 2. The Filter type. e.g. `"type":"xpath"` 3. The Filter config. e.g. `"xpath":"div[@id='content']"` or the array `"xpath": [ "div[@id='article']", "div[@id='footer']"]` Example: ```json { "example.com":{ "type":"xpath", "xpath":"div[@id='content']" }, "secondexample.com":{ "type":"xpath", "xpath": [ "div[@id='article']", "div[@id='footer']" ] } } ``` <sub>Note: Take care while values are separated by a `,` (comma) using a trailing `,` (comma) is not valid.</sub> --- # Filters: * [xpath](#xpath-filter) - `"type":"xpath"` * [xpath](#xpath---xpathxpath-str---array-of-xpath-str-) - `"xpath":"xpath str" / [ "array of xpath str" ]` * [index](#index---index-int) - `"index":int` * [multipage](#multipage---multipageoptions) - `"multipage":{options}` * xpath - `"xpath":"xpath str"` * [append](#append---appendbool) - `"append":bool` * [recursive](#recursive---recursivebool) - `"recursive":bool` * [start_element](#start_element---start_elementstr) - `"start_element":"str"` * [join_element](#join_element---join_elementstr) - `"join_element":"str"` * [end_element](#end_element----end_elementstr) - `"end_element":"str"` * [cleanup](#cleanup---cleanupxpath-str---array-of-xpath-str-) - `"cleanup":"xpath str" / [ "array of xpath str" ]` * [split](#split---typesplit) - `"type":"split"` * [steps](#steps---steps-array-of-steps-) - `"steps":[ array of steps ]` * after - `"after":"str"` * before - `"before":"str"` * [cleanup](#cleanup-cleanup-array-of-regex-) - `"cleanup":"/regex str/" / [ "/array of regex str/" ]` * [readability](#readability) - `"type":"readability"` Note: Also accepts all [Xpath type](#xpath-filter) options 1. [PHP-Readability](#php-readability) 2. [Readability.php](#readabilityphp) (Optionally installed) * [relativeurl](#relativeurl---relativeurlstr) - `"relativeurl":"str"` * [removebyline](#removebyline---removebylinebool) - `"removebyline":bool` * [normalize](#normalize---normalizebool) - `"normalize":bool` * [prependimage](#prependimage---prependimagebool) - `"prependimage":bool` * [mainimage](#mainimage---mainimagebool) - `"mainimage":bool` * [appendimages](#appendimages---appendimagesbool) - `"appendimages":bool` * [allimages](#allimages---allimagesbool) - `"allimages":bool` * [cleanup](#cleanup-cleanup-array-of-regex-) - `"cleanup": "/regex str/" / [ "/array of regex str/" ]` * [tags](#tags-filter) - `"tags":"{options}"` * [xpath](#tags-type-xpath---type-xpath) - `"type": "xpath"` * [xpath](#tags-xpath---xpathxpath-str---array-of-xpath-str-) - `"xpath":"xpath str" / [ "array of xpath str" ]` * [regex](#tags-type-regex---type-regex) - `"type": "regex"` * [pattern](#tags-regex-pattern---pattern-regex-str---array-of-regex-str-) - `"pattern": "/regex str/" / [ "/array of regex str/" ]` * [index](#tags-regex-index---indexint) - `"index":int` * [search](#tags-type-search---type-search) - `"type": "search"` * [pattern](#tags-search-pattern---pattern-regex-str---array-of-regex-str-) - `"pattern": "/regex str/" / [ "/array of regex str/" ]` * [match](#tags-search-match---match-str---array-of-str-) - `"match": "str" / [ "array of str" ]` * [replace-tags](#replace-tags---replace-tagsbool) - `"replace-tags":bool` * [cleanup](#cleanup---cleanupxpath-str---array-of-xpath-str-) - `"cleanup":"xpath str" / [ "array of xpath str" ]` * [split](#split---splitstr) - `"split":"str"` ## Xpath Filter The **xpath** value is the actual Xpath-element to fetch from the linked page. Omit the leading `//` - they will get prepended automatically. See also - [Xpath General Information](#xpath-general-information) ### xpath - `"xpath":"xpath str" / [ "array of xpath str" ]` Xpath string or Array of xpath strings Single xpath string: ```json "example.com":{ "type":"xpath", "xpath":"div[@id='content']" } ``` Array of xpath strings: ```json "example.com":{ "type":"xpath", "xpath":[ "div[@id='footer']", "div[@class='content']", "div[@class='header']", ] } ``` Xpaths are evaluated in the order they are given in the array and will be concatenated together. In the above example the output would be in the order of `Footer -> Content -> Header` instead of the normal `Header -> Footer -> Content`. See also [concatenation elements](#concatenation-elements) ### index - `"index": int` Integer - Every xpath can also be an object consisting of an `xpath` element and an `index` element. Selecting the 3rd Div in a page: ```json "example.com":{ "type":"xpath", "xpath":[ { "xpath":"div", "index":3 } ] } ``` ### multipage - `"multipage":{[options]}` This option indicates that the article is split into two or more pages (eventually). FeedIron can combine all the parts into the content of the article. You have to specify a ```xpath``` which identifies the links (&lt;a&gt;) to the pages. ```json "example.com":{ "type": "xpath", "multipage": { "xpath": "a[contains(@data-ga-category,'Pagination') and text() = 'Next']", "append": true, "recursive": true } } ``` #### append - `"append":bool` Boolean - If false, only the links are used and the original link is ignored else the links found using the xpath expression are added to the original page link. #### recursive - `"recursive":bool` Boolean - If true this option to parses every following page for more links. To avoid infinite loops the fetching stops if an url is added twice. ### Concatenation Elements #### start_element - `"start_element":"str"` String - Prepends string to the start of content ```json "example.com":{ "type":"xpath", "xpath":[ "div[@id='footer']" ], "start_element":"The Footer is >" } ``` Result: `The Footer is ><p>Footer Text</p>` #### join_element - `"join_element":"str"` String - Joins xpath array content together with string ```json "example.com":{ "type":"xpath", "xpath":[ "div[@id='footer']", "div[@class='header']" ], "join_element":"<br><br>" } ``` Result: `<p>Footer Text</p></div><br><br><p>Header Text</p>` #### end_element - `"end_element":"str"` String - Appends string to the end of content ```json "example.com":{ "type":"xpath", "xpath":[ "div[@class='header']" ], "end_element":"< The Header was" } ``` Result: `<p>Header Text</p>< The Header was` **Full Example of Concatenation Elements:** ```json "example.com":{ "type":"xpath", "xpath":[ "div[@id='footer']", "div[@class='content']", "div[@class='header']" ], "start_element":"The Footer is >", "join_element":"<br><br>", "end_element":"< The Header was" } ``` Result: `The Footer is ><p>Footer Text</p><br><br>><p>Content Text</p></div><br><br><p>Header Text</p>< The Header was` ### cleanup - `"cleanup":"xpath str" / [ "array of xpath str" ]` An array of Xpath-elements (relative to the fetched node) to remove from the fetched node. ```json "example.com":{ "type":"xpath", "xpath":"div[@id='content']", "cleanup" : [ "~<script([^<]|<(?!/script))*</script>~msi" ] } ``` ## split - `"type":"split"` ### steps - `"steps":[ array of steps ]` The steps value is an array of actions performed in the given order. If after is given the content will be split using the value and the second half is used, if before the first half is used. [preg_split](http://php.net/manual/en/function.preg-split.php) is used for this action. ```json "example.com":{ "type":"split", "steps":[{ "after": "/article-section clearfix\"\\W*>/", "before": "/<div\\W*class=\"module-box home-link-box/" }, { "before": "/<div\\W*class=\"btwBarInArticles/" } ] } ``` ### cleanup `"cleanup":[ "array of regex" ]` Optional - An array of regex that are removed using preg_replace. ```json "example.com":{ "type":"split", "steps":[{ "after": "/article-section clearfix\"\\W*>/", "before": "/<div\\W*class=\"module-box home-link-box/" }, { "before": "/<div\\W*class=\"btwBarInArticles/" } ], "cleanup" : [ "~<script([^<]|<(?!/script))*</script>~msi" ] } ``` ## Readability The Readability modules are a automated method that attempts to isolate the relevant article text and images. Basic Usage: ```json "example.com":{ "type":"readability" } ``` ### PHP-Readability In built default, This option makes use of [php-readability]( https://github.com/j0k3r/php-readability ) which is a fork of the [original](http://code.fivefilters.org/php-readability). All the extraction is performed within this module and has no configuration options ### Readability.php Optionally installed via composer [Readability.php](https://github.com/andreskrey/readability.php) is a PHP port of Mozilla's Readability.js. All the extraction is performed within this module. #### relativeurl - `"relativeurl":"str"` Convert relative URLs to absolute. Like `/test` to `http://host/test` ```json "example.com":{ "type":"readability", "relativeurl":"http:\/\/example.com\/" } ``` #### removebyline - `"removebyline":bool` Default value `false` ```json "example.com":{ "type":"readability", "removebyline":true } ``` #### normalize - `"normalize":bool` Default value `false` Converts UTF-8 characters to its HTML Entity equivalent. Useful to parse HTML with mixed encoding. ```json "example.com":{ "type":"readability", "normalize":true } ``` #### prependimage - `"prependimage":bool` Default value `false` Returns the main image of the article Prepended before the article. ```json "example.com":{ "type":"readability", "prependimage":true } ``` #### mainimage - `"mainimage":bool` Default value `false` Returns the main image of the article. ```json "example.com":{ "type":"readability", "mainimage":true } ``` #### appendimages - `"appendimages":bool` Default value `false` Returns all images in article appended after the article. ```json "example.com":{ "type":"readability", "appendimages":true } ``` #### allimages - `"allimages":bool` Default value `false` Returns all images in article without the article. ```json "example.com":{ "type":"readability", "allimages":true } ``` ## Tags Filter FeedIron can fetch text from a page and save them as article tags. This can be used to improve the filtering options found in TT-RSS. Note: The Tag filter can use all the options available to the xpath filter and the modify option. The order of execution for tags is: 1. Fetch Tag HTML. 2. Perform Cleanup tags individually. 3. Split Tags. 4. Modify Tags individually. 5. Strip any remaining HTML from Tags. Usage Example: ```json "tags": { "type": "xpath", "replace-tags":true, "xpath": [ "p[@class='topics']" ], "split":",", "cleanup": [ "strong" ], "modify":[ { "type": "replace", "search": "-", "replace": " " } ] } ``` ### tags type xpath - `"type": "xpath"` #### tags xpath - `"xpath":"xpath str" / [ "array of xpath str" ]` ```json "tags":{ "type":"xpath", "xpath":"p[@class='topics']" } ``` ### tags type regex - `"type": "regex"` Uses PHP preg_match() in order to find and return a string from the article. Requires at least on pattern. #### tags regex pattern - `"pattern": "/regex str/" / [ "/array of regex str/" ]` ```json "tags":{ "type":"regex", "pattern": "/The quick.*fox jumped/" } ``` #### tags regex index - `"index":int` Specifies the number of the entry in article to return. Default value `1` ```json "tags":{ "type":"regex", "pattern": "/The quick.*fox jumped/", "index": 2 } ``` ### tags type search - `"type": "search"` Search article using regex, if found it returns a pre-defined matching tag. ```json "tags":{ "type":"search", "pattern": [ "/feediron/", "/ttrss/" ], "match": [ "FeedIron is here", "TT-RSS is here" ] } ``` #### tags search pattern - `"pattern": "/regex str/" / [ "/array of regex str/" ]` Must have corresponding match entries #### tags search match - `"match": "str" / [ "array of str" ]` Must have corresponding pattern entries. This can be inverted using the `!` symbol at the beginning of the match entry to return if **NO** match is found ```json "tags":{ "type":"search", "pattern": [ "/feediron/", "/ttrss/" ], "match": [ "!FeedIron is not here", "TT-RSS is here" ] } ``` ### replace-tags - `"replace-tags":bool` Default value `false` Replace the article tags with fetched ones. By default tags are merged. ```json "tags":{ "type":"xpath", "xpath":"p[@class='topics']", "replace-tags": true } ``` ## split - `"split":"str"` String - Splits tags using a delimiter ```json "tags":{ "type":"xpath", "xpath":"p[@class='topics']", "split":"-" } ``` Input: `Tag1-Tag2-Tag3` Result: `Tag1, Tag2, Tag3` --- # General Options: * [reformat / modify](#reformat--modify---reformatarray-of-options-modifyarray-of-options) - `"reformat":[array of options]` `"modify":[array of options]` * [regex](#regex---typeregex) - `"type":"regex"` * [pattern](#pattern---patternregex-str) - `"pattern":"/regex str/"` * [replace](#replace---replacestr) - `"replace":"str"` * [replace](#replace---typereplace) - `"type":"replace"` * [search](#search---typesearch-str---array-of-search-str-) - `"type":"search str" / [ "array of search str" ]` * [replace](#replace---replacestr---array-of-str-) - `"replace":"str"` * [force_charset](#force_charset---force_charsetcharset) - `"force_charset":"charset"` * [force_unicode](#force_unicode---force_unicodebool) - `"force_unicode":bool` * [tidy-source](#tidysource---tidysourcebool) - `"tidy-source":bool` * [tidy](#tidy---tidybool) - `"tidy":bool` ## reformat / modify - `"reformat":[array of options]` `"modify":[array of options]` Reformat is an array of formatting rules for the url of the full article. The rules are applied before the full article is fetched. Where as Modify is an array of formatting rules for article using the same options. ### regex - `"type":"regex"` regex takes a regex in an option called pattern and the replacement in replace. For details see [preg_replace](http://www.php.net/manual/de/function.preg-replace.php) in the PHP documentation. #### pattern - `"pattern":"/regex str/"` A regular expression or regex string. #### replace - `"replace":"str"` String to replace regex match with Example reformat golem.de url: ```json "golem0Bde0C":{ "type":"xpath", "xpath":"article", "reformat": [ { "type": "regex", "pattern": "/(?:[a-z0-9A-Z\\/.\\:]*?)golem0Bde0C(.*)0Erss0Bhtml\\/story01.htm/", "replace": "http://www.golem.de/$1.html" } ] } ``` ### replace - `"type":"replace"` Uses the PHP function [str_replace](http://php.net/manual/en/function.str-replace.php), which takes either a string or an array as search and replace value. #### search - `"type":"search str" / [ "array of search str" ]` String to search for replacement. If an array the order will match the replacement string order #### replace - `"replace":"str" / [ "array of str" ]` String to replace search match with. Array must have the same number of options as the search array. Example search and replace instances of srcset with null: ```json { "type": "xpath", "xpath": "img", "modify": [ { "type": "replace", "search": "srcset", "replace": "null" } ] } ``` Example search and replace h1 and h2 tags with h3 tags: ```json "example.tld":{ "type": "xpath", "xpath": "article", "modify": [ { "type": "replace", "search": [ "<h1>", "<\/h1>", "<h2>", "<\/h2>" ], "replace": [ "<h3>", "<\/h3>", "<h3>", "<\/h3>" ] } ] } ``` ### force_charset - `"force_charset":"charset"` force_charset allows to override automatic charset detection. If it is omitted, the charset will be parsed from the HTTP headers or loadHTML() will decide on its own. ```json "example.tld":{ "type": "xpath", "xpath": "article", "force_charset": "utf-8" } ``` ### force_unicode - `"force_unicode":bool` force_unicode performs a UTF-8 character set conversion on the html via [iconv](http://php.net/manual/en/function.iconv.php). ```json "example.tld":{ "type": "xpath", "xpath": "article", "force_unicode": true } ``` ### tidy-source - `"tidy-source":bool` Optionally installed php-tidy. Default - `false` Use [tidy::cleanrepair](https://secure.php.net/manual/en/tidy.cleanrepair.php) to attempt to fix fetched article source, useful for improperly closed tags interfering with xpath queries. Note: If Character set of page cannot be detected tidy will not be executed. In this case usage of [force_charset](#force_charset---force_charsetcharset) would be required. ### tidy - `"tidy":bool` Optionally installed php-tidy. Default - `true` Use [tidy::cleanrepair](https://secure.php.net/manual/en/tidy.cleanrepair.php) to attempt to fix modified article, useful for unclosed tags such as iframes. Note: If Character set of page cannot be detected tidy will not be executed. In this case usage of [force_charset](#force_charset---force_charsetcharset) would be required. --- # Global options ### debug - `"debug":bool` debug You can activate debugging informations. (At the moment there are not that much debug informations to be activated), this option must be places at the same level as the site configs. Example: ```json { "example.com":{ "type":"xpath", "xpath":"div[@id='content']" }, "secondexample.com":{ "type":"xpath", "xpath": [ "div[@id='article']", "div[@id='footer']" ] }, "debug":false } ``` --- # Testing tab The Testing tab is where you can debug/create your configurations and view a preview of the filter results. The configuration in the testing tab is identical to the configuration tab while omitting the domain/url. ```json { "type":"xpath", "xpath":"article" } ``` Not ```json "example.tld":{ "type":"xpath", "xpath":"article" } ``` ![](./screenshots/testing.png) # Full configuration example ```json { "heise.de": { "name": "Heise Newsticker", "url": "http://heise.de/ticker/", "type": "xpath", "xpath": "div[@class='meldung_wrapper']", "force_charset": "utf-8" }, "berlin.de/polizei": { "type": "xpath", "xpath": "div[@class='bacontent']" }, "n24.de": { "type": "readability", }, "www.dorkly.com": { "type": "xpath", "multipage": { "xpath": "a[contains(@data-ga-category,'Pagination') and text() = 'Next']", "append": true, "recursive": true }, "xpath": "div[contains(@class,'post-content')]" }, "golem0Bde0C": { "type": "xpath", "xpath": "article", "multipage": { "xpath": "ol/li/a[contains(@id, 'atoc_')]", "append": true }, "reformat": [ { "type": "regex", "pattern": "/(?:[a-z0-9A-Z\\/.\\:]*?)golem0Bde0C(.*)0Erss0Bhtml\\/story01.htm/", "replace": "http://www.golem.de/$1.html" }, { "type": "replace", "search": [ "0A", "0C", "0B", "0E" ], "replace": [ "0", "/", ".", "-" ] } ] }, "oatmeal": { "type": "xpath", "xpath": "div[@id='comic']" }, "blog.beetlebum.de": { "type": "xpath", "xpath": "div[@class='entry-content']", "cleanup": [ "header", "footer" ] }, "sueddeutsche.de": { "type": "xpath", "xpath": [ "h2/strong", "section[contains(@class,'authors')]" ], "join_element": "<p>", "cleanup": [ "script" ] }, "www.spiegel.de": { "type": "split", "steps": [ { "after": "/article-section clearfix\"\\W*>/", "before": "/<div\\W*class=\"module-box home-link-box/" }, { "before": "/<div\\W*class=\"btwBarInArticles/" } ], "cleanup" : [ "~<script([^<]|<(?!/script))*</script>~msi" ], "force_unicode": true }, "debug": false } ``` ## Xpath General Information XPath is a query language for selecting nodes from an XML/html document. <details> <summary>Xpath Tools</summary> To test your XPath expressions, you can use these Chrome extensions: * [XPath Helper](https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl) * [xPath Viewer](https://chrome.google.com/webstore/detail/xpath-viewer/oemacabgcknpcikelclomjajcdpbilpf) * [xpathOnClick](https://chrome.google.com/webstore/detail/xpathonclick/ikbfbhbdjpjnalaooidkdbgjknhghhbo) </details> ### Xpath Examples Some XPath expressions you could need (the `//` is automatically prepended and must be omitted in the FeedMod configuration): #### HTML5 &lt;article&gt; tag <details> ```html <article>…article…</article> ``` ```xslt //article ``` </details> #### DIV inside DIV <details> ```html <div id="content"><div class="box_content">…article…</div></div>` ``` ```xslt //div[@id='content']/div[@class='box_content'] ``` </details> #### Multiple classes <details> ```html <div class="post-body entry-content xh-highlight">…article…</div> ``` ```xslt //div[starts-with(@class ,'post-body')] ``` or ```xslt //div[contains(@class, 'entry-content')] ``` </details> #### Image tag <details> ```html <a><img src='test.png' /></a> ``` ```xslt img/.. ``` </details> ## Special Thanks Thanks to [mbirth](https://github.com/mbirth) who wrote [af_feedmod](https://github.com/mbirth/ttrss_plugin-af_feedmod) who gave me a starting base.
{ "content_hash": "8da26e4e1db3e8f81c81a35b629f25f7", "timestamp": "", "source": "github", "line_count": 884, "max_line_length": 740, "avg_line_length": 27.626696832579185, "alnum_prop": 0.6387683236426173, "repo_name": "radlerandi/ttrss_plugin-feediron", "id": "1c2cad83bb59f23fca00b80d4542c2971d1da48a", "size": "24504", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "DIGITAL Command Language", "bytes": "11497" }, { "name": "PHP", "bytes": "111994" } ], "symlink_target": "" }
const array = [] const characterCodeCache = [] module.exports = function leven (first, second) { if (first === second) { return 0 } const swap = first // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (first.length > second.length) { first = second second = swap } let firstLength = first.length let secondLength = second.length // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (firstLength > 0 && (first.charCodeAt(~-firstLength) === second.charCodeAt(~-secondLength))) { firstLength-- secondLength-- } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all let start = 0 while (start < firstLength && (first.charCodeAt(start) === second.charCodeAt(start))) { start++ } firstLength -= start secondLength -= start if (firstLength === 0) { return secondLength } let bCharacterCode let result let temporary let temporary2 let index = 0 let index2 = 0 while (index < firstLength) { characterCodeCache[index] = first.charCodeAt(start + index) array[index] = ++index } while (index2 < secondLength) { bCharacterCode = second.charCodeAt(start + index2) temporary = index2++ result = index2 for (index = 0; index < firstLength; index++) { temporary2 = bCharacterCode === characterCodeCache[index] ? temporary : temporary + 1 temporary = array[index] // eslint-disable-next-line no-multi-assign result = array[index] = temporary > result ? (temporary2 > result ? result + 1 : temporary2) : (temporary2 > temporary ? temporary + 1 : temporary2) } } return result }
{ "content_hash": "63e3d3295d676bb425c86b10a983bad6", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 154, "avg_line_length": 25.905405405405407, "alnum_prop": 0.6614501825769431, "repo_name": "mcollina/commist", "id": "8baf453f414a8b6d3052f9c3313ee726146ffad2", "size": "3084", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "leven.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "14412" } ], "symlink_target": "" }
/** * Automatically generated file. DO NOT MODIFY */ package com.phonegap.helloworld; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.phonegap.helloworld"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = 100008; public static final String VERSION_NAME = "1.0.0"; }
{ "content_hash": "ae8254f8937501373246df21f557c24d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 72, "avg_line_length": 35.38461538461539, "alnum_prop": 0.741304347826087, "repo_name": "iliaskomp/MafiaApp", "id": "2162482727f41f37b0742d5bdaeaac5e7706746e", "size": "460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platforms/android/build/generated/source/buildConfig/debug/com/phonegap/helloworld/BuildConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "15347" }, { "name": "C", "bytes": "4790" }, { "name": "C#", "bytes": "429794" }, { "name": "C++", "bytes": "432816" }, { "name": "CSS", "bytes": "87636" }, { "name": "HTML", "bytes": "221861" }, { "name": "Java", "bytes": "1608112" }, { "name": "JavaScript", "bytes": "525814" }, { "name": "Objective-C", "bytes": "787258" }, { "name": "PHP", "bytes": "35598" }, { "name": "QML", "bytes": "15363" } ], "symlink_target": "" }
<?php namespace Lull\Test; use \Lull\Test\Resource\Widget\Mapper; class Service { /** @var string */ private $resource; /** @var string */ private $httpMethod; /** @var string */ private $serviceMethod; /** @var mixed */ private $id; /** @var array */ private $query = array(); /** @var \Lull\Test\Db */ private $db; /** * Uses the request to define class properties. */ public function __construct() { $this->httpMethod = filter_input(INPUT_SERVER, 'REQUEST_METHOD'); $this->serviceMethod = 'do' . ucfirst(strtolower($this->httpMethod)); $url = filter_input(INPUT_SERVER, 'HTTP_HOST') . filter_input(INPUT_SERVER, 'REQUEST_URI'); if ($urlParts = parse_url($url)) { $segments = explode('/', trim($urlParts['path'], '/')); $this->resource = $segments[0]; $this->id = isset($segments[1]) ? $segments[1] : null; if (array_key_exists('query', $urlParts)) { parse_str($urlParts['query'], $this->query); } } $this->db = new Db(); } /** * @return mixed */ public function handle() { $this->validate(); return call_user_func(array($this, $this->serviceMethod)); } /** * @return string */ public function doGet() { if (!$this->id) { $params = array('offset' => 0, 'limit' => null); if (!empty($this->query)) { $params = array_merge($params, $this->query); if (count($params) > 2) { return $this->respond(array('error' => 'Invalid query parameters.'), 400); } } return $this->respond($this->getDb()->fetchAll($params['offset'], $params['limit'])); } if (!$data = $this->getDb()->fetchById($this->id)) { return $this->respond(array('error' => 'Invalid widget ID.'), 400); } return $this->respond($data); } /** * @return string */ private function validate() { if ($this->resource != 'widgets' || (isset($this->id) && !is_numeric($this->id))) { return $this->respond(array('error' => 'Endpoint not found.'), 404); } if (!method_exists($this, $this->serviceMethod)) { $message = sprintf('%s is not a supported HTTP method.', $this->httpMethod); return $this->respond(array('error' => $message), 405); } } /** * @param mixed $data * @param int $statusCode * @return string */ private function respond($data, $statusCode = 200) { if (isset($data['error'])) { $response = array('error' => $data['error']); } else { $response = array('recordCount' => count($data), 'response' => $data); } $protocol = filter_input(INPUT_SERVER, 'SERVER_PROTOCOL'); $statusCodeString = $this->getHttpStatusCodeString($statusCode); $statusMessage = sprintf('%s %s', $protocol, $statusCodeString); ob_start(); header($statusMessage); header('Content-type: application/json'); echo json_encode($response); ob_end_flush(); exit; } /** * @param int $statusCode * @return string */ private function getHttpStatusCodeString($statusCode) { $statusCodes = array( 200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized', 404 => 'Not Found', 405 => 'Method Not Allowed', 500 => 'Internal Server Error' ); if (!array_key_exists($statusCode, $statusCodes)) { $statusCode = 500; } return sprintf('%d %s', $statusCode, $statusCodes[$statusCode]); } /** * @return \Lull\Test\Db */ private function getDb() { return $this->db; } }
{ "content_hash": "7bc38880c8f50efb2334229f886199d9", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 99, "avg_line_length": 28.148936170212767, "alnum_prop": 0.5074326026706979, "repo_name": "guillermoandrae/lull", "id": "e9ae18cd0716cfe00975ad59740c0f1484ccd510", "size": "4148", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Lull/Test/Service.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "32051" } ], "symlink_target": "" }
<?php namespace Symfony\Component\BrowserKit\Tests; use PHPUnit\Framework\TestCase; use Symfony\Component\BrowserKit\Client; use Symfony\Component\BrowserKit\History; use Symfony\Component\BrowserKit\CookieJar; use Symfony\Component\BrowserKit\Response; class SpecialResponse extends Response { } class TestClient extends Client { protected $nextResponse = null; protected $nextScript = null; public function setNextResponse(Response $response) { $this->nextResponse = $response; } public function setNextScript($script) { $this->nextScript = $script; } protected function doRequest($request) { if (null === $this->nextResponse) { return new Response(); } $response = $this->nextResponse; $this->nextResponse = null; return $response; } protected function filterResponse($response) { if ($response instanceof SpecialResponse) { return new Response($response->getContent(), $response->getStatus(), $response->getHeaders()); } return $response; } protected function getScript($request) { $r = new \ReflectionClass('Symfony\Component\BrowserKit\Response'); $path = $r->getFileName(); return <<<EOF <?php require_once('$path'); echo serialize($this->nextScript); EOF; } } class ClientTest extends TestCase { public function testGetHistory() { $client = new TestClient(array(), $history = new History()); $this->assertSame($history, $client->getHistory(), '->getHistory() returns the History'); } public function testGetCookieJar() { $client = new TestClient(array(), null, $cookieJar = new CookieJar()); $this->assertSame($cookieJar, $client->getCookieJar(), '->getCookieJar() returns the CookieJar'); } public function testGetRequest() { $client = new TestClient(); $client->request('GET', 'http://example.com/'); $this->assertEquals('http://example.com/', $client->getRequest()->getUri(), '->getCrawler() returns the Request of the last request'); } /** * @group legacy * @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0. */ public function testGetRequestNull() { $client = new TestClient(); $this->assertNull($client->getRequest()); } public function testGetRequestWithXHR() { $client = new TestClient(); $client->switchToXHR(); $client->request('GET', 'http://example.com/', array(), array(), array(), null, true, true); $this->assertEquals($client->getRequest()->getServer()['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest'); $client->removeXHR(); $this->assertFalse($client->getServerParameter('HTTP_X_REQUESTED_WITH', false)); } public function testGetRequestWithIpAsHttpHost() { $client = new TestClient(); $client->request('GET', 'https://example.com/foo', array(), array(), array('HTTP_HOST' => '127.0.0.1')); $this->assertEquals('https://example.com/foo', $client->getRequest()->getUri()); $headers = $client->getRequest()->getServer(); $this->assertEquals('127.0.0.1', $headers['HTTP_HOST']); } public function testGetResponse() { $client = new TestClient(); $client->setNextResponse(new Response('foo')); $client->request('GET', 'http://example.com/'); $this->assertEquals('foo', $client->getResponse()->getContent(), '->getCrawler() returns the Response of the last request'); $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getResponse(), '->getCrawler() returns the Response of the last request'); } /** * @group legacy * @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0. */ public function testGetResponseNull() { $client = new TestClient(); $this->assertNull($client->getResponse()); } public function testGetInternalResponse() { $client = new TestClient(); $client->setNextResponse(new SpecialResponse('foo')); $client->request('GET', 'http://example.com/'); $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse()); $this->assertNotInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getInternalResponse()); $this->assertInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getResponse()); } /** * @group legacy * @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getInternalResponse()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0. */ public function testGetInternalResponseNull() { $client = new TestClient(); $this->assertNull($client->getInternalResponse()); } public function testGetContent() { $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}'; $client = new TestClient(); $client->request('POST', 'http://example.com/jsonrpc', array(), array(), array(), $json); $this->assertEquals($json, $client->getRequest()->getContent()); } public function testGetCrawler() { $client = new TestClient(); $client->setNextResponse(new Response('foo')); $crawler = $client->request('GET', 'http://example.com/'); $this->assertSame($crawler, $client->getCrawler(), '->getCrawler() returns the Crawler of the last request'); } /** * @group legacy * @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getCrawler()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0. */ public function testGetCrawlerNull() { $client = new TestClient(); $this->assertNull($client->getCrawler()); } public function testRequestHttpHeaders() { $client = new TestClient(); $client->request('GET', '/'); $headers = $client->getRequest()->getServer(); $this->assertEquals('localhost', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header'); $client = new TestClient(); $client->request('GET', 'http://www.example.com'); $headers = $client->getRequest()->getServer(); $this->assertEquals('www.example.com', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header'); $client->request('GET', 'https://www.example.com'); $headers = $client->getRequest()->getServer(); $this->assertTrue($headers['HTTPS'], '->request() sets the HTTPS header'); $client = new TestClient(); $client->request('GET', 'http://www.example.com:8080'); $headers = $client->getRequest()->getServer(); $this->assertEquals('www.example.com:8080', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header with port'); } public function testRequestURIConversion() { $client = new TestClient(); $client->request('GET', '/foo'); $this->assertEquals('http://localhost/foo', $client->getRequest()->getUri(), '->request() converts the URI to an absolute one'); $client = new TestClient(); $client->request('GET', 'http://www.example.com'); $this->assertEquals('http://www.example.com', $client->getRequest()->getUri(), '->request() does not change absolute URIs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/'); $client->request('GET', '/foo'); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo'); $client->request('GET', '#'); $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client->request('GET', '#'); $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client->request('GET', '#foo'); $this->assertEquals('http://www.example.com/foo#foo', $client->getRequest()->getUri(), '->request() uses the previous request for #'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/'); $client->request('GET', 'http'); $this->assertEquals('http://www.example.com/foo/http', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo'); $client->request('GET', 'http/bar'); $this->assertEquals('http://www.example.com/http/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/'); $client->request('GET', 'http'); $this->assertEquals('http://www.example.com/http', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs'); $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo'); $client->request('GET', '?'); $this->assertEquals('http://www.example.com/foo?', $client->getRequest()->getUri(), '->request() uses the previous request for ?'); $client->request('GET', '?'); $this->assertEquals('http://www.example.com/foo?', $client->getRequest()->getUri(), '->request() uses the previous request for ?'); $client->request('GET', '?foo=bar'); $this->assertEquals('http://www.example.com/foo?foo=bar', $client->getRequest()->getUri(), '->request() uses the previous request for ?'); } public function testRequestReferer() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $server = $client->getRequest()->getServer(); $this->assertEquals('http://www.example.com/foo/foobar', $server['HTTP_REFERER'], '->request() sets the referer'); } public function testRequestHistory() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'bar'); $this->assertEquals('http://www.example.com/foo/bar', $client->getHistory()->current()->getUri(), '->request() updates the History'); $this->assertEquals('http://www.example.com/foo/foobar', $client->getHistory()->back()->getUri(), '->request() updates the History'); } public function testRequestCookies() { $client = new TestClient(); $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>', 200, array('Set-Cookie' => 'foo=bar'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar'); $client->request('GET', 'bar'); $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar'); } public function testRequestSecureCookies() { $client = new TestClient(); $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>', 200, array('Set-Cookie' => 'foo=bar; path=/; secure'))); $client->request('GET', 'https://www.example.com/foo/foobar'); $this->assertTrue($client->getCookieJar()->get('foo', '/', 'www.example.com')->isSecure()); } public function testClick() { $client = new TestClient(); $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->click($crawler->filter('a')->link()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() clicks on links'); } public function testClickForm() { $client = new TestClient(); $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->click($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() Form submit forms'); } public function testSubmit() { $client = new TestClient(); $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $client->submit($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms'); } public function testSubmitPreserveAuth() { $client = new TestClient(array('PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar')); $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>')); $crawler = $client->request('GET', 'http://www.example.com/foo/foobar'); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('PHP_AUTH_USER', $server); $this->assertEquals('foo', $server['PHP_AUTH_USER']); $this->assertArrayHasKey('PHP_AUTH_PW', $server); $this->assertEquals('bar', $server['PHP_AUTH_PW']); $client->submit($crawler->filter('input')->form()); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms'); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('PHP_AUTH_USER', $server); $this->assertEquals('foo', $server['PHP_AUTH_USER']); $this->assertArrayHasKey('PHP_AUTH_PW', $server); $this->assertEquals('bar', $server['PHP_AUTH_PW']); } public function testFollowRedirect() { $client = new TestClient(); $client->followRedirects(false); $client->request('GET', 'http://www.example.com/foo/foobar'); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request was not redirected'); } catch (\Exception $e) { $this->assertInstanceOf('LogicException', $e, '->followRedirect() throws a \LogicException if the request was not redirected'); } $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->followRedirect(); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() automatically follows redirects if followRedirects is true'); $client = new TestClient(); $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->followRedirect() does not follow redirect if HTTP Code is not 30x'); $client = new TestClient(); $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected'))); $client->followRedirects(false); $client->request('GET', 'http://www.example.com/foo/foobar'); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code'); } catch (\Exception $e) { $this->assertInstanceOf('LogicException', $e, '->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code'); } } public function testFollowRelativeRedirect() { $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => '/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => '/redirected:1234'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected:1234', $client->getRequest()->getUri(), '->followRedirect() follows relative urls'); } public function testFollowRedirectWithMaxRedirects() { $client = new TestClient(); $client->setMaxRedirects(1); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected2'))); try { $client->followRedirect(); $this->fail('->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached'); } catch (\Exception $e) { $this->assertInstanceOf('LogicException', $e, '->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached'); } $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any'); $client->setNextResponse(new Response('', 302, array('Location' => '/redirected'))); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows relative URLs'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => '//www.example.org/'))); $client->request('GET', 'https://www.example.com/'); $this->assertEquals('https://www.example.org/', $client->getRequest()->getUri(), '->followRedirect() follows protocol-relative URLs'); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected'))); $client->request('POST', 'http://www.example.com/foo/foobar', array('name' => 'bar')); $this->assertEquals('GET', $client->getRequest()->getMethod(), '->followRedirect() uses a GET for 302'); $this->assertEquals(array(), $client->getRequest()->getParameters(), '->followRedirect() does not submit parameters when changing the method'); } public function testFollowRedirectWithCookies() { $client = new TestClient(); $client->followRedirects(false); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com/redirected', 'Set-Cookie' => 'foo=bar', ))); $client->request('GET', 'http://www.example.com/'); $this->assertEquals(array(), $client->getRequest()->getCookies()); $client->followRedirect(); $this->assertEquals(array('foo' => 'bar'), $client->getRequest()->getCookies()); } public function testFollowRedirectWithHeaders() { $headers = array( 'HTTP_HOST' => 'www.example.com', 'HTTP_USER_AGENT' => 'Symfony BrowserKit', 'CONTENT_TYPE' => 'application/vnd.custom+xml', 'HTTPS' => false, ); $client = new TestClient(); $client->followRedirects(false); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com/redirected', ))); $client->request('GET', 'http://www.example.com/', array(), array(), array( 'CONTENT_TYPE' => 'application/vnd.custom+xml', )); $this->assertEquals($headers, $client->getRequest()->getServer()); $client->followRedirect(); $headers['HTTP_REFERER'] = 'http://www.example.com/'; $this->assertEquals($headers, $client->getRequest()->getServer()); } public function testFollowRedirectWithPort() { $headers = array( 'HTTP_HOST' => 'www.example.com:8080', 'HTTP_USER_AGENT' => 'Symfony BrowserKit', 'HTTPS' => false, 'HTTP_REFERER' => 'http://www.example.com:8080/', ); $client = new TestClient(); $client->setNextResponse(new Response('', 302, array( 'Location' => 'http://www.example.com:8080/redirected', ))); $client->request('GET', 'http://www.example.com:8080/'); $this->assertEquals($headers, $client->getRequest()->getServer()); } public function testIsFollowingRedirects() { $client = new TestClient(); $this->assertTrue($client->isFollowingRedirects(), '->getFollowRedirects() returns default value'); $client->followRedirects(false); $this->assertFalse($client->isFollowingRedirects(), '->getFollowRedirects() returns assigned value'); } public function testGetMaxRedirects() { $client = new TestClient(); $this->assertEquals(-1, $client->getMaxRedirects(), '->getMaxRedirects() returns default value'); $client->setMaxRedirects(3); $this->assertEquals(3, $client->getMaxRedirects(), '->getMaxRedirects() returns assigned value'); } public function testFollowRedirectWithPostMethod() { $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client = new TestClient(); $client->setNextResponse(new Response('', 307, array('Location' => 'http://www.example.com/redirected'))); $client->request('POST', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect with POST method'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->followRedirect() keeps parameters with POST method'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->followRedirect() keeps files with POST method'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->followRedirect() keeps $_SERVER with POST method'); $this->assertEquals($content, $client->getRequest()->getContent(), '->followRedirect() keeps content with POST method'); $this->assertEquals('POST', $client->getRequest()->getMethod(), '->followRedirect() keeps request method'); } public function testFollowRedirectDropPostMethod() { $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client = new TestClient(); foreach (array(301, 302, 303) as $code) { $client->setNextResponse(new Response('', $code, array('Location' => 'http://www.example.com/redirected'))); $client->request('POST', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect with POST method on response code: '.$code.'.'); $this->assertEmpty($client->getRequest()->getParameters(), '->followRedirect() drops parameters with POST method on response code: '.$code.'.'); $this->assertEmpty($client->getRequest()->getFiles(), '->followRedirect() drops files with POST method on response code: '.$code.'.'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->followRedirect() keeps $_SERVER with POST method on response code: '.$code.'.'); $this->assertEmpty($client->getRequest()->getContent(), '->followRedirect() drops content with POST method on response code: '.$code.'.'); $this->assertEquals('GET', $client->getRequest()->getMethod(), '->followRedirect() drops request method to GET on response code: '.$code.'.'); } } public function testBack() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $client->request('GET', 'http://www.example.com/foo'); $client->back(); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->back() goes back in the history'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->back() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->back() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->back() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->back() keeps content'); } public function testForward() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar'); $client->request('GET', 'http://www.example.com/foo', $parameters, $files, $server, $content); $client->back(); $client->forward(); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->forward() goes forward in the history'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->forward() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->forward() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->forward() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->forward() keeps content'); } public function testBackAndFrowardWithRedirects() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo'); $client->setNextResponse(new Response('', 301, array('Location' => 'http://www.example.com/redirected'))); $client->request('GET', 'http://www.example.com/bar'); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), 'client followed redirect'); $client->back(); $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->back() goes back in the history skipping redirects'); $client->forward(); $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->forward() goes forward in the history skipping redirects'); } public function testReload() { $client = new TestClient(); $parameters = array('foo' => 'bar'); $files = array('myfile.foo' => 'baz'); $server = array('X_TEST_FOO' => 'bazbar'); $content = 'foobarbaz'; $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content); $client->reload(); $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->reload() reloads the current page'); $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->reload() keeps parameters'); $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->reload() keeps files'); $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->reload() keeps $_SERVER'); $this->assertEquals($content, $client->getRequest()->getContent(), '->reload() keeps content'); } public function testRestart() { $client = new TestClient(); $client->request('GET', 'http://www.example.com/foo/foobar'); $client->restart(); $this->assertTrue($client->getHistory()->isEmpty(), '->restart() clears the history'); $this->assertEquals(array(), $client->getCookieJar()->all(), '->restart() clears the cookies'); } public function testInsulatedRequests() { $client = new TestClient(); $client->insulate(); $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar')"); $client->request('GET', 'http://www.example.com/foo/foobar'); $this->assertEquals('foobar', $client->getResponse()->getContent(), '->insulate() process the request in a forked process'); $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar)"); try { $client->request('GET', 'http://www.example.com/foo/foobar'); $this->fail('->request() throws a \RuntimeException if the script has an error'); } catch (\Exception $e) { $this->assertInstanceOf('RuntimeException', $e, '->request() throws a \RuntimeException if the script has an error'); } } public function testGetServerParameter() { $client = new TestClient(); $this->assertEquals('', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $this->assertEquals('testvalue', $client->getServerParameter('testkey', 'testvalue')); } public function testSetServerParameter() { $client = new TestClient(); $this->assertEquals('', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $client->setServerParameter('HTTP_HOST', 'testhost'); $this->assertEquals('testhost', $client->getServerParameter('HTTP_HOST')); $client->setServerParameter('HTTP_USER_AGENT', 'testua'); $this->assertEquals('testua', $client->getServerParameter('HTTP_USER_AGENT')); } public function testSetServerParameterInRequest() { $client = new TestClient(); $this->assertEquals('', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $client->request('GET', 'https://www.example.com/https/www.example.com', array(), array(), array( 'HTTP_HOST' => 'testhost', 'HTTP_USER_AGENT' => 'testua', 'HTTPS' => false, 'NEW_SERVER_KEY' => 'new-server-key-value', )); $this->assertEquals('', $client->getServerParameter('HTTP_HOST')); $this->assertEquals('Symfony BrowserKit', $client->getServerParameter('HTTP_USER_AGENT')); $this->assertEquals('http://www.example.com/https/www.example.com', $client->getRequest()->getUri()); $server = $client->getRequest()->getServer(); $this->assertArrayHasKey('HTTP_USER_AGENT', $server); $this->assertEquals('testua', $server['HTTP_USER_AGENT']); $this->assertArrayHasKey('HTTP_HOST', $server); $this->assertEquals('testhost', $server['HTTP_HOST']); $this->assertArrayHasKey('NEW_SERVER_KEY', $server); $this->assertEquals('new-server-key-value', $server['NEW_SERVER_KEY']); $this->assertArrayHasKey('HTTPS', $server); $this->assertFalse($server['HTTPS']); } public function testInternalRequest() { $client = new TestClient(); $client->request('GET', 'https://www.example.com/https/www.example.com', array(), array(), array( 'HTTP_HOST' => 'testhost', 'HTTP_USER_AGENT' => 'testua', 'HTTPS' => false, 'NEW_SERVER_KEY' => 'new-server-key-value', )); $this->assertInstanceOf('Symfony\Component\BrowserKit\Request', $client->getInternalRequest()); } /** * @group legacy * @expectedDeprecation Calling the "Symfony\Component\BrowserKit\Client::getInternalRequest()" method before the "request()" one is deprecated since Symfony 4.1 and will throw an exception in 5.0. */ public function testInternalRequestNull() { $client = new TestClient(); $this->assertNull($client->getInternalRequest()); } }
{ "content_hash": "cd1fef4bddc19c09d94665715da56ba9", "timestamp": "", "source": "github", "line_count": 765, "max_line_length": 202, "avg_line_length": 45.597385620915034, "alnum_prop": 0.6156183705062783, "repo_name": "hacfi/symfony", "id": "e4414329895589a3cfc61200ea09be65115b192d", "size": "35111", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Symfony/Component/BrowserKit/Tests/ClientTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "340020" }, { "name": "PHP", "bytes": "14391143" }, { "name": "Shell", "bytes": "375" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <feed><tipo>Rua</tipo><logradouro>Itagi</logradouro><bairro>Rosário</bairro><cidade>Sabará</cidade><uf>MG</uf><cep>34575060</cep></feed>
{ "content_hash": "aafe3f31b71145943f94ba9420f64c07", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 136, "avg_line_length": 96.5, "alnum_prop": 0.7150259067357513, "repo_name": "chesarex/webservice-cep", "id": "b715d96ce988f1668b1b97bd76502f7840f48a20", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/ceps/34/575/060/cep.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.wsl.library.design; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.os.Build; import android.support.design.R; import android.support.v4.text.TextDirectionHeuristicsCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.text.TextPaint; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.animation.Interpolator; final class CollapsingTextHelper { // Pre-JB-MR2 doesn't support HW accelerated canvas scaled text so we will workaround it // by using our own texture private static final boolean USE_SCALING_TEXTURE = Build.VERSION.SDK_INT < 18; private static final boolean DEBUG_DRAW = false; private static final Paint DEBUG_DRAW_PAINT; static { DEBUG_DRAW_PAINT = DEBUG_DRAW ? new Paint() : null; if (DEBUG_DRAW_PAINT != null) { DEBUG_DRAW_PAINT.setAntiAlias(true); DEBUG_DRAW_PAINT.setColor(Color.MAGENTA); } } private final View mView; private boolean mDrawTitle; private float mExpandedFraction; private final Rect mExpandedBounds; private final Rect mCollapsedBounds; private final RectF mCurrentBounds; private int mExpandedTextGravity = Gravity.CENTER_VERTICAL; private int mCollapsedTextGravity = Gravity.CENTER_VERTICAL; private float mExpandedTextSize = 15; private float mCollapsedTextSize = 15; private int mExpandedTextColor; private int mCollapsedTextColor; private float mExpandedDrawY; private float mCollapsedDrawY; private float mExpandedDrawX; private float mCollapsedDrawX; private float mCurrentDrawX; private float mCurrentDrawY; private Typeface mCollapsedTypeface; private Typeface mExpandedTypeface; private Typeface mCurrentTypeface; private CharSequence mText; private CharSequence mTextToDraw; private boolean mIsRtl; private boolean mUseTexture; private Bitmap mExpandedTitleTexture; private Paint mTexturePaint; private float mTextureAscent; private float mTextureDescent; private float mScale; private float mCurrentTextSize; private boolean mBoundsChanged; private final TextPaint mTextPaint; private Interpolator mPositionInterpolator; private Interpolator mTextSizeInterpolator; private float mCollapsedShadowRadius, mCollapsedShadowDx, mCollapsedShadowDy; private int mCollapsedShadowColor; private float mExpandedShadowRadius, mExpandedShadowDx, mExpandedShadowDy; private int mExpandedShadowColor; public CollapsingTextHelper(View view) { mView = view; mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); mCollapsedBounds = new Rect(); mExpandedBounds = new Rect(); mCurrentBounds = new RectF(); } void setTextSizeInterpolator(Interpolator interpolator) { mTextSizeInterpolator = interpolator; recalculate(); } void setPositionInterpolator(Interpolator interpolator) { mPositionInterpolator = interpolator; recalculate(); } void setExpandedTextSize(float textSize) { if (mExpandedTextSize != textSize) { mExpandedTextSize = textSize; recalculate(); } } void setCollapsedTextSize(float textSize) { if (mCollapsedTextSize != textSize) { mCollapsedTextSize = textSize; recalculate(); } } void setCollapsedTextColor(int textColor) { if (mCollapsedTextColor != textColor) { mCollapsedTextColor = textColor; recalculate(); } } void setExpandedTextColor(int textColor) { if (mExpandedTextColor != textColor) { mExpandedTextColor = textColor; recalculate(); } } void setExpandedBounds(int left, int top, int right, int bottom) { if (!rectEquals(mExpandedBounds, left, top, right, bottom)) { mExpandedBounds.set(left, top, right, bottom); mBoundsChanged = true; onBoundsChanged(); } } void setCollapsedBounds(int left, int top, int right, int bottom) { if (!rectEquals(mCollapsedBounds, left, top, right, bottom)) { mCollapsedBounds.set(left, top, right, bottom); mBoundsChanged = true; onBoundsChanged(); } } void onBoundsChanged() { mDrawTitle = mCollapsedBounds.width() > 0 && mCollapsedBounds.height() > 0 && mExpandedBounds.width() > 0 && mExpandedBounds.height() > 0; } void setExpandedTextGravity(int gravity) { if (mExpandedTextGravity != gravity) { mExpandedTextGravity = gravity; recalculate(); } } int getExpandedTextGravity() { return mExpandedTextGravity; } void setCollapsedTextGravity(int gravity) { if (mCollapsedTextGravity != gravity) { mCollapsedTextGravity = gravity; recalculate(); } } int getCollapsedTextGravity() { return mCollapsedTextGravity; } void setCollapsedTextAppearance(int resId) { TypedArray a = mView.getContext().obtainStyledAttributes(resId, R.styleable.TextAppearance); if (a.hasValue(R.styleable.TextAppearance_android_textColor)) { mCollapsedTextColor = a.getColor( R.styleable.TextAppearance_android_textColor, mCollapsedTextColor); } if (a.hasValue(R.styleable.TextAppearance_android_textSize)) { mCollapsedTextSize = a.getDimensionPixelSize( R.styleable.TextAppearance_android_textSize, (int) mCollapsedTextSize); } mCollapsedShadowColor = a.getInt(R.styleable.TextAppearance_android_shadowColor, 0); mCollapsedShadowDx = a.getFloat(R.styleable.TextAppearance_android_shadowDx, 0); mCollapsedShadowDy = a.getFloat(R.styleable.TextAppearance_android_shadowDy, 0); mCollapsedShadowRadius = a.getFloat(R.styleable.TextAppearance_android_shadowRadius, 0); a.recycle(); if (Build.VERSION.SDK_INT >= 16) { mCollapsedTypeface = readFontFamilyTypeface(resId); } recalculate(); } void setExpandedTextAppearance(int resId) { TypedArray a = mView.getContext().obtainStyledAttributes(resId, R.styleable.TextAppearance); if (a.hasValue(R.styleable.TextAppearance_android_textColor)) { mExpandedTextColor = a.getColor( R.styleable.TextAppearance_android_textColor, mExpandedTextColor); } if (a.hasValue(R.styleable.TextAppearance_android_textSize)) { mExpandedTextSize = a.getDimensionPixelSize( R.styleable.TextAppearance_android_textSize, (int) mExpandedTextSize); } mExpandedShadowColor = a.getInt(R.styleable.TextAppearance_android_shadowColor, 0); mExpandedShadowDx = a.getFloat(R.styleable.TextAppearance_android_shadowDx, 0); mExpandedShadowDy = a.getFloat(R.styleable.TextAppearance_android_shadowDy, 0); mExpandedShadowRadius = a.getFloat(R.styleable.TextAppearance_android_shadowRadius, 0); a.recycle(); if (Build.VERSION.SDK_INT >= 16) { mExpandedTypeface = readFontFamilyTypeface(resId); } recalculate(); } private Typeface readFontFamilyTypeface(int resId) { final TypedArray a = mView.getContext().obtainStyledAttributes(resId, new int[]{android.R.attr.fontFamily}); try { final String family = a.getString(0); if (family != null) { return Typeface.create(family, Typeface.NORMAL); } } finally { a.recycle(); } return null; } void setCollapsedTypeface(Typeface typeface) { if (mCollapsedTypeface != typeface) { mCollapsedTypeface = typeface; recalculate(); } } void setExpandedTypeface(Typeface typeface) { if (mExpandedTypeface != typeface) { mExpandedTypeface = typeface; recalculate(); } } void setTypefaces(Typeface typeface) { mCollapsedTypeface = mExpandedTypeface = typeface; recalculate(); } Typeface getCollapsedTypeface() { return mCollapsedTypeface != null ? mCollapsedTypeface : Typeface.DEFAULT; } Typeface getExpandedTypeface() { return mExpandedTypeface != null ? mExpandedTypeface : Typeface.DEFAULT; } /** * Set the value indicating the current scroll value. This decides how much of the * background will be displayed, as well as the title metrics/positioning. * * A value of {@code 0.0} indicates that the layout is fully expanded. * A value of {@code 1.0} indicates that the layout is fully collapsed. */ void setExpansionFraction(float fraction) { fraction = MathUtils.constrain(fraction, 0f, 1f); if (fraction != mExpandedFraction) { mExpandedFraction = fraction; calculateCurrentOffsets(); } } float getExpansionFraction() { return mExpandedFraction; } float getCollapsedTextSize() { return mCollapsedTextSize; } float getExpandedTextSize() { return mExpandedTextSize; } private void calculateCurrentOffsets() { calculateOffsets(mExpandedFraction); } private void calculateOffsets(final float fraction) { interpolateBounds(fraction); mCurrentDrawX = lerp(mExpandedDrawX, mCollapsedDrawX, fraction, mPositionInterpolator); mCurrentDrawY = lerp(mExpandedDrawY, mCollapsedDrawY, fraction, mPositionInterpolator); setInterpolatedTextSize(lerp(mExpandedTextSize, mCollapsedTextSize, fraction, mTextSizeInterpolator)); if (mCollapsedTextColor != mExpandedTextColor) { // If the collapsed and expanded text colors are different, blend them based on the // fraction mTextPaint.setColor(blendColors(mExpandedTextColor, mCollapsedTextColor, fraction)); } else { mTextPaint.setColor(mCollapsedTextColor); } mTextPaint.setShadowLayer( lerp(mExpandedShadowRadius, mCollapsedShadowRadius, fraction, null), lerp(mExpandedShadowDx, mCollapsedShadowDx, fraction, null), lerp(mExpandedShadowDy, mCollapsedShadowDy, fraction, null), blendColors(mExpandedShadowColor, mCollapsedShadowColor, fraction)); ViewCompat.postInvalidateOnAnimation(mView); } private void calculateBaseOffsets() { final float currentTextSize = mCurrentTextSize; // We then calculate the collapsed text size, using the same logic calculateUsingTextSize(mCollapsedTextSize); float width = mTextToDraw != null ? mTextPaint.measureText(mTextToDraw, 0, mTextToDraw.length()) : 0; final int collapsedAbsGravity = GravityCompat.getAbsoluteGravity(mCollapsedTextGravity, mIsRtl ? ViewCompat.LAYOUT_DIRECTION_RTL : ViewCompat.LAYOUT_DIRECTION_LTR); switch (collapsedAbsGravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.BOTTOM: mCollapsedDrawY = mCollapsedBounds.bottom; break; case Gravity.TOP: mCollapsedDrawY = mCollapsedBounds.top - mTextPaint.ascent(); break; case Gravity.CENTER_VERTICAL: default: float textHeight = mTextPaint.descent() - mTextPaint.ascent(); float textOffset = (textHeight / 2) - mTextPaint.descent(); mCollapsedDrawY = mCollapsedBounds.centerY() + textOffset; break; } switch (collapsedAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: mCollapsedDrawX = mCollapsedBounds.centerX() - (width / 2); break; case Gravity.RIGHT: mCollapsedDrawX = mCollapsedBounds.right - width; break; case Gravity.LEFT: default: mCollapsedDrawX = mCollapsedBounds.left; break; } calculateUsingTextSize(mExpandedTextSize); width = mTextToDraw != null ? mTextPaint.measureText(mTextToDraw, 0, mTextToDraw.length()) : 0; final int expandedAbsGravity = GravityCompat.getAbsoluteGravity(mExpandedTextGravity, mIsRtl ? ViewCompat.LAYOUT_DIRECTION_RTL : ViewCompat.LAYOUT_DIRECTION_LTR); switch (expandedAbsGravity & Gravity.VERTICAL_GRAVITY_MASK) { case Gravity.BOTTOM: mExpandedDrawY = mExpandedBounds.bottom; break; case Gravity.TOP: mExpandedDrawY = mExpandedBounds.top - mTextPaint.ascent(); break; case Gravity.CENTER_VERTICAL: default: float textHeight = mTextPaint.descent() - mTextPaint.ascent(); float textOffset = (textHeight / 2) - mTextPaint.descent(); mExpandedDrawY = mExpandedBounds.centerY() + textOffset; break; } switch (expandedAbsGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: mExpandedDrawX = mExpandedBounds.centerX() - (width / 2); break; case Gravity.RIGHT: mExpandedDrawX = mExpandedBounds.right - width; break; case Gravity.LEFT: default: mExpandedDrawX = mExpandedBounds.left; break; } // The bounds have changed so we need to clear the texture clearTexture(); // Now reset the text size back to the original setInterpolatedTextSize(currentTextSize); } private void interpolateBounds(float fraction) { mCurrentBounds.left = lerp(mExpandedBounds.left, mCollapsedBounds.left, fraction, mPositionInterpolator); mCurrentBounds.top = lerp(mExpandedDrawY, mCollapsedDrawY, fraction, mPositionInterpolator); mCurrentBounds.right = lerp(mExpandedBounds.right, mCollapsedBounds.right, fraction, mPositionInterpolator); mCurrentBounds.bottom = lerp(mExpandedBounds.bottom, mCollapsedBounds.bottom, fraction, mPositionInterpolator); } public void draw(Canvas canvas) { final int saveCount = canvas.save(); if (mTextToDraw != null && mDrawTitle) { float x = mCurrentDrawX; float y = mCurrentDrawY; final boolean drawTexture = mUseTexture && mExpandedTitleTexture != null; final float ascent; final float descent; // Update the TextPaint to the current text size mTextPaint.setTextSize(mCurrentTextSize); if (drawTexture) { ascent = mTextureAscent * mScale; descent = mTextureDescent * mScale; } else { ascent = mTextPaint.ascent() * mScale; descent = mTextPaint.descent() * mScale; } if (DEBUG_DRAW) { // Just a debug tool, which drawn a Magneta rect in the text bounds canvas.drawRect(mCurrentBounds.left, y + ascent, mCurrentBounds.right, y + descent, DEBUG_DRAW_PAINT); } if (drawTexture) { y += ascent; } if (mScale != 1f) { canvas.scale(mScale, mScale, x, y); } if (drawTexture) { // If we should use a texture, draw it instead of text canvas.drawBitmap(mExpandedTitleTexture, x, y, mTexturePaint); } else { canvas.drawText(mTextToDraw, 0, mTextToDraw.length(), x, y, mTextPaint); } } canvas.restoreToCount(saveCount); } private boolean calculateIsRtl(CharSequence text) { final boolean defaultIsRtl = ViewCompat.getLayoutDirection(mView) == ViewCompat.LAYOUT_DIRECTION_RTL; return (defaultIsRtl ? TextDirectionHeuristicsCompat.FIRSTSTRONG_RTL : TextDirectionHeuristicsCompat.FIRSTSTRONG_LTR).isRtl(text, 0, text.length()); } private void setInterpolatedTextSize(float textSize) { calculateUsingTextSize(textSize); // Use our texture if the scale isn't 1.0 mUseTexture = USE_SCALING_TEXTURE && mScale != 1f; if (mUseTexture) { // Make sure we have an expanded texture if needed ensureExpandedTexture(); } ViewCompat.postInvalidateOnAnimation(mView); } private void calculateUsingTextSize(final float textSize) { if (mText == null) return; final float availableWidth; final float newTextSize; boolean updateDrawText = false; if (isClose(textSize, mCollapsedTextSize)) { availableWidth = mCollapsedBounds.width(); newTextSize = mCollapsedTextSize; mScale = 1f; if (mCurrentTypeface != mCollapsedTypeface) { mCurrentTypeface = mCollapsedTypeface; updateDrawText = true; } } else { availableWidth = mExpandedBounds.width(); newTextSize = mExpandedTextSize; if (mCurrentTypeface != mExpandedTypeface) { mCurrentTypeface = mExpandedTypeface; updateDrawText = true; } if (isClose(textSize, mExpandedTextSize)) { // If we're close to the expanded text size, snap to it and use a scale of 1 mScale = 1f; } else { // Else, we'll scale down from the expanded text size mScale = textSize / mExpandedTextSize; } } if (availableWidth > 0) { updateDrawText = (mCurrentTextSize != newTextSize) || mBoundsChanged || updateDrawText; mCurrentTextSize = newTextSize; mBoundsChanged = false; } if (mTextToDraw == null || updateDrawText) { mTextPaint.setTextSize(mCurrentTextSize); mTextPaint.setTypeface(mCurrentTypeface); // If we don't currently have text to draw, or the text size has changed, ellipsize... final CharSequence title = TextUtils.ellipsize(mText, mTextPaint, availableWidth, TextUtils.TruncateAt.END); if (!TextUtils.equals(title, mTextToDraw)) { mTextToDraw = title; mIsRtl = calculateIsRtl(mTextToDraw); } } } private void ensureExpandedTexture() { if (mExpandedTitleTexture != null || mExpandedBounds.isEmpty() || TextUtils.isEmpty(mTextToDraw)) { return; } calculateOffsets(0f); mTextureAscent = mTextPaint.ascent(); mTextureDescent = mTextPaint.descent(); final int w = Math.round(mTextPaint.measureText(mTextToDraw, 0, mTextToDraw.length())); final int h = Math.round(mTextureDescent - mTextureAscent); if (w <= 0 && h <= 0) { return; // If the width or height are 0, return } mExpandedTitleTexture = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(mExpandedTitleTexture); c.drawText(mTextToDraw, 0, mTextToDraw.length(), 0, h - mTextPaint.descent(), mTextPaint); if (mTexturePaint == null) { // Make sure we have a paint mTexturePaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG); } } public void recalculate() { if (mView.getHeight() > 0 && mView.getWidth() > 0) { // If we've already been laid out, calculate everything now otherwise we'll wait // until a layout calculateBaseOffsets(); calculateCurrentOffsets(); } } /** * Set the title to display * * @param text */ void setText(CharSequence text) { if (text == null || !text.equals(mText)) { mText = text; mTextToDraw = null; clearTexture(); recalculate(); } } CharSequence getText() { return mText; } private void clearTexture() { if (mExpandedTitleTexture != null) { mExpandedTitleTexture.recycle(); mExpandedTitleTexture = null; } } /** * Returns true if {@code value} is 'close' to it's closest decimal value. Close is currently * defined as it's difference being < 0.001. */ private static boolean isClose(float value, float targetValue) { return Math.abs(value - targetValue) < 0.001f; } int getExpandedTextColor() { return mExpandedTextColor; } int getCollapsedTextColor() { return mCollapsedTextColor; } /** * Blend {@code color1} and {@code color2} using the given ratio. * * @param ratio of which to blend. 0.0 will return {@code color1}, 0.5 will give an even blend, * 1.0 will return {@code color2}. */ private static int blendColors(int color1, int color2, float ratio) { final float inverseRatio = 1f - ratio; float a = (Color.alpha(color1) * inverseRatio) + (Color.alpha(color2) * ratio); float r = (Color.red(color1) * inverseRatio) + (Color.red(color2) * ratio); float g = (Color.green(color1) * inverseRatio) + (Color.green(color2) * ratio); float b = (Color.blue(color1) * inverseRatio) + (Color.blue(color2) * ratio); return Color.argb((int) a, (int) r, (int) g, (int) b); } private static float lerp(float startValue, float endValue, float fraction, Interpolator interpolator) { if (interpolator != null) { fraction = interpolator.getInterpolation(fraction); } return AnimationUtils.lerp(startValue, endValue, fraction); } private static boolean rectEquals(Rect r, int left, int top, int right, int bottom) { return !(r.left != left || r.top != top || r.right != right || r.bottom != bottom); } }
{ "content_hash": "aa027431b824d832077fdd8fca8843d5", "timestamp": "", "source": "github", "line_count": 638, "max_line_length": 100, "avg_line_length": 35.822884012539184, "alnum_prop": 0.6234521986436229, "repo_name": "doubleDragon/DdDesign", "id": "d051c34d82b0668884f148a715b85bcb8955f5fa", "size": "22855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/src/main/java/com/wsl/library/design/CollapsingTextHelper.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "416932" } ], "symlink_target": "" }
#ifndef __QS_H__ #define __QS_H__ #include <qsconfig.h> #include <qswce.h> #include <windows.h> #include <memory> typedef SSIZE_T ssize_t; namespace qs { /**************************************************************************** * * Exceptions * */ #ifdef QS_EXCEPTION //# define QNOTHROW() throw() # define QNOTHROW() # define QTRY try # define QCATCH_ALL() catch(...) # define QTHROW_BADALLOC() throw(std::bad_alloc()) #else # define QNOTHROW() # define QTRY if (true) # define QCATCH_ALL() else # define QTHROW_BADALLOC() ::TerminateProcess(::GetCurrentProcess(), -1) #endif /**************************************************************************** * * Instance * */ /** * Get instance handle of exe. * * @return Instance handle of exe. */ QSEXPORTPROC HINSTANCE getInstanceHandle(); /** * Get instance handle of dll. * * @return Instance handle of dll. */ QSEXPORTPROC HINSTANCE getDllInstanceHandle(); /** * Get instance handle of resource dll. * * @return Instance handle of resource dll. */ QSEXPORTPROC HINSTANCE getResourceDllInstanceHandle(); /** * Load resource dll associated with the specified instance. * * @Param hInst Instance handle. * @return Instance handle of resource dll if loaded, hInst otherwise. */ QSEXPORTPROC HINSTANCE loadResourceDll(HINSTANCE hInst); /**************************************************************************** * * Window * */ class Window; class ModalHandler; /** * Get main window. * * @return Main window. */ QSEXPORTPROC Window* getMainWindow(); /** * Set main window. */ QSEXPORTPROC void setMainWindow(Window* pWindow); /** * Get title. * * @return Title. */ QSEXPORTPROC const WCHAR* getTitle(); /**************************************************************************** * * memory management * */ QSEXPORTPROC void* allocate(size_t nSize); QSEXPORTPROC void deallocate(void* p); QSEXPORTPROC void* reallocate(void* p, size_t nSize); /**************************************************************************** * * misc * */ #ifdef _WIN32_WCE # define WCE_T(x) L##x #else # define WCE_T(x) x #endif #if _MSC_VER < 1300 # define for if (false); else for #endif /** * Get system encoding. * * @return System encoding. */ QSEXPORTPROC const WCHAR* getSystemEncoding(); #define countof(x) (sizeof(x)/sizeof(x[0])) #define endof(x) ((x) + countof(x)) #if _STLPORT_VERSION >= 0x450 && (!defined _WIN32_WCE || _STLPORT_VERSION < 0x460) # define QSMIN min # define QSMAX max #else # define QSMIN std::min # define QSMAX std::max #endif } #endif // __QS_H__
{ "content_hash": "0e2087c936e47e401c31ba84d83edbcd", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 82, "avg_line_length": 18.278145695364238, "alnum_prop": 0.538768115942029, "repo_name": "snakamura/q3", "id": "979acc9da8b89c0251903733744a266e76943666", "size": "2828", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "q3/qs/include/qs.h", "mode": "33188", "license": "mit", "language": [ { "name": "Awk", "bytes": "618" }, { "name": "C", "bytes": "3186350" }, { "name": "C++", "bytes": "16096149" }, { "name": "CSS", "bytes": "1715" }, { "name": "JavaScript", "bytes": "7641" }, { "name": "Objective-C", "bytes": "5104" }, { "name": "PHP", "bytes": "70687" }, { "name": "Perl", "bytes": "19009" }, { "name": "Python", "bytes": "95" }, { "name": "R", "bytes": "964615" }, { "name": "Ruby", "bytes": "84" }, { "name": "Shell", "bytes": "11621" } ], "symlink_target": "" }
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require File.expand_path(File.dirname(__FILE__) + '/../lib/pedump') # uploaded by someone: https://pedump.me/1cfd896e77173e512e1627804e03317a/ describe "corkami/manyimportsW7.v2.exe" do before :all do @sample = sample end it "should have 2 imports" do @sample.imports.size.should == 3 @sample.imports.map(&:module_name).should == ["kernel32.dll", "msvcrt.dll", "<\x11"] @sample.imports.map do |iid| (iid.original_first_thunk + iid.first_thunk).uniq.map(&:name) end.flatten[0,2].should == ["ExitProcess", "printf"] end it "should have 1 TLS" do @sample.tls.size.should == 1 @sample.tls.first.AddressOfIndex.should == 0x501148 @sample.tls.first.AddressOfCallBacks.should == 0x401080 end end
{ "content_hash": "f74fb6e4a7c51711706c7eb3b38d04d9", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 88, "avg_line_length": 35.130434782608695, "alnum_prop": 0.681930693069307, "repo_name": "zed-0xff/pedump", "id": "49fee47262a538c485c6607696d539e29de464fd", "size": "824", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/manyimportsW7_v2_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "40989" }, { "name": "Makefile", "bytes": "68" }, { "name": "Ruby", "bytes": "279154" } ], "symlink_target": "" }
#pragma once #ifdef __cplusplus extern "C" { /* C-declarations for C++ */ #endif void lv_draw_preHeat(); void lv_clear_preHeat(); void disp_temp_type(); void disp_step_heat(); void disp_desire_temp(); #ifdef __cplusplus } /* C-declarations for C++ */ #endif
{ "content_hash": "2045cfa91515340e6c00371e392af027", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 43, "avg_line_length": 16.625, "alnum_prop": 0.6541353383458647, "repo_name": "limtbk/3dprinting", "id": "2993a95f0092a9bdb49ca6e401d9a8faa8eb559f", "size": "1127", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Firmware/src/Marlin/src/lcd/extui/mks_ui/draw_preHeat.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "16427042" }, { "name": "C++", "bytes": "1508812" }, { "name": "Makefile", "bytes": "58317" }, { "name": "Objective-C", "bytes": "195319" }, { "name": "Processing", "bytes": "407203" }, { "name": "Python", "bytes": "11892" }, { "name": "Scilab", "bytes": "10211" } ], "symlink_target": "" }
package org.apache.jackrabbit.mk.concurrent; import junit.framework.Assert; import org.apache.jackrabbit.mk.util.Cache; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; /** * Tests the cache implementation. */ public class ConcurrentCacheTest implements Cache.Backend<Integer, ConcurrentCacheTest.Data> { Cache<Integer, Data> cache = Cache.newInstance(this, 5); AtomicInteger counter = new AtomicInteger(); volatile int value; @Test public void test() throws Exception { Concurrent.run("cache", new Concurrent.Task() { @Override public void call() throws Exception { int k = value++ % 10; Data v = cache.get(k); Assert.assertEquals(k, v.value); } }); } @Override public Data load(Integer key) { int start = counter.get(); try { Thread.sleep(1); } catch (InterruptedException e) { // ignore } if (counter.getAndIncrement() != start) { throw new AssertionError("Concurrent load"); } return new Data(key); } static class Data implements Cache.Value { int value; Data(int value) { this.value = value; } @Override public int getMemory() { return 1; } } }
{ "content_hash": "e59432b2547d80ac9f150f875811528f", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 94, "avg_line_length": 23.661016949152543, "alnum_prop": 0.5723495702005731, "repo_name": "tteofili/jackrabbit-oak", "id": "200e9e89b4fd53bf94d2dcfea213957deb33a33a", "size": "2197", "binary": false, "copies": "1", "ref": "refs/heads/0.6", "path": "oak-mk/src/test/java/org/apache/jackrabbit/mk/concurrent/ConcurrentCacheTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2921" }, { "name": "Java", "bytes": "5278180" }, { "name": "JavaScript", "bytes": "2821" }, { "name": "Shell", "bytes": "6571" } ], "symlink_target": "" }
""" Originally from: http://github.com/jacobian/munin-plugins/blob/master/munin.py Microframework for writing Munin plugins with Python. Howto: * Subclass ``Plugin``. * Define at least ``fetch`` and ``config``, and possibly others (see below). * Add a main invocation to your script. A simple example:: import munin class Load(munin.Plugin): def fetch(self): load1, load5, load15 = open("/proc/loadavg").split(' ')[:3] return [ ("load1.value", load1), ("load5.value", load5), ("load15.value", load15) ] def config(self): return [ ("graph_title", "Load"), ("graph_args", "-l 0 --base 1000"), ("graph_vlabel", "Load"), ("load1.label", "1 min"), ("load5.label", "5 min"), ("load15.label", "15 min") ] if __name__ == '__main__': munin.run(Load) For more complex uses, read the code. It's short. """ import os import sys class Plugin(object): def __init__(self): self.env = {} for var, default in self.__get_dynamic_attr("env_vars", None, {}).items(): self.env[var] = os.environ.get(var, default) def __get_dynamic_attr(self, attname, arg, default=None): """ Gets "something" from self, which could be an attribute or a callable with either 0 or 1 arguments (besides self). Stolen from django.contrib.syntication.feeds.Feed. """ try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check func_code.co_argcount rather than try/excepting the # function and catching the TypeError, because something inside # the function may raise the TypeError. This technique is more # accurate. if hasattr(attr, 'func_code'): argcount = attr.func_code.co_argcount else: argcount = attr.__call__.func_code.co_argcount if argcount == 2: # one argument is 'self' return attr(arg) else: return attr() return attr def main(self, argv): if "_" in argv[0]: _, arg = argv[0].rsplit("_", 1) else: arg = None args = argv[1:] if "suggest" in args and hasattr(self, "suggest"): for suggested in self.__get_dynamic_attr("suggest", arg): print suggested return 0 if "autoconf" in args: if self.__get_dynamic_attr("autoconf", arg, True): print "yes" return 0 else: print "no" return 1 if "config" in args: for field, value in self.__get_dynamic_attr("config", arg, []): print "%s %s" % (field, value) return 0 for field, value in self.__get_dynamic_attr("fetch", arg, []): print "%s %s" % (field, value) return 0 def run(plugin): if callable(plugin): plugin = plugin() sys.exit(plugin.main(sys.argv))
{ "content_hash": "5b08f493bb61396b042e01c63b2f0034", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 82, "avg_line_length": 29.946902654867255, "alnum_prop": 0.49379432624113473, "repo_name": "ericholscher/django-kong", "id": "e9c569765a12dde3daf80b3ebf3cde9651d49075", "size": "3384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kong/plugins/munin.py", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "17262" }, { "name": "Python", "bytes": "30117" }, { "name": "Shell", "bytes": "179" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <book id="HAG" singlevoice="false" pageheader="Haggai"> <block style="mt" chapter="0" book="HAG" initialStartVerse="0" characterId="BC-HAG"> <text>Haggai</text> </block> <block style="c" paragraphStart="true" chapter="1" book="HAG" initialStartVerse="0" characterId="BC-HAG"> <text>1</text> </block> <block style="p" chapter="1" initialStartVerse="1" characterId="narrator-HAG"> <verse num="1" /> <text>In the second year of Darius the king, in the sixth month, in the first day of the month, Yahweh’s word came by Haggai, the prophet, to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, saying,</text> </block> <block style="p" chapter="1" initialStartVerse="2" characterId="Haggai"> <verse num="2" /> <text>«This is what Yahweh of Armies says: These people say, ‹The time hasn’t yet come, the time for Yahweh’s house to be built.› »</text> </block> <block style="p" chapter="1" initialStartVerse="3" characterId="narrator-HAG"> <verse num="3" /> <text>Then Yahweh’s word came by Haggai, the prophet, saying,</text> </block> <block style="p" chapter="1" initialStartVerse="4" characterId="God"> <verse num="4" /> <text>«Is it a time for you yourselves to dwell in your paneled houses, while this house lies waste?</text> </block> <block style="p" chapter="1" initialStartVerse="5" characterId="God"> <verse num="5" /> <text>Now therefore this is what Yahweh of Armies says:</text> </block> <block style="p" chapter="1" initialStartVerse="6" characterId="God"> <verse num="6" /> <text>You have sown much, and bring in little. You eat, but you don’t have enough. You drink, but you aren’t filled with drink. You clothe yourselves, but no one is warm, and he who earns wages earns wages to put them into a bag with holes in it.»</text> </block> <block style="p" chapter="1" initialStartVerse="7" characterId="narrator-HAG"> <verse num="7" /> <text>This is what Yahweh of Armies says:</text> </block> <block style="p" chapter="1" initialStartVerse="7" characterId="God"> <text>«Consider your ways.</text> </block> <block style="p" chapter="1" initialStartVerse="8" characterId="God"> <verse num="8" /> <text>Go up to the mountain, bring wood, and build the house. I will take pleasure in it, and I will be glorified,»</text> </block> <block style="p" chapter="1" initialStartVerse="8" characterId="narrator-HAG"> <text>says Yahweh.</text> </block> <block style="p" chapter="1" initialStartVerse="9" characterId="God"> <verse num="9" /> <text>«You looked for much, and, behold, it came to little; and when you brought it home, I blew it away. Why?»</text> </block> <block style="p" chapter="1" initialStartVerse="9" characterId="narrator-HAG"> <text>says Yahweh of Armies,</text> </block> <block style="p" chapter="1" initialStartVerse="9" characterId="God"> <text>«Because of my house that lies waste, while each of you is busy with his own house.</text> </block> <block style="p" chapter="1" initialStartVerse="10" characterId="God"> <verse num="10" /> <text>Therefore for your sake the heavens withhold the dew, and the earth withholds its fruit.</text> </block> <block style="p" chapter="1" initialStartVerse="11" characterId="God"> <verse num="11" /> <text>I called for a drought on the land, on the mountains, on the grain, on the new wine, on the oil, on that which the ground produces, on men, on livestock, and on all the labor of the hands.»</text> </block> <block style="p" chapter="1" initialStartVerse="12" characterId="narrator-HAG"> <verse num="12" /> <text>Then Zerubbabel, the son of Shealtiel, and Joshua, the son of Jehozadak, the high priest, with all the remnant of the people, obeyed Yahweh their God’s voice, and the words of Haggai the prophet, as Yahweh, their God, had sent him; and the people feared Yahweh.</text> </block> <block style="p" chapter="1" initialStartVerse="13" characterId="narrator-HAG"> <verse num="13" /> <text>Then Haggai, Yahweh’s messenger, spoke Yahweh’s message to the people, saying,</text> </block> <block style="p" chapter="1" initialStartVerse="13" characterId="God"> <text>«I am with you,»</text> </block> <block style="p" chapter="1" initialStartVerse="13" characterId="narrator-HAG"> <text>says Yahweh.</text> </block> <block style="p" chapter="1" initialStartVerse="14" characterId="narrator-HAG"> <verse num="14" /> <text>Yahweh stirred up the spirit of Zerubbabel, the son of Shealtiel, governor of Judah, and the spirit of Joshua, the son of Jehozadak, the high priest, and the spirit of all the remnant of the people; and they came and worked on the house of Yahweh of Armies, their God,</text> </block> <block style="p" chapter="1" initialStartVerse="15" characterId="narrator-HAG"> <verse num="15" /> <text>in the twenty-fourth day of the month, in the sixth month, in the second year of Darius the king.</text> </block> <block style="c" paragraphStart="true" chapter="2" book="HAG" initialStartVerse="0" characterId="BC-HAG"> <text>2</text> </block> <block style="p" chapter="2" initialStartVerse="1" characterId="narrator-HAG"> <verse num="1" /> <text>In the seventh month, in the twenty-first day of the month, Yahweh’s word came by Haggai the prophet, saying,</text> </block> <block style="p" chapter="2" initialStartVerse="2" characterId="God"> <verse num="2" /> <text>«Speak now to Zerubbabel, the son of Shealtiel, governor of Judah, and to Joshua, the son of Jehozadak, the high priest, and to the remnant of the people, saying,</text> </block> <block style="p" chapter="2" initialStartVerse="3" characterId="God"> <verse num="3" /> <text>‹Who is left among you who saw this house in its former glory? How do you see it now? Isn’t it in your eyes as nothing?</text> </block> <block style="p" chapter="2" initialStartVerse="4" characterId="God"> <verse num="4" /> <text>Yet now be strong, Zerubbabel,› says Yahweh. ‹Be strong, Joshua, son of Jehozadak, the high priest. Be strong, all you people of the land,› says Yahweh, ‹and work, for I am with you,› says Yahweh of Armies.</text> </block> <block style="p" chapter="2" initialStartVerse="5" characterId="God"> <verse num="5" /> <text>This is the word that I covenanted with you when you came out of Egypt, and my Spirit lived among you. ‹Don’t be afraid.›</text> </block> <block style="p" chapter="2" initialStartVerse="6" characterId="God"> <verse num="6" /> <text>For this is what Yahweh of Armies says: ‹Yet once, it is a little while, and I will shake the heavens, the earth, the sea, and the dry land;</text> </block> <block style="p" chapter="2" initialStartVerse="7" characterId="God"> <verse num="7" /> <text>and I will shake all nations. The precious things of all nations will come, and I will fill this house with glory, says Yahweh of Armies.</text> </block> <block style="p" chapter="2" initialStartVerse="8" characterId="God"> <verse num="8" /> <text>The silver is mine, and the gold is mine,› says Yahweh of Armies.</text> </block> <block style="p" chapter="2" initialStartVerse="9" characterId="God"> <verse num="9" /> <text>‹The latter glory of this house will be greater than the former,› says Yahweh of Armies; ‹and in this place I will give peace,› says Yahweh of Armies.»</text> </block> <block style="p" chapter="2" initialStartVerse="10" characterId="narrator-HAG"> <verse num="10" /> <text>In the twenty-fourth day of the ninth month, in the second year of Darius, Yahweh’s word came by Haggai the prophet, saying,</text> </block> <block style="p" chapter="2" initialStartVerse="11" characterId="Haggai"> <verse num="11" /> <text>«Yahweh of Armies says: Ask now the priests concerning the law, saying,</text> </block> <block style="p" chapter="2" initialStartVerse="12" characterId="Haggai"> <verse num="12" /> <text>‹If someone carries holy meat in the fold of his garment, and with his fold touches bread, stew, wine, oil, or any food, will it become holy?› »</text> </block> <block style="p" chapter="2" initialStartVerse="12" characterId="narrator-HAG"> <text>The priests answered,</text> </block> <block style="p" chapter="2" initialStartVerse="12" characterId="priests"> <text>«No.»</text> </block> <block style="p" chapter="2" initialStartVerse="13" characterId="narrator-HAG"> <verse num="13" /> <text>Then Haggai said,</text> </block> <block style="p" chapter="2" initialStartVerse="13" characterId="Haggai"> <text>«If one who is unclean by reason of a dead body touch any of these, will it be unclean?»</text> </block> <block style="p" chapter="2" initialStartVerse="13" characterId="narrator-HAG"> <text>The priests answered,</text> </block> <block style="p" chapter="2" initialStartVerse="13" characterId="priests"> <text>«It will be unclean.»</text> </block> <block style="p" chapter="2" initialStartVerse="14" characterId="narrator-HAG"> <verse num="14" /> <text>Then Haggai answered,</text> </block> <block style="p" chapter="2" initialStartVerse="14" characterId="Haggai"> <text>« ‹So is this people, and so is this nation before me,› says Yahweh; ‹and so is every work of their hands. That which they offer there is unclean.</text> </block> <block style="p" chapter="2" initialStartVerse="15" characterId="Haggai"> <verse num="15" /> <text>Now, please consider from this day and backward, before a stone was laid on a stone in Yahweh’s temple.</text> </block> <block style="p" chapter="2" initialStartVerse="16" characterId="Haggai"> <verse num="16" /> <text>Through all that time, when one came to a heap of twenty measures, there were only ten. When one came to the wine vat to draw out fifty, there were only twenty.</text> </block> <block style="p" chapter="2" initialStartVerse="17" characterId="Haggai"> <verse num="17" /> <text>I struck you with blight, mildew, and hail in all the work of your hands; yet you didn’t turn to me,› says Yahweh.</text> </block> <block style="p" chapter="2" initialStartVerse="18" characterId="Haggai"> <verse num="18" /> <text>‹Consider, please, from this day and backward, from the twenty-fourth day of the ninth month, since the day that the foundation of Yahweh’s temple was laid, consider it.</text> </block> <block style="p" chapter="2" initialStartVerse="19" characterId="Haggai"> <verse num="19" /> <text>Is the seed yet in the barn? Yes, the vine, the fig tree, the pomegranate, and the olive tree haven’t produced. From today I will bless you.› »</text> </block> <block style="p" chapter="2" initialStartVerse="20" characterId="narrator-HAG"> <verse num="20" /> <text>Yahweh’s word came the second time to Haggai in the twenty-fourth day of the month, saying,</text> </block> <block style="p" chapter="2" initialStartVerse="21" characterId="God"> <verse num="21" /> <text>«Speak to Zerubbabel, governor of Judah, saying, ‹I will shake the heavens and the earth.</text> </block> <block style="p" chapter="2" initialStartVerse="22" characterId="God"> <verse num="22" /> <text>I will overthrow the throne of kingdoms. I will destroy the strength of the kingdoms of the nations. I will overthrow the chariots, and those who ride in them. The horses and their riders will come down, everyone by the sword of his brother.</text> </block> <block style="p" chapter="2" initialStartVerse="23" characterId="God"> <verse num="23" /> <text>In that day, says Yahweh of Armies, I will take you, Zerubbabel, my servant, the son of Shealtiel,› says Yahweh, ‹and will make you as a signet, for I have chosen you,› says Yahweh of Armies.»</text> </block> <UnappliedSplits /> </book>
{ "content_hash": "0be6438cf425dc747605194526ae3840", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 285, "avg_line_length": 59.93532338308458, "alnum_prop": 0.6853158462687806, "repo_name": "sillsdev/Glyssen", "id": "f002152e7ec992d09f30c72088d8897cc65c8d6a", "size": "12173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DistFiles/reference_texts/English/HAG.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4485" }, { "name": "C#", "bytes": "4447393" }, { "name": "CSS", "bytes": "1703" }, { "name": "HTML", "bytes": "5577" }, { "name": "TeX", "bytes": "77425" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Collections.ObjectModel; namespace API.Areas.HelpPage.ModelDescriptions { public class EnumTypeModelDescription : ModelDescription { public EnumTypeModelDescription() { Values = new Collection<EnumValueDescription>(); } public Collection<EnumValueDescription> Values { get; private set; } } }
{ "content_hash": "92207da6368a4ab97652988b16656734", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 76, "avg_line_length": 26.466666666666665, "alnum_prop": 0.7027707808564232, "repo_name": "sgermosen/TorneoPredicciones", "id": "6254ac269ed56c388da60658a9d6ef13c2adcdab", "size": "397", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "_Legacy/Backend/API/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP.NET", "bytes": "390" }, { "name": "C#", "bytes": "1383561" }, { "name": "CSS", "bytes": "18071" }, { "name": "HTML", "bytes": "493527" }, { "name": "JavaScript", "bytes": "1216080" }, { "name": "Less", "bytes": "8374" }, { "name": "TSQL", "bytes": "23484" } ], "symlink_target": "" }
package awslabs.lab31; import java.util.List; import com.amazonaws.services.sns.AmazonSNSClient; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.Message; /** * ƒvƒƒWƒFƒNƒgt: Lab3.1 */ public interface ILabCode { String createQueue(AmazonSQSClient sqsClient, String queueName); String getQueueArn(AmazonSQSClient sqsClient, String queueUrl); String createTopic(AmazonSNSClient snsClient, String topicName); void createSubscription(AmazonSNSClient snsClient, String queueArn, String topicArn); void publishTopicMessage(AmazonSNSClient snsClient, String topicArn, String subject, String message); void postToQueue(AmazonSQSClient sqsClient, String queueUrl, String messageText); List<Message> readMessages(AmazonSQSClient sqsClient, String queueUrl); void removeMessage(AmazonSQSClient sqsClient, String queueUrl, String receiptHandle); void deleteSubscriptions(AmazonSNSClient snsClient, String topicArn); void deleteTopic(AmazonSNSClient snsClient, String topicArn); void deleteQueue(AmazonSQSClient sqsClient, String queueUrl); }
{ "content_hash": "0d997efed14b1033c67eedbe4b8f29a7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 102, "avg_line_length": 43.64, "alnum_prop": 0.8249312557286893, "repo_name": "aws-jp-trainers/devonaws-labs-java-master-jp", "id": "8caeb0b790fd1d51950adccc325ae388a7544b37", "size": "1668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lab3.1/src/awslabs/lab31/ILabCode.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "888" }, { "name": "Java", "bytes": "150756" } ], "symlink_target": "" }
package reader import ( "bufio" "compress/gzip" "errors" "fmt" "io" "net" "net/http" "sync/atomic" "time" "github.com/qiniu/log" "github.com/qiniu/logkit/conf" "github.com/qiniu/logkit/queue" "github.com/qiniu/logkit/utils" . "github.com/qiniu/logkit/utils/models" "github.com/labstack/echo" ) const ( KeyHttpServiceAddress = "http_service_address" KeyHttpServicePath = "http_service_path" DefaultHttpServiceAddress = ":4000" DefaultHttpServicePath = "/logkit/data" DefaultSyncEvery = 10 DefaultMaxBodySize = 100 * 1024 * 1024 DefaultMaxBytesPerFile = 500 * 1024 * 1024 DefaultWriteSpeedLimit = 10 * 1024 * 1024 // 默认写速限制为10MB ) type HttpReader struct { address string path string meta *Meta status int32 listener net.Listener bufQueue queue.BackendQueue readChan <-chan []byte } func NewHttpReader(meta *Meta, conf conf.MapConf) (*HttpReader, error) { address, _ := conf.GetStringOr(KeyHttpServiceAddress, DefaultHttpServiceAddress) path, _ := conf.GetStringOr(KeyHttpServicePath, DefaultHttpServicePath) address, _ = utils.RemoveHttpProtocal(address) bq := queue.NewDiskQueue("HttpReader<"+address+">_buffer", meta.BufFile(), DefaultMaxBytesPerFile, 0, DefaultMaxBytesPerFile, DefaultSyncEvery, DefaultSyncEvery, time.Second*2, DefaultWriteSpeedLimit, false, 0) err := utils.CreateDirIfNotExist(meta.BufFile()) if err != nil { return nil, err } readChan := bq.ReadChan() return &HttpReader{ address: address, path: path, meta: meta, bufQueue: bq, readChan: readChan, status: StatusInit, }, nil } func (h *HttpReader) Name() string { return "HttpReader<" + h.address + ">" } func (h *HttpReader) Source() string { return h.address } func (h *HttpReader) Start() error { if !atomic.CompareAndSwapInt32(&h.status, StatusInit, StatusRunning) { return fmt.Errorf("runner[%v] Reader[%v] already started", h.meta.RunnerName, h.Name()) } var err error r := echo.New() r.POST(h.path, h.postData()) if h.listener, err = net.Listen("tcp", h.address); err != nil { return err } server := &http.Server{ Handler: r, Addr: h.address, } go func() { server.Serve(h.listener) }() log.Infof("runner[%v] Reader[%v] has started and listener service on %v\n", h.meta.RunnerName, h.Name(), h.address) return nil } func (h *HttpReader) ReadLine() (data string, err error) { if atomic.LoadInt32(&h.status) == StatusInit { err = h.Start() if err != nil { log.Error(err) } } timer := time.NewTimer(time.Second) select { case dat := <-h.readChan: data = string(dat) case <-timer.C: } timer.Stop() return } func (h *HttpReader) SetMode(mode string, v interface{}) error { return fmt.Errorf("runner[%v] Reader[%v] not support read mode\n", h.meta.RunnerName, h.Name()) } func (h *HttpReader) Close() error { if atomic.CompareAndSwapInt32(&h.status, StatusRunning, StatusStopping) { log.Infof("Runner[%v] Reader[%v] stopping", h.meta.RunnerName, h.Name()) } else { h.bufQueue.Close() } if h.listener != nil { h.listener.Close() } return nil } func (h *HttpReader) SyncMeta() {} func (h *HttpReader) postData() echo.HandlerFunc { return func(c echo.Context) error { if err := h.pickUpData(c.Request()); err != nil { return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) } return c.JSON(http.StatusOK, nil) } } func (h *HttpReader) pickUpData(req *http.Request) (err error) { if req.ContentLength > DefaultMaxBodySize { return errors.New("the request body is too large") } reqBody := req.Body defer reqBody.Close() contentEncoding := req.Header.Get(ContentEncodingHeader) contentType := req.Header.Get(ContentTypeHeader) if contentEncoding == "gzip" || contentType == "application/gzip" { reqBody, err = gzip.NewReader(req.Body) if err != nil { return fmt.Errorf("read gzip body error %v", err) } } r := bufio.NewReader(reqBody) return h.storageData(r) } func (h *HttpReader) storageData(r *bufio.Reader) (err error) { for { line, err := h.readLine(r) if err != nil { if err != io.EOF { fmt.Errorf("runner[%v] Reader[%v] read data from http request error, %v\n", h.meta.RunnerName, h.Name(), err) } break } if line == "" { continue } h.bufQueue.Put([]byte(line)) } return } func (h *HttpReader) readLine(r *bufio.Reader) (str string, err error) { isPrefix := true var line, fragment []byte for isPrefix && err == nil { fragment, isPrefix, err = r.ReadLine() line = append(line, fragment...) } return string(line), err }
{ "content_hash": "dba6244632f6d9a8360b00aa3669dd65", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 116, "avg_line_length": 24.24468085106383, "alnum_prop": 0.6807810443176832, "repo_name": "andrewei1316/logkit", "id": "606977f1a78cd196ce94c16ccb07a730a665808c", "size": "4572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "reader/http_reader.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1875" }, { "name": "CSS", "bytes": "2293" }, { "name": "Go", "bytes": "1213844" }, { "name": "HTML", "bytes": "2747" }, { "name": "JavaScript", "bytes": "131185" }, { "name": "Makefile", "bytes": "238" }, { "name": "Shell", "bytes": "1418" } ], "symlink_target": "" }
/** * Created by jaboko on 16.04.15. */ /// <reference path="chai/chai.d.ts" /> declare module chai{ export function should(target: any, message?: string): Should; export function should(): Should; interface Should extends chai.LanguageChains, chai.NumericComparison, chai.TypeComparison, chai.Assertions { not: chai.Expect; deep: chai.Deep; a: chai.TypeComparison; an: chai.TypeComparison; include: chai.Include; contain: chai.Include; ok: chai.Expect; true: chai.Expect; false: chai.Expect; null: chai.Expect; undefined: chai.Expect; exist: chai.Expect; empty: chai.Expect; arguments: chai.Expect; Arguments: chai.Expect; equal: chai.Equal; equals: chai.Equal; eq: chai.Equal; eql: chai.Equal; eqls: chai.Equal; property: chai.Property; ownProperty: chai.OwnProperty; haveOwnProperty: chai.OwnProperty; length: chai.Length; lengthOf: chai.Length; match(RegularExpression: RegExp, message?: string): chai.Expect; string(string: string, message?: string): chai.Expect; keys: chai.Keys; key(string: string): chai.Expect; throw: chai.Throw; throws: chai.Throw; Throw: chai.Throw; respondTo(method: string, message?: string): chai.Expect; itself: chai.Expect; satisfy(matcher: Function, message?: string): chai.Expect; closeTo(expected: number, delta: number, message?: string): chai.Expect; members: chai.Members; } } declare var assert: chai.Assert; declare function expect(target: any, message?: string): chai.Expect; declare function should(target: any, message?: string): chai.Should; declare function should(): chai.Should;
{ "content_hash": "42b4b5d59c539d34f40321d168f8c669", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 112, "avg_line_length": 33.527272727272724, "alnum_prop": 0.6296095444685467, "repo_name": "jaboko/typescript-decorator-processor", "id": "8ab6fc10f17272c9648237bc7c1dc42209bdfef5", "size": "1844", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "typings/addon.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "18769" }, { "name": "TypeScript", "bytes": "20407" } ], "symlink_target": "" }
- Fixed an issue where the **ok_codes** argument was passed twice to the HTTP requuest.
{ "content_hash": "7b34c53f0d8a6b76703b0b0f77437925", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 87, "avg_line_length": 88, "alnum_prop": 0.75, "repo_name": "demisto/content", "id": "d8c150ea54b6255f21f09cccede2f341cd74bcb9", "size": "146", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Packs/AzureKubernetesServices/ReleaseNotes/1_0_2.md", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "2146" }, { "name": "HTML", "bytes": "205901" }, { "name": "JavaScript", "bytes": "1584075" }, { "name": "PowerShell", "bytes": "442288" }, { "name": "Python", "bytes": "47881712" }, { "name": "Rich Text Format", "bytes": "480911" }, { "name": "Shell", "bytes": "108066" }, { "name": "YARA", "bytes": "1185" } ], "symlink_target": "" }
<?php // Start session include_once("../lib/session_manager.php") ; include_once("../database/queries.php"); $objDB = new CQueryManager(CConfig::DB_AUDIO) ; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <title>Untitled Document</title> </head> <body> <HTML> <HEAD> <TITLE>Playlist Info</TITLE> <script language="javascript" type="text/javascript"> function OnRemovePlaylistElmt(pid, id, title, pageno) { if(confirm("Are you sure you want to remove audio : "+title+" ?" )) { window.location = "tab_manage_aud_rem_pl_elm.php?pid="+pid+"&pg="+pageno+"&id="+id; } } </script> </HEAD> <BODY> <FIELDSET> <?php include("../lib/utils.php") ; $url = CUtils::curPageURL() ; $query_str = parse_url($url); // will return array of url components. parse_str($query_str["query"]) ; // the query string will be parsed here. if(empty($pg)) { $pg = 1; } $objDB-> PreparePlaylistInfo($pid,$pg); ?> </FIELDSET> </BODY> </HTML> </body> </html>
{ "content_hash": "385cd2dd24e6119fee9e815e520097b1", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 102, "avg_line_length": 23.979591836734695, "alnum_prop": 0.6119148936170212, "repo_name": "mastishka/mgoos", "id": "932db09cfa3a11a04fd641b8f1384c86c61f2698", "size": "1175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iframe_pages/tab_manage_aud_playlist_info.php", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Alcatel-OT-802Y/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 ObigoInternetBrowser/Q05A</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Alcatel-OT-802Y/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 ObigoInternetBrowser/Q05A </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_device.yaml</small></td><td> </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-802Y</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Alcatel-OT-802Y/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 ObigoInternetBrowser/Q05A [family] => Alcatel OT-802Y [brand] => Alcatel [model] => OT-802Y ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Obigo Q 5.0</td><td> </td><td>JAVA </td><td style="border-left: 1px solid #555"></td><td></td><td>Mobile Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.025</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^.*obigointernetbrowser\/q05.*$/ [browser_name_pattern] => *obigointernetbrowser/q05* [parent] => Obigo Q 5.0 [comment] => Obigo Q 5.0 [browser] => Obigo Q [browser_type] => Browser [browser_bits] => 32 [browser_maker] => Obigo [browser_modus] => unknown [version] => 5.0 [majorver] => 5 [minorver] => 0 [platform] => JAVA [platform_version] => unknown [platform_description] => unknown [platform_bits] => 32 [platform_maker] => Oracle [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => 1 [iframes] => 1 [tables] => 1 [cookies] => 1 [backgroundsounds] => [javascript] => 1 [vbscript] => [javaapplets] => [activexcontrols] => [ismobiledevice] => 1 [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 1 [aolversion] => 0 [device_name] => general Mobile Phone [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => general Mobile Phone [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Obigo Q 5.0</td><td><i class="material-icons">close</i></td><td>JAVA </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.054</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^.*obigointernetbrowser\/q05.*$/ [browser_name_pattern] => *obigointernetbrowser/q05* [parent] => Obigo Q 5.0 [comment] => Obigo Q 5.0 [browser] => Obigo Q [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Obigo [browser_modus] => unknown [version] => 5.0 [majorver] => 5 [minorver] => 0 [platform] => JAVA [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => 1 [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Mobile Phone [device_pointing_method] => unknown [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Alcatel-OT-802Y 1.0</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => [browser] => Alcatel-OT-802Y [version] => 1.0 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>ObigoBrowser </td><td><i class="material-icons">close</i></td><td>JavaOS </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => ObigoBrowser [browserVersion] => [osName] => JavaOS [osVersion] => [deviceModel] => Alcatel [isMobile] => 1 [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Obigo </td><td><i class="material-icons">close</i></td><td>JVM </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-802Y</td><td>mobile-browser</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.20601</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 240 [is_mobile] => 1 [type] => mobile-browser [mobile_brand] => Alcatel [mobile_model] => OT-802Y [version] => [is_android] => [browser_name] => Obigo [operating_system_family] => JVM [operating_system_version] => [is_ios] => [producer] => Obigo Ltd [operating_system] => JVM (Platform Micro Edition) [mobile_screen_width] => 320 [mobile_browser] => Teleca-Obigo ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Obigo Q05A</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-802Y</td><td>smartphone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.006</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => Array ( [type] => browser [name] => Obigo [short_name] => OB [version] => Q05A [engine] => ) [operatingSystem] => Array ( ) [device] => Array ( [brand] => AL [brandName] => Alcatel [model] => OT-802Y [device] => 1 [deviceName] => smartphone ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => 1 [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => 1 [isTablet] => [isTV] => [isDesktop] => [isMobile] => 1 [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Obigo </td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-802Y</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => [minor] => [patch] => [family] => Obigo ) [os] => UAParser\Result\OperatingSystem Object ( [major] => [minor] => [patch] => [patchMinor] => [family] => Other ) [device] => UAParser\Result\Device Object ( [brand] => Alcatel [model] => OT-802Y [family] => Alcatel OT-802Y ) [originalUserAgent] => Alcatel-OT-802Y/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 ObigoInternetBrowser/Q05A ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Obigo 05</td><td> </td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Mobile</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => Alcatel [platform_version] => 802 [platform_type] => Mobile [browser_name] => Obigo [browser_version] => 05 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Obigo Browser </td><td> </td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.36702</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => [simple_sub_description_string] => [simple_browser_string] => Obigo Browser [browser_version] => [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => Array ( ) [layout_engine_name] => [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => obigo-browser [operating_system_version] => [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => [browser_capabilities] => Array ( [0] => MIDP v2.0 [1] => CLDC v1.1 ) [operating_platform_vendor_name] => [operating_system] => [operating_system_version_full] => [operating_platform_code] => [browser_name] => Obigo Browser [operating_system_name_code] => [user_agent] => Alcatel-OT-802Y/1.0 Profile/MIDP-2.0 Configuration/CLDC-1.1 ObigoInternetBrowser/Q05A [browser_version_full] => [browser] => Obigo Browser ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td>Obigo Q 5A</td><td> </td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>One Touch 802Y</td><td>mobile:feature</td><td>yes</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [name] => Obigo Q [version] => Array ( [value] => 5 [alias] => 5A ) [type] => browser ) [device] => Array ( [type] => mobile [subtype] => feature [manufacturer] => Alcatel [model] => One Touch 802Y ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Teleca Obigo Q05A</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555">Alcatel</td><td>OT-802Y</td><td>Feature Phone</td><td>yes</td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.019</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => false [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => false [is_largescreen] => false [is_mobile] => true [is_robot] => false [is_smartphone] => false [is_touchscreen] => false [is_wml_preferred] => false [is_xhtmlmp_preferred] => true [is_html_preferred] => false [advertised_device_os] => [advertised_device_os_version] => [advertised_browser] => Teleca Obigo [advertised_browser_version] => Q05A [complete_device_name] => Alcatel OT-802Y (Wave) [device_name] => Alcatel Wave [form_factor] => Feature Phone [is_phone] => true [is_app_webview] => false ) [all] => Array ( [brand_name] => Alcatel [model_name] => OT-802Y [unique] => true [ununiqueness_handler] => [is_wireless_device] => true [device_claims_web_support] => false [has_qwerty_keyboard] => false [can_skip_aligned_link_row] => true [uaprof] => http://www-ccpp.tcl-ta.com/files/ALCATEL-OT-802Y.rdf [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => [mobile_browser] => Teleca-Obigo [mobile_browser_version] => Q05 [device_os_version] => [pointing_method] => [release_date] => 2009_december [marketing_name] => Wave [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => true [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => true [softkey_support] => true [table_support] => true [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => true [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => true [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => true [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => wtai://wp/mc; [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => false [xhtml_honors_bgcolor] => false [xhtml_supports_forms_in_table] => false [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => false [xhtml_select_as_radiobutton] => false [xhtml_select_as_popup] => false [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => false [xhtml_supports_css_cell_table_coloring] => false [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => false [xhtml_document_title_support] => true [xhtml_preferred_charset] => utf8 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => tel: [xhtmlmp_preferred_mime_type] => application/vnd.wap.xhtml+xml [xhtml_table_support] => true [xhtml_send_sms_string] => none [xhtml_send_mms_string] => none [xhtml_file_upload] => not_supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => none [xhtml_avoid_accesskeys] => false [xhtml_can_embed_video] => none [ajax_support_javascript] => false [ajax_manipulate_css] => false [ajax_support_getelementbyid] => false [ajax_support_inner_html] => false [ajax_xhr_type] => none [ajax_manipulate_dom] => false [ajax_support_events] => false [ajax_support_event_listener] => false [ajax_preferred_geoloc_api] => none [xhtml_support_level] => 1 [preferred_markup] => html_wi_oma_xhtmlmp_1_0 [wml_1_1] => true [wml_1_2] => false [wml_1_3] => true [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => true [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => false [html_web_4_0] => false [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 320 [resolution_height] => 240 [columns] => 36 [max_image_width] => 300 [max_image_height] => 92 [rows] => 10 [physical_screen_width] => 49 [physical_screen_height] => 37 [dual_orientation] => false [density_class] => 1.0 [wbmp] => true [bmp] => true [epoc_bmp] => false [gif_animated] => true [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => false [transparent_png_index] => false [svgt_1_1] => false [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 262144 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => true [wta_voice_call] => false [wta_phonebook] => true [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 9 [wifi] => false [sdio] => false [vpn] => false [has_cellular_radio] => true [max_deck_size] => 65536 [max_url_length_in_requests] => 256 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => false [inline_support] => false [oma_support] => false [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => false [streaming_3gpp] => false [streaming_mp4] => false [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => -1 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => -1 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => -1 [streaming_acodec_amr] => none [streaming_acodec_aac] => none [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => none [wap_push_support] => true [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => false [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 300000 [mms_max_height] => 768 [mms_max_width] => 1024 [built_in_recorder] => false [built_in_camera] => false [mms_jpeg_baseline] => true [mms_jpeg_progressive] => false [mms_gif_static] => true [mms_gif_animated] => false [mms_png] => true [mms_bmp] => true [mms_wbmp] => true [mms_amr] => true [mms_wav] => true [mms_midi_monophonic] => true [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => true [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => true [mms_jad] => true [mms_vcard] => true [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => true [wav] => true [mmf] => false [smf] => false [mld] => false [midi_monophonic] => true [midi_polyphonic] => false [sp_midi] => true [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => true [au] => false [amr] => true [awb] => false [aac] => false [mp3] => false [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => false [css_supports_width_as_percentage] => true [css_border_image] => none [css_rounded_corners] => none [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => false [progressive_download] => false [playback_vcodec_h263_0] => -1 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => -1 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => -1 [playback_real_media] => none [playback_3gpp] => false [playback_3g2] => false [playback_mp4] => false [playback_mov] => false [playback_acodec_amr] => none [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => false [html_preferred_dtd] => xhtml_mp1 [viewport_supported] => false [viewport_width] => [viewport_userscalable] => [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => none [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => false [jqm_grade] => none [is_sencha_touch_ok] => false ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Obigo InternetBrowser</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://en.wikipedia.org/wiki/Obigo_Browser [title] => Obigo InternetBrowser [code] => obigo [version] => InternetBrowser [name] => Obigo [image] => img/16/browser/obigo.png ) [os] => Array ( [link] => [name] => [version] => [code] => null [x64] => [title] => [type] => os [dir] => os [image] => img/16/os/null.png ) [device] => Array ( [link] => # [title] => Unknown [code] => null [dir] => browser [type] => os [image] => img/16/browser/null.png ) [platform] => Array ( [link] => # [title] => Unknown [code] => null [dir] => browser [type] => os [image] => img/16/browser/null.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 08:00:03</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
{ "content_hash": "47a234853c1439f6b80f7c00f81cdb00", "timestamp": "", "source": "github", "line_count": 1191, "max_line_length": 962, "avg_line_length": 39.70864819479429, "alnum_prop": 0.5288097604296619, "repo_name": "ThaDafinser/UserAgentParserComparison", "id": "a6ad71ca09b877719da882e4ade65dc2f4498ba4", "size": "47294", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "v5/user-agent-detail/74/27/7427f0ff-fd82-494d-bbd9-e3317092aa61.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2060859160" } ], "symlink_target": "" }
This is a short, simple tutorial intended to get you started with Registrator as quickly as possible. For full reference, see [Run Reference](run.md). ## Overview Registrator watches for new Docker containers and inspects them to determine what services they provide. For our purposes, a service is anything listening on a port. Any services Registrator finds on a container, they will be added to a service registry, such as Consul or etcd. In this tutorial, we're going to use Registrator with Consul, and run a Redis container that will automatically get added to Consul. ## Before Starting We're going to need a host running Docker, which could just be a local [boot2docker](http://boot2docker.io/) VM, and a shell with the `docker` client pointed to that host. We'll also need to have Consul running, which can just be running in a container. Let's run a single instance of Consul in server bootstrap mode: ``` $ docker run -d --name=consul --net=host gliderlabs/consul-server -bootstrap ``` Consul is run differently in production, but this will get us through this tutorial. We can now access Consul's HTTP API via the Docker machine's IP: ``` $ curl $(boot2docker ip):8500/v1/catalog/services {"consul":[]} ``` Now we can start Registrator. ## Running Registrator Registrator is run on every host, but since we only have one host here, we can just run it once. The primary bit of configuration needed to start Registrator is how to connect to its registry, or Consul in this case. Besides option flags, the only argument Registrator takes is a registry URI, which encodes what type of registry, how to connect to it, and any options. ``` $ docker run -d \ --cap-drop=all \ --name=registrator \ --read-only \ --security-opt=no-new-privileges \ --user="registrator:$(getent group docker | awk -F':' '{print $3}')" \ --volume=/etc/localtime:/etc/localtime:ro \ --volume=/etc/timezone:/etc/timezone:ro \ --volume=/var/run/docker.sock:/tmp/docker.sock \ olafnorge/golang-registrator:latest \ consul://localhost:8500 ``` There's a bit going on here in the Docker run arguments. First, we run the container detached and name it. We also run in host network mode. This makes sure Registrator has the hostname and IP of the actual host. It also makes it easier to connect to Consul. We also must mount the Docker socket. The last line is the argument to Registrator itself, which is just our registry URI. We're using `consul` on `localhost:8500`, since this is running on the same network interface as Consul. ``` $ docker logs registrator ``` We should see it started up and "Listening for Docker events". That's it, it's working! ## Running Redis Now as you start containers, if they provide any services, they'll be added to Consul. We'll run Redis now from the standard library image: ``` $ docker run -d -P --name=redis redis ``` Notice we used `-P` to publish all ports. This is not often used except with Registrator. Not only does it publish all exposed ports the container has, but it assigns them to a random port on the host. Since the point of Registrator and Consul is to provide service discovery, the port doesn't matter. Though there can still be cases where you still want to manually specify the port. Let's look at Consul's services endpoint again: ``` $ curl $(boot2docker ip):8500/v1/catalog/services {"consul":[],"redis":[]} ``` Consul now has a service called redis. We can see more about the service including what port was published by looking at the service endpoint for redis: ``` $ curl $(boot2docker ip):8500/v1/catalog/service/redis [{"Node":"boot2docker","Address":"10.0.2.15","ServiceID":"boot2docker:redis:6379","ServiceName":"redis","ServiceTags":null,"ServiceAddress":"","ServicePort":32768}] ``` If we remove the redis container, we can see the service is removed from Consul: ``` $ docker rm -f redis redis $ curl $(boot2docker ip):8500/v1/catalog/service/redis [] ``` That's it! I know this may not be interesting alone, but there's a lot you can do once services are registered in Consul. However, that's out of the scope of Registrator. All it does is puts container services into Consul. ## Next Steps There are more ways to configure Registrator and ways you can run containers to customize the services that are extracted from them. For this, take a look at the [Run Reference](run.md) and [Service Model](services.md).
{ "content_hash": "8673a47af2aebbe86f989bec2834e1d6", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 164, "avg_line_length": 41.66355140186916, "alnum_prop": 0.7420367877972185, "repo_name": "olafnorge/golang-registrator", "id": "7604ed6a90cb9bb04809b7928ed77064bb6cbf3d", "size": "4472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/user/quickstart.md", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "41287" } ], "symlink_target": "" }
package org.apache.derby.client.am; // Methods implemented by the common Statement class to handle // certain events that may originate from the material or common layers. // // Reply implementations may update statement state via this interface. // public interface StatementCallbackInterface extends UnitOfWorkListener { // A query has been opened on the server. public void completeOpenQuery(Sqlca sqlca, ResultSet resultSet) throws DisconnectException; public void completeExecuteCallOpenQuery(Sqlca sqlca, ResultSet resultSet, ColumnMetaData resultSetMetaData, Section generatedSection); // Chains a warning onto the statement. public void accumulateWarning(SqlWarning e); public void completePrepare(Sqlca sqlca); public void completePrepareDescribeOutput(ColumnMetaData columnMetaData, Sqlca sqlca); public void completeExecuteImmediate(Sqlca sqlca); public void completeExecuteSetStatement(Sqlca sqlca); public void completeExecute(Sqlca sqlca); public void completeExecuteCall(Sqlca sqlca, Cursor params, ResultSet[] resultSets); public void completeExecuteCall(Sqlca sqlca, Cursor params); public int completeSqlca(Sqlca sqlca); public ConnectionCallbackInterface getConnectionCallbackInterface(); public ColumnMetaData getGuessedResultSetMetaData(); }
{ "content_hash": "972e3331cf0ff3a8d0706dbda1b5e12f", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 139, "avg_line_length": 31.952380952380953, "alnum_prop": 0.7913561847988078, "repo_name": "lpxz/grail-derby104", "id": "82eca73bcfaf278685cd6d2267466a92c4e71fba", "size": "2211", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "java/client/org/apache/derby/client/am/StatementCallbackInterface.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13654" }, { "name": "HTML", "bytes": "261297" }, { "name": "Java", "bytes": "33386324" }, { "name": "JavaScript", "bytes": "12169" }, { "name": "PLSQL", "bytes": "173048" }, { "name": "PLpgSQL", "bytes": "96936" }, { "name": "SQLPL", "bytes": "658480" }, { "name": "Shell", "bytes": "2876" } ], "symlink_target": "" }
* Initial release. ## v0.7.5 and Earlier * Can be found in the [old `monit` cookbook](https://github.com/apsoto/monit/).
{ "content_hash": "644433aaf0d093a861bfc64b93e72969", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 79, "avg_line_length": 24.6, "alnum_prop": 0.6829268292682927, "repo_name": "poise/poise-monit-compat", "id": "0a4da14ac159e245a55c7dca5e8ac37f35eadfaa", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3049" }, { "name": "Ruby", "bytes": "36433" } ], "symlink_target": "" }
package io.datarouter.filesystem.snapshot.block; public class BlockSizeCalculator{ private static final int WORD_WIDTH = 8; private int size; public static int pad(int inputSize){ int overflow = inputSize % WORD_WIDTH; int padding = WORD_WIDTH - overflow; return inputSize + padding; } public int calculate(){ return pad(size); } public BlockSizeCalculator addObjectHeaders(int num){ size += num * 16; return this; } public BlockSizeCalculator addRefs(int num){ size += num * 8; return this; } public BlockSizeCalculator addArrays(int num){ size += num * 24; return this; } public BlockSizeCalculator addLongs(int num){ size += num * 8; return this; } public BlockSizeCalculator addDoubles(int num){ size += num * 8; return this; } public BlockSizeCalculator addInts(int num){ size += num * 4; return this; } public BlockSizeCalculator addFloats(int num){ size += num * 4; return this; } public BlockSizeCalculator addChars(int num){ size += num * 2; return this; } public BlockSizeCalculator addShorts(int num){ size += num * 2; return this; } public BlockSizeCalculator addBytes(int num){ size += num; return this; } public BlockSizeCalculator addBooleans(int num){ size += num; return this; } // excludes the reference to the byte[] public BlockSizeCalculator addByteArrayValue(byte[] array){ addArrays(1); addBytes(pad(array.length)); return this; } // excludes the reference to the int[] public BlockSizeCalculator addIntArrayValue(int[] array){ addArrays(1); addBytes(pad(4 * array.length)); return this; } // excludes the reference to the String public BlockSizeCalculator addStringValue(String string){ addObjectHeaders(1);// the String Object addArrays(1);// String.value reference addBytes(pad(string.length()));// String.value body addBytes(1);// String.coder addInts(1);// String.hash addBooleans(1);// String.hashIsZero return this; } }
{ "content_hash": "b0c27d216f9d2c929bedb18ecb73affb", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 60, "avg_line_length": 19.86, "alnum_prop": 0.703423967774421, "repo_name": "hotpads/datarouter", "id": "fd3f71c36587e2cc367337289bd35a0a7e888f6b", "size": "2599", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "datarouter-snapshot/src/main/java/io/datarouter/filesystem/snapshot/block/BlockSizeCalculator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9438" }, { "name": "Java", "bytes": "8616487" }, { "name": "JavaScript", "bytes": "639471" } ], "symlink_target": "" }
// Copyright (c) 2011-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include <key.h> #include <script/sign.h> #include <script/signingprovider.h> #include <script/standard.h> #include <test/util/setup_common.h> #include <txmempool.h> #include <validation.h> #include <boost/test/unit_test.hpp> bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks); BOOST_AUTO_TEST_SUITE(txvalidationcache_tests) BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) { // Make sure skipping validation of transactions that were // validated going into the memory pool does not allow // double-spends in blocks to pass validation when they should not. CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; const auto ToMemPool = [this](const CMutableTransaction& tx) { LOCK(cs_main); TxValidationState state; return AcceptToMemoryPool(*m_node.mempool, state, MakeTransactionRef(tx), nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */); }; // Create a double-spend of mature coinbase txn: std::vector<CMutableTransaction> spends; spends.resize(2); for (int i = 0; i < 2; i++) { spends[i].nVersion = 1; spends[i].vin.resize(1); spends[i].vin[0].prevout.hash = m_coinbase_txns[0]->GetHash(); spends[i].vin[0].prevout.n = 0; spends[i].vout.resize(1); spends[i].vout[0].nValue = 11*CENT; spends[i].vout[0].scriptPubKey = scriptPubKey; // Sign: std::vector<unsigned char> vchSig; uint256 hash = SignatureHash(scriptPubKey, spends[i], 0, SIGHASH_ALL, 0, SigVersion::BASE); BOOST_CHECK(coinbaseKey.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); spends[i].vin[0].scriptSig << vchSig; } CBlock block; // Test 1: block with both of those transactions should be rejected. block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } // Test 2: ... and should be rejected if spend1 is in the memory pool BOOST_CHECK(ToMemPool(spends[0])); block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } m_node.mempool->clear(); // Test 3: ... and should be rejected if spend2 is in the memory pool BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } m_node.mempool->clear(); // Final sanity test: first spend in *m_node.mempool, second in block, that's OK: std::vector<CMutableTransaction> oneSpend; oneSpend.push_back(spends[0]); BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(oneSpend, scriptPubKey); { LOCK(cs_main); BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash()); } // spends[1] should have been removed from the mempool when the // block with spends[0] is accepted: BOOST_CHECK_EQUAL(m_node.mempool->size(), 0U); } // Run CheckInputScripts (using CoinsTip()) on the given transaction, for all script // flags. Test that CheckInputScripts passes for all flags that don't overlap with // the failing_flags argument, but otherwise fails. // CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY (and future NOP codes that may // get reassigned) have an interaction with DISCOURAGE_UPGRADABLE_NOPS: if // the script flags used contain DISCOURAGE_UPGRADABLE_NOPS but don't contain // CHECKLOCKTIMEVERIFY (or CHECKSEQUENCEVERIFY), but the script does contain // OP_CHECKLOCKTIMEVERIFY (or OP_CHECKSEQUENCEVERIFY), then script execution // should fail. // Capture this interaction with the upgraded_nop argument: set it when evaluating // any script flag that is implemented as an upgraded NOP code. static void ValidateCheckInputsForAllFlags(const CTransaction &tx, uint32_t failing_flags, bool add_to_cache) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { PrecomputedTransactionData txdata; // If we add many more flags, this loop can get too expensive, but we can // rewrite in the future to randomly pick a set of flags to evaluate. for (uint32_t test_flags=0; test_flags < (1U << 16); test_flags += 1) { TxValidationState state; // Filter out incompatible flag choices if ((test_flags & SCRIPT_VERIFY_CLEANSTACK)) { // CLEANSTACK requires P2SH and WITNESS, see VerifyScript() in // script/interpreter.cpp test_flags |= SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS; } if ((test_flags & SCRIPT_VERIFY_WITNESS)) { // WITNESS requires P2SH test_flags |= SCRIPT_VERIFY_P2SH; } bool ret = CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, nullptr); // CheckInputScripts should succeed iff test_flags doesn't intersect with // failing_flags bool expected_return_value = !(test_flags & failing_flags); BOOST_CHECK_EQUAL(ret, expected_return_value); // Test the caching if (ret && add_to_cache) { // Check that we get a cache hit if the tx was valid std::vector<CScriptCheck> scriptchecks; BOOST_CHECK(CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, &scriptchecks)); BOOST_CHECK(scriptchecks.empty()); } else { // Check that we get script executions to check, if the transaction // was invalid, or we didn't add to cache. std::vector<CScriptCheck> scriptchecks; BOOST_CHECK(CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, &scriptchecks)); BOOST_CHECK_EQUAL(scriptchecks.size(), tx.vin.size()); } } } BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup) { // Test that passing CheckInputScripts with one set of script flags doesn't imply // that we would pass again with a different set of flags. { LOCK(cs_main); InitScriptExecutionCache(); } CScript p2pk_scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; CScript p2sh_scriptPubKey = GetScriptForDestination(ScriptHash(p2pk_scriptPubKey)); CScript p2pkh_scriptPubKey = GetScriptForDestination(PKHash(coinbaseKey.GetPubKey())); CScript p2wpkh_scriptPubKey = GetScriptForWitness(p2pkh_scriptPubKey); FillableSigningProvider keystore; BOOST_CHECK(keystore.AddKey(coinbaseKey)); BOOST_CHECK(keystore.AddCScript(p2pk_scriptPubKey)); // flags to test: SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, SCRIPT_VERIFY_CHECKSEQUENCE_VERIFY, SCRIPT_VERIFY_NULLDUMMY, uncompressed pubkey thing // Create 2 outputs that match the three scripts above, spending the first // coinbase tx. CMutableTransaction spend_tx; spend_tx.nVersion = 1; spend_tx.vin.resize(1); spend_tx.vin[0].prevout.hash = m_coinbase_txns[0]->GetHash(); spend_tx.vin[0].prevout.n = 0; spend_tx.vout.resize(4); spend_tx.vout[0].nValue = 11*CENT; spend_tx.vout[0].scriptPubKey = p2sh_scriptPubKey; spend_tx.vout[1].nValue = 11*CENT; spend_tx.vout[1].scriptPubKey = p2wpkh_scriptPubKey; spend_tx.vout[2].nValue = 11*CENT; spend_tx.vout[2].scriptPubKey = CScript() << OP_CHECKLOCKTIMEVERIFY << OP_DROP << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; spend_tx.vout[3].nValue = 11*CENT; spend_tx.vout[3].scriptPubKey = CScript() << OP_CHECKSEQUENCEVERIFY << OP_DROP << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG; // Sign, with a non-DER signature { std::vector<unsigned char> vchSig; uint256 hash = SignatureHash(p2pk_scriptPubKey, spend_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE); BOOST_CHECK(coinbaseKey.Sign(hash, vchSig)); vchSig.push_back((unsigned char) 0); // padding byte makes this non-DER vchSig.push_back((unsigned char)SIGHASH_ALL); spend_tx.vin[0].scriptSig << vchSig; } // Test that invalidity under a set of flags doesn't preclude validity // under other (eg consensus) flags. // spend_tx is invalid according to DERSIG { LOCK(cs_main); TxValidationState state; PrecomputedTransactionData ptd_spend_tx; BOOST_CHECK(!CheckInputScripts(CTransaction(spend_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, nullptr)); // If we call again asking for scriptchecks (as happens in // ConnectBlock), we should add a script check object for this -- we're // not caching invalidity (if that changes, delete this test case). std::vector<CScriptCheck> scriptchecks; BOOST_CHECK(CheckInputScripts(CTransaction(spend_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, &scriptchecks)); BOOST_CHECK_EQUAL(scriptchecks.size(), 1U); // Test that CheckInputScripts returns true iff DERSIG-enforcing flags are // not present. Don't add these checks to the cache, so that we can // test later that block validation works fine in the absence of cached // successes. ValidateCheckInputsForAllFlags(CTransaction(spend_tx), SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC, false); } // And if we produce a block with this tx, it should be valid (DERSIG not // enabled yet), even though there's no cache entry. CBlock block; block = CreateAndProcessBlock({spend_tx}, p2pk_scriptPubKey); LOCK(cs_main); BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash()); BOOST_CHECK(::ChainstateActive().CoinsTip().GetBestBlock() == block.GetHash()); // Test P2SH: construct a transaction that is valid without P2SH, and // then test validity with P2SH. { CMutableTransaction invalid_under_p2sh_tx; invalid_under_p2sh_tx.nVersion = 1; invalid_under_p2sh_tx.vin.resize(1); invalid_under_p2sh_tx.vin[0].prevout.hash = spend_tx.GetHash(); invalid_under_p2sh_tx.vin[0].prevout.n = 0; invalid_under_p2sh_tx.vout.resize(1); invalid_under_p2sh_tx.vout[0].nValue = 11*CENT; invalid_under_p2sh_tx.vout[0].scriptPubKey = p2pk_scriptPubKey; std::vector<unsigned char> vchSig2(p2pk_scriptPubKey.begin(), p2pk_scriptPubKey.end()); invalid_under_p2sh_tx.vin[0].scriptSig << vchSig2; ValidateCheckInputsForAllFlags(CTransaction(invalid_under_p2sh_tx), SCRIPT_VERIFY_P2SH, true); } // Test CHECKLOCKTIMEVERIFY { CMutableTransaction invalid_with_cltv_tx; invalid_with_cltv_tx.nVersion = 1; invalid_with_cltv_tx.nLockTime = 100; invalid_with_cltv_tx.vin.resize(1); invalid_with_cltv_tx.vin[0].prevout.hash = spend_tx.GetHash(); invalid_with_cltv_tx.vin[0].prevout.n = 2; invalid_with_cltv_tx.vin[0].nSequence = 0; invalid_with_cltv_tx.vout.resize(1); invalid_with_cltv_tx.vout[0].nValue = 11*CENT; invalid_with_cltv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey; // Sign std::vector<unsigned char> vchSig; uint256 hash = SignatureHash(spend_tx.vout[2].scriptPubKey, invalid_with_cltv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE); BOOST_CHECK(coinbaseKey.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 101; ValidateCheckInputsForAllFlags(CTransaction(invalid_with_cltv_tx), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, true); // Make it valid, and check again invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 100; TxValidationState state; PrecomputedTransactionData txdata; BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_cltv_tx), state, ::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, true, true, txdata, nullptr)); } // TEST CHECKSEQUENCEVERIFY { CMutableTransaction invalid_with_csv_tx; invalid_with_csv_tx.nVersion = 2; invalid_with_csv_tx.vin.resize(1); invalid_with_csv_tx.vin[0].prevout.hash = spend_tx.GetHash(); invalid_with_csv_tx.vin[0].prevout.n = 3; invalid_with_csv_tx.vin[0].nSequence = 100; invalid_with_csv_tx.vout.resize(1); invalid_with_csv_tx.vout[0].nValue = 11*CENT; invalid_with_csv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey; // Sign std::vector<unsigned char> vchSig; uint256 hash = SignatureHash(spend_tx.vout[3].scriptPubKey, invalid_with_csv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE); BOOST_CHECK(coinbaseKey.Sign(hash, vchSig)); vchSig.push_back((unsigned char)SIGHASH_ALL); invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 101; ValidateCheckInputsForAllFlags(CTransaction(invalid_with_csv_tx), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, true); // Make it valid, and check again invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 100; TxValidationState state; PrecomputedTransactionData txdata; BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_csv_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, true, true, txdata, nullptr)); } // TODO: add tests for remaining script flags // Test that passing CheckInputScripts with a valid witness doesn't imply success // for the same tx with a different witness. { CMutableTransaction valid_with_witness_tx; valid_with_witness_tx.nVersion = 1; valid_with_witness_tx.vin.resize(1); valid_with_witness_tx.vin[0].prevout.hash = spend_tx.GetHash(); valid_with_witness_tx.vin[0].prevout.n = 1; valid_with_witness_tx.vout.resize(1); valid_with_witness_tx.vout[0].nValue = 11*CENT; valid_with_witness_tx.vout[0].scriptPubKey = p2pk_scriptPubKey; // Sign SignatureData sigdata; BOOST_CHECK(ProduceSignature(keystore, MutableTransactionSignatureCreator(&valid_with_witness_tx, 0, 11*CENT, SIGHASH_ALL), spend_tx.vout[1].scriptPubKey, sigdata)); UpdateInput(valid_with_witness_tx.vin[0], sigdata); // This should be valid under all script flags. ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), 0, true); // Remove the witness, and check that it is now invalid. valid_with_witness_tx.vin[0].scriptWitness.SetNull(); ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), SCRIPT_VERIFY_WITNESS, true); } { // Test a transaction with multiple inputs. CMutableTransaction tx; tx.nVersion = 1; tx.vin.resize(2); tx.vin[0].prevout.hash = spend_tx.GetHash(); tx.vin[0].prevout.n = 0; tx.vin[1].prevout.hash = spend_tx.GetHash(); tx.vin[1].prevout.n = 1; tx.vout.resize(1); tx.vout[0].nValue = 22*CENT; tx.vout[0].scriptPubKey = p2pk_scriptPubKey; // Sign for (int i=0; i<2; ++i) { SignatureData sigdata; BOOST_CHECK(ProduceSignature(keystore, MutableTransactionSignatureCreator(&tx, i, 11*CENT, SIGHASH_ALL), spend_tx.vout[i].scriptPubKey, sigdata)); UpdateInput(tx.vin[i], sigdata); } // This should be valid under all script flags ValidateCheckInputsForAllFlags(CTransaction(tx), 0, true); // Check that if the second input is invalid, but the first input is // valid, the transaction is not cached. // Invalidate vin[1] tx.vin[1].scriptWitness.SetNull(); TxValidationState state; PrecomputedTransactionData txdata; // This transaction is now invalid under segwit, because of the second input. BOOST_CHECK(!CheckInputScripts(CTransaction(tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, nullptr)); std::vector<CScriptCheck> scriptchecks; // Make sure this transaction was not cached (ie because the first // input was valid) BOOST_CHECK(CheckInputScripts(CTransaction(tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, &scriptchecks)); // Should get 2 script checks back -- caching is on a whole-transaction basis. BOOST_CHECK_EQUAL(scriptchecks.size(), 2U); } } BOOST_AUTO_TEST_SUITE_END()
{ "content_hash": "b96077278fbec0509e1c2c13386e3c0e", "timestamp": "", "source": "github", "line_count": 374, "max_line_length": 244, "avg_line_length": 46.25668449197861, "alnum_prop": 0.6728323699421965, "repo_name": "midnightmagic/bitcoin", "id": "cdef7dcc3cbb0f1d926b071bd9bc6ebf01de792f", "size": "17300", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/txvalidationcache_tests.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "534165" }, { "name": "C++", "bytes": "3705952" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "19797" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "Makefile", "bytes": "65360" }, { "name": "Objective-C", "bytes": "2022" }, { "name": "Objective-C++", "bytes": "7238" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "447889" }, { "name": "QMake", "bytes": "2019" }, { "name": "Shell", "bytes": "40702" } ], "symlink_target": "" }
package com.amazonaws.services.frauddetector.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/frauddetector-2019-11-15/CreateDetectorVersion" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateDetectorVersionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The ID of the detector under which you want to create a new version. * </p> */ private String detectorId; /** * <p> * The description of the detector version. * </p> */ private String description; /** * <p> * The Amazon Sagemaker model endpoints to include in the detector version. * </p> */ private java.util.List<String> externalModelEndpoints; /** * <p> * The rules to include in the detector version. * </p> */ private java.util.List<Rule> rules; /** * <p> * The model versions to include in the detector version. * </p> */ private java.util.List<ModelVersion> modelVersions; /** * <p> * The rule execution mode for the rules included in the detector version. * </p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to last, * stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the outcomes for * all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * </p> */ private String ruleExecutionMode; /** * <p> * A collection of key and value pairs. * </p> */ private java.util.List<Tag> tags; /** * <p> * The ID of the detector under which you want to create a new version. * </p> * * @param detectorId * The ID of the detector under which you want to create a new version. */ public void setDetectorId(String detectorId) { this.detectorId = detectorId; } /** * <p> * The ID of the detector under which you want to create a new version. * </p> * * @return The ID of the detector under which you want to create a new version. */ public String getDetectorId() { return this.detectorId; } /** * <p> * The ID of the detector under which you want to create a new version. * </p> * * @param detectorId * The ID of the detector under which you want to create a new version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withDetectorId(String detectorId) { setDetectorId(detectorId); return this; } /** * <p> * The description of the detector version. * </p> * * @param description * The description of the detector version. */ public void setDescription(String description) { this.description = description; } /** * <p> * The description of the detector version. * </p> * * @return The description of the detector version. */ public String getDescription() { return this.description; } /** * <p> * The description of the detector version. * </p> * * @param description * The description of the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withDescription(String description) { setDescription(description); return this; } /** * <p> * The Amazon Sagemaker model endpoints to include in the detector version. * </p> * * @return The Amazon Sagemaker model endpoints to include in the detector version. */ public java.util.List<String> getExternalModelEndpoints() { return externalModelEndpoints; } /** * <p> * The Amazon Sagemaker model endpoints to include in the detector version. * </p> * * @param externalModelEndpoints * The Amazon Sagemaker model endpoints to include in the detector version. */ public void setExternalModelEndpoints(java.util.Collection<String> externalModelEndpoints) { if (externalModelEndpoints == null) { this.externalModelEndpoints = null; return; } this.externalModelEndpoints = new java.util.ArrayList<String>(externalModelEndpoints); } /** * <p> * The Amazon Sagemaker model endpoints to include in the detector version. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setExternalModelEndpoints(java.util.Collection)} or * {@link #withExternalModelEndpoints(java.util.Collection)} if you want to override the existing values. * </p> * * @param externalModelEndpoints * The Amazon Sagemaker model endpoints to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withExternalModelEndpoints(String... externalModelEndpoints) { if (this.externalModelEndpoints == null) { setExternalModelEndpoints(new java.util.ArrayList<String>(externalModelEndpoints.length)); } for (String ele : externalModelEndpoints) { this.externalModelEndpoints.add(ele); } return this; } /** * <p> * The Amazon Sagemaker model endpoints to include in the detector version. * </p> * * @param externalModelEndpoints * The Amazon Sagemaker model endpoints to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withExternalModelEndpoints(java.util.Collection<String> externalModelEndpoints) { setExternalModelEndpoints(externalModelEndpoints); return this; } /** * <p> * The rules to include in the detector version. * </p> * * @return The rules to include in the detector version. */ public java.util.List<Rule> getRules() { return rules; } /** * <p> * The rules to include in the detector version. * </p> * * @param rules * The rules to include in the detector version. */ public void setRules(java.util.Collection<Rule> rules) { if (rules == null) { this.rules = null; return; } this.rules = new java.util.ArrayList<Rule>(rules); } /** * <p> * The rules to include in the detector version. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setRules(java.util.Collection)} or {@link #withRules(java.util.Collection)} if you want to override the * existing values. * </p> * * @param rules * The rules to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withRules(Rule... rules) { if (this.rules == null) { setRules(new java.util.ArrayList<Rule>(rules.length)); } for (Rule ele : rules) { this.rules.add(ele); } return this; } /** * <p> * The rules to include in the detector version. * </p> * * @param rules * The rules to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withRules(java.util.Collection<Rule> rules) { setRules(rules); return this; } /** * <p> * The model versions to include in the detector version. * </p> * * @return The model versions to include in the detector version. */ public java.util.List<ModelVersion> getModelVersions() { return modelVersions; } /** * <p> * The model versions to include in the detector version. * </p> * * @param modelVersions * The model versions to include in the detector version. */ public void setModelVersions(java.util.Collection<ModelVersion> modelVersions) { if (modelVersions == null) { this.modelVersions = null; return; } this.modelVersions = new java.util.ArrayList<ModelVersion>(modelVersions); } /** * <p> * The model versions to include in the detector version. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setModelVersions(java.util.Collection)} or {@link #withModelVersions(java.util.Collection)} if you want * to override the existing values. * </p> * * @param modelVersions * The model versions to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withModelVersions(ModelVersion... modelVersions) { if (this.modelVersions == null) { setModelVersions(new java.util.ArrayList<ModelVersion>(modelVersions.length)); } for (ModelVersion ele : modelVersions) { this.modelVersions.add(ele); } return this; } /** * <p> * The model versions to include in the detector version. * </p> * * @param modelVersions * The model versions to include in the detector version. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withModelVersions(java.util.Collection<ModelVersion> modelVersions) { setModelVersions(modelVersions); return this; } /** * <p> * The rule execution mode for the rules included in the detector version. * </p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to last, * stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the outcomes for * all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * </p> * * @param ruleExecutionMode * The rule execution mode for the rules included in the detector version.</p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to * last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that * single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the * outcomes for all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * @see RuleExecutionMode */ public void setRuleExecutionMode(String ruleExecutionMode) { this.ruleExecutionMode = ruleExecutionMode; } /** * <p> * The rule execution mode for the rules included in the detector version. * </p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to last, * stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the outcomes for * all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * </p> * * @return The rule execution mode for the rules included in the detector version.</p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to * last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that * single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the * outcomes for all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * @see RuleExecutionMode */ public String getRuleExecutionMode() { return this.ruleExecutionMode; } /** * <p> * The rule execution mode for the rules included in the detector version. * </p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to last, * stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the outcomes for * all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * </p> * * @param ruleExecutionMode * The rule execution mode for the rules included in the detector version.</p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to * last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that * single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the * outcomes for all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see RuleExecutionMode */ public CreateDetectorVersionRequest withRuleExecutionMode(String ruleExecutionMode) { setRuleExecutionMode(ruleExecutionMode); return this; } /** * <p> * The rule execution mode for the rules included in the detector version. * </p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to last, * stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the outcomes for * all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * </p> * * @param ruleExecutionMode * The rule execution mode for the rules included in the detector version.</p> * <p> * You can define and edit the rule mode at the detector version level, when it is in draft status. * </p> * <p> * If you specify <code>FIRST_MATCHED</code>, Amazon Fraud Detector evaluates rules sequentially, first to * last, stopping at the first matched rule. Amazon Fraud dectector then provides the outcomes for that * single rule. * </p> * <p> * If you specifiy <code>ALL_MATCHED</code>, Amazon Fraud Detector evaluates all rules and returns the * outcomes for all matched rules. * </p> * <p> * The default behavior is <code>FIRST_MATCHED</code>. * @return Returns a reference to this object so that method calls can be chained together. * @see RuleExecutionMode */ public CreateDetectorVersionRequest withRuleExecutionMode(RuleExecutionMode ruleExecutionMode) { this.ruleExecutionMode = ruleExecutionMode.toString(); return this; } /** * <p> * A collection of key and value pairs. * </p> * * @return A collection of key and value pairs. */ public java.util.List<Tag> getTags() { return tags; } /** * <p> * A collection of key and value pairs. * </p> * * @param tags * A collection of key and value pairs. */ public void setTags(java.util.Collection<Tag> tags) { if (tags == null) { this.tags = null; return; } this.tags = new java.util.ArrayList<Tag>(tags); } /** * <p> * A collection of key and value pairs. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the * existing values. * </p> * * @param tags * A collection of key and value pairs. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withTags(Tag... tags) { if (this.tags == null) { setTags(new java.util.ArrayList<Tag>(tags.length)); } for (Tag ele : tags) { this.tags.add(ele); } return this; } /** * <p> * A collection of key and value pairs. * </p> * * @param tags * A collection of key and value pairs. * @return Returns a reference to this object so that method calls can be chained together. */ public CreateDetectorVersionRequest withTags(java.util.Collection<Tag> tags) { setTags(tags); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getDetectorId() != null) sb.append("DetectorId: ").append(getDetectorId()).append(","); if (getDescription() != null) sb.append("Description: ").append(getDescription()).append(","); if (getExternalModelEndpoints() != null) sb.append("ExternalModelEndpoints: ").append(getExternalModelEndpoints()).append(","); if (getRules() != null) sb.append("Rules: ").append(getRules()).append(","); if (getModelVersions() != null) sb.append("ModelVersions: ").append(getModelVersions()).append(","); if (getRuleExecutionMode() != null) sb.append("RuleExecutionMode: ").append(getRuleExecutionMode()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateDetectorVersionRequest == false) return false; CreateDetectorVersionRequest other = (CreateDetectorVersionRequest) obj; if (other.getDetectorId() == null ^ this.getDetectorId() == null) return false; if (other.getDetectorId() != null && other.getDetectorId().equals(this.getDetectorId()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getExternalModelEndpoints() == null ^ this.getExternalModelEndpoints() == null) return false; if (other.getExternalModelEndpoints() != null && other.getExternalModelEndpoints().equals(this.getExternalModelEndpoints()) == false) return false; if (other.getRules() == null ^ this.getRules() == null) return false; if (other.getRules() != null && other.getRules().equals(this.getRules()) == false) return false; if (other.getModelVersions() == null ^ this.getModelVersions() == null) return false; if (other.getModelVersions() != null && other.getModelVersions().equals(this.getModelVersions()) == false) return false; if (other.getRuleExecutionMode() == null ^ this.getRuleExecutionMode() == null) return false; if (other.getRuleExecutionMode() != null && other.getRuleExecutionMode().equals(this.getRuleExecutionMode()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getDetectorId() == null) ? 0 : getDetectorId().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getExternalModelEndpoints() == null) ? 0 : getExternalModelEndpoints().hashCode()); hashCode = prime * hashCode + ((getRules() == null) ? 0 : getRules().hashCode()); hashCode = prime * hashCode + ((getModelVersions() == null) ? 0 : getModelVersions().hashCode()); hashCode = prime * hashCode + ((getRuleExecutionMode() == null) ? 0 : getRuleExecutionMode().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); return hashCode; } @Override public CreateDetectorVersionRequest clone() { return (CreateDetectorVersionRequest) super.clone(); } }
{ "content_hash": "b7785132cfec9a8ffe47f272534a8ce1", "timestamp": "", "source": "github", "line_count": 696, "max_line_length": 141, "avg_line_length": 34.5948275862069, "alnum_prop": 0.6050336406678296, "repo_name": "aws/aws-sdk-java", "id": "55684703f821f7f354f7e9d6c8809febc5f0c11e", "size": "24658", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-frauddetector/src/main/java/com/amazonaws/services/frauddetector/model/CreateDetectorVersionRequest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
@interface ShareSDKTest3_7UITests : XCTestCase @end @implementation ShareSDKTest3_7UITests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. self.continueAfterFailure = NO; // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. [[[XCUIApplication alloc] init] launch]; // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } @end
{ "content_hash": "20a08e1cb38d8b59b16ccbb9b9c9fd50", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 178, "avg_line_length": 35.03333333333333, "alnum_prop": 0.7193149381541389, "repo_name": "WymanLyu/WYDemo", "id": "e325bceece0aa653bfd832119ef210dace339ee1", "size": "1233", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ShareSDKTest3-7/ShareSDKTest3-7UITests/ShareSDKTest3_7UITests.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "22469" }, { "name": "C", "bytes": "9341283" }, { "name": "C++", "bytes": "25210057" }, { "name": "HTML", "bytes": "33634" }, { "name": "Java", "bytes": "330631" }, { "name": "JavaScript", "bytes": "128054" }, { "name": "Makefile", "bytes": "45840" }, { "name": "Matlab", "bytes": "42078" }, { "name": "Objective-C", "bytes": "4817874" }, { "name": "Objective-C++", "bytes": "539172" }, { "name": "Python", "bytes": "642022" }, { "name": "Ruby", "bytes": "11503" }, { "name": "Shell", "bytes": "321885" }, { "name": "Swift", "bytes": "4973" } ], "symlink_target": "" }
/* * MaterialGemDrawer.java * Creation date: (10/25/00 8:44:19 AM) * By: Luke Evans */ package org.openquark.gems.client.browser; import javax.swing.tree.MutableTreeNode; import org.openquark.cal.compiler.ModuleName; import org.openquark.cal.compiler.ModuleNameResolver; import org.openquark.gems.client.ModuleNameDisplayUtilities; import org.openquark.gems.client.ModuleNameDisplayUtilities.TreeViewDisplayMode; /** * A Vault Drawer (tree node) which represents material (compiled) modules and entities. * Creation date: (10/25/00 8:44:19 AM) * @author Luke Evans */ class MaterialGemDrawer extends GemDrawer { private static final long serialVersionUID = -8442272696944239342L; /** Whether this node is a namespace node - i.e. it does not contain children corresponding to entities. */ private final boolean isNamespaceNode; /** * The displayed name of the drawer. */ private final String displayedString; /** * Construct a MaterialGemDrawer from a name. * Creation date: (10/25/00 8:54:58 AM) * @param workspaceModuleNameResolver the module name resolver to use to generate an appropriate module name * @param moduleTreeDisplayMode the display mode of the module tree. * @param isNamespaceNode whether this node is a namespace node. */ public MaterialGemDrawer(final ModuleName nodeName, final ModuleNameResolver workspaceModuleNameResolver, final TreeViewDisplayMode moduleTreeDisplayMode, final boolean isNamespaceNode) { super(nodeName); this.displayedString = ModuleNameDisplayUtilities.getDisplayNameForModuleInTreeView(nodeName, workspaceModuleNameResolver, moduleTreeDisplayMode); this.isNamespaceNode = isNamespaceNode; } /** * Returns the name of this MaterialGemDrawer's module. * Creation date: (05/02/01 9:55:42 AM) * @return java.lang.String */ @Override public ModuleName getModuleName() { return (ModuleName) getUserObject(); } /** * Return the name of the drawer. * Note: Unlike the getModuleName method, if the module name has length * zero, then a default name will be returned. * Creation date: (10/27/00 2:23:56 PM) * @return java.lang.String the name */ @Override public String toString() { return getDisplayedString(); } /** * @see org.openquark.gems.client.browser.BrowserTreeNode#getDisplayedString() */ @Override public String getDisplayedString() { return displayedString.length() > 0 ? displayedString : BrowserTree.DEFAULT_MODULE_NAME; } /** * {@inheritDoc} */ @Override public void insert(MutableTreeNode newChild, int childIndex) { super.insert(newChild, childIndex); } /** * @return whether this node is a namespace node - i.e. it does not contain children corresponding to entities. */ @Override public boolean isNamespaceNode() { return isNamespaceNode; } }
{ "content_hash": "ea1e69a686ec68defe34ba40b1ac7cfb", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 191, "avg_line_length": 33.234042553191486, "alnum_prop": 0.677336747759283, "repo_name": "levans/Open-Quark", "id": "83edc62fd3bb8696bac04fccf69b990dca091689", "size": "4783", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Quark_Gems/src/org/openquark/gems/client/browser/MaterialGemDrawer.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "31016785" }, { "name": "Shell", "bytes": "36042" } ], "symlink_target": "" }
//#define LOG_NDEBUG 0 #define LOG_TAG "ALooper" #include <media/stagefright/foundation/ADebug.h> #include <utils/Log.h> #include <sys/time.h> #include "ALooper.h" #include "AHandler.h" #include "ALooperRoster.h" #include "AMessage.h" namespace android { ANDROID_API_STAGEFRIGHT_FOUNDATION ALooperRoster gLooperRoster; // M3E: struct ALooper::LooperThread : public Thread { LooperThread(ALooper *looper, bool canCallJava) : Thread(canCallJava), mLooper(looper), mThreadId(NULL) { } virtual status_t readyToRun() { mThreadId = androidGetThreadId(); return Thread::readyToRun(); } virtual bool threadLoop() { return mLooper->loop(); } bool isCurrentThread() const { return mThreadId == androidGetThreadId(); } protected: virtual ~LooperThread() {} private: ALooper *mLooper; android_thread_id_t mThreadId; DISALLOW_EVIL_CONSTRUCTORS(LooperThread); }; // static int64_t ALooper::GetNowUs() { return systemTime(SYSTEM_TIME_MONOTONIC) / 1000ll; } ALooper::ALooper() : mRunningLocally(false) { // clean up stale AHandlers. Doing it here instead of in the destructor avoids // the side effect of objects being deleted from the unregister function recursively. gLooperRoster.unregisterStaleHandlers(); } ALooper::~ALooper() { stop(); // stale AHandlers are now cleaned up in the constructor of the next ALooper to come along } void ALooper::setName(const char *name) { mName = name; } ALooper::handler_id ALooper::registerHandler(const sp<AHandler> &handler) { return gLooperRoster.registerHandler(this, handler); } void ALooper::unregisterHandler(handler_id handlerID) { gLooperRoster.unregisterHandler(handlerID); } status_t ALooper::start( bool runOnCallingThread, bool canCallJava, int32_t priority) { if (runOnCallingThread) { { Mutex::Autolock autoLock(mLock); if (mThread != NULL || mRunningLocally) { return INVALID_OPERATION; } mRunningLocally = true; } do { } while (loop()); return OK; } Mutex::Autolock autoLock(mLock); if (mThread != NULL || mRunningLocally) { return INVALID_OPERATION; } mThread = new LooperThread(this, canCallJava); status_t err = mThread->run( mName.empty() ? "ALooper" : mName.c_str(), priority); if (err != OK) { mThread.clear(); } return err; } status_t ALooper::stop() { sp<LooperThread> thread; bool runningLocally; { Mutex::Autolock autoLock(mLock); thread = mThread; runningLocally = mRunningLocally; mThread.clear(); mRunningLocally = false; } if (thread == NULL && !runningLocally) { return INVALID_OPERATION; } if (thread != NULL) { thread->requestExit(); } mQueueChangedCondition.signal(); { Mutex::Autolock autoLock(mRepliesLock); mRepliesCondition.broadcast(); } if (!runningLocally && !thread->isCurrentThread()) { // If not running locally and this thread _is_ the looper thread, // the loop() function will return and never be called again. thread->requestExitAndWait(); } return OK; } void ALooper::post(const sp<AMessage> &msg, int64_t delayUs) { Mutex::Autolock autoLock(mLock); int64_t whenUs; if (delayUs > 0) { whenUs = GetNowUs() + delayUs; } else { whenUs = GetNowUs(); } List<Event>::iterator it = mEventQueue.begin(); while (it != mEventQueue.end() && (*it).mWhenUs <= whenUs) { ++it; } Event event; event.mWhenUs = whenUs; event.mMessage = msg; if (it == mEventQueue.begin()) { mQueueChangedCondition.signal(); } mEventQueue.insert(it, event); } bool ALooper::loop() { Event event; { Mutex::Autolock autoLock(mLock); if (mThread == NULL && !mRunningLocally) { return false; } if (mEventQueue.empty()) { mQueueChangedCondition.wait(mLock); return true; } int64_t whenUs = (*mEventQueue.begin()).mWhenUs; int64_t nowUs = GetNowUs(); if (whenUs > nowUs) { int64_t delayUs = whenUs - nowUs; mQueueChangedCondition.waitRelative(mLock, delayUs * 1000ll); return true; } event = *mEventQueue.begin(); mEventQueue.erase(mEventQueue.begin()); } event.mMessage->deliver(); // NOTE: It's important to note that at this point our "ALooper" object // may no longer exist (its final reference may have gone away while // delivering the message). We have made sure, however, that loop() // won't be called again. return true; } // to be called by AMessage::postAndAwaitResponse only sp<AReplyToken> ALooper::createReplyToken() { return new AReplyToken(this); } // to be called by AMessage::postAndAwaitResponse only status_t ALooper::awaitResponse(const sp<AReplyToken> &replyToken, sp<AMessage> *response) { // return status in case we want to handle an interrupted wait Mutex::Autolock autoLock(mRepliesLock); CHECK(replyToken != NULL); while (!replyToken->retrieveReply(response)) { { Mutex::Autolock autoLock(mLock); if (mThread == NULL) { return -ENOENT; } } mRepliesCondition.wait(mRepliesLock); } return OK; } status_t ALooper::postReply(const sp<AReplyToken> &replyToken, const sp<AMessage> &reply) { Mutex::Autolock autoLock(mRepliesLock); status_t err = replyToken->setReply(reply); if (err == OK) { mRepliesCondition.broadcast(); } return err; } } // namespace android
{ "content_hash": "930e941de2ee2f8ba1c92a9f0c4dad92", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 94, "avg_line_length": 23.781376518218625, "alnum_prop": 0.6205311542390194, "repo_name": "dAck2cC2/m3e", "id": "a35bc103726f725e132e94cef51415c334a9292e", "size": "6493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/frameworks/av/media/libstagefright/foundation/ALooper.cpp", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "10986" }, { "name": "Assembly", "bytes": "179243" }, { "name": "C", "bytes": "7339857" }, { "name": "C++", "bytes": "27763758" }, { "name": "CMake", "bytes": "277213" }, { "name": "HTML", "bytes": "47935" }, { "name": "Makefile", "bytes": "396212" }, { "name": "Objective-C++", "bytes": "2804" }, { "name": "Perl", "bytes": "3733" }, { "name": "Python", "bytes": "3628" }, { "name": "RenderScript", "bytes": "6664" }, { "name": "Shell", "bytes": "25112" } ], "symlink_target": "" }
package org.olat.group.model; import org.olat.group.BusinessGroupShort; /** * * @author srosse, [email protected], http://www.frentix.com */ public class BusinessGroupReference { private Long key; private String name; private Long originalKey; private String originalName; public BusinessGroupReference() { // } public BusinessGroupReference(BusinessGroupShort group) { this.key = group.getKey(); this.name = group.getName(); this.originalKey = group.getKey(); this.originalName = group.getName(); } public BusinessGroupReference(BusinessGroupShort group, Long originalKey, String originalName) { this.key = group.getKey(); this.name = group.getName(); this.originalKey = originalKey; this.originalName = originalName; } public Long getKey() { return key; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getOriginalKey() { return originalKey; } public void setOriginalKey(Long originalKey) { this.originalKey = originalKey; } public String getOriginalName() { return originalName; } public void setOriginalName(String originalName) { this.originalName = originalName; } }
{ "content_hash": "1520c1d13fd51a498e0d82bfb67290b9", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 97, "avg_line_length": 19.444444444444443, "alnum_prop": 0.7224489795918367, "repo_name": "stevenhva/InfoLearn_OpenOLAT", "id": "aac83b2f0f05dfdb8662a2523d093149ddd71e13", "size": "2047", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/olat/group/model/BusinessGroupReference.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import * as utils from '../../utils'; import i18n from '../../i18n'; import { util } from 'chessground'; import settings from '../../settings'; import formWidgets from '../shared/form'; import { renderEndedGameStatus } from '../shared/offlineRound'; import popupWidget from '../shared/popup'; import backbutton from '../../backbutton'; import helper from '../helper'; import m from 'mithril'; function renderAlways(ctrl) { var d = ctrl.root.data; return [ m('div.action', m('div.select_input', formWidgets.renderSelect('opponent', 'opponent', settings.ai.availableOpponents, settings.ai.opponent) )), m('button[data-icon=U]', { config: helper.ontouch(utils.f(ctrl.root.initAs, util.opposite(d.player.color))) }, i18n('createAGame')), m('button.fa', { className: 'fa-share-alt', config: helper.ontouch(ctrl.sharePGN) }, i18n('sharePGN')) ]; } export default { controller: function(root) { let isOpen = false; function open() { backbutton.stack.push(close); isOpen = true; } function close(fromBB) { if (fromBB !== 'backbutton' && isOpen) backbutton.stack.pop(); isOpen = false; } return { open: open, close: close, isOpen: function() { return isOpen; }, sharePGN: function() { window.plugins.socialsharing.share(root.replay.pgn()); }, root: root }; }, view: function(ctrl) { return popupWidget( 'offline_actions', null, [ renderEndedGameStatus(ctrl), renderAlways(ctrl) ], ctrl.isOpen(), ctrl.close ); } };
{ "content_hash": "7a19af7a840b5850f49ab464b90c44f7", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 108, "avg_line_length": 24.46268656716418, "alnum_prop": 0.6040268456375839, "repo_name": "garawaa/lichobile", "id": "c1b461af24cd41fe2a90fabe995d6bebccd5804b", "size": "1639", "binary": false, "copies": "1", "ref": "refs/heads/2.1.x", "path": "project/src/js/ui/ai/actions.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "101662" }, { "name": "HTML", "bytes": "1771" }, { "name": "JavaScript", "bytes": "574221" }, { "name": "Shell", "bytes": "637" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>huffman: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.14.0 / huffman - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> huffman <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-03 04:13:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-03 04:13:51 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.0 Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/huffman&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Huffman&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: Data Compression&quot; &quot;keyword: Code&quot; &quot;keyword: Huffman Tree&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; &quot;category: Miscellaneous/Extracted Programs/Combinatorics&quot; &quot;date: 2003-10&quot; ] authors: [ &quot;Laurent Théry&quot; ] bug-reports: &quot;https://github.com/coq-contribs/huffman/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/huffman.git&quot; synopsis: &quot;A correctness proof of Huffman algorithm&quot; description: &quot;&quot;&quot; This directory contains the proof of correctness of Huffman algorithm as described in: David A. Huffman, &quot;A Method for the Construction of Minimum-Redundancy Codes,&quot; Proc. IRE, pp. 1098-1101, September 1952.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/huffman/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=82b32f5cfbe4c692d497c8561ff2ec4a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-huffman.8.8.0 coq.8.14.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0). The following dependencies couldn&#39;t be met: - coq-huffman -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-huffman.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "8565a2ee3fe009a51be4e4e69fb175e3", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 319, "avg_line_length": 42.69461077844311, "alnum_prop": 0.5493688639551192, "repo_name": "coq-bench/coq-bench.github.io", "id": "d27eb239d7fe1029b79ee973189d21562eff75ed", "size": "7156", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.14.0/huffman/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <HTML><head><TITLE>Manpage of webalizer</TITLE> <meta charset="utf-8"> <link rel="stylesheet" href="/css/main.css" type="text/css"> </head> <body> <header class="site-header"> <div class="wrap"> <div class="site-title"><a href="/manpages/index.html">linux manpages</a></div> <div class="site-description">{"type":"documentation"}</div> </div> </header> <div class="page-content"><div class="wrap"> <H1>webalizer</H1> Section: The Webalizer (1)<BR>Updated: 12-Jul-2008<BR><A HREF="#index">Index</A> <A HREF="/manpages/index.html">Return to Main Contents</A><HR> <A NAME="lbAB">&nbsp;</A> <H2>NAME</H2> webalizer - A web server log file analysis tool. <A NAME="lbAC">&nbsp;</A> <H2>SYNOPSIS</H2> <B>webalizer</B> [<I> option ... </I>] [<I> log-file </I>] <P> <B>webazolver</B> [<I> option ... </I>] [<I> log-file </I>] <P> <A NAME="lbAD">&nbsp;</A> <H2>DESCRIPTION</H2> The <I>Webalizer</I> is a web server log file analysis program which produces usage statistics in HTML format for viewing with a browser. The results are presented in both columnar and graphical format, which facilitates interpretation. Yearly, monthly, daily and hourly usage statistics are presented, along with the ability to display usage by site, URL, referrer, user agent (browser), username, search strings, entry/exit pages, and country (some information may not be available if not present in the log file being processed). <P> The <I>Webalizer</I> supports <B>CLF</B> (common log format) log files, as well as <B>Combined</B> log formats as defined by NCSA and others, and variations of these which it attempts to handle intelligently. In addition, the <I>Webalizer</I> supports <B>xferlog</B> formatted (<I>FTP</I>) log files, <B>squid</B> proxy logs and <B>W3C</B> extended format logs. Logs may also be compressed, via <I>gzip</I> (.gz) or, if enabled at compile time, <I>bzip2</I> (.bz2). If a compressed log file is detected, it will be automatically uncompressed while it is read. Compressed logs must have the standard <I>gzip</I> extension of <B>.gz</B> or <I>bzip2</I> extension of <B>.bz2</B>. <P> <I>webazolver</I> is normally just a symbolic link to the <I>Webalizer</I>. When run as <I>webazolver</I>, only DNS file creation/updates are performed, and the program will exit once complete. All normal options and configuration directives are available, however many will not be used. In addition, a DNS cache file must be specified. If the number of DNS children processes to use are not specified, the <I>webazolver</I> will default to <B>5</B>. <P> This documentation applies to The Webalizer Version 2.20 <A NAME="lbAE">&nbsp;</A> <H2>RUNNING THE WEBALIZER</H2> The <I>Webalizer</I> was designed to be run from a Unix command line prompt or as a <B><A HREF="/manpages/index.html?8+crond">crond</A>(8)</B> job. Once executed, the general flow of the program is: <DL COMPACT> <DT><B>o</B> <DD> A default configuration file is scanned for. A file named <I>webalizer.conf</I> is searched for in the current directory, and if found, and is owned by the invoking user, then its configuration data is parsed. If the file is not present in the current directory, the file <I>/etc/webalizer.conf</I> is searched for and, if found, is used instead. <DT><B>o</B> <DD> Any command line arguments given to the program are parsed. This may include the specification of a configuration file, which is processed at the time it is encountered. <DT><B>o</B> <DD> If a log file was specified, it is opened and made ready for processing. If no log file was given, <I>STDIN</I> is used for input. If the log filename '<B>-</B>' is specified, <I>STDIN</I> will be forced. <DT><B>o</B> <DD> If an output directory was specified, the program does a <B><A HREF="/manpages/index.html?2+chdir">chdir</A>(2)</B> to that directory in preparation for generating output. If no output directory was given, the current directory is used. <DT><B>o</B> <DD> If a non-zero number of DNS Children processes were specified, they will be started, and the specified log file will be processed, creating or updating the specified DNS cache file. <DT><B>o</B> <DD> If no hostname was given, the program attempts to get the hostname using a <B><A HREF="/manpages/index.html?2+uname">uname</A>(2)</B> system call. If that fails, <I>localhost</I> is used. <DT><B>o</B> <DD> A history file is searched for in the current directory (output directory) and read if found. This file keeps totals for previous months, which is used in the main <I>index.html</I> HTML document. <B>Note:</B> The file location can now be specified with the <I>HistoryName</I> configuration option. <DT><B>o</B> <DD> If incremental processing was specified, a data file is searched for and loaded if found, containing the 'internal state' data of the program at the end of a previous run. <B>Note:</B> The file location can now be specified with the <I>IncrementalName</I> configuration option. <DT><B>o</B> <DD> Main processing begins on the log file. If the log spans multiple months, a separate HTML document is created for each month. <DT><B>o</B> <DD> After main processing, the main <I>index.html</I> page is created, which has totals by month and links to each months HTML document. <DT><B>o</B> <DD> A new history file is saved to disk, which includes totals generated by The <I>Webalizer</I> during the current run. <DT><B>o</B> <DD> If incremental processing was specified, a data file is written that contains the 'internal state' data at the end of this run. </DL> <A NAME="lbAF">&nbsp;</A> <H2>INCREMENTAL PROCESSING</H2> The <I>Webalizer</I> supports incremental run capability. Simply put, this allows processing large log files by breaking them up into smaller pieces, and processing these pieces instead. What this means in real terms is that you can now rotate your log files as often as you want, and still be able to produce monthly usage statistics without the loss of any detail. Basically, The <I>Webalizer</I> saves and restores all internal data in a file named <I>webalizer.current</I>. This allows the program to 'start where it left off' so to speak, and allows the preservation of detail from one run to the next. The data file is placed in the current output directory, and is a plain ASCII text file that can be viewed with any standard text editor. It's location and name may be changed using the <I>IncrementalName</I> configuration keyword. <P> Some special precautions need to be taken when using the incremental run capability of The <I>Webalizer</I>. Configuration options should not be changed between runs, as that could cause corruption of the internal data stored. For example, changing the <I>MangleAgents</I> level will cause different representations of user agents to be stored, producing invalid results in the user agents section of the report. If you need to change configuration options, do it at the end of the month after normal processing of the previous month and before processing the current month. You may also want to delete the <I>webalizer.current</I> file as well. <P> The <I>Webalizer</I> also attempts to prevent data duplication by keeping track of the timestamp of the last record processed. This timestamp is then compared to current records being processed, and any records that were logged previous to that timestamp are ignored. This, in theory, should allow you to re-process logs that have already been processed, or process logs that contain a mix of processed/not yet processed records, and not produce duplication of statistics. The only time this may break is if you have duplicate timestamps in two separate log files... any records in the second log file that do have the same timestamp as the last record in the previous log file processed, will be discarded as if they had already been processed. There are lots of ways to prevent this however, for example, stopping the web server before rotating logs will prevent this situation. This setup also necessitates that you always process logs in chronological order, otherwise data loss will occur as a result of the timestamp compare. <A NAME="lbAG">&nbsp;</A> <H2>REVERSE DNS LOOKUPS</H2> The <I>Webalizer</I> fully supports IPv4 and IPv6 DNS lookups, and maintains a cache of those lookups to reduce processing the same addresses in subsequent runs. The cache file can be created at run-time, or may be created before running the webalizer using either the stand alone '<I>webazolver</I>' program, or The Webalizer (DNS) Cache file manager program '<I>wcmgr</I>'. In order to perform reverse lookups, a <B>DNSCache</B> file must be specified, either on the command line or in a configuration file. In order to create/update the cache file at run-time, the number of <B>DNSChildren</B> must also be specified, and can be anything between 1 and 100. This specifies the number of child processes to be forked, each of which will perform network DNS queries in order to lookup up the addresses and update the cache. Cached entries that are older than a specified TTL (time to live) will be expired, and if encountered again in a log, will be looked up at that time in order to 'freshen' them (verify the name is still the same and update its timestamp). The default TTL is 7 days, however may be set to anything between 1 and 100 days. Using the '<I>wcmgr</I>' program, entries may also be marked as 'permanent', in which case they will persist (with an infinite TTL) in the cache until manually removed. See the file <B>DNS.README</B> for additional information and examples. <A NAME="lbAH">&nbsp;</A> <H2>GEOLOCATION LOOKUPS</H2> The <I>Webalizer</I> has the ability to perform geolocation lookups on IP addresses using either it's own internal <I>GeoDB</I> database, or optionally the <I>GeoIP</I> database from MaxMind, Inc. (<A HREF="http://www.maxmind.com">www.maxmind.com</A>). If used, unresolved addresses will be searched for in the database and its country of origin will be returned if found. This actually produces more accurate <I>Country</I> information than DNS lookups, since the DNS address space has additional <I>gcTLDs</I> that do not necessarily map to a specific country (such as <I>.net</I> and <I>.com</I>). It is possible to use both DNS lookups and geolocation lookups at the same time, which will cause any addresses that could not be resolved using DNS lookups to then be looked up in the database, greatly reducing the number of <I>Unknown/Unresolved</I> entries in the generated reports. The native <I>GeoDB</I> geolocation database provided by The <I>Webalizer</I> fully supports both <I>IPv4</I> and <I>IPv6</I> lookups, is updated regularly and is the preferred geolocation method for use with The <I>Webalizer</I>. The most current version of the database can be obtained from our ftp site (<I><A HREF="ftp://ftp.mrunix.net/">ftp://ftp.mrunix.net/</A></I>). <A NAME="lbAI">&nbsp;</A> <H2>COMMAND LINE OPTIONS</H2> The <I>Webalizer</I> supports many different configuration options that will alter the way the program behaves and generates output. Most of these can be specified on the command line, while some can only be specified in a configuration file. The command line options are listed below, with references to the corresponding configuration file keywords. <P> <I>General Options</I> <DL COMPACT> <DT><B>-h</B> <DD> Display all available command line options and exit program. <DT><B>-v</B> <DD> Be verbose. Will cause the program to output informational and <I>Debug</I> messages at run-time. <DT><B>-V</B> <DD> Display the program version and exit. Additional program specific information will be displayed if <I>verbose</I> mode is also used (e.g. '<I>-vV</I>'), which can be useful when submitting bug reports. <DT><B>-d</B> <DD> <B>Debug</B>. Display debugging information for errors and warnings. <DT><B>-i</B> <DD> <B>IgnoreHist</B>. Ignore history. <B>USE WITH CAUTION</B>. This will cause The <I>Webalizer</I> to ignore any previous monthly history file only. Incremental data (if present) is still processed. <DT><B>-b</B> <DD> <B>IgnoreState</B>. Ignore incremental data file. <B>USE WITH CAUTION</B>. This will cause The <I>Webalizer</I> to ignore any existing incremental data file. By ignoring the incremental data file, all previous processing for the current month will be lost and those logs must be re-processed. <DT><B>-p</B> <DD> <B>Incremental</B>. Preserve internal data between runs. <DT><B>-q</B> <DD> <B>Quiet</B>. Suppress informational messages. Does not suppress warnings or errors. <DT><B>-Q</B> <DD> <B>ReallyQuiet</B>. Suppress all messages including warnings and errors. <DT><B>-T</B> <DD> <B>TimeMe</B>. Force display of timing information at end of processing. <DT><B>-c </B><I>file</I> <DD> Use configuration file <I>file</I>. <DT><B>-n </B><I>name</I> <DD> <B>HostName</B>. Use the hostname <I>name</I>. <DT><B>-o </B><I>dir</I> <DD> <B>OutputDir</B>. Use output directory <I>dir</I>. <DT><B>-t </B><I>name</I> <DD> <B>ReportTitle</B>. Use <I>name</I> for report title. <DT><B>-F </B>( <B>c</B>lf | <B>f</B>tp | <B>s</B>quid | <B>w</B>3c ) <DD> <B>LogType</B>. Specify log type to be processed. Value can be either <I>c</I>lf, <I>f</I>tp, <I>s</I>quid or <I>w</I>3c format. If not specified, will default to <B>CLF</B> format. <I>FTP</I> logs must be in standard wu-ftpd <I>xferlog</I> format. <DT><B>-f</B> <DD> <B>FoldSeqErr</B>. Fold out of sequence log records back into analysis, by treating as if they were the same date/time as the last good record. Normally, out of sequence log records are simply ignored. <DT><B>-Y</B> <DD> <B>CountryGraph</B>. Suppress country graph. <DT><B>-G</B> <DD> <B>HourlyGraph</B>. Suppress hourly graph. <DT><B>-x </B><I>name</I> <DD> <B>HTMLExtension</B>. Defines HTML file extension to use. If not specified, defaults to <I>html</I>. Do not include the leading period. <DT><B>-H</B> <DD> <B>HourlyStats</B>. Suppress hourly statistics. <DT><B>-K </B><I>num</I> <DD> <B>IndexMonths</B>. Specify how many months should be displayed in the main index (yearly summary) table. Default is 12 months. Can be set to anything between 12 and 120 months (1 to 10 years). <DT><B>-k </B><I>num</I> <DD> <B>GraphMonths</B>. Specify how many months should be displayed in the main index (yearly summary) graph. Default is 12 months. Can be set to anything between 12 and 72 months (1 to 6 years). <DT><B>-L</B> <DD> <B>GraphLegend</B>. Suppress color coded graph legends. <DT><B>-l </B><I>num</I> <DD> <B>GraphLines</B>. Specify number of background lines. Default is 2. Use zero ('0') to disable the lines. <DT><B>-P </B><I>name</I> <DD> <B>PageType</B>. Specify file extensions that are considered <I>pages</I>. Sometimes referred to as <I>pageviews</I>. <DT><B>-O </B><I>name</I> <DD> <B>OmitPage</B>. Specify URLs to exclude from being counted as <I>pages</I>. <DT><B>-m </B><I>num</I> <DD> <B>VisitTimeout</B>. Specify the Visit timeout period. Specified in number of seconds. Default is 1800 seconds (30 minutes). <DT><B>-I </B><I>name</I> <DD> <B>IndexAlias</B>. Use the filename <I>name</I> as an additional alias for <I>index.</I>. <DT><B>-M </B><I>num</I> <DD> <B>MangleAgents</B>. Mangle user agent names according to the mangle level specified by <I>num</I>. Mangle levels are: <DL COMPACT><DT><DD> <DL COMPACT> <DT><B>5</B> <DD> Browser name and major version. <DT><B>4</B> <DD> Browser name, major and minor version. <DT><B>3</B> <DD> Browser name, major version, minor version to two decimal places. <DT><B>2</B> <DD> Browser name, major and minor versions and sub-version. <DT><B>1</B> <DD> Browser name, version and machine type if possible. <DT><B>0</B> <DD> All information (left unchanged). </DL> </DL> <DT><B>-g </B><I>num</I> <DD> <B>GroupDomains</B>. Automatically group sites by domain. The grouping level specified by <I>num</I> can be thought of as 'the number of dots' to display in the grouping. The default value of <B>0</B> disables any domain grouping. <DT><B>-D </B><I>name</I> <DD> <B>DNSCache</B>. Use the DNS cache file <I>name</I>. <DT><B>-N </B><I>num</I> <DD> <B>DNSChildren</B>. Use <I>num</I> DNS children processes to perform DNS lookups, either creating or updating the DNS cache file. Specify zero (<B>0</B>) to disable cache file creation/updates. If given, a DNS cache filename must be specified. <DT><B>-j</B> <DD> Enable <I>GeoDB</I>. This enables the internal GeoDB geolocation services provided by The <I>Webalizer</I>. <DT><B>-J </B><I>name</I> <DD> <B>GeoDBDatabase</B>. Use the alternate GeoDB database <I>name</I>. <DT><B>-w</B> <DD> Enable <I>GeoIP</I>. Enables GeoIP (by MaxMind Inc.) geolocation services. If native <I>GeoDB</I> services are also enabled, then this option will have no effect. <DT><B>-W </B><I>name</I> <DD> <B>GeoIPDatabase</B>. Use the alternate GeoIP database <I>name</I>. <DT><B>-z </B><I>name</I> <DD> <B>FlagDir</B>. Specify location of the country flag graphics and enable their display in the top country table. The directory <I>name</I> is relative to the output directory being used unless an absolute path is given (ie: starts with a leading '/'). </DL> <P> <I>Hide Options</I> <DL COMPACT> <DT><B>-a </B><I>name</I> <DD> <B>HideAgent</B>. Hide user agents matching <I>name</I>. <DT><B>-r </B><I>name</I> <DD> <B>HideReferrer</B>. Hide referrer matching <I>name</I>. <DT><B>-s </B><I>name</I> <DD> <B>HideSite</B>. Hide site matching <I>name</I>. <DT><B>-X</B> <DD> <B>HideAllSites</B>. Hide all individual sites (only display groups). <DT><B>-u </B><I>name</I> <DD> <B>HideURL</B>. Hide URL matching <I>name</I>. </DL> <P> <I>Table size options</I> <DL COMPACT> <DT><B>-A </B><I>num</I> <DD> <B>TopAgents</B>. Display the top <I>num</I> user agents table. <DT><B>-R </B><I>num</I> <DD> <B>TopReferrers</B>. Display the top <I>num</I> referrers table. <DT><B>-S </B><I>num</I> <DD> <B>TopSites</B>. Display the top <I>num</I> sites table. <DT><B>-U </B><I>num</I> <DD> <B>TopURLs</B>. Display the top <I>num</I> URLs table. <DT><B>-C </B><I>num</I> <DD> <B>TopCountries</B>. Display the top <I>num</I> countries table. <DT><B>-e </B><I>num</I> <DD> <B>TopEntry</B>. Display the top <I>num</I> entry pages table. <DT><B>-E </B><I>num</I> <DD> <B>TopExit</B>. Display the top <I>num</I> exit pages table. </DL> <A NAME="lbAJ">&nbsp;</A> <H2>CONFIGURATION FILES</H2> Configuration files are standard <B><A HREF="/manpages/index.html?7+ASCII">ASCII</A>(7)</B> text files that may be created or edited using any standard editor. Blank lines and lines that begin with a pound sign ('#') are ignored. Any other lines are considered to be configuration lines, and have the form &quot;Keyword Value&quot;, where the 'Keyword' is one of the currently available configuration keywords defined below, and 'Value' is the value to assign to that particular option. Any text found after the keyword up to the end of the line is considered the keyword's value, so you should not include anything after the actual value on the line that is not actually part of the value being assigned. The file <I>sample.conf</I> provided with the distribution contains lots of useful documentation and examples as well. <P> <I>General Configuration Keywords</I> <DL COMPACT> <DT><B>LogFile </B><I>name</I> <DD> Use log file named <I>name</I>. If none specified, <I>STDIN</I> will be used. <DT><B>LogType </B><I>name</I> <DD> Specify log file type as <I>name</I>. Values can be either <I>clf</I>, <I>squid</I>, <I>ftp</I> or <I>w3c</I>, with the default being <B>clf</B>. <DT><B>OutputDir </B><I>dir</I> <DD> Create output in the directory <I>dir</I>. If none specified, the current directory will be used. <DT><B>HistoryName </B><I>name</I> <DD> Filename to use for history file. Relative to output directory unless absolute name is given (ie: starts with '/'). Defaults to '<B>webalizer.hist</B>' in the standard output directory. <DT><B>ReportTitle </B><I>name</I> <DD> Use the title string <I>name</I> for the report title. If none specified, use the default of (in english) &quot;<I>Usage Statistics for </I>&quot;. <DT><B>HostName </B><I>name</I> <DD> Set the hostname for the report as <I>name</I>. If none specified, an attempt will be made to gather the hostname via a <B><A HREF="/manpages/index.html?2+uname">uname</A>(2)</B> system call. If that fails, <I>localhost</I> will be used. <DT><B>UseHTTPS </B>( yes | <B>no</B> ) <DD> Use <I>https://</I> on links to URLS, instead of the default <I>http://</I>, in the '<B>Top URLs</B>' table. <DT><B>HTAccess </B>( yes | <B>no</B> ) <DD> Enables the creation of a default .htaccess file in the output directory. <DT><B>Quiet </B>( yes | <B>no</B> ) <DD> Suppress informational messages. Warning and Error messages will not be suppressed. <DT><B>ReallyQuiet </B>( yes | <B>no</B> ) <DD> Suppress all messages, including Warning and Error messages. <DT><B>Debug </B>( yes | <B>no</B> ) <DD> Print extra debugging information on Warnings and Errors. <DT><B>TimeMe </B>( yes | <B>no</B> ) <DD> Force timing information at end of processing. <DT><B>GMTTime </B>( yes | <B>no</B> ) <DD> Use <I>GMT </I>(<I>UTC</I>) time instead of local timezone for reports. <DT><B>IgnoreHist </B>( yes | <B>no</B> ) <DD> Ignore previous monthly history file. <B>USE WITH CAUTION</B>. Does not prevent <I>Incremental</I> file processing. <DT><B>IgnoreState </B>( yes | <B>no</B> ) <DD> Ignore incremental data file. <B>USE WITH CAUTION</B>. By ignoring the incremental data file, all previous processing for the current month will be lost and those logs must be re-processed. <DT><B>FoldSeqErr </B>( yes | <B>no</B> ) <DD> Fold out of sequence log records back into analysis by treating them as if they had the same date/time as the last good record. Normally, out of sequence log records are ignored. <DT><B>CountryGraph </B>( <B>yes</B> | no ) <DD> Display Country Usage Graph in output report. <DT><B>CountryFlags </B>( yes | <B>no</B> ) <DD> Enable or disable the display of flags in the top country table. <DT><B>FlagDir </B><I>name</I> <DD> Specifies the directory <I>name</I> where the flag graphics are located. If not specified, the default is in the <I>flags</I> directory directly under the output directory being used. If specified, the display of country flags will be enabled by default. Using '<I>FlagDir flags</I>' is identical to using '<I>CountryFlags yes</I>'. <DT><B>DailyGraph </B>( <B>yes</B> | no ) <DD> Display Daily Graph in output report. <DT><B>DailyStats </B>( <B>yes</B> | no ) <DD> Display Daily Statistics in output report. <DT><B>HourlyGraph </B>( <B>yes</B> | no ) <DD> Display Hourly Graph in output report. <DT><B>HourlyStats </B>( <B>yes</B> | no ) <DD> Display Hourly Statistics in output report. <DT><B>PageType </B><I>name</I> <DD> Define the file extensions to consider as a <I>page</I>. If a file is found to have the same extension as <I>name</I>, it will be counted as a <I>page</I> (sometimes called a <I>pageview</I>). <DT><B>PagePrefix </B><I>name</I> <DD> Allows URLs with the prefix <I>name</I> to be counted as a <I>page</I> type regardless of actual file type. This allows you to treat contents under specified directories as pages no matter what their extension is. <DT><B>OmitPage </B><I>name</I> <DD> Specifies URLs which should not be counted as pages, regardless of their extension (or lack thereof). <DT><B>GraphLegend </B>( <B>yes</B> | no ) <DD> Allows the color coded graph legends to be enabled/disabled. <DT><B>GraphLines </B><I>num</I> <DD> Specify the number of background reference lines displayed on the graphs produced. Disable by using zero ('<B>0</B>'), default is <B>2</B>. <DT><B>IndexMonths </B><I>num</I> <DD> Specify the number of months to display in the main index (yearly summary) table. Default is 12 months. Can be set to anything between 12 and 120 months (1 to 10 years). <DT><B>YearHeaders </B>( <B>yes</B> | no ) <DD> Enable/disable the display of year headers in the main index (yearly summary) table. If enabled, year headers will be shown when the table is displaying more than 16 months worth of data. Values can be 'yes' or 'no'. Default is 'yes'. <DT><B>YearTotals </B>( <B>yes</B> | no ) <DD> Enable/disable the display of year totals in the main index (yearly summary) table. If enabled, year totals will be shown when the table is displaying more than 16 months worth of data. Values can be 'yes' or 'no'. Default is 'yes'. <DT><B>GraphMonths </B><I>num</I> <DD> Specify the number of months to display in the main index (yearly summary) graph. Default is 12 months. Can be set to anything between 12 and 72 months (1 to 6 years). <DT><B>VisitTimeout </B><I>num</I> <DD> Specifies the visit timeout value. Default is <I>1800 seconds</I> (30 minutes). A visit is determined by looking at the difference in time between the current and last request from a specific site. If the difference is greater or equal to the timeout value, the request is counted as a new visit. Specified in seconds. <DT><B>IndexAlias </B><I>name</I> <DD> Use <I>name</I> as an additional alias for <I>index.*</I>. <DT><B>DefaultIndex </B>( <B>yes</B> | no ) <DD> Enables or disables the use of '<B>index.</B>' as a default index name to be stripped from the end of URLs. This does not effect any index names that may be defined with the <I>IndexAlias</I> option. <DT><B>MangleAgents </B><I>num</I> <DD> Mangle user agent names based on mangle level <I>num</I>. See the <I>-M</I> command line switch for mangle levels and their meaning. The default is <B>0</B>, which doesn't mangle user agents at all. <DT><B>StripCGI </B>( <B>yes</B> | no ) <DD> Determines if URL CGI variables should be stripped from the end of URLs. Values may be 'yes' or 'no', with the default being 'yes'. <DT><B>TrimSquidURL </B><I>num</I> <DD> Allows squid log URLs to be reduced in granularity by truncating them after <I>num</I> slashes ('/') after the http:// prefix. A setting of one (1) will cause all URLs to be summarized by domain only. The default value is zero (0), which will disable any URL modifications and leave them exactly as found in the log file. <DT><B>SearchEngine</B> <I>name</I> <I>variable</I> <DD> Allows the specification of search engines and their query strings. The <I>name</I> is the name to match against the referrer string for a given search engine. The <I>variable</I> is the cgi variable that the search engine uses for queries. See the <B>sample.conf</B> file for example usage with common search engines. <DT><B>SearchCaseI</B> ( <B>yes</B> | no ) <DD> Determines if search strings should be treated case insensitive or not. The default is 'yes', which lowercases all search strings (treat as case insensitive). <DT><B>Incremental </B>( yes | <B>no</B> ) <DD> Enable Incremental mode processing. <DT><B>IncrementalName </B><I>name</I> <DD> Filename to use for incremental data. Relative to output directory unless an absolute name is given (ie: starts with '/'). Defaults to '<B>webalizer.current</B>' in the standard output directory. <DT><B>DNSCache </B><I>name</I> <DD> Filename to use for the DNS cache. Relative to output directory unless an absolute name is given (ie: starts with '/'). <DT><B>DNSChildren </B><I>num</I> <DD> Number of children DNS processes to run in order to create/update the DNS cache file. Specify zero (<B>0</B>) to disable. <DT><B>CacheIPs </B>( yes | <B>no</B> ) <DD> Cache unresolved IP addresses in the DNS database. Default is '<B>no</B>'. <DT><B>CacheTTL </B><I>num</I> <DD> DNS cache entry time to live (TTL) in days. Default is 7 days. May be any value between 1 and 100. <DT><B>GeoDB </B>( yes | <B>no</B> ) <DD> Allows native GeoDB geolocation services to be enabled or disabled. Default value is '<B>no</B>'. <DT><B>GeoDBDatabase </B><I>name</I> <DD> Allows the use of an alternate GeoDB database <I>name</I>. If not specified, the default database will be used. <DT><B>GeoIP </B>( yes | <B>no</B> ) <DD> Allows GeoIP (by MaxMind Inc.) geolocation services to be enabled or disabled. Default is '<B>no</B>'. If native <I>GeoDB</I> geolocation services are also enabled, then this option will have no effect (and the native <I>GeoDB</I> services will be used). <DT><B>GeoIPDatabase </B><I>name</I> <DD> Allows the use of an alternate GeoIP database <I>name</I>. If not specified, the default database will be used. </DL> <P> <I>Top Table Keywords</I> <DL COMPACT> <DT><B>TopAgents </B><I>num</I> <DD> Display the top <I>num</I> User Agents table. Use zero to disable. <DT><B>AllAgents </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> User Agents. <DT><B>TopReferrers </B><I>num</I> <DD> Display the top <I>num</I> Referrers table. Use zero to disable. <DT><B>AllReferrers </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> Referrers. <DT><B>TopSites </B><I>num</I> <DD> Display the top <I>num</I> Sites table. Use zero to disable. <DT><B>TopKSites </B><I>num</I> <DD> Display the top <I>num</I> Sites (by KByte) table. Use zero to disable. <DT><B>AllSites </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> Sites. <DT><B>TopURLs </B><I>num</I> <DD> Display the top <I>num</I> URLs table. Use zero to disable. <DT><B>TopKURLs </B><I>num</I> <DD> Display the top <I>num</I> URLs (by KByte) table. Use zero to disable. <DT><B>AllURLs </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> URLs. <DT><B>TopCountries </B><I>num</I> <DD> Display the top <I>num</I> Countries in the table. Use zero to disable. <DT><B>TopEntry </B><I>num</I> <DD> Display the top <I>num</I> Entry Pages in the table. Use zero to disable. <DT><B>TopExit </B><I>num</I> <DD> Display the top <I>num</I> Exit Pages in the table. Use zero to disable. <DT><B>TopSearch </B><I>num</I> <DD> Display the top <I>num</I> Search Strings in the table. Use zero to disable. <DT><B>AllSearchStr </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> Search Strings. <DT><B>TopUsers </B><I>num</I> <DD> Display the top <I>num</I> Usernames in the table. Use zero to disable. Usernames are only available if using http based authentication. <DT><B>AllUsers </B>( yes | <B>no</B> ) <DD> Create separate HTML page with <B>All</B> Usernames. </DL> <P> <I>Hide/Ignore/Group/Include Keywords</I> <DL COMPACT> <DT><B>HideAgent </B><I>name</I> <DD> Hide User Agents that match <I>name</I>. <DT><B>HideReferrer </B><I>name</I> <DD> Hide Referrers that match <I>name</I>. <DT><B>HideSite </B><I>name</I> <DD> Hide Sites that match <I>name</I>. <DT><B>HideAllSites </B>( yes | <B>no</B> ) <DD> Hide all individual sites. This causes only grouped sites to be displayed. <DT><B>HideURL </B><I>name</I> <DD> Hide URLs that match <I>name</I>. <DT><B>HideUser </B><I>name</I> <DD> Hide Usernames that match <I>name</I>. <DT><B>IgnoreAgent </B><I>name</I> <DD> Ignore User Agents that match <I>name</I>. <DT><B>IgnoreReferrer </B><I>name</I> <DD> Ignore Referrers that match <I>name</I>. <DT><B>IgnoreSite </B><I>name</I> <DD> Ignore Sites that match <I>name</I>. <DT><B>IgnoreURL </B><I>name</I> <DD> Ignore URLs that match <I>name</I>. <DT><B>IgnoreUser </B><I>name</I> <DD> Ignore Usernames that match <I>name</I>. <DT><B>GroupAgent </B><I>name</I> [<I>Label</I>] <DD> Group User Agents that match <I>name</I>. Display <I>Label</I> in 'Top Agent' table if given (instead of <I>name</I>). <I>name</I> may be enclosed in quotes. <DT><B>GroupReferrer </B><I>name</I> [<I>Label</I>] <DD> Group Referrers that match <I>name</I>. Display <I>Label</I> in 'Top Referrer' table if given (instead of <I>name</I>). <I>name</I> may be enclosed in quotes. <DT><B>GroupSite </B><I>name</I> [<I>Label</I>] <DD> Group Sites that match <I>name</I>. Display <I>Label</I> in 'Top Site' table if given (instead of <I>name</I>). <I>name</I> may be enclosed in quotes. <DT><B>GroupDomains </B><I>num</I> <DD> Automatically group sites by domain. The value <I>num</I> specifies the level of grouping, and can be thought of as the 'number of dots' to be displayed. The default value of <B>0</B> disables domain grouping. <DT><B>GroupURL </B><I>name</I> [<I>Label</I>] <DD> Group URLs that match <I>name</I>. Display <I>Label</I> in 'Top URL' table if given (instead of <I>name</I>). <I>name</I> may be enclosed in quotes. <DT><B>GroupUser </B><I>name</I> [<I>Label</I>] <DD> Group Usernames that match <I>name</I>. Display <I>Label</I> in 'Top Usernames' table if given (instead of <I>name</I>). <I>name</I> may be enclosed in quotes. <DT><B>IncludeSite </B><I>name</I> <DD> Force inclusion of sites that match <I>name</I>. Takes precedence over <B>Ignore*</B> keywords. <DT><B>IncludeURL </B><I>name</I> <DD> Force inclusion of URLs that match <I>name</I>. Takes precedence over <B>Ignore*</B> keywords. <DT><B>IncludeReferrer </B><I>name</I> <DD> Force inclusion of Referrers that match <I>name</I>. Takes precedence over <B>Ignore*</B> keywords. <DT><B>IncludeAgent </B><I>name</I> <DD> Force inclusion of User Agents that match <I>name</I>. Takes precedence over <B>Ignore*</B> keywords. <DT><B>IncludeUser </B><I>name</I> <DD> Force inclusion of Usernames that match <I>name</I>. Takes precedence over <B>Ignore*</B> keywords. </DL> <P> <I>HTML Generation Keywords</I> <DL COMPACT> <DT><B>HTMLExtension </B><I>text</I> <DD> Defines the HTML file extension to use. Default is <I>html</I>. Do not include the leading period! <DT><B>HTMLPre </B><I>text</I> <DD> Insert <I>text</I> at the very beginning of the generated HTML file. Defaults to a standard html 3.2 <I>DOCTYPE</I> record. <DT><B>HTMLHead </B><I>text</I> <DD> Insert <I>text</I> within the &lt;HEAD&gt;&lt;/HEAD&gt; block of the HTML file. <DT><B>HTMLBody </B><I>text</I> <DD> Insert <I>text</I> in HTML page, starting with the &lt;BODY&gt; tag. If used, the first line must be a <I>&lt;BODY ...&gt;</I> tag. Multiple lines may be specified. <DT><B>HTMLPost </B><I>text</I> <DD> Insert <I>text</I> at top (before horiz. rule) of HTML pages. Multiple lines may be specified. <DT><B>HTMLTail </B><I>text</I> <DD> Insert <I>text</I> at bottom of the HTML page. The <I>text</I> is top and right aligned within a table column at the end of the report. <DT><B>HTMLEnd </B><I>text</I> <DD> Insert <I>text</I> at the very end of the HTML page. If not specified, the default is to insert the ending &lt;/BODY&gt; and &lt;/HTML&gt; tags. If used, you <I>must</I> supply these tags yourself. <DT><B>LinkReferrer </B>( yes | <B>no</B> ) <DD> Determines if the referrers listed in the top referrers table should be displayed as plain text, or as a link to the referrer URL. <DT><B>ColorHit </B>( rrggbb | <B>00805c</B> ) <DD> Sets the graph's hit-color to the specified html color (no '#'). <DT><B>ColorFile </B>( rrggbb | <B>0040ff</B> ) <DD> Sets the graph's file-color to the specified html color (no '#'). <DT><B>ColorSite </B>( rrggbb | <B>ff8000</B> ) <DD> Sets the graph's site-color to the specified html color (no '#'). <DT><B>ColorKbyte </B>( rrggbb | <B>ff0000</B> ) <DD> Sets the graph's kilobyte-color to the specified html color (no '#'). <DT><B>ColorPage </B>( rrggbb | <B>00e0ff</B> ) <DD> Sets the graph's page-color to the specified html color (no '#'). <DT><B>ColorVisit </B>( rrggbb | <B>ffff00</B> ) <DD> Sets the graph's visit-color to the specified html color (no '#'). <DT><B>ColorMisc </B>( rrggbb | <B>00e0ff</B> ) <DD> Sets the 'miscellaneous' color for table headers (not graphs) to the specified html color (no '#'). <DT><B>PieColor1 </B>( rrggbb | <B>800080</B> ) <DD> Sets the pie's first optional color to the specified html color (no '#'). <DT><B>PieColor2 </B>( rrggbb | <B>80ffc0</B> ) <DD> Sets the pie's second optional color to the specified html color (no '#'). <DT><B>PieColor3 </B>( rrggbb | <B>ff00ff</B> ) <DD> Sets the pie's third optional color to the specified html color (no '#'). <DT><B>PieColor4 </B>( rrggbb | <B>ffc480</B> ) <DD> Sets the pie's fourth optional color to the specified html color (no '#'). </DL> <P> <I>Dump Object Keywords</I> <P> The <I>Webalizer</I> allows you to export processed data to other programs by using <I>tab delimited</I> text files. The <I>Dump*</I> commands specify which files are to be written, and where. <DL COMPACT> <DT><B>DumpPath </B><I>name</I> <DD> Save dump files in directory <I>name</I>. If not specified, the default output directory will be used. Do not specify a trailing slash ('/'). <DT><B>DumpExtension </B><I>name</I> <DD> Use <I>name</I> as the filename extension for dump files. If not given, the default of <B>tab</B> will be used. <DT><B>DumpHeader </B>( yes | <B>no</B> ) <DD> Print a column header as the first record of the file. <DT><B>DumpSites </B>( yes | <B>no</B> ) <DD> Dump the sites data to a tab delimited file. <DT><B>DumpURLs </B>( yes | <B>no</B> ) <DD> Dump the url data to a tab delimited file. <DT><B>DumpReferrers </B>( yes | <B>no</B> ) <DD> Dump the referrer data to a tab delimited file. This data is only available if using a log that contains referrer information (ie: a combined format web log). <DT><B>DumpAgents </B>( yes | <B>no</B> ) <DD> Dump the user agent data to a tab delimited file. This data is only available if using a log that contains user agent information (ie: a combined format web log). <DT><B>DumpUsers </B>( yes | <B>no</B> ) <DD> Dump the username data to a tab delimited file. This data is only available if processing a wu-ftpd xferlog or a web log that contains http authentication information. <DT><B>DumpSearchStr </B>( yes | <B>no</B> ) <DD> Dump the search string data to a tab delimited file. This data is only available if processing a web log that contains referrer information and had search string information present. </DL> <A NAME="lbAK">&nbsp;</A> <H2>FILES</H2> <DL COMPACT> <DT><I>webalizer.conf</I> <DD> Default configuration file. Is searched for in the current directory and if not found, in the <I>/etc/</I> directory. <DT><I>webalizer.hist</I> <DD> Monthly history file for previous months. (can be changed) <DT><I>webalizer.current</I> <DD> Current state data file (Incremental processing). (can be changed) <DT><I>xxxxx_YYYYMM.html</I> <DD> Various monthly <I>HTML</I> output files produced. (extension can be changed) <DT><I>xxxxx_YYYYMM.png</I> <DD> Various monthly image files used in the reports. <DT><I>xxxxx_YYYYMM.tab</I> <DD> Monthly tab delimited text files. (extension can be changed) </DL> <A NAME="lbAL">&nbsp;</A> <H2>BUGS</H2> Please report bugs to the author. <A NAME="lbAM">&nbsp;</A> <H2>COPYRIGHT</H2> Copyright (C) 1997-2009 by Bradford L. Barrett. Distributed under the GNU GPL. See the files &quot;<I>COPYING</I>&quot; and &quot;<I>Copyright</I>&quot;, supplied with all distributions for additional information. <A NAME="lbAN">&nbsp;</A> <H2>AUTHOR</H2> Bradford L. Barrett &lt;<I>brad at mrunix dot net</I>&gt; <P> <HR> <A NAME="index">&nbsp;</A><H2>Index</H2> <DL> <DT><A HREF="#lbAB">NAME</A><DD> <DT><A HREF="#lbAC">SYNOPSIS</A><DD> <DT><A HREF="#lbAD">DESCRIPTION</A><DD> <DT><A HREF="#lbAE">RUNNING THE WEBALIZER</A><DD> <DT><A HREF="#lbAF">INCREMENTAL PROCESSING</A><DD> <DT><A HREF="#lbAG">REVERSE DNS LOOKUPS</A><DD> <DT><A HREF="#lbAH">GEOLOCATION LOOKUPS</A><DD> <DT><A HREF="#lbAI">COMMAND LINE OPTIONS</A><DD> <DT><A HREF="#lbAJ">CONFIGURATION FILES</A><DD> <DT><A HREF="#lbAK">FILES</A><DD> <DT><A HREF="#lbAL">BUGS</A><DD> <DT><A HREF="#lbAM">COPYRIGHT</A><DD> <DT><A HREF="#lbAN">AUTHOR</A><DD> </DL> <HR> This document was created by <A HREF="/manpages/index.html">man2html</A>, using the manual pages.<BR> Time: 05:29:12 GMT, December 24, 2015 </div></div> </body> </HTML>
{ "content_hash": "2ecc6755d235c44b2df62d764f8d95f4", "timestamp": "", "source": "github", "line_count": 1215, "max_line_length": 122, "avg_line_length": 32.90781893004115, "alnum_prop": 0.6970462446539779, "repo_name": "yuweijun/yuweijun.github.io", "id": "cc8540586d08d5fd58d2d7ed2be6cd575c8076dc", "size": "39983", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "manpages/man1/webazolver.1.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "589062" }, { "name": "CSS", "bytes": "86538" }, { "name": "Go", "bytes": "2652" }, { "name": "HTML", "bytes": "126806134" }, { "name": "JavaScript", "bytes": "12389716" }, { "name": "Perl", "bytes": "7390" }, { "name": "PostScript", "bytes": "32036" }, { "name": "Ruby", "bytes": "8626" }, { "name": "Shell", "bytes": "193" }, { "name": "Vim Script", "bytes": "209" }, { "name": "XSLT", "bytes": "7176" } ], "symlink_target": "" }
AliAnalysisTaskCaloTrackCorrelation *AddTaskPi0IMGammaCorrQA(const TString calorimeter = "EMCAL", Bool_t simulation = kFALSE, TString collision = "pp", TString period = "", const Bool_t qaan = kTRUE, const Bool_t hadronan = kTRUE, const Bool_t calibrate = kFALSE, const Int_t minTime = -1000, const Int_t maxTime = 1000, const Int_t minCen = -1, const Int_t maxCen = -1, const Int_t debugLevel = -1, const char * suffix = "default" ) { // Check the global variables, and reset the provided ones if empty. // TString trigger = suffix; if(collision=="") { if (!strcmp(kColType, "PbPb")) collision = "PbPb"; else if (!strcmp(kColType, "AA" )) collision = "PbPb"; else if (!strcmp(kColType, "pA" )) collision = "pPb"; else if (!strcmp(kColType, "Ap" )) collision = "pPb"; else if (!strcmp(kColType, "pPb" )) collision = "pPb"; else if (!strcmp(kColType, "Pbp" )) collision = "pPb"; else if (!strcmp(kColType, "pp" )) collision = "pp" ; simulation = kMC; period = kPeriod; // print check on global settings once if(trigger.Contains("default") ||trigger.Contains("INT") || trigger.Contains("MB") ) printf("AddTaskPi0IMGammaCorrQA - Get the data features from global parameters: col <%s>, period <%s>, mc <%d> \n", kColType,kPeriod,kMC); } Int_t year = 2017; if ( period!="" ) { if (period.Contains("16")) year = 2016; else if(period.Contains("15")) year = 2015; else if(period.Contains("13")) year = 2013; else if(period.Contains("12")) year = 2012; else if(period.Contains("11")) year = 2011; else if(period.Contains("10")) year = 2010; } // Get the pointer to the existing analysis manager via the static access method. // AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskPi0IMGammaCorrQA", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. // if (!mgr->GetInputEventHandler()) { ::Error("AddTaskPi0IMGammaCorrQA", "This task requires an input event handler"); return NULL; } // // Create task // // Name for containers TString containerName = Form("%s_Trig_%s",calorimeter.Data(), trigger.Data()); if(collision!="pp" && maxCen>=0) containerName+=Form("Cen%d_%d",minCen,maxCen); TString taskName =Form("Pi0IM_GammaTrackCorr_%s",containerName.Data()); AliAnalysisTaskCaloTrackCorrelation * task = new AliAnalysisTaskCaloTrackCorrelation (taskName); //task->SetConfigFileName(""); //Don't configure the analysis via configuration file. task->SetDebugLevel(debugLevel); //task->SetBranches("ESD:AliESDRun.,AliESDHeader"); //task->SetBranches("AOD:header,tracks,vertices,emcalCells,caloClusters"); // // Init main analysis maker and pass it to the task AliAnaCaloTrackCorrMaker * maker = new AliAnaCaloTrackCorrMaker(); task->SetAnalysisMaker(maker); // // Pass the task to the analysis manager mgr->AddTask(task); // // Create containers TString outputfile = AliAnalysisManager::GetCommonFileName(); AliAnalysisDataContainer *cout_pc = mgr->CreateContainer(trigger, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s",outputfile.Data(),Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data()))); AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("Param_%s",trigger.Data()), TList::Class(), AliAnalysisManager::kParamContainer, Form("%s_Parameters.root",Form("Pi0IM_GammaTrackCorr_%s",calorimeter.Data()))); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (task, 1, cout_pc); mgr->ConnectOutput (task, 2, cout_cuts); //============================================================================== // Do not configure the wagon for certain analysis combinations // But create the task so that the sub-wagon train can run // Bool_t doAnalysis = CheckAnalysisTrigger(simulation,trigger,period,year); if(!doAnalysis) { maker->SwitchOffProcessEvent(); return task; } // #### Start analysis configuration #### // TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // Make sure the B field is enabled for track selection, some cuts need it // ((AliInputEventHandler*)mgr->GetInputEventHandler())->SetNeedField(kTRUE); // Print settings to check all is as expected // printf("AddTaskPi0IMGammaCorrQA - Task NAME: %s \n",taskName.Data()); printf("AddTaskPi0IMGammaCorrQA - Settings: data <%s>, calo <%s>, MC <%d>, collision <%s>, trigger <%s>, period <%s>, year <%d>,\n" "\t \t \t CaloQA on <%d>, Track QA on <%d>, Make corrections <%d>, %d < time < %d, %d < cen < %d, debug level <%d> \n", inputDataType.Data(), calorimeter.Data(),simulation, collision.Data(),trigger.Data(), period.Data(), year, qaan , hadronan, calibrate, minTime, maxTime, minCen, maxCen, debugLevel); // // General frame setting and configuration maker->SetReader ( ConfigureReader (inputDataType,collision,calibrate,minTime,maxTime,minCen,maxCen,simulation,year,debugLevel) ); if(hadronan)maker->GetReader()->SwitchOnCTS(); maker->SetCaloUtils( ConfigureCaloUtils(calorimeter,trigger,simulation,calibrate,year,debugLevel) ); // Analysis tasks setting and configuration Int_t n = 0;//Analysis number, order is important // Cell QA if(qaan) maker->AddAnalysis(ConfigureQAAnalysis(calorimeter,collision,simulation,year,debugLevel),n++); // Analysis with EMCal trigger or MB if ( !trigger.Contains("DCAL") ) { // Cluster selection maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,0,collision,containerName,simulation,year,debugLevel) ,n++); // Previous cluster invariant mass maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen),n++); if(hadronan) { // Isolation of selected clusters by AliAnaPhoton maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel), n++); // Selected clusters-track correlation maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,0,collision,containerName,simulation,year,debugLevel,minCen), n++); } } // Analysis with DCal trigger or MB if(year > 2014 && calorimeter=="EMCAL" && !trigger.Contains("EMCAL")) { // Cluster selection maker->AddAnalysis(ConfigurePhotonAnalysis(calorimeter,1,collision,containerName,simulation,year,debugLevel) , n++); // Previous cluster invariant mass maker->AddAnalysis(ConfigurePi0Analysis (calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen),n++); if(hadronan) { // Isolation of selected clusters by AliAnaPhoton maker->AddAnalysis(ConfigureIsolationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel), n++); // Selected clusters-track correlation maker->AddAnalysis(ConfigureHadronCorrelationAnalysis("Photon",calorimeter,1,collision,containerName,simulation,year,debugLevel,minCen), n++); } } // Charged tracks plots, any trigger if(hadronan) maker->AddAnalysis(ConfigureChargedAnalysis(collision,containerName,simulation,year,debugLevel), n++); if(simulation) { // Calculate the cross section weights, apply them to all histograms // and fill xsec and trial histo. Sumw2 must be activated. //maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionCalculation(); //maker->SwitchOnSumw2Histograms(); // For recent productions where the cross sections and trials are not stored in separate file //maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionFromEventHeader() ; // Just fill cross section and trials histograms. maker->GetReader()->GetWeightUtils()->SwitchOnMCCrossSectionHistoFill(); // Add control histogram with pT hard to control aplication of weights maker->SwitchOnPtHardHistogram(); } // // Select events trigger depending on trigger // if(!simulation) { gROOT->LoadMacro("$ALICE_PHYSICS/PWGGA/CaloTrackCorrelations/macros/ConfigureAndGetEventTriggerMaskAndCaloTriggerString.C"); TString caloTriggerString = ""; UInt_t mask = ConfigureAndGetEventTriggerMaskAndCaloTriggerString(trigger, year, caloTriggerString); task ->SelectCollisionCandidates( mask ); maker->GetReader()->SetFiredTriggerClassName(caloTriggerString); printf("AddTaskPi0IMGammaCorrQA - Trigger Mask %d, caloTriggerString <%s>\n", mask, caloTriggerString.Data()); } // // Final maker settings // maker->SetAnaDebug(debugLevel) ; maker->SwitchOnHistogramsMaker() ; maker->SwitchOnAODsMaker() ; maker->SwitchOnDataControlHistograms(); if(debugLevel > 0) maker->Print(""); return task; } /// /// Configure the class handling the events and cluster/tracks filtering. /// AliCaloTrackReader * ConfigureReader(TString inputDataType, TString collision, Bool_t calibrate, Int_t minTime, Int_t maxTime, Int_t minCen, Int_t maxCen, Bool_t simulation, Int_t year, Int_t debugLevel) { AliCaloTrackReader * reader = 0; if (inputDataType=="AOD") reader = new AliCaloTrackAODReader(); else if(inputDataType=="ESD") reader = new AliCaloTrackESDReader(); else printf("AliCaloTrackReader::ConfigureReader() - Data combination not known input Data=%s\n", inputDataType.Data()); reader->SetDebug(debugLevel);//10 for lots of messages //------------------------ // Detector input filling //------------------------ //Min cluster/track E reader->SetEMCALEMin(0.3); reader->SetEMCALEMax(1000); reader->SetPHOSEMin(0.3); reader->SetPHOSEMax(1000); reader->SetCTSPtMin(0.2); reader->SetCTSPtMax(1000); // Time cut reader->SwitchOffUseParametrizedTimeCut(); if(calibrate) { reader->SwitchOnUseEMCALTimeCut() ; reader->SetEMCALTimeCut(minTime,maxTime); } reader->SwitchOffUseTrackTimeCut(); reader->SetTrackTimeCut(-1e10,1e10); reader->SwitchOffFiducialCut(); // Tracks reader->SwitchOffCTS(); reader->SwitchOffRejectNoTrackEvents(); reader->SwitchOffRecalculateVertexBC(); reader->SwitchOffVertexBCEventSelection(); reader->SwitchOffUseTrackDCACut(); //reader->SetTrackDCACut(0,0.0105); //reader->SetTrackDCACut(1,0.035); //reader->SetTrackDCACut(2,1.1); if(inputDataType=="ESD") { gROOT->LoadMacro("$ALICE_PHYSICS/PWGJE/macros/CreateTrackCutsPWGJE.C"); if(year > 2010) { //Hybrids 2011 AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001008); reader->SetTrackCuts(esdTrackCuts); AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10011008); reader->SetTrackComplementaryCuts(esdTrackCuts2); } else { //Hybrids 2010 AliESDtrackCuts * esdTrackCuts = CreateTrackCutsPWGJE(10001006); reader->SetTrackCuts(esdTrackCuts); AliESDtrackCuts * esdTrackCuts2 = CreateTrackCutsPWGJE(10041006); reader->SetTrackComplementaryCuts(esdTrackCuts2); } } else if(inputDataType=="AOD") { reader->SwitchOnAODHybridTrackSelection(); // Check that the AODs have Hybrids!!!! reader->SetTrackStatus(AliVTrack::kITSrefit); } // Calorimeter //reader->SetEMCALClusterListName(""); if(calibrate && !simulation) reader->SwitchOnClusterRecalculation(); else reader->SwitchOffClusterRecalculation(); reader->SwitchOnEMCALCells(); reader->SwitchOnEMCAL(); reader->SwitchOffPHOSCells(); reader->SwitchOffPHOS(); //----------------- // Event selection //----------------- reader->SwitchOnEventTriggerAtSE(); reader->SetZvertexCut(10.); reader->SwitchOnPrimaryVertexSelection(); // and besides primary vertex reader->SwitchOffPileUpEventRejection(); // remove pileup reader->SwitchOffV0ANDSelection() ; // and besides v0 AND if(collision=="PbPb") { if(year < 2014) reader->SwitchOnAliCentrality(); reader->SetCentralityBin(minCen,maxCen); // Accept all events, if not select range reader->SetCentralityOpt(100); // 10 (c= 0-10, 10-20 ...), 20 (c= 0-5, 5-10 ...) or 100 (c= 1, 2, 3 ..) } if(debugLevel > 0) reader->Print(""); return reader; } /// /// Configure the class handling the calorimeter clusters specific methods /// AliCalorimeterUtils* ConfigureCaloUtils(TString calorimeter, TString trigger, Bool_t simulation , Bool_t calibrate, Int_t year , Int_t debugLevel) { AliCalorimeterUtils *cu = new AliCalorimeterUtils; cu->SetDebug(debugLevel); // Remove clusters close to borders, at least max energy cell is 1 cell away cu->SetNumberOfCellsFromEMCALBorder(1); cu->SetNumberOfCellsFromPHOSBorder(2); // Search of local maxima in cluster cu->SetLocalMaximaCutE(0.1); cu->SetLocalMaximaCutEDiff(0.03); //cu->SwitchOffClusterPlot(); cu->SwitchOffRecalculateClusterTrackMatching(); cu->SwitchOnBadChannelsRemoval() ; //EMCAL settings if(!simulation) cu->SwitchOnLoadOwnEMCALGeometryMatrices(); AliEMCALRecoUtils * recou = cu->GetEMCALRecoUtils(); cu->SwitchOffRecalibration(); // Check the reader if it is taken into account during filtering cu->SwitchOffRunDepCorrection(); cu->SwitchOffCorrectClusterLinearity(); Bool_t bExotic = kTRUE; Bool_t bNonLin = kFALSE; Bool_t bBadMap = kTRUE; Bool_t bEnCalib = kFALSE; Bool_t bTiCalib = kFALSE; if(calibrate && !simulation) { cu->SwitchOnRecalibration(); // Check the reader if it is taken into account during filtering cu->SwitchOffRunDepCorrection(); cu->SwitchOnRecalculateClusterPosition() ; bEnCalib = kTRUE; bTiCalib = kTRUE; } gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/EMCAL/macros/ConfigureEMCALRecoUtils.C"); ConfigureEMCALRecoUtils(recou, simulation, bExotic, bNonLin, bEnCalib, bBadMap, bTiCalib, debugLevel ); //recou->SetExoticCellDiffTimeCut(50.); if(calorimeter=="PHOS") { if(year < 2014) cu->SetNumberOfSuperModulesUsed(3); else cu->SetNumberOfSuperModulesUsed(4); } else { Int_t nSM = 20; Int_t lastEMC = 11; if (year == 2010) { nSM = 4; lastEMC = 3; }// EMCAL first year else if (year < 2014) { nSM = 10; lastEMC = 9; }// EMCAL active 2011-2013 cu->SetNumberOfSuperModulesUsed(nSM); if (trigger.Contains("EMCAL")) { cu->SetFirstSuperModuleUsed( 0); cu->SetLastSuperModuleUsed (lastEMC); } else if (trigger.Contains("DCAL")) { cu->SetFirstSuperModuleUsed(12); cu->SetLastSuperModuleUsed (19); } else { cu->SetFirstSuperModuleUsed(0); cu->SetLastSuperModuleUsed (cu->GetNumberOfSuperModulesUsed()-1); } printf("AddTaskPi0IMGammaCorrQA - CalorimeterUtils: nSM %d, first %d, last %d\n", cu->GetNumberOfSuperModulesUsed(),cu->GetFirstSuperModuleUsed(), cu->GetLastSuperModuleUsed()); } // PHOS cu->SwitchOffLoadOwnPHOSGeometryMatrices(); if(debugLevel > 0) cu->Print(""); return cu; } /// /// Configure the task doing the first photon cluster selections /// Basically the track matching, minor shower shape cut, NLM selection ... /// AliAnaPhoton* ConfigurePhotonAnalysis(TString calorimeter, Bool_t caloType, TString collision, TString containerName, Bool_t simulation, Int_t year, Int_t debugLevel) { AliAnaPhoton *ana = new AliAnaPhoton(); ana->SetDebug(debugLevel); //10 for lots of messages // cluster selection cuts ana->SwitchOnFiducialCut(); if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE); ana->SetCalorimeter(calorimeter); if(calorimeter == "PHOS") { ana->SetNCellCut(2);// At least 3 cells ana->SetMinPt(0.5); ana->SetMinDistanceToBadChannel(2, 4, 5); ana->SetTimeCut(-1e10,1e10); // open cut } else { // EMCAL ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns ana->SetNCellCut(1);// At least 2 cells ana->SetMinEnergy(0.5); // avoid mip peak at E = 260 MeV ana->SetMaxEnergy(1000); ana->SetTimeCut(-1e10,1e10); // open cut, usual time window of [425-825] ns if time recalibration is off // restrict to less than 100 ns when time calibration is on ana->SetMinDistanceToBadChannel(2, 4, 6); // Not useful if M02 cut is already strong ana->SetNLMCut(1, 2) ; } ana->SwitchOnTrackMatchRejection() ; ana->SwitchOnTMHistoFill() ; ana->SwitchOnAcceptanceHistoPerEBin(); ana->SetNEBinCuts(2); // Set the acceptance E bins depending on the trigger and their likely values if(containerName.Contains("efault") || containerName.Contains("INT") || containerName.Contains("MB")) { ana->SetEBinCutsAt(0, 0.5); ana->SetEBinCutsAt(1, 3.0); ana->SetEBinCutsAt(2, 100.0); } else if(containerName.Contains("L0")) { ana->SetEBinCutsAt(0, 2.0); ana->SetEBinCutsAt(1, 5.0); ana->SetEBinCutsAt(2, 100.0); } else { ana->SetEBinCutsAt(0, 5.0); ana->SetEBinCutsAt(1, 12.0); ana->SetEBinCutsAt(2, 100.0); } //PID cuts (shower shape) ana->SwitchOnCaloPID(); // do PID selection, unless specified in GetCaloPID, selection not based on bayesian AliCaloPID* caloPID = ana->GetCaloPID(); //Not used in bayesian //EMCAL caloPID->SetEMCALLambda0CutMax(0.4); // Rather open caloPID->SetEMCALLambda0CutMin(0.10); caloPID->SetEMCALDEtaCut(0.025); caloPID->SetEMCALDPhiCut(0.030); //PHOS caloPID->SetPHOSDispersionCut(2.5); caloPID->SetPHOSRCut(2.); ana->SwitchOnFillShowerShapeHistograms(); // Filled before photon shower shape selection //if(!simulation)ana->SwitchOnFillPileUpHistograms(); if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms(); // Input / output delta AOD settings ana->SetOutputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType)); ana->SetOutputAODClassName("AliCaloTrackParticleCorrelation"); ana->SetInputAODName (Form("Photon%s_Calo%d",containerName.Data(),caloType)); // Set Histograms name tag, bins and ranges ana->AddToHistogramsName(Form("AnaPhoton_Calo%d_",caloType)); SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below // Number of particle type MC histograms ana->FillNOriginHistograms(7); ana->FillNPrimaryHistograms(4); if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0 ) ana->Print(""); return ana; } /// /// Configure the task doing the 2 cluster invariant mass analysis /// AliAnaPi0* ConfigurePi0Analysis(TString calorimeter , Bool_t caloType , TString collision, TString containerName, Bool_t simulation, Int_t year, Int_t debugLevel , Int_t minCen) { AliAnaPi0 *ana = new AliAnaPi0(); ana->SetDebug(debugLevel);//10 for lots of messages // Input delta AOD settings ana->SetInputAODName(Form("Photon%s_Calo%d",containerName.Data(),caloType)); // Calorimeter settings ana->SetCalorimeter(calorimeter); ana->SwitchOnFiducialCut(); if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE); ana->SwitchOnRealCaloAcceptance(); // Settings for pp collision mixing ana->SwitchOnOwnMix(); //Off when mixing done with general mixing frame // Cuts if(calorimeter=="EMCAL") { ana->SetPairTimeCut(100); // Angle cut, avoid pairs with too large angle ana->SwitchOnAngleSelection(); ana->SetAngleMaxCut(TMath::DegToRad()*80.); // EMCal: 4 SM in phi, 2 full SMs in eta ana->SetAngleCut(0.016); // Minimum angle open, ~cell size } ana->SetNPIDBits(1); ana->SetNAsymCuts(1); // no asymmetry cut, previous studies showed small effect. // In EMCAL assymetry cut prevents combination of assymetric decays which is the main source of pi0 at high E. if (collision == "pp" ) { ana->SetNCentrBin(1); ana->SetNZvertBin(10); ana->SetNRPBin(1); ana->SetNMaxEvMix(100); ana->SetMinPt(0.5); } else if(collision =="PbPb") { ana->SetNCentrBin(10); ana->SetNZvertBin(10); ana->SetNRPBin(4); ana->SetNMaxEvMix(10); if(minCen >= 10) ana->SetNMaxEvMix(50); if(minCen >= 50) ana->SetNMaxEvMix(100); ana->SetMinPt(1.5); ana->SwitchOnFillHighMultiplicityHistograms(); } else if(collision =="pPb") { ana->SetNCentrBin(1); ana->SetNZvertBin(10); ana->SetNRPBin(4); ana->SetNMaxEvMix(100); ana->SetMinPt(0.5); ana->SwitchOnFillHighMultiplicityHistograms(); } ana->SwitchOffMultipleCutAnalysis(); ana->SwitchOnSMCombinations(); ana->SwitchOffFillAngleHisto(); ana->SwitchOffFillOriginHisto(); // Set Histograms name tag, bins and ranges ana->AddToHistogramsName(Form("AnaPi0_Calo%d_",caloType)); SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0) ana->Print(""); return ana; } /// /// Configure the task doing charged track selection /// AliAnaChargedParticles* ConfigureChargedAnalysis(TString collision,TString containerName, Bool_t simulation, Int_t year, Int_t debugLevel) { AliAnaChargedParticles *ana = new AliAnaChargedParticles(); ana->SetDebug(debugLevel); //10 for lots of messages // selection cuts ana->SetMinPt(0.5); ana->SwitchOnFiducialCut(); Float_t etacut = 0.8; ana->GetFiducialCut()->SetSimpleCTSFiducialCut(etacut, 0, 360) ; //more restrictive cut in reader and after in isolation // histogram switchs ana->SwitchOffFillVertexBC0Histograms() ; //if(!simulation) ana->SwitchOnFillPileUpHistograms(); ana->SwitchOffFillTrackMultiplicityHistograms(); // Input / output delta AOD settings ana->SetOutputAODName(Form("Hadron%s",containerName.Data())); ana->SetOutputAODClassName("AliCaloTrackParticleCorrelation"); ana->SetInputAODName(Form("Hadron%s",containerName.Data())); //Set Histograms name tag, bins and ranges ana->AddToHistogramsName("AnaHadrons_"); SetHistoRangeAndNBins(ana->GetHistogramRanges(),"",kFALSE,collision,year); // see method below ana->GetHistogramRanges()->SetHistoPhiRangeAndNBins(0, TMath::TwoPi(), 120) ; ana->GetHistogramRanges()->SetHistoEtaRangeAndNBins(-1.*etacut, 1.*etacut, etacut*100) ; if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0) ana->Print(""); return ana; } /// /// Configure the task doing the trigger particle hadron correlation /// AliAnaParticleIsolation* ConfigureIsolationAnalysis(TString particle , TString calorimeter , Bool_t caloType, TString collision , TString containerName, Bool_t simulation, Int_t year , Int_t debugLevel) { AliAnaParticleIsolation *ana = new AliAnaParticleIsolation(); ana->SetDebug(debugLevel); //if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms(); ana->SetMinPt(5); ana->SwitchOffStudyTracksInCone() ; ana->SwitchOnUEBandSubtractionHistoFill(); ana->SwitchOffDecayTaggedHistoFill() ; ana->SwitchOnSSHistoFill(); ana->SwitchOffLeadingOnly(); ana->SwitchOffCheckNeutralClustersForLeading(); ana->SwitchOffPtTrigBinHistoFill(); ana->SwitchOffBackgroundBinHistoFill(); ana->SwitchOffTMHistoFill(); // MC ana->SwitchOffPrimariesInConeSelection(); ana->SwitchOffPrimariesPi0DecayStudy() ; ana->SwitchOnRealCaloAcceptance(); ana->SwitchOnFiducialCut(); if(calorimeter == "EMCAL" && caloType == 0) { // Avoid borders of EMCal ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 86, 174) ; } if(calorimeter == "EMCAL" && caloType == 1) { // Avoid borders of DCal ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.60, 264, 316) ; } AliCaloPID* caloPID = ana->GetCaloPID(); caloPID->SetEMCALDEtaCut(0.025); caloPID->SetEMCALDPhiCut(0.030); ana->SwitchOffSeveralIsolation() ; ana->SwitchOffReIsolation(); // // Do settings for main isolation cut class // AliIsolationCut * ic = ana->GetIsolationCut(); ic->SetDebug(debugLevel); ic->SetParticleTypeInCone(AliIsolationCut::kNeutralAndCharged); ic->SetICMethod(AliIsolationCut::kSumPtIC); if ( collision == "pp" || collision == "pPb" ) { ic->SetPtThreshold(0.5); ic->SetSumPtThreshold(2.0) ; ic->SetConeSize(0.4); } if ( collision == "PbPb" ) { ic->SetPtThreshold(3.); ic->SetSumPtThreshold(3.0) ; ic->SetConeSize(0.3); } // Input / output delta AOD settings ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType)); ana->SetAODObjArrayName(Form("%sIso_%s_Calo%d",particle.Data(),containerName.Data(),caloType)); // Set Histograms name tag, bins and ranges ana->AddToHistogramsName(Form("AnaIsol%s_Calo%d_",particle.Data(),caloType)); SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0) ana->Print(""); return ana; } /// /// Configure the task doing the trigger particle hadron correlation /// AliAnaParticleHadronCorrelation* ConfigureHadronCorrelationAnalysis(TString particle, TString calorimeter, Bool_t caloType, TString collision, TString containerName, Bool_t simulation, Int_t year, Int_t debugLevel, Int_t minCen) { AliAnaParticleHadronCorrelation *ana = new AliAnaParticleHadronCorrelation(); ana->SetDebug(debugLevel); ana->SetTriggerPtRange(5,100); ana->SetAssociatedPtRange(0.2,100); //ana->SetDeltaPhiCutRange( TMath::Pi()/2,3*TMath::Pi()/2 ); //[90 deg, 270 deg] ana->SetDeltaPhiCutRange (TMath::DegToRad()*120.,TMath::DegToRad()*240.); ana->SetUeDeltaPhiCutRange(TMath::DegToRad()*60. ,TMath::DegToRad()*120.); ana->SwitchOffFillEtaGapHistograms(); ana->SetNAssocPtBins(4); ana->SetAssocPtBinLimit(0, 0.5) ; ana->SetAssocPtBinLimit(1, 2) ; ana->SetAssocPtBinLimit(2, 5) ; ana->SetAssocPtBinLimit(3, 10) ; ana->SetAssocPtBinLimit(4, 20) ; ana->SelectIsolated(kFALSE); // do correlation with isolated photons //if(!simulation) ana->SwitchOnFillPileUpHistograms(); ana->SwitchOffAbsoluteLeading(); // Select trigger leading particle of all the selected tracks ana->SwitchOffNearSideLeading(); // Select trigger leading particle of all the particles at +-90 degrees, default //ana->SwitchOnLeadHadronSelection(); //ana->SetLeadHadronPhiCut(TMath::DegToRad()*100., TMath::DegToRad()*260.); //ana->SetLeadHadronPtCut(0.5, 100); // Mixing with own pool ana->SwitchOffOwnMix(); ana->SetNZvertBin(20); ana->SwitchOffCorrelationVzBin() ; //if(collision.Contains("Pb")) ana->SwitchOnFillHighMultiplicityHistograms(); if(collision=="pp") { ana->SetNMaxEvMix(100); ana->SwitchOnTrackMultBins(); ana->SetNTrackMultBin(10); // same as SetNCentrBin(10); ana->SetNRPBin(1); } else { ana->SetNMaxEvMix(10); if(minCen >= 10) ana->SetNMaxEvMix(50); if(minCen >= 50) ana->SetNMaxEvMix(100); ana->SwitchOffTrackMultBins(); // centrality bins ana->SetNCentrBin(10); ana->SetNRPBin(3); } // Input / output delta AOD settings ana->SetInputAODName(Form("%s%s_Calo%d",particle.Data(),containerName.Data(),caloType)); ana->SetAODObjArrayName(Form("%sHadronCorr_%s_Calo%d",particle.Data(),containerName.Data(),caloType)); ana->SwitchOffPi0TriggerDecayCorr(); ana->SwitchOffDecayTriggerDecayCorr(); ana->SwitchOffNeutralCorr(); // Do only correlation with TPC ana->SwitchOffHMPIDCorrelation(); ana->SwitchOffFillBradHistograms(); // Underlying event ana->SwitchOffSeveralUECalculation(); ana->SetUeDeltaPhiCutRange(TMath::Pi()/3, 2*TMath::Pi()/3); //Set Histograms name tag, bins and ranges ana->AddToHistogramsName(Form("Ana%sHadronCorr_Calo%d_",particle.Data(),caloType)); SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter,caloType,collision,year); // see method below if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0) ana->Print(""); return ana; } /// /// Configure the task doing standard calorimeter QA /// AliAnaCalorimeterQA* ConfigureQAAnalysis(TString calorimeter, TString collision, Bool_t simulation , Int_t year, Int_t debugLevel) { AliAnaCalorimeterQA *ana = new AliAnaCalorimeterQA(); ana->SetDebug(debugLevel); //10 for lots of messages ana->SetCalorimeter(calorimeter); //printf("QA: calorimeter %s, caloType %d, collision %s, simulation %d, fillCellTime %d, year %d, debugLevel %d\n", // calorimeter.Data(),caloType,collision.Data(),simulation,fillCellTime,year,debugLevel); ana->SetTimeCut(-1e10,1e10); // Open time cut ana->SetConstantTimeShift(615); // for MC and uncalibrated data, whenever there is time > 400 ns ana->SetEMCALCellAmpMin(0.5); ana->SwitchOffStudyBadClusters() ; ana->SwitchOffFillAllTH3Histogram(); ana->SwitchOffFillAllPositionHistogram(); ana->SwitchOffFillAllPositionHistogram2(); ana->SwitchOffStudyBadClusters(); ana->SwitchOffFillAllPi0Histogram() ; ana->SwitchOffCorrelation(); ana->SwitchOffFillAllCellAbsIdHistogram(); ana->SwitchOffFillAllTrackMatchingHistogram(); ana->SwitchOnFillAllCellTimeHisto() ; ana->SwitchOnFillAllCellHistogram(); ana->SwitchOffFillAllClusterHistogram() ; ana->AddToHistogramsName("QA_Cell_"); //Begining of histograms name SetHistoRangeAndNBins(ana->GetHistogramRanges(),calorimeter, -1, collision,year); // see method below // ana->SwitchOnFiducialCut(); // if(caloType==0)ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 80, 187) ; // EMC // else ana->GetFiducialCut()->SetSimpleEMCALFiducialCut(0.7, 260, 327) ; // DMC // // ana->GetFiducialCut()->DoEMCALFiducialCut(kTRUE); //if(simulation) ana->SwitchOnDataMC(); if(debugLevel > 0) ana->Print(""); return ana; } /// /// Configure histograms ranges and bins /// void SetHistoRangeAndNBins (AliHistogramRanges* histoRanges, TString calorimeter, Bool_t caloType, TString collision, Int_t year) { histoRanges->SetHistoPtRangeAndNBins(0, 100, 200) ; // Energy and pt histograms if(calorimeter=="EMCAL") { if ( year == 2010 ) { histoRanges->SetHistoPhiRangeAndNBins(79*TMath::DegToRad(), 121*TMath::DegToRad(), 42) ; histoRanges->SetHistoXRangeAndNBins(-230,90,120); // QA histoRanges->SetHistoYRangeAndNBins(370,450,40); // QA } else if ( year < 2014 ) { histoRanges->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 182*TMath::DegToRad(), 108) ; histoRanges->SetHistoXRangeAndNBins(-460,90,200); // QA histoRanges->SetHistoYRangeAndNBins(100,450,100); // QA } else // Run2 { if (caloType == 0) histoRanges->SetHistoPhiRangeAndNBins(78 *TMath::DegToRad(), 189*TMath::DegToRad(), 111) ; else if (caloType == 1) histoRanges->SetHistoPhiRangeAndNBins(258*TMath::DegToRad(), 329*TMath::DegToRad(), 71) ; else histoRanges->SetHistoPhiRangeAndNBins(80 *TMath::DegToRad(), 327*TMath::DegToRad(), 247) ; histoRanges->SetHistoXRangeAndNBins(-460,460,230); // QA histoRanges->SetHistoYRangeAndNBins(-450,450,225); // QA } histoRanges->SetHistoEtaRangeAndNBins(-0.72, 0.72, 144) ; } else { histoRanges->SetHistoPhiRangeAndNBins(250*TMath::DegToRad(), 320*TMath::DegToRad(), 70) ; histoRanges->SetHistoEtaRangeAndNBins(-0.13, 0.13, 130) ; } histoRanges->SetHistoShowerShapeRangeAndNBins(-0.1, 2.9, 300); // Invariant mass histoRangeslysis histoRanges->SetHistoMassRangeAndNBins(0., 0.8, 160) ; histoRanges->SetHistoAsymmetryRangeAndNBins(0., 1. , 100) ; histoRanges->SetHistoOpeningAngleRangeAndNBins(0,0.7,50); // check if time calibration is on histoRanges->SetHistoTimeRangeAndNBins(-250.,250,250); histoRanges->SetHistoDiffTimeRangeAndNBins(-150, 150, 150); // track-cluster residuals histoRanges->SetHistoTrackResidualEtaRangeAndNBins(-0.05,0.05,100); histoRanges->SetHistoTrackResidualPhiRangeAndNBins(-0.05,0.05,100); histoRanges->SetHistodRRangeAndNBins(0.,0.05,50);//QA // QA, electron, charged histoRanges->SetHistoPOverERangeAndNBins(0, 2. ,100); histoRanges->SetHistodEdxRangeAndNBins (0.,200.,100); // QA histoRanges->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId histoRanges->SetHistoVertexDistRangeAndNBins(0.,500.,250); histoRanges->SetHistoZRangeAndNBins(-350,350,175); histoRanges->SetHistoRRangeAndNBins(430,460,30); histoRanges->SetHistoV0SignalRangeAndNBins(0,5000,250); histoRanges->SetHistoV0MultiplicityRangeAndNBins(0,5000,250); // QA, correlation if(collision=="PbPb") { histoRanges->SetHistoNClusterCellRangeAndNBins(0,100,100); histoRanges->SetHistoNClustersRangeAndNBins(0,500,50); histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,2000,200); } else { histoRanges->SetHistoNClusterCellRangeAndNBins(0,50,50); histoRanges->SetHistoNClustersRangeAndNBins(0,50,50); histoRanges->SetHistoTrackMultiplicityRangeAndNBins(0,200,200); } // xE, zT histoRanges->SetHistoRatioRangeAndNBins(0.,1.2,120); histoRanges->SetHistoHBPRangeAndNBins (0.,10.,100); // Isolation histoRanges->SetHistoPtInConeRangeAndNBins(0, 50 , 100); histoRanges->SetHistoPtSumRangeAndNBins (0, 100, 100); if(collision.Contains("pPb")) histoRanges->SetHistoPtSumRangeAndNBins (0, 200, 100); else if(collision.Contains("PbPb")) histoRanges->SetHistoPtSumRangeAndNBins (0, 500, 100); } /// /// Check if the selected trigger is appropriate /// to run the analysis, depending on the period /// certain triggers were not available. /// /// Run MC analysis for no trigger. /// /// \param simulation: bool with data (0) or MC (1) condition /// \param trigger: trigger string name (EMCAL_L0, EMCAL_L1, EMCAL_L2, DCAL_L0, DCAL_L1, DCAL_L2) /// \param period: LHCXX /// \param year: 2011, ... /// /// \return True if analysis can be done. /// Bool_t CheckAnalysisTrigger(Bool_t simulation, TString trigger, TString period, Int_t year) { // Accept directly all MB kind of events // if ( trigger.Contains("default") || trigger.Contains("INT") || trigger.Contains("MB") ) return kTRUE; // MC analysis has no trigger dependence, execute only for the default case // if ( simulation ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggered events not checked in simulation, SKIP trigger %s! \n", trigger.Data()); return kFALSE; } // Triggers introduced in 2011 // if ( year < 2011 && ( trigger.Contains("EMCAL") || trigger.Contains("DCAL") ) ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events for year < 2011, SKIP trigger %s! \n", trigger.Data()); return kFALSE; } // DCal Triggers introduced in 2015 // if ( year < 2014 && trigger.Contains("DCAL") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data()); return kFALSE; } // EG2 trigger only activated from 2013 // if ( year < 2013 && trigger.Contains("L2") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : EG2 trigger not available for year < 2012, SKIP trigger %s in %s \n", trigger.Data(),period.Data()); return kFALSE; } // Triggers only activated in 2013 from LHC13d for physics (it might be there are in b and c but not taking data) // if ( year == 2013 && trigger.Contains("L") && ( period.Contains("b") || period.Contains("c") ) ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : Triggers not available for year 2013 in period %s, SKIP trigger %s! \n",period.Data(), trigger.Data()); return kFALSE; } // DCal Triggers introduced in 2015 // if ( year < 2014 && ( trigger.Contains("DCAL") ) ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No triggered events by DCal for year < 2014, SKIP trigger %s! \n", trigger.Data()); return kFALSE; } // L0 trigger used for periods below LHC11e? // if ( period == "LHC11h" && trigger.Contains("EMCAL_L0") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No EMCAL_L0 triggered events by EMCal for period LHC11h, SKIP trigger %s! \n", trigger.Data()); return kFALSE; } // L1 trigger not used until LHC11e? period, what about LHC11f? // if ( period.Contains("LHC11") && period != "LHC11h" && trigger.Contains("EMCAL_L1") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data()); return kFALSE; } // L1 trigger not used again until LHC12c period // if ( ( period == "LHC12a" || period == "LHC12b" ) && trigger.Contains("EMCAL_L1") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data()); return kFALSE; } // Run2: No trigger used again until LHC15i period // if ( year == 2015 && ( period == "LHC15h" || period == "LHC15g" || period == "LHC15f" || period == "LHC15e" || period == "LHC15d" || period == "LHC15c" || period == "LHC15b" || period == "LHC15a" ) ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data()); return kFALSE; } // Run2: L1 trigger not used again until LHC15o period // if ( year == 2015 && period != "LHC15o" && !trigger.Contains("L0") ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data()); return kFALSE; } // Run2: L1 trigger not used again until LHC15o period // if ( year == 2015 && period == "LHC15o" && ( trigger.Contains("L0") || trigger.Contains("L2") ) ) { printf("AddTaskPi0IMGammaCorrQA - CAREFUL : No %s triggered events by EMCal for period %s, SKIP \n", trigger.Data(),period.Data()); return kFALSE; } return kTRUE; }
{ "content_hash": "5b5238b360547c94929da12ae2160e9e", "timestamp": "", "source": "github", "line_count": 1135, "max_line_length": 151, "avg_line_length": 36.073127753303964, "alnum_prop": 0.6527611557531202, "repo_name": "mbjadhav/AliPhysics", "id": "a4814836f78341035d8e6072bf3e28a42fc1ae2d", "size": "47345", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "PWGGA/CaloTrackCorrelations/macros/QA/AddTaskPi0IMGammaCorrQA.C", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "55549165" }, { "name": "C++", "bytes": "97260808" }, { "name": "CMake", "bytes": "535896" }, { "name": "CSS", "bytes": "5189" }, { "name": "Fortran", "bytes": "134275" }, { "name": "HTML", "bytes": "7245" }, { "name": "JavaScript", "bytes": "3536" }, { "name": "Makefile", "bytes": "25080" }, { "name": "Objective-C", "bytes": "166764" }, { "name": "Perl", "bytes": "29916" }, { "name": "Python", "bytes": "719854" }, { "name": "Shell", "bytes": "1004662" }, { "name": "TeX", "bytes": "392122" } ], "symlink_target": "" }
/*jslint regexp: true */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, window: false, process: false, Packages: false, java: false, location: false */ define(['module'], function (module) { 'use strict'; var text, fs, progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), defaultHostName = hasLocation && location.hostname, defaultPort = hasLocation && (location.port || undefined), buildMap = [], masterConfig = (module.config && module.config()) || {}; text = { version: '2.0.5', strip: function (content) { //Strips <?xml ...?> declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, jsEscape: function (content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r") .replace(/[\u2028]/g, "\\u2028") .replace(/[\u2029]/g, "\\u2029"); }, createXhr: masterConfig.createXhr || function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject !== "undefined") { for (i = 0; i < 3; i += 1) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } return xhr; }, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var modName, ext, temp, strip = false, index = name.indexOf("."), isRelative = name.indexOf('./') === 0 || name.indexOf('../') === 0; if (index !== -1 && (!isRelative || index > 1)) { modName = name.substring(0, index); ext = name.substring(index + 1, name.length); } else { modName = name; } temp = ext || modName; index = temp.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = temp.substring(index + 1) === "strip"; temp = temp.substring(0, index); if (ext) { ext = temp; } else { modName = temp; } } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ useXhr: function (url, protocol, hostname, port) { var uProtocol, uHostName, uPort, match = text.xdRegExp.exec(url); if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad) { content = strip ? text.strip(content) : content; if (masterConfig.isBuild) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the <?xml ...?> declarations so the content can be inserted //into the current doc without problems. // Do not bother with the work if a build and text will // not be inlined. if (config.isBuild && !config.inlineText) { onLoad(); return; } masterConfig.isBuild = config.isBuild; var parsed = text.parseName(name), nonStripName = parsed.moduleName + (parsed.ext ? '.' + parsed.ext : ''), url = req.toUrl(nonStripName), useXhr = (masterConfig.useXhr) || text.useXhr; //Load the text. Use XHR if possible and in a browser. if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad); }, function (err) { if (onLoad.error) { onLoad.error(err); } }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad); }); } }, write: function (pluginName, moduleName, write, config) { if (buildMap.hasOwnProperty(moduleName)) { var content = text.jsEscape(buildMap[moduleName]); write.asModule(pluginName + "!" + moduleName, "define(function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), extPart = parsed.ext ? '.' + parsed.ext : '', nonStripName = parsed.moduleName + extPart, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + extPart) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. //But need to create shell that translates writeFile's //write() to the right interface. var textWrite = function (contents) { return write(fileName, contents); }; textWrite.asModule = function (moduleName, contents) { return write.asModule(moduleName, fileName, contents); }; text.write(pluginName, nonStripName, textWrite, config); }, config); } }; if (masterConfig.env === 'node' || (!masterConfig.env && typeof process !== "undefined" && process.versions && !!process.versions.node)) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); text.get = function (url, callback) { var file = fs.readFileSync(url, 'utf8'); //Remove BOM (Byte Mark Order) from utf8 files if it is there. if (file.indexOf('\uFEFF') === 0) { file = file.substring(1); } callback(file); }; } else if (masterConfig.env === 'xhr' || (!masterConfig.env && text.createXhr())) { text.get = function (url, callback, errback, headers) { var xhr = text.createXhr(), header; xhr.open('GET', url, true); //Allow plugins direct access to xhr headers if (headers) { for (header in headers) { if (headers.hasOwnProperty(header)) { xhr.setRequestHeader(header.toLowerCase(), headers[header]); } } } //Allow overrides specified in config if (masterConfig.onXhr) { masterConfig.onXhr(xhr, url); } xhr.onreadystatechange = function (evt) { var status, err; //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { status = xhr.status; if (status > 399 && status < 600) { //An http 4xx or 5xx error. Signal an error. err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; errback(err); } else { callback(xhr.responseText); } } }; xhr.send(null); }; } else if (masterConfig.env === 'rhino' || (!masterConfig.env && typeof Packages !== 'undefined' && typeof java !== 'undefined')) { //Why Java, why is this so awkward? text.get = function (url, callback) { var stringBuffer, line, encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } return text; });
{ "content_hash": "e8b65cdc1b79e9b52c76a5587cfa8dd4", "timestamp": "", "source": "github", "line_count": 328, "max_line_length": 127, "avg_line_length": 40.1859756097561, "alnum_prop": 0.47780896745315227, "repo_name": "pissang/claygl", "id": "38a2efc1d465a93816754623684c2a2db30c54fd", "size": "13385", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "example/text.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "303" }, { "name": "GLSL", "bytes": "133630" }, { "name": "HTML", "bytes": "267329" }, { "name": "JavaScript", "bytes": "1548089" }, { "name": "Python", "bytes": "58877" } ], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigateTo { [ExportWorkspaceServiceFactory(typeof(INavigateToPreviewService), ServiceLayer.Editor), Shared] internal sealed class DefaultNavigateToPreviewServiceFactory : IWorkspaceServiceFactory { private readonly Lazy<INavigateToPreviewService> _singleton = new Lazy<INavigateToPreviewService>(() => new DefaultNavigateToPreviewService()); [ImportingConstructor] public DefaultNavigateToPreviewServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { return _singleton.Value; } } }
{ "content_hash": "9cc34b3d16344db47fa2d920435fbacc", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 99, "avg_line_length": 36.142857142857146, "alnum_prop": 0.7450592885375494, "repo_name": "agocke/roslyn", "id": "64c7ee842385e3d332342b1ce9cb7bc284087bf4", "size": "1014", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/EditorFeatures/Core.Wpf/NavigateTo/DefaultNavigateToPreviewServiceFactory.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "289100" }, { "name": "Batchfile", "bytes": "9059" }, { "name": "C#", "bytes": "126326705" }, { "name": "C++", "bytes": "5602" }, { "name": "CMake", "bytes": "8276" }, { "name": "Dockerfile", "bytes": "2450" }, { "name": "F#", "bytes": "549" }, { "name": "PowerShell", "bytes": "237208" }, { "name": "Shell", "bytes": "94927" }, { "name": "Visual Basic .NET", "bytes": "70527543" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/header" /> <!--<android.support.v4.widget.SwipeRefreshLayout--> <!--android:id="@+id/contact_refresh"--> <!--android:layout_width="match_parent"--> <!--android:layout_height="match_parent">--> <com.test.myqq.view.ContactView android:id="@+id/contactView" android:layout_width="match_parent" android:layout_height="match_parent"/> <!--</android.support.v4.widget.SwipeRefreshLayout>--> </LinearLayout>
{ "content_hash": "af4b66053c1e027063816398e864cc4c", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 72, "avg_line_length": 38.78947368421053, "alnum_prop": 0.6445047489823609, "repo_name": "xqgdmg/MyQQDemo", "id": "9aabb4d387588a22909aaea6dac3937d0d67844d", "size": "737", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/fragment_contact.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "89180" } ], "symlink_target": "" }
"""Settings for Norc, including all Django configuration. Defaults are stored in defaults.py, and local environments are stored in settings_local.py to avoid version control. This file merely pulls in settings from those other files. """ import os import sys try: import norc except ImportError, e: print 'ImportError:', e sys.exit(1) from norc.settings_local import * from norc.defaults import Envs # Find the user's environment. env_str = os.environ.get('NORC_ENVIRONMENT') if not env_str: raise Exception('You must set the NORC_ENVIRONMENT shell variable.') try: cur_env = Envs.ALL[env_str] except KeyError, ke: raise Exception("Unknown NORC_ENVIRONMENT '%s'." % env_str) # Use the settings from that environment. for s in dir(cur_env): # If the setting name is a valid constant, add it to globals. VALID_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_' if not s.startswith('_') and all(map(lambda c: c in VALID_CHARS, s)): globals()[s] = cur_env[s]
{ "content_hash": "bf04bb1100ab6dfc381b2538429a68ce", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 73, "avg_line_length": 28.4, "alnum_prop": 0.7142857142857143, "repo_name": "darrellsilver/norc", "id": "143e692ad6848ae2dd1811eb6569a0e029b7bd95", "size": "995", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "settings.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "20532" }, { "name": "Python", "bytes": "165903" } ], "symlink_target": "" }
<?php // src/AppBundle/Admin/PostAdmin.php namespace tutolympique\AdminBundle\Admin; use Sonata\AdminBundle\Admin\AbstractAdmin; use Sonata\AdminBundle\Show\ShowMapper; use Sonata\AdminBundle\Form\FormMapper; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; class UtilisateurAdmin extends AbstractAdmin { // Fields to be shown on create/edit forms protected function configureFormFields(FormMapper $formMapper) { $formMapper ->add('uti_pk_fk_per_id','entity',array('class'=>'tutolympique\AdminBundle\Entity\Personne')) ->add('uti_ville','text') ->add('uti_code_postal','text') ->add('uti_nombre_tutos','text') ; } // Fields to be shown on filter forms protected function configureDatagridFilters(DatagridMapper $datagridMapper) { $datagridMapper ->add('uti_pk_fk_per_id','entity',array('class'=>'tutolympique\AdminBundle\Entity\Personne')) ->add('uti_ville','doctrine_orm_string') ->add('uti_code_postal','doctrine_orm_string') ->add('uti_nombre_tutos','doctrine_orm_string') ; } // Fields to be shown on lists protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('uti_pk_fk_per_id','entity',array('class'=>'tutolympique\AdminBundle\Entity\Personne')) ->add('uti_ville') ->add('uti_code_postal') ->add('uti_nombre_tutos') ; } // Fields to be shown on show action protected function configureShowFields(ShowMapper $showMapper) { $showMapper ->add('uti_pk_fk_per_id','entity',array('class'=>'tutolympique\AdminBundle\Entity\Personne')) ->add('uti_ville') ->add('uti_code_postal') ->add('uti_nombre_tutos') ; } }
{ "content_hash": "df25d2391c6726b076f9499d47144133", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 115, "avg_line_length": 33.54385964912281, "alnum_prop": 0.6312761506276151, "repo_name": "nico06530/tutolympique", "id": "3f548e6a55f01c3ed27ab46fe62142e22c515922", "size": "1912", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/tutolympique/AdminBundle/Admin/UtilisateurAdmin.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "248" }, { "name": "CSS", "bytes": "112486" }, { "name": "HTML", "bytes": "323887" }, { "name": "JavaScript", "bytes": "68982" }, { "name": "PHP", "bytes": "952251" }, { "name": "Shell", "bytes": "1228" } ], "symlink_target": "" }
import os import sys import h5py import numpy as np from time import gmtime import ibmtomography as itm import matlab.engine # python 2 and 3 import of the IBM experience module if sys.version_info.major > 2: from IBMQuantumExperience.IBMQuantumExperience import IBMQuantumExperience else: from IBMQuantumExperience import IBMQuantumExperience # define user token token = 'a42ac7aef6ce008f2e7f437a708e64e6683f6dcb0fe043474663b8f4909a40e3357266a496c7c3659c69dc984ba56476d1c6b4c84c4af2cb2d0f7f6d52874cab' # define config URL explicitly config = {"url": 'https://quantumexperience.ng.bluemix.net/api'} # path to experiment data file if os.path.isdir('C:\\Users\\Helios'): archivepath = 'C:\\Users\\Helios\\Documents\\Projects\\Uni\\2017\\markovpy\\archive.hdf5' else: archivepath = 'C:\\Users\\Joshua\\Documents\\Projects\\Uni\\2017\\Research\\markovpy\\archive.hdf5' #-------------------------------------------------------------------------- # COMPLETED #-------------------------------------------------------------------------- class TCircGen(): """ Implements an iterator that returns the next circuit suffix for a tomography run """ def __init__(self, targets, measureset=[]): # store qubits to be reconstructed self.targets = targets # define the measurement basis set if len(measureset) == 0: self.measureset = np.asarray( ['h q[{0}];\nmeasure q[{0}] -> c[{0}];', 's q[{0}];\nh q[{0}];\nmeasure q[{0}] -> c[{0}];', 'measure q[{0}] -> c[{0}];']) else: self.measureset = measureset # define all combinations of measure set for given number of qubits from itertools import product self.combs = product(self.measureset, repeat=len(self.targets)) self.measindex = product( list(range(0, len(self.measureset))), repeat=len(self.targets)) def __iter__(self): # initialise circuit iterator number self.circnum = 0 return self def __next__(self): if self.circnum < len(self.measureset)**len(self.targets): # retrieve next circuit configuration combination = next(self.combs) circuitsuffix = '' # generate circuit suffix for num, qtarget in enumerate(self.targets): circuitsuffix += '\n' + combination[num].format(qtarget) # compute measurement indexes applied in current circuit circconfig = (len(self.targets)*'{}').format(*next(self.measindex)) # increment iterator self.circnum += 1 return circuitsuffix, circconfig else: raise StopIteration # format target file into appropriate string def fileparse(filename, filepath=None): # retrieve file contents, stripping white space and semicolon delimiter if filepath == None: with open(os.getcwd() + '\\' + filename, 'r') as f: qasm = [m.lstrip() for m in f] else: with open(filepath + '\\' + filename, 'r') as f: qasm = [m.lstrip() for m in f] # get rid of all blank lines and return concatenated file return ''.join(list(filter(None, qasm))) # test function for archive def archivetest(archive): for i in archive: print(i) # distributes the execution codes for an uploaded file. Assumes IBM return # an ordered dictionary D: def codedist(archive, codes): # iterate through archive for circuit in archive: if circuit == 'Support_Group': continue # check for complete case if archive[circuit].attrs['complete'] < archive[circuit].attrs['total']: # iterate over first len(codes) circuits with ready status for perm in archive[circuit]: if perm == 'raw_qasm' or perm == 'tomography_ML' or perm == 'Data_Group': continue # check for remaining return codes elif len(codes) == 0: break # update circuit permutation with return code elif archive[circuit][perm].attrs['status'] == 0: archive[circuit][perm].attrs['executionId'] = np.string_( codes[0]['executionId']) archive[circuit][perm].attrs['status'] = 1 # remove return code for perm circuit del codes[0] # adds new circuit to archive def archiveadd(archive, path, fileparams, shots): filepath = os.path.dirname(path) filename = os.path.basename(path) print('------- ADDING CIRCUIT: {} TO ARCHIVE -------'.format(filename)) if filename[-5:] != '.qasm': print('------- UNRECOGNISED INPUT FILE - ONLY FILES WITH \'.qasm\' EXTENSION ACCEPTED: ABORTING -------') # close archive gracefully archive.flush() archive.close() exit() # compute uploadable qasm code qasm = fileparse(filename, filepath) # attempt to add circuit to archive try: # check if file already in archive (run increase shot number routine) dataname = filename[:-5] + '_' + fileparams[0] if dataname in archive: # check if still waiting on previous results if archive[dataname].attrs['complete'] < archive[dataname].attrs['total']: print( '------- PREVIOUS ITERATION OF CIRCUIT {} IS ONGOING: IGNORING RESUBMISSION COMMAND -------'.format(dataname)) else: print( '------- CIRCUIT {} HAS ALREADY BEEN UPLOADED: REPEATING EXPERIMENT/ANALYSIS -------'.format(dataname)) # delete tomography related data try: if archive[dataname].attrs['tomography'].decode('ascii') == 'state': archive[dataname].__delitem__('tomography_ML') elif archive[dataname].attrs['tomography'].decode('ascii') == 'process': archive[dataname].__delitem__('tomography_ML') archive[dataname].__delitem__('Data_Group') # fine for now, change to specific error later except Exception: pass # adjust shot number accordingly archive[dataname].attrs['shots'] = archive[ dataname].attrs['shots'] + shots # set status for circuit reupload for perm in archive[dataname]: # ignore qasm file if perm == 'raw_qasm': continue # set status code for re-upload archive[dataname][perm].attrs['status'] = 0 archive[dataname][perm].attrs['executionId'] = 'Null' archive[dataname].attrs['complete'] = 0 # add state tomography circuit elif fileparams[1] == 'state': newcircuit = archive.create_group(dataname) # add appropriate attributes # device type to run circuits on newcircuit.attrs['device'] = np.string_(fileparams[0]) # type of tomography that is being performed (state or process) newcircuit.attrs['tomography'] = np.string_(fileparams[1]) # target qubits to measure newcircuit.attrs['qubits'] = fileparams[2] # number of completed circuits (results retrieved) newcircuit.attrs['complete'] = 0 # total number of circuits to be run newcircuit.attrs['total'] = 3**len(fileparams[2]) # set number of shots newcircuit.attrs['shots'] = shots # add raw qasm code to group newcircuit.create_dataset('raw_qasm', data=np.string_(qasm)) # generate circuits to be computed for circuit, meas in TCircGen(fileparams[2]): # create data groups with appropriate format grpname = filename[ :-5] + '_{}:{}:{}:{}:{}:{}_'.format(*gmtime()[0:6]) + meas tomogcirc = newcircuit.create_group(grpname) # add status attribute: 0 for ready, 1 for uploaded, 2 for # complete tomogcirc.attrs['status'] = int(0) # add idExecution code (null for now) tomogcirc.attrs['executionId'] = np.string_('Null') # add specific qasm code tomogcirc.create_dataset( 'qasm', data=np.string_(qasm + circuit)) # generate process tomography circuits elif fileparams[1] == 'process': newcircuit = archive.create_group(dataname) # add appropriate attributes # device type to run circuits on newcircuit.attrs['device'] = np.string_(fileparams[0]) # type of tomography that is being performed (state or process) newcircuit.attrs['tomography'] = np.string_(fileparams[1]) # target qubits to measure newcircuit.attrs['qubits'] = fileparams[2] # number of completed circuits (results retrieved) newcircuit.attrs['complete'] = 0 # total number of circuits to be run newcircuit.attrs['total'] = ( 3**len(fileparams[2]))*(4**len(fileparams[2])) # set number of shots newcircuit.attrs['shots'] = shots # add raw qasm code to group newcircuit.create_dataset('raw_qasm', data=np.string_(qasm)) # define preparation basis for the set {|0>, |1>, |+>, |i+>} basisset = np.asarray( ['', 'x q[{0}];', 'h q[{0}];', 'h q[{0}];\ns q[{0}];']) # generate all circuit preparation stages and for each all # tomography permutations for prepcircuit, prep in TCircGen(fileparams[2], basisset): for statecircuit, state in TCircGen(fileparams[2]): # create data groups with appropriate formatting grpname = filename[ :-5] + '_{}:{}:{}:{}:{}:{}_'.format(*gmtime()[0:6]) + prep + '_' + state tomogcirc = newcircuit.create_group(grpname) # add status attribute: 0 for ready, 1 for uploaded, 2 for # complete tomogcirc.attrs['status'] = int(0) # add idExecution code (null for now) tomogcirc.attrs['executionId'] = np.string_('Null') # insert preparation string prepqasm = qasm.replace( '//PROCESS', prepcircuit + '\n') # add specific qasm code tomogcirc.create_dataset( 'qasm', data=np.string_(prepqasm + statecircuit)) # run circuit as is elif fileparams[1] == 'none': newcircuit = archive.create_group(dataname) # add appropriate attributes # device type to run circuits on newcircuit.attrs['device'] = np.string_(fileparams[0]) # type of tomography that is being performed (state or process) newcircuit.attrs['tomography'] = np.string_(fileparams[1]) # target qubits to measure newcircuit.attrs['qubits'] = fileparams[2] # number of completed circuits (results retrieved) newcircuit.attrs['complete'] = 0 # total number of circuits to be run newcircuit.attrs['total'] = 1 # set number of shots newcircuit.attrs['shots'] = shots # add raw qasm code to group newcircuit.create_dataset('raw_qasm', data=np.string_(qasm)) # create sub group for circuit grpname = filename[:-5] + \ '_{}:{}:{}:{}:{}:{}_'.format(*gmtime()[0:6]) singlecirc = newcircuit.create_group(grpname) # add status attribute: 0 for ready, 1 for uploaded, 2 for # complete singlecirc.attrs['status'] = int(0) # add idExecution code (null for now) singlecirc.attrs['executionId'] = np.string_('Null') # create group specific qasm dataset singlecirc.create_dataset('qasm', data=np.string_(qasm)) return else: archive.flush() archive.close() print( '------- UNRECOGNISED TOMOGRPAHY PARAMETER: \'{}\' ABORTING -------'.format(fileparams[1])) exit() except ValueError as e: # catch group construction error and close archive file with grace print(e) archive.flush() archive.close() exit() # adds target qasm files to archive in batch files from txt file def batchparse(archive, shots, queuefile='filequeue.txt'): # path to experiment data file if os.path.isdir('C:\\Users\\Helios'): queuepath = 'C:\\Users\\Helios\\Documents\\Projects\\Uni\\2017\\markovpy' else: queuepath = 'C:\\Users\\Joshua\\Documents\\Projects\\Uni\\2017\\Research\\markovpy' # check that target file exists path = queuepath + '\\' + queuefile if os.path.isfile(path): # open file and parse all awaiting circuits with open(path, 'r') as queue: # extract lines and drop blank lines lines = (line.rstrip() for line in queue) lines = list(line for line in lines if line) # lines that are invalid are rewritten to list queue for user rewrite = [] # parse each new circuit file with parameters for index, item in enumerate(lines): circuit = item.split(';') # check for correct input formatting if len(circuit) == 4: file = circuit[0] fileparams = [circuit[1], circuit[ 2], list(map(int, circuit[3]))] archiveadd(archive, file, fileparams, shots) else: rewrite.append(index) print( '------- CIRCUIT {} IN QUEUE FILE HAS INCORRECT NUMBER OF ARGUMENTS: IGNORING -------'.format(index)) # write all lines that were not parsed back to file lines = [lines[i] for i in rewrite] with open(path, 'w') as queue: for line in lines: queue.write(line + '\n') else: print('------- CIRCUIT BATCH FILE \'{}\' NOT FOUND IN WORKING DIRECTORY: RECOMMEND CREATION -------'.format(path)) # handles experiment interfacing and data arbitration def experimentrun(archive, interface, filename=None, filepath=None, tomography="ML", shots=1024): # get number of credits remaining credits = interface.get_my_credits()['remaining'] if qInterface.backend_status('ibmqx4')['available']: print('------- IBM QUANTUM COMPUTER IS ONLINE: {} CREDITS AVAILABLE -------'.format(credits)) ibmOnline = True else: print('------- IBM QUANTUM COMPUTER IS OFFLINE: UNABLE TO RUN ON EXPERIMENTAL HARDWARE -------') ibmOnline = False # add new circuits to archive file if any exist batchparse(archive, shots) # run experiments remotely jobcodes = [] for circuit in archive: if circuit == 'Support_Group': continue ccirc = archive[circuit] # check if experiment has any circuits awaiting completion for current # circuit if ccirc.attrs['complete'] < ccirc.attrs['total']: print( '------- RETRIEVING MEASUREMENT STATISTICS FOR CIRCUIT: {} -------'.format(circuit)) device = ccirc.attrs['device'].decode('ascii') # iterate over archive circuits, handling status as needed: # status = 0: upload file # status = 1: retrieve data # status = 2: do nothing for perm in ccirc: # skip raw_qasm, could put in attributes but.....size # guidelines if perm == 'raw_qasm': continue # add files with status 0 (ready) to job queue if qc online or # running on simulator elif ccirc[perm].attrs['status'] == 0 and (ibmOnline or device == 'simulator'): jobcodes.append( {'qasm': ccirc[perm]['qasm'][()].decode('ascii')}) # check if past jobs are finished elif ccirc[perm].attrs['status'] == 1: # get execution result from IBM result = qInterface.get_result_from_execution( ccirc[perm].attrs['executionId'].decode('ascii')) # check for null result (computation not done yet) if any(result): # check if previous result exists and if so, average # measurement result if 'values' in ccirc[perm]: if len(np.asarray(ccirc[perm]['values'][()])) != len(np.asarray(result['measure']['values'])): print('------- RETURN VALUE DIMENSION MISMATCH for {}: COMPENSATING -------'.format(perm)) # compute new values nlabels, nmeas = measurementpad(ccirc[perm]['labels'][()], result['measure'][ 'labels'], np.asarray(ccirc[perm]['values'][()]), np.asarray(result['measure']['values'])) # store updated statistics ccirc[perm].__delitem__('labels') ccirc[perm].__delitem__('values') ccirc[perm].create_dataset('labels', data=np.array(labels, data=object), dtype=h5py.special_dtype(vlen=str)) ccirc[perm].create_dataset('values', data=nmeas) else: newval = 0.5 * \ np.asarray(ccirc[perm]['values'][ ()]) + 0.5*np.asarray(result['measure']['values']) ccirc[perm].__delitem__('values') ccirc[perm].create_dataset( 'values', data=newval) else: # add label data to archive file ccirc[perm].create_dataset('labels', data=np.array( result['measure']['labels'], dtype=object), dtype=h5py.special_dtype(vlen=str)) # add measured probabilities to archive file ccirc[perm].create_dataset( 'values', data=result['measure']['values']) # set circuit permutation status to complete ccirc[perm].attrs['status'] = 2 # increment number of completed circuits in parent # group ccirc.attrs['complete'] += 1 # upload jobs in batches of 50 if len(jobcodes) == 50: if interface.get_my_credits()['remaining'] >= 5 or device == 'simulator': uploads = interface.run_job( jobcodes, backend=device, shots=shots, max_credits=100) codedist(archive, uploads['qasms']) else: print( '------- OUT OF CREDITS TO RUN EXPERIMENT: AWAITING RENEWAL -------') jobcodes = [] # empty job list if any circuits remain if len(jobcodes) > 0: if interface.get_my_credits()['remaining'] >= 5 or device == 'simulator': uploads = interface.run_job( jobcodes, backend=device, shots=shots, max_credits=100) codedist(archive, uploads['qasms']) else: print('------- OUT OF CREDITS TO RUN EXPERIMENT: AWAITING RENEWAL -------') jobcodes = [] # perform state tomography using defined method on all completed circuits # instantiate matlab engine mateng = matlab.engine.start_matlab() for circuit in archive: if circuit == 'Support_Group': continue # check if circuit is complete and is compliant with state # tomography if (archive[circuit].attrs['complete'] == archive[circuit].attrs['total']): path = '/' + circuit + '/tomography_' + tomography # check if tomography already performed if path not in archive: # perform state tomography if archive[circuit].attrs['tomography'].decode('ascii') == 'state': print( '------- PERFORMING STATE TOMOGRAPHY ON CIRCUIT: {} -------'.format(circuit)) # perform state reconstruction using appropriate method density = getattr(itm, 'statetomography_' + tomography)(archive, circuit, mateng, goal='state') # add reconstructed operator to archive archive[circuit].create_dataset( 'tomography_' + tomography, data=density) # flush archive to be safe archive.flush() # perform state tomography on all preperation states, storing # reconstructed states in new group elif archive[circuit].attrs['tomography'].decode('ascii') == 'process' and tomography == 'ML': # perform state reconstruction using appropriate method state_set = getattr(itm, 'statetomography_ML')( archive, circuit, mateng, goal='process') newcircuit = archive[circuit].create_group('tomography_ML') for pair in state_set: # add reconstructed operator to archive archive[circuit]['tomography_ML'].create_dataset( 'tomography_ML_' + pair[0], data=np.asarray(pair[1])) # flush archive to be safe archive.flush() # perform process tomography on all completed and reconstructed circuits # check if process tomography has already been performed path = '/' + circuit + '/Data_Group' if path not in archive: if archive[circuit].attrs['tomography'].decode('ascii') == 'process' and archive[circuit].get('tomography_ML', getclass=True) == h5py._hl.group.Group: print( '------- PERFORMING PROCESS TOMOGRAPHY ON CIRCUIT: {} -------'.format(circuit)) # iterate over computed density matrices chi, opbasis, prepbasis = itm.processtomography( archive, circuit, mateng) # compute kraus operators kraus = itm.mapcompute(chi, opbasis) # compute Choi matrix representation choi = itm.kraus2choi(kraus) # compute A form aform = itm.kraus2choi(kraus, rep='loui') # create data group datagroup = archive[circuit].create_group('Data_Group') # add computed chi matrix to archive datagroup.create_dataset('Process_matrix', data=chi) # add operator sum representation datagroup.create_dataset('Kraus_set', data=kraus) # add Choi matrix datagroup.create_dataset('Choi_matrix', data=choi) # add A matrix datagroup.create_dataset('A_form', data=aform) # add operator basis used to compute above datagroup.create_dataset( 'Operator_basis_set', data=opbasis) # add preparation basis used to compute above datagroup.create_dataset( 'Preperation_basis_set', data=prepbasis) # flush archive to be safe archive.flush() # pads measurement results to avoid measurment mismatch def measurementpad(clabels, inlabels, cmeas, inmeas): # initialise new labels and measurements clabels = list(clabels) inlabels = list(inlabels) nlabels = [] nmeas = [] for j, item in enumerate(inlabels): # check if measurement result already exists try: ind = clabels.index(item) nlabels.append(item) # compute measurement value meas = 0.5*(cmeas[ind] + inmeas[j]) nmeas.append(meas) # catch new value except ValueError: # aqdd new value to labels nlabels.append(item) meas = 0.5*inmeas[j] nmeas.append(meas) return nlabels, np.asarray(nmeas) #-------------------------------------------------------------------------- # TO BE IMPLEMENTED #-------------------------------------------------------------------------- #-------------------------------------------------------------------------- # CURRENTLY WORKING ON #-------------------------------------------------------------------------- if __name__ == '__main__': # construct API object for interfacing with the IBM QC qInterface = IBMQuantumExperience(token, config) # hdf5 data storage file with h5py.File(archivepath, 'a') as archive: # archive.__delitem__('hadamardq0_simulator') try: experimentrun(archive, qInterface, shots=8192) #itm.densityplot(archive, '5QSTentangle_ibmqx2') except Exception as e: print(e) archive.flush() archive.close() exit() archive.flush() archive.close() from gitmanage import gitcommit gitcommit(os.getcwd())
{ "content_hash": "de431e90706428acc814893e6b16cc6f", "timestamp": "", "source": "github", "line_count": 600, "max_line_length": 166, "avg_line_length": 43.95166666666667, "alnum_prop": 0.530506996321717, "repo_name": "QCmonk/ibmSDK", "id": "2acb239e44c61b788406b2f2a6b1407ea818e77e", "size": "26519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "python/ibmupload.py", "mode": "33188", "license": "mit", "language": [ { "name": "Mathematica", "bytes": "4667" }, { "name": "Matlab", "bytes": "11907" }, { "name": "Python", "bytes": "99933" } ], "symlink_target": "" }
Djortunes (`django_fortunes` app) ================================= `django_fortunes`'s a [Django](http://www.djangoproject.com/) application to store fortunes (snippets of quotes, eg. IRC/IM ones). Originally inspired by the « [Fortunes](http://fortunes.inertie.org/) » application, by [Maurice Svay](http://svay.com/). ![screenshot](http://files.droplr.com/files/6619162/RKP6D.djortunes.png "Example app screen") I'm discovering and learning both [Python](http://python.org/) and [Django](http://www.djangoproject.com/) while coding it, so don't expect too much reliability, but I would warmly welcome any code review against the code :) If you're curious enough, you might check out the [Symfony version of this app](http://github.com/n1k0/sftunes). Prerequisites ------------- * Django 1.2 or more recent * `django-registration` 0.7 * Eventually, the `django-debug-toolbar` if you plan to use the provided sample `settings_local.py.sample` file for a standard dev environment Installation ------------ Djortunes ship as a standalone application (located in the `django_fortunes` directory), and a sample Django project is also provided as an example of use (in the `django_fortunes_example` directory). The better way to install dependencies (using a `virtualenv` is highly encouraged) is by using the provided `pip` requirements file: $ pip install -r requirements.txt You can adjust and override the project settings by configuring a custom settings file: a sample `settings_local.py.sample` file is provided within the example project directory. You can safely rename it `settings_local.py` and tweak its values. Then, just run the `./manage.py runserver` within the `django_fortunes_example` directory: $ cd django_fortunes_example $ ./manage.py runserver --settings=settings_local Configuration ------------- Several settings are available in the `django_fortunes` application, and you can override their defaults in your project's `settings.py` configuration file: # Maximum number of fortunes to be shown in lists FORTUNES_MAX_PER_PAGE = 10 # Maximum number of top fortune authors to display in the sidebar FORTUNES_MAX_TOP_CONTRIBUTORS = 5 License ------- This work is released under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License). Authors ------- * [Nicolas Perriault](http://github.com/n1k0) * [Florent Messa](http://github.com/thoas)
{ "content_hash": "7d8fe252f81b15ed36434dd81329d21e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 252, "avg_line_length": 44.09090909090909, "alnum_prop": 0.7327835051546392, "repo_name": "n1k0/djortunes", "id": "7e698f3d800296bc0546fac9b337a87518650140", "size": "2427", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "28585" } ], "symlink_target": "" }
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "util.h" #include "sync.h" #include "ui_interface.h" #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include <boost/asio.hpp> #include <boost/asio/ip/v6_only.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/asio/ssl.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/shared_ptr.hpp> #include <list> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static inline unsigned short GetDefaultRPCPort() { return GetBoolArg("-testnet", false) ? 16332 : 6332; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; } void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str())); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64 AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 84000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64 nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64 amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; if (pcmd->reqWallet && !pwalletMain) continue; try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand.c_str()); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help [command]\n" "List commands, or get help for a command."); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "Stop YACCoin server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "YACCoin server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, { "getblockcount", &getblockcount, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "getgenerate", &getgenerate, true, false, false }, { "setgenerate", &setgenerate, true, false, true }, { "gethashespersec", &gethashespersec, true, false, false }, { "getinfo", &getinfo, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, { "getnewaddress", &getnewaddress, true, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, { "setaccount", &setaccount, true, false, true }, { "getaccount", &getaccount, false, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, { "walletlock", &walletlock, true, false, true }, { "encryptwallet", &encryptwallet, false, false, true }, { "validateaddress", &validateaddress, true, false, false }, { "getbalance", &getbalance, false, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "addmultisigaddress", &addmultisigaddress, false, false, true }, { "createmultisig", &createmultisig, true, true , false }, { "getrawmempool", &getrawmempool, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "gettransaction", &gettransaction, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, { "signmessage", &signmessage, false, false, true }, { "verifymessage", &verifymessage, false, false, false }, { "getwork", &getwork, true, false, true }, { "getworkex", &getworkex, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "settxfee", &settxfee, false, false, true }, { "getblocktemplate", &getblocktemplate, true, false, false }, { "submitblock", &submitblock, false, false, false }, { "setmininput", &setmininput, false, false, false }, { "listsinceblock", &listsinceblock, false, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "importprivkey", &importprivkey, false, false, true }, { "listunspent", &listunspent, false, false, true }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false }, { "gettxout", &gettxout, true, false, false }, { "lockunspent", &lockunspent, false, false, true }, { "listlockunspent", &listlockunspent, false, false, true }, { "verifychain", &verifychain, true, false, false }, }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } // // HTTP protocol // // This ain't Apache. We're just using HTTP header for the length field // and to be compatible with other JSON-RPC implementations. // string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: yaccoin-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } string rfc1123Time() { char buffer[64]; time_t now; time(&now); struct tm* now_gmt = gmtime(&now); string locale(setlocale(LC_TIME, NULL)); setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt); setlocale(LC_TIME, locale.c_str()); return string(buffer); } static string HTTPReply(int nStatus, const string& strMsg, bool keepalive) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: yaccoin-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str()); const char *cStatus; if (nStatus == HTTP_OK) cStatus = "OK"; else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request"; else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden"; else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found"; else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error"; else cStatus = ""; return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %"PRIszu"\r\n" "Content-Type: application/json\r\n" "Server: yaccoin-json-rpc/%s\r\n" "\r\n" "%s", nStatus, cStatus, rfc1123Time().c_str(), keepalive ? "keep-alive" : "close", strMsg.size(), FormatFullVersion().c_str(), strMsg.c_str()); } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char *ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto) { string str; getline(stream, str); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char *ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver+7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon+1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || nLen > (int)MAX_SIZE) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch(nLen); stream.read(&vch[0], nLen); strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } // // JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility, // but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were // unspecified (HTTP errors and contents of 'error'). // // 1.0 spec: http://json-rpc.org/wiki/specification // 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http // http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx // string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } // // IOStream device that speaks SSL but can also speak non-SSL // template <typename Protocol> class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> { public: SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn) { fUseSSL = fUseSSLIn; fNeedHandshake = fUseSSLIn; } void handshake(ssl::stream_base::handshake_type role) { if (!fNeedHandshake) return; fNeedHandshake = false; stream.handshake(role); } std::streamsize read(char* s, std::streamsize n) { handshake(ssl::stream_base::server); // HTTPS servers read first if (fUseSSL) return stream.read_some(asio::buffer(s, n)); return stream.next_layer().read_some(asio::buffer(s, n)); } std::streamsize write(const char* s, std::streamsize n) { handshake(ssl::stream_base::client); // HTTPS clients write first if (fUseSSL) return asio::write(stream, asio::buffer(s, n)); return asio::write(stream.next_layer(), asio::buffer(s, n)); } bool connect(const std::string& server, const std::string& port) { ip::tcp::resolver resolver(stream.get_io_service()); ip::tcp::resolver::query query(server.c_str(), port.c_str()); ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); ip::tcp::resolver::iterator end; boost::system::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { stream.lowest_layer().close(); stream.lowest_layer().connect(*endpoint_iterator++, error); } if (error) return false; return true; } private: bool fNeedHandshake; bool fUseSSL; asio::ssl::stream<typename Protocol::socket>& stream; }; class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, boost::asio::placeholders::error)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, AcceptedConnection* conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn); // TODO: Actually handle errors if (error) { delete conn; } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; delete conn; } else { ServiceConnection(conn); conn->close(); delete conn; } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if ((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use yaccoind"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=yaccoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"YACCoin Alert\" [email protected]\n"), strWhatAmI.c_str(), GetConfigFile().string().c_str(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl"); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort())); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); bool fListening = false; std::string strerr; try { acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); acceptor.reset(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StopRPCThreads() { if (rpc_io_service == NULL) return; rpc_io_service->stop(); rpc_worker_group->join_all(); delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate") printf("ThreadRPCServer method=%s\n", strMethod.c_str()); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str()); /* Deter brute-forcing short passwords. If this results in a DOS the user really shouldn't have their RPC port exposed.*/ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode") && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl"); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort())))) throw runtime_error("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } template<typename T> void ConvertTo(Value& value, bool fAllowNull=false) { if (fAllowNull && value.type() == null_type) return; if (value.type() == str_type) { // reinterpret string as unquoted json value Value value2; string strJSON = value.get_str(); if (!read_string(strJSON, value2)) throw runtime_error(string("Error parsing JSON:")+strJSON); ConvertTo<T>(value2, fAllowNull); value = value2; } else { value = value.get_value<T>(); } } // Convert strings to command-specific RPC representation Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams) { Array params; BOOST_FOREACH(const std::string &param, strParams) params.push_back(param); int n = params.size(); // // Special case non-string parameter types // if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]); if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]); if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]); if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]); if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]); if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]); if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]); if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]); if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]); if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]); if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true); if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true); if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]); if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]); if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]); if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]); if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]); if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]); return params; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error strPrint = "error: " + write_string(error, false); int code = find_value(error.get_obj(), "code").get_int(); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = 87; } catch (...) { PrintException(NULL, "CommandLineRPC()"); } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } #ifdef TEST int main(int argc, char *argv[]) { #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); try { if (argc >= 2 && string(argv[1]) == "-server") { printf("server ready\n"); ThreadRPCServer(NULL); } else { return CommandLineRPC(argc, argv); } } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { PrintException(&e, "main()"); } catch (...) { PrintException(NULL, "main()"); } return 0; } #endif const CRPCTable tableRPC;
{ "content_hash": "82cde265585fea9965c80446ae2fc311", "timestamp": "", "source": "github", "line_count": 1305, "max_line_length": 159, "avg_line_length": 37.216858237547896, "alnum_prop": 0.5769436666117608, "repo_name": "yaccoin/yaccoin", "id": "141814f0cdecc3c563931f54d563178aeec5854f", "size": "48568", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/bitcoinrpc.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "32677" }, { "name": "C++", "bytes": "2601125" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18284" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "99424" }, { "name": "NSIS", "bytes": "6074" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "5864" }, { "name": "Python", "bytes": "69709" }, { "name": "QMake", "bytes": "15072" }, { "name": "Shell", "bytes": "9702" } ], "symlink_target": "" }
/* -*- buffer-read-only: t -*- vi: set ro: */ /* DO NOT EDIT! GENERATED AUTOMATICALLY! */ /* Copyright (C) 2001-2002, 2004-2011 Free Software Foundation, Inc. Written by Paul Eggert, Bruno Haible, Sam Steingold, Peter Burwood. This file is part of gnulib. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * ISO C 99 <stdint.h> for platforms that lack it. * <http://www.opengroup.org/susv3xbd/stdint.h.html> */ #ifndef _@GUARD_PREFIX@_STDINT_H #if __GNUC__ >= 3 @PRAGMA_SYSTEM_HEADER@ #endif @PRAGMA_COLUMNS@ /* When including a system file that in turn includes <inttypes.h>, use the system <inttypes.h>, not our substitute. This avoids problems with (for example) VMS, whose <sys/bitypes.h> includes <inttypes.h>. */ #define _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H /* Get those types that are already defined in other system include files, so that we can "#define int8_t signed char" below without worrying about a later system include file containing a "typedef signed char int8_t;" that will get messed up by our macro. Our macros should all be consistent with the system versions, except for the "fast" types and macros, which we recommend against using in public interfaces due to compiler differences. */ #if @HAVE_STDINT_H@ # if defined __sgi && ! defined __c99 /* Bypass IRIX's <stdint.h> if in C89 mode, since it merely annoys users with "This header file is to be used only for c99 mode compilations" diagnostics. */ # define __STDINT_H__ # endif /* Other systems may have an incomplete or buggy <stdint.h>. Include it before <inttypes.h>, since any "#include <stdint.h>" in <inttypes.h> would reinclude us, skipping our contents because _@GUARD_PREFIX@_STDINT_H is defined. The include_next requires a split double-inclusion guard. */ # @INCLUDE_NEXT@ @NEXT_STDINT_H@ #endif #if ! defined _@GUARD_PREFIX@_STDINT_H && ! defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H #define _@GUARD_PREFIX@_STDINT_H /* <sys/types.h> defines some of the stdint.h types as well, on glibc, IRIX 6.5, and OpenBSD 3.8 (via <machine/types.h>). AIX 5.2 <sys/types.h> isn't needed and causes troubles. MacOS X 10.4.6 <sys/types.h> includes <stdint.h> (which is us), but relies on the system <stdint.h> definitions, so include <sys/types.h> after @NEXT_STDINT_H@. */ #if @HAVE_SYS_TYPES_H@ && ! defined _AIX # include <sys/types.h> #endif /* Get LONG_MIN, LONG_MAX, ULONG_MAX. */ #include <limits.h> #if @HAVE_INTTYPES_H@ /* In OpenBSD 3.8, <inttypes.h> includes <machine/types.h>, which defines int{8,16,32,64}_t, uint{8,16,32,64}_t and __BIT_TYPES_DEFINED__. <inttypes.h> also defines intptr_t and uintptr_t. */ # include <inttypes.h> #elif @HAVE_SYS_INTTYPES_H@ /* Solaris 7 <sys/inttypes.h> has the types except the *_fast*_t types, and the macros except for *_FAST*_*, INTPTR_MIN, PTRDIFF_MIN, PTRDIFF_MAX. */ # include <sys/inttypes.h> #endif #if @HAVE_SYS_BITYPES_H@ && ! defined __BIT_TYPES_DEFINED__ /* Linux libc4 >= 4.6.7 and libc5 have a <sys/bitypes.h> that defines int{8,16,32,64}_t and __BIT_TYPES_DEFINED__. In libc5 >= 5.2.2 it is included by <sys/types.h>. */ # include <sys/bitypes.h> #endif #undef _GL_JUST_INCLUDE_SYSTEM_INTTYPES_H /* Minimum and maximum values for an integer type under the usual assumption. Return an unspecified value if BITS == 0, adding a check to pacify picky compilers. */ #define _STDINT_MIN(signed, bits, zero) \ ((signed) ? (- ((zero) + 1) << ((bits) ? (bits) - 1 : 0)) : (zero)) #define _STDINT_MAX(signed, bits, zero) \ ((signed) \ ? ~ _STDINT_MIN (signed, bits, zero) \ : /* The expression for the unsigned case. The subtraction of (signed) \ is a nop in the unsigned case and avoids "signed integer overflow" \ warnings in the signed case. */ \ ((((zero) + 1) << ((bits) ? (bits) - 1 - (signed) : 0)) - 1) * 2 + 1) #if !GNULIB_defined_stdint_types /* 7.18.1.1. Exact-width integer types */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. */ #undef int8_t #undef uint8_t typedef signed char gl_int8_t; typedef unsigned char gl_uint8_t; #define int8_t gl_int8_t #define uint8_t gl_uint8_t #undef int16_t #undef uint16_t typedef short int gl_int16_t; typedef unsigned short int gl_uint16_t; #define int16_t gl_int16_t #define uint16_t gl_uint16_t #undef int32_t #undef uint32_t typedef int gl_int32_t; typedef unsigned int gl_uint32_t; #define int32_t gl_int32_t #define uint32_t gl_uint32_t /* If the system defines INT64_MAX, assume int64_t works. That way, if the underlying platform defines int64_t to be a 64-bit long long int, the code below won't mistakenly define it to be a 64-bit long int, which would mess up C++ name mangling. We must use #ifdef rather than #if, to avoid an error with HP-UX 10.20 cc. */ #ifdef INT64_MAX # define GL_INT64_T #else /* Do not undefine int64_t if gnulib is not being used with 64-bit types, since otherwise it breaks platforms like Tandem/NSK. */ # if LONG_MAX >> 31 >> 31 == 1 # undef int64_t typedef long int gl_int64_t; # define int64_t gl_int64_t # define GL_INT64_T # elif defined _MSC_VER # undef int64_t typedef __int64 gl_int64_t; # define int64_t gl_int64_t # define GL_INT64_T # elif @HAVE_LONG_LONG_INT@ # undef int64_t typedef long long int gl_int64_t; # define int64_t gl_int64_t # define GL_INT64_T # endif #endif #ifdef UINT64_MAX # define GL_UINT64_T #else # if ULONG_MAX >> 31 >> 31 >> 1 == 1 # undef uint64_t typedef unsigned long int gl_uint64_t; # define uint64_t gl_uint64_t # define GL_UINT64_T # elif defined _MSC_VER # undef uint64_t typedef unsigned __int64 gl_uint64_t; # define uint64_t gl_uint64_t # define GL_UINT64_T # elif @HAVE_UNSIGNED_LONG_LONG_INT@ # undef uint64_t typedef unsigned long long int gl_uint64_t; # define uint64_t gl_uint64_t # define GL_UINT64_T # endif #endif /* Avoid collision with Solaris 2.5.1 <pthread.h> etc. */ #define _UINT8_T #define _UINT32_T #define _UINT64_T /* 7.18.1.2. Minimum-width integer types */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types are the same as the corresponding N_t types. */ #undef int_least8_t #undef uint_least8_t #undef int_least16_t #undef uint_least16_t #undef int_least32_t #undef uint_least32_t #undef int_least64_t #undef uint_least64_t #define int_least8_t int8_t #define uint_least8_t uint8_t #define int_least16_t int16_t #define uint_least16_t uint16_t #define int_least32_t int32_t #define uint_least32_t uint32_t #ifdef GL_INT64_T # define int_least64_t int64_t #endif #ifdef GL_UINT64_T # define uint_least64_t uint64_t #endif /* 7.18.1.3. Fastest minimum-width integer types */ /* Note: Other <stdint.h> substitutes may define these types differently. It is not recommended to use these types in public header files. */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types are taken from the same list of types. Assume that 'long int' is fast enough for all narrower integers. */ #undef int_fast8_t #undef uint_fast8_t #undef int_fast16_t #undef uint_fast16_t #undef int_fast32_t #undef uint_fast32_t #undef int_fast64_t #undef uint_fast64_t typedef long int gl_int_fast8_t; typedef unsigned long int gl_uint_fast8_t; typedef long int gl_int_fast16_t; typedef unsigned long int gl_uint_fast16_t; typedef long int gl_int_fast32_t; typedef unsigned long int gl_uint_fast32_t; #define int_fast8_t gl_int_fast8_t #define uint_fast8_t gl_uint_fast8_t #define int_fast16_t gl_int_fast16_t #define uint_fast16_t gl_uint_fast16_t #define int_fast32_t gl_int_fast32_t #define uint_fast32_t gl_uint_fast32_t #ifdef GL_INT64_T # define int_fast64_t int64_t #endif #ifdef GL_UINT64_T # define uint_fast64_t uint64_t #endif /* 7.18.1.4. Integer types capable of holding object pointers */ #undef intptr_t #undef uintptr_t typedef long int gl_intptr_t; typedef unsigned long int gl_uintptr_t; #define intptr_t gl_intptr_t #define uintptr_t gl_uintptr_t /* 7.18.1.5. Greatest-width integer types */ /* Note: These types are compiler dependent. It may be unwise to use them in public header files. */ #undef intmax_t #if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 typedef long long int gl_intmax_t; # define intmax_t gl_intmax_t #elif defined GL_INT64_T # define intmax_t int64_t #else typedef long int gl_intmax_t; # define intmax_t gl_intmax_t #endif #undef uintmax_t #if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 typedef unsigned long long int gl_uintmax_t; # define uintmax_t gl_uintmax_t #elif defined GL_UINT64_T # define uintmax_t uint64_t #else typedef unsigned long int gl_uintmax_t; # define uintmax_t gl_uintmax_t #endif /* Verify that intmax_t and uintmax_t have the same size. Too much code breaks if this is not the case. If this check fails, the reason is likely to be found in the autoconf macros. */ typedef int _verify_intmax_size[sizeof (intmax_t) == sizeof (uintmax_t) ? 1 : -1]; #define GNULIB_defined_stdint_types 1 #endif /* !GNULIB_defined_stdint_types */ /* 7.18.2. Limits of specified-width integer types */ #if ! defined __cplusplus || defined __STDC_LIMIT_MACROS /* 7.18.2.1. Limits of exact-width integer types */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. */ #undef INT8_MIN #undef INT8_MAX #undef UINT8_MAX #define INT8_MIN (~ INT8_MAX) #define INT8_MAX 127 #define UINT8_MAX 255 #undef INT16_MIN #undef INT16_MAX #undef UINT16_MAX #define INT16_MIN (~ INT16_MAX) #define INT16_MAX 32767 #define UINT16_MAX 65535 #undef INT32_MIN #undef INT32_MAX #undef UINT32_MAX #define INT32_MIN (~ INT32_MAX) #define INT32_MAX 2147483647 #define UINT32_MAX 4294967295U #if defined GL_INT64_T && ! defined INT64_MAX /* Prefer (- INTMAX_C (1) << 63) over (~ INT64_MAX) because SunPRO C 5.0 evaluates the latter incorrectly in preprocessor expressions. */ # define INT64_MIN (- INTMAX_C (1) << 63) # define INT64_MAX INTMAX_C (9223372036854775807) #endif #if defined GL_UINT64_T && ! defined UINT64_MAX # define UINT64_MAX UINTMAX_C (18446744073709551615) #endif /* 7.18.2.2. Limits of minimum-width integer types */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. Therefore the leastN_t types are the same as the corresponding N_t types. */ #undef INT_LEAST8_MIN #undef INT_LEAST8_MAX #undef UINT_LEAST8_MAX #define INT_LEAST8_MIN INT8_MIN #define INT_LEAST8_MAX INT8_MAX #define UINT_LEAST8_MAX UINT8_MAX #undef INT_LEAST16_MIN #undef INT_LEAST16_MAX #undef UINT_LEAST16_MAX #define INT_LEAST16_MIN INT16_MIN #define INT_LEAST16_MAX INT16_MAX #define UINT_LEAST16_MAX UINT16_MAX #undef INT_LEAST32_MIN #undef INT_LEAST32_MAX #undef UINT_LEAST32_MAX #define INT_LEAST32_MIN INT32_MIN #define INT_LEAST32_MAX INT32_MAX #define UINT_LEAST32_MAX UINT32_MAX #undef INT_LEAST64_MIN #undef INT_LEAST64_MAX #ifdef GL_INT64_T # define INT_LEAST64_MIN INT64_MIN # define INT_LEAST64_MAX INT64_MAX #endif #undef UINT_LEAST64_MAX #ifdef GL_UINT64_T # define UINT_LEAST64_MAX UINT64_MAX #endif /* 7.18.2.3. Limits of fastest minimum-width integer types */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits. Therefore the fastN_t types are taken from the same list of types. */ #undef INT_FAST8_MIN #undef INT_FAST8_MAX #undef UINT_FAST8_MAX #define INT_FAST8_MIN LONG_MIN #define INT_FAST8_MAX LONG_MAX #define UINT_FAST8_MAX ULONG_MAX #undef INT_FAST16_MIN #undef INT_FAST16_MAX #undef UINT_FAST16_MAX #define INT_FAST16_MIN LONG_MIN #define INT_FAST16_MAX LONG_MAX #define UINT_FAST16_MAX ULONG_MAX #undef INT_FAST32_MIN #undef INT_FAST32_MAX #undef UINT_FAST32_MAX #define INT_FAST32_MIN LONG_MIN #define INT_FAST32_MAX LONG_MAX #define UINT_FAST32_MAX ULONG_MAX #undef INT_FAST64_MIN #undef INT_FAST64_MAX #ifdef GL_INT64_T # define INT_FAST64_MIN INT64_MIN # define INT_FAST64_MAX INT64_MAX #endif #undef UINT_FAST64_MAX #ifdef GL_UINT64_T # define UINT_FAST64_MAX UINT64_MAX #endif /* 7.18.2.4. Limits of integer types capable of holding object pointers */ #undef INTPTR_MIN #undef INTPTR_MAX #undef UINTPTR_MAX #define INTPTR_MIN LONG_MIN #define INTPTR_MAX LONG_MAX #define UINTPTR_MAX ULONG_MAX /* 7.18.2.5. Limits of greatest-width integer types */ #undef INTMAX_MIN #undef INTMAX_MAX #ifdef INT64_MAX # define INTMAX_MIN INT64_MIN # define INTMAX_MAX INT64_MAX #else # define INTMAX_MIN INT32_MIN # define INTMAX_MAX INT32_MAX #endif #undef UINTMAX_MAX #ifdef UINT64_MAX # define UINTMAX_MAX UINT64_MAX #else # define UINTMAX_MAX UINT32_MAX #endif /* 7.18.3. Limits of other integer types */ /* ptrdiff_t limits */ #undef PTRDIFF_MIN #undef PTRDIFF_MAX #if @APPLE_UNIVERSAL_BUILD@ # ifdef _LP64 # define PTRDIFF_MIN _STDINT_MIN (1, 64, 0l) # define PTRDIFF_MAX _STDINT_MAX (1, 64, 0l) # else # define PTRDIFF_MIN _STDINT_MIN (1, 32, 0) # define PTRDIFF_MAX _STDINT_MAX (1, 32, 0) # endif #else # define PTRDIFF_MIN \ _STDINT_MIN (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@) # define PTRDIFF_MAX \ _STDINT_MAX (1, @BITSIZEOF_PTRDIFF_T@, 0@PTRDIFF_T_SUFFIX@) #endif /* sig_atomic_t limits */ #undef SIG_ATOMIC_MIN #undef SIG_ATOMIC_MAX #define SIG_ATOMIC_MIN \ _STDINT_MIN (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \ 0@SIG_ATOMIC_T_SUFFIX@) #define SIG_ATOMIC_MAX \ _STDINT_MAX (@HAVE_SIGNED_SIG_ATOMIC_T@, @BITSIZEOF_SIG_ATOMIC_T@, \ 0@SIG_ATOMIC_T_SUFFIX@) /* size_t limit */ #undef SIZE_MAX #if @APPLE_UNIVERSAL_BUILD@ # ifdef _LP64 # define SIZE_MAX _STDINT_MAX (0, 64, 0ul) # else # define SIZE_MAX _STDINT_MAX (0, 32, 0ul) # endif #else # define SIZE_MAX _STDINT_MAX (0, @BITSIZEOF_SIZE_T@, 0@SIZE_T_SUFFIX@) #endif /* wchar_t limits */ /* Get WCHAR_MIN, WCHAR_MAX. This include is not on the top, above, because on OSF/1 4.0 we have a sequence of nested includes <wchar.h> -> <stdio.h> -> <getopt.h> -> <stdlib.h>, and the latter includes <stdint.h> and assumes its types are already defined. */ #if @HAVE_WCHAR_H@ && ! (defined WCHAR_MIN && defined WCHAR_MAX) /* BSD/OS 4.0.1 has a bug: <stddef.h>, <stdio.h> and <time.h> must be included before <wchar.h>. */ # include <stddef.h> # include <stdio.h> # include <time.h> # define _GL_JUST_INCLUDE_SYSTEM_WCHAR_H # include <wchar.h> # undef _GL_JUST_INCLUDE_SYSTEM_WCHAR_H #endif #undef WCHAR_MIN #undef WCHAR_MAX #define WCHAR_MIN \ _STDINT_MIN (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@) #define WCHAR_MAX \ _STDINT_MAX (@HAVE_SIGNED_WCHAR_T@, @BITSIZEOF_WCHAR_T@, 0@WCHAR_T_SUFFIX@) /* wint_t limits */ #undef WINT_MIN #undef WINT_MAX #define WINT_MIN \ _STDINT_MIN (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@) #define WINT_MAX \ _STDINT_MAX (@HAVE_SIGNED_WINT_T@, @BITSIZEOF_WINT_T@, 0@WINT_T_SUFFIX@) #endif /* !defined __cplusplus || defined __STDC_LIMIT_MACROS */ /* 7.18.4. Macros for integer constants */ #if ! defined __cplusplus || defined __STDC_CONSTANT_MACROS /* 7.18.4.1. Macros for minimum-width integer constants */ /* According to ISO C 99 Technical Corrigendum 1 */ /* Here we assume a standard architecture where the hardware integer types have 8, 16, 32, optionally 64 bits, and int is 32 bits. */ #undef INT8_C #undef UINT8_C #define INT8_C(x) x #define UINT8_C(x) x #undef INT16_C #undef UINT16_C #define INT16_C(x) x #define UINT16_C(x) x #undef INT32_C #undef UINT32_C #define INT32_C(x) x #define UINT32_C(x) x ## U #undef INT64_C #undef UINT64_C #if LONG_MAX >> 31 >> 31 == 1 # define INT64_C(x) x##L #elif defined _MSC_VER # define INT64_C(x) x##i64 #elif @HAVE_LONG_LONG_INT@ # define INT64_C(x) x##LL #endif #if ULONG_MAX >> 31 >> 31 >> 1 == 1 # define UINT64_C(x) x##UL #elif defined _MSC_VER # define UINT64_C(x) x##ui64 #elif @HAVE_UNSIGNED_LONG_LONG_INT@ # define UINT64_C(x) x##ULL #endif /* 7.18.4.2. Macros for greatest-width integer constants */ #undef INTMAX_C #if @HAVE_LONG_LONG_INT@ && LONG_MAX >> 30 == 1 # define INTMAX_C(x) x##LL #elif defined GL_INT64_T # define INTMAX_C(x) INT64_C(x) #else # define INTMAX_C(x) x##L #endif #undef UINTMAX_C #if @HAVE_UNSIGNED_LONG_LONG_INT@ && ULONG_MAX >> 31 == 1 # define UINTMAX_C(x) x##ULL #elif defined GL_UINT64_T # define UINTMAX_C(x) UINT64_C(x) #else # define UINTMAX_C(x) x##UL #endif #endif /* !defined __cplusplus || defined __STDC_CONSTANT_MACROS */ #endif /* _@GUARD_PREFIX@_STDINT_H */ #endif /* !defined _@GUARD_PREFIX@_STDINT_H && !defined _GL_JUST_INCLUDE_SYSTEM_STDINT_H */
{ "content_hash": "febed8511df95c66550b135a1c9d0649", "timestamp": "", "source": "github", "line_count": 594, "max_line_length": 91, "avg_line_length": 29.63131313131313, "alnum_prop": 0.7005851940230668, "repo_name": "WhiteBearSolutions/WBSAirback", "id": "5ef43adbae70c1f6e56536a28072032640e6bc4c", "size": "17601", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/wbsairback-parted/wbsairback-parted-3.0/lib/stdint.in.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4780982" } ], "symlink_target": "" }
package org.apache.uima.rdf; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.clerezza.rdf.core.MGraph; import org.apache.clerezza.rdf.core.UriRef; import org.apache.clerezza.rdf.core.impl.SimpleMGraph; import org.apache.clerezza.rdf.core.serializedform.Serializer; import org.apache.clerezza.rdf.utils.GraphNode; import org.apache.clerezza.uima.utils.UIMAUtils; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.cas.CASException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; /** * CASConsumer that writes CAS contents to an RDF-like format */ public class RDFCASConsumer extends JCasAnnotator_ImplBase { private String view; private String file; private String format; @Override public void initialize(UimaContext context) { view = String.valueOf(context.getConfigParameterValue("view")); file = String.valueOf(context.getConfigParameterValue("file")); format = String.valueOf(context.getConfigParameterValue("format")); } @Override public void process(JCas jCas) throws AnalysisEngineProcessException { try { JCas selectedView = getCASToSerialize(jCas); GraphNode node = createNode(selectedView); Type type = selectedView.getCasType(Annotation.type); List<FeatureStructure> annotations = getAnnotations(selectedView, type); UIMAUtils.enhanceNode(node, annotations); writeFile(node); } catch (Exception e) { throw new AnalysisEngineProcessException(e); } } private JCas getCASToSerialize(JCas jCas) throws CASException { JCas selectedView; if (view != null && view.length() > 0 && !view.equals("current")) { selectedView = jCas.getView(view); } else selectedView = jCas; return selectedView; } private GraphNode createNode(JCas selectedView) { MGraph mGraph = new SimpleMGraph(); return new GraphNode(new UriRef(selectedView.toString()), mGraph); } private List<FeatureStructure> getAnnotations(JCas selectedView, Type type) { AnnotationIndex<Annotation> annotationIndex = selectedView.getAnnotationIndex(type); List<FeatureStructure> annotations = new ArrayList<FeatureStructure>(annotationIndex.size()); for (Annotation a : annotationIndex) { annotations.add(a); } return annotations; } private void writeFile(GraphNode node) throws IOException { OutputStream outputStream = null; try { URI uri = UriUtils.create(file); File f = new File(uri); if (!f.exists()) { f.createNewFile(); } outputStream = new FileOutputStream(f); Serializer serializer = Serializer.getInstance(); serializer.serialize(outputStream, node.getGraph(), format); outputStream.flush(); outputStream.close(); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e1) { // do nothing } } } } }
{ "content_hash": "8ec3429fd9d02b4fee2c5f28036a1471", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 97, "avg_line_length": 29.391304347826086, "alnum_prop": 0.7189349112426036, "repo_name": "apache/uima-sandbox", "id": "1543e6317217c75074b66329eb29485d91a6601d", "size": "4200", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "RDFCASConsumer/src/main/java/org/apache/uima/rdf/RDFCASConsumer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4249" }, { "name": "Groovy", "bytes": "24927" }, { "name": "HTML", "bytes": "21923" }, { "name": "Java", "bytes": "1594180" }, { "name": "Shell", "bytes": "3756" }, { "name": "XSLT", "bytes": "24506" } ], "symlink_target": "" }
'use strict' // import material components import { Container, View, Checkbox, Button, Text } from 'material' import Layout from 'material/src/layout' import css from 'material/src/module/css' import iconStar from '../icon/star.svg' import iconAccessibility from '../icon/accessibility.svg' import iconPhone from '../icon/phone.svg' import iconHappy from '../icon/happy.svg' import iconLink from '../icon/link.svg' /** * [initTest description] * @return {[type]} [description] */ export default function (body) { var layout = new Layout([View, 'button', {}, [Container, 'top', {}, [Text, 'title', { type: 'title', text: 'Buttons' }], [Text, 'title', { text: 'Buttons communicate the action that will occur when the user touches them.' }] ], [Container, 'hero', {}, [Button, 'first', { text: 'Flat', color: 'primary' }], [Button, 'second', { text: 'Raised', type: 'raised', color: 'primary' }], [Button, 'third', { icon: iconStar, type: 'action', color: 'secondary' }], [Button, 'fourth', { icon: iconStar, text: 'text' }], [Button, 'fifth', { icon: iconStar, type: 'floating', color: 'secondary' }] ], [Container, 'containerbutton', {}, [Container, 'button-default', {}, [Text, 'standard-button', { text: 'Standard Button', type: 'subheading2' }], [Container, 'buttons-container', {}, [Button, 'default', { text: 'default' }], [Button, 'default-icontext', { icon: iconHappy, text: 'icon text' }], [Button, 'default-compact', { text: 'Compact', style: 'compact' }], [Button, 'default-dense', { text: 'Dense', style: 'dense' }], [Button, 'default-densecompact', { text: 'Compact dense', style: 'compact dense' }], [Button, 'default-link', { text: 'Link', tag: 'a' }] ], [Container, 'buttons-container', {}, [Button, 'default', { text: 'default', color: 'primary' }], [Button, 'default-icontext', { icon: iconHappy, text: 'icon text', color: 'primary' }], [Button, 'default-compact', { text: 'Compact', style: 'compact', color: 'primary' }], [Button, 'default-dense', { text: 'Dense', style: 'dense', color: 'primary' }], [Button, 'default-densecompact', { text: 'Compact dense', style: 'compact dense', color: 'primary' }], [Button, 'default-link', { text: 'Link', color: 'primary', tag: 'a' }] ], [Container, 'buttons-container', {}, [Button, 'default', { text: 'default', color: 'secondary' }], [Button, 'default-icontext', { icon: iconHappy, text: 'icon text', color: 'secondary' }], [Button, 'default-compact', { text: 'Compact', style: 'compact', color: 'secondary' }], [Button, 'default-dense', { text: 'Dense', style: 'dense', color: 'secondary' }], [Button, 'default-densecompact', { text: 'Compact dense', style: 'compact dense', color: 'secondary' }], [Button, 'default-link', { text: 'Link', color: 'secondary', tag: 'a' }] ], [Text, 'raised-button', { text: 'Raised Button', type: 'subheading2' }], [Container, 'buttons-raised', {}, [Button, 'raised', { text: 'raised', type: 'raised' }], [Button, 'default-icontext', { icon: iconHappy, type: 'raised', text: 'icon text' }], [Button, 'raised-compact', { text: 'Compact', type: 'raised', style: 'compact' }], [Button, 'raised-dense', { text: 'Dense', type: 'raised', style: 'dense' }], [Button, 'raised-densecompact', { text: 'Compact dense', type: 'raised', style: 'compact dense' }], [Button, 'raised-link', { text: 'Link', type: 'raised' }], [Button, 'raised-link', { icon: iconStar, type: 'raised' }] ], [Container, 'buttons-raised-primary', {}, [Button, 'raised', { text: 'raised primary', type: 'raised', color: 'primary' }], [Button, 'default-icontext', { icon: iconHappy, type: 'raised', text: 'icon text', color: 'primary' }], [Button, 'raised-compact', { text: 'Compact', type: 'raised', style: 'compact', color: 'primary' }], [Button, 'raised-dense', { text: 'Dense', style: 'dense', type: 'raised', color: 'primary' }], [Button, 'raised-densecompact', { text: 'Compact dense', style: 'dense compact', type: 'raised', color: 'primary' }], [Button, 'raised-link', { text: 'Link', type: 'raised', color: 'primary' }], [Button, 'raised-link', { icon: iconStar, type: 'raised', color: 'primary' }] ], [Container, 'buttons-raised-secondary', {}, [Button, 'raised', { text: 'raised secondary', type: 'raised', color: 'secondary' }], [Button, 'default-icontext', { icon: iconHappy, type: 'raised', text: 'icon text', color: 'secondary' }], [Button, 'raised-compact', { text: 'Compact', type: 'raised', style: 'compact', color: 'secondary' }], [Button, 'raised-dense', { text: 'Dense', type: 'raised', style: 'dense', color: 'secondary' }], [Button, 'raised-densecompact', { text: 'Compact dense', type: 'raised', style: 'compact dense', color: 'secondary' }], [Button, 'raised-link', { text: 'Link', type: 'raised', color: 'secondary' }], [Button, 'raised-link', { icon: iconStar, type: 'raised', color: 'secondary' }] ], [Text, 'action-button', { text: 'Action Button', type: 'subheading2' }], [Container, 'buttons-action', {}, [Button, 'action', { icon: iconStar, type: 'action' }], [Button, 'action-compact', { icon: iconHappy, type: 'action', style: 'compact' }], [Button, 'action-dense', { icon: iconPhone, type: 'action', style: 'dense' }], [Button, 'action-densecompact', { icon: iconAccessibility, type: 'action', style: 'compact dense' }], [Button, 'action-link', { icon: iconLink, type: 'action' }] ], [Container, 'buttons-action', {}, [Button, 'action', { icon: iconStar, type: 'action', color: 'primary' }], [Button, 'action-compact', { icon: iconHappy, type: 'action', style: 'compact', color: 'primary' }], [Button, 'action-dense', { icon: iconPhone, type: 'action', style: 'dense', color: 'primary' }], [Button, 'action-densecompact', { icon: iconAccessibility, type: 'action', style: 'compact dense', color: 'primary' }], [Button, 'action-link', { icon: iconLink, type: 'action', color: 'primary' }] ], [Container, 'buttons-action-secondary', {}, [Button, 'action', { icon: iconStar, type: 'action', color: 'secondary' }], [Button, 'action-compact', { icon: iconHappy, type: 'action', style: 'compact', color: 'secondary' }], [Button, 'action-dense', { icon: iconPhone, type: 'action', style: 'dense', color: 'secondary' }], [Button, 'action-densecompact', { icon: iconAccessibility, type: 'action', style: 'compact dense', color: 'secondary' }], [Button, 'action-link', { icon: iconLink, type: 'action', color: 'secondary' }] ], [Text, 'floating-button', { text: 'Floating Button', type: 'subheading2' }], [Container, 'buttons-floating', {}, [Button, 'floating', { icon: iconStar, type: 'floating' }], [Button, 'floating-compact', { icon: iconHappy, type: 'floating', style: 'compact' }], [Button, 'floating-dense', { icon: iconPhone, type: 'floating', style: 'dense' }], [Button, 'floating-densecompact', { icon: iconAccessibility, type: 'floating', style: 'compact dense' }], [Button, 'floating-link', { icon: iconLink, type: 'floating', tag: 'a' }] ], [Container, 'buttons-floating', {}, [Button, 'floating', { icon: iconStar, type: 'floating', color: 'primary' }], [Button, 'floating-compact', { icon: iconHappy, type: 'floating', style: 'compact', color: 'primary' }], [Button, 'floating-dense', { icon: iconPhone, type: 'floating', style: 'dense', color: 'primary' }], [Button, 'floating-densecompact', { icon: iconAccessibility, type: 'floating', style: 'compact dense', color: 'primary' }], [Button, 'floating-link', { icon: iconLink, type: 'floating', color: 'primary' }] ], [Container, 'buttons-floating-secondary', {}, [Button, 'floating', { icon: iconStar, text: 'floating secondary', type: 'floating', color: 'secondary' }], [Button, 'floating-compact', { icon: iconHappy, text: 'Compact', type: 'floating', style: 'compact', color: 'secondary' }], [Button, 'floating-dense', { icon: iconPhone, text: 'Dense', type: 'floating', style: 'dense', color: 'secondary' }], [Button, 'floating-densecompact', { icon: iconAccessibility, type: 'floating', style: 'compact dense', color: 'secondary' }], [Button, 'floating-link', { icon: iconLink, type: 'floating', color: 'secondary' }] ] ] ] ], body) var component = layout.get() layout.get('default').on('click', (e) => { console.log('click', e, layout.get('default')) }) }
{ "content_hash": "95861269e04c59f7f6771292c340696d", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 135, "avg_line_length": 62.56164383561644, "alnum_prop": 0.5768557039632144, "repo_name": "codepolitan/material-demo", "id": "fd7b60f50d8e563d910cf6f36afc8028b40df952", "size": "9134", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/view/button.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14577" }, { "name": "HTML", "bytes": "2435" }, { "name": "JavaScript", "bytes": "94091" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <!-- Copyright 2021 Google LLC 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. --> <ServiceCallout continueOnError="false" enabled="true" name="Correct-Billing-Information-Southbound-API-Call"> <DisplayName>Correct Billing Information Southbound API Call</DisplayName> <Request> <Set> <Headers> <Header name="Accept">application/json</Header> </Headers> <Verb>POST</Verb> </Set> </Request> <Response>southboundAPIResponse</Response> <LocalTargetConnection> <Path>/v1/telco/mocks/billing-management/profiles/{google.dialogflow.session.parameters.id}/adjustments</Path> </LocalTargetConnection> </ServiceCallout>
{ "content_hash": "e4242242362449b5eb2f201713993050", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 118, "avg_line_length": 39.25, "alnum_prop": 0.714171974522293, "repo_name": "apigee/conversational-ai-reference-implementations", "id": "29e6de8441a9294308f79e20beafe2663277dd68", "size": "1256", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "webhook-adapters/shared-flows/telecommunications/billing-management/sharedflowbundle/policies/Correct-Billing-Information-Southbound-API-Call.xml", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2582d9925e87dabe519bf38aeaba6390", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "f4853e0bd0658b824a80ee2047218cd8f1dc7522", "size": "195", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Koeleria/Koeleria macrantha/ Syn. Koeleria cristata chakassica/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** @module ember-flexberry */ import Ember from 'ember'; import FlexberryBaseComponent from './flexberry-base-component'; /** Component for expand / collapse content. Sample usage: ```handlebars {{#flexberry-toggler expandedCaption='Expanded caption' collapsedCaption='Collapsed caption' }} Your content. {{/flexberry-toggler}} ``` @class FlexberryToggler @extends FlexberryBaseComponent */ export default FlexberryBaseComponent.extend({ /** Current visibility state. @property _expanded @type Boolean @default false @private */ _expanded: false, /** Common caption in the component header. Used when appropriate sate-related caption ({{#crossLink "FlexberryToggler/expandedCaption:property"}}{{/crossLink}} or {{#crossLink "FlexberryToggler/collapsedCaption:property"}}{{/crossLink}}) is not specified. @property caption @type String @default '' */ caption: '', /** Caption in the component header for expanded state. If it is not specified, {{#crossLink "FlexberryToggler/caption:property"}}{{/crossLink}} will be used. @property expandedCaption @type String @default null */ expandedCaption: null, /** Caption in the component header for collapsed state. If it is not specified, {{#crossLink "FlexberryToggler/caption:property"}}{{/crossLink}} will be used. @property collapsedCaption @type String @default null */ collapsedCaption: null, /** Current caption. @property _caption @type String @readOnly */ currentCaption: Ember.computed('caption', 'expandedCaption', 'collapsedCaption', '_expanded', function() { let defaultCaption = this.get('caption'); let caption = this.get('_expanded') ? (this.get('expandedCaption') || defaultCaption) : (this.get('collapsedCaption') || defaultCaption); return caption; }), /** Array CSS class names. [More info.](http://emberjs.com/api/classes/Ember.Component.html#property_classNames) @property classNames @type Array @readOnly */ classNames: ['flexberry-toggler', 'ui', 'accordion', 'fluid'], /** Handles the event, when component has been insterted. Attaches event handlers for expanding / collapsing content. */ didInsertElement() { let $accordeonDomElement = this.$(); // Attach semantic-ui open/close callbacks. $accordeonDomElement.accordion({ onOpen: () => { this.set('_expanded', true); }, onClose: () => { this.set('_expanded', false); } }); // Initialize right state (call semantic-ui accordion open/close method). $accordeonDomElement.accordion(this.get('_expanded') ? 'open' : 'close'); } });
{ "content_hash": "60623b508e821709c4aed0d60c702837", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 141, "avg_line_length": 26.970588235294116, "alnum_prop": 0.6641221374045801, "repo_name": "akosinsky/test_ember", "id": "7be8007c34e3f73f721fea890f730e14caa3d687", "size": "2751", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/components/flexberry-toggler.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6232" }, { "name": "HTML", "bytes": "77003" }, { "name": "JavaScript", "bytes": "514296" }, { "name": "Shell", "bytes": "1609" }, { "name": "TypeScript", "bytes": "25877" } ], "symlink_target": "" }
using namespace DirectX; // we will be using the directxmath library D3dx12jo::D3dx12jo() { hwnd_jo = NULL; FullScreen_jo = false; Running = true; } bool D3dx12jo::InitD3D(HWND hwnd_tmp) { HRESULT hr; // -- Create the Device -- // IDXGIFactory4* dxgiFactory; hwnd_jo = hwnd_tmp; hr = CreateDXGIFactory1(IID_PPV_ARGS(&dxgiFactory)); if (FAILED(hr)) { return false; } IDXGIAdapter1* adapter; // adapters are the graphics card (this includes the embedded graphics on the motherboard) int adapterIndex = 0; // we'll start looking for directx 12 compatible graphics devices starting at index 0 bool adapterFound = false; // set this to true when a good one was found // find first hardware gpu that supports d3d 12 //while (dxgiFactory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND) while (adapterIndex<3) { DXGI_ADAPTER_DESC1 desc; if (dxgiFactory->EnumAdapters1(adapterIndex, &adapter) == DXGI_ERROR_NOT_FOUND) { break; } adapter->GetDesc1(&desc); if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { // we dont want a software device adapterIndex++; continue; } if (desc.VendorId == 32902) { // we dont want INTEL device (id=0x8086) look up vendor id in device manager adapterIndex++; continue; } if (desc.VendorId == 4098) { // we dont want AMD device (id=0x1002) look up vendor id in device manager adapterIndex++; continue; } // we want a device that is compatible with direct3d 12 (feature level 11 or higher) hr = D3D12CreateDevice(adapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr); if (SUCCEEDED(hr)) { adapterFound = true; break; } adapterIndex++; } if (!adapterFound) { return false; } // Create the device hr = D3D12CreateDevice( adapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device) ); if (FAILED(hr)) { return false; } // -- Create a direct command queue -- // D3D12_COMMAND_QUEUE_DESC cqDesc = {}; cqDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; cqDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; // direct means the gpu can directly execute this command queue hr = device->CreateCommandQueue(&cqDesc, IID_PPV_ARGS(&commandQueue)); // create the command queue if (FAILED(hr)) { return false; } // -- Create the Swap Chain (double/tripple buffering) -- // DXGI_MODE_DESC backBufferDesc = {}; // this is to describe our display mode backBufferDesc.Width = 300; //Width; // buffer width backBufferDesc.Height = 240; //Height; // buffer height backBufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // format of the buffer (rgba 32 bits, 8 bits for each chanel) // describe our multi-sampling. We are not multi-sampling, so we set the count to 1 (we need at least one sample of course) DXGI_SAMPLE_DESC sampleDesc = {}; sampleDesc.Count = 1; // multisample count (no multisampling, so we just put 1, since we still need 1 sample) // Describe and create the swap chain. DXGI_SWAP_CHAIN_DESC swapChainDesc = {}; swapChainDesc.BufferCount = FRAME_BUFFER_COUNT_X; // number of buffers we have swapChainDesc.BufferDesc = backBufferDesc; // our back buffer description swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // this says the pipeline will render to this swap chain swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // dxgi will discard the buffer (data) after we call present swapChainDesc.OutputWindow = hwnd_jo; // handle to our window swapChainDesc.SampleDesc = sampleDesc; // our multi-sampling description swapChainDesc.Windowed = !FullScreen_jo; // set to true, then if in fullscreen must call SetFullScreenState with true for full screen to get uncapped fps IDXGISwapChain* tempSwapChain; dxgiFactory->CreateSwapChain( commandQueue, // the queue will be flushed once the swap chain is created &swapChainDesc, // give it the swap chain description we created above &tempSwapChain // store the created swap chain in a temp IDXGISwapChain interface ); swapChain = static_cast<IDXGISwapChain3*>(tempSwapChain); frameIndex = swapChain->GetCurrentBackBufferIndex(); // -- Create the Back Buffers (render target views) Descriptor Heap -- // // describe an rtv descriptor heap and create D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = FRAME_BUFFER_COUNT_X; // number of descriptors for this heap. rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; // this heap is a render target view heap // This heap will not be directly referenced by the shaders (not shader visible), as this will store the output from the pipeline // otherwise we would set the heap's flag to D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; hr = device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&rtvDescriptorHeap)); if (FAILED(hr)) { return false; } // get the size of a descriptor in this heap (this is a rtv heap, so only rtv descriptors should be stored in it. // descriptor sizes may vary from device to device, which is why there is no set size and we must ask the // device to give us the size. we will use this size to increment a descriptor handle offset rtvDescriptorSize = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); // get a handle to the first descriptor in the descriptor heap. a handle is basically a pointer, // but we cannot literally use it like a c++ pointer. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart()); // Create a RTV for each buffer (double buffering is two buffers, tripple buffering is 3). for (int i = 0; i < FRAME_BUFFER_COUNT_X; i++) { // first we get the n'th buffer in the swap chain and store it in the n'th // position of our ID3D12Resource array hr = swapChain->GetBuffer(i, IID_PPV_ARGS(&renderTargets[i])); if (FAILED(hr)) { return false; } // the we "create" a render target view which binds the swap chain buffer (ID3D12Resource[n]) to the rtv handle device->CreateRenderTargetView(renderTargets[i], nullptr, rtvHandle); // we increment the rtv handle by the rtv descriptor size we got above rtvHandle.Offset(1, rtvDescriptorSize); } // -- Create the Command Allocators -- // for (int i = 0; i < FRAME_BUFFER_COUNT_X; i++) { hr = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&commandAllocator[i])); if (FAILED(hr)) { return false; } } // -- Create a Command List -- // // create the command list with the first allocator hr = device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator[0], NULL, IID_PPV_ARGS(&commandList)); if (FAILED(hr)) { return false; } // command lists are created in the recording state. our main loop will set it up for recording again so close it now commandList->Close(); // -- Create a Fence & Fence Event -- // // create the fences for (int i = 0; i < FRAME_BUFFER_COUNT_X; i++) { hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence[i])); if (FAILED(hr)) { return false; } fenceValue[i] = 0; // set the initial fence value to 0 } // create a handle to a fence event fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (fenceEvent == nullptr) { return false; } return true; } void D3dx12jo::UpdatePipeline() { HRESULT hr; // We have to wait for the gpu to finish with the command allocator before we reset it WaitForPreviousFrame(); // we can only reset an allocator once the gpu is done with it // resetting an allocator frees the memory that the command list was stored in hr = commandAllocator[frameIndex]->Reset(); if (FAILED(hr)) { Running = false; } // reset the command list. by resetting the command list we are putting it into // a recording state so we can start recording commands into the command allocator. // the command allocator that we reference here may have multiple command lists // associated with it, but only one can be recording at any time. Make sure // that any other command lists associated to this command allocator are in // the closed state (not recording). // Here you will pass an initial pipeline state object as the second parameter, // but in this tutorial we are only clearing the rtv, and do not actually need // anything but an initial default pipeline, which is what we get by setting // the second parameter to NULL hr = commandList->Reset(commandAllocator[frameIndex], NULL); if (FAILED(hr)) { Running = false; } // here we start recording commands into the commandList (which all the commands will be stored in the commandAllocator) // transition the "frameIndex" render target from the present state to the render target state so the command list draws to it starting from here commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(renderTargets[frameIndex], D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); // here we again get the handle to our current render target view so we can set it as the render target in the output merger stage of the pipeline CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(rtvDescriptorHeap->GetCPUDescriptorHandleForHeapStart(), frameIndex, rtvDescriptorSize); // set the render target for the output merger stage (the output of the pipeline) commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr); // Clear the render target by using the ClearRenderTargetView command const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f }; //DARK BLUE commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr); // transition the "frameIndex" render target from the render target state to the present state. If the debug layer is enabled, you will receive a // warning if present is called on the render target when it's not in the present state commandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(renderTargets[frameIndex], D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)); hr = commandList->Close(); if (FAILED(hr)) { Running = false; } } void D3dx12jo::Render() { HRESULT hr; UpdatePipeline(); // update the pipeline by sending commands to the commandqueue // create an array of command lists (only one command list here) ID3D12CommandList* ppCommandLists[] = { commandList }; // execute the array of command lists commandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists); // this command goes in at the end of our command queue. we will know when our command queue // has finished because the fence value will be set to "fenceValue" from the GPU since the command // queue is being executed on the GPU hr = commandQueue->Signal(fence[frameIndex], fenceValue[frameIndex]); if (FAILED(hr)) { Running = false; } // present the current backbuffer hr = swapChain->Present(0, 0); if (FAILED(hr)) { Running = false; } } void D3dx12jo::Cleanup() { // wait for the gpu to finish all frames for (int i = 0; i < FRAME_BUFFER_COUNT_X; ++i) { frameIndex = i; WaitForPreviousFrame(); } // get swapchain out of full screen before exiting BOOL fs = false; if (swapChain->GetFullscreenState(&fs, NULL)) swapChain->SetFullscreenState(false, NULL); SAFE_RELEASE(device); SAFE_RELEASE(swapChain); SAFE_RELEASE(commandQueue); SAFE_RELEASE(rtvDescriptorHeap); SAFE_RELEASE(commandList); for (int i = 0; i < FRAME_BUFFER_COUNT_X; ++i) { SAFE_RELEASE(renderTargets[i]); SAFE_RELEASE(commandAllocator[i]); SAFE_RELEASE(fence[i]); }; } void D3dx12jo::WaitForPreviousFrame() { HRESULT hr; // if the current fence value is still less than "fenceValue", then we know the GPU has not finished executing // the command queue since it has not reached the "commandQueue->Signal(fence, fenceValue)" command if (fence[frameIndex]->GetCompletedValue() < fenceValue[frameIndex]) { // we have the fence create an event which is signaled once the fence's current value is "fenceValue" hr = fence[frameIndex]->SetEventOnCompletion(fenceValue[frameIndex], fenceEvent); if (FAILED(hr)) { Running = false; } // We will wait until the fence has triggered the event that it's current value has reached "fenceValue". once it's value // has reached "fenceValue", we know the command queue has finished executing WaitForSingleObject(fenceEvent, INFINITE); } // increment fenceValue for next frame fenceValue[frameIndex]++; // swap the current rtv buffer index so we draw on the correct buffer frameIndex = swapChain->GetCurrentBackBufferIndex(); } void D3dx12jo::CloseFenceHandle() { WaitForPreviousFrame(); CloseHandle(fenceEvent); }
{ "content_hash": "9d167cc9f65a84d41d6de6d719a6376b", "timestamp": "", "source": "github", "line_count": 367, "max_line_length": 165, "avg_line_length": 35.59945504087194, "alnum_prop": 0.7062380405663988, "repo_name": "jobeid/TrayPwrD3", "id": "bba0a662b91475587327f61b1c0f6efb7e941a3a", "size": "13109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/D3dx12jo.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1044" }, { "name": "C++", "bytes": "89116" } ], "symlink_target": "" }
from translate.misc import optrecurse import os class TestRecursiveOptionParser: def __init__(self): self.parser = optrecurse.RecursiveOptionParser({"txt":("po", None)}) def test_splitext(self): """test the L{optrecurse.splitext} function""" name = "name" extension = "ext" filename = name + os.extsep + extension dirname = os.path.join("some", "path", "to") fullpath = os.path.join(dirname, filename) root = os.path.join(dirname, name) print fullpath assert self.parser.splitext(fullpath) == (root, extension)
{ "content_hash": "caa9047ece0e04ad4dc9de2fb10d1a08", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 76, "avg_line_length": 33.44444444444444, "alnum_prop": 0.6262458471760798, "repo_name": "dbbhattacharya/kitsune", "id": "c3ef108c6197392ad478ef33b56857eda92829e9", "size": "625", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "vendor/packages/translate-toolkit/translate/misc/test_optrecurse.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "2694" }, { "name": "CSS", "bytes": "276585" }, { "name": "HTML", "bytes": "600145" }, { "name": "JavaScript", "bytes": "800276" }, { "name": "Python", "bytes": "2762831" }, { "name": "Shell", "bytes": "6720" }, { "name": "Smarty", "bytes": "1752" } ], "symlink_target": "" }
/* * Copyright (C) 1990-93 Silicon Graphics, Inc. * _______________________________________________________________________ ______________ S I L I C O N G R A P H I C S I N C . ____________ | | $Revision: 1.3 $ | | Classes: | SoXtSliderSets for creating organized groups of sliders | | Author(s) : Paul Isaacs | ______________ S I L I C O N G R A P H I C S I N C . ____________ _______________________________________________________________________ */ #include <inttypes.h> #include <Inventor/Xt/SoXtSliderSet.h> #include <X11/StringDefs.h> #include <Xm/Form.h> static XtResource _editorWidthResource[] = { { XtNwidth, XtCWidth, XtRDimension, sizeof( unsigned short), 0, XtRImmediate, (XtPointer) 0 } }; static XtResource _editorHeightResource[] = { { XtNheight, XtCHeight, XtRDimension, sizeof( unsigned short), 0, XtRImmediate, (XtPointer) 0 } }; SoXtSliderSet::SoXtSliderSet( Widget parent, const char *name, SbBool buildInsideParent, SoNode *newEditNode) : SoXtSliderSetBase( parent, name, buildInsideParent, newEditNode) { _parentShellWidget = NULL; } SoXtSliderSet::~SoXtSliderSet() { } void SoXtSliderSet::updateLayout() { int newLayoutH, newLayoutW; Dimension initialWidth, initialHeight; Dimension oldWidgetHeight, newWidgetHeight; int tempW, tempH; float topPos, bottomPos; Widget theSubWidget; Arg wargs[10]; int nargs; newLayoutH = 0; newLayoutW = 0; int i; for (i = 0; i < _numSubComponents; i++ ) { _subComponentArray[i]->getLayoutSize( tempW, tempH ); newLayoutH += tempH; newLayoutW = ( tempW > newLayoutW ) ? tempW : newLayoutW; } // set attachment and position for each module topPos = 0; bottomPos = 0; for (i = 0; i < _numSubComponents; i++ ) { // set its relative size in the container theSubWidget = _subComponentArray[i]->getWidget(); topPos = bottomPos; _subComponentArray[i]->getLayoutSize( tempW, tempH ); bottomPos += 100.0 * ((float) tempH / (float) newLayoutH); nargs = 0; XtSetArg( wargs[nargs], XmNtopAttachment, XmATTACH_POSITION); nargs++; XtSetArg( wargs[nargs], XmNtopPosition, (int) topPos ); nargs++; XtSetArg( wargs[nargs], XmNbottomAttachment, XmATTACH_POSITION);nargs++; XtSetArg( wargs[nargs], XmNbottomPosition, (int) bottomPos ); nargs++; XtSetArg( wargs[nargs], XmNleftAttachment, XmATTACH_FORM); nargs++; XtSetArg( wargs[nargs], XmNrightAttachment, XmATTACH_FORM); nargs++; XtSetValues( theSubWidget, wargs, nargs ); } // Now deal with adjusting SIZE of the ENTIRE EDITOR. if (widget == NULL) return; if ( _layoutHeight == 0 || _layoutWidth == 0 ) { // if first time throught, _layoutHeight and _layoutWidth will still // be at their initialized values of 0. In this case, just copy. _layoutHeight = newLayoutH; _layoutWidth = newLayoutW; // if the user has not specified a size for the window through the // resource system, then use the layout size. // otherwise, leave it alone. _editorHeightResource[0].default_addr = (XtPointer) (unsigned long) newLayoutH; _editorWidthResource[0].default_addr = (XtPointer) (unsigned long) newLayoutW; XtGetApplicationResources( widget, (XtPointer) &initialWidth, _editorWidthResource, XtNumber( _editorWidthResource ), NULL, 0); XtGetApplicationResources(widget, (XtPointer) &initialHeight, _editorHeightResource, XtNumber( _editorHeightResource ), NULL, 0); XtSetArg( wargs[0], XmNwidth, initialWidth ); XtSetArg( wargs[1], XmNheight, initialHeight ); XtSetValues( widget, wargs, 2 ); XtSetValues( _parentShellWidget, wargs, 2 ); } else if ( _layoutHeight != newLayoutH ) { // If layout height has changed (this will happen if modules // changed size, typically by opening or closing the multiSliders.) // Then we must calculate a new size for the editor. // To calculate, we keep these two ratios equal: // newWidgetHeight / newLayoutH = oldWidgetHeight / _layoutHeight XtSetArg( wargs[0], XmNheight, &oldWidgetHeight ); XtGetValues( _parentShellWidget, wargs, 1 ); // note that previous if statement prevents us from dividing by zero if (oldWidgetHeight == 0) newWidgetHeight = newLayoutH; else newWidgetHeight = (Dimension) (((float) newLayoutH ) * ((float) oldWidgetHeight / (float) _layoutHeight)); XtSetArg( wargs[0], XmNheight, newWidgetHeight ); XtSetValues( _parentShellWidget, wargs, 1 ); XtSetValues( widget, wargs, 1 ); _layoutHeight = newLayoutH; _layoutWidth = newLayoutW; } }
{ "content_hash": "46504938ea093d72524d22991596b804", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 80, "avg_line_length": 32.09027777777778, "alnum_prop": 0.6528889850681671, "repo_name": "OpenXIP/xip-libraries", "id": "5cc164227847f75341406f09ffdf82bdfd43a9b6", "size": "6127", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/extern/inventor/libSoXt/src/motif/SoXtSldrSet.c++", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "8314" }, { "name": "C", "bytes": "21064260" }, { "name": "C#", "bytes": "41726" }, { "name": "C++", "bytes": "33308677" }, { "name": "D", "bytes": "373" }, { "name": "Java", "bytes": "59889" }, { "name": "JavaScript", "bytes": "35954" }, { "name": "Objective-C", "bytes": "272450" }, { "name": "Perl", "bytes": "727865" }, { "name": "Prolog", "bytes": "101780" }, { "name": "Puppet", "bytes": "371631" }, { "name": "Python", "bytes": "162364" }, { "name": "Shell", "bytes": "906979" }, { "name": "Smalltalk", "bytes": "10530" }, { "name": "SuperCollider", "bytes": "2169433" }, { "name": "Tcl", "bytes": "10289" } ], "symlink_target": "" }
using namespace std; using namespace boost; static uint64 nAccountingEntryNumber = 0; extern CCriticalSection cs_db; extern map<string, int> mapFileUseCount; extern void CloseDb(const string& strFile); // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, ++nAccountingEntryNumber), acentry); } int64 CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64 nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; loop { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; entries.push_back(acentry); } pcursor->close(); } int CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey.clear(); int nFileVersion = 0; vector<uint256> vWalletUpgrade; bool fIsEncrypted = false; //// todo: shouldn't we catch exceptions and try to recover and continue? { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { printf("Error getting wallet database cursor\n"); return DB_CORRUPT; } loop { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { printf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other string strType; ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[strAddress]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; wtx.BindWallet(pwallet); if (wtx.GetHash() != hash) printf("Error in wallet.dat, hash mismatch\n"); // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; printf("LoadWallet() upgrading tx ver=%d %d '%s' %s\n", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = fTmp; } else { printf("LoadWallet() repairing tx ver=%d %s\n", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = 0; } vWalletUpgrade.push_back(hash); } //// debug print //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str()); //printf(" %12"PRI64d" %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat(wtx.GetBlockTime()).c_str(), // wtx.hashBlock.ToString().substr(0,20).c_str(), // wtx.mapValue["message"].c_str()); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64 nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; } else if (strType == "key" || strType == "wkey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; CKey key; if (strType == "key") { CPrivKey pkey; ssValue >> pkey; key.SetPubKey(vchPubKey); key.SetPrivKey(pkey); if (key.GetPubKey() != vchPubKey) { printf("Error reading wallet database: CPrivKey pubkey inconsistency\n"); return DB_CORRUPT; } if (!key.IsValid()) { printf("Error reading wallet database: invalid CPrivKey\n"); return DB_CORRUPT; } } else { CWalletKey wkey; ssValue >> wkey; key.SetPubKey(vchPubKey); key.SetPrivKey(wkey.vchPrivKey); if (key.GetPubKey() != vchPubKey) { printf("Error reading wallet database: CWalletKey pubkey inconsistency\n"); return DB_CORRUPT; } if (!key.IsValid()) { printf("Error reading wallet database: invalid CWalletKey\n"); return DB_CORRUPT; } } if (!pwallet->LoadKey(key)) { printf("Error reading wallet database: LoadKey failed\n"); return DB_CORRUPT; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { printf("Error reading wallet database: duplicate CMasterKey id %u\n", nID); return DB_CORRUPT; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { printf("Error reading wallet database: LoadCryptedKey failed\n"); return DB_CORRUPT; } fIsEncrypted = true; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64 nIndex; ssKey >> nIndex; pwallet->setKeyPool.insert(nIndex); } else if (strType == "version") { ssValue >> nFileVersion; if (nFileVersion == 10300) nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { printf("Error reading wallet database: LoadCScript failed\n"); return DB_CORRUPT; } } } pcursor->close(); } BOOST_FOREACH(uint256 hash, vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); printf("nFileVersion = %d\n", nFileVersion); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (fIsEncrypted && (nFileVersion == 40000 || nFileVersion == 50000)) return DB_NEED_REWRITE; if (nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); return DB_LOAD_OK; } void ThreadFlushWalletDB(void* parg) { const string& strFile = ((const string*)parg)[0]; static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64 nLastWalletUpdate = GetTime(); while (!fShutdown) { Sleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = mapFileUseCount.begin(); while (mi != mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0 && !fShutdown) { map<string, int>::iterator mi = mapFileUseCount.find(strFile); if (mi != mapFileUseCount.end()) { printf("%s ", DateTimeStrFormat(GetTime()).c_str()); printf("Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64 nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained CloseDb(strFile); dbenv.txn_checkpoint(0, 0, 0); dbenv.lsn_reset(strFile.c_str(), 0); mapFileUseCount.erase(mi++); printf("Flushed wallet.dat %"PRI64d"ms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (!fShutdown) { { LOCK(cs_db); if (!mapFileUseCount.count(wallet.strWalletFile) || mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file CloseDb(wallet.strWalletFile); dbenv.txn_checkpoint(0, 0, 0); dbenv.lsn_reset(wallet.strWalletFile.c_str(), 0); mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif printf("copied wallet.dat to %s\n", pathDest.string().c_str()); return true; } catch(const filesystem::filesystem_error &e) { printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what()); return false; } } } Sleep(100); } return false; }
{ "content_hash": "b37c0b0d8b1b0cec74af65040be77026", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 166, "avg_line_length": 33.9928400954654, "alnum_prop": 0.49961384539773923, "repo_name": "linuxmahara/Negativity5-1", "id": "e94c449f8f930147f87c892a5b8a1414e5ae4ba8", "size": "14604", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/walletdb.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7765" }, { "name": "C++", "bytes": "14513638" }, { "name": "Groff", "bytes": "12841" }, { "name": "Makefile", "bytes": "69485" }, { "name": "NSIS", "bytes": "5970" }, { "name": "Objective-C++", "bytes": "2463" }, { "name": "Python", "bytes": "50532" }, { "name": "QMake", "bytes": "11037" }, { "name": "Shell", "bytes": "1849" } ], "symlink_target": "" }
<?php /* Now prepare the MySQL insert */ /* Include the config file */ require_once "config.php"; /* and the database file */ require_once "db.php"; // Create connection $conn = new mysqli($host, $user, $pass, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // strip_tags($text, '<p><a>'); $c = $_POST['content']; $t = $_POST['title']; $c = mysqli_real_escape_string($conn, $c); $t = mysqli_real_escape_string($conn, $t); $sql = "INSERT INTO `" . $database . "`.`openappstorestatic` (`content`, `hidden`, `title`) VALUES ('". strip_tags($c, ALLOWEDHTML) . "', '0', '" . strip_tags($t, ALLOWEDHTML) . "');"; if(isset($_POST['edit'])) { if(isset($_POST['edit_id'])) { $sql = "UPDATE `openappstorestatic` SET `content` = '" . strip_tags($c, ALLOWEDHTML) . "', `title` = '" . strip_tags($t, ALLOWEDHTML) . "' WHERE `id` = " . mysqli_real_escape_string($conn, $_POST['edit_id']) . ";"; //echo $sql; } else { die("error"); } } //die($sql); if ($conn->query($sql) === TRUE) { //echo "Database created successfully"; } else { echo "Error creating post: " . $conn->error; } $conn->close(); header("Location: index.php?success=1");
{ "content_hash": "60655dd4a661dc135c2a3638a923ed84", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 218, "avg_line_length": 31.24390243902439, "alnum_prop": 0.5644028103044496, "repo_name": "brendanmanning/OpenAppStore", "id": "7d399ef1036a1adfac199a8e6ba38e6d6ad001a1", "size": "1281", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "createpage.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "118602" } ], "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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cidic</groupId> <artifactId>fontdesign</artifactId> <name>FontDesign</name> <packaging>war</packaging> <version>1.0.0-BUILD-SNAPSHOT</version> <properties> <java-version>1.6</java-version> <org.springframework-version>3.1.1.RELEASE</org.springframework-version> <org.aspectj-version>1.6.10</org.aspectj-version> <org.slf4j-version>1.6.6</org.slf4j-version> </properties> <dependencies> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.0.3.RELEASE</version> </dependency> <!-- AspectJ --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <!-- Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <!-- Hibernate4 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <!-- for JPA, use hibernate-entitymanager instead of hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.3.5.Final</version> </dependency> <!-- 以下可选 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-c3p0</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-proxool</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-infinispan</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>3.2.0.Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>org.jboss</groupId> <artifactId>jandex</artifactId> <version>1.1.0.Final</version> </dependency> <!-- 为了让Hibernate使用代理模式,需要javassist --> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.18.1-GA</version> </dependency> <dependency> <groupId>org.jboss.logging</groupId> <artifactId>jboss-logging</artifactId> <version>3.1.3.GA</version> </dependency> <dependency> <groupId>org.jboss.spec.javax.annotation</groupId> <artifactId>jboss-annotations-api_1.2_spec</artifactId> <version>1.0.0.Final</version> </dependency> <dependency> <groupId>antlr</groupId> <artifactId>antlr</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> <!-- tomcat7.0.35 数据库连接池 --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>7.0.35</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.19</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.10</version> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.0.0, 7.0.99]</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-eclipse-plugin</artifactId> <version>2.9</version> <configuration> <additionalProjectnatures> <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature> </additionalProjectnatures> <additionalBuildcommands> <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand> </additionalBuildcommands> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <compilerArgument>-Xlint:all</compilerArgument> <showWarnings>true</showWarnings> <showDeprecation>true</showDeprecation> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>org.test.int1.Main</mainClass> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "c915a1a7dc29674264f20e58245f8879", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 104, "avg_line_length": 29.018691588785046, "alnum_prop": 0.6618357487922706, "repo_name": "zyhndesign/FontDesign", "id": "2b75733c550dc9c14633b20fcce188951dd7bd89", "size": "9359", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "20693" }, { "name": "HTML", "bytes": "213" }, { "name": "Java", "bytes": "121255" }, { "name": "JavaScript", "bytes": "177958" } ], "symlink_target": "" }
package me.magicall.xml.dom4j; import java.util.Map; /** * 在给定的map中,以节点名作为key寻找对应的java bean的类全名。 * * @author MaGiCalL */ public class MappingNodeNameToClassNameXmlParser extends AbsXmlParser { private final Map<String, String> nodeNameClassNameMap; public MappingNodeNameToClassNameXmlParser(final Map<String, String> nodeNameClassNameMap) { super(); this.nodeNameClassNameMap = nodeNameClassNameMap; } @Override protected String nodeNameToClassName(final String nodeName) { return nodeNameClassNameMap.get(nodeName); } }
{ "content_hash": "e2ac28f84d0a786ee80b084c92b56a12", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 93, "avg_line_length": 23.652173913043477, "alnum_prop": 0.7904411764705882, "repo_name": "magical-l/magicall-xml-dom4j", "id": "28162366668c209c2825ef30b55950ce4178b987", "size": "588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/me/magicall/xml/dom4j/MappingNodeNameToClassNameXmlParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8187" } ], "symlink_target": "" }
namespace blink { namespace { class EmptyModuleRecordResolver final : public ModuleRecordResolver { public: EmptyModuleRecordResolver() = default; // We ignore {Unr,R}egisterModuleScript() calls caused by // ModuleScript::CreateForTest(). void RegisterModuleScript(const ModuleScript*) override {} void UnregisterModuleScript(const ModuleScript*) override {} const ModuleScript* GetModuleScriptFromModuleRecord( v8::Local<v8::Module>) const override { NOTREACHED(); return nullptr; } v8::Local<v8::Module> Resolve(const String& specifier, v8::Local<v8::Module> referrer, ExceptionState&) override { NOTREACHED(); return v8::Local<v8::Module>(); } }; } // namespace DummyModulator::DummyModulator() : resolver_(MakeGarbageCollected<EmptyModuleRecordResolver>()) {} DummyModulator::~DummyModulator() = default; void DummyModulator::Trace(Visitor* visitor) { visitor->Trace(resolver_); Modulator::Trace(visitor); } ScriptState* DummyModulator::GetScriptState() { NOTREACHED(); return nullptr; } V8CacheOptions DummyModulator::GetV8CacheOptions() const { return kV8CacheOptionsDefault; } bool DummyModulator::IsScriptingDisabled() const { return false; } bool DummyModulator::ImportMapsEnabled() const { return false; } ModuleRecordResolver* DummyModulator::GetModuleRecordResolver() { return resolver_.Get(); } base::SingleThreadTaskRunner* DummyModulator::TaskRunner() { NOTREACHED(); return nullptr; } void DummyModulator::FetchTree(const KURL&, ResourceFetcher*, mojom::RequestContextType, network::mojom::RequestDestination, const ScriptFetchOptions&, ModuleScriptCustomFetchType, ModuleTreeClient*) { NOTREACHED(); } void DummyModulator::FetchSingle(const ModuleScriptFetchRequest&, ResourceFetcher*, ModuleGraphLevel, ModuleScriptCustomFetchType, SingleModuleClient*) { NOTREACHED(); } void DummyModulator::FetchDescendantsForInlineScript( ModuleScript*, ResourceFetcher*, mojom::RequestContextType, network::mojom::RequestDestination, ModuleTreeClient*) { NOTREACHED(); } ModuleScript* DummyModulator::GetFetchedModuleScript(const KURL&) { NOTREACHED(); return nullptr; } KURL DummyModulator::ResolveModuleSpecifier(const String&, const KURL&, String*) { NOTREACHED(); return KURL(); } bool DummyModulator::HasValidContext() { return true; } void DummyModulator::ResolveDynamically(const String&, const KURL&, const ReferrerScriptInfo&, ScriptPromiseResolver*) { NOTREACHED(); } ScriptValue DummyModulator::CreateTypeError(const String& message) const { NOTREACHED(); return ScriptValue(); } ScriptValue DummyModulator::CreateSyntaxError(const String& message) const { NOTREACHED(); return ScriptValue(); } void DummyModulator::RegisterImportMap(const ImportMap*, ScriptValue error_to_rethrow) { NOTREACHED(); } bool DummyModulator::IsAcquiringImportMaps() const { NOTREACHED(); return true; } void DummyModulator::ClearIsAcquiringImportMaps() { NOTREACHED(); } const ImportMap* DummyModulator::GetImportMapForTest() const { NOTREACHED(); return nullptr; } ModuleImportMeta DummyModulator::HostGetImportMetaProperties( v8::Local<v8::Module>) const { NOTREACHED(); return ModuleImportMeta(String()); } ScriptValue DummyModulator::InstantiateModule(v8::Local<v8::Module>, const KURL&) { NOTREACHED(); return ScriptValue(); } Vector<Modulator::ModuleRequest> DummyModulator::ModuleRequestsFromModuleRecord( v8::Local<v8::Module>) { NOTREACHED(); return Vector<ModuleRequest>(); } ModuleEvaluationResult DummyModulator::ExecuteModule(ModuleScript*, CaptureEvalErrorFlag) { NOTREACHED(); return ModuleEvaluationResult::Empty(); } ModuleScriptFetcher* DummyModulator::CreateModuleScriptFetcher( ModuleScriptCustomFetchType, util::PassKey<ModuleScriptLoader> pass_key) { NOTREACHED(); return nullptr; } } // namespace blink
{ "content_hash": "c8bd6c2adc530a5bad7402e276a023cd", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 80, "avg_line_length": 26.53142857142857, "alnum_prop": 0.6398880034460478, "repo_name": "endlessm/chromium-browser", "id": "23f14bb37a8a54324a8b57bd67df7cf6c9487469", "size": "5096", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "third_party/blink/renderer/core/testing/dummy_modulator.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
module Pokemon class Set attr_accessor :id, :name, :series, :printed_total, :total, :legalities, :ptcgo_code, :release_date, :updated_at, :images def self.from_json(json) set = Set.new set.id = json['id'] set.name = json['name'] set.series = json['series'] set.printed_total = json['printedTotal'] set.total = json['total'] set.legalities = Legalities.from_json(json['legalities']) if !json['legalities'].nil? set.ptcgo_code = json['ptcgoCode'] set.release_date = json['releaseDate'] set.updated_at = json['updatedAt'] set.images = SetImages.from_json(json['images']) if !json['images'].nil? set end # Get the resource string # # @return [String] The API resource string def self.Resource "sets" end # Find a single set by the set code # # @param id [String] the set code # @return [Set] the Set object response def self.find(id) QueryBuilder.new(Set).find(id) end # Get all sets from a query by paging through data # # @return [Array<Set>] Array of Set objects def self.all QueryBuilder.new(Set).all end # Adds a parameter to the hash of query parameters # # @param args [Hash] the query parameter # @return [Array<Set>] Array of Set objects def self.where(args) QueryBuilder.new(Set).where(args) end end end
{ "content_hash": "9b5eeeef53fb8e8c8210bfcb15355f3e", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 124, "avg_line_length": 27.901960784313726, "alnum_prop": 0.6163035839775123, "repo_name": "PokemonTCG/pokemon-tcg-sdk-ruby", "id": "86380de22e0e73ccdf91f2dd9cc9b6766132a67a", "size": "1423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/pokemon_tcg_sdk/set.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21796" } ], "symlink_target": "" }
from CIM14.CPSM.StateVariables.Element import Element class TopologicalIsland(Element): """An electrically connected subset of the network. Topological islands can change as the current network state changes (i.e. switch or Terminal.connected status changes). """ def __init__(self, AngleRef_TopologicalNode=None, TopologicalNodes=None, *args, **kw_args): """Initialises a new 'TopologicalIsland' instance. @param AngleRef_TopologicalNode: The angle reference for the island. Normally there is one TopologicalNode that is selected as the angle reference for each island. Other reference schemes exist, so the association is optional. @param TopologicalNodes: A topological node belongs to a topological island """ self._AngleRef_TopologicalNode = None self.AngleRef_TopologicalNode = AngleRef_TopologicalNode self._TopologicalNodes = [] self.TopologicalNodes = [] if TopologicalNodes is None else TopologicalNodes super(TopologicalIsland, self).__init__(*args, **kw_args) _attrs = [] _attr_types = {} _defaults = {} _enums = {} _refs = ["AngleRef_TopologicalNode", "TopologicalNodes"] _many_refs = ["TopologicalNodes"] def getAngleRef_TopologicalNode(self): """The angle reference for the island. Normally there is one TopologicalNode that is selected as the angle reference for each island. Other reference schemes exist, so the association is optional. """ return self._AngleRef_TopologicalNode def setAngleRef_TopologicalNode(self, value): if self._AngleRef_TopologicalNode is not None: self._AngleRef_TopologicalNode._AngleRef_TopologicalIsland = None self._AngleRef_TopologicalNode = value if self._AngleRef_TopologicalNode is not None: self._AngleRef_TopologicalNode.AngleRef_TopologicalIsland = None self._AngleRef_TopologicalNode._AngleRef_TopologicalIsland = self AngleRef_TopologicalNode = property(getAngleRef_TopologicalNode, setAngleRef_TopologicalNode) def getTopologicalNodes(self): """A topological node belongs to a topological island """ return self._TopologicalNodes def setTopologicalNodes(self, value): for x in self._TopologicalNodes: x.TopologicalIsland = None for y in value: y._TopologicalIsland = self self._TopologicalNodes = value TopologicalNodes = property(getTopologicalNodes, setTopologicalNodes) def addTopologicalNodes(self, *TopologicalNodes): for obj in TopologicalNodes: obj.TopologicalIsland = self def removeTopologicalNodes(self, *TopologicalNodes): for obj in TopologicalNodes: obj.TopologicalIsland = None
{ "content_hash": "5db07d75cfc63e41ec9a43b8c318f962", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 238, "avg_line_length": 43.2, "alnum_prop": 0.7029914529914529, "repo_name": "rwl/PyCIM", "id": "2aed487bcdfdaceacdecc7e3eb7f5740e05264ce", "size": "3908", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CIM14/CPSM/StateVariables/StateVariables/TopologicalIsland.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "7420564" } ], "symlink_target": "" }
import fnmatch import sys import subprocess def git_get_staged_files(): files = str(subprocess.check_output(['git', 'diff', '--name-only', '--cached'])) return [line for line in files.splitlines() if line != ''] def git_get_all_files(): files = str(subprocess.check_output(['git', 'ls-files'])) return [line for line in files.splitlines() if line != ''] def get_src_files(): files = git_get_all_files() extensions = ('c', 'cpp', 'h', 'hpp') return [file for file in files if (file.startswith('src/') or file.startswith('inc')) and file.endswith(extensions)] def get_staged_src_files(): files = git_get_staged_files() extensions = ('c', 'cpp', 'h', 'hpp') return [file for file in files if file.startswith('src/') and file.endswith(extensions)] def get_blacklisted_files(): with open('blacklist', 'r') as blacklist: return [line.rstrip() for line in blacklist if line != '' and line.lstrip()[0] != '#'] def cpplint_check_file(filename): try: filters = '--filter=-readability/check,-build/include_order,-build/header_guard' subprocess.check_call(['python', 'cpplint.py', '--root=src', filters, filename]) except subprocess.CalledProcessError as error: return False return True def main(): src_files = get_staged_src_files() if len(sys.argv) == 2 and sys.argv[1] == 'all': src_files = get_src_files() blacklisted_files = get_blacklisted_files() files_to_check = [file for file in src_files if file not in blacklisted_files] bad_files_count = 0 for file in files_to_check: if not cpplint_check_file(file): bad_files_count += 1 sys.exit(bad_files_count) if __name__ == '__main__': main()
{ "content_hash": "f2c0ffbddf1f28550dcde8c89b853ef3", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 118, "avg_line_length": 33.34, "alnum_prop": 0.6634673065386922, "repo_name": "xairy/enet-plus", "id": "45dc83770097ac2599846172f28d4d12f967a9d7", "size": "1686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "checkstyle.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "41552" }, { "name": "C++", "bytes": "31403" }, { "name": "Lua", "bytes": "2421" }, { "name": "Python", "bytes": "160588" }, { "name": "Shell", "bytes": "306" } ], "symlink_target": "" }
package org.apache.asterix.runtime.evaluators.accessors; import java.io.DataOutput; import java.io.IOException; import org.apache.asterix.dataflow.data.nontagged.serde.ADurationSerializerDeserializer; import org.apache.asterix.dataflow.data.nontagged.serde.AInt32SerializerDeserializer; import org.apache.asterix.dataflow.data.nontagged.serde.AInt64SerializerDeserializer; import org.apache.asterix.dataflow.data.nontagged.serde.AYearMonthDurationSerializerDeserializer; import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider; import org.apache.asterix.om.base.AInt64; import org.apache.asterix.om.base.AMutableInt64; import org.apache.asterix.om.base.ANull; import org.apache.asterix.om.base.temporal.GregorianCalendarSystem; import org.apache.asterix.om.functions.AsterixBuiltinFunctions; import org.apache.asterix.om.functions.IFunctionDescriptor; import org.apache.asterix.om.functions.IFunctionDescriptorFactory; import org.apache.asterix.om.types.ATypeTag; import org.apache.asterix.om.types.BuiltinType; import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.algebricks.runtime.base.ICopyEvaluator; import org.apache.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.data.std.api.IDataOutputProvider; import org.apache.hyracks.data.std.util.ArrayBackedValueStorage; import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference; public class TemporalMonthAccessor extends AbstractScalarFunctionDynamicDescriptor { private static final long serialVersionUID = 1L; private static final FunctionIdentifier FID = AsterixBuiltinFunctions.ACCESSOR_TEMPORAL_MONTH; // allowed input types private static final byte SER_DATE_TYPE_TAG = ATypeTag.DATE.serialize(); private static final byte SER_DATETIME_TYPE_TAG = ATypeTag.DATETIME.serialize(); private static final byte SER_DURATION_TYPE_TAG = ATypeTag.DURATION.serialize(); private static final byte SER_YEAR_MONTH_TYPE_TAG = ATypeTag.YEARMONTHDURATION.serialize(); private static final byte SER_NULL_TYPE_TAG = ATypeTag.NULL.serialize(); public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new TemporalMonthAccessor(); } }; /* (non-Javadoc) * @see org.apache.asterix.runtime.base.IScalarFunctionDynamicDescriptor#createEvaluatorFactory(org.apache.hyracks.algebricks.runtime.base.ICopyEvaluatorFactory[]) */ @Override public ICopyEvaluatorFactory createEvaluatorFactory(final ICopyEvaluatorFactory[] args) throws AlgebricksException { return new ICopyEvaluatorFactory() { private static final long serialVersionUID = 1L; @Override public ICopyEvaluator createEvaluator(final IDataOutputProvider output) throws AlgebricksException { return new ICopyEvaluator() { private final DataOutput out = output.getDataOutput(); private final ArrayBackedValueStorage argOut = new ArrayBackedValueStorage(); private final ICopyEvaluator eval = args[0].createEvaluator(argOut); private final GregorianCalendarSystem calSystem = GregorianCalendarSystem.getInstance(); // for output: type integer @SuppressWarnings("unchecked") private final ISerializerDeserializer<AInt64> intSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.AINT64); private final AMutableInt64 aMutableInt64 = new AMutableInt64(0); @SuppressWarnings("unchecked") private final ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE .getSerializerDeserializer(BuiltinType.ANULL); @Override public void evaluate(IFrameTupleReference tuple) throws AlgebricksException { argOut.reset(); eval.evaluate(tuple); byte[] bytes = argOut.getByteArray(); try { if (bytes[0] == SER_DURATION_TYPE_TAG) { aMutableInt64.setValue(calSystem.getDurationMonth(ADurationSerializerDeserializer .getYearMonth(bytes, 1))); intSerde.serialize(aMutableInt64, out); return; } if (bytes[0] == SER_YEAR_MONTH_TYPE_TAG) { aMutableInt64.setValue(calSystem .getDurationMonth(AYearMonthDurationSerializerDeserializer.getYearMonth(bytes, 1))); intSerde.serialize(aMutableInt64, out); return; } long chrononTimeInMs = 0; if (bytes[0] == SER_DATE_TYPE_TAG) { chrononTimeInMs = AInt32SerializerDeserializer.getInt(bytes, 1) * GregorianCalendarSystem.CHRONON_OF_DAY; } else if (bytes[0] == SER_DATETIME_TYPE_TAG) { chrononTimeInMs = AInt64SerializerDeserializer.getLong(bytes, 1); } else if (bytes[0] == SER_NULL_TYPE_TAG) { nullSerde.serialize(ANull.NULL, out); return; } else { throw new AlgebricksException("Inapplicable input type: " + bytes[0]); } int year = calSystem.getYear(chrononTimeInMs); int month = calSystem.getMonthOfYear(chrononTimeInMs, year); aMutableInt64.setValue(month); intSerde.serialize(aMutableInt64, out); } catch (IOException e) { throw new AlgebricksException(e); } } }; } }; } /* (non-Javadoc) * @see org.apache.asterix.om.functions.IFunctionDescriptor#getIdentifier() */ @Override public FunctionIdentifier getIdentifier() { return FID; } }
{ "content_hash": "98176ad64a1da99398916d74011b8366", "timestamp": "", "source": "github", "line_count": 142, "max_line_length": 167, "avg_line_length": 48.859154929577464, "alnum_prop": 0.6317382530988758, "repo_name": "amoudi87/asterixdb", "id": "48856ca0d52355b55b185abfa17499ab933516bf", "size": "7745", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "asterix-runtime/src/main/java/org/apache/asterix/runtime/evaluators/accessors/TemporalMonthAccessor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6115" }, { "name": "CSS", "bytes": "4763" }, { "name": "Crystal", "bytes": "453" }, { "name": "HTML", "bytes": "114488" }, { "name": "Java", "bytes": "9375622" }, { "name": "JavaScript", "bytes": "237719" }, { "name": "Python", "bytes": "268336" }, { "name": "Ruby", "bytes": "2666" }, { "name": "Scheme", "bytes": "1105" }, { "name": "Shell", "bytes": "182529" }, { "name": "Smarty", "bytes": "31412" } ], "symlink_target": "" }
const RGBImage = require('./RaspiRGBImage'); const Overlay = require('./Overlay').Overlay; const RGBBuffer = require('./RGBBuffer'); const HumidTemp = require('../sensor/HumidTemp'); const overlay = new Overlay(); const imagemin = require('imagemin'); const imageminPngquant = require('imagemin-pngquant'); /** * [getPNGCapturePromise description] * @param {Number} imageWidth The width of the image to capture. * @param {Number} imageHeight The height of the image to capture. * @return {{ * pngBuffer: {Buffer}, * brightness: {Number}, * captureStartTime: {Number}. * captureEndTime: {Number}, * captureDuration: {Number} * }} */ function getPNGCapturePromise(imageWidth, imageHeight) { let captureStartTime = (new Date()).getTime(); return new Promise((resolve, reject) => { Promise.all([ RGBImage.takeRGBPicture(imageWidth, imageHeight), overlay.loadResources() ]).then((results) => { // The RGB Buffer from the image capture. let rgbBuffer = results[0]; // Converted RGB buffer into a bitmap. let rgbBitmap = RGBBuffer.getBitmapFromBuffer(rgbBuffer, imageWidth, imageHeight); // The brightness of the returned image. let brightness = getAverageBrightness(rgbBitmap); // Get the correct sensor information to draw our overlay. HumidTemp.getHumidityTemperature().then( (result) => { overlay.drawOverlay(rgbBitmap, result.temperature, result.humidity); }) .then(() => { // Write out the overlay into a PNG buffer. return RGBBuffer.writeBitmapToPNGBuffer(rgbBitmap).then((pngBuffer) => { let captureEndTime = (new Date()).getTime(); return imagemin.buffer( pngBuffer, {plugins: imageminPngquant({quality: '80'})} ).then((compressedPng) => { // Resolve with the compressed PNG and other variables. resolve({ pngBuffer: compressedPng, brightness, captureStartTime, captureEndTime, captureDuration: captureEndTime - captureStartTime }); }); }); }) }); }); }; /** * Returns the average brightness of an RGB bitmap. This is computed by * calculating the average greyscale value of the entire image. * @param {Number} rgbBitmap The bitmap to iterate over. * @return {Number} A number between 0-255 depending on the brightness. */ function getAverageBrightness(rgbBitmap) { let greyscaleValue = 0; for(var x=0; x < rgbBitmap.width; x++) { for(var y=0; y < rgbBitmap.height; y++) { var rgb = rgbBitmap.getPixelRGBA(x,y); // Using masking, calculate the average of the three color channels. greyscaleValue += (((0xFF000000 & rgb) >>> 24) + ((0xFF0000 & rgb) >>> 16) + ((0xFF00 & rgb) >>> 8)) / 3; } } return greyscaleValue / (rgbBitmap.width * rgbBitmap.height); } // The public module exports~ module.exports = { getPNGCapturePromise, getAverageBrightness };
{ "content_hash": "54f32cf5ebedaf848781b00426a160a6", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 111, "avg_line_length": 34.022222222222226, "alnum_prop": 0.6358589157413456, "repo_name": "malbanese/hydroponic-monitoring-system", "id": "e43819011ab764b9e5faeb3d207e44de732cbe85", "size": "3062", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/image/PNGCaptureRoutine.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "19142" } ], "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_22) on Wed Sep 14 22:21:33 CEST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Uses of Class net.sourceforge.pmd.rules.junit.AbstractJUnitRule (PMD 4.2.6 API) </TITLE> <META NAME="date" CONTENT="2011-09-14"> <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 net.sourceforge.pmd.rules.junit.AbstractJUnitRule (PMD 4.2.6 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="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit"><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> </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?net/sourceforge/pmd/rules/junit//class-useAbstractJUnitRule.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AbstractJUnitRule.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>net.sourceforge.pmd.rules.junit.AbstractJUnitRule</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit">AbstractJUnitRule</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.rules.junit"><B>net.sourceforge.pmd.rules.junit</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#net.sourceforge.pmd.rules.migration"><B>net.sourceforge.pmd.rules.migration</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.rules.junit"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit">AbstractJUnitRule</A> in <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/package-summary.html">net.sourceforge.pmd.rules.junit</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit">AbstractJUnitRule</A> in <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/package-summary.html">net.sourceforge.pmd.rules.junit</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../net/sourceforge/pmd/rules/junit/JUnitAssertionsShouldIncludeMessage.html" title="class in net.sourceforge.pmd.rules.junit">JUnitAssertionsShouldIncludeMessage</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../net/sourceforge/pmd/rules/junit/JUnitTestsShouldContainAsserts.html" title="class in net.sourceforge.pmd.rules.junit">JUnitTestsShouldContainAsserts</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../net/sourceforge/pmd/rules/junit/TestClassWithoutTestCases.html" title="class in net.sourceforge.pmd.rules.junit">TestClassWithoutTestCases</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="net.sourceforge.pmd.rules.migration"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit">AbstractJUnitRule</A> in <A HREF="../../../../../../net/sourceforge/pmd/rules/migration/package-summary.html">net.sourceforge.pmd.rules.migration</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit">AbstractJUnitRule</A> in <A HREF="../../../../../../net/sourceforge/pmd/rules/migration/package-summary.html">net.sourceforge.pmd.rules.migration</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../net/sourceforge/pmd/rules/migration/JUnitUseExpected.html" title="class in net.sourceforge.pmd.rules.migration">JUnitUseExpected</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This rule finds code like this:</TD> </TR> </TABLE> &nbsp; <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="../../../../../../net/sourceforge/pmd/rules/junit/AbstractJUnitRule.html" title="class in net.sourceforge.pmd.rules.junit"><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> </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?net/sourceforge/pmd/rules/junit//class-useAbstractJUnitRule.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="AbstractJUnitRule.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 &copy; 2002-2011 InfoEther. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "975f8f558f7ab400749c57ea33acc430", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 336, "avg_line_length": 47.22566371681416, "alnum_prop": 0.641525344326806, "repo_name": "pscadiz/pmd-4.2.6-gds", "id": "dfd69b6d73876a10e0af63ebf6aaff8d6fed71a1", "size": "10673", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/apidocs/net/sourceforge/pmd/rules/junit/class-use/AbstractJUnitRule.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3336" }, { "name": "CSS", "bytes": "1241" }, { "name": "HTML", "bytes": "440" }, { "name": "Java", "bytes": "2602537" }, { "name": "JavaScript", "bytes": "7987" }, { "name": "Ruby", "bytes": "845" }, { "name": "Shell", "bytes": "19634" }, { "name": "XSLT", "bytes": "60577" } ], "symlink_target": "" }
let wizard = { house: '', courses: [], }; export default class WizardRepository { static get() { return wizard; } static save(updatedWizard) { wizard = updatedWizard; return wizard; } }
{ "content_hash": "bb771cb1b10e60c1680c1012159b7aaf", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 39, "avg_line_length": 12.588235294117647, "alnum_prop": 0.6074766355140186, "repo_name": "zhon/react-hogwarts-tdd-kata", "id": "3eb0e37ec78e97cba595c1c8a27d0e21455be530", "size": "214", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/repositories/wizard-repository.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1691" }, { "name": "JavaScript", "bytes": "19806" } ], "symlink_target": "" }
 CKEDITOR.dialog.add( 'radio', function( editor ) { return { title: editor.lang.forms.checkboxAndRadio.radioTitle, minWidth: 350, minHeight: 140, onShow: function() { delete this.radioButton; var element = this.getParentEditor().getSelection().getSelectedElement(); if ( element && element.getName() == 'input' && element.getAttribute( 'type' ) == 'radio' ) { this.radioButton = element; this.setupContent( element ); } }, onOk: function() { var editor, element = this.radioButton, isInsertMode = !element; if ( isInsertMode ) { editor = this.getParentEditor(); element = editor.document.createElement( 'input' ); element.setAttribute( 'type', 'radio' ); } if ( isInsertMode ) editor.insertElement( element ); this.commitContent({ element: element } ); }, contents: [ { id: 'info', label: editor.lang.forms.checkboxAndRadio.radioTitle, title: editor.lang.forms.checkboxAndRadio.radioTitle, elements: [ { id: 'name', type: 'text', label: editor.lang.common.name, 'default': '', accessKey: 'N', setup: function( element ) { this.setValue( element.data( 'cke-saved-name' ) || element.getAttribute( 'name' ) || '' ); }, commit: function( data ) { var element = data.element; if ( this.getValue() ) element.data( 'cke-saved-name', this.getValue() ); else { element.data( 'cke-saved-name', false ); element.removeAttribute( 'name' ); } } }, { id: 'value', type: 'text', label: editor.lang.forms.checkboxAndRadio.value, 'default': '', accessKey: 'V', setup: function( element ) { this.setValue( element.getAttribute( 'value' ) || '' ); }, commit: function( data ) { var element = data.element; if ( this.getValue() ) element.setAttribute( 'value', this.getValue() ); else element.removeAttribute( 'value' ); } }, { id: 'checked', type: 'checkbox', label: editor.lang.forms.checkboxAndRadio.selected, 'default': '', accessKey: 'S', value: "checked", setup: function( element ) { this.setValue( element.getAttribute( 'checked' ) ); }, commit: function( data ) { var element = data.element; if ( !( CKEDITOR.env.ie || CKEDITOR.env.opera ) ) { if ( this.getValue() ) element.setAttribute( 'checked', 'checked' ); else element.removeAttribute( 'checked' ); } else { var isElementChecked = element.getAttribute( 'checked' ); var isChecked = !!this.getValue(); if ( isElementChecked != isChecked ) { var replace = CKEDITOR.dom.element.createFromHtml( '<input type="radio"' + ( isChecked ? ' checked="checked"' : '' ) + '></input>', editor.document ); element.copyAttributes( replace, { type:1,checked:1 } ); replace.replace( element ); editor.getSelection().selectElement( replace ); data.element = replace; } } } } ] } ] }; });
{ "content_hash": "0175eb292e79d8bfca8dead210d9d58c", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 123, "avg_line_length": 28.214285714285715, "alnum_prop": 0.5715189873417722, "repo_name": "webmasterETSI/web", "id": "ebdf951e9ce79784e5a1e8968fd526e56e70baf3", "size": "3326", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "web/ckeditor/plugins/forms/dialogs/radio.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4357402" }, { "name": "PHP", "bytes": "185061" }, { "name": "Perl", "bytes": "26" }, { "name": "Shell", "bytes": "213" } ], "symlink_target": "" }
namespace oless { namespace excel { namespace records { class FrtWrapperRecord : public Record { public: FrtWrapperRecord(unsigned short type, std::vector<uint8_t> data) : Record(type, data) { } }; } } }
{ "content_hash": "3c0dcdc9d5a5a7ff2850c00d1ab0709b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 91, "avg_line_length": 17.615384615384617, "alnum_prop": 0.6506550218340611, "repo_name": "DBHeise/fileid", "id": "95f18bbddd51c42001b9c1b12a4e8ef8127d6645", "size": "266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fileid/document/excel/records/FrtWrapperRecord.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1263238" }, { "name": "Makefile", "bytes": "1186" }, { "name": "PowerShell", "bytes": "17765" }, { "name": "Python", "bytes": "2380" }, { "name": "Shell", "bytes": "209" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_40) on Wed Apr 13 18:09:41 UTC 2016 --> <title>Uses of Class org.apache.cassandra.cql3.statements.DropRoleStatement (apache-cassandra API)</title> <meta name="date" content="2016-04-13"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.cassandra.cql3.statements.DropRoleStatement (apache-cassandra API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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><a href="../../../../../../org/apache/cassandra/cql3/statements/DropRoleStatement.html" title="class in org.apache.cassandra.cql3.statements">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></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"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/cql3/statements/class-use/DropRoleStatement.html" target="_top">Frames</a></li> <li><a href="DropRoleStatement.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.cassandra.cql3.statements.DropRoleStatement" class="title">Uses of Class<br>org.apache.cassandra.cql3.statements.DropRoleStatement</h2> </div> <div class="classUseContainer">No usage of org.apache.cassandra.cql3.statements.DropRoleStatement</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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><a href="../../../../../../org/apache/cassandra/cql3/statements/DropRoleStatement.html" title="class in org.apache.cassandra.cql3.statements">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></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"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/cassandra/cql3/statements/class-use/DropRoleStatement.html" target="_top">Frames</a></li> <li><a href="DropRoleStatement.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "7796426ff9f76fc516c8b347058153a7", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 171, "avg_line_length": 38.184, "alnum_prop": 0.6174313848732453, "repo_name": "elisska/cloudera-cassandra", "id": "11e6173501b1a675688c3c89f78833fb6ea520b5", "size": "4773", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DATASTAX_CASSANDRA-3.5.0/javadoc/org/apache/cassandra/cql3/statements/class-use/DropRoleStatement.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "75145" }, { "name": "CSS", "bytes": "4112" }, { "name": "HTML", "bytes": "331372" }, { "name": "PowerShell", "bytes": "77673" }, { "name": "Python", "bytes": "979128" }, { "name": "Shell", "bytes": "143685" }, { "name": "Thrift", "bytes": "80564" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Files { class Program { static void Main(string[] args) { var numberOfFiles = int.Parse(Console.ReadLine()); // Dictionary : ROOT -> FILENAMEANDEXT -> SIZE var files = new Dictionary<string, Dictionary<string, long>>(); for (int i = 0; i < numberOfFiles; i++) { string[] input = Console.ReadLine().Split(new char[] { ' ', ';', '\\' }, StringSplitOptions.RemoveEmptyEntries); string root = input[0]; string filenameAndExt = input[input.Length - 2]; long size = long.Parse(input[input.Length - 1]); if (!files.ContainsKey(root)) { files[root] = new Dictionary<string, long>(); } files[root][filenameAndExt] = size; } string[] query = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string queryExtension = query[0]; string queryRoot = query[query.Length-1]; if (files.ContainsKey(queryRoot)) { var extractedFiles = files.Where(x => x.Key == queryRoot).ToDictionary(x => x.Key, x => x.Value); var count = 0; foreach (var item in extractedFiles[queryRoot].OrderByDescending(x => x.Value).ThenBy(x => x.Key)) { var fileParams = item.Key.Split('.').ToArray(); string filename = fileParams[0]; string ext = fileParams[fileParams.Length - 1]; if (queryExtension == ext) { Console.WriteLine("{0} - {1} KB", item.Key, item.Value); count++; } } if (count == 0) { Console.WriteLine("No"); } } /* else { Console.WriteLine("No"); }*/ } } }
{ "content_hash": "5a768d416486fe5bc63d354dcd61ab69", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 128, "avg_line_length": 32.6764705882353, "alnum_prop": 0.46624662466246625, "repo_name": "MiraNedeva/SoftUni", "id": "c8203cc4271887566ddcb5c0c2db922eddb0e19a", "size": "2224", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Fundamentals Exams/Files/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "594560" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com" rel="preconnect" crossorigin=""> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700%7CRoboto+Mono:400,500,700&display=fallback"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_stability_method" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_stability_method.html" /> <link rel="prev" title="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smooth_method" href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smooth_method.html" /> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.11.0</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels 0.11.0</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-set-smoother-output--page-root">statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output<a class="headerlink" href="#generated-statsmodels-tsa-statespace-simulation-smoother-simulationsmoother-set-smoother-output--page-root" title="Permalink to this headline">¶</a></h1> <dl class="method"> <dt id="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output"> <code class="sig-prename descclassname">SimulationSmoother.</code><code class="sig-name descname">set_smoother_output</code><span class="sig-paren">(</span><em class="sig-param">smoother_output=None</em>, <em class="sig-param">**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output" title="Permalink to this definition">¶</a></dt> <dd><p>Set the smoother output</p> <p>The smoother can produce several types of results. The smoother output variable controls which are calculated and returned.</p> <dl class="field-list"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl> <dt><strong>smoother_output</strong><span class="classifier"><a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><code class="docutils literal notranslate"><span class="pre">int</span></code></a>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">optional</span></code></span></dt><dd><p>Bitmask value to set the smoother output to. See notes for details.</p> </dd> <dt><strong>**kwargs</strong></dt><dd><p>Keyword arguments may be used to influence the smoother output by setting individual boolean flags. See notes for details.</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>The smoother output is defined by a collection of boolean flags, and is internally stored as a bitmask. The methods available are:</p> <dl class="simple"> <dt>SMOOTHER_STATE = 0x01</dt><dd><p>Calculate and return the smoothed states.</p> </dd> <dt>SMOOTHER_STATE_COV = 0x02</dt><dd><p>Calculate and return the smoothed state covariance matrices.</p> </dd> <dt>SMOOTHER_STATE_AUTOCOV = 0x10</dt><dd><p>Calculate and return the smoothed state lag-one autocovariance matrices.</p> </dd> <dt>SMOOTHER_DISTURBANCE = 0x04</dt><dd><p>Calculate and return the smoothed state and observation disturbances.</p> </dd> <dt>SMOOTHER_DISTURBANCE_COV = 0x08</dt><dd><p>Calculate and return the covariance matrices for the smoothed state and observation disturbances.</p> </dd> <dt>SMOOTHER_ALL</dt><dd><p>Calculate and return all results.</p> </dd> </dl> <p>If the bitmask is set directly via the <cite>smoother_output</cite> argument, then the full method must be provided.</p> <p>If keyword arguments are used to set individual boolean flags, then the lowercase of the method must be used as an argument name, and the value is the desired value of the boolean flag (True or False).</p> <p>Note that the smoother output may also be specified by directly modifying the class attributes which are defined similarly to the keyword arguments.</p> <p>The default smoother output is SMOOTHER_ALL.</p> <p>If performance is a concern, only those results which are needed should be specified as any results that are not specified will not be calculated. For example, if the smoother output is set to only include SMOOTHER_STATE, the smoother operates much more quickly than if all output is required.</p> <p class="rubric">Examples</p> <div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">statsmodels.tsa.statespace.kalman_smoother</span> <span class="k">as</span> <span class="nn">ks</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span> <span class="o">=</span> <span class="n">ks</span><span class="o">.</span><span class="n">KalmanSmoother</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">smoother_output</span> <span class="go">15</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">set_smoother_output</span><span class="p">(</span><span class="n">smoother_output</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">smoother_state</span> <span class="o">=</span> <span class="kc">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">smoother_output</span> <span class="go">1</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">smoother_state</span> <span class="go">True</span> </pre></div> </div> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smooth_method.html" title="Material" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smooth_method </span> </div> </a> <a href="statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_stability_method.html" title="Admonition" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_stability_method </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Jan 22, 2020. <br/> Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.3.1. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "265d15b91a0fd326405a35b7619a9281", "timestamp": "", "source": "github", "line_count": 471, "max_line_length": 999, "avg_line_length": 47.524416135881104, "alnum_prop": 0.635319871336669, "repo_name": "statsmodels/statsmodels.github.io", "id": "05a0fa4b497e83f82f1fc84f3ec57b6ae3b40e1e", "size": "22388", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.11.0/generated/statsmodels.tsa.statespace.simulation_smoother.SimulationSmoother.set_smoother_output.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
module.exports = { '@desiredCapabilities': { name: 'test-Name' }, demoTest: function (client) { client.assert.equal(client.options.desiredCapabilities.name, 'test-Name'); client.url('http://localhost') .assert.elementPresent('#weblogin'); }, after: function (client) { client.end(); } };
{ "content_hash": "6f3cd8ad484bca6230579abd1f4e7f94", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 78, "avg_line_length": 20.625, "alnum_prop": 0.6212121212121212, "repo_name": "nightwatchjs/nightwatch", "id": "bdb1ea93bae3528a98b0d90641857322e210d31f", "size": "330", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "test/sampletests/mixed-files/sampleJs.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25616" }, { "name": "EJS", "bytes": "22775" }, { "name": "Gherkin", "bytes": "2090" }, { "name": "JavaScript", "bytes": "2406040" }, { "name": "TypeScript", "bytes": "1063" }, { "name": "Vue", "bytes": "1502" } ], "symlink_target": "" }
#include <sys/cdefs.h> __FBSDID("$FreeBSD: soc2013/dpl/head/lib/libutil/login_cap.c 184676 2008-11-04 13:49:53Z des $"); #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/param.h> #include <errno.h> #include <fcntl.h> #include <libutil.h> #include <login_cap.h> #include <pwd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <unistd.h> /* * allocstr() * Manage a single static pointer for handling a local char* buffer, * resizing as necessary to contain the string. * * allocarray() * Manage a static array for handling a group of strings, resizing * when necessary. */ static int lc_object_count = 0; static size_t internal_stringsz = 0; static char * internal_string = NULL; static size_t internal_arraysz = 0; static const char ** internal_array = NULL; static char path_login_conf[] = _PATH_LOGIN_CONF; static char * allocstr(const char *str) { char *p; size_t sz = strlen(str) + 1; /* realloc() only if necessary */ if (sz <= internal_stringsz) p = strcpy(internal_string, str); else if ((p = realloc(internal_string, sz)) != NULL) { internal_stringsz = sz; internal_string = strcpy(p, str); } return p; } static const char ** allocarray(size_t sz) { static const char **p; if (sz <= internal_arraysz) p = internal_array; else if ((p = realloc(internal_array, sz * sizeof(char*))) != NULL) { internal_arraysz = sz; internal_array = p; } return p; } /* * arrayize() * Turn a simple string <str> separated by any of * the set of <chars> into an array. The last element * of the array will be NULL, as is proper. * Free using freearraystr() */ static const char ** arrayize(const char *str, const char *chars, int *size) { int i; char *ptr; const char *cptr; const char **res = NULL; /* count the sub-strings */ for (i = 0, cptr = str; *cptr; i++) { int count = strcspn(cptr, chars); cptr += count; if (*cptr) ++cptr; } /* alloc the array */ if ((ptr = allocstr(str)) != NULL) { if ((res = allocarray(++i)) == NULL) free((void *)(uintptr_t)(const void *)str); else { /* now split the string */ i = 0; while (*ptr) { int count = strcspn(ptr, chars); res[i++] = ptr; ptr += count; if (*ptr) *ptr++ = '\0'; } res[i] = NULL; } } if (size) *size = i; return res; } /* * login_close() * Frees up all resources relating to a login class * */ void login_close(login_cap_t * lc) { if (lc) { free(lc->lc_style); free(lc->lc_class); free(lc->lc_cap); free(lc); if (--lc_object_count == 0) { free(internal_string); free(internal_array); internal_array = NULL; internal_arraysz = 0; internal_string = NULL; internal_stringsz = 0; cgetclose(); } } } /* * login_getclassbyname() * Get the login class by its name. * If the name given is NULL or empty, the default class * LOGIN_DEFCLASS (i.e., "default") is fetched. * If the name given is LOGIN_MECLASS and * 'pwd' argument is non-NULL and contains an non-NULL * dir entry, then the file _FILE_LOGIN_CONF is picked * up from that directory and used before the system * login database. In that case the system login database * is looked up using LOGIN_MECLASS, too, which is a bug. * Return a filled-out login_cap_t structure, including * class name, and the capability record buffer. */ login_cap_t * login_getclassbyname(char const *name, const struct passwd *pwd) { login_cap_t *lc; if ((lc = malloc(sizeof(login_cap_t))) != NULL) { int r, me, i = 0; uid_t euid = 0; gid_t egid = 0; const char *msg = NULL; const char *dir; char userpath[MAXPATHLEN]; static char *login_dbarray[] = { NULL, NULL, NULL }; me = (name != NULL && strcmp(name, LOGIN_MECLASS) == 0); dir = (!me || pwd == NULL) ? NULL : pwd->pw_dir; /* * Switch to user mode before checking/reading its ~/.login_conf * - some NFSes have root read access disabled. * * XXX: This fails to configure additional groups. */ if (dir) { euid = geteuid(); egid = getegid(); (void)setegid(pwd->pw_gid); (void)seteuid(pwd->pw_uid); } if (dir && snprintf(userpath, MAXPATHLEN, "%s/%s", dir, _FILE_LOGIN_CONF) < MAXPATHLEN) { if (_secure_path(userpath, pwd->pw_uid, pwd->pw_gid) != -1) login_dbarray[i++] = userpath; } /* * XXX: Why to add the system database if the class is `me'? */ if (_secure_path(path_login_conf, 0, 0) != -1) login_dbarray[i++] = path_login_conf; login_dbarray[i] = NULL; memset(lc, 0, sizeof(login_cap_t)); lc->lc_cap = lc->lc_class = lc->lc_style = NULL; if (name == NULL || *name == '\0') name = LOGIN_DEFCLASS; switch (cgetent(&lc->lc_cap, login_dbarray, name)) { case -1: /* Failed, entry does not exist */ if (me) break; /* Don't retry default on 'me' */ if (i == 0) r = -1; else if ((r = open(login_dbarray[0], O_RDONLY)) >= 0) close(r); /* * If there's at least one login class database, * and we aren't searching for a default class * then complain about a non-existent class. */ if (r >= 0 || strcmp(name, LOGIN_DEFCLASS) != 0) syslog(LOG_ERR, "login_getclass: unknown class '%s'", name); /* fall-back to default class */ name = LOGIN_DEFCLASS; msg = "%s: no default/fallback class '%s'"; if (cgetent(&lc->lc_cap, login_dbarray, name) != 0 && r >= 0) break; /* FALLTHROUGH - just return system defaults */ case 0: /* success! */ if ((lc->lc_class = strdup(name)) != NULL) { if (dir) { (void)seteuid(euid); (void)setegid(egid); } ++lc_object_count; return lc; } msg = "%s: strdup: %m"; break; case -2: msg = "%s: retrieving class information: %m"; break; case -3: msg = "%s: 'tc=' reference loop '%s'"; break; case 1: msg = "couldn't resolve 'tc=' reference in '%s'"; break; default: msg = "%s: unexpected cgetent() error '%s': %m"; break; } if (dir) { (void)seteuid(euid); (void)setegid(egid); } if (msg != NULL) syslog(LOG_ERR, msg, "login_getclass", name); free(lc); } return NULL; } /* * login_getclass() * Get the login class for the system (only) login class database. * Return a filled-out login_cap_t structure, including * class name, and the capability record buffer. */ login_cap_t * login_getclass(const char *cls) { return login_getclassbyname(cls, NULL); } /* * login_getpwclass() * Get the login class for a given password entry from * the system (only) login class database. * If the password entry's class field is not set, or * the class specified does not exist, then use the * default of LOGIN_DEFCLASS (i.e., "default") for an unprivileged * user or that of LOGIN_DEFROOTCLASS (i.e., "root") for a super-user. * Return a filled-out login_cap_t structure, including * class name, and the capability record buffer. */ login_cap_t * login_getpwclass(const struct passwd *pwd) { const char *cls = NULL; if (pwd != NULL) { cls = pwd->pw_class; if (cls == NULL || *cls == '\0') cls = (pwd->pw_uid == 0) ? LOGIN_DEFROOTCLASS : LOGIN_DEFCLASS; } /* * XXX: pwd should be unused by login_getclassbyname() unless cls is `me', * so NULL can be passed instead of pwd for more safety. */ return login_getclassbyname(cls, pwd); } /* * login_getuserclass() * Get the `me' login class, allowing user overrides via ~/.login_conf. * Note that user overrides are allowed only in the `me' class. */ login_cap_t * login_getuserclass(const struct passwd *pwd) { return login_getclassbyname(LOGIN_MECLASS, pwd); } /* * login_getcapstr() * Given a login_cap entry, and a capability name, return the * value defined for that capability, a default if not found, or * an error string on error. */ const char * login_getcapstr(login_cap_t *lc, const char *cap, const char *def, const char *error) { char *res; int ret; if (lc == NULL || cap == NULL || lc->lc_cap == NULL || *cap == '\0') return def; if ((ret = cgetstr(lc->lc_cap, cap, &res)) == -1) return def; return (ret >= 0) ? res : error; } /* * login_getcaplist() * Given a login_cap entry, and a capability name, return the * value defined for that capability split into an array of * strings. */ const char ** login_getcaplist(login_cap_t *lc, const char *cap, const char *chars) { const char *lstring; if (chars == NULL) chars = ", \t"; if ((lstring = login_getcapstr(lc, cap, NULL, NULL)) != NULL) return arrayize(lstring, chars, NULL); return NULL; } /* * login_getpath() * From the login_cap_t <lc>, get the capability <cap> which is * formatted as either a space or comma delimited list of paths * and append them all into a string and separate by semicolons. * If there is an error of any kind, return <error>. */ const char * login_getpath(login_cap_t *lc, const char *cap, const char *error) { const char *str; char *ptr; int count; str = login_getcapstr(lc, cap, NULL, NULL); if (str == NULL) return error; ptr = __DECONST(char *, str); /* XXXX Yes, very dodgy */ while (*ptr) { count = strcspn(ptr, ", \t"); ptr += count; if (*ptr) *ptr++ = ':'; } return str; } static int isinfinite(const char *s) { static const char *infs[] = { "infinity", "inf", "unlimited", "unlimit", "-1", NULL }; const char **i = &infs[0]; while (*i != NULL) { if (strcasecmp(s, *i) == 0) return 1; ++i; } return 0; } static u_quad_t rmultiply(u_quad_t n1, u_quad_t n2) { u_quad_t m, r; int b1, b2; static int bpw = 0; /* Handle simple cases */ if (n1 == 0 || n2 == 0) return 0; if (n1 == 1) return n2; if (n2 == 1) return n1; /* * sizeof() returns number of bytes needed for storage. * This may be different from the actual number of useful bits. */ if (!bpw) { bpw = sizeof(u_quad_t) * 8; while (((u_quad_t)1 << (bpw-1)) == 0) --bpw; } /* * First check the magnitude of each number. If the sum of the * magnatude is way to high, reject the number. (If this test * is not done then the first multiply below may overflow.) */ for (b1 = bpw; (((u_quad_t)1 << (b1-1)) & n1) == 0; --b1) ; for (b2 = bpw; (((u_quad_t)1 << (b2-1)) & n2) == 0; --b2) ; if (b1 + b2 - 2 > bpw) { errno = ERANGE; return (UQUAD_MAX); } /* * Decompose the multiplication to be: * h1 = n1 & ~1 * h2 = n2 & ~1 * l1 = n1 & 1 * l2 = n2 & 1 * (h1 + l1) * (h2 + l2) * (h1 * h2) + (h1 * l2) + (l1 * h2) + (l1 * l2) * * Since h1 && h2 do not have the low bit set, we can then say: * * (h1>>1 * h2>>1 * 4) + ... * * So if (h1>>1 * h2>>1) > (1<<(bpw - 2)) then the result will * overflow. * * Finally, if MAX - ((h1 * l2) + (l1 * h2) + (l1 * l2)) < (h1*h2) * then adding in residual amout will cause an overflow. */ m = (n1 >> 1) * (n2 >> 1); if (m >= ((u_quad_t)1 << (bpw-2))) { errno = ERANGE; return (UQUAD_MAX); } m *= 4; r = (n1 & n2 & 1) + (n2 & 1) * (n1 & ~(u_quad_t)1) + (n1 & 1) * (n2 & ~(u_quad_t)1); if ((u_quad_t)(m + r) < m) { errno = ERANGE; return (UQUAD_MAX); } m += r; return (m); } /* * login_getcaptime() * From the login_cap_t <lc>, get the capability <cap>, which is * formatted as a time (e.g., "<cap>=10h3m2s"). If <cap> is not * present in <lc>, return <def>; if there is an error of some kind, * return <error>. */ rlim_t login_getcaptime(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error) { char *res, *ep, *oval; int r; rlim_t tot; errno = 0; if (lc == NULL || lc->lc_cap == NULL) return def; /* * Look for <cap> in lc_cap. * If it's not there (-1), return <def>. * If there's an error, return <error>. */ if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1) return def; else if (r < 0) { errno = ERANGE; return error; } /* "inf" and "infinity" are special cases */ if (isinfinite(res)) return RLIM_INFINITY; /* * Now go through the string, turning something like 1h2m3s into * an integral value. Whee. */ errno = 0; tot = 0; oval = res; while (*res) { rlim_t tim = strtoq(res, &ep, 0); rlim_t mult = 1; if (ep == NULL || ep == res || errno != 0) { invalid: syslog(LOG_WARNING, "login_getcaptime: class '%s' bad value %s=%s", lc->lc_class, cap, oval); errno = ERANGE; return error; } /* Look for suffixes */ switch (*ep++) { case 0: ep--; break; /* end of string */ case 's': case 'S': /* seconds */ break; case 'm': case 'M': /* minutes */ mult = 60; break; case 'h': case 'H': /* hours */ mult = 60L * 60L; break; case 'd': case 'D': /* days */ mult = 60L * 60L * 24L; break; case 'w': case 'W': /* weeks */ mult = 60L * 60L * 24L * 7L; break; case 'y': case 'Y': /* 365-day years */ mult = 60L * 60L * 24L * 365L; break; default: goto invalid; } res = ep; tot += rmultiply(tim, mult); if (errno) goto invalid; } return tot; } /* * login_getcapnum() * From the login_cap_t <lc>, extract the numerical value <cap>. * If it is not present, return <def> for a default, and return * <error> if there is an error. * Like login_getcaptime(), only it only converts to a number, not * to a time; "infinity" and "inf" are 'special.' */ rlim_t login_getcapnum(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error) { char *ep, *res; int r; rlim_t val; if (lc == NULL || lc->lc_cap == NULL) return def; /* * For BSDI compatibility, try for the tag=<val> first */ if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1) { long lval; /* string capability not present, so try for tag#<val> as numeric */ if ((r = cgetnum(lc->lc_cap, cap, &lval)) == -1) return def; /* Not there, so return default */ else if (r >= 0) return (rlim_t)lval; } if (r < 0) { errno = ERANGE; return error; } if (isinfinite(res)) return RLIM_INFINITY; errno = 0; val = strtoq(res, &ep, 0); if (ep == NULL || ep == res || errno != 0) { syslog(LOG_WARNING, "login_getcapnum: class '%s' bad value %s=%s", lc->lc_class, cap, res); errno = ERANGE; return error; } return val; } /* * login_getcapsize() * From the login_cap_t <lc>, extract the capability <cap>, which is * formatted as a size (e.g., "<cap>=10M"); it can also be "infinity". * If not present, return <def>, or <error> if there is an error of * some sort. */ rlim_t login_getcapsize(login_cap_t *lc, const char *cap, rlim_t def, rlim_t error) { char *ep, *res, *oval; int r; rlim_t tot; if (lc == NULL || lc->lc_cap == NULL) return def; if ((r = cgetstr(lc->lc_cap, cap, &res)) == -1) return def; else if (r < 0) { errno = ERANGE; return error; } if (isinfinite(res)) return RLIM_INFINITY; errno = 0; tot = 0; oval = res; while (*res) { rlim_t siz = strtoq(res, &ep, 0); rlim_t mult = 1; if (ep == NULL || ep == res || errno != 0) { invalid: syslog(LOG_WARNING, "login_getcapsize: class '%s' bad value %s=%s", lc->lc_class, cap, oval); errno = ERANGE; return error; } switch (*ep++) { case 0: /* end of string */ ep--; break; case 'b': case 'B': /* 512-byte blocks */ mult = 512; break; case 'k': case 'K': /* 1024-byte Kilobytes */ mult = 1024; break; case 'm': case 'M': /* 1024-k kbytes */ mult = 1024 * 1024; break; case 'g': case 'G': /* 1Gbyte */ mult = 1024 * 1024 * 1024; break; case 't': case 'T': /* 1TBte */ mult = 1024LL * 1024LL * 1024LL * 1024LL; break; default: goto invalid; } res = ep; tot += rmultiply(siz, mult); if (errno) goto invalid; } return tot; } /* * login_getcapbool() * From the login_cap_t <lc>, check for the existance of the capability * of <cap>. Return <def> if <lc>->lc_cap is NULL, otherwise return * the whether or not <cap> exists there. */ int login_getcapbool(login_cap_t *lc, const char *cap, int def) { if (lc == NULL || lc->lc_cap == NULL) return def; return (cgetcap(lc->lc_cap, cap, ':') != NULL); } /* * login_getstyle() * Given a login_cap entry <lc>, and optionally a type of auth <auth>, * and optionally a style <style>, find the style that best suits these * rules: * 1. If <auth> is non-null, look for an "auth-<auth>=" string * in the capability; if not present, default to "auth=". * 2. If there is no auth list found from (1), default to * "passwd" as an authorization list. * 3. If <style> is non-null, look for <style> in the list of * authorization methods found from (2); if <style> is NULL, default * to LOGIN_DEFSTYLE ("passwd"). * 4. If the chosen style is found in the chosen list of authorization * methods, return that; otherwise, return NULL. * E.g.: * login_getstyle(lc, NULL, "ftp"); * login_getstyle(lc, "login", NULL); * login_getstyle(lc, "skey", "network"); */ const char * login_getstyle(login_cap_t *lc, const char *style, const char *auth) { int i; const char **authtypes = NULL; char *auths= NULL; char realauth[64]; static const char *defauthtypes[] = { LOGIN_DEFSTYLE, NULL }; if (auth != NULL && *auth != '\0') { if (snprintf(realauth, sizeof realauth, "auth-%s", auth) < (int)sizeof(realauth)) authtypes = login_getcaplist(lc, realauth, NULL); } if (authtypes == NULL) authtypes = login_getcaplist(lc, "auth", NULL); if (authtypes == NULL) authtypes = defauthtypes; /* * We have at least one authtype now; auths is a comma-separated * (or space-separated) list of authentication types. We have to * convert from this to an array of char*'s; authtypes then gets this. */ i = 0; if (style != NULL && *style != '\0') { while (authtypes[i] != NULL && strcmp(style, authtypes[i]) != 0) i++; } lc->lc_style = NULL; if (authtypes[i] != NULL && (auths = strdup(authtypes[i])) != NULL) lc->lc_style = auths; if (lc->lc_style != NULL) lc->lc_style = strdup(lc->lc_style); return lc->lc_style; }
{ "content_hash": "111493bfc42c1265a548e4e079ada2e3", "timestamp": "", "source": "github", "line_count": 793, "max_line_length": 97, "avg_line_length": 23.402269861286253, "alnum_prop": 0.5796422028235801, "repo_name": "dplbsd/soc2013", "id": "c3a976fdd38719381f79c17c7f33c252ce7b6830", "size": "19739", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "head/lib/libutil/login_cap.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "AGS Script", "bytes": "62471" }, { "name": "Assembly", "bytes": "4478661" }, { "name": "Awk", "bytes": "278525" }, { "name": "Batchfile", "bytes": "20417" }, { "name": "C", "bytes": "383420305" }, { "name": "C++", "bytes": "72796771" }, { "name": "CSS", "bytes": "109748" }, { "name": "ChucK", "bytes": "39" }, { "name": "D", "bytes": "3784" }, { "name": "DIGITAL Command Language", "bytes": "10640" }, { "name": "DTrace", "bytes": "2311027" }, { "name": "Emacs Lisp", "bytes": "65902" }, { "name": "EmberScript", "bytes": "286" }, { "name": "Forth", "bytes": "184405" }, { "name": "GAP", "bytes": "72156" }, { "name": "Groff", "bytes": "32248806" }, { "name": "HTML", "bytes": "6749816" }, { "name": "IGOR Pro", "bytes": "6301" }, { "name": "Java", "bytes": "112547" }, { "name": "KRL", "bytes": "4950" }, { "name": "Lex", "bytes": "398817" }, { "name": "Limbo", "bytes": "3583" }, { "name": "Logos", "bytes": "187900" }, { "name": "Makefile", "bytes": "3551839" }, { "name": "Mathematica", "bytes": "9556" }, { "name": "Max", "bytes": "4178" }, { "name": "Module Management System", "bytes": "817" }, { "name": "NSIS", "bytes": "3383" }, { "name": "Objective-C", "bytes": "836351" }, { "name": "PHP", "bytes": "6649" }, { "name": "Perl", "bytes": "5530761" }, { "name": "Perl6", "bytes": "41802" }, { "name": "PostScript", "bytes": "140088" }, { "name": "Prolog", "bytes": "29514" }, { "name": "Protocol Buffer", "bytes": "61933" }, { "name": "Python", "bytes": "299247" }, { "name": "R", "bytes": "764" }, { "name": "Rebol", "bytes": "738" }, { "name": "Ruby", "bytes": "45958" }, { "name": "Scilab", "bytes": "197" }, { "name": "Shell", "bytes": "10501540" }, { "name": "SourcePawn", "bytes": "463194" }, { "name": "SuperCollider", "bytes": "80208" }, { "name": "Tcl", "bytes": "80913" }, { "name": "TeX", "bytes": "719821" }, { "name": "VimL", "bytes": "22201" }, { "name": "XS", "bytes": "25451" }, { "name": "XSLT", "bytes": "31488" }, { "name": "Yacc", "bytes": "1857830" } ], "symlink_target": "" }