    type MaxReserves = ();
    type ReserveIdentifier = ();
}

parameter_types! {
    pub const MinHandleLen: u32 = DEFAULT_MIN_HANDLE_LEN;
    pub const MaxHandleLen: u32 = DEFAULT_MAX_HANDLE_LEN;
}

impl pallet_utils::Config for Test {
    type Event = Event;
    type Currency = Balances;
    type MinHandleLen = MinHandleLen;
    type MaxHandleLen = MaxHandleLen;
}

impl Config for Test {
    type Event = Event;
    type Currency = Balances;
}

pub(crate) type AccountId = u64;
pub(crate) type BlockNumber = u64;
pub(crate) type Balance = u64;

pub struct ExtBuilder;

impl ExtBuilder {
    fn configure_storages(storage: &mut Storage) {
        let mut faucet_accounts = Vec::new();
        // FAUCET9 should have no balance
        for faucet in FAUCET1..=FAUCET8 {
            faucet_accounts.push(faucet);
        }

        let _ = pallet_balances::GenesisConfig::<Test> {
            balances: faucet_accounts.iter().cloned().map(|k|(k, FAUCET_INITIAL_BALANCE)).collect(),
        }.assimilate_storage(storage);
    }

    pub fn build() -> TestExternalities {
        let mut storage = system::GenesisConfig::default()
            .build_storage::<Test>()
            .unwrap();

        Self::configure_storages(&mut storage);

        let mut ext = TestExternalities::from(storage);
        ext.execute_with(|| System::set_block_number(1));

        ext
    }

    pub fn build_with_faucet() -> TestExternalities {
        let mut storage = system::GenesisConfig::default()
            .build_storage::<Test>()
            .unwrap();

        Self::configure_storages(&mut storage);

        let mut ext = TestExternalities::from(storage);
        ext.execute_with(|| {
            System::set_block_number(1);

            assert_ok!(_add_default_faucet());
        });

        ext
    }

    // TODO do we really need this func? it's much clearer to call _do_default_drip() in a few tests directly.
    pub fn build_with_one_default_drip() -> TestExternalities {
        let mut storage = system::GenesisConfig::default()
            .build_storage::<Test>()
            .unwrap();

        Self::configure_storages(&mut storage);

        let mut ext = TestExternalities::from(storage);
        ext.execute_with(|| {
            System::set_block_number(1);

            assert_ok!(_add_default_faucet());

            System::set_block_number(INITIAL_BLOCK_NUMBER);
            assert_ok!(_do_default_drip());
        });

        ext
    }
}

pub(crate) const FAUCET_INITIAL_BALANCE: Balance = 400;

pub(crate) const FAUCET1: AccountId = 1;
pub(crate) const FAUCET2: AccountId = 2;
pub(crate) const FAUCET8: AccountId = 8;
pub(crate) const FAUCET9: AccountId = 9;

pub(crate) const ACCOUNT1: AccountId = 11;

pub(crate) const INITIAL_BLOCK_NUMBER: BlockNumber = 20;

pub(crate) fn default_faucet() -> Faucet<Test> {
    Faucet {
        enabled: true,
        period: 100,
        period_limit: 50,
        drip_limit: 25


ationResult()
        data class Invalid(val errors: List<String>) : ValidationResult()
    }
}
package dev.joseluisgs

// Funcion
fun sumar(a: Int, b: Int) = a + b

// Funcion Anonima
val suma: (Int, Int) -> Int = fun(a: Int, b: Int) = a + b
val multiply: (Int, Int) -> Int = fun(a: Int, b: Int) = a * b

// Funcion Lambda
val divide: (Int, Int) -> Int = { a: Int, b: Int -> a / b }

// Funcion de orden superior, que recibe funciones como parámetros
fun operar(a: Int, b: Int, operacion: (Int, Int) -> Int): Int {
    return operacion(a, b)
}

fun main() {
    var resultado = sumar(1, 2)
    println("El resultado es $resultado")
    resultado = suma(1, 2)
    println("El resultado es $resultado")
    var pepe: (Int, Int) -> Int = suma
    resultado = pepe(1, 2)
    println("El resultado es $resultado")
    pepe = multiply
    resultado = pepe(1, 2)
    println("El resultado es $resultado")
    pepe = divide
    resultado = pepe(1, 2)
    println("El resultado es $resultado")
    resultado = divide(1, 2)
    println("El resultado es $resultado")

    resultado = operar(1, 2, suma)
    println("El resultado es $resultado")

    resultado = operar(1, 2, multiply)
    println("El resultado es $resultado")

    resultado = operar(1, 2, divide)
    println("El resultado es $resultado")

    resultado = operar(1, 2, fun(a: Int, b: Int) = a + b)
    println("El resultado es $resultado")

    resultado = operar(1, 2, { a, b -> a + b })
    println("El resultado es $resultado")

    // Cuando la función es el último parámetro, podemos sacarla fuera de los paréntesis
    resultado = operar(1, 2) { a, b -> a + b }
    println("El resultado es $resultado")

    resultado = operar(1, 2) { a, b -> a * b }
    println("El resultado es $resultado")

    resultado = operar(1, 2) { a, b -> a / b }
    println("El resultado es $resultado")

    resultado = operar(1, 2) { a, b -> a % b }
    println("El resultado es $resultado")

    resultado = operar(1, 2) { a, b -> a / b + a % b }
    println("El resultado es $resultado")

    // Podemos poner tantas líneas como queramos,
    // pero el resultado será el de la última
    resultado = operar(1, 2) { a, b ->
        var res = a / b + a % b + a * b + a - b + 500
        res += 1000
        res / 200
        res
    }
    println("El resultado es $resultado")

    repeat(10) {
        println("Hola $it")
    }

    myRepeat(10) {
        println("Hola $it")
    }

    val intArray = intArrayOf(1, 2, 3, 4, 5)

    for (i in intArray) {
        println(i)
    }

    myForEach(intArray) {
        println(it)
    }

    myForEach(intArray) {
        if (it % 2 == 0) {
            println("$it es par")
        }
    }

    val res = myFilter(intArray) {
        it % 2 == 0
    }
    println(res.contentToString())

    val res2 = myFilter(intArray) {
        it % 2 != 0
    }
    println(res2.contentToString())

    val res3 = myFilter(intArray) {
        isPrime(it)
    }
    println(res3.contentToString())

    val res4 = myMap(intArray) {
        it * 2
    }
    println(res4.contentToString())

    val res5 = myMap(intArray) {
        it * 3
    }
    println(res5.contentToString())

    val res6 = myMap(


ing handled (case where the OS tick interrupted another */	\
    /* interrupt handler (which was of a higher priority level but decided to lower its priority */	\
    /* level and allow other lower interrupt level to occur). */									\
    /* In this case it's of no use to switch context and restore a new SP because we purposedly */	\
    /* did not previously save SP in its TCB. */													\
    "ld.w    r0, sp[9*4]																			\n\t" /* Read SR in stack */\
    "bfextu  r0, r0, 22, 3																			\n\t" /* Extract the mode bits to R0. */\
    "cp.w    r0, 1																					\n\t" /* Compare the mode bits with supervisor mode(b'001) */\
    "brhi    LABEL_ISR_SKIP_RESTORE_CONTEXT_"ASTRINGZ(__LINE__)"									\n\t"\
																									\
    /* If a switch is required then we just need to call */											\
    /* vTaskSwitchContext() as the context has already been */										\
    /* saved. */																					\
    "cp.w    r12, 1																					\n\t" /* Check if Switch context is required. */\
    "brne    LABEL_ISR_RESTORE_CONTEXT_"ASTRINGZ(__LINE__)":C"										\
  );																								\
																									\
  /* A critical section has to be used here because vTaskSwitchContext handles FreeRTOS linked lists. */\
  portENTER_CRITICAL();																				\
  vTaskSwitchContext();																				\
  portEXIT_CRITICAL();																				\
																									\
  __asm__ __volatile__ (																			\
    "LABEL_ISR_RESTORE_CONTEXT_"ASTRINGZ(__LINE__)":												\n\t"\
    /* Restore the context of which ever task is now the highest */									\
    /* priority that is ready to run. */															\
																									\
    /* Restore all registers */																		\
																									\
    /* Set SP to point to new stack */																\
    "mov     r8, LWRD("ASTRINGZ(pxCurrentTCB)")														\n\t"\
    "orh     r8, HWRD("ASTRINGZ(pxCurrentTCB)")														\n\t"\
    "ld.w    r0, r8[0]																				\n\t"\
    "ld.w    sp, r0[0]																				\n"\
																									\
    "LABEL_ISR_SKIP_RESTORE_CONTEXT_"ASTRINGZ(__LINE__)":											\n\t"\
																									\
    /* Restore ulCriticalNesting variable */														\
    "ld.w    r0, sp++																				\n\t"\
    "mov     r8, LWRD("ASTRINGZ(ulCriticalNesting)")												\n\t"\
    "orh     r8, HWRD("ASTRINGZ(ulCriticalNesting)")												\n\t"\
    "st.w    r8[0], r0																				\n\t"\
																									\
    /* Restore R0..R7 */																			\
    "ldm     sp++, r0-r7																			\n\t"\
																									\
    /* Now, the stack should be R8..R12, LR, PC and SR  */											\
    "rete"																							\
  );																								\
																									\
  /* Force import of global symbols from assembly */												\
  ulCriticalNesting;																				\
  pxCurrentTCB;																						\
}

#endif

#define portYIELD()                 {__asm__ __volatile__ ("scall");}

/* Task function macros as described on the FreeRTOS.org WEB site. */
#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )

#ifdef __cplusplus
}
#endif

#endif /* PORTMACRO_H */


rt
      cur_index++;
      ret->indices_[cur_index] = next_stack_start_index + (n_slices-1);
      cur_index++;
    }

    // Bottom Indices
    uint32_t cur_stack_start_index = ( n_stacks - 3 ) * n_slices + 1;
    for (uint32_t j = 0; j < ( n_slices - 1); j++) {
      // First vertex is the top, so first slice vertex starts at 1
      ret->indices_[cur_index] = cur_stack_start_index + j;
      cur_index++;
      ret->indices_[cur_index] = cur_stack_start_index + j + 1;
      cur_index++;
      ret->indices_[cur_index] = n_vert-1;  // Bottom Vertex
      cur_index++;
    }
    ret->indices_[cur_index] = cur_stack_start_index + n_slices - 1;
    cur_index++;
    ret->indices_[cur_index] = cur_stack_start_index;  // Back to first vert
    cur_index++;
    ret->indices_[cur_index] = n_vert-1; // Top Vertex
    cur_index++;

#if defined(DEBUG) || defined(_DEBUG)
    if(cur_index != n_ind) {
      throw std::runtime_error(string("GeometryColoredMesh::makeSphere() -") +
        string(" Internal Error: Didn't create enough indices"));
    }
#endif

    ret->colors_.capacity(n_vert);
    ret->colors_.resize(n_vert);
    for (uint32_t i = 0; i < n_vert; ++i) {
      ret->colors_[i].set(color);
    }

    ret->syncVAO();
  }

  // This function calculates the outside radius of the geometry for a
  // cone with a given number of slices and inside radius.  Very
  // useful to know how far a discrete cone extends beyond a perfect cone.
  float GeometryColoredMesh::calcConeOutsideRadius(uint32_t n_slices,
    float inside_radius) {
    if(n_slices < 3) {
      throw std::runtime_error(string("GeometryColoredMesh::") +
        string("calcConeOutsideRadius()- Error: n_slices < 3"));
    }

    float seperation_angle = 2.0f * static_cast<float>(M_PI) /
      static_cast<float>(n_slices);
    return inside_radius / cos(seperation_angle * 0.5f);
  }

  GeometryColoredMesh* GeometryColoredMesh::makeCone(uint32_t n_slices,
    float height, float inside_radius, const Float3& color) {
    GeometryColoredMesh* ret = new GeometryColoredMesh();

    if(n_slices < 3) {
      throw std::runtime_error(string("GeometryColoredMesh::makeCone()") +
        string("- Error: n_slices < 3"));
    }

    uint32_t n_vert = n_slices + 1 + // base vertices
                      n_slices * 2;  // Each side needs a top vert for the norm
    ret->vertices_.capacity(n_vert);
    ret->vertices_.resize(n_vert);
    ret->normals_.capacity(n_vert);
    ret->normals_.resize(n_vert);

    uint32_t n_ind = (n_slices * 3) + (n_slices * 3);
    ret->indices_.capacity(n_ind);
    ret->indices_.resize(n_ind);

    uint32_t cur_vertex = 0;
    float seperation_angle = 2.0f * static_cast<float>(M_PI) /
      static_cast<float>(n_slices);
    float outside_rad = calcConeOutsideRadius(n_slices, inside_radius);

    // Define the base center vertex
    ret->normals_.at(cur_vertex)->set(0


d]
	if !ok {
		return nil
	}

	return this.refToGroup(gr)
}

