    rating = 4.5,
                        released = DateTimes.of(1995, 8, 10)
                )
        )
    }

    /*
     Sample action ( similar to greeting above ), but with access to the Request object
     Examples:
     CLI: samples.all.request -greeting="hey there"
     WEB: curl -X POST http://localhost:5000/api/samples/all/request -d '{ "greeting": "hello" }'
     */
    @Action(desc = "test access to the request")
    fun request(request: Request, greeting: String): String {
        val greetFromBody = request.data.getString("greeting")
        return "Handled Request: got `$greeting` as parameter, got `$greetFromBody` from request body"
    }

    /*
     Sample action ( similar to greeting above ), to show error handling and returning statuses
     Examples:
     CLI: samples.all.response -status="invalid"
     WEB: curl -X POST http://localhost:5000/api/samples/all/request -d '{ "greeting": "hello" }'
     */
    @Action(desc = "test wrapped result")
    fun response(request: Request, status: String): Outcome<Movie> {
        val sampleMovie = Movie(
                title = "Sample Movie 1",
                category = "action",
                playing = false,
                cost = 10,
                rating = 4.5,
                released = DateTimes.of(1985, 8, 10)
        )
        val result:Outcome<Movie> = when(status) {
            "invalid"  -> Outcomes.invalid ("test status invalid")
            "ignored"  -> Outcomes.ignored ("test status ignored")
            "denied"   -> Outcomes.denied  ("test status denied ")
            "errored"  -> Outcomes.errored ("test status errored")
            "conflict" -> Outcomes.conflict("test status conflict")
            "pending"  -> Outcomes.pending (sampleMovie)
            "success"  -> Outcomes.success (sampleMovie)
            else       -> Outcomes.unexpected("test status unknown")
        }
        return result
    }

    /*
     Sample action to show getting list of objects
     Examples:
     CLI: samples.all.recent -category="sci-fi"
     WEB: curl -X POST http://localhost:5000/api/samples/all/recent -d '{ "category": "sci-fi" }'
     */
    @Action(desc = "test movie list", verb = Verbs.GET)
    fun recent(category: String): List<Movie> {
        return listOf(
                Movie(
                        title = "Sample Movie 1",
                        category = category,
                        playing = false,
                        cost = 10,
                        rating = 4.5,
                        released = DateTimes.of(1985, 8, 10)
                ),
                Movie(
                        title = "Sample Movie 2",
                        category = category,
                        playing = false,
                        cost = 10,
                        rating = 4.5,
                        released = DateTimes.of(1995, 8, 10)
                )
        )
    }

    /**
     * The HTTP Verb handling is automatic or can be explicitly supplied.
     * Names starting with the following match to HTTP Verbs
     * 1. create -> post
     * 2. update -> put
     * 3. patch  -> patch
     * 4. delete -> delete
     */
    /*
     Sample action to show creating a complex object with POST, restricted to WEB only calls
     Examples:
     CLI: N/A
     WEB: curl -X POST http://localhost:5000/api/samples/all/create \
          -H 'Content-Type: application/json' \
          -d '{
                "movie" : {
                    "id": 0,
                    "title": "Indiana Jones",
                    "category": "action",
                    "playing": false,
                    "cost": 10,
                    "rating": 4.5,
                    "released": "1985-08-10T04


_rs_common::world::{Chunk, CHUNK_SIZE};

mod sunlight;
pub mod worker;

/// This data structure contains the y position of the highest opaque block
#[derive(Clone)]
pub struct HighestOpaqueBlock {
    pub y: [i64; (CHUNK_SIZE * CHUNK_SIZE) as usize],
}

impl HighestOpaqueBlock {
    pub fn new() -> Self {
        Self {
            y: [i64::MIN; (CHUNK_SIZE * CHUNK_SIZE) as usize],
        }
    }

    pub fn from_chunk(chunk: &Arc<Chunk>) -> Self {
        let mut hob = Self {
            y: [i64::MIN; (CHUNK_SIZE * CHUNK_SIZE) as usize],
        };
        for i in 0..CHUNK_SIZE {
            for k in 0..CHUNK_SIZE {
                for j in (0..CHUNK_SIZE).rev() {
                    // TODO: use BlockRegistry
                    if chunk.get_block_at((i, j, k)) != 0 {
                        hob.y[(i * CHUNK_SIZE + k) as usize] =
                            j as i64 + chunk.pos.py * CHUNK_SIZE as i64;
                        break;
                    }
                }
            }
        }
        hob
    }

    /// Merge with other HighestOpaqueBlock
    pub fn merge(&mut self, other: &HighestOpaqueBlock) {
        for i in 0..CHUNK_SIZE {
            for k in 0..CHUNK_SIZE {
                let idx = (i * CHUNK_SIZE + k) as usize;
                self.y[idx] = Ord::max(self.y[idx], other.y[idx]);
            }
        }
    }
}
use super::{ParsedModel, ParsedModelPart};
use crate::model::{Material, Vertex};
use genmesh::EmitTriangles;
use obj::ObjMaterial;
use std::sync::Arc;

/// Errors that can occur when loading an .obj file
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Could not load an .obj file
    #[error("Could not load object from file: {0:?}")]
    CouldNotLoadObj(obj::ObjError),
    /// Could not load the .obj's materials
    #[error("Could not load materials: {0:?}")]
    CouldNotLoadMaterials(obj::MtlLibsLoadError),
}

pub fn load(src: &str) -> Result<ParsedModel, Error> {
    let mut obj = obj::Obj::load(std::path::Path::new(src)).map_err(Error::CouldNotLoadObj)?;
    obj.load_mtls().map_err(Error::CouldNotLoadMaterials)?;
    let obj::ObjData {
        position,
        texture,
        normal,
        objects,
        material_libs,
    } = obj.data;

    let vertices: Vec<_> = position
        .into_iter()
        .enumerate()
        .map(|(index, position)| Vertex {
            position,
            normal: normal.get(index).cloned().unwrap_or([0.0, 0.0, 0.0]),
            tex_coord: texture.get(index).cloned().unwrap_or([-1.0, -1.0]),
        })
        .collect();

    let mut result: ParsedModel = vertices.into();
    result
        .parts
        .reserve(objects.iter().map(|o| o.groups.len()).sum());

    for object in objects {
        for group in object.groups {
            let mut index_group = Vec::new();
            for poly in group.polys {
                poly.into_genmesh().emit_triangles(|triangle| {
                    index_group.push(triangle.x.0 as u32);
                    index_group.push(triangle.y.0 as u32);
                    index_group.


();
        return retVal;
    }

    //
    // C++:  void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat& R1, Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags, Size newImageSize = Size(), double balance = 0.0, double fov_scale = 1.0)
    //

    //javadoc: stereoRectify(K1, D1, K2, D2, imageSize, R, tvec, R1, R2, P1, P2, Q, flags, newImageSize, balance, fov_scale)
    public static void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q, int flags, Size newImageSize, double balance, double fov_scale)
    {

        stereoRectify_2(K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, tvec.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj, flags, newImageSize.width, newImageSize.height, balance, fov_scale);

        return;
    }

    //javadoc: stereoRectify(K1, D1, K2, D2, imageSize, R, tvec, R1, R2, P1, P2, Q, flags)
    public static void stereoRectify(Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat tvec, Mat R1, Mat R2, Mat P1, Mat P2, Mat Q, int flags)
    {

        stereoRectify_3(K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, tvec.nativeObj, R1.nativeObj, R2.nativeObj, P1.nativeObj, P2.nativeObj, Q.nativeObj, flags);

        return;
    }

    //
    // C++:  double stereoCalibrate(vector_Mat objectPoints, vector_Mat imagePoints1, vector_Mat imagePoints2, Mat& K1, Mat& D1, Mat& K2, Mat& D2, Size imageSize, Mat& R, Mat& T, int flags = fisheye::CALIB_FIX_INTRINSIC, TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON))
    //

    //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T, flags, criteria)
    public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat K1, Mat D1, Mat K2, Mat D2, Size imageSize, Mat R, Mat T, int flags, TermCriteria criteria)
    {
        Mat objectPoints_mat = Converters.vector_Mat_to_Mat(objectPoints);
        Mat imagePoints1_mat = Converters.vector_Mat_to_Mat(imagePoints1);
        Mat imagePoints2_mat = Converters.vector_Mat_to_Mat(imagePoints2);
        double retVal = stereoCalibrate_3(objectPoints_mat.nativeObj, imagePoints1_mat.nativeObj, imagePoints2_mat.nativeObj, K1.nativeObj, D1.nativeObj, K2.nativeObj, D2.nativeObj, imageSize.width, imageSize.height, R.nativeObj, T.nativeObj, flags, criteria.type, criteria.maxCount, criteria.epsilon);

        return retVal;
    }

    //javadoc: stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T, flags)
    public static double stereoCalibrate(List<Mat> objectPoints, List<Mat> imagePoints1, List<Mat> imagePoints2, Mat K1,


# Test 64-bit COMPARE IMMEDIATE AND BRANCH in cases where the sheer number of
# instructions causes some branches to be out of range.
# RUN: python %s | llc -mtriple=s390x-linux-gnu | FileCheck %s

# Construct:
#
# before0:
#   conditional branch to after0
#   ...
# beforeN:
#   conditional branch to after0
# main:
#   0xffcc bytes, from MVIY instructions
#   conditional branch to main
# after0:
#   ...
#   conditional branch to main
# afterN:
#
# Each conditional branch sequence occupies 12 bytes if it uses a short
# branch and 16 if it uses a long one.  The ones before "main:" have to
# take the branch length into account, which is 6 for short branches,
# so the final (0x34 - 6) / 12 == 3 blocks can use short branches.
# The ones after "main:" do not, so the first 0x34 / 12 == 4 blocks
# can use short branches.  The conservative algorithm we use makes
# one of the forward branches unnecessarily long, as noted in the
# check output below.
#
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 50
# CHECK: jgl [[LABEL:\.L[^ ]*]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 51
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 52
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 53
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 54
# CHECK: jgl [[LABEL]]
# ...as mentioned above, the next one could be a CGIJL instead...
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 55
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 56, [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 57, [[LABEL]]
# ...main goes here...
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 100, [[LABEL:\.L[^ ]*]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 101, [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 102, [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cgijl [[REG]], 103, [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 104
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 105
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 106
# CHECK: jgl [[LABEL]]
# CHECK: lgb [[REG:%r[0-5]]], 0(%r3)
# CHECK: cghi [[REG]], 107
# CHECK: jgl [[LABEL]]

from __future__ import print_function

branch_blocks = 8
main_size = 0xffcc

print('@global = global i32 0')

print('define void @f1(i8 *%base, i8 *%stop) {')
print('entry:')
print('  br label %before0')
print('')

for i in range(branch_blocks):
    next = 'before%d' % (i + 1) if i + 1 < branch_blocks else 'main'
    print('before%d:' % i)
    print('  %%bcur%d = load i8 , i8 *%%stop' % i)
    print('  %%bext%d = sext i8 %%bcur%d to i64' % (i, i))
    print('  %%btest%d = icmp slt i64 %%bext%d, %d' % (i, i, i + 50))
    print('  br i1 %%btest%d, label %%after0, label %%%s' % (i, next))
    print('')

print('%s:' % next)
a, b = 1, 1
for i in range(0, main_size, 6):
    a, b = b, a + b
    offset = 4096 + b % 500000
    value = a % 256
    print('  %%ptr%d = getelementptr i8, i8 *%%base, i64 %d' % (i, offset))
    print('  store volatile i8 %d, i8 *%%ptr%d' % (value, i))

for i in range(branch_blocks):
    print('  %%acur%d = load i8 , i8 *%%stop' % i)
    print('  %%aext%d = sext i8 %%acur%d to i64' % (i, i))
    print('  %%atest%d = icmp slt i64 %%aext%d, %d' % (i, i, i + 100))
    print('  br i1 %%atest%d, label %%main, label %%after%d' % (i, i))
    print('')
    print('after%d:' % i)

print('  %dummy = load volatile i32, i32 *@global')
print('  ret void')
print('}')


ic const struct of_device_id rt288x_wdt_match[] = {
	{ .compatible = "ralink,rt2880-wdt" },
	{},
};
MODULE_DEVICE_TABLE(of, rt288x_wdt_match);

static struct platform_driver rt288x_wdt_driver = {
	.probe		= rt288x_wdt_probe,
	.remove		= rt288x_wdt_remove,
	.shutdown	= rt288x_wdt_shutdown,
	.driver		= {
		.name		= KBUILD_MODNAME,
		.of_match_table	= rt288x_wdt_match,
	},
};

module_platform_driver(rt288x_wdt_driver);

MODULE_DESCRIPTION("MediaTek/Ralink RT288x/RT3xxx hardware watchdog driver");
MODULE_AUTHOR("Gabor Juhos <juhosg@openwrt.org");
MODULE_LICENSE("GPL v2");


Buffer, "AS2D_OUR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE());

			bool bAdvance = canAdvance(pPlot, ((pDefender->canDefendAgainst(this)) ? 1 : 0));

			CvCity* pCapital = GET_PLAYER(pDefender->getOwnerINLINE()).getCapitalCity();
			if (pCapital != NULL && !pDefender->atPlot(pCapital->plot()))
			{
				szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_DEFENDER_UNIT_WITHDRAW", pDefender->getNameKey(), getNameKey(), pCapital->getName().c_str());
				gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_THEIR_WITHDRAWL", MESSAGE_TYPE_INFO, pDefender->getButton(), (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pCapital->getX_INLINE(), pCapital->getY_INLINE());

				pDefender->setXY(pCapital->getX(), pCapital->getY());
			}
			else
			{
				szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WITHDRAW", pDefender->getNameKey(), getNameKey());
				gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, "AS2D_THEIR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE());
			}

			if (!bAdvance)
			{
				changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot())));
				checkRemoveSelectionAfterAttack();
			}

			if (pPlot->getNumVisibleEnemyDefenders(this) == 0)
			{
				getGroup()->groupMove(pPlot, true, ((bAdvance) ? this : NULL));
			}

			getGroup()->clearMissionQueue();
		}
		else
		{
			szBuffer = gDLL->getText("TXT_KEY_MISC_YOU_UNIT_WITHDRAW", getNameKey(), pDefender->getNameKey());
			gDLL->getInterfaceIFace()->addMessage(getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, pDefender->getDomainType() == DOMAIN_SEA ? "AS2D_OUR_SEA_WITHDRAWL" : "AS2D_OUR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_GREEN"), pPlot->getX_INLINE(), pPlot->getY_INLINE());
			szBuffer = gDLL->getText("TXT_KEY_MISC_ENEMY_UNIT_WITHDRAW", getNameKey(), pDefender->getNameKey());
			gDLL->getInterfaceIFace()->addMessage(pDefender->getOwnerINLINE(), true, GC.getEVENT_MESSAGE_TIME(), szBuffer, pDefender->getDomainType() == DOMAIN_SEA ? "AS2D_THEIR_SEA_WITHDRAWL" : "AS2D_THEIR_WITHDRAWL", MESSAGE_TYPE_INFO, NULL, (ColorTypes)GC.getInfoTypeForString("COLOR_RED"), pPlot->getX_INLINE(), pPlot->getY_INLINE());

			changeMoves(std::max(GC.getMOVE_DENOMINATOR(), pPlot->movementCost(this, plot())));
			checkRemoveSelectionAfterAttack();

			getGroup()->clearMissionQueue();
		}
	}
}

void CvUnit::checkRemoveSelectionAfter


tion resumed',
            'timestamp': timezone.now().isoformat()
        })
    except Exception as e:
        return JsonResponse(
            {'error': f'Failed to resume injection: {str(e)}'},
            status=500
        )

@csrf_exempt
@require_http_methods(["POST"])
def injection_manual(request):
    """Manually trigger injection of next message in queue"""
    try:
        create_trigger_file('injection-manual')

        return JsonResponse({
            'success': True,
            'message_injected': True,
            'status': 'Manual injection triggered',
            'timestamp': timezone.now().isoformat()
        })
    except Exception as e:
        return JsonResponse(
            {'error': f'Failed to trigger manual injection: {str(e)}'},
            status=500
        )

# Queue Status (Read-Only)

@csrf_exempt
@require_http_methods(["GET"])
def queue_status(request):
    """Get the current queue status from the frontend"""
    try:
        terminal_id = request.GET.get('terminal_id')

        # Read status from a shared status file (frontend should update this)
        status_file = '/tmp/claude-code-queue-status'

        if os.path.exists(status_file):
            with open(status_file, 'r') as f:
                status_data = json.loads(f.read())

            # Filter by terminal if requested
            if terminal_id:
                terminal_key = f'terminal_{terminal_id}'
                if terminal_key in status_data.get('terminals', {}):
                    return JsonResponse({
                        'success': True,
                        'terminal_id': terminal_id,
                        'count': status_data['terminals'][terminal_key].get('count', 0),
                        'messages': status_data['terminals'][terminal_key].get('messages', []),
                        'timestamp': timezone.now().isoformat()
                    })
                else:
                    return JsonResponse({
                        'success': True,
                        'terminal_id': terminal_id,
                        'count': 0,
                        'messages': [],
                        'timestamp': timezone.now().isoformat()
                    })

            return JsonResponse({
                'success': True,
                **status_data,
                'timestamp': timezone.now().isoformat()
            })
        else:
            # Default response if no status file
            return JsonResponse({
                'success': True,
                'total_messages': 0,
                'terminals': {},
                'timestamp': timezone.now().isoformat()
            })
    except Exception as e:
        return JsonResponse(
            {'error': f'Failed to get queue status: {str(e)}'},
            status=500
        )


nst listOfTransaksiPenjualan: TransaksiPenjualan[] = apiResponseData.map((item) =>
                mapTransaksiPenjualanResponseToTransaksiPenjualan(item),
            );

            return listOfTransaksiPenjualan;
        } else {
            throw new Error("another error");
        }
    } catch (error) {
        throw new Error(error);
    }
};

interface GetKiosDetilTransaksiPenjualanQueryString {
    transaksiId?: number;
}

interface GetKiosDetilTransaksiPenjualanQueryStringRequest {
    transaksi_id?: number;
}
/**
 *
 * @param token
 * @param penjualanId
 * @param queryString
 */
