se["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise e
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def DescribeTaskTemplates(self, request):
        """用于查询任务模板信息

        :param request: 调用DescribeTaskTemplates所需参数的结构体。
        :type request: :class:`tencentcloud.batch.v20170312.models.DescribeTaskTemplatesRequest`
        :rtype: :class:`tencentcloud.batch.v20170312.models.DescribeTaskTemplatesResponse`

        """
        try:
            params = request._serialize()
            body = self.call("DescribeTaskTemplates", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.DescribeTaskTemplatesResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise e
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def ModifyComputeEnv(self, request):
        """用于修改计算环境的期望节点数量

        :param request: 调用ModifyComputeEnv所需参数的结构体。
        :type request: :class:`tencentcloud.batch.v20170312.models.ModifyComputeEnvRequest`
        :rtype: :class:`tencentcloud.batch.v20170312.models.ModifyComputeEnvResponse`

        """
        try:
            params = request._serialize()
            body = self.call("ModifyComputeEnv", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.ModifyComputeEnvResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise e
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def ModifyTaskTemplate(self, request):
        """用于修改任务模板

        :param request: 调用ModifyTaskTemplate所需参数的结构体。
        :type request: :class:`tencentcloud.batch.v20170312.models.ModifyTaskTemplateRequest`
        :rtype: :class:`tencentcloud.batch.v20170312.models.ModifyTaskTemplateResponse`

        """
        try:
            params = request._serialize()
            body = self.call("ModifyTaskTemplate", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.ModifyTaskTemplateResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise e
            else:
                raise TencentCloudSDKException(e.message, e.message)

    def SubmitJob(self, request):
        """用于提交一个作业

        :param request: 调用SubmitJob所需参数的结构体。
        :type request: :class:`tencentcloud.batch.v20170312.models.SubmitJobRequest`
        :rtype: :class:`tencentcloud.batch.v20170312.models.SubmitJobResponse`

        """
        try:
            params = request._serialize()
            body = self.call("SubmitJob", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.SubmitJobResponse()
                model._deserialize(response["Response"])
                return model
            else:


，也就是只存了索引，没有存数据，因为要筛选出来TraceID和SpanID，然后根据这两个ID去HBase里取原始数据。

HBase里存储的是HBase的原始数据，除了TraceID和SpanID，因为这两个属性的数据在ES里已经有了。HBase里的每条数据是一个Span，每条数据的RowKey是xx-TraceID-SpanID，最开始的两个字符是TraceID做hash取前两位，为什么要做个hash？因为我们TraceID的开头是应用名，如果不加前面两位hash值的话，根据HBase存储数据的策略，前缀一样的会存储到一起，也就是同一个应用的Trace会存储到一起，那么流量大的应用Trace会很多，这样就会导致倾斜问题，加两位hash值可以让数据分散开，并且同一个TraceID的数据会存储到一起，可以一次性Scan出来。

既然RowKey的设计已经考虑到了倾斜问题，已经做了hash分散数据，那为什么日常会存在倾斜问题？而且偶尔会出现很严重的倾斜问题？原因是每个Trace的Span数量是不一样的，有的Trace可能就几个Span，有的Trace有几万个Span，还会出现一种极端情况，一个MQ消费者消费消息后又向好几个Topic里发送了消息，后续的消费者重复这样的操作，导致一条消息最终放大了几万甚至几十万倍，导致一个Trace里有几十万甚至几千万个Span，这只是其中一种场景，也可能业务开发做了什么骚操作，也会导致一个Trace包含的Span数量非常多，那么根据现在的存储架构，同一个Trace的数据会存储到一起，这就导致了倾斜问题。

方案设计

在定位到问题后，最直接的想法就是彻底打散RowKey，也就是把SpanID的MD5当作RowKey，因为SpanID是全局唯一的，所以MD5必然是彻底打散的，不过这样做有一个坏处，就是数据彻底打散后，要查出一整个Trace的话，就得一个Span一个Span去查，不像之前的RowKey设计可以一次性Scan出来。

为了知道这样查询性能有多慢，特意做了一次性能测试，结果如下：

 span数量(个)	 scan(ms)	 search_es(ms)	 gets(ms)	 gets_parallel_batch100(ms)	 gets_parallel_batch200(ms)	 gets_parallel_batch300(ms)	 gets_parallel_batch500(ms)

 100	 5	 12	 12+10</


KR 70₃₃₀, SC 18₄₀₂, TC 90₅₇₅.
    '4r1d6w2t6q,'
    // #4621: 5 fonts: HK 94₁₂₁, JP 19₁₅₅, KR 71₃₃₁, SC 21₄₀₅, TC 90₅₇₅.
    '4r1h6t2v6n,'
    // #4622: 5 fonts: HK 94₁₂₁, JP 19₁₅₅, KR 72₃₃₂, SC 85₄₆₉, TC 90₅₇₅.
    '4r1h6u5g4b,'
    // #4623: 4 fonts: HK 94₁₂₁, JP 19₁₅₅, SC 86₄₇₀, TC 90₅₇₅.
    '4r1h12c4a,'
    // #4624: 5 fonts: HK 94₁₂₁, JP 20₁₅₆, KR 72₃₃₂, SC 85₄₆₉, TC 90₅₇₅.
    '4r1i6t5g4b,'
    // #4625: 5 fonts: HK 94₁₂₁, JP 20₁₅₆, KR 72₃₃₂, SC 86₄₇₀, TC 90₅₇₅.
    '4r1i6t5h4a,'
    // #4626: 5 fonts: HK 94₁₂₁, JP 21₁₅₇, KR 73₃₃₃, SC 87₄₇₁, TC 90₅₇₅.
    '4r1j6t5h3z,'
    // #4627: 4 fonts: HK 94₁₂₁, JP 21₁₅₇, SC 24₄₀₈, TC 90₅₇₅.
    '4r1j9q6k,'
    // #4628: 5 fonts: HK 94₁₂₁, JP 22₁₅₈, KR 73₃₃₃, SC 25₄₀₉, TC 90₅₇₅.
    '4r1k6s2x6j,'
    // #4629: 5 fonts: HK 94₁₂₁, JP 22₁₅₈, KR 73₃₃₃, SC 92₄₇₆, TC 90₅₇₅.
    '4r1k6s5m3u,'
    // #4630: 5 fonts: HK 94₁₂₁, JP 23₁₅₉, KR 74₃₃₄, SC 84₄₆₈, TC 90₅₇₅.
    '4r1l6s5d4c,'
    // #4631: 4 fonts: HK 94₁₂₁, JP 23₁₅₉, SC 27₄₁₁, TC 90₅₇₅.
    '4r1l9r6h,'
    // #4632: 4 fonts: HK 94₁₂₁, JP 23₁₅₉, SC 28₄₁₂, TC 90₅₇₅.
    '4r1l9s6g,'
    // #4633: 5 fonts: HK 94₁₂₁, JP 26₁₆₂, KR 76₃₃₆, SC 31₄₁₅, TC 90₅₇₅.
    '4r1o6r3a6d,'
    // #4634: 5 fonts: HK 94₁₂₁, JP 26₁₆₂, KR 76₃₃₆, SC 32₄₁₆, TC 90₅₇₅.
    '4r1o6r3b6c,'
    // #4635: 4 fonts: HK 94₁₂₁, JP 26₁₆₂, SC 84₄₆₈, TC 90₅₇₅


over/pulls">
        Pull requests
        12
        <meta itemprop="position" content="3">

          Projects
          0
          <meta itemprop="position" content="4">

          Wiki
          <meta itemprop="position" content="5">

        Pulse

          Community

    Permalink

    Branch:
    master

    <include-fragment class="select-menu-loading-overlay anim-pulse">
      <svg height="32" class="octicon octicon-octoface" viewBox="0 0 16 16" version="1.


v1.IPFamily{corev1.IPv4Protocol}, svcName,
						trafficPolicy, client, 2, gobgpClient, containerIP, "")
				},
				Entry("with external traffic policy - cluster", "test-svc-cluster", SOffset.Get(), corev1.ServiceExternalTrafficPolicyCluster),
				Entry("with external traffic policy - local", "test-svc-local", SOffset.Get(), corev1.ServiceExternalTrafficPolicyLocal),
			)

			DescribeTable("only stops advertising route if it was referenced by multiple services and all of them were deleted while using common lease",
				func(svcName string, offset uint, trafficPolicy corev1.ServiceExternalTrafficPolicy) {
					testBGP(offset, e2e.IPv4Family, api.Family_AFI_IP, []corev1.IPFamily{corev1.IPv4Protocol}, svcName,
						trafficPolicy, client, 2, gobgpClient, containerIP, "common-lease")
				},
				Entry("with external traffic policy - cluster", "test-svc-cluster", SOffset.Get(), corev1.ServiceExternalTrafficPolicyCluster),
			)
		})
	}
})

func testBGP(offset uint, lbFamily string, afiFamily api.Family_Afi, svcFamily []corev1.IPFamily, svcName string,
	trafficPolicy corev1.ServiceExternalTrafficPolicy, client kubernetes.Interface, numberOfServices int,
	gobgpClient api.GobgpApiClient, expectedNexthop string, serviceLease string) {
	lbAddress := e2e.GenerateVIP(lbFamily, offset)
	routeCheckFamily := &api.Family{
		Afi:  afiFamily,
		Safi: api.Family_SAFI_UNICAST,
	}
	testServiceBGP(svcName, lbAddress, trafficPolicy, client, svcFamily, numberOfServices, gobgpClient, routeCheckFamily, expectedNexthop, serviceLease)
}

func setupEnv(cpVIP, clusterName *string, tempDirPath string, manifestValues *e2e.KubevipManifestValues,
	localIPv4, localIPv6, imagePath, configPath, k8sImagePath, clusterAddrFamily, bgpClientAddrFamily string, peerAddrFamily []string, client *kubernetes.Interface,
	gobgpPeers *[]*e2e.BGPPeerValues, v129 bool, kubeVIPBGPManifestTemplate *template.Template, gobgpClient *api.GobgpApiClient,
	logger log.Logger, nodesNumber int, mpbgpnexthop, clusterNameSuffix string, serviceElection bool) (string, string) {
	var err error

	*cpVIP = e2e.GenerateVIP(clusterAddrFamily, SOffset.Get())

	var clusterIPFamily kindconfigv1alpha4.ClusterIPFamily
	var podSubnet, serviceSubnet string
	switch clusterAddrFamily {
	case e2e.IPv6Family:
		clusterIPFamily = kindconfigv1alpha4.IPv6Family
	case e2e.DualstackFamily:
		clusterIPFamily = kindconfigv1alpha4.DualStackFamily
	case e2e.DualstackFamilyIPv6:
		clusterIPFamily = kindconfigv1alpha4.DualStackFamily
		podSubnet = "fd00:10:244::/56,10.244.0.0/16"
		serviceSubnet = "fd00:10:96::/112,10.96.0.0/16"
	default:
		clusterIPFamily = kindconfigv1alpha4.IPv4Family
	}

	networking := &kindconfigv1alpha4.Networking{
		IPFamily: clusterIPFamily,
	}

	if podSubnet !


st (#502).
            Ok(mut addrs) => match addrs.next() {
                Some(addr) => Ok(addr),
                None => Err(anyhow!("{} did not resolve to any addresses", addr)),
            },
            Err(err) => Err(anyhow!("error resolving {}: {}", addr, err)),
        })
        .collect::<Result<Vec<_>, _>>()?)
}

lazy_static! {
    static ref PANIC_MUTEX: Mutex<()> = Mutex::new(());
}

fn handle_panic(panic_info: &PanicInfo) {
    let _guard = PANIC_MUTEX.lock();

    let thr = thread::current();
    let thr_name = thr.name().unwrap_or("<unnamed>");

    let msg = match panic_info.payload().downcast_ref::<&'static str>() {
        Some(s) => *s,
        None => match panic_info.payload().downcast_ref::<String>() {
            Some(s) => &s[..],
            None => "Box<Any>",
        },
    };

    log::error!(target: "panic", "{}: {}\n{:?}", thr_name, msg, Backtrace::new());
    eprintln!(
        r#"materialized encountered an internal error and crashed.

We rely on bug reports to diagnose and fix these errors. Please
copy and paste the above details and file a report at:

    https://materialize.io/s/bug

To protect your privacy, we do not collect crash reports automatically."#,
    );
    process::exit(1);
}

/// Print to the screen information about how to contact us.
fn beta_splash() {
    eprintln!(
        "=======================================================================
Thank you for trying Materialize!

We are interested in any and all feedback you have, which may be able
to improve both our software and your queries! Please reach out at:

    Web: https://materialize.io
    GitHub issues: https://github.com/MaterializeInc/materialize/issues
    Email: <EMAIL>
    Twitter: @MaterializeInc
=======================================================================
"
    );
}

/// Print a warning about the dangers of using experimental mode.
fn experimental_mode_splash() {
    eprintln!(
        "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                               WARNING!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Starting Materialize in experimental mode means:

- This node's catalog of views and sources are unstable.

If you use any version of Materialize besides this one, you might
not be able to start the Materialize node. To fix this, you'll have
to remove all of Materialize's data (e.g. rm -rf mzdata) and start
the node anew.

- You must always start this node in experimental mode; it can no
longer be started in non-experimental/regular mode.

For more details, see https://materialize.io/docs/cli#experimental-mode
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
"
    );
}

fn print_build_info() {
    let openssl_version =
        unsafe { CStr::from_ptr(openssl_sys::OpenSSL_version(openssl_sys::OPENSSL_VERSION)) };
    let rdkafka_version = unsafe { CStr::from_ptr(rdkafka_sys::bindings::rd_kafka_version_str()) };
    println!("{}", openssl_version.to_string_lossy());
    println!("librdkafka v{}", rdkafka_version.to_string_lossy());
}