func (this *EtcColonRepository) lookupByRequirement(_ context.Context, req *Requirement) *etcPasswdRef {
	if v := req.Name; v != "" {
		n2u := this.nameToUser
		if n2u != nil {
			result, ok := n2u[v]
			if ok {
				return result
			}
		}
	}

	if v := req.Uid; v != nil {
		i2u := this.idToUser
		if i2u != nil {
			result, ok := i2u[*v]
			if ok {
				return result
			}
		}
	}

	return nil
}

func (this *EtcColonRepository) lookupGroupByRequirement(_ context.Context, req *GroupRequirement, mutex sync.Locker) *etcGroupRef {
	if mutex != nil {
		this.mutex.RLock()
		defer this.mutex.RUnlock()
	}

	if v := req.Name; v != "" {
		n2g := this.nameToGroup
		if n2g != nil {
			result, ok := n2g[v]
			if ok {
				return result
			}
		}
	}

	if v := req.Gid; v != nil {
		i2g := this.idToGroup
		if i2g != nil {
			result, ok := i2g[*v]
			if ok {
				return result
			}
		}
	}

	return nil
}

func (this *EtcColonRepository) isRequirementFulfilled(ctx context.Context, req *Requirement, mutex sync.Locker) (*etcPasswdRef, *User, error) {
	if mutex != nil {
		mutex.Lock()
		defer mutex.Unlock()
	}

	existing := this.lookupByRequirement(ctx, req)
	if existing == nil {
		return nil, nil, nil
	}

	if !req.doesFulfilRef(existing) {
		return existing, nil, nil
	}

	existingGroup := this.lookupGroupByRequirement(ctx, &req.Group, nil)
	if existingGroup == nil {
		return existing, nil, nil
	}
	if !req.Group.doesFulfilRef(existingGroup) {
		return existing, nil, nil
	}
	if existingGroup.gid != existing.gid {
		return existing, nil, nil
	}

	var groupRefs []*etcGroupRef
	if u2gs := this.usernameToGroups; u2gs != nil {
		if vs, ok := u2gs[string(existing.etcPasswdEntry.name)]; ok {
			groupRefs = vs
		}
	}

	if len(req.Groups) != len(groupRefs) {
		return existing, nil, nil
	}

	for _, groupRef := range groupRefs {
		atLeastOneMatches := false
		for _, groupReq := range req.Groups {
			if groupReq.doesFulfilRef(groupRef) {
				atLeastOneMatches = true
				break
			}
		}
		if !atLeastOneMatches {
			return existing, nil, nil
		}
	}

	user, err := this.refToUser(ctx, existing)
	return existing, user, err
}