export const getKiosDetilTransaksiPenjualan = async (
    token: string,
    penjualanId: number,
    queryString: GetKiosDetilTransaksiPenjualanQueryString,
): Promise<DetilTransaksiPenjualan> => {
    try {
        const url = "/api/v1/penjualan/" + penjualanId;
        const headers = {
            Authorization: "Bearer " + token,
        };
        const params: GetKiosDetilTransaksiPenjualanQueryStringRequest = {
            transaksi_id: queryString.transaksiId,
        };
        const response = await apiService<any, ApiResponse<DetilTransaksiPenjualanResponse>>({
            url: url,
            headers: headers,
            method: "GET",
            params: params,
        });
        const statusCode = response.status.toString();
        if (statusCode.substr(0, 1) === "2") {
            const apiResponseData = response.data.data;
            const detilTransaksiPenjualan: DetilTransaksiPenjualan = mapDetilTransaksiPenjualanResponseToDetilTransaksiPenjualan(
                apiResponseData,
            );

            return detilTransaksiPenjualan;
        } else {
            throw new Error("another error");
        }
    } catch (error) {
        console.log(error);
        throw new Error(error);
    }
};

export const getKiosDetilPenjualanShow = async (token: string, penjualanId: number): Promise<RincianPenjualan> => {
    try {
        const url = "/api/v1/penjualan/" + penjualanId + "/show";
        const headers = {
            Authorization: "Bearer " + token,
        };

        const response = await apiService<any, ApiResponse<RincianPenjualanResponse>>({
            url: url,
            method: "GET",
            headers: headers,
        });

        const statusCode = response.status.toString();
        if (statusCode.substr(0, 1) === "2") {
            const apiResponseData = response.data.data;
            return mapRincianPenjualanResponseToRincianPenjualan(apiResponseData);
        } else {
            throw new Error("another error");
        }
    } catch (error) {
        throw new Error(error?.response?.data?.message ?? error?.message ?? error);
    }
};

export const usePenjualanApiService = {
    postKiosPenjualan,
    getKiosListOfTransaksiPenjualan,
    getKiosDetilTransaksiPenjualan,
    getKiosDetilPenjualanShow,
};
// export type Command<K extends keyof RemoteCommandMap> = (payload: RemoteCommandMap[K]) => void;
// export const useCommand: <T>(fn: () => T) => T = fn => fn();

import { MessageChannel } from '../messageChannel'
/**
 * maps from id to node
 */
interface NodeMap {
  [key: number]: Node
}

export interface RemotePluginApi {
  nodeMap: NodeMap


dim_timesteps

        assert noise is None or noise.shape == shape
        x = th.randn(shape, device=dev) if noise is None else noise
        time_range = np.flip(timesteps)
        total_steps = timesteps.shape[0]
        tqdm_kwargs = dict(
            total=total_steps,
            desc="Sample DDIM",
            ncols=128,
            disable=not (show_pbar and rankzero),
        )
        tqdm_kwargs.update(pbar_kwargs)
        pbar = tqdm(time_range, **tqdm_kwargs)

        intermediates = [x]
        for i, step in enumerate(pbar):
            index = total_steps - i - 1
            ts = th.full((b,), step, device=dev, dtype=th.long)
            noise_level = self.sqrt_alphas_cumprod_prev[ts]

            e_t = post_fn(denoise_fn(x, noise_level, **denoise_kwargs))
            if self.model_mean_type == "x_0":
                e_t = self.predict_noise_from_start(x, ts, e_t)

            a_t = unsqueeze_as(th.full((b,), self.ddim_alphas[index], device=dev), x)
            a_prev = unsqueeze_as(th.full((b,), self.ddim_alphas_prev[index], device=dev), x)
            sigma_t = unsqueeze_as(th.full((b,), self.ddim_sigmas[index], device=dev), x)
            sqrt_one_minus_at = unsqueeze_as(th.full((b,), self.ddim_sqrt_one_minus_alphas[index], device=dev), x)

            # current prediction for x_0
            pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
            if clip_denoised:
                pred_x0.clamp_(-1.0, 1.0)
            if index % log_every_t == 0 or index == total_steps - 1:
                intermediates.append(pred_x0)

            # direction pointing to x_t
            dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t
            noise = sigma_t * th.randn_like(x)
            x = a_prev.sqrt() * pred_x0 + dir_xt + noise

        if return_intermediates:
            return intermediates
        else:
            return intermediates[-1]


oll;\n}\n#areaAgent .success[data-v-314dd65a] {\n  height: 12.5rem;\n  padding-top: 4.0625rem;\n  background: #ffffff;\n}\n#areaAgent .success .ico[data-v-314dd65a] {\n    height: 4.0625rem;\n    width: 4.0625rem;\n    margin: auto;\n    border: 0.1875rem solid #32cd32;\n    border-radius: 4rem;\n    color: #32cd32;\n    font-size: 36px;\n    text-align: center;\n    line-height: 4rem;\n}\n#areaAgent .success .text[data-v-314dd65a] {\n    height: 2rem;\n    margin-top: 1.875rem;\n    color: #666;\n    line-height: 1.6rem;\n    text-align: center;\n}\n#areaAgent .success a .sub[data-v-314dd65a] {\n    height: 2rem;\n    width: 80%;\n    background: #f55955;\n    margin: 1.25rem auto;\n    border-radius: 2rem;\n    color: #fff;\n    line-height: 2rem;\n    text-align: center;\n    font-size: 14px;\n    margin-bottom: 1.25rem;\n}\n#areaAgent .success a .sub[data-v-314dd65a]:focus {\n    background: #d8403c;\n}\n",""])},FG9p:function(t,e,i){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=i("mvHQ"),a=i.n(n),s=i("Tg7E"),o={data:function(){return{apply:"-1",provicevalue:"",cityvalue:"",regionvalue:"",selectLevel:"",streetvalue:"",level:[],provinceoptions:[],cityoptions:[],regionoptions:[],stroptions:[],proviceObject:"",cityObject:"",regionObject:"",districtObject:"",proshow:!1,cityshow:!1,regshow:!1,strshow:!1,selshow:!1,prozoneshow:!1,cityzoneshow:!1,regzoneshow:!1,streetshow:!1,username:"",password:"",income_name_text:""}},mounted:function(){},activated:function(){this.apply="-1",this.getStatus(),this.customizeIncome()},methods:{getStatus:function(){var t=this;$http.get("plugin.area-dividend.api.area-dividend.apply-status",{},"").then(function(e){1==e.result?(t.apply=e.data.apply,t.tipMsg=e.msg,t.setLogic(t.apply)):MessageBox.alert(e.msg)},function(t){MessageBox.alert(t)})},setLogic:function(t){var e=this;switch(t){case"0":break;case"1":case"2":this.initLevel().then(function(){e.initData()})}},goHome:function(){this.$router.push(this.fun.getUrl("home"))},submitAgain:function(){var t=this,e={data:a()(this.assembleJson())};$http.get("plugin.area-dividend.api.area-dividend.apply-again",e,"提交中").then(function(e){1==e.result?(Object(s.Toast)(e.msg),t.$router.go(-1)):Object(s.Toast)(e.msg)},function(t){Object(s.Toast)(t.msg)})},initLevel:function(){var t=this;return $http.get("plugin.area-dividend.api.area-dividend.can-apply-agent-level",{}).then(function(e){1==e.result&&(console.log(e),t.level=e.data,console.log(1))}).catch(function(t){console.log(t)})},initData