#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "ios")))]
fn adjust_rlimits() {
    trace!("rlimit crate does not support this OS; not adjusting nofile limit");
}

#[cfg(any(target_os = "macos", target_os = "linux", target_os = "ios"))]
/// Attempts to increase the soft nofile rlimit to the maximum possible value.
fn adjust_rlimits() {
    // getrlimit/setrlimit can have surprisingly different behavior across
    // platforms, even with the rlimit wrapper crate


 of the controller, you may also send vibration data to the controller to alter the feedback provided to the user of the controller. The controller contains two rumble motors that can be independently controlled by passing values to the [**XInputSetState**](/windows/desktop/api/XInput/nf-xinput-xinputsetstate) function.

The speed of each motor can be specified using a WORD value in the [**XINPUT\_VIBRATION**](/windows/desktop/api/XInput/ns-xinput-xinput_vibration) structure that is passed to the [**XInputSetState**](/windows/desktop/api/XInput/nf-xinput-xinputsetstate) function as follows:

```cpp
XINPUT_VIBRATION vibration;
ZeroMemory( &vibration, sizeof(XINPUT_VIBRATION) );
vibration.wLeftMotorSpeed = 32000; // use any value between 0-65535 here
vibration.wRightMotorSpeed = 16000; // use any value between 0-65535 here
XInputSetState( i, &vibration );
```

Note that the right motor is the high-frequency motor, the left motor is the low-frequency motor. They do not always need to be set to the same amount, as they provide different effects.

### Getting Audio Device Identifiers

The headset for a controller has these functions:

-   Record sound using a microphone
-   Play back sound using a headphone

Use this code to obtain the device identifiers for the headset:

```cpp
WCHAR renderId[ 256 ] = {0};
WCHAR captureId[ 256 ] = {0};
UINT rcount = 256;
UINT ccount = 256;

XInputGetAudioDeviceIds( i, renderId, &rcount, captureId, &ccount );
```

After you obtain the device identifiers, you can create the appropriate interfaces. For example, if you use XAudio 2.8, use this code to create a mastering voice for this device:

```cpp
IXAudio2* pXAudio2 = NULL;
HRESULT hr;
if ( FAILED(hr = XAudio2Create( &pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) )
    return hr;

IXAudio2MasteringVoice* pMasterVoice = NULL;
if ( FAILED(hr = pXAudio2->CreateMasteringVoice( &pMasterVoice, XAUDIO2_DEFAULT_CHANNELS, XAUDIO2_DEFAULT_SAMPLERATE, 0, renderId, NULL, AudioCategory_Communications ) ) )
    return hr;
```

For info about how to use the captureId device identifier, see [Capturing a Stream](/windows/desktop/CoreAudio/capturing-a-stream).

### Getting DirectSound GUIDs (legacy DirectX SDK only)

The headset that can be connected to a controller has two functions: it can record sound using a microphone, and it can play back sound using a headphone. In the XInput API, these functions are accomplished through [DirectSound](/previous-versions/windows/desktop/ee416960(v=vs.85)), using the **IDirectSound8** and **IDirectSoundCapture8** interfaces.

To associate the headset microphone and headphone with their appropriate [DirectSound](/previous-versions/windows/desktop/ee416960(v=vs.85)) interfaces, you must get the DirectSoundGUIDs for the capture and render devices by calling [**XInputGetDSoundAudioDeviceGuids**](/windows/desktop/api/XInput/nf-xinput-xinputgetdsoundaudiodeviceguids).

> [!Note]
> Use of the legacy [DirectSound](/previous-versions/windows/desktop/ee416960(v=vs.85)) is not recommended, and is not available in Windows Store apps. The info in this section only applies to the DirectX SDK version of XInput (XInput 1.3). The Windows 8 version of XInput (XInput 1.4) exclusively uses Windows Audio Session API (WASAPI) device identifiers that are obtained through [**XInputGetAudioDeviceIds**](/windows/desktop/api/XInput/nf-xinput-xinputgetaudiodeviceids).

```cpp
XInputGetDSoundAudioDeviceGuid


						while (helv.getWidthPoint(sFl, textHeight) > (2 * (radius - TEXT_TO_CIRCLE_INTERSPACE)))
							textHeight--;
						float fAscent = helv.getAscentPoint(sFl, textHeight) + helv.getDescentPoint(sFl, textHeight);
						over.setFontAndSize(helv, textHeight);
						over.showTextAligned(Element.ALIGN_CENTER, sFl, xCenter, yCenter - 0.5f * fAscent, 0);
						over.endText();
						over.restoreState();
					}
				}

			}
			stamp.close();
			byte[] pdf = bo2.toByteArray();
			return pdf;
		}
	}

	private static String gerarReducaoAssinaturas(boolean reduzirVisuAssinPdf, String mensagem) {
		Pattern pattern = Pattern.compile("\\b(Assinado|Autenticado)\\b");
		if (reduzirVisuAssinPdf && pattern.matcher(mensagem).find()) {
			pattern = Pattern.compile("\\b(Assinado|Autenticado)\\b|(,| e )|(\\bDocumento Nº: \\b)");
	        Matcher mm = pattern.matcher(mensagem);

	        Map<Integer, Integer> assinaturas = new HashMap<Integer, Integer>();
	        int contador=0;
			while(mm.find()) {
				//System.out.println(mm.start() +" "+ mm.group() +" "+ mm.end());
				assinaturas.put(++contador, mm.start());
	        }
			if (!assinaturas.isEmpty() && assinaturas.size() > 2) {
				StringBuilder str = new StringBuilder();
				//print 2 assinaturas
				str.append(mensagem.substring(assinaturas.get(1), assinaturas.get(3)));
				str.append(" +" + (assinaturas.size() - (mensagem.substring(assinaturas.get(assinaturas.size())).contains("Documento Nº:") ? 3 : 2))
									+ " Pessoas - Para verificar todas as assinaturas consulte o link de autenticação. \n");
				str.append(mensagem.substring(assinaturas.get(assinaturas.size())));
				return str.toString();
			}
		}
		return mensagem;
	}

	private static byte[] estamparAssinaturas(byte[] pdf, List<Long> idsAssinantes) {
		try {
			PDDocument doc;
			doc = PDDocument.load(pdf);

			List<String> seek = new ArrayList<>();
			for (Long id : idsAssinantes)
				seek.add(VALIDAR_ASSINATURA_URL + id + "&");

			List<LocalizaAnotacaoResultado> l = LocalizaAnotacao.localizar(doc, seek);
			if (l == null)
				return pdf;

			byte[] abStamp = SigaHTTP
					.convertStreamToByteArray(Stamp.class.getResourceAsStream("assinado-digitalmente.png"), 4096);
			PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, abStamp, "assinado digitalmente");

			Set<String> set = new HashSet<>();

			for (LocalizaAnotacaoResultado i : l) {
				System.out.println("achei: " + i.page + ", (" + i.lowerLeftX + ", " + i.upperRightY + ")");
				if (set.contains(i.uri))
					continue;
				set.add(i.uri);
				System.out.println("processando: " + i.page + ", (" + i.lowerLeftX + ", " + i.upperRightY + ")");

				PDPage page = doc.getPage(i.page - 1);

				PDPageContentStream contents = new PDPageContentStream(doc, page, true, true);
				float height = i.height * 1.2f;
				float width = pdImage.getWidth() * (


ipe)
    }

    override fun selectedRecipe(container: StonecutterContainer): Int {
        return container.`(selectedRecipe)`
    }

    override fun selectedRecipeOrNull(container: StonecutterContainer?): Int? {
        return container?.`(selectedRecipe)`
    }

}
/*
 * Inventory Profiles Next
 *
 *   Copyright (c) 2019-2020 jsnimda <7615255+jsnimda@users.noreply.github.com>
 *   Copyright (c) 2021-2022 Plamen K. Kosseff <p.kosseff@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package org.anti_ad.mc.ipnext.parser

import org.anti_ad.mc.common.LogBase
import org.anti_ad.mc.ipnext.Log
import org.anti_ad.mc.common.Savable
import org.anti_ad.mc.common.TellPlayer
import org.anti_ad.mc.common.annotation.MayThrow
import org.anti_ad.mc.common.extensions.createDirectories
import org.anti_ad.mc.common.extensions.div
import org.anti_ad.mc.common.extensions.exists
import org.anti_ad.mc.common.extensions.listFiles
import org.anti_ad.mc.common.extensions.name
import org.anti_ad.mc.common.extensions.tryOrPrint
import org.anti_ad.mc.common.extensions.writeToFile
import org.anti_ad.mc.common.gui.widgets.ConfigButtonClickHandler
import org.anti_ad.mc.ipnext.profiles.config.ProfileData
import org.anti_ad.mc.ipnext.profiles.config.ProfilesConfig
import org.anti_ad.mc.ipnext.profiles.config.dump
import org.anti_ad.mc.common.util.LogicalStringComparator
import org.anti_ad.mc.common.vanilla.VanillaUtil
import org.anti_ad.mc.ipnext.config.ModSettings
import org.anti_ad.mc.ipnext.event.LockSlotsHandler
import org.anti_ad.mc.ipnext.integration.HintsManagerNG
import org.anti_ad.mc.ipnext.inventory.ContainerTypes
import org.anti_ad.mc.ipnext.item.rule.file.RuleFile
import org.anti_ad.mc.ipnext.item.rule.file.RuleFileRegister
import org.anti_ad.mc.ipnext.specific.serverIdentifier
import org.anti_ad.mc.common.extensions.dashedSanitized
import org.anti_ad.mc.common.extensions.ifTrue
import org.anti_ad.mc.common.extensions.loggingPath
import org.anti_ad.mc.common.extensions.sanitized
import org.anti_ad.mc.ipnext.ModInfo
import org.anti_ad.mc.ipnext.NotificationManager
import org.anti_ad.mc.ipnext.event.autorefill.AutoRefillHandler
import org.anti_ad.mc.ipnext.event.ProfileSwitchHandler
import org.anti_ad.mc.ipnext.event.villagers.VillagerDataManager
import org.anti_ad.mc.ipnext.integration.SlotIntegrationHints
import java.nio.file.Path
import kotlin.io.path.deleteExisting
import kotlin.io.path.notExists
import kotlin.io.path.readText
import kotlin.io.path.writeText

private val strCmpLogical = LogicalStringComparator.file()

object ReloadRuleFileButtonInfoDelegate : ConfigButtonClickHandler() {

    override fun onClick(guiClick: () -> Unit) {
        TellPlayer.listenLog(LogBase.LogLevel.INFO) {


## otherwise, just update the image
        else:
            self.update_image()

    go_to_top = partialmethod(walk, -INFINITY)
    go_to_bottom = partialmethod(walk, INFINITY)

    def scroll(self, steps):
        """Scroll items."""

        itvi = self.index_of_top_visible_item
        nvl = self.no_of_visible_lines
        length = len(self.item_objects)

        ### if steps == 0 or number of visible lines is equal or higher
        ### than number of items, there's no need to scroll, so we exit
        ### the method by returning
        if not steps or (nvl >= length):
            return

        ### if scrolling down (items go up), ensure last item
        ### doesn't go above last visible line

        elif steps > 0:

            ## index of bottom visible item
            ibvi = itvi + nvl

            ## index of last item
            ili = length

            ##
            if ibvi + steps > ili:
                steps = ili - ibvi

        ### if scrolling up (items go down), ensure first item
        ### doesn't go below first visible line

        elif steps < 0:

            if itvi + steps < 0:
                steps = -itvi

        ### finally, increment/decrement the index of the top visible
        ### item and update the image

        self.index_of_top_visible_item += steps
        self.update_image()

    def sort(self):

        self.items.sort()
        self.item_objects.sort(key=lambda item: item.value)

        self.selected_flags.clear()
        self.selected_flags.extend(0 for _ in self.items)

        self.index_of_top_visible_item = 0
        self.index_of_last_selected = None

        self.update_image()


                30 => (new WDir(+5, +5), true),
                31 => (new WDir(-15, -15), true),
                32 => (new WDir(+15, -15), true),
                33 => (new WDir(-15, +15), true),
                34 => (new WDir(+15, +15), true),
                _ => (new WDir(), false)
            };
            if (offset != default)
            {
                AddTower(Module.Center + offset, blue);
            }
        }
    }

    public override void OnStatusGain(Actor actor, ActorStatus status)
    {
        var blueSlot = (SID)status.ID switch
        {
            SID.OdderPrayer => 0,
            SID.OdderIncarnation1 => 1,
            SID.OdderIncarnation2 => 2,
            SID.OdderIncarnation3 => 3,
            _ => -1
        };
        if (blueSlot >= 0 && Raid.TryFindSlot(actor.InstanceID, out var slot))
            _playerBlue[slot, blueSlot] = true;
    }

    public override void OnStatusLose(Actor actor, ActorStatus status)
    {
        if ((SID)status.ID is SID.SquirrellyPrayer or SID.OdderPrayer)
        {
            _baitsDone = true;
            EnableNextTowers();
        }
    }

    public override void OnEventCast(Actor caster, ActorCastEvent spell)
    {
        if ((AID)spell.Action.ID is AID.NBurstOrange or AID.NBurstBlue or AID.SBurstOrange or AID.SBurstBlue)
        {
            ++NumCasts;
            var index = Towers.FindIndex(t => t.Position.AlmostEqual(caster.Position, 1));
            if (index >= 0)
                Towers.RemoveAt(index);
            else
                ReportError($"Failed to find at {caster.Position}");
            if ((NumCasts & 3) == 0)
                EnableNextTowers();
        }
    }

    private void AddTower(WPos position, bool blue)
    {
        if (blue)
            _blueTowers.Set(Towers.Count);
        Towers.Add(new(position, TowerRadius, 0, 0, new(0xF)));
    }

    private void EnableNextTowers()
    {
        var blueSlot = NumCasts / 4 + 1;
        BitMask forbiddenOrange = new();
        foreach (var (slot, _) in Raid.WithSlot(true))
            if (_playerBlue[slot, blueSlot])
                forbiddenOrange.Set(slot);
        var forbiddenBlue = forbiddenOrange ^ new BitMask(0xF);
        for (int i = 0, limit = Math.Min(4, Towers.Count); i < limit; ++i)
        {
            Towers.AsSpan()[i].ForbiddenSoakers = _blueTowers[i + NumCasts] ? forbiddenBlue : forbiddenOrange;
        }
    }
}

class FlickeringFlame(BossModule module, AID aid) : Components.StandardAOEs(module, aid, new AOEShapeRect(46, 2.5f), 8);
class NFlickeringFlame(BossModule module) : FlickeringFlame(module, AID.NFireSpreadCross);
class SFlickeringFlame(BossModule module) : FlickeringFlame(module, AID.SFireSpreadCross);


YEBROW_HEIGHT,
            SLIDER_NAME_EYEBROW_ANGLE,
            SLIDER_NAME_EYEBROW_SKEW,
            SLIDER_NAME_EYEBROW_DEPTH,
        },

        [SLIDER_SUBCAT_FACE_NOSE] =
        {
            SLIDER_NAME_NOSE_SHAPE,
            SLIDER_NAME_NOSE_HEIGHT,
            SLIDER_NAME_NOSE_WIDTH,
            SLIDER_NAME_NOSE_LENGTH,
        },

        [SLIDER_SUBCAT_FACE_MOUTH] =
        {
            SLIDER_NAME_MOUTH_HEIGHT,
            SLIDER_NAME_MOUTH_WIDTH,
            SLIDER_NAME_MOUTH_CURVE,
            SLIDER_NAME_LIP_FULLNESS,
        },

        [SLIDER_SUBCAT_FACE_EARS] =
        {
            SLIDER_NAME_EAR_SIZE,
            SLIDER_NAME_EAR_ROTATION,
            SLIDER_NAME_EAR_HEIGHT,
            SLIDER_NAME_EAR_TIP_FLARE,
        },
    }

    local function SliderComparator(data1, data2)
        local name1 = data1.name
        local name2 = data2.name

        local subCat1 = data1.subCat
        local subCat2 = data2.subCat

        if subCat1 ~= subCat2 then
            return subCat1 < subCat2
        end

        return FindOrdering(CONTROL_ORDERING[subCat1], name1) < FindOrdering(CONTROL_ORDERING[subCat2], name2)
    end

    local SLIDER_CATEGORY_TO_CREATE_BUCKET =
    {
        [SLIDER_CATEGORY_AGE] = CREATE_BUCKET_BODY,
        [SLIDER_CATEGORY_BODY] = CREATE_BUCKET_BODY,
        [SLIDER_CATEGORY_FACE] = CREATE_BUCKET_FACE,
    }

    local APPEARANCE_NAME_TO_CREATE_BUCKET =
    {
        [APPEARANCE_NAME_HAIR_STYLE] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_HAIR_TINT] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_SKIN_TINT] = CREATE_BUCKET_BODY,
        [APPEARANCE_NAME_ACCESSORY] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_HEAD_MARKING] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_BODY_MARKING] = CREATE_BUCKET_BODY,
        [APPEARANCE_NAME_EYE_TINT] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_AGE] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_EYEBROW] = CREATE_BUCKET_FACE,
        [APPEARANCE_NAME_VOICE] = CREATE_BUCKET_FACE,
    }

    local SUBCATEGORY_FOR_SLIDER =
    {
        [SLIDER_NAME_FOREHEAD_SLOPE] = SLIDER_SUBCAT_FACE_FACE,
        [SLIDER_NAME_CHEEK_BONE_SIZE] = SLIDER_SUBCAT_FACE_FACE,
        [SLIDER_NAME_CHEEK_BONE_HEIGHT] = SLIDER_SUBCAT_FACE_FACE,


},
		{"percent-encoded-crlf", `"toni.tester@example.com%0d%0aRCPT TO:<other@example.com>"@example.com`, false},

		// null / control byte insertion
		{"null-byte", `"toni.tester@example.com\000> ORCPT=admin@example.com"@example.com`, false},

		// explicit CRLF-injection attempts
		{"crlf-rcpt", `"toni.tester@example.com">\r\nRCPT TO:<attacker@example.com>"@example.com`, true},
		{"crlf-mailfrom", `"toni.tester@example.com">\r\nMAIL FROM:<attacker@example.com>"@example.com`, true},

		// folding whitespace / long-wrapping
		{"folding-ws", `"toni.tester@example.com> \r\n\tORCPT=admin@example.com"@example.com`, false},

		// unicode / homoglyphs
		{"unicode-fullwidth", `"toni.tester@example.com> ORCPT=admin@ｅxample.com"@example.com`, false},
		{"unicode-hidden", `"toni.tester@example.com> ORCPT=admin@exam` + "\u200c" + `ple.com"@example.com`, false},

		// multiple @ / nested-at attempts
		{"nested-at", `"toni.tester@example.com> ORCPT=admin@sub@example.com"@example.com`, false},
		{"double-at", `"toni.tester@example.com> ORCPT=admin@@example.com"@example.com`, false},

		// long / overflow-ish
		{"long-localpart", `"toni.tester@example.comAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA> ORCPT=admin@example.com"@example.com`, false},

		// safe detection-only marker
		{"detection-marker", `"toni.tester@example.com> X-INJECT-TEST=smuggle-detect@example.com"@example.com`, false},
	}

	t.Run("address command injects in recipients", func(t *testing.T) {
		for _, tc := range tests {
			t.Run(tc.name, func(t *testing.T) {
				message := NewMsg()
				if message == nil {
					t.Fatal("message is nil")
				}
				err := message.To(tc.payload)
				if err != nil && !tc.shouldFail {
					t.Errorf("failed to set to address: %s", err)
				}
				if err == nil && tc.shouldFail {
					t.Errorf("setting address was supposed to fail but didn't")
				}
				if tc.shouldFail {
					return
				}

				addr, err := mail.ParseAddress(tc.payload)
				if err != nil {
					t.Errorf("failed to parse address payload: %s", err)
				}
				rcpts, err := message.GetRecipients()
				if err != nil {
					t.Errorf("failed to get recipient: %s", err)
				}
				if len(rcpts) != 1 {
					t.Fatalf("expected 1 recipient, got: %d", len(rcpts))
				}
				if !strings.EqualFold(rcpts[0], addr.String()) {
					t.Errorf("recipients don't match, expected: %s, got: %s", addr.String(), rcpts[0])
				}
			})
		}
	})
	t.Run("address command injects in sender (from)", func(t *testing.T) {
		for _, tc := range tests {
			t.Run(tc.name, func(t *testing.T) {
				message := NewMsg()
				if message == nil {
					t.Fatal("message is nil")
				}
				err := message.From(tc.payload)
				if err != nil && !tc.shouldFail {
					t.Errorf("failed to set to address: %s", err)
				}
				if err == nil && tc.shouldFail {
					t.Errorf("setting address was supposed to fa


t } from "postcss";
import postcssFn from "postcss";

// eslint-disable-next-line @typescript-eslint/no-var-requires
const vars = require("postcss-simple-vars");

const PLUGIN_NAME = "utilitycss-postcss-for";

// eslint-disable-next-line @typescript-eslint/no-var-requires
const debug = require("debug")(PLUGIN_NAME);

const plugin = (): Plugin => {
  const iterStack: string[] = [];
  const value: {
    [key: string]: number;
  } = {};
  const manageIterStack = (rule: AtRule) => {
    if (rule.parent.type !== "root") {
      debug("rule.parent", (rule.parent as any)?.params);
      const parentIterVar =
        (rule.parent as any).params &&
        list.space((rule.parent as any).params)[0];
      if (iterStack.indexOf(parentIterVar) === -1) {
        // If parent isn't in stack, wipe stack
        iterStack.splice(0, iterStack.length);
      } else {
        // If parent is in stack, remove stack after parent
        iterStack.splice(
          iterStack.indexOf(parentIterVar) + 1,
          iterStack.length - iterStack.indexOf(parentIterVar) - 1
        );
      }
    } else {
      // If parent (root) isn't in stack, wipe stack
      iterStack.splice(0, iterStack.length);
    }
    // Push current rule on stack regardless
    iterStack.push(list.space(rule.params)[0]);
  };

  const parentsHaveIterator = (
    rule: AtRule | Container,
    param: string
  ): boolean => {
    if (rule.parent == null) {
      return false;
    }
    if (rule.parent.type === "root") {
      return false;
    }
    if ((rule.parent as any).params == null) {
      return false;
    }

    const parentIterVar = list.space((rule.parent as any).params);

    if (parentIterVar[0] == null) {
      return false;
    }
    if (parentIterVar[0] === param) {
      return true;
    }
    if (iterStack.indexOf(param) !== -1) {
      return true;
    }
    return parentsHaveIterator(rule.parent, param);
  };

  const checkNumber = (rule: AtRule) => {
    return (param: string) => {
      debug("param", param);
      if (isNaN(parseInt(param)) || !param.match(/^-?\d+\.?\d*$/)) {
        debug("Number is NaN");
        if (param.indexOf("$") !== -1) {
          if (!parentsHaveIterator(rule, param)) {
            throw new Error(
              "External variable (not from a parent for loop) cannot be used as a range parameter"
            );
          }
        } else {
          throw new Error("Range parameter should be a number");
        }
      }
    };
  };

  const validateParams = (rule: AtRule, params: string[]) => {
    const [one, two, three, four, five, six, seven] = params;
    if (
      !one.match(/(^|[^\w])\$([\w\d-_]+)/) ||
      two !== "from" ||
      four !== "to" ||
      (six !== "by") !== (six === undefined)
    ) {
      throw new Error("Wrong loop syntax");
    }

    const paramsToCheckForNumber = [three, five, seven || "0"];
    debug("checkNumber", paramsToCheckForNumber);

    paramsToCheckForNumber.forEach(checkNumber(rule));
  };

  const unrollLoop = (rule: AtRule) => {
    const params = list.space(rule.params);

    validateParams(rule, params);

    // debug("params", params);

    const [one, _, three, __, five, ___, seven] = params;

    const iterator = one.slice(1);
    const index = +three;
    const top = +five;
    const dir = top < index ? -1 : 1;
    const by = (+seven || 1) * dir;

    /* debug(`iterator =>


IC),
        transforms.Lambda(lambda x: x.float().div(255.0)),
    ])

    return t

def dreamsim_transform_Image(n_px):
    t = transforms.Compose([
        transforms.Resize((n_px, n_px),
                          interpolation=transforms.InterpolationMode.BICUBIC),
        transforms.ToTensor(),
    ])

    return t

def dinov2_transform(n_px):
    t = transforms.Compose([
        transforms.Resize(256, interpolation=transforms.InterpolationMode.BICUBIC),
        transforms.CenterCrop(n_px),
        transforms.Lambda(lambda x: x.float().div(255.0)),
        transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ])

    return t

def dinov2_transform_Image(n_px):
    t = transforms.Compose([
        transforms.Resize(256, interpolation=transforms.InterpolationMode.BICUBIC),
        transforms.CenterCrop(n_px),
        transforms.ToTensor(),
        transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ])

    return t


re": "2dcc71b5e8ba94ff5ee64467007b6afc412c3ee70e41855ab12a932ba95b89f2f72b499c8003f297b8e760a80ed7fd5de545467594f4ed1c9de166228b61fb29f2c6a8bdf387c98f7f47e1c058b64a1aa2e7f718606969e083069e26c775c40c0d79da746b52b9fae8ea3359b9bb18dd291a14dfd36a37277a9da0dacffffc22c4faf009ff33e93e17ba1cc742cfce2743d30c0c5581303db96060ce02ece19ee81ddc852ce0a18d966d95ac17a4713ea16741b6281d2ce3b615e5b7e5a2f6256d86e320acf9f8314f8e629b9833376d6af735523e90feb03b5fc5b852a9e06ea0479a279e97aea24a9e531939ec357ec659de3ae0aaf533f06abda0821812dea18c4570ca2bd62e959145995a5c240049bd23b30ceca43df5b9e1d1b1825a38eea3fba1ab483a8c5dffa065223fd3d3fe4990db1446a3852e8a554b09ab38b2ab63a008d1fdad48e273d812bcc26ca516fad09ac05e38383a2b718e553aac42197a1f0d4220e7ab5d8c6880524ca1c0d488d02321fb901309007b4937afa9df486022abf4f6c2363bf8513c34bbc586e43ae19f4b90fe5461024b159c34176aa94b8d4cb69d2326c83af1d6b805cdda1d6240183a2f1b41cd3a993a0aa9d1d77eb8c4aff7b8c980105ed55df6ce7a9a02c50f6381efb564e9fc5bd8d2619a68c37cf9c78df91e87d5fa2cf816ae9dab068fc86dc741cda14e84e3dac26ebcfb",
      "SignatureAlgorithmOID": "1.2.840.113549.1.1.5",
      "Subject": "C=US, O=thawte, Inc., OU=Certification Services Division, OU=(c) 2006 thawte, Inc. , For authorized use only, CN=thawte Primary Root CA",
      "TBS": {
        "MD5": "a3f222107d4e1085e73b5b589c2f480b",
        "SHA1": "b94aa26cd77c48d91a53ac44506cbd255e1d362c",
        "SHA256": "a39ed0d6fd4eb1a6f7fed60f726e23eae668b7591bc004644625d22c701213fa",
        "SHA384": "64b7643e4146016cbf83c911eb67e4601b6bb8d66f8ee8dcee67b815f91770d86ab23678b984430f22a963e5484881b7"
      },
      "ValidFrom": "2011-02-22 19:31:57",
      "ValidTo": "2021-02-22 19:41:57",
      "Version": 3
    }
  ],
  "CertificatesInfo": "",
  "Signer": [
    {
      "Issuer": "C=US, O=Thawte, Inc., CN=Thawte Code Signing CA , G2",
      "SerialNumber": "38de06b8be15187f107e04f8b1138977",
      "Version": 1
    }
  ],
  "SignerInfo": ""
}
```

{{< /details >}}
-----


// Authors:
//   Jose Medrano <josmed@microsoft.com>
//
// Copyright (C) 2018 Microsoft, Corp
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;

using AppKit;

using FigmaSharp;
using F


if (GetLocale() == "frFR") then

--------------------------------------------------------------------------------
-- ItemIDs (French)
--------------------------------------------------------------------------------

MetaMapBLTData = {

    --------------------
	-- Blackwing Lair --
	--------------------

	BWLRazorgore = {
		{ 16918, "INV_Bracer_09", "=q4=Bracelets de Vent du n\195\169ant", "=q1=Classes: =ds=Mage", "20.41%" },
		{ 16926, "INV_Bracer_09", "=q4=Bracelets de transcendance", "=q1=Classes: =ds=Pr\195\170tre", "20.37%" },
		{ 16934, "INV_Bracer_07", "=q4=Bracelets de N\195\169m\195\169sis", "=q1=Classes: =ds=D\195\169moniste", "18.11%" },
		{ 16911, "INV_Bracer_02", "=q4=Bracelets Rougecroc", "=q1=Classes: =ds=Voleur", "20.69%" },
		{ 16904, "INV_Bracer_03", "=q4=Bracelets de Stormrage", "=q1=Classes: =ds=Druide", "17.38%" },
		{ 16935, "INV_Bracer_17", "=q4=Bracelets de chasseur de dragon", "=q1=Classes: =ds=Chasseur", "19.13%" },
		{ 16943, "INV_Bracer_16", "=q4=Bracelets des dix temp\195\170tes", "=q1=Classes: =ds=Chaman", "7.54%" },
		{ 16959, "INV_Bracer_19", "=q4=Bracelets de courroux", "=q1=Classes: =ds=Guerrier", "20.29%" },
		{ 16951, "INV_Bracer_18", "=q4=Bracelets du jugement", "=q1=Classes: =ds=Paladin", "13.61%" },
		{ 0,"","","" },
		{ 0,"","","" },
		{ 0,"","","" },
		{ 0,"","","" },
		{ 0,"","","" },
		{ 0,"","","" },
		{ 19337, "INV_Misc_Book_06", "=q4=Le Livre noir", "=q1=Classes: =ds=D\195\169moniste =ds=Bijou", "18.37%" },
		{ 19336, "Spell_Nature_WispSplode", "=q4=Gemme impr\195\169gn\195\169e d'arcanes", "=q1=Classes: =ds=Chasseur =ds=Bijou", "17.33%" },
		{ 0,"","","" },
		{ 19370, "INV_Shoulder_25", "=q4=Mantelet de la cabale de l'Aile noire","=ds=Epaule, Tissu", "18.57%" },
		{ 19369, "INV_Gauntlets_06", "=q4=Gants de l'\195\169volution rapide", "=ds=Mains, Tissu", "17.52%" },
		{ 19335, "INV_Mace_06", "=q4=Brise-\195\169chine", "=ds=Main droite, Masse", "10.44%" },
		{ 19334, "INV_Sword_50", "=q4=La lame indompt\195\169e", "=ds=Deux mains, Ep\195\169e", "9.76%" },
		};
	BWLVaelastrasz = {
		{ 16818, "INV_Belt_22", "=q4=Ceinture de Vent du n\195\


        assert_eq!(Err(Error::CorruptMsgHeader), FileReader::new(data_with_corrupted_header).unwrap().read());
    }

    #[test]
    fn writer_return_err_when_writing_header_with_short_length() {
        let mut buffer = [0u8;3];
        assert_eq!(Error::CorruptSegmentHeader, FileWriter::new(&mut buffer[..]).err().unwrap());
    }

    #[test]
    fn writer_write_one_message() {
        let message: &[u8] = b"hello";
        let mut writer: Vec<u8> = vec![];
        assert!(FileWriter::new(&mut writer).unwrap().write(message).is_ok());
        assert_eq!(b"DFSN\x05\0\0\0hello".as_ref(), &writer[..]);
    }
}
//! Baja error
//!
//! Various Baja-specific errors produced by the Baja session and Baja contexts,
//! and operations on them.
//!
//! ## Authors
//!
//! The Veracruz Development Team.
//!
//! ## Licensing and copyright notice
//!
//! See the `LICENSE.markdown` file in the Veracruz root directory for
//! information on licensing and copyright.

use err_derive::Error;

/// The various different error modes associated with the Baja module.
///
/// NOTE: `protobuf` does not implement `Clone`, so deriving `Clone` for this
/// type is impossible.
#[derive(Debug, Error)]
pub enum BajaError {
    /// A TLS error originating in the `RusTLS` library occurred, with an
    /// accompanying error code.
    #[error(display = "Baja: a TLS error occurred: {:?}.", _0)]
    TLSError(#[error(source)] rustls::TLSError),
    /// A generic, unspecified TLS error occurred.
    #[error(display = "Baja: an unspecified or unknown TLS error occurred.")]
    TLSUnspecifiedError,
    /// An invalid, or unknown, ciphersuite was requested.
    #[error(
        display = "Baja: an invalid cyphersuite was requested in the TLS handshake: {:?}.",
        _0
    )]
    TLSInvalidCyphersuiteError(std::string::String),
    /// An unsupported ciphersuite was requested.
    #[error(
        display = "Baja: an unsupported cyphersuite was requested in the TLS handshake: {:?}.",
        _0
    )]
    TLSUnsupportedCyphersuiteError(rustls::CipherSuite),
    /// An IO error occurred, with an accompanying error code.
    #[error(display = "Baja: an IO error occurred: {:?}.", _0)]
    IOError(#[error(source)] std::io::Error),
    /// A generic error occurred in the Ring library.
    #[error(
        display = "Baja: an unspecified error occurred in the Ring library: {:?}.",
        _0
    )]
    RingUnspecifiedError(#[error(source)] ring::error::Unspecified),
    /// A cryptographic key was rejected by the Ring library.
    #[error(
        display = "Baja: the Ring library rejected a cryptographic key: {:?}.",
        _0
    )]
    RingKeyRejectedError(#[error(source)] ring::error::KeyRejected),
    /// A WebPKI error occurred with an accompanying error code.
    #[error(display = "Baja: a WebPKI error occurred: {:?}.", _0)]
    WebpkiError(#[error(source)] webpki::Error),
    /// The runtime failed to obtain the peer certificates from the TLS session.
    #[error(display = "Baja: failed to retrieve peer certificates.")]
    PeerCertificateError,
    /// The length of a variable (e.g. the number of expected peer certificates)
    /// did not match expectations.
    #[error(display = "Baja: invalid length of variable `{}`, expected {}", _0, _1)]
    InvalidLengthError(&'static str, usize),
    /// A principal has not been assigned any roles in the Veracruz computation.
    #[error(
        display = "Baja: principal {} has not been assigned any role in the computation.",
        _0
    )]
    EmptyRoleError(u64),
    /// A cryptographic certificate was missing.


igits' : 5, 'expectedOutput' : [65537]},
      {'sequence' : NumberSequencesMode.RECAMAN,          'digits' : 2, 'expectedOutput' : [13,20,12,21,11,22,10,23,24,25,43,62,42,63,41,18,42,17,43,16,44,15,45,14,46,79,78,77,39,78,38,79,37,80,36,81,35,82,34,83,33,84,32,85,31,86,30,87,29,88,28,89,27,90,26]},
      {'sequence' : NumberSequencesMode.LUCAS,            'digits' : 4, 'expectedOutput' : [1364,2207,3571,5778,9349]},
      {'sequence' : NumberSequencesMode.FIBONACCI,        'digits' : 4, 'expectedOutput' : [1597,2584,4181,6765]},
      {'sequence' : NumberSequencesMode.PELL,             'digits' : 4, 'expectedOutput' : [2378,5741]},
      {'sequence' : NumberSequencesMode.PELL_LUCAS,       'digits' : 4, 'expectedOutput' : [1154,2786,6726]},
      {'sequence' : NumberSequencesMode.FACTORIAL,        'digits' : 3, 'expectedOutput' : [120,720]},
      {'sequence' : NumberSequencesMode.LYCHREL,          'digits' : 3, 'expectedOutput' : [196, 295, 394, 493, 592, 689, 691, 788, 790, 879, 887, 978, 986]}, // Mark test
      {'sequence' : NumberSequencesMode.PRIMES,           'digits' : 1, 'expectedOutput' : [2, 3, 5, 7]},
      {'sequence' : NumberSequencesMode.BUSY_BEAVER,      'digits' : 1, 'expectedOutput' : [1, 6]},
    ];

    for (var elem in _inputsToExpected) {
      test('sequence: ${elem['sequence']}, digits: ${elem['digits']}', () {
        var _actual = numberSequencesGetNumbersWithNDigits(elem['sequence'] as NumberSequencesMode, elem['digits'] as int?);
        var length = (elem['expectedOutput'] as List<Object>).length;
        for (int i = 0; i < length; i++) {
          if (_actual[i].runtimeType.toString() == 'String') {
            expect(BigInt.parse(_actual[i].toString()), BigInt.from((elem['expectedOutput'] as List<int>)[i]));
          } else {
            expect(_actual[i], BigInt.from((elem['expectedOutput'] as List<int>)[i]));
          }
        }
      });
    }
  });

  group("numbersequence.getFirstPositionOfSequence:", () {
    List<Map<String, Object?>> _inputsToExpected = [
      {'sequence' : NumberSequencesMode.CATALAN,          'maxIndex' : 1000,  'number' : '27361', 'expectedOutput' : PositionOfSequenceOutput('7107690250413013761896628105173181658589772625392889208165477368352734802736195805963143770815133859332929972050727625767936724822523808745285247568658130484108957872094022098605943811100613700',
          328, 73)},
      {'sequence' : NumberSequencesMode.RECAMAN,          'maxIndex' : 90000, 'number' : '27361', 'expectedOutput' : PositionOfSequenceOutput('273610',
          83076, 1)},
      {'sequence' : NumberSequencesMode.LUCAS,            'maxIndex' : 1500,  'number' : '27361', 'expectedOutput' : PositionOfSequenceOutput('187487718160318824323612795854373790277932993999775275191574124646609656402496443136812


c = rs.getString("ReadOnlyLogic");
			vo.ReadOnlyLogicExpr = Services.get(IExpressionFactory.class)
					.compileOrDefault(ReadOnlyLogic, DEFAULT_ReadOnlyLogicExpr, ILogicExpression.class); // metas: 03093
			if (rs.getString("IsInsertRecord").equals("N"))
			{
				vo.IsInsertRecord = false;
			}
			final String InsertLogic = rs.getString("InsertLogic");
			vo.InsertLogicExpr = Services.get(IExpressionFactory.class)
					.compileOrDefault(InsertLogic, DEFAULT_InsertLogicExpr, ILogicExpression.class); // metas: 03093

			if ("Y".equals(rs.getString("IsSingleRow")))
			{
				vo.IsSingleRow = true;
			}
			if ("Y".equals(rs.getString("HasTree")))
			{
				vo.HasTree = true;
			}

			if ("Y".equals(rs.getString("IsView")))
			{
				vo.IsView = true;
			}
			vo.AD_Column_ID = rs.getInt("AD_Column_ID");   //  Primary Link Column
			vo.Parent_Column_ID = rs.getInt("Parent_Column_ID");   // Parent tab link column

			if ("Y".equals(rs.getString("IsSecurityEnabled")))
			{
				vo.IsSecurityEnabled = true;
			}
			if ("Y".equals(rs.getString("IsDeleteable")))
			{
				vo.IsDeleteable = true;
			}
			if ("Y".equals(rs.getString("IsHighVolume")))
			{
				vo.IsHighVolume = true;
			}

			if ("Y".equals(rs.getString("IsAutodetectDefaultDateFilter")))
			{
				vo.IsAutodetectDefaultDateFilter = true;
			}

			//
			// Where clause
			{
				vo.WhereClause = rs.getString("WhereClause");
				if (vo.WhereClause == null)
				{
					vo.WhereClause = "";
				}
				//jz col=null not good for Derby
				if (vo.WhereClause.indexOf("=null") > 0)
				{
					logger.warn("Replaced '=null' with 'IS NULL' for {}", vo);
					vo.WhereClause = vo.WhereClause.replaceAll("=null", " IS NULL ");
				}
				// Where Clauses should be surrounded by parenthesis - teo_sarca, BF [ 1982327 ]
				if (vo.WhereClause.trim().length() > 0)
				{
					vo.WhereClause = "(" + vo.WhereClause + ")";
				}
			}

			vo.OrderByClause = rs.getString("OrderByClause");
			if (vo.OrderByClause == null)
			{
				vo.OrderByClause = "";
			}

			vo.printProcessId = AdProcessId.ofRepoIdOrNull(rs.getInt("AD_Process_ID"));
			if (rs.wasNull())
			{
				vo.printProcessId = null;
			}
			vo.AD_Image_ID = rs.getInt("AD_Image_ID");
			if (rs.wasNull())
			{
				vo.AD_Image_ID = 0;
			}
			vo.Included_Tab_ID = rs.getInt("Included_Tab_ID");
			if (rs.wasNull())
			{
				vo.Included_Tab_ID = 0;
			}
			//
			vo.TabLevel = rs.getInt("TabLevel");
			if (rs.wasNull())
			{
				vo.TabLevel = 0;
			}
			Env.setContext(vo.ctx, vo.WindowNo, vo.TabNo, GridTab.CTX_TabLevel, String.valueOf(vo.TabLevel)); // metas: tsa: set this value here because here is the right place

			//
			vo.IsSortTab = rs.getString("IsSortTab").equals("Y");
			if (vo.IsSortTab)
			{
				vo.AD_ColumnSortOrder_ID = rs.getInt("AD_ColumnSortOrder_ID");
				vo.AD_ColumnSortYesNo_ID = rs.getInt("AD_ColumnSortYesNo_ID");
			}
			//


 override int GetHashCode() {
			return m_UGCFileWriteStreamHandle.GetHashCode();
		}

		public static bool operator ==(UGCFileWriteStreamHandle_t x, UGCFileWriteStreamHandle_t y) {
			return x.m_UGCFileWriteStreamHandle == y.m_UGCFileWriteStreamHandle;
		}

		public static bool operator !=(UGCFileWriteStreamHandle_t x, UGCFileWriteStreamHandle_t y) {
			return !(x == y);
		}

		public static explicit operator UGCFileWriteStreamHandle_t(ulong value) {
			return new UGCFileWriteStreamHandle_t(value);
		}

		public static explicit operator ulong(UGCFileWriteStreamHandle_t that) {
			return that.m_UGCFileWriteStreamHandle;
		}

		public bool Equals(UGCFileWriteStreamHandle_t other) {
			return m_UGCFileWriteStreamHandle == other.m_UGCFileWriteStreamHandle;
		}

		public int CompareTo(UGCFileWriteStreamHandle_t other) {
			return m_UGCFileWriteStreamHandle.CompareTo(other.m_UGCFileWriteStreamHandle);
		}
	}
}


urns>
        public override byte[] GetBytes()
        {
            var messageAttribute = this.GetType().GetCustomAttributes(typeof(MessageAttribute), true).SingleOrDefault() as MessageAttribute;

            if (messageAttribute == null)
                throw new SshException(string.Format(CultureInfo.CurrentCulture, "Type '{0}' is not a valid message type.", this.GetType().AssemblyQualifiedName));

            var data = new List<byte>(base.GetBytes());

            data.Insert(0, messageAttribute.Number);

            return data.ToArray();
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            var messageAttribute = this.GetType().GetCustomAttributes(typeof(MessageAttribute), true).SingleOrDefault() as MessageAttribute;

            if (messageAttribute == null)
                return string.Format(CultureInfo.CurrentCulture, "'{0}' without Message attribute.", this.GetType().FullName);

            return messageAttribute.Name;
        }
    }
}


_80374798:
/* 80374798 003703F8  2C 1E 00 0F */	cmpwi r30, 0xf
/* 8037479C 003703FC  40 81 00 0C */	ble lbl_803747A8
/* 803747A0 00370400  3B A0 00 00 */	li r29, 0
/* 803747A4 00370404  48 00 00 08 */	b lbl_803747AC
lbl_803747A8:
/* 803747A8 00370408  83 BC 00 B8 */	lwz r29, 0xb8(r28)
lbl_803747AC:
/* 803747AC 0037040C  2C 1D 00 00 */	cmpwi r29, 0
/* 803747B0 00370410  41 82 00 18 */	beq lbl_803747C8
/* 803747B4 00370414  7F A3 EB 78 */	mr r3, r29
/* 803747B8 00370418  38 80 00 7F */	li r4, 0x7f
/* 803747BC 0037041C  48 00 11 65 */	bl ReleaseAllChannel__Q44nw4r3snd6detail8SeqTrackFi
/* 803747C0 00370420  7F A3 EB 78 */	mr r3, r29
/* 803747C4 00370424  48 00 17 5D */	bl FreeAllChannel__Q44nw4r3snd6detail8SeqTrackFv
lbl_803747C8:
/* 803747C8 00370428  3B DE 00 01 */	addi r30, r30, 1
/* 803747CC 0037042C  3B 9C 00 04 */	addi r28, r28, 4
/* 803747D0 00370430  2C 1E 00 10 */	cmpwi r30, 0x10
/* 803747D4 00370434  41 80 FF C4 */	blt lbl_80374798
lbl_803747D8:
/* 803747D8 00370438  3B 80 00 00 */	li r28, 0
/* 803747DC 0037043C  48 00 00 F0 */	b lbl_803748CC
lbl_803747E0:
/* 803747E0 00370440  80 BF 00 9C */	lwz r5, 0x9c(r31)
/* 803747E4 00370444  7F E3 FB 78 */	mr r3, r31
/* 803747E8 00370448  38 80 00 00 */	li r4, 0
/* 803747EC 0037044C  38 05 FF FF */	addi r0, r5, -1
/* 803747F0 00370450  90 1F 00 9C */	stw r0, 0x9c(r31)
/* 803747F4 00370454  4B FF FD 95 */	bl ParseNextTick__Q44nw4r3snd6detail9SeqPlayerFb
/* 803747F8 00370458  2C 03 00 00 */	cmpwi r3, 0
/* 803747FC 0037045C  41 82 00 C0 */	beq lbl_803748BC
/* 80374800 00370460  88 1F 00 8D */	lbz r0, 0x8d(r31)
/* 80374804 00370464  2C 00 00 00 */	cmpwi r0, 0
/* 80374808 00370468  41 82 00 28 */	beq lbl_80374830
/* 8037480C 0037046C  2C 1F 00 00 */	cmpwi r31, 0
/* 80374810 00370470  7F FD FB 78 */	mr r29, r31
/* 80374814 00370474  41 82 00 08 */	beq lbl_8037481C
/* 80374818 00370478  3B BF 00 80 */	addi r29, r31, 0x80
lbl_8037


:

     * Length:  - 256

     * Pattern:
     * arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:entity
     * -recognizer/
     * [a-zA-Z0-9](-*[a-zA-Z0-9])*(/version/[a-zA-Z0-9](-*[a-zA-Z0-9])*)?

     *
     * @return

     *         The Amazon Resource Name (ARN) that identifies the specific
     *         entity recognizer to be used by the
     *         StartEntitiesDetectionJob. This ARN is optional and
     *         is only used for a custom entity recognition job.
     *

     */
    public String getEntityRecognizerArn() {
        return entityRecognizerArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the specific entity
     * recognizer to be used by the StartEntitiesDetectionJob. This
     * ARN is optional and is only used for a custom entity recognition job.
     *

     *

     * Constraints:

     * Length:  - 256

     * Pattern:
     * arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:entity
     * -recognizer/
     * [a-zA-Z0-9](-*[a-zA-Z0-9])*(/version/[a-zA-Z0-9](-*[a-zA-Z0-9])*)?

     *
     * @param entityRecognizerArn

     *            The Amazon Resource Name (ARN) that identifies the specific
     *            entity recognizer to be used by the
     *            StartEntitiesDetectionJob. This ARN is optional
     *            and is only used for a custom entity recognition job.
     *

     */
    public void setEntityRecognizerArn(String entityRecognizerArn) {
        this.entityRecognizerArn = entityRecognizerArn;
    }

    /**
     *

     * The Amazon Resource Name (ARN) that identifies the specific entity
     * recognizer to be used by the StartEntitiesDetectionJob. This
     * ARN is optional and is only used for a custom entity recognition job.
     *

     *

     * Returns a reference to this object so that method calls can be chained
     * together.
     *

     * Constraints:

     * Length:  - 256

     * Pattern:
     * arn:aws(-[^:]+)?:comprehend:[a-zA-Z0-9-]*:[0-9]{12}:entity
     * -recognizer/
     * [a-zA-Z0-9](-*[a-zA-Z0-9])*(/version/[a-zA-Z0-9](-*[a-zA-Z0-9])*)?

     *
     * @param entityRecognizerArn

     *            The Amazon Resource Name (ARN) that identifies the specific
     *            entity recognizer to be used by the
     *            StartEntitiesDetectionJob. This ARN is optional
     *            and is only used for a custom entity recognition job.
     *

     * @return A reference to this updated object so that method calls can be
     *         chained together.
     */
    public StartEntitiesDetectionJobRequest withEntityRecognizerArn(String entityRecognizerArn) {
        this.entityRecognizerArn = entityRecognizerArn;
        return this;
    }

    /**
     *

     * The language of the input documents. All documents must be in the same
     * language. You can specify any of the languages supported by Amazon
     * Comprehend. If custom entities recognition is used, this parameter is
     * ignored and the language used for training the model is used instead.
     *

     *

     * Constraints:

     * Allowed Values: en, es, fr, de, it, pt, ar, hi, ja, ko, zh, zh-TW
     *
     * @return

     *


     * If no [after] period is provided, the same value as for [before] will be used.
     *
     * If [before] or [after] contain timezone-dependent values, UTC will be used as the ZoneId.
     */
    fun extend(before: TimeSpan, after: TimeSpan = before): Timeframe {
        val e = makeValid(end + after)
        val incl = (end.equals(MAX)) || inclusive
        return Timeframe(makeValid(start - before), e, incl)
    }

    /**
     * Annualize a [rate] based on the duration of this timeframe. So given x percent return
     * during a timeframe, what would be the return percentage for a full year (365 days). If this timeframe has higher
     * than millisecond precision, the remaining precision will not be used.
     *
     * [rate] is expected to be provided as a fraction — for example, 1% is 0.01
     */
    fun annualize(rate: Double): Double {
        return (1.0 + rate).pow(toYears()) - 1.0
    }

    /**
     * Convert this timeframe to years (using 365 days in a year).
     */
    private fun toYears(): Double {
        val period = duration.toMillis()
        return ONE_YEAR_MILLIS / period
    }

    /**
     * Compare timeframes based on their [duration]
     */
    operator fun compareTo(other: TimeSpan): Int {
        return duration.compareTo(other.duration)
    }

}

/*
 * Copyright 2020-2025 Neural Layer
 *
 * 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
 *
 *      https://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.
 */

@file:Suppress("TooGenericExceptionThrown", "MaxLineLength", "ReturnCount")
@file:Repository("https://repo.maven.apache.org/maven2/")
@file:DependsOn("com.google.code.gson:gson:2.9.0")

import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import java.io.File

operator fun StringBuffer.plusAssign(str: Any) {
    append(str.toString())
}

/**
 * Base wrapper contains the shared functionality for both TALib (streaming) and TALibBatch generators
 *
 * @property root
 * @constructor Create empty Base wrapper
 */
@Suppress("MemberVisibilityCanBePrivate", "KotlinConstantConditions", "UnusedReceiverParameter")
class TaLibGenerator(private val root: JsonObject) {

     fun JsonObject.getAttr(key: String): String = get(key).asString
     private fun String.unCapitalize() = get(0).lowercase() + substring(1)

     fun JsonObject.getVariableName(key: String): String {
        var result = get(key).asString
        result = result.replace(" ", "")
        result = result.replace("-", "")
        result = result.unCapitalize()
        result = result.replace("inReal", "data")
        return result
    }

     fun getList(key: String): List<JsonObject> {
        if (!root.has(key + "s")) return emptyList()

        val child = root.getAsJsonObject(key + "s").get(key)
        if (child is JsonArray)
            return child.filterIsInstance<JsonObject>().toList()
        else if (child is JsonObject) {
            return listOf(child)
        }
        return emptyList()
    }

    val desc = root.getAttr("ShortDescription")
    // private val className: String = root.get("CamelCaseName").asString
    val fnName = className.unCapitalize()
    val fixedFnName = if (fnName == "cdlStickSandwhich") "cdlStickSandwich" else fnName
    val inputParams = getInput()
    val optional = getOpti


)*)) -> Value {
      get_func_variant!(self, $variant).call_once_rr(a)
    }
  }

  // FnMut

  // -- Static arguments

  impl<$($T),*> FnMut<($($T,)*)> for Function
    where
      $($T: 'static,)*
  {
    default extern "rust-call" fn call_mut(&mut self, a: ($($T,)*)) -> Value {
      get_func_variant!(self, $variant).call_mut_s(a)
    }
  }

  // -- Reference arguments

  impl<$($T),*> FnMut<($(&$T,)*)> for Function
    where
      $($T: 'static,)*
  {
    extern "rust-call" fn call_mut(&mut self, a: ($(&$T,)*)) -> Value {
      get_func_variant!(self, $variant).call_mut_r(a)
    }
  }

  // -- ValueRef arguments

  impl FnMut<($(as_value_ref!($T),)*)> for Function {
    extern "rust-call" fn call_mut(&mut self, a: ($(as_value_ref!($T),)*)) -> Value {
      get_func_variant!(self, $variant).call_mut_rr(a)
    }
  }

  // Fn

  // -- Static arguments

  impl<$($T),*> Fn<($($T,)*)> for Function
    where
      $($T: 'static,)*
  {
    default extern "rust-call" fn call(&self, a: ($($T,)*)) -> Value {
      get_func_variant!(self, $variant).call_s(a)
    }
  }

  // -- Reference arguments

  impl<$($T),*> Fn<($(&$T,)*)> for Function
    where
      $($T: 'static,)*
  {
    extern "rust-call" fn call(&self, a: ($(&$T,)*)) -> Value {
      get_func_variant!(self, $variant).call_r(a)
    }
  }

  // -- ValueRef arguments

  impl Fn<($(as_value_ref!($T),)*)> for Function {
    extern "rust-call" fn call(&self, a: ($(as_value_ref!($T),)*)) -> Value {
      get_func_variant!(self, $variant).call_rr(a)
    }
  }
}

pub macro impl_ref_fn($variant: ident, $($T: ident),*) {
  impl<'a,$($T),*> RefFn<'a, ($(&'a $T,)*)> for Function
    where
      $($T: 'static),*
  {
    fn r(&self, a: ($(&'a $T,)*)) -> ValueRef<'a> {
      match self {
        Function::$variant(func) => {
          func.call(a)
        }
        _ => panic!("Not a Function::{}", stringify!($variant))
      }
    }
  }
}

///
/// Dependencies:
///
/// # This library is meant to be used on development or testing environments
/// # in which setting environment variables is not practical.
/// dotenv = "^0.13"
///
/// Requirements:
///
/// To run this example you need to create a archive named ``.env`` in the root of the directory with the following info
/// MAILCHIMP_API_KEY=<API KEY>
///
use dotenv::dotenv;
use mailchimp::{Conversations, MailchimpApi};

use std::env;

fn main() {
    // Init dotenv
    dotenv().ok();
    // Filter the env vars to get the Mailchimp Credential
    // mailchimp
    let mut env_mailchimp = env::vars().filter(|e| e.0.to_string().contains("MAILCHIMP_"));
    let apk = env_mailchimp.next().unwrap().1;
    // Init API
    let api = MailchimpApi::new(&apk);

    // Create Conversations instance
    let conv = Conversations::new(api);
    let mut conversation_id = "".to_string();

    for it in conv.get_con


              logoRadius = logoRadiusPx,
                    emojiSet = emojiSets[currentThemeIndex]
                )
            }
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                // 4. 手势检测：单击切换主题
                .pointerInput(Unit) {
                    detectTapGestures(
                        onTap = {
                            currentThemeIndex = (currentThemeIndex + 1) % emojiSets.size
                        })
                }) {
            // 5. 使用Canvas绘制所有背景Emoji
            Canvas(modifier = Modifier.fillMaxSize()) {
                backgroundEmojis.forEach { emoji ->
                    // 调整Y坐标以使Emoji在视觉上居中
                    val yOffset = emoji.y + emoji.size / 3
                    textPaint.textSize = emoji.size
                    drawIntoCanvas { canvas ->
                        canvas.nativeCanvas.drawText(emoji.emoji, emoji.x, yOffset, textPaint)
                    }
                }
            }

            // 6. 在屏幕中央显示App的Logo
            Box(
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(logoSize)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Image(
                    painter = painterResource(R.drawable.icon),
                    contentDescription = "App Logo",
                    modifier = Modifier
                        .size(logoSize * 0.5f)
                        //.clip(RoundedCornerShape(16.dp)),
                )
            }

            // 在底部显示操作提示
            Text(
                text = "单击切换背景",
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(32.dp),
                style = TextStyle(
                    color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                    fontSize = 16.sp,
                    fontWeight = FontWeight.Bold
                )
            )
        }
    }
}

/**
 * 使用圆盘填充算法生成一屏静态的、不重叠的Emoji
 */
private fun generatePackedEmojis(
    width: Float,
    height: Float,
    logoCenterX: Float,
    logoCenterY: Float,
    logoRadius: Float,
    emojiSet: List<String>
): List<StaticEmoji> {
    val placedCircles = mutableListOf<Circle>()

    // 1. 将Logo视为一个固定的、不可侵犯的圆�


00&hospDeptId=23dff9e0-f623-47f0-b65f-c08d9e2664e2000) 预约挂号
1. 可在门诊一楼现场挂号
1. 若无号可在门诊四楼整形外科现场请求护士加号

也可直接联系赵博：

1. 设法获取护士台电话后，通过护士台询问赵烨德医生在不在后联络 赵烨德医生
1. 与 赵烨德医生 交流，或在社群内设法获取其微信号后，预约面诊时间

在线上挂号后线下就诊需要注意的：

1. 请去一楼挂号处报道，进行缴费后才会叫号

## 面诊内容

赵烨德医生一般会在门诊没有人后立刻返回住院楼，请勿过晚抵达。

可能的面谈内容：

- 类似精神科医生的问诊（更详细完全版本）
- 是否取得证明
- 家长同意与否
- 手术资金来源
- 可预约时间
- 具体手术要求
- ~~你为什么喝水都胖~~
- 跟你一起来的这位是什么关系（诸如此类的家长）
- 赵烨德医生预先告知来访者更擅长的术式

手术排期时间并不严格按照就诊顺序，考虑因素可能包括是否已经 RLE，是否急于在毕业前修改身份证件等。
{{< expand "染色体异常情况下的预约检查" >}}

对于提交**染色体异常检查单**的情况，赵烨德医生可能会询问如下问题：

- 未进行 HRT 前的遗精与晨勃情况
- 染色体异常发现的时间与检查原因
- 家里的情况与看法
- 身份证上的性别
- （若已以女性身份生活）以女性身份生活的开始时间

在看过报告单/诊断书后，赵烨德医生会带至旁边小房间里检查相关部位的发育情况。

{{< /expand >}}

如手术材料上体毛过多可能会建议脱毛，本门诊提供钻孔取毛服务，需在手术前半年以上进行。

## 需要自行购买或携带的物品

出于便携移动的考虑，并不推荐提前在行李中携带过多物品前往医院。~~这里是上海，没有任何东西是京东和顺丰隔天送不到的，京东超市/京东自营甚至可以做到早上下单傍晚送达，下午下单次日送达。~~

如果在你刚入院的时候有认识的朋友快要出院了（即使没有朋友的话在411术前群多


,r){let n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);let i="";for(let a=t;a<r;++a)i+=q3t[e[a]];return i}function I3t(e,t,r){let n=e.slice(t,r),i="";for(let a=0;a<n.length-1;a+=2)i+=String.fromCharCode(n[a]+n[a+1]*256);return i}ta.prototype.slice=function(t,r){let n=this.length;t=~~t,r=r===void 0?n:~~r,t<0?(t+=n,t<0&&(t=0)):t>n&&(t=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<t&&(r=t);let i=this.subarray(t,r);return Object.setPrototypeOf(i,ta.prototype),i};function ev(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}ta.prototype.readUintLE=ta.prototype.readUIntLE=function(t,r,n){t=t>>>0,r=r>>>0,n||ev(t,r,this.length);let i=this[t],a=1,o=0;for(;++o<r&&(a*=256);)i+=this[t+o]*a;return i};ta.prototype.readUintBE=ta.prototype.readUIntBE=function(t,r,n){t=t>>>0,r=r>>>0,n||ev(t,r,this.length);let i=this[t+--r],a=1;for(;r>0&&(a*=256);)i+=this[t+--r]*a;return i};ta.prototype.readUint8=ta.prototype.readUInt8=function(t,r){return t=t>>>0,r||ev(t,1,this.length),this[t]};ta.prototype.readUint16LE=ta.prototype.readUInt16LE=function(t,r){return t=t>>>0,r||ev(t,2,this.length),this[t]|this[t+1]<<8};ta.prototype.readUint16BE=ta.prototype.readUInt16BE=function(t,r){return t=t>>>0,r||ev(t,2,this.length),this[t]<<8|this[t+1]};ta.prototype.readUint32LE=ta.prototype.readUInt32LE=function(t,r){return t=t>>>0,r||ev(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};ta.prototype.readUint32BE=ta.prototype.readUInt32BE=function(t,r){return t=t>>>0,r||ev(t,4,this.length),this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};ta.prototype.readBigUInt64LE=I_(function(t){t=t>>>0,YT(t,"offset");let r=this[t],n=this[t+7];(r===void 0||n===void 0)&&B4(t,this.length-8);let i=r+this[++t]*2**8+this[++t]*2**16+this[++t]*2**24,a=this[++t]+this[++t]*2**8+this[++t]*2**16+n*2**24;return BigInt(i)+(BigInt(a)<<BigInt(32))});ta.prototype.readBigUInt64BE=I_(funct


lbar
import cn.vove7.bottomdialog.util.ObservableList
import cn.vove7.bottomsheetdialog.builder.AppListBuilder
import cn.vove7.bottomsheetdialog.builder.ViewIntentBuilder
import cn.vove7.bottomsheetdialog.builder.markdownContent
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

/**
 *
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        BottomDialogBuilder.apply {
            enableAutoDarkTheme = true
            darkTheme = R.style.BottomDialog_Dark
        }

        val items = listOf(
            getString(R.string.message_dialog),
            getString(R.string.simple_list_dialog),
            getString(R.string.adapter_list_dialog),
            "Multi Buttons Dialog",
            "Dialog Activity",
            "Toolbar",
            "Awesome Header Dialog",
            "Delay Show ActivityDialog",
            "Awesome Share",
            "Markdown Dialog",
            "UnExpandable Dialog",
            "DarkDialog"
        )
        list_view.adapter = object : BaseAdapter() {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
                return ((convertView as TextView?)
                    ?: TextView(this@MainActivity)).apply {

                    setPadding(20, 30, 20, 30)
                    text = items[position]

                    setOnClickListener {
                        onClick(position)
                    }
                }
            }

            override fun getItem(position: Int): Any = items[position]

            override fun getItemId(position: Int): Long = position.toLong()

            override fun getCount(): Int = items.size
        }

    }

    fun onClick(pos: Int) {
        when (pos) {
            0 -> {
                BottomDialog.builder(this) {
                    title("Hello", true)
                    cancelable(false)
                    withCloseIcon()
                    message(
                        buildString {
                            for (i in 0..30) {
                                for (j in 0..i * 5) append(j)
                                appendln()
                            }
                        }, true
                    )
                    oneButton(
                        "OK",
                        bgColorId = R.color.colorAccent,
                        textColorId = android.R.color.white
                    ) {
                        onLongClick { dialog ->
                            dialog.updateContent<MessageContentBuilder> {
                                text = Random().nextDouble().toString()
                            }
                        }
                    }
                }
            }
            1 -> {

                val list = ObservableList.build<String?> {
                    for (i in 0..50) add("item $i")
                    add("到底了")
                }

                BottomDialog.builder(this) {
                    this.title("Hello", true)
                    mutableList(list) { _, position, s, l ->
                        toast("clicked $s at $position longClick: $l")
                    }
                    buttons {
                        negativeButton()
                        neutralButton("removeAt(0)") {
                            if (list.isNotEmpty())
                                list.removeAt(0)
                        }
                        positiveButton("add(0,'...')") {
                            list.add(0, "...")
                        }
                    }
                }
            }
            2 -> {

                BottomDialog.builder(this) {
                    title("应用列表", true)
                    content(AppListBuilder(this@MainActivity


] (Int)
ldx [%i0 + 32], %o2
! move %o2(upper) -> %o2(upper)

P21041: !ST [1] (maybe <- 0xc8000d1) (Int)
stw   %l4, [%i0 + 4 ]
add   %l4, 1, %l4

P21042: !DWLD [6] (Int) (LE)
wr %g0, 0x88, %asi
ldxa [%i1 + 80] %asi, %l7
! move %l7(lower) -> %o2(lower)
srlx %o2, 32, %o2
sllx %o2, 32, %o2
srl %l7, 0, %l6
or %l6, %o2, %o2
! move %l7(upper) -> %o3(upper)
or %l7, %g0, %o3

P21043: !PREFETCH [14] (Int)
prefetch [%i3 + 128], 1

P21044: !REPLACEMENT [1] (Int)
sethi %hi(0x4), %o5
or %o5, %lo(0x4),  %o5
sethi %hi(0x10000), %l3
or %l3, %lo(0x10000),  %l3
add %i3, %o5, %o5
add %o5, %l3, %o5
ld [%o5], %l6
st %l6, [%o5]
add %o5, %l3, %o5
ld [%o5], %l6
st %l6, [%o5]
add %o5, %l3, %o5
ld [%o5], %l6
st %l6, [%o5]
add %o5, %l3, %o5
ld [%o5], %l6
st %l6, [%o5]

P21045: !DWLD [2] (Int) (LE) (Branch target of P21122)
wr %g0, 0x88, %asi
ldxa [%i0 + 8] %asi, %o5
! move %o5(upper) -> %o3(lower)
srlx %o3, 32, %o3
sllx %o3, 32, %o3
srlx %o5, 32, %l7
or %l7, %o3, %o3
ba P21046
nop

TARGET21122:
ba RET21122
nop

P21046: !DWLD [13] (Int)
ldx [%i3 + 64], %o4
! move %o4(upper) -> %o4(upper)

P21047: !MEMBAR (Int)
membar #StoreLoad

P21048: !LD [5] (Int)
lduw [%i1 + 76], %o5
! move %o5(lower) -> %o4(lower)
srlx %o4, 32, %o4
sllx %o4, 32, %o4
or %o5, %o4, %o4
!---- flushing int results buffer----
mov %o0, %l5
mov %o1, %l5
mov %o2, %l5
mov %o3, %l5
mov %o4, %l5

P21049: !REPLACEMENT [15] (Int)
sethi %hi(0xc0), %l3
or %l3, %lo(0xc0),  %l3
sethi %hi(0x10000), %l6
or %l6, %lo(0x10000),  %l6
add %i3, %l3, %l3
add %l3, %l6, %l3
ld [%l3], %l7
st %l7, [%l3]
add %l3, %l6, %l3
ld [%l3], %l7
st %l7, [%l3]
add %l3, %l6, %l3
ld [%l3],


者が新株を引き受ける 第三者割当増資、既存株主に新株を割り当てる 株主割当増資 があります。 — location: [1449](kindle://book?action=open&asin=B088T7J1FD&location=1449) ^ref-60491

---
1つは、順調に事業展開している企業のケースです。旺盛な資金需要を金融機関からの借り入れや債券の発行でなく、新たな資本金の調達でまかなうのです。 　2つめは財務内容の改善で、純資産の増加や負債の返済が目的となります。増資で得られる資金は借入金のように返済義務がなく、それで財務が改善できれば、企業の信頼度や評価も高まります。ただ極端な例として、自己資本がゼロ圏の会社や債務超過の会社が上場廃止基準抵触を回避するために行う、かなり緊急的な延命策としての増資もあります。 — location: [1453](kindle://book?action=open&asin=B088T7J1FD&location=1453) ^ref-4093

---
おカネの出入りを確認することは、会社分析に際して非常に重要です。会計上、利益が出ていても、資金繰りが逼迫すれば、黒字倒産といった危険もあるからです。 　キャッシュフロー計算書（CF）は貸借対照表、損益計算書（PL）と合わせて財務三表と呼ばれます。この三表はそれぞれ別個に存在するわけではなく、貸借対照表を中心にして関係を説明することができます。 — location: [1481](kindle://book?action=open&asin=B088T7J1FD&location=1481) ^ref-36966

---
で、売上高に対して、どれだけ営業CFを効率的に生み出せているかがわかります。 — location: [1520](kindle://book?action=open&asin=B088T7J1FD&location=1520) ^ref-7520

---
株式交換は会社を買収する際、買収先の株式と自社の株式を交換すること、株式移転は持株会社を設立して、その傘下に入り、株主には設立した持株会社の株式を交付することです。 — location: [1547](kindle://book?action=open&asin=B088T7J1FD&location=1547) ^ref-4178

---
ある会社の売上高が突然大きく — location: [1553](kindle://book?action=open&asin=B088T7J1FD&location=1553) ^ref-20299

---
たときは【資本異動】をみましょ — location: [1553](kindle://book?action=open&asin=B088T7J1FD&location=1553) ^ref-60604

---
こうした場合は、利益が大きく増えていても、1株当たり利益は変化なし、とい


* handle
   * version fallback logic: for each level searched, if child nodes are not found in one version, try earlier versions.
   *
   * Note: Version fallback logic can be complex, e.g., parent node found in V2, child nodes found in V1.
   *
   * @param parentCode Parent administrative district code
   * @param maxDepth Maximum search depth relative to `parentCode` (e.g., `maxDepth = 1` means only direct children, equivalent to `fetchChildren`)
   * @param yearVersion **Starting** data year version to search (each recursion level should start trying from this version)
   * @return List of all qualifying descendant [CnDistrict] (each District should include actual year version where data was found)
   */
  fun fetchChildrenRecursive(parentCode: string, maxDepth: Int = supportedMaxLevel, yearVersion: String = lastYearVersion): List<CnDistrict>

  /**
   * Recursively processes all descendant administrative districts under the specified code using traversal.
   *
   * This method allows callers to control the traversal process through callback functions, suitable for large-scale database operations.
   *
   * @param parentCode Parent administrative district code
   * @param maxDepth Maximum traversal depth relative to `parentCode`
   * @param yearVersion **Starting** data year version for traversal
   * @param onVisit Node visit callback function, return true to continue traversal, false to stop current branch traversal. Parameter descriptions:
   *     - children: Direct child node list of currently visited node
   *     - depth: Depth of current node relative to parentCode (starting from 1)
   *     - parentDistrict: Parent node information (null if top-level node)
   */
  fun traverseChildrenRecursive(
    parentCode: string,
    maxDepth: Int = supportedMaxLevel,
    yearVersion: String = lastYearVersion,
    onVisit: (children: List<CnDistrict>, depth: Int, parentDistrict: CnDistrict?) -> Boolean,
  )
}
package io.github.truenine.composeserver.security.crypto

import io.github.truenine.composeserver.security.crypto.domain.IEccExtKeyPair
import io.github.truenine.composeserver.security.crypto.domain.IKeysRepo
import io.github.truenine.composeserver.security.crypto.domain.IRsaExtKeyPair
import io.github.truenine.composeserver.slf4j
import javax.crypto.spec.SecretKeySpec

private val log = slf4j<AutoGeneratedKeysRepo>()

class AutoGeneratedKeysRepo : IKeysRepo {
  private val aesKey = CryptographicKeyManager.generateAesKey()
  private val rsaKeyPair = CryptographicKeyManager.generateRsaKeyPair()
  private val eccKeyPair = CryptographicKeyManager.generateEccKeyPair(CryptographicKeyManager.generateRandomAsciiString())

  init {
    log.warn("警告：正在使用一次性生成的 KeyRepository，该提供程序每次启动都会变化")
  }

  override fun basicAesKey(): SecretKeySpec? = aesKey

  override fun basicRsaKeyPair(): IRsaExtKeyPair? = rsaKeyPair

  override fun basicEccKeyPair(): IEccExtKeyPair? = eccKeyPair
}
package io.github.truenine.composeserver.security.crypto.domain

import java.security.PrivateKey
import java.security.PublicKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import javax.crypto.spec.SecretKeySpec

interface IKeysRepo {
  fun basicRsaKeyPair(): IRsaExtKeyPair? = null

  fun basicEccKeyPair(): IEccExtKeyPair? = null

  fun basicAesKey(): SecretKeySpec? = null

  fun findRsaKeyPairByName(publicKeyName: String, privateKeyName: String): IRsaExtKeyPair? {
    return RsaExtKeyPair(findRsaPublicKeyByName(publicKeyName)!!, findRsaPrivateKeyByName(privateKeyName)!!)
  }

  fun findEccKeyPairByName(publicKeyName: String, privateKeyName: String): IEccExtKeyPair? {
    return EccExtKeyPair(findEccPublicKeyByName(publicKeyName)!!


            }
        }

        public String getAsString(String columnName) {
            Object v = getObject(columnName);
            if (v != null) {
                return v.toString();
            } else {
                return null;
            }
        }

        public String getAsString(int index) {
            Object v = getObject(index);
            if (v != null) {
                return v.toString();
            } else {
                return null;
            }
        }

        @SuppressWarnings({"unchecked", "rawtypes"})
        public <T extends IEntity> T toEntity(T entityObject) throws Exception {
            EntityMeta entityMeta = EntityMeta.createAndGet(entityObject.getClass());
            if (entityMeta != null) {
                Object primaryKeyObject = null;
                if (entityMeta.isMultiplePrimaryKey()) {
                    primaryKeyObject = entityMeta.getPrimaryKeyClass().newInstance();
                    //
                    entityObject.setId((Serializable) primaryKeyObject);
                }
                for (PropertyMeta propertyMeta : entityMeta.getProperties()) {
                    Object fieldValue = getObject(propertyMeta.getName());
                    if (fieldValue != null) {
                        if (entityMeta.isPrimaryKey(propertyMeta.getName()) && entityMeta.isMultiplePrimaryKey()) {
                            propertyMeta.getField().set(primaryKeyObject, fieldValue);
                        } else {
                            propertyMeta.getField().set(entityObject, fieldValue);
                        }
                    }
                }
            }
            return entityObject;
        }

        public <T> T toObject(T valueObject) throws Exception {
            ClassUtils.BeanWrapper<?> wrapper = ClassUtils.wrapper(valueObject);
            for (String fieldName : wrapper.getFieldNames()) {
                String columnName = ClassUtils.fieldNameToPropertyName(fieldName, 0);
                Object value = this.getObject(columnName);
                if (value == null) {
                    continue;
                }
                wrapper.setValue(fieldName, value);
            }
            return valueObject;
        }
    }

    /**
     * 结果集输出列渲染器
     */
    public interface IColumnRenderer {

        /**
         * 渲染列值
         *
         * @param columnName 列名称
         * @param value      当前列值
         * @return 返回渲染后的列值
         */
        Object render(String columnName, Object value);
    }

    private ConsoleTableBuilder buildTableBuilder(String type, IColumnRenderer columnRenderer) {
        ConsoleTableBuilder tableBuilder = ConsoleTableBuilder.create(columnCount).escape();
        if (StringUtils.isNotBlank(type)) {
            switch (type) {
                case ConsoleTableBuilder.TYPE_CSV:
                    tableBuilder.csv();
                    break;
                case ConsoleTableBuilder.TYPE_MARKDOWN:
                    tableBuilder.markdown();
                    break;
                default:
            }
        }
        // Append Headers
        ConsoleTableBuilder.Row header = tableBuilder.addRow();
        Arrays.stream(getColumnNames()).map(StringUtils::upperCase).forEachOrdered(header::addColumn);
        // Append Rows
        try {
            forEach((wrapper, row) -> {
                ConsoleTableBuilder.Row newRow = tableBuilder.addRow();
                for (String colName : wrapper.getColumnNames()) {
                    Object


48b4 	sw	a1,18612(a1)
bfc0c210:	8d0248b4 	lw	v0,18612(t0)
bfc0c214:	8ca448b4 	lw	a0,18612(a1)
bfc0c218:	8c8548b4 	lw	a1,18612(a0)
bfc0c21c:	8ca648b4 	lw	a2,18612(a1)
bfc0c220:	144308d1 	bne	v0,v1,bfc0e568 <inst_error>
bfc0c224:	00000000 	nop
/home/ghj/Desktop/func/inst/n64_sh.S:21
bfc0c228:	3c0ae57c 	lui	t2,0xe57c
bfc0c22c:	354a6800 	ori	t2,t2,0x6800
bfc0c230:	3c09a1fc 	lui	t1,0xa1fc
bfc0c234:	35296927 	ori	t1,t1,0x6927
bfc0c238:	3c08800d 	lui	t0,0x800d
bfc0c23c:	35082f30 	ori	t0,t0,0x2f30
bfc0c240:	3c03e57c 	lui	v1,0xe57c
bfc0c244:	34636927 	ori	v1,v1,0x6927
bfc0c248:	ad0a693c 	sw	t2,26940(t0)
bfc0c24c:	a509693c 	sh	t1,26940(t0)
bfc0c250:	25040004 	addiu	a0,t0,4
bfc0c254:	2505fffc 	addiu	a1,t0,-4
bfc0c258:	ac84693c 	sw	a0,26940(a0)
bfc0c25c:	aca5693c 	sw	a1,26940(a1)
bfc0c260:	8d02693c 	lw	v0,26940(t0)
bfc0c264:	8ca4693c 	lw	a0,26940(a1)
bfc0c268:	8c85693c 	lw	a1,26940(a0)
bfc0c26c:	8ca6693c 	lw	a2,26940(a1)
bfc0c270:	144308bd 	bne	v0,v1,bfc0e568 <inst_error>
bfc0c274:	00000000 	nop
/home/ghj/Desktop/func/inst/n64_sh.S:22
bfc0c278:	3c0aa645 	lui	t2,0xa645
bfc0c27c:	354a0915 	ori	t2,t2,0x915
bfc0c280:	3c094c8f 	lui	t1,0x4c8f
bfc0c284:	3529b6e6 	ori	t1,t1,0xb6e6
bfc0c288:	3c08800d 	lui	t0,0x800d
bfc0c28c:	35082728 	ori	t0,t0,0x2728
bfc0c290:	3c03a645 	lui	v1,0xa645
bfc0c294:	3463b6e6 	ori	v1,v1,0xb6e6
bfc0c298:	ad0a22b8 	sw	t2,8888(t0)
bfc0c29c:	a50922b8 	sh	t1,


 setting.ignored_channel_ids.len() == 0 {
                    "No channels ignored".to_string()
                } else {
                    setting.ignored_channel_ids.into_iter().map(|channel_id| {
                        match context.cache.guild_channel(channel_id){
                            Some(_) => format!("<#{}>", channel_id),
                            None => format!("{} **(no longer exists)**", channel_id),
                        }
                    }).collect::<Vec<String>>().join("\n")
                };
                let result_text = match setting.results_channel_id {
                    Some(channel_id) => format!("<#{}>", channel_id),
                    None => "No results channel set".to_string()
                };

                embed
                    .field(EmbedFieldBuilder::new("Categories", categories_text).build())
                    .field(EmbedFieldBuilder::new("Embed color", color_text).build())
                    .field(EmbedFieldBuilder::new("Ignored", ignored_text).build())
                    .field(EmbedFieldBuilder::new("Results channel", result_text).build())
            },
            None => {
                embed.description("No settings found. Please kick and reinvite Sakura.")
            }
        };

        context
            .get_interaction_client()
            .interaction_callback(
                command.id,
                &command.token,
                &InteractionResponse::ChannelMessageWithSource(
                    CallbackDataBuilder::new().embeds(embed.build()).build()
                )
            )
            .exec()
            .await
            .unwrap();
    }
}/*
 * Copyright 2020 Fluence Labs Limited
 *
 * 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.
 */

use crate::execution_step::air::ExecutionResult;
use crate::execution_step::execution_context::ExecutionCtx;
use crate::execution_step::utils::resolve_ast_variable;
use crate::JValue;

use air_parser::ast;
use air_parser::ast::MatchableValue;

pub(crate) fn are_matchable_eq<'ctx>(
    left: &MatchableValue<'_>,
    right: &MatchableValue<'_>,
    exec_ctx: &'ctx ExecutionCtx<'_>,
) -> ExecutionResult<bool> {
    use MatchableValue::*;

    match (left, right) {
        (InitPeerId, InitPeerId) => Ok(true),
        (InitPeerId, matchable) => compare_matchable(
            matchable,
            exec_ctx,
            make_string_comparator(exec_ctx.init_peer_id.as_str()),
        ),
        (matchable, InitPeerId) => compare_matchable(
            matchable,
            exec_ctx,
            make_string_comparator(exec_ctx.init_peer_id.as_str()),
        ),

        (Literal(left_name), Literal(right_name)) => Ok(left_name == right_name),
        (Literal(value), matchable) => compare_matchable(matchable, exec_ctx, make_string_comparator(value)),
        (matchable, Literal(value)) => compare_matchable(matchable, exec_ctx, make_string_comparat


pseIndicator:SetShown(false);
		self.RibbonStacked:SetShown(false);
		self.Ribbon:SetShown(showRibbon);
	end

	self:UpdateButtonStateShared();
end

function MonthlyActivitiesButtonMixin:OnEnter()
	local data = self:GetData();
	if not data then
		return;
	end

	if data.requirementsList then
		self.showingTooltip = true;
		GameTooltip:SetOwner(self, "ANCHOR_CURSOR_RIGHT");
		self:ShowTooltip();
	end
end

-- Returns true if this method acted on the click
-- This may be needed since if the internal method handles the click in a way which leads to the button being released back to the pool then we won't want to continue after
function MonthlyActivitiesButtonMixin:OnClick_Internal()
	local data = self:GetData();
	if not data then
		return false;
	end

	if ( IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow() ) then
		local perksActivityLink = C_PerksActivities.GetPerksActivityChatLink(data.ID);
		ChatEdit_InsertLink(perksActivityLink);
		return true;
	end

	if ( IsModifiedClick("QUESTWATCHTOGGLE") ) then
		if data.tracked then
			C_PerksActivities.RemoveTrackedPerksActivity(data.ID);
		elseif self:CanTrack() then
			C_PerksActivities.AddTrackedPerksActivity(data.ID);
		end
		if self.showingTooltip then
			self:ShowTooltip();
		end

		PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
		return true;
	end

	return false;
end

function MonthlyActivitiesButtonMixin:OnClick()
	if self:OnClick_Internal() then
		return;
	end

	local data = self:GetData();
	if data and data.hasChild then
		local node = self:GetElementData();
		node:ToggleCollapsed();
		self:UpdateButtonState();
	end
end

function MonthlyActivitiesButtonMixin:OnLeave()
	GameTooltip:Hide();
	self.showingTooltip = false;
end

function MonthlyActivitiesButtonMixin:ShowTooltip()
	local data = self:GetData();
	if not data then
		return;
	end

	GameTooltip_SetTitle(GameTooltip, data.name, NORMAL_FONT_COLOR, true);
	GameTooltip_AddBlankLineToTooltip(GameTooltip);

	if #data.description > 0 then
		GameTooltip:AddLine(data.description, 1, 1, 1, true);
		GameTooltip_AddBlankLineToTooltip(GameTooltip);
	end

	for _, requirement in ipairs(data.requirementsList) do
		local tooltipLine = requirement.requirementText;
		tooltipLine = string.gsub(tooltipLine, " / ", "/");
		local color = not requirement.completed and WHITE_FONT_COLOR or DISABLED_FONT_COLOR;
		GameTooltip:AddLine(tooltipLine, color.r, color.g, color.b, true);
	end

	local conditionLines = {};
	local function AddConditionLine(text, r, g, b)
		table.insert(conditionLines, {
			text = text,
			r = r,
			g = g,
			b = b,
		});
	end

	if not data.completed and IsTimedActivity(data) then
		if not HasTimedActivityBegun(data) then
			AddConditionLine(MONTHLY_ACTIVITIES_EVENT_NOT_BEGUN, 1, 0, 0);
		elseif HasTimedActivityExpired(data) then
			AddConditionLine(MONTHLY_ACTIVITIES_EVENT_EXPIRED, 1, 0, 0);
		end
	end

	for index, condition in ipairs(data.conditions) do
		AddConditionLine(condition.text, 1, condition.isMet and 1 or 0, condition.isMet and 1 or 0);
	end

	if #conditionLines > 0 then
		GameTooltip_AddBlankLineToTooltip(GameTooltip);
		for index, conditionLine in ipairs(conditionLines)


if (direction === "NE") translation = [1, -1];
  if (direction === "E") translation = [1, 0];
  if (direction === "SE") translation = [1, 1];
  if (direction === "S") translation = [0, 1];
  if (direction === "SW") translation = [-1, 1];
  if (direction === "W") translation = [-1, 0];
  if (direction === "NW") translation = [-1, -1];
  const coords = [x + translation[0], y + translation[1]] as Coords;
  const cell = getCell(grid, coords);
  if (cell === ".") return getFirstSeatInDirection(grid, coords, direction);
  if (cell == "#" || cell === "L") return cell;
  if (!cell) return undefined;
};

const getVisibleSeats = (grid: Grid, coords: Coords): ("L" | "#")[] => {
  const all = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"] as Direction[];
  return all
    .map((d) => getFirstSeatInDirection(grid, coords, d))
    .filter((c) => c !== undefined) as ("L" | "#")[];
};

const getNextCell = (cell: Cell, neighbours: Cell[]): Cell => {
  if (cell === "L" && !neighbours.includes("#")) return "#";
  if (cell === "#" && neighbours.filter((a) => a === "#").length >= 4)
    return "L";
  return cell;
};

const getNextCellV2 = (grid: Grid, coords: Coords): Cell => {
  const cell = getCell(grid, coords) as Cell;
  const visible = getVisibleSeats(grid, coords);
  if (cell === "L" && !visible.includes("#")) return "#";
  if (cell === "#" && visible.filter((a) => a === "#").length >= 5) return "L";
  return cell;
};

const getNextGrid = (grid: Grid): Grid => {
  return grid.map((row, y) =>
    row.map((cell, x) => getNextCell(cell, getNeighbours(grid, [x, y])))
  );
};

const getNextGridV2 = (grid: Grid): Grid => {
  return grid.map((row, y) =>
    row.map((cell, x) => getNextCellV2(grid, [x, y]))
  );
};

const gridToString = (grid: Grid): string =>
  grid.map((row) => row.join("")).join("\n");

const gridEquals = (a: Grid, b: Grid) => gridToString(a) === gridToString(b);

const getFinalGrid = (grid: Grid, nextGridGetter: (g: Grid) => Grid): Grid => {
  function* makeGridsIterator(
    startGrid: Grid,
    nextGridGetter: (g: Grid) => Grid
  ) {
    let currentGrid = startGrid;
    while (true) {
      let nextGrid = nextGridGetter(currentGrid);
      if (gridEquals(currentGrid, nextGrid)) return;
      currentGrid = nextGrid;
      yield nextGrid;
    }
  }
  let grids = [...makeGridsIterator(grid, nextGridGetter)];
  return grids[grids.length - 1];
};

const countOccupied = (grid: Grid) =>
  grid.flat().filter((c) => c === "#").length;

const solve: AOCSolver = (input) => {
  const grid = parse(input);
  const part1 = countOccupied(getFinalGrid(grid, getNextGrid));
  const part2 = countOccupied(getFinalGrid(grid, getNextGridV2));
  return { part1, part2 };
};

export default solve;
import 'mocha';
import { helloWorld, helloUser } from '../src/handlers/handler';
import { StubEvent, StubContext } from '../stubs/hello';
import * as expect from 'expect.js';

describe('helloWorld', function () {
  let event: StubEvent;
  let context: StubContext = new StubContext('helloWorld');

  it('should return a status code of 200', function () {
    helloWorld(event, context, funct


II",
[31838] = "Poción de sanación de combate sublime",
[31839] = "Poción de sanación de combate sublime",
[31840] = "Poción de maná de combate sublime",
[31841] = "Poción de maná de combate sublime",
[31852] = "Poción de sanación de combate sublime",
[31853] = "Poción de sanación de combate sublime",
[31854] = "Poción de maná de combate sublime",
[31855] = "Poción de maná de combate sublime",
[31856] = "Naipe de la Luna Negra: Cruzada",
[31857] = "Naipe de la Luna Negra: Cólera",
[31858] = "Naipe de la Luna Negra: Venganza",
[31859] = "Naipe de la Luna Negra: Locura",
[31860] = "Gran draenita dorada",
[31861] = "Gran piedra del alba",
[31862] = "Draenita de Sombras equilibrada",
[31863] = "Ojo de noche equilibrado",
[31864] = "Draenita de Sombras imbuida",
[31865] = "Ojo de noche imbuido",
[31866] = "Espesartita de llamas velada",
[31867] = "Topacio noble velado",
[31868] = "Topacio noble maligno",
[31869] = "Espesartita de llamas maligna",
[31870] = "Boceto: gran draenita dorada",
[31871] = "Boceto: draenita de Sombras equilibrada",
[31872] = "Boceto: draenita de Sombras imbuida",
[31873] = "Boceto: espesartita de llamas velada",
[31874] = "Boceto: espesartita de llamas maligna",
[31875] = "Boceto: gran piedra del alba",
[31876] = "Boceto: Ojo de noche equilibrado",
[31877] = "Boceto: Ojo de noche imbuido",
[31878] = "Boceto: topacio noble velado",
[31879] = "Boceto: topacio noble maligno",
[31880] = "Silbato de huérfano elfo de sangre",
[31881] = "Silbato de huérfana draenei",
[31882] = "As de Bendiciones",
[31883] = "Ocho de Bendiciones",
[31884] = "Cinco de Bendiciones",
[31885] = "Cuatro de Bendiciones",
[31886] = "Siete de Bendiciones",
[31887] = "Seis de Bendiciones",
[31888] = "Tres de Bendiciones",
[31889] = "Dos de Bendiciones",
[31890] = "Baraja de Bendiciones",
[31891] = "Baraja de Tormentas",
[31892] = "As de Tormentas",
[31893] = "Ocho de Tormentas",
[31894] = "Cinco de Tormentas",
[31895] = "Cuatro de Tormentas",
[31896] = "Siete de Tormentas",
[31898] = "Seis de Tormentas",
[31899] = "Tres de Tormentas",
[31900] = "Dos de Tormentas",
[31901] = "As de Furias",
[31902] = "Ocho de Furias",
[31903] = "Cinco de Furias",
[31904] = "Cuatro de Furias",
[31905] = "Siete de Furias",
[31906] = "Seis de Furias",
[31907] = "Baraja de Furias",
[31908] = "Tres de Furias",
[31909] = "Dos de Furias",
[31910


%r25
	.word 0xd88c8400  ! 2761: LDUBA_R	lduba	[%r18, %r0] 0x20, %r12
	mov	0x28, %r27
	.word 0xd8956000  ! 2763: LDUHA_I	lduha	[%r21, + 0x0000] %asi, %r12
	.word 0xd8c52000  ! 2764: LDSWA_I	ldswa	[%r20, + 0x0000] %asi, %r12
	.word 0x8780204f  ! 2765: WRASI_I	wr	%r0, 0x004f, %asi
	.word 0xd8d6a000  ! 2766: LDSHA_I	ldsha	[%r26, + 0x0000] %asi, %r12
	.word 0xdcb74e40  ! 2767: STHA_R	stha	%r14, [%r29 + %r0] 0x72
	.word 0xdcb6e000  ! 2768: STHA_I	stha	%r14, [%r27 + 0x0000] %asi
	.word 0xdcc62000  ! 2769: LDSWA_I	ldswa	[%r24, + 0x0000] %asi, %r14
	.word 0xd0d4c400  ! 2770: LDSHA_R	ldsha	[%r19, %r0] 0x20, %r8
	mov	0x7f0, %r21
	.word 0x87802073  ! 2772: WRASI_I	wr	%r0, 0x0073, %asi
	.word 0xd087e000  ! 2773: LDUWA_I	lduwa	[%r31, + 0x0000] %asi, %r8
	.word 0xdc9d84a0  ! 2774: LDDA_R	ldda	[%r22, %r0] 0x25, %r14
	.word 0xd6840400  ! 2775: LDUWA_R	lduwa	[%r16, %r0] 0x20, %r11
	.word 0x87802072  ! 2776: WRASI_I	wr	%r0, 0x0072, %asi
	.word 0xd4f5c4a0  ! 2777: STXA_R	stxa	%r10, [%r23 + %r0] 0x25
	.word 0x87802025  ! 2778: WRASI_I	wr	%r0, 0x0025, %asi
	.word 0xd4cd6000  ! 2779: LDSBA_I	ldsba	[%r21, + 0x0000] %asi, %r10
	.word 0xd4d56000  ! 2780: LDSHA_I	ldsha	[%r21, + 0x0000] %asi, %r10
	.word 0xd4b5a000  ! 2781: STHA_I	stha	%r10, [%r22 + 0x0000] %asi
	.word 0xd6a70e80  ! 2782: STWA_R	stwa	%r11, [%r28 + %r0] 0x74
	.word 0xd6ad2000  ! 2783: STBA_I	stba	%r11, [%r20 + 0x0000] %asi
	.word 0xd0df4e60  ! 2784: LDXA_R	ldxa	[%r29, %r0] 0x73, %r8
	mov	0x58, %r25
	.word 0xd085e000  ! 2786: LDUWA_I	lduwa	[%r23, + 0x0000] %asi, %r8
	mov	0x0, %r17
	.word 0x8780204f  ! 2788: WRASI_I	wr	%r0, 0x004f, %asi