func (this *EtcColonRepository) ensurePreChecks(ctx context.Context, req *Requirement, opts *EnsureOpts, mutex sync.Locker) (existing *etcPasswdRef, user *User, _ EnsureResult, err error) {
	if existing, user, err = this.isRequirementFulfilled(ctx, req, mutex); err != nil {
		return nil, nil, EnsureResultError, err
	} else if user != nil {
		return nil, user, EnsureResultUnchanged, nil
	}

	if existing == nil && !opts.IsCreateAllowed() {
		return nil, nil, EnsureResultError, ErrNoSuchUser
	}

	if !opts.IsModifyAllowed() {
		return nil, nil, EnsureResultError, ErrUser


import numpy as np
import nibabel as nib
from scipy.ndimage import binary_dilation, binary_erosion
from scipy.spatial.distance import directed_hausdorff

def calculate_dsc(seg1, seg2):
    """
    Compute Dice Similarity Coefficient (DSC).
    """
    intersection = np.logical_and(seg1, seg2).sum()
    return (2.0 * intersection) / (seg1.sum() + seg2.sum()) if seg1.sum() + seg2.sum() > 0 else np.nan

def calculate_hd(seg1, seg2):
    """
    Compute Hausdorff Distance (HD).
    """
    seg1_points = np.argwhere(seg1 > 0)
    seg2_points = np.argwhere(seg2 > 0)

    if len(seg1_points) == 0 or len(seg2_points) == 0:
        return np.nan  # Undefined if one segmentation is empty

    return max(
        directed_hausdorff(seg1_points, seg2_points)[0],
        directed_hausdorff(seg2_points, seg1_points)[0]
    )

def calculate_dilated_dsc(seg1, seg2, dilation_iters=1):
    """
    Compute Dilated Dice Similarity Coefficient (dDSC).
    """
    seg1_dilated = binary_dilation(seg1, iterations=dilation_iters)
    seg1_eroded = binary_erosion(seg1, iterations=dilation_iters)
    seg2_dilated = binary_dilation(seg2, iterations=dilation_iters)
    seg2_eroded = binary_erosion(seg2, iterations=dilation_iters)

    seg1_modified = np.logical_or(seg1_dilated, seg1_eroded)
    seg2_modified = np.logical_or(seg2_dilated, seg2_eroded)

    intersection = np.logical_and(seg1_modified, seg2_modified).sum()
    return (2.0 * intersection) / (seg1_modified.sum() + seg2_modified.sum()) if seg1_modified.sum() + seg2_modified.sum() > 0 else np.nan

def calculate_balanced_average_hd(seg1, seg2):
    """
    Compute Balanced Average Hausdorff Distance (baHD).
    """
    seg1_points = np.argwhere(seg1 > 0)
    seg2_points = np.argwhere(seg2 > 0)

    if len(seg1_points) == 0 or len(seg2_points) == 0:
        return np.nan  # Undefined if one segmentation is empty

    hd_1 = directed_hausdorff(seg1_points, seg2_points)[0]
    hd_2 = directed_hausdorff(seg2_points, seg1_points)[0]

    weight1 = len(seg1_points) / (len(seg1_points) + len(seg2_points))
    weight2 = len(seg2_points) / (len(seg1_points) + len(seg2_points))

    return (weight1 * hd_1) + (weight2 * hd_2)


using System.Data;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Oqtane.Databases.Interfaces;
using Oqtane.Migrations.EntityBuilders;
using Oqtane.Repository;

namespace Oqtane.Migrations.Master
{
    [DbContext(typeof(MasterDBContext))]
    [Migration("Master.06.01.05.01")]
    public class UpdateTenantDBType : MultiDatabaseMigration
    {
        public UpdateTenantDBType(IDatabase database) : base(database)
        {
        }

        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // database providers moved to oqtane.server
            var tenantEntityBuilder = new TenantEntityBuilder(migrationBuilder, ActiveDatabase);
            tenantEntityBuilder.UpdateData("DBType", "'Oqtane.Database.SqlServer.SqlServerDatabase, Oqtane.Server'", $"{DelimitName(RewriteName("DBType"))} = '


ng, ConfigExtruder> extruders = {};
  Map<(ConfigFileObjectIdentifiers, String), ConfigPin> outputs = {};
  Map<String, ConfigStepper> steppers = {};
  Map<String, ConfigGcodeMacro> gcodeMacros = {};
  Map<(ConfigFileObjectIdentifiers, String), ConfigLed> leds = {};
  Map<(ConfigFileObjectIdentifiers, String), ConfigFan> fans = {};
  Map<String, ConfigHeaterGeneric> genericHeaters = {};
  List<String>? beaconModels;

  ConfigFile();

  ConfigStepper? get stepperX => steppers['x'];

  ConfigStepper? get stepperY => steppers['y'];

  ConfigFile.parse(this.rawConfig) {
    for (String key in rawConfig.keys) {
      var (cIdentifier, objectName) = key.toKlipperObjectIdentifier();

      Map<String, dynamic> jsonChild = Map.of(rawConfig[key]);

      if (cIdentifier == ConfigFileObjectIdentifiers.heater_bed) {
        configHeaterBed = ConfigHeaterBed.fromJson(rawConfig['heater_bed']);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.printer) {
        configPrinter = ConfigPrinter.fromJson(rawConfig['printer']);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.extruder) {
        if (jsonChild.containsKey('shared_heater')) {
          String sharedHeater = jsonChild['shared_heater'];
          Map<String, dynamic> sharedHeaterConfig = Map.of(rawConfig[sharedHeater]);
          sharedHeaterConfig.removeWhere((key, value) => jsonChild.containsKey(key));
          jsonChild.addAll(sharedHeaterConfig);
        }
        extruders[key] = ConfigExtruder.fromJson(key, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.output_pin) {
        outputs[(cIdentifier!, objectName!)] = ConfigOutput.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.pwm_tool) {
        outputs[(cIdentifier!, objectName!)] = ConfigPwmTool.fromJson(objectName, jsonChild);
      } else if (stepperRegex.hasMatch(key)) {
        var match = stepperRegex.firstMatch(key)!;
        steppers[match.group(1)!] = ConfigStepper.fromJson(match.group(1)!, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.gcode_macro) {
        gcodeMacros[objectName!] = ConfigGcodeMacro.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.dotstar) {
        leds[(cIdentifier!, objectName!)] = ConfigDotstar.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.neopixel) {
        leds[(cIdentifier!, objectName!)] = ConfigNeopixel.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.led) {
        leds[(cIdentifier!, objectName!)] = ConfigDumbLed.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.pca9533 ||
          cIdentifier == ConfigFileObjectIdentifiers.pca9632) {
        //pca9533 and pcapca9632
        leds[(cIdentifier!, objectName!)] = ConfigPcaLed.fromJson(objectName, jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.fan) {
        configPrintCoolingFan = ConfigPrintCoolingFan.fromJson(jsonChild);
      } else if (cIdentifier == ConfigFileObjectIdentifiers.heater_fan) {
        fans[(c


 PlayGlobalSound ( 1 ) end
  if g_Scancode == 3 then PlayGlobalSound ( 2 ) end
  if g_Scancode == 4 then PlayGlobalSound ( 3 ) end
  if g_Scancode == 5 then
   if GetGlobalSoundExist ( 4 ) == 1 then
    PlayGlobalSound ( 4 )
    SetGlobalSoundSpeed ( 4, 66000 )
   end
  end
  if g_Scancode == 6 then
   if GetGlobalSoundPlaying ( 5 ) == 0 then
    PlayGlobalSound ( 5 )
    SetGlobalSoundVolume ( 5, 90 )
   end
  end
  if g_Scancode == 7 then
   if GetGlobalSoundLooping ( 6 ) == 0 then
    LoopGlobalSound ( 6 )
   end
  end
  if g_Scancode == 8 then
   StopGlobalSound ( 1 )
   StopGlobalSound ( 2 )
   StopGlobalSound ( 3 )
   StopGlobalSound ( 4 )
   StopGlobalSound ( 5 )
   StopGlobalSound ( 6 )
  end
 end
end


mp_ca4
/*0x0c9a*/      ldr r2, [pc, #0x1c] /* data_cb8 */
/*0x0c9c*/      ldrb r2, [r2]
/*0x0c9e*/      cbz r2, jump_ca4
/*0x0ca0*/      str r0, [r1, #0x24]
/*0x0ca2*/      b jump_ca6
            jump_ca4:
/*0x0ca4*/      str r0, [r1, #0x28]
            jump_ca6:
/*0x0ca6*/      str r6, [r5, #0x28]
/*0x0ca8*/      b jump_c7c

/*0x0caa*/  .byte 0x00
/*0x0cab*/  .byte 0x00

            data_cac:
/*0x0cac*/  .word 0x200006a4
            data_cb0:
/*0x0cb0*/  .word 0x00002264 /* possible pointer */
            data_cb4:
/*0x0cb4*/  .word 0x400b2000
            data_cb8:
/*0x0cb8*/  .word 0x20000055

            .thumb_func
            call_cbc:
/*0x0cbc*/      push {r4, r5, r6, lr}
/*0x0cbe*/      mov r4, r0
/*0x0cc0*/      bl call_d34
/*0x0cc4*/      ldr r5, [pc, #0x60] /* data_d28 */
/*0x0cc6*/      ldrb r0, [r5]
/*0x0cc8*/      cmp r0, #1
/*0x0cca*/      bne jump_d24
/*0x0ccc*/      ldr r6, [pc, #0x5c] /* data_d2c */
/*0x0cce*/      ldrh r0, [r4, #0x10]
/*0x0cd0*/      sub.w r3, r6, #0x28
/*0x0cd4*/      strh r0, [r6, #0x18]
/*0x0cd6*/      ldr r0, [r4, #0xc]
/*0x0cd8*/      str r0, [r6]
/*0x0cda*/      ldrb r0, [r4, #0x13]
/*0x0cdc*/      lsls r0, r0, #1
/*0x0cde*/      strb r0, [r6, #0x1a]
/*0x0ce0*/      movs r0, #0
/*0x0ce2*/      strb r0, [r6, #0x1b]
/*0x0ce4*/      movs r2, #0xff
/*0x0ce6*/      b jump_cf2
            jump_ce8:
/*0x0ce8*/      adds r1, r3, r0
/*0x0cea*/      .short 0x1c40 /* adds r0, r0, #1 */
/*0x0cec*/      strb r2, [r1, #2]
/*0x0cee*/      strb r2, [r1, #0x14]
/*0x0cf0*/      uxtb r0, r0
            jump_cf2:
/*0x0cf2*/      ldrb r1, [r4, #0x13]
/*0x0cf4*/      cmp r1, r0
/*0x0cf6*/      bhi jump_ce8
/*0x0cf8*/      ldr r0, [r4]
/*0x0cfa*/      str r0, [r6, #0xc]
/*0x0cfc*/      ldr r0, [r4, #4]
/*0x0cfe*/      str r0, [r6, #0


> et dans la colonne de gauche, sélectionnez l\'onglet \"Vendre\". Ensuite, sélectionnez la crypto-monnaie que vous souhaitez échanger en appuyant sur l\'onglet correspondant sur la ligne au-dessus du tableau des annonces. Pour cet exemple, nous choisirons BTC. Vous pouvez affiner davantage vos résultats en saisissant le montant souhaité et modifier la devise, le pays ou le mode de paiement (sélectionnez \"Toutes les offres en ligne\" si vous n\'êtes pas sûr du mode de paiement que vous souhaitez utiliser) dans le champ de recherche. Appuyez sur le bouton bleu avec l\'icône \"Rechercher\".';

  @override
  String guide250Sbnon8722Sbcustodial250Sbsell250Sb3(Object assetName) {
    return 'Après avoir appuyé sur le bouton \"Vendre\", vous verrez plus d\'informations sur l\'annonce, y compris les conditions de l\'échange. Lisez-les avant de soumettre la demande d\'échange, si vous n\'êtes pas d\'accord avec celles-ci, vous pouvez revenir à la page précédente et choisir une autre annonce. Pour démarrer une transaction, saisissez la quantité de $assetName que vous souhaitez vendre et cliquez sur le bouton \"Envoyer une demande de transaction\". Vous verrez à nouveau les conditions de transaction, lisez-les attentivement une fois de plus et assurez-vous que vous êtes d\'accord, puis appuyez sur \"Accepter les conditions et commencer à échanger\".';
  }

  @override
  String get guide250Sbnon8722Sbcustodial250Sbsell250Sb4 => 'Une page de transaction s\'ouvrira dans votre navigateur. Communiquez avec l\'acheteur via le tchat de transaction et fournissez-lui vos informations de paiement.';

  @override
  String get guide250Sbnon8722Sbcustodial250Sbsell250Sb5 => 'Vous serez averti une fois que l\'acheteur aura effectué le paiement. Assurez-vous d\'avoir reçu le paiement et qu\'il s\'agit du bon montant. Une fois que vous avez vérifié que le paiement est correct à 100%, appuyez sur \"Finaliser\".';

  @override
  String guide250Sbnon8722Sbcustodial250Sbsell250Sb6(Object appName) {
    return 'À ce stade, vous serez invité à saisir votre mot de passe $appName actuel. Tapez-le et appuyez sur confirmer. En entrant votre mot de passe, vous générez un portefeuille de règlement et signez la transaction de crypto-monnaie, alors assurez-vous de ne pas oublier ou perdre le mot de passe au moins jusqu\'à ce que la transaction soit réglée.';
  }

  @override
  String get guide250Sbnon8722Sbcustodial250Sbsell250Sb7 => 'Vous verrez que le statut de l\'échange sera passé à \"Traitement\". À ce stade, vous n\'avez rien d\'autre à faire - les jetons de crypto-monnaie seront automatiquement transférés à l\'adresse du portefeuille de règlement de l\'acheteur.';

  @override
  String get guide250Sbnon8722Sbcustodial250Sbsell250Sb8 => 'Ça y est ! Une fois le règlement de la transaction terminé, vous pourrez voir les détails du règlement en développant la section \"Détails de la transaction\" sur la page de la transaction. N\'oubliez pas de laisser une évaluation de votre expérience avec cet acheteur !';

  @override
  String guide250Sbsell250Sbstep8722Sbfive8722Sbtext(Object assetName) {
    return 'Après avoi


7.066,0,0,0-6.392,5.129l-91.46,349.436a4.073,4.073,0,0,0-.229,1.347,3.872,3.872,0,0,0,3.863,3.851c.056,0,.112,0,.169,0h40.968a7.1,7.1,0,0,0,6.392-5.193L639.68,81.2a3.624,3.624,0,0,0,.32-1.475,3.841,3.841,0,0,0-3.821-3.564c-.068,0-.137,0-.206.006ZM371.562,225.236l10.8-41.1a4.369,4.369,0,0,0,.227-1.388,3.869,3.869,0,0,0-3.861-3.842c-.057,0-.113,0-.169,0h-41.1a7.292,7.292,0,0,0-6.391,5.226l-10.834,41.1a4.417,4.417,0,0,0-.26,1.493c0,.069,0,.138,0,.206a3.776,3.776,0,0,0,3.757,3.507c.076,0,.18,0,.3-.012h41.129A7.034,7.034,0,0,0,371.562,225.236Z"]},Wo={prefix:"fab",iconName:"upwork",icon:[641,512,[],"e641","M494.7 295.6c-50.3 0-83.5-38.9-92.8-53.9c11.9-95.3 46.8-125.4 92.8-125.4c45.5 0 80.9 36.4 80.9 89.7s-35.4 89.7-80.9 89.7zm0-237.8c-81.9 0-127.8 53.4-141 108.4c-14.9-28-25.9-65.5-34.5-100.3H206v141c0 51.1-23.3 89-68.8 89s-71.6-37.8-71.6-89l.5-141H.8v141c0 41.1 13.3 78.4 37.6 105.1c25 27.5 59.2 41.8 98.8 41.8c78.8 0 133.8-60.4 133.8-146.9V112.1c8.2 31.2 27.8 91.1 65.3 143.6l-35 199.4h66.4l23.1-141.3c7.6 6.3 15.7 12 24.2 17c22.2 14 47.7 21.9 73.9 22.8c0 0 4 .2 6.1 .2c81.2 0 145.9-62.9 145.9-147.8s-64.8-148.1-146-148.1z"]},Uo={prefix:"fab",iconName:"facebook",icon:[512,512,[62e3],"f09a","M512 256C512 114.6 397.4 0 256 0S0 114.6 0 256C0 376 82.7 476.8 194.2 504.5V334.2H141.4V256h52.8V222.3c0-87.1 39.4-127.5 125-127.5c16.2 0 44.2 3.2 55.7 6.4V172c-6-.6-16.5-1-29.6-1c-42 0-58.2 15.9-58.2 57.2V256h83.6l-14.4 78.2H287V510.1C413.8 494.8 512 386.9 512 256h0z"]},Zo={prefix:"fab",iconName:"gripfire",icon:[384,512,[],"f3ac","M112.5 301.4c0-73.8 105.1-122.5 1


WUudG9WYWx1ZSgpXG4gICAgICAgIDogdW53cmFwcGVkVmFsdWU7XG59XG5cbmV4cG9ydCB7IHJlc29sdmVNb3Rpb25WYWx1ZSB9O1xuIl0sIm5hbWVzIjpbImlzQ3VzdG9tVmFsdWUiLCJpc01vdGlvblZhbHVlIiwicmVzb2x2ZU1vdGlvblZhbHVlIiwidmFsdWUiLCJ1bndyYXBwZWRWYWx1ZSIsImdldCIsInRvVmFsdWUiXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///(ssr)/./node_modules/framer-motion/dist/es/value/utils/resolve-motion-value.mjs\n");

/***/ })

};
;"use strict";
/*
 * ATTENTION: An "eval-source-map" devtool has been used.
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
exports.id = "vendor-chunks/fast-equals";
exports.ids = ["vendor-chunks/fast-equals"];
exports.modules = {

/***/ "(ssr)/./node_modules/fast-equals/dist/esm/index.mjs":
/*!*****************************************************!*\
  !*** ./node_modules/fast-equals/dist/esm/index.mjs ***!
  \*****************************************************/
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {

eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   circularDeepEqual: () => (/* binding */ circularDeepEqual),\n/* harmony export */   circularShallowEqual: () => (/* binding */ circularShallowEqual),\n/* harmony export */   createCustomEqual: () => (/* binding */ createCustomEqual),\n/* harmony export */   deepEqual: () => (/* binding */ deepEqual),\n/* harmony export */   sameValueZeroEqual: () => (/* binding */ sameValueZeroEqual),\n/* harmony export */   shallowEqual: () => (/* binding */ shallowEqual),\n/* harmony export */   strictCircularDeepEqual: () => (/* binding */ strictCircularDeepEqual),\n/* harmony export */   strictCircularShallowEqual: () => (/* binding */ strictCircularShallowEqual),\n/* harmony export */   strictDeepEqual: () => (/* binding */ strictDeepEqual),\n/* harmony export */   strictShallowEqual: () => (/* binding */ strictShallowEqual)\n/* harmony export */ });\nvar getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n/**\n * Combine two comparators into a single comparators.\n */\nfunction combineComparators(comparatorA, comparatorB) {\n    return function isEqual(a, b, state) {\n        return comparatorA(a, b, state) && comparatorB(a, b, state);\n    };\n}\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nfunction createIsCircular(areItemsEqual) {\n    return function isCircular(a, b, state) {\n        if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n            return areItemsEqual(a, b, state);\n        }\n        var cache = state.cache;\


portant}table.dataTable>tbody>tr.child ul.dtr-details{display:inline-block;list-style-type:none;margin:0;padding:0}table.dataTable>tbody>tr.child ul.dtr-details>li{border-bottom:1px solid #efefef;padding:0.5em 0}table.dataTable>tbody>tr.child ul.dtr-details>li:first-child{padding-top:0}table.dataTable>tbody>tr.child ul.dtr-details>li:last-child{border-bottom:none}table.dataTable>tbody>tr.child span.dtr-title{display:inline-block;min-width:75px;font-weight:bold}div.dtr-modal{position:fixed;box-sizing:border-box;top:0;left:0;height:100%;width:100%;z-index:100;padding:10em 1em}div.dtr-modal div.dtr-modal-display{position:absolute;top:0;left:0;bottom:0;right:0;width:50%;height:50%;overflow:auto;margin:auto;z-index:102;overflow:auto;background-color:#f5f5f7;border:1px solid black;border-radius:0.5em;box-shadow:0 12px 30px rgba(0,0,0,0.6)}div.dtr-modal div.dtr-modal-content{position:relative;padding:1em}div.dtr-modal div.dtr-modal-close{position:absolute;top:6px;right:6px;width:22px;height:22px;border:1px solid #eaeaea;background-color:#f9f9f9;text-align:center;border-radius:3px;cursor:pointer;z-index:12}div.dtr-modal div.dtr-modal-close:hover{background-color:#eaeaea}div.dtr-modal div.dtr-modal-background{position:fixed;top:0;left:0;right:0;bottom:0;z-index:101;background:rgba(0,0,0,0.6)}@media screen and (max-width: 767px){div.dtr-modal div.dtr-modal-display{width:95%}}
/*
 * This combined file was created by the DataTables downloader builder:
 *   https://datatables.net/download
 *
 * To rebuild or modify this file with the latest versions of the included
 * software please visit:
 *   https://datatables.net/download/#bs4/dt-1.10.16/af-2.2.2/b-1.4.2/b-colvis-1.4.2/b-flash-1.4.2/b-html5-1.4.2/jszip-2.5.0/pdfmake-0.1.32/b-print-1.4.2/cr-1.4.1/fc-3.2.3/fh-3.1.3/kt-2.3.2/r-2.2.0/rg-1.0.2/rr-1.2.3/sc-1.4.3/sl-1.2.3
 *
 * Included libraries:
 *   JSZip 2.5.0, pdfmake 0.1.32, DataTables 1.10.16, AutoFill 2.2.2, Buttons 1.4.2, Column visibility 1.4.2, Flash export 1.4.2, HTML5 export 1.4.2, Print view 1.4.2, ColReorder 1.4.1, FixedColumns 3.2.3, FixedHeader 3.1.3, KeyTable 2.3.2, Responsive 2.2.0, RowGroup 1.0.2, RowReorder 1.2.3, Scroller 1.4.3, Select 1.2.3
 */

table.dataTable{clear:both;margin-top:6px !important;margin-bottom:6px !important;max-width:none !important;border-collapse:separate !important}table.dataTable td,table.dataTable th{-webkit-box-sizing:content-box;box-sizing:content-box}table.dataTable td.dataTables_empty,table.dataTable th.dataTables_empty{text-align:center}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}div.dataTables


多可以累计获得 120% 的分数。

???+ question "如何提问？"

    [提问的智慧](https://lug.ustc.edu.cn/wiki/doc/smart-questions/)

    以下是一些要点：

    - 提问前，请先 [STFW 和 RTFM](https://lug.ustc.edu.cn/wiki/doc/smart-questions/#rtfm-%E5%92%8C-stfw%E5%A6%82%E4%BD%95%E7%9F%A5%E9%81%93%E4%BD%A0%E5%B7%B2%E5%AE%8C%E5%85%A8%E6%90%9E%E7%A0%B8%E4%BA%86)，ChatGPT 也是一个可考虑的选择；
    - 尽量使你的问题是可复现的、明确的，并在此基础上裁剪定位到会导致出问题的核心代码；
    - 详细描述问题，并提供相关指令及相关问题的报错截图，如果涉及系统问题请提供系统版本。

    **优先**在实验文档评论区、[Issue 区](https://github.com/OSH-2024/osh-2024.github.io/issues) 及课程群内讨论实验的相关问题以便解决共性问题。

## 实验要求

请按照以下目录结构组织你的 GitHub 仓库：

```
.                     // Git 仓库目录
├── lab2              // 实验二根目录
│   ├── shell.cpp     // 你的 shell 的源代码
│   ├── other.cpp
│   ├── Makefile      // 你提供的 Makefile
│   └── README.md     // 运行说明及简要的实验报告
├── .gitignore
└── README.md
```

如果选用 Rust 语言，lab2 目录下按照 Rust 工程组织（即包含 `src` 文件夹和 `Cargo.lock`, `Cargo.toml` 文件）即可。

本实验可以使用 libc, libstdc++, libm 以及 iostream, STL 等 C/C++ 语言标准和常用库。如果你愿意，你也可以使用 readline 和 ncurses 等 Linux 程序常用库。对 Rust 允许使用库的说明请参见实验零。使用此处没有列出的库前请询问助教。

Git 的使用应符合规范。当出现以下情况时，我们会酌情扣除一定分数：

- 很大一部分的 commit 是由 GitHub 网页上传的文件；
- commit 寥寥无几。最好的习惯是每实现一个新的功能及每一次代码重构都对应 commit；
- 上传了大量与实验要求无关的文件。

## 实验报告

你在 `README.md` 中应该至少包括：

- 你的 shell 实现可能与系统中的 bash（或助教期望的表现）


"""
ckwg +29
Copyright 2019-2020 by Kitware, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Kitware, Inc. nor the names of any contributors may be used
   to endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Tests for python algorithm factory class
"""

from kwiver.vital import plugin_management
from kwiver.vital.algo import ImageObjectDetector

# an algorithm needs to implement a minimal pluggable API:
class DummyImageObjectDetector(ImageObjectDetector):
    def __init__(self):
        ImageObjectDetector.__init__(self)

    @classmethod
    def from_config(cls, c):
        return DummyImageObjectDetector()

    @classmethod
    def get_default_config(cls, c):
        return

def test_algorithm_factory():
    # algorithm is automatically added since it is defined in the same file.
    vpm = plugin_management.plugin_manager_instance()
    vpm.load_all_plugins()

    assert ImageObjectDetector.has_algorithm_impl_name(
        "DummyImageObjectDetector"
    ), "TestImageObjectDetector not found by the factory"

    # Check with an empty implementation
    assert ImageObjectDetector.has_algorithm_impl_name("") == False

    # Check with non existsting implementation
    assert ImageObjectDetector.has_algorithm_impl_name("NotAnObjectDetector") == False

    # Check that a registered implementation is returned by implementations
    assert (
        "DummyImageObjectDetector" in ImageObjectDetector.registered_names()
    ), "Dummy example_detector not registered"

    # Check with an empty algorithm return empty list
    assert len(vpm.impl_names("")) == 0
    # Check with dummy algorithm returns empty list
    assert len(vpm.impl_names("NotAnAlgorithm")) == 0

    # Make sure creating works
    alg_out = ImageObjectDetector.create_algorithm("DummyImageObjectDetector")

    assert isinstance(alg_out, DummyImageObjectDetector)
    assert isinstance(alg_out, ImageObjectDetector)


;
    }

    // Update all ready scene views.
    for (int i = 0; i < sceneViews.Count; ++i) {
      UpdateShaderForSceneView((SceneView) sceneViews[i]);
    }
  }

  // Updates the shader of a specific scene view.
  private void UpdateShaderForSceneView(SceneView sceneView) {
    if (isInVisualizeMode) {
      sceneView.SetSceneViewShaderReplace(surfaceMaterialShader, "RenderType");
    } else {
      sceneView.SetSceneViewShaderReplace(null, null);
    }
    sceneView.Repaint();
    updatedSceneViews.Add(sceneView.GetInstanceID());
  }

  // The UI for selecting a ResonanceAudioMaterialMap asset to use.
  private void DrawMaterialMapSelection() {
    EditorGUILayout.PropertyField(materialMap, materialMapLabel);
  }

  // Draws the objects filtering GUI. Users can decide which layers to include, and whether to
  // include non-static objects.
  private void DrawObjectFiltering() {
    EditorGUILayout.PropertyField(reverbLayerMask, reverbLayerMaskLabel);

    EditorGUILayout.Separator();

    EditorGUILayout.PropertyField(includeNonStaticGameObjects, nonStaticGameObjectLabel);
  }

  // Draws the "Visualize Mode" checkbox.
  private void DrawVisualizeModeCheckbox() {
    if (isInVisualizeMode != EditorGUILayout.Toggle(visualizeModeLabel, isInVisualizeMode)) {
      isInVisualizeMode = !isInVisualizeMode;
      RefreshMaterialMapper();
      UpdateShader();
    }
  }

  // The UI for selecting a subset of reverb probes to bake reverb to.
  private void DrawProbeSelection() {
    ResonanceAudioReverbProbe[] allReverbProbes =
        UnityEngine.Object.FindObjectsOfType<ResonanceAudioReverbProbe>();

    // Clean up the deleted reverb probes.
    var selectedReverbProbes = ResonanceAudioReverbComputer.selectedReverbProbes;
    selectedReverbProbes.RemoveAll(reverbProbe => reverbProbe == null);

    probeSelectionScrollPosition = EditorGUILayout.BeginScrollView(probeSelectionScrollPosition,
                                                                   GUILayout.ExpandHeight(false));
    for (int i = 0; i < allReverbProbes.Length; ++i) {
      var reverbProbe = allReverbProbes[i];
      bool currentlySelected = selectedReverbProbes.Contains(reverbProbe);
      if (EditorGUILayout.ToggleLeft(reverbProbe.name, currentlySelected)) {
        if (!currentlySelected) {
          // Reverb probe selected.
          selectedReverbProbes.Add(reverbProbe);
        }
      } else {
        if (currentlySelected) {
          // Reverb probe de-selected.


) -> Result<usize, String> {
        self.inspector.write(len)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compat::Compat;
    use crate::event_listener::RocksEventListener;
    use crate::raw::{ColumnFamilyOptions, DBCompressionType};
    use crate::raw_util::{new_engine_opt, CFOptions};
    use engine_traits::{CompactExt, CF_DEFAULT};
    use file_system::{IOOp, IORateLimiter, IORateLimiterStatistics, IOType};
    use keys::data_key;
    use rocksdb::Writable;
    use rocksdb::{DBOptions, DB};
    use std::sync::Arc;
    use tempfile::Builder;

    fn new_test_db(dir: &str) -> (Arc<DB>, Arc<IORateLimiterStatistics>) {
        let limiter = Arc::new(IORateLimiter::new_for_test());
        let mut db_opts = DBOptions::new();
        db_opts.add_event_listener(RocksEventListener::new("test_db"));
        let env = get_env(None, Some(limiter.clone())).unwrap();
        db_opts.set_env(env);
        let mut cf_opts = ColumnFamilyOptions::new();
        cf_opts.set_disable_auto_compactions(true);
        cf_opts.compression_per_level(&[DBCompressionType::No; 7]);
        let db = Arc::new(
            new_engine_opt(dir, db_opts, vec![CFOptions::new(CF_DEFAULT, cf_opts)]).unwrap(),
        );
        (db, limiter.statistics().unwrap())
    }

    #[test]
    fn test_inspected_compact() {
        let value_size = 1024;
        let temp_dir = Builder::new()
            .prefix("test_inspected_compact")
            .tempdir()
            .unwrap();

        let (db, stats) = new_test_db(temp_dir.path().to_str().unwrap());
        let value = vec![b'v'; value_size];

        db.put(&data_key(b"a1"), &value).unwrap();
        db.put(&data_key(b"a2"), &value).unwrap();
        db.flush(true /*sync*/).unwrap();
        assert!(stats.fetch(IOType::Flush, IOOp::Write) > value_size * 2);
        assert!(stats.fetch(IOType::Flush, IOOp::Write) < value_size * 3);
        stats.reset();
        db.put(&data_key(b"a2"), &value).unwrap();
        db.put(&data_key(b"a3"), &value).unwrap();
        db.flush(true /*sync*/).unwrap();
        assert!(stats.fetch(IOType::Flush, IOOp::Write) > value_size * 2);
        assert!(stats.fetch(IOType::Flush, IOOp::Write) < value_size * 3);
        stats.reset();
        db.c()
            .compact_range(
                CF_DEFAULT, None,  /*start_key*/
                None,  /*end_key*/
                false, /*exclusive_manual*/
                1,     /*max_subcompactions*/
            )
            .unwrap();
        assert!(stats.fetch(IOType::LevelZeroCompaction, IOOp::Read) > value_size * 4);
        assert!(stats.fetch(IOType::LevelZeroCompaction, IOOp::Read) < value_size * 5);
        assert!(stats.fetch(IOType::LevelZeroCompaction, IOOp::Write) > value_size * 3);
        assert!(stats.fetch(IOType::LevelZeroCompaction, IOOp::Write) < value_size * 4);
    }
}
//! Tracks positive integers for keys.

use std::{
    collections::HashMap,
    hash::Hash,
    ops::{Ad


 a component to mantain design uniformity and avoid repetitions (ex. Icons ?!).

Battle tested example
```javascript
import {PickerField, LinkField} from 'react-native-form-generator';
import Icon from 'react-native-vector-icons/Ionicons';

let {
  StyleSheet
} = React;

export class WrappedLinkField extends React.Component{
  render(){

    return <LinkField
      label={this.props.label}
      onPress={this.props.onPress}
      iconRight={<Icon name='ios-arrow-right'
      size={30}
        />
    }
}

export class WrappedPickerField extends React.Component{
    render(){

      return <PickerField
        fieldRef = {this.props.fieldRef}
        value={this.props.value}
        placeholder={this.props.placeholder}
        options={this.props.options}
        onChange={this.props.onChange}
        onValueChange={this.props.onValueChange}
        iconRight={
          <Icon name='ios-arrow-right'
          size={30}

          style={[
            formStyles.alignRight,{color: '#C7C7CC'},
            this.props.iconStyle]}/>
      }
      />
  }
}

let formStyles = StyleSheet.create({
    alignRight:{
      marginTop: 7, position:'absolute', right: 10
    }
  });
```
# Helm

### 目錄

* [什麼是 Helm？](#什麼是-helm)

* [安裝 Helm](#安裝-helm)

* [Helm 的實作](#helm-的實作建立並部署第一個-chart)

* [修改 Helm 的 value 設定](#修改-helm-的-value-設定)

* [打包 Chart 並分享](#打包-chart-並分享)

* [部署他人分享的 Chart](#部署他人分享的-chart)

* [建立自己的 helm chart repository：以 Gitlab 為例](#建立自己的-helm-chart-repository以-gitlab-為例)

* [Helm 的常用指令彙整](#helm-的基本指令彙整)

### 什麼是 Helm？

Helm 是一項 CNCF 的專案，能將 k8s 中的應用打包起來，方便我們管理、部署、升級。

那為什麼應用需要打包？在實務中，一項 k8s 應用服務會由很多份 yaml 來組成，例如常聽見的微服務架構。而這會造成以下問題：

* 因為有很多的 yaml，所以部署整套應用時就要一直複製貼上、複製貼上，非常麻煩。

* 因為部署環境的不同，可能需要針對應用服務做一些微調，例如 replica 數量、image tag 等等的小修改。但如果需要微調的 yaml 數量很多，雖然手動設定難度不高，但容易發


ypes.FsrmMacroTypeEnum[]

### System.String[]

## OUTPUTS

### Microsoft.Management.Infrastructure.CimInstance

### Microsoft.Management.Infrastructure.CimInstance#Root/Microsoft/Windows/FSRM/MSFT_FSRMMacro

## NOTES

## RELATED LINKS

[Get-FsrmAdrSetting](./Get-FsrmAdrSetting.md)

[Get-FsrmFileManagementJob](./Get-FsrmFileManagementJob.md)

[Get-FsrmFileScreen](./Get-FsrmFileScreen.md)

[Get-FsrmQuota](./Get-FsrmQuota.md)

---
description: The Remove-MpPreference cmdlet removes exclusions for file name extensions, paths, and processes, or default actions for high, moderate, and low threats.
external help file: MSFT_MpPreference.cdxml-help.xml
Module Name: Defender
ms.date: 12/20/2016
online version: https://learn.microsoft.com/powershell/module/defender/remove-mppreference?view=windowsserver2022-ps&wt.mc_id=ps-gethelp
schema: 2.0.0
title: Remove-MpPreference
---

# Remove-MpPreference

## SYNOPSIS

Removes values from multi-valued properties (for example, exclusions and protected folders) and
returns settings in Windows Defender to their default values.

> [!NOTE]
> You need to run this cmdlet in an elevated PowerShell window (a PowerShell window you opened by
selecting **Run as administrator**).

## SYNTAX

```
Remove-MpPreference
 [-AllowDatagramProcessingOnWinServer]
 [-AllowNetworkProtectionDownLevel]
 [-AllowNetworkProtectionOnWinServer]
 [-AllowSwitchToAsyncInspection]
 [-AsJob]
 [-AttackSurfaceReductionOnlyExclusions <String[]>]
 [-AttackSurfaceReductionRules_Actions <ASRRuleActionType[]>]
 [-AttackSurfaceReductionRules_Ids <String[]>]
 [-CheckForSignaturesBeforeRunningScan]
 [-CimSession <CimSession[]>]
 [-CloudBlockLevel]
 [-CloudExtendedTimeout]
 [-ControlledFolderAccessAllowedApplications <String[]>]
 [-ControlledFolderAccessProtectedFolders <String[]>]
 [-DefinitionUpdatesChannel]
 [-DisableArchiveScanning]
 [-DisableAutoExclusions]
 [-DisableBehaviorMonitoring]
 [-DisableBlockAtFirstSeen]
 [-DisableCacheMaintenance]
 [-DisableCatchupFullScan]
 [-DisableCatchupQuickScan]
 [-DisableCpuThrottleOnIdleScans]
 [-DisableDatagramProcessing]
 [-DisableDnsOverTcpParsing]
 [-DisableDnsParsing]
 [-DisableEmailScanning]
 [-DisableFtpParsing]
 [-DisableGradualRelease]
 [-DisableHttpParsing]
 [-DisableInboundConnectionFiltering]
 [-DisableIntrusionPreventionSystem]
 [-DisableIOAVProtection]
 [-DisableNetworkProtectionPerfTelemetry]
 [-DisablePrivacyMode]
 [-DisableRdpParsing]
 [-DisableRealtimeMonitoring]
 [-DisableRemovableDriveScanning]
 [-DisableRestorePoint]
 [-DisableScanningMappedNetworkDrivesForFullScan]
 [-DisableScanningNetworkFiles]
 [-DisableScriptScanning]
 [-DisableSmtpParsing]
 [-DisableSshParsing]
 [-DisableTlsParsing]
 [-EnableControlledFolderAccess]
 [-EnableConvertWarnToBlock]
 [-EnableDnsSinkhole]
 [-EnableFileHashComputation]
 [-EnableFullScanOnBatteryPower]
 [-EnableLowCpuPriority]
 [-EnableNetworkProtection]
 [-EnableUdpReceiveOffload]
 [-EnableUdpSegmentationOffload]
 [-EngineUpdatesChannel]
 [-ExclusionExtension <String[]>]
 [-ExclusionIpAddress <String[]>]
 [-ExclusionPath <String[]>]
 [-ExclusionProcess <String[]>]
 [-Force]
 [-ForceUseProxyOnly]
 [-HighThreatDefaultAction]
 [-IntelTDTEnabled]
 [-LowThreatDefaultAction]
 [-MAPSReporting]
 [-MeteredConnectionUpdates]
 [-ModerateThreatDefaultAction]
 [-OobeEnableRtpAndSigUpdate]
 [-PlatformUpdatesChannel]
 [-ProxyBypass]
 [-ProxyPacUrl]
 [-ProxyServer]
 [-PUAProtection]
 [-


ks = position,
			mediaSourceId = streamInfo.mediaSourceId,
			liveStreamId = streamInfo.mediaSource?.liveStreamId,
			playSessionId = streamInfo.playSessionId,
			failed = false,
		)

		lifecycleOwner.lifecycleScope.launch(Dispatchers.IO + NonCancellable) {
			Timber.i("Reporting ${item.name} playback stopped at $position")
			runCatching {
				api.playStateApi.reportPlaybackStopped(info)
			}.onFailure { error -> Timber.e(error, "Failed to report stopped playback!") }
		}

		// Update dataRefreshService
		dataRefreshService.lastPlayback = Instant.now()
		when (item.type) {
			BaseItemKind.MOVIE -> dataRefreshService.lastMoviePlayback = Instant.now()
			BaseItemKind.EPISODE -> dataRefreshService.lastTvPlayback = Instant.now()
			else -> Unit
		}
	}
}
package org.jellyfin.androidtv.auth.service

import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import androidx.core.os.bundleOf
import org.jellyfin.androidtv.ui.preference.PreferencesActivity

class AuthenticatorService : Service() {
	private val authenticator by lazy {
		Authenticator(this)
	}

	override fun onBind(intent: Intent): IBinder? = authenticator.iBinder

	private inner class Authenticator(
		private val service: AuthenticatorService
	) : AbstractAccountAuthenticator(service) {
		private val unsupportedOperationBundle = bundleOf(
			AccountManager.KEY_ERROR_CODE to AccountManager.ERROR_CODE_REMOTE_EXCEPTION,
			AccountManager.KEY_ERROR_MESSAGE to "Unsupported operation"
		)

		override fun addAccount(
			response: AccountAuthenticatorResponse,
			accountType: String,
			authTokenType: String?,
			requiredFeatures: Array<String>?,
			options: Bundle,
		): Bundle = unsupportedOperationBundle

		override fun confirmCredentials(
			response: AccountAuthenticatorResponse,
			account: Account,
			options: Bundle?,
		): Bundle = unsupportedOperationBundle

		override fun editProperties(
			response: AccountAuthenticatorResponse,
			accountType: String,
		): Bundle = bundleOf(
			AccountManager.KEY_INTENT to Intent(service, PreferencesActivity::class.java)
		)

		override fun getAccountRemovalAllowed(
			response: AccountAuthenticatorResponse,
			account: Account,
		): Bundle = bundleOf(
			AccountManager.KEY_BOOLEAN_RESULT to true
		)

		override fun getAuthToken(
			response: AccountAuthenticatorResponse,
			account: Account,
			authTokenType: String,
			options: Bundle,
		): Bundle = unsupportedOperationBundle

		override fun getAuthTokenLabel(authTokenType: String): String? = null

		override fun hasFeatures(
			response: AccountAuthenticatorResponse,
			account: Account,
			features: Array<String>,
		): Bundle = unsupportedOperationBundle

		override fun updateCredentials(
			response: AccountAuthenticatorResponse,
			account: Account,
			authTokenType: String?,
			options: Bundle?,
		): Bundle = unsupportedOperationBundle
	}
}
package org.jellyfin.androidtv.auth.repository

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow


t": "tcp/udp",  "s": "tpdu",  "n": "hypercom tpdu"}, {  "p": 1431,  "t": "tcp/udp",  "s": "rgtp",  "n": "reverse gossip transport"}, {  "p": 1432,  "t": "tcp/udp",  "s": "blueberry-lm",  "n": "blueberry software license manager"}, {  "p": 1433,  "t": "tcp/udp",  "s": "ms-sql-s",  "n": "microsoft-sql-server"}, {  "p": 1434,  "t": "tcp/udp",  "s": "ms-sql-m",  "n": "microsoft-sql-monitor"}, {  "p": 1435,  "t": "tcp/udp",  "s": "ibm-cics",  "n": "ibm cics"}, {  "p": 1436,  "t": "tcp/udp",  "s": "saism",  "n": "satellite-data acquisition system 2"}, {  "p": 1437,  "t": "tcp/udp",  "s": "tabula",  "n": "tabula"}, {  "p": 1438,  "t": "tcp/udp",  "s": "eicon-server",  "n": "eicon security agent/server"}, {  "p": 1439,  "t": "tcp/udp",  "s": "eicon-x25",  "n": "eicon x25/sna gateway"}, {  "p": 1440,  "t": "tcp/udp",  "s": "eicon-slp",  "n": "eicon service location protocol"}, {  "p": 1441,  "t": "tcp/udp",  "s": "cadis-1",  "n": "cadis license management"}, {  "p": 1442,  "t": "tcp/udp",  "s": "cadis-2",  "n": "cadis license management"}, {  "p": 1443,  "t": "tcp/udp",  "s": "ies-lm",  "n": "integrated engineering software"}, {  "p": 1444,  "t": "tcp/udp",  "s": "marcam-lm",  "n": "marcam license management"}, {  "p": 1445,  "t": "tcp/udp",  "s": "proxima-lm",  "n": "proxima license manager"}, {  "p": 1446,  "t": "tcp/udp",  "s": "ora-lm",  "n": "optical research associates license manager"}, {  "p": 1447,  "t": "tcp/udp",  "s": "apri-lm",  "n": "applied parallel research lm"}, {  "p": 1448,  "t": "tcp/udp",  "s": "oc-lm",  "n": "openconnect license manager"}, {  "p": 1449,  "t": "tcp/udp",  "s": "peport",  "n": "peport"}, {  "p": 1450,  "t": "tcp/udp",  "s": "dwf",  "n": "tandem distributed workbench facility"}, {  "p": 1451,  "t": "tcp/udp",  "s": "infoman",  "n": "ibm information management"}, {  "p": 1452,  "t": "tcp/udp",  "s": "gtegsc-lm",  "n": "gte government systems license man"}, {  "p": 1453,  "t": "tcp/udp",  "s": "genie-lm",  "n": "genie license manager"}, {  "p": 1454,  "t": "tcp/udp",  "s": "interhdl_elmd",  "n": "interhdl license manager"}, {  "p": 1455,  "t": "tcp/udp",  "s":


        }

        /// <inheritdoc />
        protected override void onRecognized()
        {
            base.onRecognized();

            if (transformCompletedInvoker != null)
                transformCompletedInvoker.InvokeHandleExceptions(this, EventArgs.Empty);
            if (UseSendMessage && SendMessageTarget != null)
                SendMessageTarget.SendMessage(TRANSFORM_COMPLETE_MESSAGE, this, SendMessageOptions.DontRequireReceiver);
			if (UseUnityEvents) OnTransformComplete.Invoke(this);
        }

        /// <inheritdoc />
        protected override void reset()
        {
            base.reset();

            resetValues();
            isTransforming = false;
        }

        #endregion

        #region Protected methods

        /// <summary>
        /// Updates the type of the gesture.
        /// </summary>
        protected virtual void updateType() {}

        /// <summary>
        /// Resets the frame delta values.
        /// </summary>
        protected void resetValues()
		{
			deltaPosition = Vector3.zero;
			deltaRotation = 0f;
			deltaScale = 1f;
			transformMask = 0;
		}

#if TOUCHSCRIPT_DEBUG
        protected int debugID;
        protected Coroutine debugCoroutine;
        protected Vector2 debugPointerSize;
#endif

        #endregion

        #region Private functions

        private void updateScreenTransformThreshold()
        {
            screenTransformPixelThreshold = screenTransformThreshold * touchManager.DotsPerCentimeter;
            screenTransformPixelThresholdSquared = screenTransformPixelThreshold * screenTransformPixelThreshold;
        }

        #endregion
    }
}


using System.IO.Pipes;
using System.Text;
using GoAwayEdge.Common.Debugging;

namespace GoAwayEdge.Common.Runtime
{
    public class NamedPipeManager(string pipeName, int maxRetryAttempts = 3)
    {
        private bool _isServerRunning;
        private Thread? _pipeThread;
        private readonly object _lock = new();

        public event Action<string>? MessageReceived;
        public event Action<Exception>? ErrorOccurred;

        public void StartServer()
        {
            _isServerRunning = true;

            _pipeThread = new Thread(() =>
            {
                while (_isServerRunning)
                {
                    try
                    {
                        using (var pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
                        {
                            Logging.Log("Waiting for client connection...");
                            pipeServer.WaitForConnection();

                            Logging.Log("Client connected.");
                            var buffer = new byte[256];
                            while (pipeServer.IsConnected)
                            {
                                try
                                {
                                    int bytesRead = pipeServer.Read(buffer, 0, buffer.Length);
                                    if (bytesRead > 0)
                                    {
                                        string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                                        MessageReceived?.Invoke(message);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    HandleError(ex);
                                    break;
                                }
                            }

                            Logging.Log("Client disconnected. Resetting pipe...");
                            pipeServer.Disconnect();


evel: number): string;
/**
 * Removes leading period (.) from string and returns new string.
 * @param {String} str The string to clean.
 * @returns {*} The cleaned string.
 */
export function clean(str: string): any;
/**
 * Counts the total number of key leaf nodes in the passed object.
 * @param {Object|Array} obj The object to count key leaf nodes for.
 * @param {Array=} objCache Do not use. Internal array to track
 * visited leafs.
 * @returns {Number} The number of keys.
 */
export function countLeafNodes(obj: any | any[], objCache?: any[] | undefined): number;
/**
 * Tests if the passed object has the paths that are specified and that
 * a value exists in those paths and if so returns the number matched.
 * MAY NOT BE INFINITE RECURSION SAFE.
 * @param {Object|Array} testKeys The object describing the paths to test for.
 * @param {Object|Array} testObj The object to test paths against.
 * @returns {Object<matchedKeys<Number>, matchedKeyCount<Number>, totalKeyCount<Number>>} Stats on the matched keys.
 */
export function countMatchingPathsInObject(testKeys: any | any[], testObj: any | any[]): any;
/**
 * If options.immutable === true then return a new de-referenced
 * instance of the passed object/array. If immutable is false
 * then simply return the same `obj` that was passed.
 * @param {*} obj The object or array to decouple.
 * @param {Object=} options The options object that has the immutable
 * key with a boolean value.
 * @returns {*} The new decoupled instance (if immutable is true)
 * or the original `obj` if immutable is false.
 */
export function decouple(obj: any, options?: any | undefined): any;
/**
 * Compares two provided objects / arrays and returns an array of
 * dot-notation paths to the fields that hold different values.
 * @param {Object|Array} obj1 The first object / array to compare.
 * @param {Object|Array} obj2 The second object / array to compare.
 * @param {String=""} basePath The base path from which to check for
 * differences. Differences outside the base path will not be
 * returned as part of the array of differences. Leave blank to check
 * for all differences between the two objects to compare.
 * @param {Boolean=false} strict If strict is true, diff uses strict
 * equality to determine difference rather than non-strict equality;
 * effectively (=== is strict, == is non-strict).
 * @param {Number=Infinity} maxDepth Specifies the maximum number of
 * path sub-trees to walk down before returning what we have found.
 * For instance, if set to 2, a diff would only check down,
 * "someFieldName.anotherField", or "user.name" and would not go
 * further down than two fields. If anything in the trees further
 * down than this level have changed, the change will not be detected
 * and the path will not be included in the resulting diff array.
 * @param {String=""} parentPath Used internally only.
 * @returns {Array} An array of strings, each string is a path to a
 * field that holds a different value between the two objects being
 * compared.
 */
export function diff(obj1: any | any[], obj2: any | any[], basePath?: string, strict?: boolean, maxDepth?: number, parentPath?: string, objCache?: any[]): any[];
/**
 * Gets the values of the paths in pathArr and returns them as an object
 * with each key matching the path and the value matching


8 (dyskusja) 18:46, 23 paź 2018 (CEST)

czego? Faktów, dat, np zakończenia studiów, co studiował, kiedy i jakie funkcje w związku pełnił. O peanach itp. przecież pisałem - do usunięcia. Skupmy się, czy ta FB strona może być źródłem podstawowych danych biograficznych? --Piotr967 podyskutujmy 18:52, 23 paź 2018 (CEST)

Fb to strona reklamowa, mająca na celu zaprezentowanie się w jak najlepszym świetle. Może to dotyczyć zarówno peanów na swoją cześć jak i faktów. Zbyt wielkie pole do manipulacji, przedstawienia wszystkiego w korzystnym, najlepszym obrazie, bijemy się o lajki. Jestem przeciwny--Tokyotown8 (dyskusja) 19:16, 23 paź 2018 (CEST)

Reply to c-Tokyotown8-2018-10-23T17:16:00.000Z-Piotr967-2018-10-23T16:52:00.000Z

Każdy sobie może napisać, że coś studiował, i dowolną inną bzdurę. Mpn (dyskusja) 19:40, 23 paź 2018 (CEST)

Z drugiej strony – na oficjalnej stronie www też można sobie wpisać bzdury. Szoltys [Re: ] 19:44, 23 paź 2018 (CEST


rt 'package:graphql/client.dart';

import 'package:animestream/core/commons/enums.dart';
import 'package:animestream/core/commons/utils.dart';
import 'package:animestream/core/data/secureStorage.dart';
import 'package:animestream/core/database/anilist/queries.dart';
import 'package:animestream/core/database/anilist/types.dart';
import 'package:animestream/core/database/database.dart';
import 'package:animestream/core/database/types.dart';

class Anilist extends Database {
  Future<List<AnilistSearchResult>> search(String query) async {
    final gquery = '''
            query {
                Page(perPage: 15) {
                    media(search: "$query", type: ANIME, isAdult: false) {
                        id
                        idMal
                        title {
                            english
                            romaji
                            native
                        }
                        episodes
                        averageScore
                        coverImage {
                            large
                        }
                    }
                }
            }
        ''';
    final data = await fetchQuery(gquery, RequestType.media);

    List<AnilistSearchResult> searchResults = [];

    if (data.length == 0) {
      return [];
    }

    data.forEach((item) {
      final classified = AnilistSearchResult(
          cover: item['coverImage']['large'],
          id: item['id'],
          idMal: item['idMal'],
          title: {
            'english': item['title']['english'],
            'romaji': item['title']['romaji'],
            'native': item['title']['native'],
          },
          totalEpisodes: item['episodes'],
          rating: item['averageScore'] is int ? item['averageScore'] / 10 : null);
      searchResults.add(classified);
    });

    return searchResults;
  }

  Future<AnilistInfo> getAnimeInfo(int id) async {
    final query = AnilistQueries.infoQuery(id);
    final String? token = await getSecureVal(SecureStorageKey.anilistToken);
    final result = await Anilist().fetchQuery(query, RequestType.media, token: token);

    final Map<String, dynamic> info = result[0];

    AnilistInfo convertToIAnimeDetails() {
      final List<Map<String, dynamic>> characters = [];
      info['characters']['edges'].forEach((character) {
        characters.add({
          'name': character['node']['name']['full'],
          'role': character['role'],
          'image': character['node']['image']['large'] ?? character['node']['image']['medium'],
        });
      });

      final List<String> studios = [];

      info['studios']['edges'].forEach((studio) {
        if (studio['node']['isAnimationStudio'] && studio['isMain'] == true) {
          studios.add(studio['node']['name']);


tiveRow==rowNumber && this.ActiveRowValues[inputRowColorNumber]!=null)
      this.checkStyleChange(inputDot,'rgba(104, 101, 101, 0.651)','#000',0.5,inputRowColorNumber,null);

    this.checkFindImageVisiblity();
  }

  checkStyleChange(htmlElement,color,shadedColor,opacity,inputRowColorNumber,activeRowValue)
  {
    htmlElement.style.background= 'radial-gradient(circle at 15px 15px,'+color +' ,'+shadedColor+')';
    htmlElement.style.opacity=opacity;

    if(inputRowColorNumber != null)
    this.ActiveRowValues[inputRowColorNumber]=activeRowValue;
  }

  checkFindImageVisiblity(){
    const el: HTMLElement = document.getElementById('findImage '+this.ActiveRow);

    if(this.ActiveRowValues.indexOf(null)==-1)
      el.style.display='inline';

    else
    el.style.display='none';

  }

  findButtonClicked()
  {
    console.log("s");

    console.log(this.ActiveRowValues);
    let commanColors = this.ActiveRowValues.filter(o => this.secretCode.some((value) => o==value));
    console.log(commanColors);
    console.log(this.ActiveRowValues);
    let blackCount:number=0,whiteCount:number=0;

    for(let i=0;i<commanColors.length;i++){
      if(this.ActiveRowValues.indexOf(commanColors[i]) == this.secretCode.indexOf(commanColors[i])){
        const el: HTMLElement = document.getElementById('row '+this.ActiveRow+' hintDot '+whiteCount);
        this.checkStyleChange(el,'white','#FFF',1,null,null);
        whiteCount++;
      }
      else{
        const el: HTMLElement = document.getElementById('row '+this.ActiveRow+' hintDot '+(this.inputRowBallCount-blackCount-1));
        this.checkStyleChange(el,'black','#000',1,null,null);
        blackCount++;
      }
    }

    this.ActiveRowValues=[null,null,null,null];
    const el: HTMLElement = document.getElementById('findImage '+this.ActiveRow);
    el.style.display='none';
    this.ActiveRow--;

    if(whiteCount==4)
    {
      alert("YEPPIIEE YOU WON!!");
    }

  }

}
class Chromosome {
    private string: string[];
    private score: number;

    constructor(string: string[], score: number) {
        this.string = string;
        this.score = score;
    }

    public getScore(): number {
        return this.score;
    }

    public getString(): string[] {
        return this.string;
    }

    public setCharacter(index: number, character: string): void {
        this.string[index] = character;
    }

    public setScore(score: number): void {
        this.score = score;
    }
}

class Main {
    readonly low = 32;
    readonly high = 126;
    readonly POP_SIZE = 100;
    private chromosomes: Chromosome[] = [];
    private newChromosomes: Chromosome[] = [];
    private startHighest = 0;
    private startHighestString: string[];

    private iteration = 0;
    readonly helloWorld = [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33];

    public run() {
        this.fillArray();
        while (!this.checkSolution()) {
            let currentHighest = 0;
            let highestString = '';
            for (let i = 0; i < this.POP_SIZE; i++) {
                if (i < this.POP_SIZE) {
                    this.createNewPopulation();
                }
                let score = this.chromosomes[i


from .util import subvals

def unary_to_nary(unary_operator):
    @wraps(unary_operator)
    def nary_operator(fun, argnum=0, *nary_op_args, **nary_op_kwargs):
        print("""inside nary_operator:
                *nary_op_args: {},
                **nary_op_kwargs: {}
        """.format(nary_op_args, nary_op_kwargs))

        assert type(argnum) in (int, tuple, list), argnum
        @wrap_nary_f(fun, unary_operator, argnum)
        def nary_f(*args, **kwargs):
            print("""inside nary_f:
                    *args: {},
                    **kwargs: {}
            """.format(args, kwargs))

            @wraps(fun)
            def unary_f(x):
                if isinstance(argnum, int):
                    subargs = subvals(args, [(argnum, x)])
                else:
                    subargs = subvals(args, zip(argnum, x))
                return fun(*subargs, **kwargs)
            if isinstance(argnum, int):
                print("argnum: ", argnum)
                x = args[argnum]
            else:
                x = tuple(args[i] for i in argnum)
            return unary_operator(unary_f, x, *nary_op_args, **nary_op_kwargs)
        return nary_f
    return nary_operator

def wraps(fun, namestr="{fun}", docstr="{doc}", **kwargs):
    """创建和返回一个函数_wraps, 而_wraps则将函数fun的__name__, __doc__ (都是string)给予另一个函数f
    Args:
        fun: 一个函数
        namestr: 默认参数，"{fun}".format(fun = get_name)，用产生的新string取代{fun}
        docstr: 默认参数，意思同上
        **kwargs: 其他潜在named args
    Returns:
        _wraps
    """
    print(""" wraps:
                arg fun: {},
                arg namestr: {},
                arg docstr: {},
                arg **kwargs: {},
    """.format(fun.__name__, namestr, docstr, kwargs))
    def _wraps(f):
        """将函数fun的__name__, __doc__ (都是string)给予另一个函数f
        """
        print("_wraps: arg f is ", f.__name__)
        try:
            f.__name__ = namestr.format(fun=get_name(fun), **kwargs)
            f.__doc__ = docstr.format(fun=get_name(fun), doc=get_doc(fun), **kwargs)
        finally:
            return f
    return _wraps

def wrap_nary_f(fun, op, argnum):
    """ 创建新的可嵌入多个参数的namestr, docstr, 引入args: fun函数, op函数, argnum, 都作为wraps的参数，op函数的名称与argnum的值，会被带入到namestr与docstr中，然后返回wraps函数运行的结果，即_wraps函数

    Args:
        fun: 一个函数
        op: 估计也是函数
        argnum: 估计是int
    Returns:
        返回wraps函数

    Note: op=get_name(op), argnum=argnum, 对应的是wraps函数的**kwargs
    """
    print("""wrap_nary_f:
                arg fun: {},
                arg op: {},
                arg argnum: {}
                """.format(fun.__name__, op.__name__, argnum))
    namestr = "{op}_of_{fun}_wrt_argnum_{argnum}"
    docstr = """\
    {op} of function {fun} with respect to argument number {argnum}. Takes the
    same arguments as {fun} but returns the {op}.
    """

    return wraps(fun, namestr, docstr, op=get_name(op), argnum=argnum)

# 获取一个函数的名称，如果无名就返回'[unknown name]'
get_name = lambda f: getattr(f, '__name__', '[unknown name]')

# 获取一个函数的document，如果无名就返回''
get_doc  = lambda f: getattr(f, '__doc__' , '')


html" title="enum clap_builder::builder::Resettable">Resettable<T>

source§
fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

source§
impl<T> From<Option<T>> for Resettable<T>

source§
fn from(other: Option<T>) -> Self

Converts to this type from the input type.

source§
impl<T> <a class="trait" href=


2/annotation_profile_move.png)  more to see [idea](https://www.jetbrains.com/help/idea/configuring-annotation-processing.html)<br>
     * (2), set generate dir to the source/test source dir.
   * 3, add dependencies.
   ```java
   dependencies {
     compile 'com.heaven7.java.data.mediator.annotation:data-mediator-annotations:<see release>'
     compile 'com.heaven7.java.data.mediator.support.gson:data-mediator-support-gson:<see release>'

     compile 'com.heaven7.java.data.mediator:data-mediator:<see release>'
     apt 'com.heaven7.java.data.mediator.compiler:data-mediator-compiler:<see release>'
     apt 'com.squareup:javapoet:1.9.0'
   }
   ```
 * android platform ( for android project) .
   * if you use old gradle version lower of 4.1. such as: '3.5'
     * 1, in the root build file。
     ```java
      classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
     ```
     * 2, in app module add apt plugin
     ```java
        apply plugin: 'com.neenbedankt.android-apt'
     ```
     * 3, add dependencies
     ```java
     dependencies {
         // gson-support( added since 1.2.0)
         compile 'com.heaven7.java.data.mediator.support.gson:data-mediator-support-gson:<see release>'
         compile 'com.heaven7.java.data.mediator:data-mediator:<see release>'

         compile 'com.heaven7.java.data.mediator.annotation:data-mediator-annotations:<see release>'
         apt 'com.heaven7.java.data.mediator.compiler:data-mediator-compiler:<see release>'
         apt 'com.squareup:javapoet:1.9.0'

         // if you want generate annotation of gson。(since 1.2.0 auto added)
         compile "com.google.code.gson:gson:2.8.2"
         // if you want to support data-bind of android
         compile 'com.heaven7.android.data.mediator:data-mediator-android:<see release>'

     }
     ```
   * if you use gradle version >=4.1. use 'annotationProcessor' directly.
   ```java
    dependencies {
         // gson-support( added since 1.2.0)
         compile 'com.heaven7.java.data.mediator.support.gson:data-mediator-support-gson:<see release>'
         compile 'com.heaven7.java.data.mediator:data-mediator:<see release>'

         compile 'com.heaven7.java.data.mediator.annotation:data-mediator-annotations:<see release>'
         annotationProcessor 'com.heaven7.java.data.mediator.compiler:data-mediator-compiler:<see release>'
         annotationProcessor 'com.squareup:javapoet:1.9.0'

         // if you want generate annotation of gson。(since 1.2.0 auto added)
         compile "com.google.code.gson:gson:2.8.2"
         // if you want to support data-bind of android
         compile 'com.heaven7.android.data.mediator:data-mediator-android:<see release>'

     }
   ```

# Quick Start.

1,[Optional] global configuration.
```java
@GlobalConfig(
        gsonConfig = @GsonConfig(
                version = 2.0,
                forceDisable = false,
                generateJsonAdapter = true
        )
)
```

2, define your data module。eg: if i want to define a student module ,
and need impl Serializable, Parcelable.
And if the student module has age, name, id property。
thus the simple data module can be define like :
```java

@Fields({


64; font-family: 'Segoe UI', Tahoma, sans-serif; font-size: 75%;}div{display:block;}h1{margin-top: 0; color: #333; font-size: 1.6em; font-weight: normal; line-height: 1.25em; margin-bottom: 16px;}button{-webkit-user-select: none; background: rgb(76, 142, 250); border: 0; border-radius: 2px; box-sizing: border-box; color: #fff; cursor: pointer; font-size: .875em; margin: 0; padding: 10px 24px; transition: box-shadow 200ms cubic-bezier(0.4, 0, 0.2, 1);}button:hover{box-shadow: 0 1px 2px rgba(1, 1, 1, 0.5);}.error-code{color: #777; display: inline; font-size: .86667em; margin-top: 15px; opacity: .5; text-transform: uppercase;}.interstitial-wrapper{box-sizing: border-box;font-size: 1em;margin: 100px auto 0;max-width: 600px;width: 100%;}.offline .interstitial-wrapper{color: #2b2b2b;font-size: 1em;line-height: 1.55;margin: 0 auto;max-width: 600px;padding-top: 100px;width: 100%;}.hidden{display: none;}.nav-wrapper{margin-top: 51px; display:inline-block;}#buttons::after{clear: both; content: ''; display: block; width: 100%;}.nav-wrapper::after{clear: both; content: ''; display: table; width: 100%;}.small-link{color: #696969; font-size: .875em;}@media (max-width: 640px), (max-height: 640px){h1{margin: 0 0 15px;}button{width: 100%;}}.reload{border: none; padding: 12px 16px; font-size: 16px; cursor: pointer;}.reload:before{content: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath fill='none' d='M0 0h24v24H0V0z'/%3E%3Cpath d='M17.65 6.35c-1.63-1.63-3.94-2.57-6.48-2.31-3.67.37-6.69 3.35-7.1 7.02C3.52 15.91 7.27 20 12 20c3.19 0 5.93-1.87 7.21-4.56.32-.67-.16-1.44-.9-1.44-.37 0-.72.2-.88.53-1.13 2.43-3.84 3.97-6.8 3.31-2.22-.49-4.01-2.3-4.48-4.52C5.31 9.44 8.26 6 12 6c1.66 0 3.14.69 4.22 1.78l-1.51 1.51c-.63.63-.19 1.71.7 1.71H19c.55 0 1-.45 1-1V6.41c0-.89-1.08-1.34-1.71-.71l-.64.65z'/%3E%3C/svg%3E\"); filter: invert(1); width: 20px; float: left; margin-right: 5px; margin-top: -2px;}</style>\n" + "

"
                            val title = mActivity.getString(R.string.https_title)
                            val start2 = "

"
                            val start3 = "

"
                            view.loadDataWithBaseURL(null, start + start1 + title


an filtros al explorar y buscar.\nLos filtros ignorados son: Filtrar por tipo de contenido (Erotico) y el Filtrar por generos: Ecchi, Boys Love, Girls Love, Harem y Trap."
        private const val SFW_MODE_PREF_DEFAULT_VALUE = false
        private val SFW_MODE_PREF_EXCLUDE_GENDERS = listOf("6", "17", "18", "19")

        private const val SAVE_LAST_CF_URL_PREF = "saveLastCFUrlPreference"
        private const val SAVE_LAST_CF_URL_PREF_TITLE = "Guardar la última URL con error de Cloudflare"
        private const val SAVE_LAST_CF_URL_PREF_SUMMARY = "Guarda la última URL con error de Cloudflare para que se pueda acceder a ella al abrir la serie en WebView."
        private const val SAVE_LAST_CF_URL_PREF_DEFAULT_VALUE = true

        const val PREFIX_LIBRARY = "library"
        const val PREFIX_SLUG_SEARCH = "slug:"

        private val SORTABLES = listOf(
            Pair("Me gusta", "likes_count"),
            Pair("Alfabético", "alphabetically"),
            Pair("Puntuación", "score"),
            Pair("Creación", "creation"),
            Pair("Fecha estreno", "release_date"),
            Pair("Núm. Capítulos", "num_chapters"),
        )

        private val CF_ERROR_CODES = listOf(403, 503)
        private val CF_SERVER_CHECK = arrayOf("cloudflare-nginx", "cloudflare")
    }
}
package eu.kanade.tachiyomi.extension.all.mangapark

import eu.kanade.tachiyomi.source.SourceFactory

class MangaParkFactory : SourceFactory {
    override fun createSources() = listOf(
        MangaPark("af"),
        MangaPark("sq"),
        MangaPark("am"),
        MangaPark("ar"),
        MangaPark("hy"),
        MangaPark("az"),
        MangaPark("be"),
        MangaPark("bn"),
        MangaPark("bs"),
        MangaPark("bg"),
        MangaPark("my"),
        MangaPark("km"),
        MangaPark("ca"),
        MangaPark("ceb"),
        MangaPark("zh"),
        MangaPark("zh-Hans", "zh_hk"),
        MangaPark("zh-Hant", "zh_tw"),
        MangaPark("hr"),
        MangaPark("cs"),
        MangaPark("da"),
        MangaPark("nl"),
        MangaPark("en"),
        MangaPark("eo"),
        MangaPark("et"),
        MangaPark("fo"),
        MangaPark("fil"),
        MangaPark("fi"),
        MangaPark("fr"),
        MangaPark("ka"),
        MangaPark("de"),
        MangaPark("el"),
        MangaPark("gn"),
        MangaPark("ht"),
        MangaPark("ha"),
        MangaPark("he"),
        MangaPark("hi"),
        MangaPark("hu"),
        MangaPark("is"),
        MangaPark("ig"),
        MangaPark("id"),
        MangaPark("ga"),
        MangaPark("it"),
        MangaPark("ja"),
        MangaPark("jv"),
        MangaPark("kk"),
        MangaPark("ko"),
        MangaPark("ku"),
        MangaPark("ky"),
        MangaPark("lo"),
        MangaPark("lv"),
        MangaPark("lt"),
        MangaPark("lb"),
        MangaPark("mk"),
        MangaPark("mg"),
        MangaPark("ms"),
        MangaPark("ml"),
        MangaPark("mt"),
        MangaPark("mi"),
        MangaPark("mo"),
        MangaPark("mn"),
        MangaPark("ne"),
        MangaPark("no"),
        MangaPark("ny"),
        MangaPark("ps"),
        MangaPark("fa"),
        MangaPark("pl"),
        MangaPark("pt"),
        MangaPark("pt-BR", "pt_br"),
        MangaPark("ro"),
        MangaPark("rm"),
        MangaPark("ru"),


2.2" data-path="commonly-used-functions.html">2.2 Natural Logarithm and Exponential

2.2.1 Log and Exponential

2.2.2 Log Rules

2.2.3 Why does \(\log (x\cdot y)=\log (x)+\log (y)\)?

2.2.4 Why does \(\log (x^a )=a\cdot \log (x)\)?

2.2.5 For Variables that Grow, Log difference is close to rate of change

3 Derivatives

3.1 Derivative Definition and Rules

3.1.1 Linear and Non-linear Functions

3.1.2 Definition

3.1.3 Derivative Rules–Constant Rule

3.1.4 Derivative Rules–Power Rule (Polynomial Rule)

<li class="chapter" data-level="3.1.5" data-path="derivatives.


) // 100ms
	if hd.totalHealthTime != 100 {
		t.Errorf("Expected totalHealthTime to be 100, got %f", hd.totalHealthTime)
	}

	hd.UpdateHealthDisplay(0.05) // 50ms more
	if hd.totalHealthTime != 150 {
		t.Errorf("Expected totalHealthTime to be 150, got %f", hd.totalHealthTime)
	}
}

func TestUpdateECGAnimation(t *testing.T) {
	hd := NewHealthDisplay()

	// Test that animation doesn't update before threshold
	hd.totalHealthTime = 25 // Below 30ms threshold
	hd.UpdateECGAnimation()

	if hd.ecgOffsetX != 0 {
		t.Errorf("Expected ecgOffsetX to remain 0, got %d", hd.ecgOffsetX)
	}

	// Test that animation updates when threshold is reached
	hd.totalHealthTime = 30 // At threshold
	hd.UpdateECGAnimation()

	if hd.ecgOffsetX != 1 {
		t.Errorf("Expected ecgOffsetX to be 1, got %d", hd.ecgOffsetX)
	}

	if hd.totalHealthTime != 0 {
		t.Errorf("Expected totalHealthTime to be reset to 0, got %f", hd.totalHealthTime)
	}
}

func TestUpdateECGAnimation_WrapAround(t *testing.T) {
	hd := NewHealthDisplay()
	hd.ecgOffsetX = 127 // Near end of cycle

	hd.totalHealthTime = 30
	hd.UpdateECGAnimation()

	if hd.ecgOffsetX != 0 {
		t.Errorf("Expected ecgOffsetX to wrap around to 0, got %d", hd.ecgOffsetX)
	}
}

func TestMultipleHealthDisplays(t *testing.T) {
	// This was impossible with global state!
	hd1 := NewHealthDisplay()
	hd2 := NewHealthDisplay()

	// Update them independently
	hd1.UpdateHealthDisplay(0.1)
	hd2.UpdateHealthDisplay(0.2)

	if hd1.totalHealthTime != 100 {
		t.Errorf("Expected hd1.totalHealthTime to be 100, got %f", hd1.totalHealthTime)
	}

	if hd2.totalHealthTime != 200 {
		t.Errorf("Expected hd2.totalHealthTime to be 200, got %f", hd2.totalHealthTime)
	}

	// They should be independent
	if hd1.totalHealthTime == hd2.totalHealthTime {
		t.Error("Health displays should be independent")
	}
}

func TestHealthDisplay_Isolation(t *testing.T) {
	// Test that multiple instances don't interfere
	hd1 := NewHealthDisplay()
	hd2 := NewHealthDisplay()

	// Set up different states
	hd1.totalHealthTime = 50
	hd1.ecgOffsetX = 10

	hd2.totalHealthTime = 25
	hd2.ecgOffsetX = 5

	// Update one
	hd1.UpdateECGAnimation()

	// The other should be unchanged
	if hd2.totalHealthTime != 25 {
		t.Errorf("Expected hd2.totalHealthTime to remain 25, got %f", hd2.totalHealthTime)
	}

	if hd2.ecgOffsetX != 5 {
		t.Errorf("Expected hd2.ecgOffsetX to remain 5, got %d", hd2.ecgOffsetX)
	}
}

// Benchmark tests
func BenchmarkUpdateHealthDisplay(b *testing.B) {
	hd := NewHealthDisplay()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		hd.UpdateHealthDisplay(0.016) // ~60 FPS
	}
}

func BenchmarkUpdateECGAnimation(b *testing.B) {
	hd := NewHealthDisplay()
	hd.totalHealthTime = 30 //


 fill-opacity: .5;
    fill: #ccc;
}

.dc-chart .heatmap g.axis text {
    pointer-events: all;
    cursor: pointer;
}@tailwind base;
  @tailwind components;
  @tailwind utilities;

  @layer base {
    :root {
      --background: 0 0% 100%;
      --foreground: 240 10% 3.9%;
      --card: 0 0% 100%;
      --card-foreground: 240 10% 3.9%;
      --popover: 0 0% 100%;
      --popover-foreground: 240 10% 3.9%;
      --primary: 240 5.9% 10%;
      --primary-foreground: 0 0% 98%;
      --secondary: 240 4.8% 95.9%;
      --secondary-foreground: 240 5.9% 10%;
      --muted: 240 4.8% 95.9%;
      --muted-foreground: 240 3.8% 46.1%;
      --accent: 240 4.8% 95.9%;
      --accent-foreground: 240 5.9% 10%;
      --destructive: 0 84.2% 60.2%;
      --destructive-foreground: 0 0% 98%;
      --border: 240 5.9% 90%;
      --input: 240 5.9% 90%;
      --ring: 240 5.9% 10%;
      --radius: 0.5rem;
    }

    .dark {
      --background: 240 10% 3.9%;
      --foreground: 0 0% 98%;
      --card: 240 10% 3.9%;
      --card-foreground: 0 0% 98%;
      --popover: 240 10% 3.9%;
      --popover-foreground: 0 0% 98%;
      --primary: 0 0% 98%;
      --primary-foreground: 240 5.9% 10%;
      --secondary: 240 3.7% 15.9%;
      --secondary-foreground: 0 0% 98%;
      --muted: 240 3.7% 15.9%;
      --muted-foreground: 240 5% 64.9%;
      --accent: 240 3.7% 15.9%;
      --accent-foreground: 0 0% 98%;
      --destructive: 0 62.8% 30.6%;
      --destructive-foreground: 0 0% 98%;
      --border: 240 3.7% 15.9%;
      --input: 240 3.7% 15.9%;
      --ring: 240 4.9% 83.9%;
    }
  }

  @layer base {
    * {
      @apply border-border;
    }
    body {
      @apply bg-background text-foreground;
    }
  }/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 *//*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:


            null,
        ).use { null != it && it.count > 0 }
    }.getOrElse {
        Utils.throwIfFatal(it)
        false
    }
}
/*
 * Copyright 2016 Hippo Seven
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hippo.ehviewer

import android.content.Context
import android.net.Uri
import androidx.paging.PagingSource
import androidx.room.Room.databaseBuilder
import com.hippo.ehviewer.EhApplication.Companion.ehDatabase
import com.hippo.ehviewer.client.data.GalleryInfo
import com.hippo.ehviewer.dao.BasicDao
import com.hippo.ehviewer.dao.DownloadDirname
import com.hippo.ehviewer.dao.DownloadInfo
import com.hippo.ehviewer.dao.DownloadLabel
import com.hippo.ehviewer.dao.EhDatabase
import com.hippo.ehviewer.dao.Filter
import com.hippo.ehviewer.dao.HistoryInfo
import com.hippo.ehviewer.dao.LocalFavoriteInfo
import com.hippo.ehviewer.dao.QuickSearch
import com.hippo.ehviewer.download.DownloadManager
import com.hippo.unifile.UniFile
import com.hippo.util.sendTo

object EhDB {
    private val db = ehDatabase

    // Fix state
    @get:Synchronized
    val allDownloadInfo: List<DownloadInfo>
        get() = db.downloadsDao().list().onEach {
            if (it.state == DownloadInfo.STATE_WAIT || it.state == DownloadInfo.STATE_DOWNLOAD) {
                it.state = DownloadInfo.STATE_NONE
            }
        }

    @Synchronized
    fun updateDownloadInfo(downloadInfos: List<DownloadInfo>) {
        val dao = db.downloadsDao()
        dao.update(downloadInfos)
    }

    @Synchronized
    fun putDownloadInfo(downloadInfo: DownloadInfo) {
        db.downloadsDao().run {
            if (load(downloadInfo.gid) != null) {
                update(downloadInfo)
            } else {
                insert(downloadInfo)
            }
        }
    }

    @Synchronized
    fun removeDownloadInfo(downloadInfo: DownloadInfo) {
        db.downloadsDao().delete(downloadInfo)
    }

    @get:Synchronized
    val allDownloadDirname: List<DownloadDirname>
        get() = db.downloadDirnameDao().list()

    @Synchronized
    fun getDownloadDirname(gid: Long): String? {
        val dao = db.downloadDirnameDao()
        val raw = dao.load(gid)
        return raw?.dirname
    }

    @Synchronized
    fun putDownloadDirname(gid: Long, dirname: String?) {
        val dao = db.downloadDirnameDao()
        var raw = dao.load(gid)
        if (raw != null) {
            raw.dirname = dirname
            dao.update(raw)
        } else {
            raw = DownloadDirname(gid, dirname)
            dao.insert(raw)
        }
    }

    @Synchronized
    fun removeDownloadDirname(gid: Long) {
        val dao = db.downloadDirnameDao()
        dao.deleteByKey(gid)
    }

    @get:Synchronized
    val allDownloadLabelList: List<DownloadLabel>
        get() = db.downloa


= ex.find_best(root);
        let eclass_ids = egraph.lookup_expr_ids(&plan).ok_or_else(|| {
            DataFusionError::Internal(String::from(
                "TokomakOptimizer could not extract plan from egraph.",
            ))
        })?;
        let converter =
            crate::plan::TokomakPlanConverter::new(&plan, &eclass_ids, &egraph);
        let rt_expr = converter.convert_to_expr(root)?;
        assert_eq!(expr, &rt_expr);
        Ok(())
    }

    fn roundtrip_plan(plan: &LogicalPlan) -> TestResult {
        let mut egraph = EGraph::default();
        let root = crate::plan::to_tokomak_plan(plan, &mut egraph)?;
        let ex = Extractor::new(&egraph, crate::DefaultCostFunc);
        let (_, rec_expr_plan) = ex.find_best(root);
        let eclass_ids = egraph.lookup_expr_ids(&rec_expr_plan).ok_or_else(|| {
            DataFusionError::Internal(String::from(
                "TokomakOptimizer could not extract plan from egraph.",
            ))
        })?;
        let rt_plan =
            crate::plan::convert_to_df_plan(&rec_expr_plan, &eclass_ids, &egraph)?;
        assert_eq!(format!("{:?}", plan), format!("{:?}", rt_plan));
        Ok(())
    }

    fn test_roundtrip_expr_list(exprs: &[Expr]) -> TestResult {
        for e in exprs {
            test_roundtrip_expr(e)?;
        }
        Ok(())
    }

    #[test]
    fn roundtrip_not() -> Result<(), Box<dyn std::error::Error>> {
        let exprs = vec![col("c2").not().not().not(), col("c2").not()];
        test_roundtrip_expr_list(&exprs)
    }

    #[test]
    fn roundtrip_scalar_value() -> TestResult {
        let scalars = [
            ScalarValue::Boolean(Some(true)),
            ScalarValue::Boolean(Some(false)),
            ScalarValue::Boolean(None),
            ScalarValue::Float32(None),
            ScalarValue::Float32(Some(1.5)),
            ScalarValue::Float32(Some(f32::NAN)),
            ScalarValue::Float64(None),
            ScalarValue::Float64(Some(1.5f64)),
            ScalarValue::Float64(Some(f64::NAN)),
            ScalarValue::Int8(None),
            ScalarValue::Int8(Some(0)),
            ScalarValue::Int8(Some(123)),
            ScalarValue::Int8(Some(-123)),
            ScalarValue::Int16(None),
            ScalarValue::Int16(Some(0)),
            ScalarValue::Int16(Some(3214)),
            ScalarValue::Int16(Some(-3214)),
            ScalarValue::Int32(None),
            ScalarValue::Int32(Some(0)),
            ScalarValue::Int32(Some(45021)),
            ScalarValue::Int32(Some(-45021)),
            ScalarValue::Int64(None),
            ScalarValue::Int64(Some(0)),
            ScalarValue::Int64(Some(45021)),
            ScalarValue::Int64(Some(-45021)),
            ScalarValue::UInt8(None),
            ScalarValue::UInt8(Some(0)),
            ScalarValue::UInt8(Some(245)),
            ScalarValue::UInt8(Some(u8::MAX)),
            ScalarValue::UInt16(None),
            ScalarValue::UInt16(Some(0)),
            ScalarValue::UInt16(Some(45021)),
            ScalarValue::UInt16(Some(u16::MAX)),
            ScalarValue::UInt32(None),
            ScalarValue::UInt32(Some(0)),
            ScalarValue::UInt32(Some(45021)),
            ScalarValue::UInt32(Some(u32::MAX)),
            ScalarValue::UInt64(None),
            ScalarValue::


from enum import Enum

from helpers import loadFile

obstacle = '#'
guard = '^'

input = loadFile(__file__)

# 0 - UP | 1 - RIGHT | 2 - DOWN | 3 - LEFT
direction = 0

# Rotate 90° clockwise.
def rotate(direction):
    return (0 if direction == 3 else direction + 1)

def column(column):
    global input
    return [row[column] for row in input]

start_position = (0, 0)
for it, row in enumerate(input):
    if guard in row:
        start_position = (row.index(guard), it)
        break

width = len(input[0]) - 1
height = len(input) - 1

loops = 0

# Put obstacle at every possible empty tile and check if it loops to 2.5B steps. Total brute force. Expected result: 2262
for x in range(len(input[0])):
    for y in range(len(input)):
        if input[x][y] == '#':
            continue

        current_position = start_position
        steps = 0
        maze = [row for row in input]
        maze[x] = maze[x][:y] + '#' + maze[x][y+1:]

        while True:
            steps += 1
            if steps >= 2500000000:
                loops += 1
                break

            match direction:
                case 0:
                    if current_position[1] == 0:
                        break
                    elif maze[current_position[1] - 1][current_position[0]] == '#':
                        direction = rotate(direction)
                    else:
                        current_position = (current_position[0], current_position[1] - 1)

                case 1:
                    if current_position[0] == width:
                        break
                    elif maze[current_position[1]][current_position[0] + 1] == '#':
                        direction = rotate(direction)
                    else:
                        current_position = (current_position[0] + 1, current_position[1])

                case 2:
                    if current_position[1] == height:
                        break
                    elif maze[current_position[1] + 1][current_position[0]] == '#':
                        direction = rotate(direction)
                    else:
                        current_position = (current_position[0], current_position[1] + 1)

                case 3:
                    if current_position[0] == 0:
                        break
                    elif maze[current_position[1]][current_position[0] - 1] == '#':
                        direction = rotate(direction)
                    else:
                        current_position = (current_position[0] - 1, current_position[1])

print(loops)


enerator": {
                "shapes": [ps, C_Y],
                "filter_spec": [25, 100, 500, 100, C_X],
            },
            "Approximator": {
                "shapes": [ps, C_X],
                "filter_spec": [25, 100, 500, 100, C_X],
            },
            "Discriminator": {
                "shapes": [ps, C_X],
                "filter_spec": [25, 100, 200, 50, 1],
            },
        }
    else:
        TRANSLATION_SPEC = {
            "Generator": {"shapes": [ps, C_Y], "filter_spec": [25, C_X],},
            "Approximator": {"shapes": [ps, C_X], "filter_spec": [25, C_X],},
            "Discriminator": {"shapes": [ps, C_X], "filter_spec": [25, 1]},
        }
    print("Change Detector Init")
    cd = CGAN(TRANSLATION_SPEC, **CONFIG)
    print("Training")
    training_time = 0
    for epoch in trange(CONFIG["epochs"]):
        CONFIG.update(epochs=1)
        dataset = [x, y, Pu]
        TRAIN = tf.data.Dataset.from_tensor_slices(tuple(dataset))
        TRAIN = TRAIN.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
        tr_time, _ = cd.train(TRAIN, evaluation_dataset=EVALUATE, **CONFIG)
        if epoch > 10:
            for x_im, y_im, _ in EVALUATE.batch(1):
                Pu = cd._change_map(cd([x_im, y_im]))
            Pu = image_in_patches(Pu, ps)
            Pu = tf.reshape(Pu, [-1, Pu.shape[-1]])
            Pu = tf.round(tf.reduce_mean(tf.cast(Pu, dtype=tf.float32), axis=-1))

    cd.final_evaluate(EVALUATE, **CONFIG)
    metrics = {}
    for key in list(cd.difference_img_metrics.keys()) + list(
        cd.change_map_metrics.keys()
    ):
        metrics[key] = cd.metrics_history[key][-1]
    metrics["F1"] = metrics["TP"] / (
        metrics["TP"] + 0.5 * (metrics["FP"] + metrics["FN"])
    )
    timestamp = cd.timestamp
    epoch = cd.epoch.numpy()
    return final_kappa, epoch, training_time, timestamp

if __name__ == "__main__":
    test("Texas")
    test("California")