esources("200M", "200m")
				return node
			}(),
			existPods: func() []*v1.Pod {
				pods := []*v1.Pod{}
				for i := 0; i < 4; i++ {
					podSpec := resourcePodSpec("node1", "50M", "50m")
					pods = append(pods, &v1.Pod{
						ObjectMeta: metav1.ObjectMeta{
							Name: fmt.Sprintf("pod_%d", i),
							OwnerReferences: []metav1.OwnerReference{
								{Controller: func() *bool { res := true; return &res }()},
							},
						},
						Spec: podSpec,
					})
				}
				return pods
			}(),
			deletedPod: func() *v1.Pod {
				podSpec := resourcePodSpec("", "50M", "50m")
				return &v1.Pod{
					ObjectMeta: metav1.ObjectMeta{
						Name: "pod_5",
					},
					Spec: podSpec,
				}
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("ds")
				ds.Spec.Template.Spec = resourcePodSpec("", "50M", "50m")
				return ds
			}(),
			shouldEnqueue: false,
		},
	}

	for _, c := range cases {
		for _, strategy := range updateStrategies() {
			manager, podControl, _, err := newTestController()
			if err != nil {
				t.Fatalf("error creating DaemonSets controller: %v", err)
			}
			manager.nodeStore.Add(c.node)
			c.ds.Spec.UpdateStrategy = *strategy
			manager.dsStore.Add(c.ds)
			for _, pod := range c.existPods {
				manager.podStore.Add(pod)
			}
			switch strategy.Type {
			case apps.OnDeleteDaemonSetStrategyType, apps.RollingUpdateDaemonSetStrategyType:
				syncAndValidateDaemonSets(t, manager, c.ds, podControl, 1, 0, 0)
			default:
				t.Fatalf("unexpected UpdateStrategy %+v", strategy)
			}

			enqueued = false
			manager.deletePod(c.deletedPod)
			if enqueued != c.shouldEnqueue {
				t.Errorf("Test case: '%s', expected: %t, got: %t", c.test, c.shouldEnqueue, enqueued)
			}
		}
	}
}

func TestDeleteUnscheduledPodForNotExistingNode(t *testing.T) {
	for _, strategy := range updateStrategies() {
		ds := newDaemonSet("foo")
		ds.Spec.UpdateStrategy = *strategy
		manager, podControl, _, err := newTestController(ds)
		if err != nil {
			t.Fatalf("error creating DaemonSets controller: %v", err)
		}
		manager.dsStore.Add(ds)
		addNodes(manager.nodeStore, 0, 1, nil)
		addPods(manager.podStore, "node-0", simpleDaemonSetLabel, ds, 1)
		addPods(manager.podStore, "node-1", simpleDaemonSetLabel, ds, 1)

		podScheduledUsingAffinity := newPod("pod1-node-3", testTenant, metav1.NamespaceDefault, "", simpleDaemonSetLabel, ds)
		podScheduledUsingAffinity.Spec.Affinity = &v1.Affinity{
			NodeAffinity: &v1.NodeAffinity{
				RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
					NodeSelectorTerms: []v1.NodeSelectorTerm{
						{
							MatchFields: []v1.NodeSelectorRequirement{
								{
									Key:      api.ObjectNameField,
									Operator: v1.NodeSelectorOpIn,
									Values:   []string{"node-2"},
								},
							},
						},
					},
				},
			},


#include	<cdt/dthdr.h>
#include	<stddef.h>

/*	Get statistics of a dictionary
**
**	Written by Kiem-Phong Vo (5/25/96)
*/

static void dttstat(Dtstat_t *ds, Dtlink_t *root, size_t depth, size_t *level) {
	if(root->left)
		dttstat(ds,root->left,depth+1,level);
	if(root->right)
		dttstat(ds,root->right,depth+1,level);
	if(depth > ds->dt_n)
		ds->dt_n = depth;
	if(level)
		level[depth] += 1;
}

static void dthstat(Dtdata_t *data, Dtstat_t *ds, size_t *count) {
	Dtlink_t*	t;
	int		h;

	for(h = data->ntab-1; h >= 0; --h)
	{	size_t n = 0;
		for(t = data->htab[h]; t; t = t->right)
			n += 1;
		if(count)
			count[n] += 1;
		else if(n > 0)
		{	ds->dt_n += 1;
			if(n > ds->dt_max)
				ds->dt_max = n;
		}
	}
}

int dtstat(Dt_t* dt, Dtstat_t* ds, int all)
{
	static size_t *Count;
	static size_t Size;

	UNFLATTEN(dt);

	ds->dt_n = ds->dt_max = 0;
	ds->dt_count = NULL;
	ds->dt_size = dtsize(dt);
	ds->dt_meth = dt->data->type&DT_METHODS;

	if(!all)
		return 0;

	if(dt->data->type&DT_SET)
	{	dthstat(dt->data,ds,NULL);
		if(ds->dt_max+1 > Size)
		{	if(Size > 0)
				free(Count);
			if(!(Count = malloc((ds->dt_max+1)*sizeof(int))) )
				return -1;
			Size = ds->dt_max+1;
		}
		for (size_t i = 0; i <= ds->dt_max; ++i)
			Count[i] = 0;
		dthstat(dt->data,ds,Count);
	}
	else if(dt->data->type&(DT_OSET|DT_OBAG))
	{	if(dt->data->here)
		{	dttstat(ds,dt->data->here,0,NULL);
			if(ds->dt_n+1 > Size)
			{	if(Size > 0)
					free(Count);
				if(!(Count = malloc((ds->dt_n+1)*sizeof(int))) )
					return -1;
				Size = ds->dt_n+1;
			}

			for (size_t i = 0; i <= ds->dt_n; ++i)
				Count[i] = 0;
			dttstat(ds,dt->data->here,0,Count);
			for(size_t i = 0; i <= ds->dt_n; ++i)
				if(Count[i] > ds->dt_max)
					ds->dt_max = Count[i];
		}
	}
	ds->dt_count = Count;

	return 0;
}


断是否可以借阅

#### 核心类和函数
- `Borrow_Book_Panel`：主面板类
  - `draw()`：绘制借书界面
  - `show_book(book_cid)`：显示单本书籍详细信息
  - `borrow(book_cid)`：执行借书/还书操作
  - `change_panel(building_type)`：切换书籍分类页面

- 重要函数：
  - `settle_library_book()`：刷新图书馆可借阅书籍，每类最多显示3本
  - `can_read_book(character_id, book_cid)`：检查角色能力是否足够阅读指定书籍
  - `check_return_book(character_id)`：检查并决定NPC是否归还书籍（随机）
  - `check_random_borrow_book(character_id)`：NPC随机借书逻辑
  - `add_borrow_history_record(character_id, book_id)`：添加借书历史记录
  - `update_return_history_record(character_id, book_id)`：更新还书历史记录
  - `update_read_count_in_history(character_id, book_id)`：更新历史记录中的阅读次数

#### 数据结构
```python
# 缓存数据
cache.rhodes_island.now_show_book_cid_of_type[book_type_cid]  # 当前展示的书籍ID列表
cache.rhodes_island.book_borrow_dict[book_id]  # 书籍借阅状态 (-1:可借, 0:被博士借, >0:被NPC借)
character_data.entertainment.borrow_book_id_set  # 角色借阅的书籍ID集合
character_data.entertainment.book_return_possibility  # 角色还书概率
```

### 2. 读书面板 (read_book_panel.py)

#### 主要功能
- **读书执行**：选择已借书籍进行阅读
- **进度显示**：显示每本书的阅读进度
- **内容展示**：随机显示书籍片段内容

#### 核心类和函数
- `Read_Book_Panel`：主面板类
  - `draw()`：绘制已借书籍列表
  - `read(book_id)`：执行读书行为

- `draw_book_fragment(book_id)`：随机绘制书籍片段内容

#### 行为触发机制
```python
character_data.behavior.behavior_id = constant.Behavior.READ_BOOK  # 设置读书行为
character_data.state = constant.CharacterStatus.STATUS_READ_BOOK   # 设置状态
character_data.behavior.book_id


from pyrogram import Client, filters
from pyrogram.types import Message
from AarohiX import app
from strings.filters import command
from config import OWNER_ID

@app.on_message(command("احسب"))
def calculate_math(client, message):
    expression = message.text.split("احسب ", 1)[1]

    try:
        result = eval(expression.replace("×", "*").replace("÷", "/"))  # استبدال علامات الضرب والقسمة
        response = f"~ الناتج هو : {result}"
    except:
        response = "~ اكتب بالصيغة الصحيحة مثل: احسب 3 + 3 * 4"

    message.reply(response)


+= chars.charAt((Math.random() * 16) | 0);
    return hex;
  },
  mergebuf(b1: Uint8Array | number[], b2: Uint8Array | number[]): Uint8Array {
    const r = new Uint8Array(b1.length + b2.length);
    r.set(b1);
    r.set(b2, b1.length);
    return r;
  },
  sexp2mic(_mi: string): OperationParameter {
    let mi = _mi
      .replace(/(?:@[a-z_]+)|(?:#.*$)/gm, '')
      .replace(/\s+/g, ' ')
      .trim();
    if (mi.charAt(0) === '(') mi = mi.slice(1, -1);
    let pl = 0;
    let sopen = false;
    let escaped = false;
    const ret = {
      prim: '',
      args: [] as OperationParameter[]
    };
    let val = '';
    for (let i = 0; i < mi.length; i++) {
      if (escaped) {
        val += mi[i];
        escaped = false;
        continue;
      } else if ((i === mi.length - 1 && !sopen) || (mi[i] === ' ' && pl === 0 && !sopen)) {
        if (i === mi.length - 1) val += mi[i];
        if (val) {
          const valInt = parseInt(val, 10);
          if (val === valInt.toString()) {
            if (!ret.prim) return { int: val };
            ret.args.push({ int: val });
          } else if (val[0] === '0') {
            if (!ret.prim) return { bytes: val };
            ret.args.push({ bytes: val });
          } else if (ret.prim) {
            ret.args.push(this.sexp2mic(val));
          } else {
            ret.prim = val;
          }
          val = '';
        }
        continue;
      } else if (mi[i] === '"' && sopen) {
        sopen = false;
        if (!ret.prim) return { string: val };
        ret.args.push({ string: val });
        val = '';
        continue;
      } else if (mi[i] === '"' && !sopen && pl === 0) {
        sopen = true;
        continue;
      } else if (mi[i] === '\\') escaped = true;
      else if (mi[i] === '(') pl++;
      else if (mi[i] === ')') pl--;
      val += mi[i];
    }
    return ret;
  },
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  mic2arr(s: OperationParameter): any {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let ret = [] as any;
    if ('prim' in s) {
      if (s.prim === 'Pair') {
        if (!s.args) throw new Error('Prim is pair but args is empty');
        ret.push(this.mic2arr(s.args[0]));
        ret = ret.concat(this.mic2arr(s.args[1]));
      } else if (s.prim === 'Elt') {
        if (!s.args) throw new Error('Prim is Elt but args is empty');
        ret = {
          key: this.mic2arr(s.args[0]),
          val: this.mic2arr(s.args[1])
        };
      } else if (s.prim === 'True') {
        ret = true;
      } else if (s.prim === 'False') {
        ret = false;
      }
    } else if (Array.isArray(s)) {
      const sc = s.length;
      for (let i = 0; i < sc; i++) {
        const n = this.mic2arr(s[i]);
        if (typeof n.key !== 'undefined') {
          if (Array.isArray(ret)) {
            ret = {
              keys: [],
              vals: []


 turtle = new InputTurtle("turtle");
    private final InputImage image = new InputImage("image");
    private final InputDouble stepSize = new InputDouble("stepSize", 1d);
    private final InputDouble thickness = new InputDouble("thickness", 5d);
    private final InputDouble penDiameter = new InputDouble("pen diameter", 0.8);
    private final OutputTurtle result = new OutputTurtle("result");

    public LineSpiralByImage() {
        super("LineSpiralByImage");
        addPort(image);
        addPort(turtle);
        addPort(stepSize);
        addPort(thickness);
        addPort(penDiameter);
        addPort(result);
    }

    @Override
    public void update() {
        Turtle myTurtle = turtle.getValue();
        if(myTurtle==null || !myTurtle.hasDrawing()) return;

        setComplete(0);

        var sourceImage = new TransformedImage(image.getValue());
        var tool = new SpiralByIntensity(sourceImage, thickness.getValue()/2.0, stepSize.getValue());
        result.setValue(tool.turtleToSpiral(myTurtle));

        setComplete(100);
    }
}
package com.marginallyclever.makelangelo.donatelloimpl.nodes.turtle.fractals;

import com.marginallyclever.donatello.ports.InputInt;
import com.marginallyclever.makelangelo.donatelloimpl.ports.OutputTurtle;
import com.marginallyclever.makelangelo.turtle.Turtle;
import com.marginallyclever.nodegraphcore.Node;

/**
 * Gosper fractal
 */
public class Gosper extends Node {
    private final InputInt order = new InputInt("order", 7);
    private final OutputTurtle output = new OutputTurtle("turtle");

    public Gosper() {
        super("Gosper");
        addPort(order);
        addPort(output);
    }

    @Override
    public void update() {
        setComplete(0);
        int count = Math.max(1,order.getValue());

        Turtle turtle = new Turtle();
        turtle.jumpTo(0,0);
        turtle.penDown();
        gosperA(turtle,count);

        // center the turtle
        var b = turtle.getBounds();
        turtle.translate(-b.x-b.width/2, -b.y-b.height/2);

        output.setValue(turtle);
        setComplete(100);
    }

    // Gosper curve A = A-B--B+A++AA+B-
    private void gosperA(Turtle turtle,int n) {
        if (n == 0) {
            gosperForward(turtle);
            return;
        }
        gosperA(turtle,n-1);
        turtle.turn(-60);
        gosperB(turtle,n-1);
        turtle.turn(-60);
        turtle.turn(-60);
        gosperB(turtle,n-1);
        turtle.turn(60);
        gosperA(turtle,n-1);
        turtle.turn(60);
        turtle.turn(60);
        gosperA(turtle,n-1);
        gosperA(turtle,n-1);
        turtle.turn(60);
        gosperB(turtle,n-1);
        turtle.turn(-60);
    }

    // Gosper curve B = +A-BB--B-A++A+B
    public void gosperB(Turtle turtle,int n) {
        if (n == 0) {
            gosperForward(turtle);
            return;
        }
        turtle.turn(60);
        gosperA(turtle,n-1);
        turtle.turn(-60);
        gosperB(turtle,n-1);
        gosperB(turtle,n-1);
        turtle.turn(-60);
        turtle.turn(-60);
        gosperB


ENCY_PRINT_LOAD_GPR7	l.mfspr r7,r0,SPR_SHADOW_GPR(7)

#define EMERGENCY_PRINT_STORE_GPR8	l.mtspr r0,r8,SPR_SHADOW_GPR(8)
#define EMERGENCY_PRINT_LOAD_GPR8	l.mfspr r8,r0,SPR_SHADOW_GPR(8)

#define EMERGENCY_PRINT_STORE_GPR9	l.mtspr r0,r9,SPR_SHADOW_GPR(9)
#define EMERGENCY_PRINT_LOAD_GPR9	l.mfspr r9,r0,SPR_SHADOW_GPR(9)

#else /* !CONFIG_OPENRISC_HAVE_SHADOW_GPRS */
#define EMERGENCY_PRINT_STORE_GPR4	l.sw    0x20(r0),r4
#define EMERGENCY_PRINT_LOAD_GPR4	l.lwz   r4,0x20(r0)

#define EMERGENCY_PRINT_STORE_GPR5	l.sw    0x24(r0),r5
#define EMERGENCY_PRINT_LOAD_GPR5	l.lwz   r5,0x24(r0)

#define EMERGENCY_PRINT_STORE_GPR6	l.sw    0x28(r0),r6
#define EMERGENCY_PRINT_LOAD_GPR6	l.lwz   r6,0x28(r0)

#define EMERGENCY_PRINT_STORE_GPR7	l.sw    0x2c(r0),r7
#define EMERGENCY_PRINT_LOAD_GPR7	l.lwz   r7,0x2c(r0)

#define EMERGENCY_PRINT_STORE_GPR8	l.sw    0x30(r0),r8
#define EMERGENCY_PRINT_LOAD_GPR8	l.lwz   r8,0x30(r0)

#define EMERGENCY_PRINT_STORE_GPR9	l.sw    0x34(r0),r9
#define EMERGENCY_PRINT_LOAD_GPR9	l.lwz   r9,0x34(r0)

#endif

/*
 * TLB miss handlers temorary stores
 */
#ifdef CONFIG_OPENRISC_HAVE_SHADOW_GPRS
#define EXCEPTION_STORE_GPR2		l.mtspr r0,r2,SPR_SHADOW_GPR(2)
#define EXCEPTION_LOAD_GPR2		l.mfspr r2,r0,SPR_SHADOW_GPR(2)

#define EXCEPTION_STORE_GPR3		l.mtspr r0,r3,SPR_SHADOW_GPR(3)
#define EXCEPTION_LOAD_GPR3		l.mfspr r3,r0,SPR_SHADOW_GPR(3)

#define EXCEPTION_STORE_GPR4		l.mtspr r0,r4,SPR_SHADOW_GPR(4)
#define EXCEPTION_LOAD_GPR4		l.mfspr r4,r0,SPR_SHADOW_GPR(4)

#define EXCEPTION_STORE_GPR5		l.mtspr r0,r5,SPR_SHADOW_GPR(5)
#define EXCEPTION_LOAD_GPR5		l.mfspr r5,r0,SPR_SHADOW_GPR(5)

#define EXCEPTION_STORE_GPR6		l.mtspr r0,r6,SPR_SHADOW_GPR(6)
#define EXCEPTION_LOAD_GPR6		l.mfspr r6,r0,SPR_SHADOW_GPR(6)

#else /* !CONFIG_OPENRISC_HAVE_SHADOW_GPRS */
#define EXCEPTION_STORE_GPR2		l.sw    0x64(r0),r2
#define EXCEPTION_LOAD_GPR2		l.lwz   r2,0x64(r0)

#define EXCEPTION_STORE_GPR3		l.sw    0x68(r0),r3


   description = "Do not fail the check if there are macOS-only artifacts which can't be checked."
  )
  var lenientOs: Boolean
    @Input
    get() = lenientOsProp.getOrElse(false)
    set(value) = lenientOsProp.set(value)

  @TaskAction
  fun run() {

    val expected = getExpectedArtifacts()

    val currentPaths = currentList.mapTo(mutableSetOf()) { it.key }

    val extraFromJson = expected.values.filterNot { it.key in currentPaths }
    val extraFromCurrent = currentList.filterNot { it.key in expected.keys }

    val changed = currentList.minus(expected.values.toSet())
      .minus(extraFromCurrent.toSet())
      .map { artifact ->
        expected.getValue(artifact.key) to artifact
      }

    // Each artifact needs to have a unique ID.  Repository managers will quietly allow overwrites
    // with duplicate IDs, so this is the last chance to catch it before publishing.
    val duplicateArtifactIds = currentList.findDuplicates { artifactId }

    // This is mostly superficial, but it ensures that a copy/pasted module also doesn't retain the
    // original's pom description.
    val duplicateDescriptions = currentList.findDuplicates { description }

    val foundSomething = sequenceOf(
      duplicateArtifactIds.keys,
      duplicateDescriptions.keys,
      extraFromJson,
      extraFromCurrent,
      changed
    ).any { it.isNotEmpty() }

    if (foundSomething) {
      reportChanges(
        duplicateArtifactIds = duplicateArtifactIds,
        duplicatePomDescriptions = duplicateDescriptions,
        missing = extraFromJson,
        extraFromCurrent = extraFromCurrent,
        changed = changed
      )
    }
  }

  private fun getExpectedArtifacts(): Map<String, ArtifactConfig> {

    val inMacOS = Os.isFamily(Os.FAMILY_MAC)
    // The macOS artifacts all have publication names like 'iosX64', 'watchosX86', 'iosSimulatorArm64', etc.
    val macOnly = """^(?:ios|tvos|watchos|macos).*""".toRegex()

    // If this task isn't running on macOS, ignore the macOS-only artifacts.
    val (testableArtifacts, ignoredArtifacts) = moshiAdapter.fromJson(reportFile.asFile.readText())
      .orEmpty()
      .partition { inMacOS || !it.publicationName.matches(macOnly) }

    if (ignoredArtifacts.isNotEmpty()) {

      val message = buildString {

        append("The existing artifacts file references artifacts which can only be created ")
        append("from a computer running macOS, so they cannot be validated now ")
        appendLine("(running ${System.getProperty("os.name")}).")
        appendLine()
        appendLine("\tThese artifacts cannot be checked:")
        appendLine()
        ignoredArtifacts.forEach {
          appendLine(it.message())
          appendLine()
        }
        if (!lenientOs) {
          appendLine()
          append("Add the `--lenient-os` option replace this failure with a warning: ")
          appendLine("./gradlew artifactsCheck --lenient-os")
        }
      }

      if (lenientOs) {
        logger.warn(message.colorized(YELLOW))
      } else {
        logger.error(message.colorized(RED))
        throw GradleException(
          "Artifacts check failed.  There are unchecked macOS-only artifacts " +
            "and lenient-os mode is not enabled."
        )
      }
    }

    return testableArtifacts.associateBy { it.key }
  }

  private fun <R : Comparable


	})

	t.Run("filter blocks all nodes", func(t *testing.T) {
		blockAllFilter := nodeselection.NodeFilterFunc(func(node *nodeselection.SelectedNode) bool {
			return false
		})

		selector := nodeselection.DownloadFilter(blockAllFilter, nodeselection.DefaultDownloadSelector)
		selected, err := selector(ctx, requester, possibleNodes, 3)

		require.NoError(t, err)
		assert.Len(t, selected, 0)
	})

	t.Run("filter allows only vetted nodes", func(t *testing.T) {
		vettedFilter := nodeselection.NodeFilterFunc(func(node *nodeselection.SelectedNode) bool {
			return node.Vetted
		})

		selector := nodeselection.DownloadFilter(vettedFilter, nodeselection.DefaultDownloadSelector)
		selected, err := selector(ctx, requester, possibleNodes, 3)

		require.NoError(t, err)
		assert.Len(t, selected, 2) // node1 and node3 are vetted
		assert.Contains(t, selected, node1.ID)
		assert.Contains(t, selected, node3.ID)
		assert.NotContains(t, selected, node2.ID)
	})

}

func TestRequesterIs(t *testing.T) {
	ctx := testcontext.New(t)

	target1 := testrand.NodeID()
	target2 := testrand.NodeID()
	other := testrand.NodeID()

	t.Run("single target - matches", func(t *testing.T) {
		condition := nodeselection.RequesterIs(target1.String())
		result := condition(ctx, target1)
		assert.True(t, result)
	})

	t.Run("single target - doesn't match", func(t *testing.T) {
		condition := nodeselection.RequesterIs(target1.String())
		result := condition(ctx, other)
		assert.False(t, result)
	})

	t.Run("multiple targets - matches first", func(t *testing.T) {
		condition := nodeselection.RequesterIs(target1.String(), target2.String())
		result := condition(ctx, target1)
		assert.True(t, result)
	})

	t.Run("multiple targets - matches second", func(t *testing.T) {
		condition := nodeselection.RequesterIs(target1.String(), target2.String())
		result := condition(ctx, target2)
		assert.True(t, result)
	})

	t.Run("multiple targets - doesn't match any", func(t *testing.T) {
		condition := nodeselection.RequesterIs(target1.String(), target2.String())
		result := condition(ctx, other)
		assert.False(t, result)
	})

	t.Run("no targets", func(t *testing.T) {
		condition := nodeselection.RequesterIs()
		result := condition(ctx, target1)
		assert.False(t, result)
	})
}
// Copyright (C) 2020 Storj Labs, Inc.
// See LICENSE for copying information.

package nodeselection

import (
	"context"

	"github.com/zeebo/errs"

	"storj.io/common/storj"
)

// ErrNotEnoughNodes is when selecting nodes failed with the given parameters.
var ErrNotEnoughNodes = errs.Class("not enough nodes")

// State includes a stateful selector (indexed nodes) for each placement.
type State map[storj.PlacementConstraint]NodeSelector

var initStateTask = mon.Task()

// InitState initializes the State for each placement.
func InitState(ctx context.Context, nodes []*SelectedNode, placements PlacementDefinitions) State {
	defer initStateTask(&ctx)(nil)
	state := make(State)
	for id, placement := range placements {
		selector := placement.Selector
		if selector == nil {
			selector = RandomSelector()
		}
		var filter =


MatrixC, int m, int n, int k) {
        int bx = blockIdx.x, by = blockIdx.y;
        int tx = threadIdx.x, ty = threadIdx.y;
        int aBegin = k * BLOCK_SIZE * by;
        int aEnd = aBegin + k - 1;
        int aStep = BLOCK_SIZE;
        int bBegin = BLOCK_SIZE * bx;
        int bStep = BLOCK_SIZE * n;
        float Csub = 0;
        for (int a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep) {
            __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
            __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
            As[ty][tx] = fpMatrixA[a + k * ty + tx];
            Bs[ty][tx] = fpMatrixB[b + n * ty + tx];
            __syncthreads();
            for (int k = 0; k < BLOCK_SIZE; ++k)
                Csub += As[ty][k] * Bs[k][tx];
            __syncthreads();
        }
        int c = n * BLOCK_SIZE * by + BLOCK_SIZE * bx;
        fpMatrixC[c + n * ty + tx] = Csub;
    }

下面是一个完整的矩阵乘法程序

      #include < iostream >
        #include < cuda_runtime.h >
        #define BLOCK_SIZE 16
        __global__ void matrixMulSharedKernel(float *fpMatrixA, float *fpMatrixB, float *fpMatrixC, int m, int n, int k)
        {
          int bx = blockIdx.x, by = blockIdx.y;
          int tx = threadIdx.x, ty = threadIdx.y;
          int aBegin = k * BLOCK_SIZE * by;
          int aEnd = aBegin + k - 1;
          int aStep = BLOCK_SIZE;
          int bBegin = BLOCK_SIZE * bx;
          int bStep = BLOCK_SIZE * n;
          float Csub = 0;
          for (int a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep)
          {
            __shared__ float As[BLOCK_SIZE][BLOCK_SIZE];
            __shared__ float Bs[BLOCK_SIZE][BLOCK_SIZE];
            As[ty][tx] = fpMatrixA[a + k * ty + tx];
            Bs[ty][tx] = fpMatrixB[b + n * ty + tx];
            __syncthreads();
            for (int k = 0; k < BLOCK_SIZE; ++k)
              Csub += As[ty][k] * Bs[k][tx];
            __syncthreads();
          }
          int c = n * BLOCK_SIZE * by + BLOCK_SIZE * bx;
          fpMatrixC[c + n * ty + tx] = Csub;
        }
        // CUDA 错误检查宏
        #define cudaCheckError(ans)
          {
            gpuAssert((ans), __FILE__, __LINE__);
          }
        inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort = true)
        {
          if (code != cudaSuccess)
          {
            fprintf(stderr, "GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
            if (abort)
              exit(code);
          }


in
	  // two separate non-overlapping live ranges, the pointer
	  // points to two different blocks of memory. In one live
	  // range, the base pointer was replaced by a preg, but of
	  // course the memops in that live range had their restricted
	  // map entries left intact (which is as it should be). As a
	  // result, alias analysis assigns the same vsym to memops
	  // from both live ranges (because the restricted map
	  // correctly says they are based on the same base pointer),
	  // but alias classification proves that memops from one live
	  // range cannot alias with memops from the other because the
	  // code after LNO uses two separate base pointers (the
	  // unique pointer in one case and the preg in the
	  // other). The right solution is to throw away the alias
	  // class information in the vsym for these memops. The
	  // Unique_pt() attribute gives us all the information we
	  // could hope for anyway because LNO will not introduce a
	  // case where the live ranges of the original base pointer
	  // and the copy overlap. The discarding of the alias class
	  // information (and the IP alias class information) happens
	  // inside POINTS_TO::Meet_info_from_alias_class(). -- RK
	  // Note: Since the above assertion doesn't hold in general,
	  if (alias_class != OPTIMISTIC_AC_ID &&
	      alias_class != PESSIMISTIC_AC_ID &&
	      !Alias_classification()->Writable_by_call(alias_class) &&
	      alias_class <= WOPT_Alias_Class_Limit) {
	    // The memory object cannot be touched by callees of this
	    // routine, and the aux_id for this vsym might not have
	    // existed at the time of
	    // Alias_classification()->Classify_memops(). As a result,
	    // this vsym's aux_id would not have been marked as
	    // inaccessible to callees by alias classification, and we
	    // have to mark it that way now.
	    Set_inaccessible_to_callees(BS_Union1D(Inaccessible_to_callees(),
						   occ->Aux_id(), mem_pool));
	    // This object can't live outside the present PU. Mark it
	    // as local so we don't generate mu/chi for it at CALL and
	    // RETURN points. This is easier than checking the
	    // Alias_class() at every place where we might generate
	    // such a mu or chi node.
	    vsym_pt->Set_local();
	    if (Get_Trace(TP_GLOBOPT, ALIAS_DUMP_FLAG)) {
	      fprintf(TFile, "Xfer_ac: Aux ID %d is local unique_pt vsym\n",
		      occ->Aux_id());
	    }
	    if (WOPT_Alias_Class_Limit != UINT32_MAX) {
	      Lmt_DevWarn(1,
			  ("Alias class used to set Inaccessible_to_callees"));
	    }
	  }
	  // The following assertion removed 981116; see comments
	  // above for the per-PU case that explain why. -- RK
#if Is_True_On
	  if ((WOPT_Ip_Alias_Class_Limit == UINT32_MAX) &&
	      (WN_MAP32_Get(WN_MAP_ALIAS_CLASS, wn) ==
	       OPTIMISTIC_AC_ID) &&
	      (vsym_pt->Ip_alias_class() != OPTIMISTIC_AC_ID)) {
	    DevWarn("Someone (LNO?) introduced a WN without setting "
		    "its IP alias class");
	  }
#endif
	}

	// Perform the part of POINTS_TO::Meet that is related to
	// alias class information, since Meet operations will already
	// have been done before we finalize the full set of
	// POINTS_TO's for the program. As a special case, this has
	// the effect that when the aux ID for this memop's vsym is
	// guaranteed to have a single consistent alias class


from "marked";
import highlightjs from "highlight.js";

class CustomMarked {

  private renderer: Renderer;

  constructor(leftIconUrl: string, rightIconUrl: string) {
    this.renderer = new Renderer();

    // # text renderer
    this.renderer.heading = (text: string, level: number): string => {

      const date = new Date();
      const dateString = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
      const datetimeDiv = level === 1 ? `<div class="datetime">更新日: ${dateString}</div>` : "";

      return `
        <h${level}>

${text}

          ${datetimeDiv}
        </h${level}>
        ${ level === 1 ? "
" : "" }
      `;
    }

    // **text** renderer
    this.renderer.strong = (text: string): string => {
      return `
        ${text}
      `;
    }

    // `text` renderer
    this.renderer.codespan = (code: string): string => {
      return `
        ${code}
      `;
    }

    // ```lang
    // code block
    // ```
    this.renderer.code = (code: string, languages: string) => {

      const langFileName = (languages || "plaintext").split(":");
      const lang = langFileName[0];
      const fileName = langFileName[1] || "";

      const fileNameBlock = fileName ? `<code class="filename">${fileName}</code>` : "";

      if (lang === "table") {
        return `
          ${fileNameBlock}
          ${renderTable(code)}
        `;
      } else if (lang === "comment") {
        const rows = code.split("\n").join("
");
        return `
          ${renderComment(rows, fileName || "left")}
        `;
      } else {
        return `
        ${fileNameBlock}
        ${renderCode(code, lang)}
      `;
      }
    }

    const renderTable = (code: string): string => {
      const rows = code.split("\n").map(row => row.split(","));
      return `

${(rows.shift() || []).map(cell => (`<th>${cell}</th>`)).join("")}

            ${rows.map(row => (`<tr>${row.map(cell => (`${cell}	`)).join("")}</tr>`)).join("")}

      `;
    }

    const renderCode = (code: string, lang: string = "left"): string => {
      return `

${
          highlightjs.highlightAuto(code, [lang]).value
        }

      `;
    }

    const renderComment = (message: string, rightOrLeft: string) => {
      return `

${message}

      `;
    }

    // p
    this.renderer.paragraph = (text: string): string => {
      return `

${text}

      `;
    }

    this.renderer.text = (text: string) => {
      return `
        ${text}
      `;
    }

    // list
    this.renderer.list = (body: string): string => {
      return `

${body}

      `;
    }

    this.renderer.listitem = (text: string): string => {
      const listItems = text.split('
');
      const listItem = (listItems.shift() || "").replace(/\n/g, "");
      const subItem = (listItem.match(/<[^span]*>.*/) || [""])[0];
      return `

          ${listItem.replace(subItem, "")}

        ${listItems.length === 0 ? "" : `<p>${listItems.join("<br>")}</p>`}
        ${subItem}
      `;
    }

    // > blockquote
    this.renderer.blockquote = (quote: string): string => {


)
    print(corpus_readable)
    print("")
    print("")

    # # #6): applico la trasformazione tf-idf ai documenti del corpus
    # tfidf = models.TfidfModel(corpus)  # step 1
    # corpus_tfidf = tfidf[corpus]
    # print("corpus_tfidf (Ogni vettore tf-idf qui sotto, rappresenta un documento.")
    # for doc in corpus_tfidf:
    #     print(doc)
    # print("")

    ########################################
    #Applicazione tecnica LDA:
    # update_every: Number of documents to be iterated through for each update.
    # chunksize: Number of documents to be used in each training chunk.
    # passes: Number of passes through the corpus during training.
    lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus, id2word=dizionario, num_topics=3, update_every=12, chunksize=12, passes=12)
    #lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus_tfidf, id2word=dizionario, num_topics=3)
    vis = pyLDAvis.gensim_models.prepare(lda_model, corpus, dizionario)
    #pyLDAvis.save_html(vis, 'Risorse_Topic_Modelling_Text_Visualization\\Risultati visualizzazione TM-TV.html') #SALVO i topics trovati
    ########################################

    print("")
    print("lda_model topics trovati:")
    print(lda_model.print_topics())
    print(type(lda_model.print_topics()))

    #Passi successivi:
    # 1) Considero tutte le parole presenti in un certo topics come un cluster (cluster_0 = music, cluster_1 = physics, cluster_2 = Artificial Intelligence.
    # 2) Dopodichè applico un algoritmo di clustering per associare ogni documento presente nel mio copus (documenti Ym-TV.txt) ad un certo cluster.

    #1)
    cluster_0 = lda_model.print_topics()[0]
    cluster_1 = lda_model.print_topics()[1]
    cluster_2 = lda_model.print_topics()[2]

    cluster_0 = get_parole_cluster_corrente(cluster_0)
    cluster_1 = get_parole_cluster_corrente(cluster_1)
    cluster_2 = get_parole_cluster_corrente(cluster_2)

    #Stampo quelli che per me saranno i centroidi di ogni cluster:
    print("termini cluster_0: ", cluster_0)
    print("termini cluster_1: ", cluster_1)
    print("termini cluster_2: ", cluster_2)
    print("")

    #2)
    documenti_cluster_0 = []
    documenti_cluster_1 = []
    documenti_cluster_2 = []
    indice_documento_corrente = 0
    for lista_termini_documento in lista_frasi_documento:
        cluster_documento_corrente = get_cluster_documento(lista_termini_documento, cluster_0, cluster_1, cluster_2)
        print("indice_documento_corrente: ", indice_documento_corrente)
        print("cluster_documento_corrente: ", cluster_documento_corrente)
        indice_documento_corrente+=1
        print("")


{
				path = getProject().getHomeDirectoryName() + targetName.substring(8, targetName.length());
			}
			else
				path = targetName;
			showWebPage(path, false);
		}
		/*else if (checker.compare(this.getClass(), "Sets background color of window", "[name of color]", commandName, "setBackground")) {
    	 		Color bc = ColorDistribution.getStandardColor(parser.getFirstToken(arguments));
			if (bc == null)
				return null;
			bgColor = bc;
			if (npw == null)
				return null;
			//npw.setColor(bc);
			if (npw.isVisible())
				npw.repaint();
    	 	}
    	 	else if (checker.compare(this.getClass(), "NOT USED", null, commandName, "makeWindow")) {
    	 	} */
		else
			return  super.doCommand(commandName, arguments, checker);
		return null;
	}
	public void shutDown(){
		if (!isDoomed() && npw!=null)
			windowGoAway(npw);
	}
	/*.................................................................................................................*/
	public void windowGoAway(MesquiteWindow whichWindow) {
		if (whichWindow == null)
			return;
		whichWindow.hide();
		whichWindow.dispose();
		iQuit();
	}
	/*.................................................................................................................*/
	public void endJob() {
		if (npw != null) {
			npw.hide();
			npw.dispose();
		}
		if (file !=null)
			file.removeListener(this);
		super.endJob();
	}
	/*.................................................................................................................*/
	public String getName() {
		return "Examples Navigator";
	}
	/*.................................................................................................................*/
	public String getExplanation() {
		return "Provides a Examples Navigator window with explanation and buttons to link to other files";
	}
	/*.................................................................................................................*/
	public String getNameForMenuItem() {
		return "New Examples Navigator";
	}
	public boolean isSubstantive(){
		return false;
	}

}

/* ======================================================================== */
class ExamplesNavigatorWindow extends MesquiteWindow implements TextListener {
	//TextField nextText;
	//TextField prevText;
	//TextField titleText;
	String nextName = "Next";
	String prevName = "Previous";
	MesquiteBoolean showFileNames;
	Parser parser = new Parser();
	Panel contents, controls, textFields;
	FieldPanel nextPanel, prevPanel, titlePanel;
	TitlePanel buttons;
	Panel extras;
	MesquiteCommand fileLinkCommand, showPageCommand, nextCommand, prevCommand;

	//TextField prevLabel;
	//TextField nextLabel;
	Button prev, next;
	TextArea explanation;
	public ExamplesNavigatorWindow(ExamplesNavigator module) {
		super(module, true);
		setWindowSize(220, 260);
		setBackground(ColorDistribution.lightGreen);
		contents = getGraphicsArea();
		contents.setLayout(new BorderLayout());
		fileLinkCommand = new MesquiteCommand("fileLink", module);
		showPageCommand = new MesquiteCommand("showPage", module);
		nextCommand = new MesquiteCommand("next", module);
		prevCommand = new MesquiteCommand("prev", module);
		explanation= new MQTextArea("", 12, 12, TextArea.SCROLLBARS_VERTICAL_ONLY);
		contents.add("Center", explanation);
		explanation.setBackground(Color.white);
		controls = new MQPanel();
		buttons = new TitlePanel(this);
		controls.setLayout(new BorderLayout());
		controls.setBackground(ColorDistribution.lightGreen);


bs, page.Value...)
	}

	// Only return the LBs we actually care about
	result := lo.Filter(lbs, isClusterLoadBalancer)
	log.FromContext(ctx).Info("found load balancers of interest", "loadBalancerCount", len(result))
	return result, nil
}

func isClusterLoadBalancer(lb *armnetwork.LoadBalancer, _ int) bool {
	name := lo.FromPtr(lb.Name)
	return strings.EqualFold(name, SLBName) || strings.EqualFold(name, InternalSLBName) // TODO: Not currently supporting IPv6
}

func extractBackendAddressPools(lb *armnetwork.LoadBalancer, _ int) []*armnetwork.BackendAddressPool {
	if lb.Properties == nil {
		return nil
	}

	return lb.Properties.BackendAddressPools
}

func isBackendAddressPoolApplicable(backendPool *armnetwork.BackendAddressPool, _ int) bool {
	if backendPool.Properties == nil || backendPool.Name == nil {
		return false // shouldn't ever happen
	}

	name := *backendPool.Name
	// Ignore well-known named ipv6 pools for now
	if strings.EqualFold(name, SLBOutboundBackendPoolNameIPv6) || strings.EqualFold(name, SLBInboundBackendPoolNameIPv6) {
		return false
	}

	// Ignore IP-based pools, which are a thing in NodeIP mode. We don't need to assign these pools.
	// See isIPBasedBackendPool in RP.
	for _, backendAddress := range backendPool.Properties.LoadBalancerBackendAddresses {
		if backendAddress.Properties == nil || backendAddress.Properties.IPAddress == nil {
			continue
		}

		if *backendAddress.Properties.IPAddress != "" {
			return false
		}
	}

	return true
}
/*
Portions Copyright (c) Microsoft Corporation.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package imagefamily_test

import (
	"testing"

	"github.com/Azure/karpenter-provider-azure/pkg/apis/v1beta1"
	"github.com/Azure/karpenter-provider-azure/pkg/fake"
	"github.com/Azure/karpenter-provider-azure/pkg/providers/imagefamily"
	"github.com/Azure/karpenter-provider-azure/pkg/providers/imagefamily/bootstrap"
	"github.com/Azure/karpenter-provider-azure/pkg/providers/imagefamily/customscriptsbootstrap"
	"github.com/Azure/karpenter-provider-azure/pkg/providers/launchtemplate/parameters"
	"github.com/stretchr/testify/assert"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	karpv1 "sigs.k8s.io/karpenter/pkg/apis/v1"
	"sigs.k8s.io/karpenter/pkg/cloudprovider"
)

func TestAzureLinux_CustomScriptsNodeBootstrapping(t *testing.T) {
	azureLinux := imagefamily.AzureLinux{
		Options: &parameters.StaticParameters{
			ClusterName:                    "test-cluster",
			SubnetID:                       "/subscriptions/test/resourceGroups/test/providers/Microsoft.Network/virtualNetworks/vnet/subnets/subnet",
			Arch:                           karpv1.ArchitectureAmd64,
			SubscriptionID:                 "test-subscription",
			ResourceGroup:                  "test-rg",


pass/oscal-sdk-go/models"
)

const defaultActor = "tool"

type generateOpts struct {
	title        string
	importAP     string
	observations []oscalTypes.Observation
}

func (g *generateOpts) defaults() {
	g.title = models.SampleRequiredString
	g.importAP = models.SampleRequiredString
}

// GenerateOption defines an option to tune the behavior of the
// GenerateAssessmentPlan function.
type GenerateOption func(opts *generateOpts)

// WithTitle is a GenerateOption that sets the AssessmentPlan title
// in the metadata.
func WithTitle(title string) GenerateOption {
	return func(opts *generateOpts) {
		opts.title = title
	}
}

// WithImport is a GenerateOption that sets the AssessmentPlan
// ImportAP Href value.
func WithImport(importAP string) GenerateOption {
	return func(opts *generateOpts) {
		opts.importAP = importAP
	}
}

// WithObservations is a GenerateOption that adds pre-processed OSCAL Observations
// to Assessment Results for associated to Assessment Plan Activities.
func WithObservations(observations []oscalTypes.Observation) GenerateOption {
	return func(opts *generateOpts) {
		opts.observations = observations
	}
}

// GenerateAssessmentResults generates an AssessmentPlan for a set of Components and ImplementationSettings. The chosen inputs allow an Assessment Plan to be generated from
// a set of OSCAL ComponentDefinitions or a SystemSecurityPlan.
//
// If `WithImport` is not set, all input components are set as Components in the Local Definitions.
// If `WithObservations is not set, default behavior is to create a new, empty Observation for each activity step with the step.Title as the
// Observation title.
func GenerateAssessmentResults(plan oscalTypes.AssessmentPlan, opts ...GenerateOption) (*oscalTypes.AssessmentResults, error) {
	options := generateOpts{}
	options.defaults()
	for _, opt := range opts {
		opt(&options)
	}

	metadata := models.NewSampleMetadata()
	metadata.Title = options.title

	assessmentResults := &oscalTypes.AssessmentResults{
		UUID: uuid.NewUUID(),
		ImportAp: oscalTypes.ImportAp{
			Href: options.importAP,
		},
		Metadata: metadata,
		Results:  make([]oscalTypes.Result, 0), // Required field
	}

	if plan.Tasks == nil {
		return assessmentResults, fmt.Errorf("assessment plan tasks cannot be empty")
	}
	tasks := *plan.Tasks

	observationManager := newObservationManager(plan)
	if options.observations != nil {
		observationManager.load(options.observations)
	}

	activitiesByUUID := make(map[string]oscalTypes.Activity)
	if plan.LocalDefinitions != nil || plan.LocalDefinitions.Activities != nil {
		for _, activity := range *plan.LocalDefinitions.Activities {
			activitiesByUUID[activity.UUID] = activity
		}
	}

	// Process each task in the assessment plan
	for _, task := range tasks {
		result := oscalTypes.Result{
			Title:       fmt.Sprintf("Result For Task %q", task.Title),
			Description: fmt.Sprintf("OSCAL Assessment Result For Task %q", task.Title),
			Start:       time.Now(),
			UUID:        uuid.NewUUID(),
		}

		// Some initial checks before proceeding with the rest
		if task.AssociatedActivities == nil {
			assessmentResults.Results = append(assessmentResults.Results, result)
			continue
		}

		// Observations


private void lbl01MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl01MouseClicked
        elegirPosicion(0, 1);
    }//GEN-LAST:event_lbl01MouseClicked

    private void lbl02MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl02MouseClicked
        elegirPosicion(0, 2);
    }//GEN-LAST:event_lbl02MouseClicked

    private void lbl10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl10MouseClicked
        elegirPosicion(1, 0);
    }//GEN-LAST:event_lbl10MouseClicked

    private void lbl11MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl11MouseClicked
        elegirPosicion(1, 1);
    }//GEN-LAST:event_lbl11MouseClicked

    private void lbl12MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl12MouseClicked
        elegirPosicion(1, 2);
    }//GEN-LAST:event_lbl12MouseClicked

    private void lbl20MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl20MouseClicked
        elegirPosicion(2, 0);
    }//GEN-LAST:event_lbl20MouseClicked

    private void lbl21MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl21MouseClicked
        elegirPosicion(2, 1);
    }//GEN-LAST:event_lbl21MouseClicked

    private void lbl22MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbl22MouseClicked
        elegirPosicion(2, 2);
    }//GEN-LAST:event_lbl22MouseClicked

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        reset();
    }//GEN-LAST:event_btnResetActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormTicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormTicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormTicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormTicTacToe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.


(FLERR,"Incorrect args for pair coefficients" + utils::errorurl(21));

  const int ntypes = atom->ntypes;
  map_element2type(ntypes,arg+(narg-ntypes));

  // read EIM file

  deallocate_setfl();
  setfl = new Setfl();
  read_file(arg[2+nelements]);

  // set per-type atomic masses

  for (int i = 1; i <= ntypes; i++)
    for (int j = i; j <= ntypes; j++)
      if ((map[i] >= 0) && (map[j] >= 0))
        if (i == j) atom->set_mass(FLERR,i,setfl->mass[map[i]]);
}

/* ----------------------------------------------------------------------
   init specific to this pair style
------------------------------------------------------------------------- */

void PairEIM::init_style()
{
  // convert read-in file(s) to arrays and spline them

  file2array();
  array2spline();

  neighbor->add_request(this);
}

/* ----------------------------------------------------------------------
   init for one type pair i,j and corresponding j,i
------------------------------------------------------------------------- */

double PairEIM::init_one(int i, int j)
{
  cutmax = sqrt(cutforcesq[i][j]);
  return cutmax;
}

/* ----------------------------------------------------------------------
   read potential values from a set file
------------------------------------------------------------------------- */

void PairEIM::read_file(char *filename)
{
  int npair = nelements*(nelements+1)/2;
  setfl->ielement = new int[nelements];
  setfl->mass = new double[nelements];
  setfl->negativity = new double[nelements];
  setfl->ra = new double[nelements];
  setfl->ri = new double[nelements];
  setfl->Ec = new double[nelements];
  setfl->q0 = new double[nelements];
  setfl->rcutphiA = new double[npair];
  setfl->rcutphiR = new double[npair];
  setfl->Eb = new double[npair];
  setfl->r0 = new double[npair];
  setfl->alpha = new double[npair];
  setfl->beta = new double[npair];
  setfl->rcutq = new double[npair];
  setfl->Asigma = new double[npair];
  setfl->rq = new double[npair];
  setfl->rcutsigma = new double[npair];
  setfl->Ac = new double[npair];
  setfl->zeta = new double[npair];
  setfl->rs = new double[npair];
  setfl->tp = new int[npair];

  // read potential file
  if ( comm->me == 0) {
    EIMPotentialFileReader reader(lmp, filename, unit_convert_flag);

    reader.get_global(setfl);

    for (int i = 0; i < nelements; i++) {
      reader.get_element(setfl, i, elements[i]);
    }

    for (int i = 0; i < nelements; i++) {
      for (int j = i; j < nelements; j++) {
        int ij;
        if (i == j) ij = i;
        else if (i < j) ij = nelements*(i+1) - (i+1)*(i+2)/2 + j;
        else ij = nelements*(j


/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) Under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for Additional information regarding copyright ownership.
   The ASF licenses this file to You Under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed Under the License is distributed on an "AS Is" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations Under the License.
==================================================================== */

namespace NPOI.HSSF.Record
{

    using System;
    using System.Text;
    using NPOI.Util;

    using NPOI.HSSF.Record;

    /**
     * Specifies the window's zoom magnification.  If this record Isn't present then the windows zoom is 100%. see p384 Excel Dev Kit
     * NOTE: This source is automatically generated please do not modify this file.  Either subclass or
     *       Remove the record in src/records/definitions.

     * @author Andrew C. Oliver (acoliver at apache.org)
     */
    public class SCLRecord
       : StandardRecord
    {
        public const short sid = 0xa0;
        private short field_1_numerator;
        private short field_2_denominator;

        public SCLRecord()
        {

        }

        /**
         * Constructs a SCL record and Sets its fields appropriately.
         *
         * @param in the RecordInputstream to Read the record from
         */

        public SCLRecord(RecordInputStream in1)
        {

            field_1_numerator = in1.ReadShort();
            field_2_denominator = in1.ReadShort();
        }


    }

    override val supportedTopics: Set<NamedAggregate> = setOf(aggregateMetadata<Order, OrderState>().materialize())
    override val supportedType: Class<*>
        get() = Any::class.java

    override fun <M> supportMessage(message: M): Boolean
        where M : Message<*, Any>, M : NamedBoundedContext, M : NamedAggregate {
        return supportedTopics.any {
            it.isSameAggregateName(message)
        }
    }

    override val processor: Any
        get() = this

    override fun <A : Annotation> getAnnotation(annotationClass: Class<A>): A? {
        return null
    }

    override fun invoke(exchange: DomainEventExchange<Any>): Mono<Void> {
        if (log.isDebugEnabled) {
            log.debug(exchange.message.body.toString())
        }
        // write
        return Mono.empty()
    }

    override val functionKind: FunctionKind
        get() = FunctionKind.EVENT
    override val contextName: String
        get() = ExampleService.SERVICE_NAME
    override val name: String
        get() = OrderMessageFunction::class.java.simpleName
}
/*
 * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].
 * 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.
 */
@file:Suppress("unused")

package me.ahoo.wow.example.domain.order

import me.ahoo.wow.api.annotation.AggregateRoot
import me.ahoo.wow.api.annotation.AggregateRoute
import me.ahoo.wow.api.annotation.Name
import me.ahoo.wow.api.command.CommandMessage
import me.ahoo.wow.api.command.CommandResultAccessor
import me.ahoo.wow.command.ServerCommandExchange
import me.ahoo.wow.event.DomainEventStream
import me.ahoo.wow.example.api.order.AddressChanged
import me.ahoo.wow.example.api.order.ChangeAddress
import me.ahoo.wow.example.api.order.CreateOrder
import me.ahoo.wow.example.api.order.OrderCreated
import me.ahoo.wow.example.api.order.OrderItem
import me.ahoo.wow.example.api.order.OrderOverPaid
import me.ahoo.wow.example.api.order.OrderPaid
import me.ahoo.wow.example.api.order.OrderPayDuplicated
import me.ahoo.wow.example.api.order.OrderReceived
import me.ahoo.wow.example.api.order.OrderShipped
import me.ahoo.wow.example.api.order.PayOrder
import me.ahoo.wow.example.api.order.ReceiptOrder
import me.ahoo.wow.example.api.order.ShipOrder
import me.ahoo.wow.id.GlobalIdGenerator
import org.slf4j.LoggerFactory
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toMono

/**
 * Order Aggregate.
 *
 * 为了防止命令处理函数不小心修改聚合状态，可拆分成聚合状态类存放聚合状态.
 *
 * [me.ahoo.wow.api.an


        return notFound;
      case 500:
        return internalServerError;
      case 502:
        return badGateway;
      case 503:
        return serviceUnavailable;
      case 504:
        return gatewayTimeout;
    }
    return HttpStatus(code, "");
  }

  final int code;
  String reasonPhrase;

  HttpStatus reason(String reasonPhrase) {
    this.reasonPhrase = reasonPhrase;
    return this;
  }

  HttpStatus(this.code, this.reasonPhrase);

  bool isSuccessful() {
    return code >= 200 && code < 300;
  }

  @override
  String toString() {
    return '$code  $reasonPhrase';
  }
}
/*
 * Copyright 2023 Hongen Wang All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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.
 */

import 'dart:async';
import 'dart:collection';

/// A cache that expires entries after a given duration.
/// The cache uses a timer to remove entries after the specified duration.
/// @author WangHongEn
class ExpiringCache<K, V> {
  final Duration duration;
  final _cache = <K, V>{};
  final _expirationTimes = <K, Timer>{};

  ExpiringCache(this.duration);

  void set(K key, V value) {
    _expirationTimes[key]?.cancel();
    _cache[key] = value;
    _expirationTimes[key] = Timer(duration, () => remove(key));
  }

  void operator []=(K key, V value) => set(key, value);

  V? putIfAbsent(K key, V Function() ifAbsent) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    }
    final value = ifAbsent();
    set(key, value);
    return value;
  }

  V? get(K key) {
    return _cache[key];
  }

  V? operator [](K key) => get(key);

  void remove(K key) {
    _expirationTimes[key]?.cancel();
    _expirationTimes.remove(key);
    _cache.remove(key);
  }

  void clear() {
    for (var timer in _expirationTimes.values) {
      timer.cancel();
    }
    _expirationTimes.clear();
    _cache.clear();
  }
}

class LruCache<K, V> {
  final int capacity;
  final _cache = LinkedHashMap<K, V>();

  LruCache(this.capacity);

  V? get(K key) {
    if (!_cache.containsKey(key)) {
      return null;
    }

    // Move the accessed key to the end to show that it was recently used
    final value = _cache.remove(key);
    _cache[key] = value as V;
    return value;
  }

  V pubIfAbsent(K key, V Function() ifAbsent) {
    if (_cache.containsKey(key)) {
      return _cache[key]!;
    }

    final value = ifAbsent();
    set(key, value);
    return value;
  }

  void set(K key, V value) {
    if (_cache.containsKey(key)) {
      // Remove the old value
      _cache.remove(key);
    } else if (_cache.length == capacity) {
      // Remove the first key (least recently used)
      _cache.remove(_cache.keys.first);
    }
    _cache[key] = value;
  }

  void remove(K key) {
    _cache.remove(key);
  }

  int get length => _cache.length;

  void


WINDOWS_1255),
        144 => Some(encoding::all::WINDOWS_1256),
        145 => Some(encoding::all::WINDOWS_1256),
        146 => Some(encoding::all::WINDOWS_1256),
        152 => Some(encoding::all::WINDOWS_1257),
        153 => Some(encoding::all::WINDOWS_1257),
        154 => Some(encoding::all::WINDOWS_1257),
        155 => Some(encoding::all::WINDOWS_1257),
        156 => Some(encoding::all::WINDOWS_1257),
        157 => Some(encoding::all::WINDOWS_1257),
        158 => Some(encoding::all::WINDOWS_1257),
        159 => Some(encoding::all::WINDOWS_1257),
        160 => Some(encoding::all::WINDOWS_1257),
        183 => Some(encoding::all::WINDOWS_1252),
        184 => Some(encoding::all::WINDOWS_1252),
        185 => Some(encoding::all::WINDOWS_1252),
        186 => Some(encoding::all::WINDOWS_1252),
        // CP 932
        192 | 193 | 200 => Some(encoding::all::WINDOWS_31J),
        194 => Some(encoding::all::WINDOWS_949),
        195 => Some(encoding::all::WINDOWS_949),
        // CP950
        196 | 197 | 202 => Some(encoding::all::BIG5_2003),
        // CP936 (GB18030 is an extension of it with more chars), should be backwards-compatible)
        198 | 199 | 203 => Some(encoding::all::GB18030),
        201 => Some(encoding::all::WINDOWS_949),
        204 => Some(encoding::all::WINDOWS_874),
        205 => Some(encoding::all::WINDOWS_874),
        206 => Some(encoding::all::WINDOWS_874),
        210 => Some(encoding::all::WINDOWS_1252),
        211 => Some(encoding::all::WINDOWS_1252),
        212 => Some(encoding::all::WINDOWS_1252),
        213 => Some(encoding::all::WINDOWS_1252),
        214 => Some(encoding::all::WINDOWS_1252),
        215 => Some(encoding::all::WINDOWS_1252),
        216 => Some(encoding::all::WINDOWS_1252),
        217 => Some(encoding::all::WINDOWS_1252),
        _ => None,
    }
}

/* TODO
#[cfg(test)]
mod tests {
    use futures_state_stream::StateStream;
    use tokio::executor::current_thread;
    use crate::tests::new_connection;

    #[test]
    fn select_nvarchar_collation_test() {
        let c1 = new_connection();
        let query = c1.simple_query(
            "select cast(cast(N'cześć' as nvarchar(5)) collate Polish_CI_AI as varchar(5))",
        );
        let mut i = 0;
        {
            let future = query.for_each(|x| {
                let val: &str = x.get(0);
                assert_eq!(val, "cześć");
                i += 1;
                Ok(())
            });
            current_thread::block_on_all(future).unwrap();
        }
        assert_eq!(i, 1);
    }
}
*/
extern crate win_event_log;
#[macro_use]
#[cfg(feature = "xml")]
extern crate serde_derive;

use std::thread::sleep;
use std::time::Duration;
#[cfg(feature = "xml")]
use win_event_log::prelude::*;

#[cfg(feature = "xml")]
#[derive(Deserialize, Default, Debug)]
#[serde(rename_all = "PascalCase")]
struct Provider {
    pub name: Option<String>,
    pub guid: Option<String>,
}

#[cfg(feature = "xml")]
#[derive(Deserialize, Default, Debug)]
#[serde(rename_all = "PascalCase")]


c4f11418690a5ddf01246a0c80a43c70088b6183639dcfda4125bd113a8f49ee23ed306faac576c3fb0c1e256671d817fc2534a52f5b439f72e424de376f4c565cca82307dd9ef76da5b7c4eb7e085172e328807c02d011ffbf33785378d79dc266f6a5be6bb0e4a92eceebaeb1",
            "dc49fb549c9182fcd139853ac8aa9e11e8a3d1f03419110e0021c56f5779b10faf6fd53e0db337a64ea972441a53365f"
        )
    }
}
/*
 * Copyright 2022 Appmattus 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.
 */

@file:Suppress("ClassName")

package com.appmattus.crypto.internal

import com.appmattus.crypto.Algorithm
import com.appmattus.crypto.Digest
import com.appmattus.crypto.internal.core.sphlib.strtobin
import com.appmattus.crypto.internal.core.sphlib.testKatHex
import kotlin.test.Test
import kotlin.test.assertNotNull

class SkeinCoreTest : SkeinTest() {

    override fun digest(algorithm: Algorithm): Digest<*> = CoreDigest.create(algorithm)

    @Test
    fun hasImplementation() {
        assertNotNull(digest(Algorithm.Skein(1024, 1024)))
    }
}

/**
 * Test Skein implementation.
 */
abstract class SkeinTest {

    abstract fun digest(algorithm: Algorithm): Digest<*>

    // From https://github.com/pyca/pynacl/blob/main/tests/data/crypto-test-vectors-blake2-salt-personalization.txt
    @Test
    fun testSkein() {
        testSkeinKat(
            256,
            256,
            "",
            "CB41F1706CDE09651203C2D0EFBADDF8",
            "886E4EFEFC15F06AA298963971D7A253" +
                    "98FFFE5681C84DB39BD00851F64AE29D"
        )
        testSkeinKat(
            256,
            256,
            "D3090C72",
            "CB41F1706CDE09651203C2D0EFBADDF8" +
                    "47A0D315CB2E53FF8BAC41DA0002672E",


 int?,
  );

  @override
  Map<String, dynamic> toMap() => {
    'id': id,
    'job_id': jobId,
    'total_amount': totalAmount.minorUnits.toInt(),
    'created_date': createdDate.toIso8601String(),
    'modified_date': modifiedDate.toIso8601String(),
    'invoice_num': invoiceNum,
    'external_invoice_id': externalInvoiceId,
    'due_date': const LocalDateConverter().toJson(dueDate),
    'sent': sent ? 1 : 0,
    'billing_contact_id': billingContactId,
  };
}
//
// Generated file. Do not modify.
// Created by `barrel_create`
// barrel_create is sponsored by OnePub the dart private repository
// https://onepub.dev
//
export 'category.dart';
export 'check_list.dart';
export 'check_list_item.dart';
export 'contact.dart';
export 'customer.dart';
export 'entity.dart';
export 'invoice.dart';
export 'invoice_line.dart';
export 'invoice_line_group.dart';
export 'job.dart';
export 'job_activity.dart';
export 'job_status.dart';
export 'job_status_stage.dart';
export 'manufacturer.dart';
export 'message_template.dart';
export 'milestone.dart';
export 'operating_day.dart';
export 'operating_hours.dart';
export 'photo.dart';
export 'quote.dart';
export 'quote_line.dart';
export 'quote_line_group.dart';
export 'receipt.dart';
export 'site.dart';
export 'supplier.dart';
export 'system.dart';
export 'task.dart';
export 'task_check_list.dart';
export 'task_item.dart';
export 'task_item_type.dart';
export 'task_status.dart';
export 'time_entry.dart';
export 'todo.dart';
export 'tool.dart';
export 'version.dart';
export 'work_assignment.dart';
export 'work_assignment_task.dart';
/*
 Copyright © OnePub IP Pty Ltd. S. Brett Sutton.
 All Rights Reserved.

 Note: This software is licensed under the GNU General Public License,
         with the following exceptions:
   • Permitted for internal use within your own business or organization only.
   • Any external distribution, resale, or incorporation into products
      for third parties is strictly prohibited.

 See the full license on GitHub:
 https://github.com/bsutton/hmb/blob/main/LICENSE
*/

// lib/src/entity/receipt.dart
import 'package:money2/money2.dart';

import 'entity.dart';

class Receipt extends Entity<Receipt> {
  final DateTime receiptDate;
  final int jobId;
  final int supplierId;
  final Money totalExcludingTax; // stored as cents
  final Money tax; // stored as cents
  final Money totalIncludingTax; // stored as cents

  Receipt({
    required super.id,
    required this.receiptDate,
    required this.jobId,
    required this.supplierId,
    required this.totalExcludingTax,
    required this.tax,
    required this.totalIncludingTax,
    required super.createdDate,
    required super.modifiedDate,
  }) : super();

  Receipt.forInsert({
    required this.receiptDate,
    required this.jobId,
    required this.supplierId,
    required this.totalExcludingTax,
    required this.tax,
    required this.totalIncludingTax,
  }) : super.forInsert();

  Receipt copyWith({
    DateTime? receiptDate,
    int? jobId,
    int? supplierId,
    Money? totalExcludingTax,
    Money? tax,
    Money? totalIncludingTax,
  }) => Receipt(
    id: id,
    rece


 wall. This is equivalent to using
 *  a one-sided gradient when we get to do the divergence.
 *
 *  The stress on the wall is recorded for accounting purposes.
 *
 *****************************************************************************/

static __host__
int phi_force_wallx(cs_t * cs, wall_t * wall, fe_t * fe, double * fluxe,
			   double * fluxw) {

  int ic, jc, kc;
  int index, ia;
  int nsf;
  int nlocal[3];
  int mpisz[3];
  int mpicoords[3];

  double fw[3];         /* Net force on wall */
  double pth0[3][3];    /* Chemical stress at fluid point next to wall */

  assert(cs);
  assert(wall);
  assert(fe);
  assert(fe->func->stress);

  cs_nlocal(cs, nlocal);
  cs_nsites(cs, &nsf);
  cs_cartsz(cs, mpisz);
  cs_cart_coords(cs, mpicoords);

  fw[X] = 0.0;
  fw[Y] = 0.0;
  fw[Z] = 0.0;

  if (mpicoords[X] == 0) {
    ic = 1;

    for (jc = 1; jc <= nlocal[Y]; jc++) {
      for (kc = 1; kc <= nlocal[Z]; kc++) {

	index = cs_index(cs, ic, jc, kc);
	fe->func->stress(fe, index, pth0);

	for (ia = 0; ia < 3; ia++) {
	  fluxw[addr_rank1(nsf,3,index,ia)] = pth0[ia][X];
	  fw[ia] -= pth0[ia][X];
	}
      }
    }
  }

  if (mpicoords[X] == mpisz[X] - 1) {
    ic = nlocal[X];

    for (jc = 1; jc <= nlocal[Y]; jc++) {
      for (kc = 1; kc <= nlocal[Z]; kc++) {

	index = cs_index(cs, ic, jc, kc);
	fe->func->stress(fe, index, pth0);

	for (ia = 0; ia < 3; ia++) {
	  fluxe[addr_rank1(nsf,3,index,ia)] = pth0[ia][X];
	  fw[ia] += pth0[ia][X];
	}
      }
    }
  }

  wall_momentum_add(wall, fw);

  return 0;
}


         getDriver();
        }
    }

    public static void switchToDriver(String driverName) {
        if (DRIVERS.has(driverName)) {
            DRIVER.name = driverName;
        }
        else {
            throw runtimeException("Can't switch to WebDriver '%s'. This Driver name not registered", driverName);
        }
    }

    public static void close() {
        for (Pair<String, WebDriver> pair : getRunDrivers()) {
            closeDriver(pair.value);
        }
        getRunDrivers().clear();
    }

    private static void closeDriver(WebDriver driver) {
        try {
            driver.quit();
        } catch (Exception ignore) { }
    }

    public static void quit() {
        close();
    }
}
package com.epam.jdi.light.elements.composite;

import com.epam.jdi.light.common.FormFilters;
import com.epam.jdi.light.common.JDIAction;
import com.epam.jdi.light.common.JDebug;
import com.epam.jdi.light.elements.common.UIElement;
import com.epam.jdi.light.elements.interfaces.base.HasValue;
import com.epam.jdi.light.elements.interfaces.base.IClickable;
import com.epam.jdi.light.elements.interfaces.base.ICoreElement;
import com.epam.jdi.light.elements.interfaces.base.SetValue;
import com.epam.jdi.light.elements.pageobjects.annotations.MapToField;
import com.jdiai.tools.func.JAction4;
import com.jdiai.tools.func.JFunc1;
import com.jdiai.tools.func.JFunc3;
import com.jdiai.tools.map.MapArray;
import com.jdiai.tools.pairs.Pair;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import static com.epam.jdi.light.common.Exceptions.exception;
import static com.epam.jdi.light.common.Exceptions.runtimeException;
import static com.epam.jdi.light.common.FormFilters.*;
import static com.epam.jdi.light.common.UIUtils.GET_BUTTON;
import static com.epam.jdi.light.common.UIUtils.getMapFromObject;
import static com.epam.jdi.light.elements.pageobjects.annotations.WebAnnotationsUtil.getElementName;
import static com.epam.jdi.light.elements.pageobjects.annotations.WebAnnotationsUtil.hasAnnotation;
import static com.epam.jdi.light.settings.JDISettings.ELEMENT;
import static com.epam.jdi.light.settings.WebSettings.logger;
import static com.jdiai.tools.LinqUtils.first;
import static com.jdiai.tools.PrintUtils.print;
import static com.jdiai.tools.ReflectionUtils.*;
import static com.jdiai.tools.StringUtils.LINE_BREAK;
import static com.jdiai.tools.StringUtils.format;

/**
 * Created by Roman Iovlev on 29.03.2018
 * Email: roman.iovlev.jdi@gmail.com; Skype: roman.iovlev
 */
public class Form<T> extends Section {
    public static JAction4<Field, Object, Object, String> FILL_ACTION = (field, element, parent, setValue)
        -> ((SetValue) element).setValue(setValue);

    public static JFunc3<Field, Object, Object, String> GET_ACTION = (field, element, parent)
        -> ((HasValue) element).getValue().trim();

    public static JFunc1<Field, String> MAP_FORM = field -> {
        if (hasAnnotation(field, MapToField.class)) {
            return field.getAnnotation(MapToField.class).value();
        }
        return field.getType().isAnnotationPresent(MapToField.class)
            ? field.getType().getAnnotation(MapToField.class).value()
            : getElementName(field);
    };

    @JDebug
    public void fillAction(Field field, Object element, Object parent, String setValue) {
        logger.debug("Fill element '%s


cript>
    <![endif]-->

    <link rel="shortcut icon" href="../assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">

Bootstrap dropdown

Action

Another action

Something else here

Separated link

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Bootstrap, from Twitter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="../assets/css/bootstrap.css" rel="stylesheet">
    <link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">

    <link rel="shortcut icon" href="../assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon


// var tmp = table[i].created[j].toLowerCase().replace(/\(.*\)/g,'').replace(/ /g,'_');
				var tmp = table[i].created[j].toLowerCase().replace(/[\(\)]/g,'').replace(/ /g,'_');
				if(tmp){
					if(!categories[tmp]) categories[tmp] = {'name':table[i].created[j]};
					table[i].created[j] = tmp;
				}
			}
		}

		// Add toggles for each category
		$('table.periodic').before('

Formed in:

');
		for(c in categories){
			$('.key').append('

'+categories[c].name+'

');
			toggles.create($('#'+c),c,{
				"off": {"label":"off","checked": true },
				"on": { "label":"on" }
			});
		}
		$('.key').prepend('

Key:

Essential to life

');
	//	$('.key').append('

Formed
<form>

</form>
');
		$(document).on('click','.keylabel',function(){ toggles.toggle($(this).parent().attr('id')) });

		// Switch the Big Bang on
		toggles.change('big_bang','on');

	}

	$('.noscript').remove();

	// Load the files
	loadCSV('data/element_origin.csv',parseFile,{});

	function updatePeriodicTable(){
		var td,ok,i,j,c;
		for(c in categories) categories[c].val = toggles.val(c);

		for(i = 0; i < table.length; i++){
			if(!table[i].td) table[i].td = $('#'+table[i].symbol).parent();
			ok = false;
			for(j = 0; j < table[i].created.length; j++){
				if(table[i].created[j] && categories[table[i].created[j]].val=="on"){
					ok = true;
					break;
				}
			}
			if(ok) table[i].td.addClass('formed');
			else table[i].td.removeClass('formed')
		}
	}
})
r(function(){

	// Define array to hold stars
	var stars = new Array();
	var spectral = {"O5": "#9bb0ff","O6": "#a2b8ff","O7": "#9db1ff","O8": "#9db1ff","O9": "#9ab2ff","O9.5": "#a4baff"