for default processing.
    if (_state == _stateProbingLength) {
      _completeError(e, s);
    } else {
      _resumableController.addError(e, s);
    }
  }

  void _completeError(Object e, StackTrace s) {
    if (_state != _stateLengthKnown) {
      // Always cancel subscription on error.
      _subscription.cancel();
    }
    _doneCompleter.completeError(e, s);
  }

  void _startNormalUpload(Stream<List<int>> stream, int? length) async {
    var contentType = _object.contentType ?? 'application/octet-stream';
    var media = storage_api.Media(stream, length, contentType: contentType);
    try {
      final response = await _api.objects.insert(
        _object,
        _bucketName,
        name: _objectName,
        predefinedAcl: _predefinedAcl,
        uploadMedia: media,
        uploadOptions: storage_api.UploadOptions.defaultOptions,
      );
      _doneCompleter.complete(_ObjectInfoImpl(response));
    } catch (e, st) {
      _completeError(e, st);
    }
  }

  void _startResumableUpload(Stream<List<int>> stream, int? length) {
    var contentType = _object.contentType ?? 'application/octet-stream';
    var media = storage_api.Media(stream, length, contentType: contentType);
    _api.objects
        .insert(_object, _bucketName,
            name: _objectName,
            predefinedAcl: _predefinedAcl,
            uploadMedia: media,
            uploadOptions: storage_api.UploadOptions.resumable)
        .then((response) {
      _doneCompleter.complete(_ObjectInfoImpl(response));
    }, onError: _completeError);
  }
}
// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';

import 'package:gcloud/service_scope.dart' as ss;

class LogLevel {
  static const LogLevel CRITICAL = LogLevel._('Critical', 4);
  static const LogLevel ERROR = LogLevel._('Error', 3);
  static const LogLevel WARNING = LogLevel._('Warning', 2);
  static const LogLevel INFO = LogLevel._('Info', 1);
  static const LogLevel DEBUG = LogLevel._('Debug', 0);

  final String name;
  final int level;

  const LogLevel._(this.name, this.level);

  @override
  String toString() => name;
}

abstract class Logging {
  void critical(String string, {DateTime timestamp});
  void error(String string, {DateTime timestamp});
  void warning(String string, {DateTime timestamp});
  void info(String string, {DateTime timestamp});
  void debug(String string, {DateTime timestamp});

  /// Report an error, may print the error to log or report it to stackdriver
  /// error reporting if [stackTrace] is given and running on appengine, not
  /// localhost.
  ///
  /// Notice that Stackdriver Error Reporting only collects errors if [level] is
  /// either [LogLevel.ERROR] or [LogLevel.CRITICAL].
  void reportError(
    LogLevel level,
    Object error,
    StackTrace stackTrace, {
    DateTime timestamp,
  });

  void log(
    LogLevel level,
    String message, {
    DateTime timestamp,
  });

  Future<void> flush();
}

/// Register a new [Logging] object.
///
/// Calling this outside of a service scope or calling it more than once inside
/// the same service scope will result in an error.
///
/// See the `package:gcloud/service_scope.dart` library for more information.
void registerLoggingService(Logging service) {
  ss.register(#appengine.logging, service);
}

/// The logging service.
///
/// Request handlers will be run inside a service


vice to bind address
  nrfWriteReg( REG_RX_ADDR_P0, (char *) rf_addr_bind, 5);
  nrfWriteReg( REG_TX_ADDR, (char *) rf_addr_bind, 5);

  // Power up
  nrfWrite1Reg(REG_CONFIG, (NRF24_EN_CRC | NRF24_PWR_UP | NRF24_PRIM_RX));

  while(!bind) {

    // Wait until we receive a data packet, flashing alternately
		flashtime = micros()/1000;
    while(!(nrfGetStatus() & 0x40))  bindflasher(500);

      // TX sends mutliple packets, so keep reading the FIFO
      // until there is no more data.
      while (!(nrfRead1Reg(REG_FIFO_STATUS) & 0x01)) {

        // Bind packet is nine bytes on pipe zero
        if(nrfRxLength(0) == PAYLOADSIZE) {

          // Get the packet
          nrfReadRX(rxbuffer, PAYLOADSIZE);
        }
      }

      // Flush buffer and clear status
      nrfFlushRx();
      nrfWrite1Reg(REG_STATUS, NRF_STATUS_CLEAR);

        // Configure the command address
        rf_addr_cmnd[0] = rxbuffer[0];
        rf_addr_cmnd[1] = rxbuffer[1];
        rf_addr_cmnd[2] = rxbuffer[2];
        rf_addr_cmnd[3] = rxbuffer[3];
        rf_addr_cmnd[4] = 0xC1;

        // Set to TX command address
        nrfWriteReg( REG_RX_ADDR_P0,  rf_addr_cmnd, 5);
        nrfWriteReg( REG_TX_ADDR, rf_addr_cmnd, 5);

        // Flush buffer and clear status
        nrfFlushRx();
        nrfWrite1Reg(REG_STATUS, NRF_STATUS_CLEAR);

        // Wait until we receive data on the command address
				flashtime = micros()/1000;
        while(!(nrfGetStatus() & 0x40)) bindflasher(250);

        bind = true;

				// Turn of LEDs
				GPIO_WriteBit(LED1_PORT, LED1_BIT, LEDoff);
        GPIO_WriteBit(LED2_PORT, LED2_BIT, LEDoff);

      }

}

// Place RF command data in RXcommand variable, process AUX commands
void get_RFRXDatas() {

  // If a new packet exists in the buffer
  if(nrfGetStatus() & 0x40)
  {
    // Read the latest command to the buffer
    nrfReadRX(rxbuffer, PAYLOADSIZE);

    // Flush the buffer and clear interrupt
    nrfFlushRx();
    nrfWrite1Reg(REG_STATUS, NRF_STATUS_CLEAR);

    // FC order: T   A   E   R   A1   A2
    // RF order: T    R   ?   E   A     Et    At   F   ?

    // PPM firmware expects a range of 1000, TX range is 0xFF (max rate), mid-stick is 0x40,
    // BS twice leads to a range of 1020, which is close enough for now.
    RXcommands[0] = constrain((((int16_t)rxbuffer[0])<<2), 0, 1000);
    RXcommands[1] = constrain((((int16_t)rxbuffer[4])<<2) - 512, -500, 500);
    RXcommands[2] = constrain((((int16_t)rxbuffer[3])<<2) - 512, -500, 500);
    RXcommands[3] = constrain((((int16_t)rxbuffer[1])<<2) - 512, -500, 500);

    // Forward flip sets AUX1 high, backwards flip sets AUX1 low
    if( rxbuffer[7] & 0x0F ) {
      if((uint8_t) rxbuffer[3] > 0xF0) RXcommands[4] = 500;
      if((uint8_t) rxbuffer[3] < 0x0F) RXcommands[4] = -500;
    }

    // Since data has been received, reset failsafe counter
    failsave = 0;
  }

}

void bindflasher(uint32_t rate) {

	uint32_t millitime = micros()/1000;

	 if(millitime-flashtime > rate)
      {
        flashtime = millitime;
        switch(flashstate)
        {

          case true:
            GPIO_WriteBit(LED1_PORT, LED1_BIT, LEDon);
            GPIO_WriteBit(LED2_PORT, LED2_BIT, LEDoff);
            flashstate = false;
            break;

          case false:
            GPIO_WriteBit(LED1_PORT, LED1_BIT, LEDoff);
            GPIO_WriteBit(LED2_PORT, LED2_BIT, LEDon);
            flashstate = true;
            break;

        }
      }

}


hen using https://vapolia.eu/Vapolia.SegmentedViews instead of clr-namespace:Vapolia.SegmentedViews;assembly=Vapolia.SegmentedViews
    /// </summary>
    public static Vapolia.SegmentedViews.Segment InternalSegment;

    /// <summary>
    /// Add Maui handlers for this control
    /// </summary>
    public static MauiAppBuilder UseSegmentedView(this MauiAppBuilder builder)
    {
        //?! Try to fix ns not found for Segment (but not SegmentedView)
        InternalSegment = new ();

        builder.ConfigureMauiHandlers(handlers =>
        {
#if ANDROID
            handlers.TryAddHandler<SegmentedView, SegmentedViewHandler>();
#elif IOS || MACCATALYST
            handlers.TryAddHandler<SegmentedView, SegmentedViewHandler>();
#elif WINDOWS
            handlers.TryAddHandler<SegmentedView, SegmentedViewHandler>();
#endif
        });

        return builder;
    }
}


 so operator== and so forth work.
    if (value < 1) {
        value = 1;
    } else if (value > 7) {
        value = 7;
    }
    if (fMinimalDaysInFirstWeek != value) {
        fMinimalDaysInFirstWeek = value;
        fAreFieldsSet = false;
    }
}

// -------------------------------------

uint8_t
Calendar::getMinimalDaysInFirstWeek() const
{
    return fMinimalDaysInFirstWeek;
}

// -------------------------------------
// weekend functions, just dummy implementations for now (for API freeze)

UCalendarWeekdayType
Calendar::getDayOfWeekType(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const
{
    if (U_FAILURE(status)) {
        return UCAL_WEEKDAY;
    }
    if (dayOfWeek < UCAL_SUNDAY || dayOfWeek > UCAL_SATURDAY) {
        status = U_ILLEGAL_ARGUMENT_ERROR;
        return UCAL_WEEKDAY;
    }
    if (fWeekendOnset == fWeekendCease) {
        if (dayOfWeek != fWeekendOnset)
            return UCAL_WEEKDAY;
        return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET;
    }
    if (fWeekendOnset < fWeekendCease) {
        if (dayOfWeek < fWeekendOnset || dayOfWeek > fWeekendCease) {
            return UCAL_WEEKDAY;
        }
    } else {
        if (dayOfWeek > fWeekendCease && dayOfWeek < fWeekendOnset) {
            return UCAL_WEEKDAY;
        }
    }
    if (dayOfWeek == fWeekendOnset) {
        return (fWeekendOnsetMillis == 0) ? UCAL_WEEKEND : UCAL_WEEKEND_ONSET;
    }
    if (dayOfWeek == fWeekendCease) {
        return (fWeekendCeaseMillis >= 86400000) ? UCAL_WEEKEND : UCAL_WEEKEND_CEASE;
    }
    return UCAL_WEEKEND;
}

int32_t
Calendar::getWeekendTransition(UCalendarDaysOfWeek dayOfWeek, UErrorCode &status) const
{
    if (U_FAILURE(status)) {
        return 0;
    }
    if (dayOfWeek == fWeekendOnset) {
        return fWeekendOnsetMillis;
    } else if (dayOfWeek == fWeekendCease) {
        return fWeekendCeaseMillis;
    }
    status = U_ILLEGAL_ARGUMENT_ERROR;
    return 0;
}

UBool
Calendar::isWeekend(UDate date, UErrorCode &status) const
{
    if (U_FAILURE(status)) {
        return false;
    }
    // clone the calendar so we don't mess with the real one.
    Calendar *work = this->clone();
    if (work == nullptr) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return false;
    }
    UBool result = false;
    work->setTime(date, status);
    if (U_SUCCESS(status)) {
        result = work->isWeekend();
    }
    delete work;
    return result;
}

UBool
Calendar::isWeekend() const
{
    UErrorCode status = U_ZERO_ERROR;
    UCalendarDaysOfWeek dayOfWeek = (UCalendarDaysOfWeek)get(UCAL_DAY_OF_WEEK, status);
    UCalendarWeekdayType dayType = getDayOfWeekType(dayOfWeek, status);
    if (U_SUCCESS(status)) {
        switch (dayType) {
            case UCAL_WEEKDAY:
                return false;
            case UCAL_WEEKEND:
                return true;
            case UCAL_WEEKEND_ONSET:
            case UCAL_WEEKEND_CEASE:
                // Use internalGet() because the above call to get() populated all fields.
                {
                    int32_t millisInDay = internalGet(UCAL_MILLISECONDS_IN_DAY);
                    int32_t transitionMillis = getWeekendTransition(dayOfWeek, status);
                    if (U_SUCCESS(status)) {


GitHub issue

Addresses [CWG2320], which was caused by resolving [CWG2039], see Richard Smith’s email regarding this approach.

Notes 2020-02-12

Notes 2020-09-30

Notes 2020-10-28

Highlight: allow conversions from integral types to type <c- b>bool</c-> in <c- k>static_assert</c-> and <c- k>if</c-> <c- k>constexpr</c->-statements.

🗳 Poll: Forward P1401R4 "Narrowing contextual conversions to <c- b>bool</c->" to Core.

Poll votes:

      SF
      F
      N
      A
      SA

      13
      13
      3
      0
      0

Poll outcome: ✅ consensus.

Salient comments:

Increases consistency.

The decision this paper is undoing is yet another example of an attempt to move the language in a particular direction, but without a complete migration plan. These incomplete migrations make the language incoherent and frustrating.

I wish we could go the other direction and disallow any conversions to bool everywhere (including from integer and pointer types, regardless of context, allowing only user-defined conversions), but there’s no way we’ll ever get there from here.  C++ is a language that thinks non-boolean types have boolean properties, and we shouldn’t make exceptions to that based on context.

5.11. P1393R0 A General Property Customization Mechanism

[P1393R0]

GitHub issue

Notes 2020-05-21

Highlight: "properties" are a customization mechanism at the center of [P0443R14] executors. The proposed approach is li


 AlphaComposite.getInstance(3, 0.41111f * origAlpha)
// _0_0_10_9_0
if (generalPath == null) {
   generalPath = GeneralPath()
} else {
   generalPath!!.reset()
}
generalPath!!.moveTo(31.009f, 9.381f)
generalPath!!.lineTo(31.009f, 12.620999f)
generalPath!!.curveTo(31.009f, 12.620999f, 31.621f, 12.273f, 32.0f, 12.259999f)
generalPath!!.lineTo(32.0f, 8.999999f)
generalPath!!.curveTo(31.518f, 9.069499f, 31.009f, 9.380999f, 31.009f, 9.380999f)
generalPath!!.closePath()
shape = generalPath
paint = colorFilter?.filter(Color(230, 231, 230, 255)) ?: Color(230, 231, 230, 255)
g.paint = paint
g.fill(shape)
g.composite = AlphaComposite.getInstance(3, 1.0f * origAlpha)
// _0_0_10_9_1
if (generalPath == null) {
   generalPath = GeneralPath()
} else {
   generalPath!!.reset()
}
generalPath!!.moveTo(33.009f, 8.76f)
generalPath!!.lineTo(33.009f, 12.0f)
generalPath!!.curveTo(33.009f, 12.0f, 33.621f, 11.917f, 34.0f, 11.904f)
generalPath!!.lineTo(34.0f, 8.588901f)
generalPath!!.curveTo(33.488f, 8.6147f, 33.009f, 8.76f, 33.009f, 8.76f)
generalPath!!.closePath()
shape = generalPath
paint = colorFilter?.filter(Color(230, 231, 230, 255)) ?: Color(230, 231, 230, 255)
g.paint = paint
g.fill(shape)
g.composite = AlphaComposite.getInstance(3, 0.44444f * origAlpha)
// _0_0_10_9_2
if (generalPath == null) {
   generalPath = GeneralPath()
} else {
   generalPath!!.reset()
}
generalPath!!.moveTo(35.009f, 8.5611f)
generalPath!!.lineTo(35.009f, 11.856f)
generalPath!!.curveTo(35.009f, 11.856f, 35.565f, 11.851f, 36.0f, 11.871f)
generalPath!!.lineTo(36.0f, 8.5337f)
generalPath!!.curveTo(35.499f, 8.4821f, 35.009f, 8.5611f, 35.009f, 8.5611f)
generalPath!!.closePath()
shape = generalPath
paint = colorFilter?.filter(Color(230, 231, 230, 255)) ?: Color(230, 231, 230, 255)
g.paint = paint
g.fill(shape)

}

	private fun innerPaint(g : Graphics2D) {
        var origAlpha = 1.0f
        val origComposite = g.composite
        if (origComposite is AlphaComposite) {
            if (origComposite.rule == AlphaComposite.SRC_OVER) {
                origAlpha = origComposite.alpha
            }
        }

	    _paint0(g, origAlpha)

	    shape = null
	    generalPath = null
	    paint = null
	    stroke = null
	    clip = null
	}

    companion object {
        /**
         * Returns the X of the bounding box of the original SVG image.
         *
         * @return The X of the bounding box of the original SVG image.
         */
        fun getOrigX(): Double {
            return 0.0
        }

        /**
         * Returns the Y of the bounding box of the original SVG image.
         *
         * @return The Y of the bounding box of the original SVG image.
         */
        fun getOrigY(): Double {
            return 0.29957765340805054
        }

        /**
         * Returns the width of the bounding box of the original SVG image.
         *
         * @return The width of the bounding box of the original SVG image.
         */
        fun getOrigWidth(): Double {
            return 48.0
        }

        /**
         * Returns the height of the bounding box of the original SVG


(451);
				match(XOR);
				setState(452);
				and_expression();
				}
				}
				setState(457);
				_errHandler.sync(this);
				_la = _input.LA(1);
			}
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			_errHandler.reportError(this, re);
			_errHandler.recover(this, re);
		}
		finally {
			exitRule();
		}
		return _localctx;
	}

	@SuppressWarnings("CheckReturnValue")
	public static class And_expressionContext extends ParserRuleContext {
		public List<Equality_expressionContext> equality_expression() {
			return getRuleContexts(Equality_expressionContext.class);
		}
		public Equality_expressionContext equality_expression(int i) {
			return getRuleContext(Equality_expressionContext.class,i);
		}
		public List<TerminalNode> AND() { return getTokens(lab6Parser.AND); }
		public TerminalNode AND(int i) {
			return getToken(lab6Parser.AND, i);
		}
		public And_expressionContext(ParserRuleContext parent, int invokingState) {
			super(parent, invokingState);
		}
		@Override public int getRuleIndex() { return RULE_and_expression; }
		@Override
		public void enterRule(ParseTreeListener listener) {
			if ( listener instanceof lab6Listener ) ((lab6Listener)listener).enterAnd_expression(this);
		}
		@Override
		public void exitRule(ParseTreeListener listener) {
			if ( listener instanceof lab6Listener ) ((lab6Listener)listener).exitAnd_expression(this);
		}
		@Override
		public <T> T accept(ParseTreeVisitor<? extends T> visitor) {
			if ( visitor instanceof lab6Visitor ) return ((lab6Visitor<? extends T>)visitor).visitAnd_expression(this);
			else return visitor.visitChildren(this);
		}
	}

	public final And_expressionContext and_expression() throws RecognitionException {
		And_expressionContext _localctx = new And_expressionContext(_ctx, getState());
		enterRule(_localctx, 78, RULE_and_expression);
		int _la;
		try {
			enterOuterAlt(_localctx, 1);
			{
			setState(458);
			equality_expression();
			setState(463);
			_errHandler.sync(this);
			_la = _input.LA(1);
			while (_la==AND) {
				{
				{
				setState(459);
				match(AND);
				setState(460);
				equality_expression();
				}
				}
				setState(465);
				_errHandler.sync(this);
				_la = _input.LA(1);
			}
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			_errHandler.reportError(this, re);
			_errHandler.recover(this, re);
		}
		finally {
			exitRule();
		}
		return _localctx;
	}

	@SuppressWarnings("CheckReturnValue")
	public static class Equality_expressionContext extends ParserRuleContext {
		public List<Relational_expressionContext> relational_expression() {
			return getRuleContexts(Relational_expressionContext.class);
		}
		public Relational_expressionContext relational_expression(int i) {
			return getRuleContext(Relational_expressionContext.class,i);
		}
		public List<TerminalNode> EQEQ() { return getTokens(lab6Parser.EQEQ); }
		public TerminalNode EQEQ(int i) {
			return getToken(lab6Parser.EQEQ, i);
		}
		public List<TerminalNode> NEQ() { return getTokens(lab6Parser.NEQ); }
		public TerminalNode NEQ(int i) {
			return getToken(lab6Parser.NEQ, i);
		}
		public Equality_expressionContext


 height - 1; // Values between 1-8
    var sizeDec = widthDec + heightDec;
    /*
    * @todo I would suggest replacing the return line by the code below since
    *         `String.fromCharCode()` can generate undesirable results.
    *
    * return Buffer.from('1d21' + numToHexString(sizeDec), 'hex');
    * */
    return '\x1d\x21' + String.fromCharCode(sizeDec);
  },

  TXT_HEIGHT: {
    1: '\x00',
    2: '\x01',
    3: '\x02',
    4: '\x03',
    5: '\x04',
    6: '\x05',
    7: '\x06',
    8: '\x07'
  },
  TXT_WIDTH: {
    1: '\x00',
    2: '\x10',
    3: '\x20',
    4: '\x30',
    5: '\x40',
    6: '\x50',
    7: '\x60',
    8: '\x70'
  },

  TXT_UNDERL_OFF: '\x1b\x2d\x00', // Underline font OFF
  TXT_UNDERL_ON: '\x1b\x2d\x01', // Underline font 1-dot ON
  TXT_UNDERL2_ON: '\x1b\x2d\x02', // Underline font 2-dot ON
  TXT_BOLD_OFF: '\x1b\x45\x00', // Bold font OFF
  TXT_BOLD_ON: '\x1b\x45\x01', // Bold font ON
  TXT_ITALIC_OFF: '\x1b\x35', // Italic font ON
  TXT_ITALIC_ON: '\x1b\x34', // Italic font ON

  TXT_FONT_A: '\x1b\x4d\x00', // Font type A
  TXT_FONT_B: '\x1b\x4d\x01', // Font type B
  TXT_FONT_C: '\x1b\x4d\x02', // Font type C

  TXT_ALIGN_LT: '\x1b\x61\x00', // Left justification
  TXT_ALIGN_CT: '\x1b\x61\x01', // Centering
  TXT_ALIGN_RT: '\x1b\x61\x02', // Right justification

  STAR_TXT_ALIGN_LA: '\x1B\x1D\x61\x00', // STAR printer - Left alignment
  STAR_TXT_ALIGN_CA: '\x1B\x1D\x61\x01', // STAR printer - Center alignment
  STAR_TXT_ALIGN_RA: '\x1B\x1D\x61\x02', // STAR printer - Right alignment
};

/**
 * Qsprinter-compatible
 * Added by Attawit Kittikrairit
 * [MODEL Model-specific commands]
 * @type {Object}
 */
export const MODEL = {
  QSPRINTER: {
    BARCODE_MODE: {
      ON: '\x1d\x45\x43\x01', // Barcode mode on
      OFF: '\x1d\x45\x43\x00', // Barcode mode off
    },
    BARCODE_HEIGHT_DEFAULT: '\x1d\x68\xA2', // Barcode height default:162
    CODE2D_FORMAT: {
      PIXEL_SIZE: {
        CMD: '\x1b\x23\x23\x51\x50\x49\x58',
        MIN: 1,
        MAX: 24,
        DEFAULT: 12,
      },
      VERSION: {
        CMD: '\x1d\x28\x6b\x03\x00\x31\x43',
        MIN: 1,
        MAX: 16,
        DEFAULT: 3,
      },
      LEVEL: {
        CMD: '\x1d\x28\x6b\x03\x00\x31\x45',
        OPTIONS: {
          L: 48,
          M: 49,
          Q: 50,
          H: 51,
        }


r otherwise describe an
empty grid rather than displaying zero rows, which often looks unattractive.

#### Footers
At the bottom of the grid is an optional footer.  You can use this to display
static information (such as string literals) or aggregate information such as
sums, averages, etc.

#### Show More
Sometimes your grid is only showing one or more pages of data.  When the Show More
Button is enabled, a button appears at the bottom of the grid that when clicked
should execute code that fetches more data from the server to add in a new page
of data to the grid.

#### Loading Indicator
You can use the loading indicator to indicate to the user that the grid has no
content yet because you are making a request to a server, for example.  Similar
to the empty state, it completely takes over the content of the grid, and also
suppresses any footers.
            `);

            mainPanel.add(controlPanel);
            mainPanel.add(this.grid);
            mainPanel.add(buttons);
            mainPanel.add(summary);

            this.populate();

            this.content = mainPanel;
        }

        clear() {
            this.grid.clear();
        }

        populate() {
            this.grid.add(new TestRow("Kirk", "Woll", 39));
            this.grid.add(new TestRow("Andrew", "Simpkins", 39));
            this.grid.add(new TestRow("Carl", "Woll", 56));
            this.grid.add(new TestRow("Lara", "Robinette", 49));
        }
    }

    class TestRow {
        constructor(public firstName: string, public lastName: string, public age: number) {
        }
    }
}
import { Injectable } from '@angular/core';
import { DateAdapter } from '@angular/material/core';
import { Title } from '@angular/platform-browser';
import { ActivatedRouteSnapshot, CanActivate, NavigationEnd, Router, UrlSegment } from '@angular/router';

import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';
import { TranslateService } from '@ngx-translate/core';

interface Language {
    code: string;
    name: string;
}

// Define here new languages...
// IMPORTANT: if you add new languages here, make sure to also add register them at the top of app.module.ts
export const languages: Language[] = [
    { code: 'en', name: 'English' },
    { code: 'de', name: 'Deutsch' }
];

/**
 * Custom url matcher to manage language prefixes.
 * If url starts with a valid language code, consume the language part and continue with routing.
 * Otherwise, returns null, so route doesn't match and default route is used (see routing module).
 */
const langRegEx = new RegExp('^(' + languages.map(e => e.code).join('|') + ')$'); // class attr so mapping is only done once
export function LanguageUrlMatcher(url: UrlSegment[]): { consumed: UrlSegment[] } | null {
    return url.length && url[0].path.match(langRegEx) ? { consumed: url.slice(0, 1) } : null;
}

@Injectable({
    providedIn: 'root'
})
export class LanguageService implements CanActivate {
    private title_string = _('OpenSlides: das digitale Antrags- und Versammlungssystem');

    public constructor(
        protected translate: TranslateService,
        private router: Router,
        private title: Title,
        private dateAdapter: DateAdapter<any>
    ) {
        this.translate.addLangs(languages.map(e => e.code));
        this.translate.setDefaultLang('de'); // german is default language
        this.dateAdapter.setLocale('de');

        // set language after each page load
        this.router.events.subscribe(event => {
            if (event instanceof NavigationEnd) {
                const lang = this.getCurrentLanguage();
                this.translate.use(lang).subscribe();
                this.dateAdapter.setLocale(lang);
            }
        });

        this.translate.stream(this.title_string).subscribe(translated_title => {
            this.title.setTitle(translated_title);
        });
    }

    /**
     * Helper function because languages has to


;
              if (_value != null && _value >= 1) return null;
              return 'Minimum of 1 Item';
            },
            keyboardType: TextInputType.number,
          ),
        ),
      ],
      contentPadding: LunaDialog.inputTextDialogContentPadding(),
    );

    return Tuple2(_flag, int.tryParse(_textController.text) ?? 50);
  }

  Future<void> addMovieOptions(BuildContext context) async {
    await LunaDialog.dialog(
      context: context,
      title: 'lunasea.Options'.tr(),
      buttons: [
        LunaDialog.button(
          text: 'lunasea.Close'.tr(),
          onPressed: () => Navigator.of(context, rootNavigator: true).pop(),
        ),
      ],
      showCancelButton: false,
      content: [
        RadarrDatabase.ADD_MOVIE_SEARCH_FOR_MISSING.listenableBuilder(
          builder: (context, _) => LunaDialog.checkbox(
            title: 'radarr.StartSearchForMissingMovie'.tr(),
            value: RadarrDatabase.ADD_MOVIE_SEARCH_FOR_MISSING.read(),
            onChanged: (value) =>
                RadarrDatabase.ADD_MOVIE_SEARCH_FOR_MISSING.update(value!),
          ),
        ),
      ],
      contentPadding: LunaDialog.listDialogContentPadding(),
    );
  }

  Future<bool> moveFiles() async {
    bool _flag = false;

    void _setValues(bool flag) {
      _flag = flag;
      Navigator.of(LunaState.context, rootNavigator: true).pop();
    }

    await LunaDialog.dialog(
      context: LunaState.context,
      title: 'radarr.MoveFiles'.tr(),
      contentPadding: LunaDialog.textDialogContentPadding(),
      cancelButtonText: 'lunasea.No'.tr(),
      buttons: [
        LunaDialog.button(
          text: 'lunasea.Yes'.tr(),
          onPressed: () => _setValues(true),
        ),
      ],
      content: [
        LunaDialog.textContent(text: 'radarr.MoveFilesDescription'.tr()),
      ],
    );

    return _flag;
  }
}
import 'package:lunasea/core.dart';
import 'package:lunasea/modules/radarr.dart';

part 'filter_releases.g.dart';

@HiveType(typeId: 20, adapterName: 'RadarrReleasesFilterAdapter')
enum RadarrReleasesFilter {
  @HiveField(0)
  ALL,
  @HiveField(1)
  APPROVED,
  @HiveField(2)
  REJECTED,
}

extension RadarrReleasesFilterExtension on RadarrReleasesFilter {
  String get key {
    switch (this) {
      case RadarrReleasesFilter.ALL:
        return 'all';
      case RadarrReleasesFilter.APPROVED:
        return 'approved';
      case RadarrReleasesFilter.REJECTED:
        return 'rejected';
    }
  }

  String get readable {
    switch (this) {
      case RadarrReleasesFilter.ALL:
        return 'radarr.All'.tr();
      case RadarrReleasesFilter.APPROVED:
        return 'radarr.Approved'.tr();
      case RadarrReleasesFilter.REJECTED:
        return 'radarr.Rejected'.tr();
    }
  }

  RadarrReleasesFilter? fromKey(String key) {
    switch (key) {
      case 'all':
        return RadarrReleasesFilter.ALL;
      case 'approved':
        return RadarrReleasesFilter.APPROVED;
      case 'rejected':
        return RadarrReleasesFilter.REJECTED;
      default:
        return null;
    }
  }

  List<RadarrRelease> filter(List<RadarrRelease> releases) =>
      _Filterer().byType(releases, this);
}

class _Filterer {
  List<RadarrRelease> byType(
    List<RadarrRelease> releases,
    RadarrReleasesFilter type,
  ) {
    switch (type) {
      case RadarrReleasesFilter


 client.FetchBatchRaw(ctx, &op.request)
		if err != nil {
			op.completeAll(nil, err)
			cleanup()
			return
		}

		resultLen := len(result.Elements)
		opLen := op.Size()
		for i := 0; i < opLen; i++ {
			if !(i < resultLen) {
				// No results for this entry, in practice should never occur
				op.complete(i, nil, errQueueFetchNoResponse(q.host.ID()))
				continue
			}
			if result.Elements[i].Err != nil {
				op.complete(i, nil, result.Elements[i].Err)
				continue
			}
			op.complete(i, result.Elements[i].Segments, nil)
		}
		cleanup()
	})
}

func (q *queue) asyncFetchV2(
	ops []op,
	currV2FetchBatchRawReq *rpc.FetchBatchRawV2Request,
) {
	q.fetchOpBatchSize.RecordValue(float64(len(currV2FetchBatchRawReq.Elements)))
	q.Add(1)
	q.workerPool.Go(func() {
		// NB(r): Defer is slow in the hot path unfortunately
		cleanup := func() {
			q.fetchBatchRawV2RequestElementArrayPool.Put(currV2FetchBatchRawReq.Elements)
			q.fetchBatchRawV2RequestPool.Put(currV2FetchBatchRawReq)
			for _, op := range ops {
				fetchOp := op.(*fetchBatchOp)
				fetchOp.DecRef()
				fetchOp.Finalize()
			}
			q.Done()
		}

		client, _, err := q.connPool.NextClient()
		if err != nil {
			// No client available.
			callAllCompletionFns(ops, nil, err)
			cleanup()
			return
		}

		ctx, _ := thrift.NewContext(q.opts.FetchRequestTimeout())
		result, err := client.FetchBatchRawV2(ctx, currV2FetchBatchRawReq)
		if err != nil {
			callAllCompletionFns(ops, nil, err)
			cleanup()
			return
		}

		resultIdx := -1
		for _, op := range ops {
			fetchOp := op.(*fetchBatchOp)
			for j := 0; j < fetchOp.Size(); j++ {
				resultIdx++
				if resultIdx >= len(result.Elements) {
					// No results for this entry, in practice should never occur.
					fetchOp.complete(j, nil, errQueueFetchNoResponse(q.host.ID()))
					continue
				}

				if result.Elements[resultIdx].Err != nil {
					fetchOp.complete(j, nil, result.Elements[resultIdx].Err)
					continue
				}
				fetchOp.complete(j, result.Elements[resultIdx].Segments, nil)
			}
		}
		cleanup()
	})
}

func (q *queue) asyncFetchTagged(op *fetchTaggedOp) {
	// Note: No worker pool required for fetch tagged queries, they do
	// not benefit from goroutine re-use the same way the write
	// code path does which frequently runs into stack splitting due to
	// how deep the stacks are in the write code path.
	// Context on stack splitting (a lot of other material out there too):
	// https://medium.com/a-journey-with-go/go-how-does-the-goroutine-stack-size-evolve-447fc02085e5
	q.Add(1)

	// NB(r): Need to perform any completion function in async
	// goroutine since caller may hold the lock while enqueing the op
	// which is required to access the completion fn with op.CompletionFn().
	go func() {
		defer func() {
			op.decRef()
			q.Done()
		}()

		// All fetch tagged calls are required to provide a context with a deadline.
		ctx, err := q.


mozilla-esr45" },
        { value: "mozilla-esr31" },
        { value: "mozilla-esr17" },
      ],
    },
  ],
  [
    {
      name: "Firefox other",
      items: [
        { value: "mozilla-mobile" },
        { value: "mozilla-elm" },
        { value: "mozilla-cedar" },
        { value: "mozilla-cypress" },
      ],
    },
    {
      name: "Thunderbird",
      items: [
        { value: "comm-central" },
        { value: "comm-esr128" },
        { value: "comm-esr115" },
        { value: "comm-esr102" },
        { value: "comm-esr91" },
        { value: "comm-esr78" },
        { value: "comm-esr68" },
        { value: "comm-esr60" },
      ],
    },
  ],
  [
    {
      name: "Searchfox",
      items: [
        { value: "mozsearch" },
        { value: "mozsearch-mozilla" },
        { value: "mozsearch-tests" },
      ],
    },
    {
      name: "MinGW",
      items: [
        { value: "mingw" },
        { value: "mingw-moz" },
      ],
    },
    {
      name: "Other",
      items: [
        { label: "KaiOS", value: "kaios" },
        { value: "glean" },
        { value: "l10n" },
        { label: "LLVM", value: "llvm" },
        { value: "nss" },
        { label: "Rust", value: "rust" },
        { label: "TC39 ECMA262 spec", value: "ecma262" },
        { value: "version-control-tools" },
        { label: "WHATWG HTML spec", value: "whatwg-html" },
        { value: "wubkat" },
      ]
    }
  ]
];
var Dxr = new (class Dxr {
  constructor() {
    let constants = document.getElementById("data");

    // This will usually be "/"
    this.wwwRoot = constants.getAttribute("data-root");
    // This will look like "mozilla-central"
    this.tree = constants.getAttribute("data-tree");
    this.baseUrl = location.protocol + "//" + location.host;
    // This will end up "/TREE/static/icons/"
    this.icons = this.wwwRoot + `${this.tree}/static/icons/`;
    // This will usually be "/TREE/search"
    this.searchUrl = constants.getAttribute("data-search");
    this.timeouts = {
      search: 300,
      // We start the history timeout after the search updates (i.e., after
      // timeouts.search has elapsed).
      history: 2000 - 300,
    };
    this.searchBox = document.getElementById("search-box");

    // TODO(emilio): Maybe these should be their own web component or
    // something.
    this.fields = {
      query: document.getElementById("query"),
      path: document.getElementById("path"),
      caseSensitive: document.getElementById("case"),
      regexp: document.getElementById("regexp"),
    };
    this.bubbles = {
      query: document.getElementById("query-bubble"),
      path: document.getElementById("path-bubble"),
    };

    this.setupColSelector();

    this.startSearchTimer = null;
    // The timer to move to the next url.
    this.historyTimer = null;
    // The controller to allow aborting a fetch().
    this.fetchController = null;

    window.addEventListener("pageshow", () =>
      this.initFormFromLocalStorageOrUrl()
    );
    // FIXME: This reloads the page when you navigate to #lineno.
    window.addEventListener("popstate", () => window.location.reload(), {
      once: true,
    });

    // XXX hacky mechanism so that we only run this on pages with a "search"
    // header rather than a "query" header.  We should refactor this and t


import speech_recognition as sr

def start(command):
    print(command)

def stop(command):
    print(command)

def reset(command):
    print(command)

def main():
    recognizer = sr.Recognizer()

    with sr.Microphone() as source:
        recognizer.adjust_for_ambient_noise(source, 1)

    while True:
        with sr.Microphone() as source:
            print("Say a command:")

            try:
                audio = recognizer.listen(source, timeout=2)

                command = recognizer.recognize_google(audio)

                if "grass" in command:
                    start(command)
                elif "stop" in command:
                    stop(command)
                elif "reset" in command:
                    reset(command)
                elif "exit" in command:
                    print("Exiting program.")
                    break
                else:
                    print("Command not recognized. Try again with start, stop, reset, or exit.")

            except sr.UnknownValueError:
                print("Could not understand audio. Try again.")
            except sr.RequestError as e:
                print(f"Error connecting to Google Speech Recognition service: {e}")
            except sr.WaitTimeoutError:
                print("Listening timed out. No command detected.")

if __name__ == "__main__":
    main()


        void HandleCalendarEventRemoveInvite(WorldPacket& recv_data);
        void HandleCalendarEventStatus(WorldPacket& recv_data);
        void HandleCalendarEventModeratorStatus(WorldPacket& recv_data);
        void HandleCalendarComplain(WorldPacket& recv_data);
        void HandleCalendarGetNumPending(WorldPacket& recv_data);

        void HandleSpellClick(WorldPacket& recv_data);
        void HandleGetMirrorimageData(WorldPacket& recv_data);
        void HandleAlterAppearanceOpcode(WorldPacket& recv_data);
        void HandleRemoveGlyphOpcode(WorldPacket& recv_data);
        void HandleCharCustomizeOpcode(WorldPacket& recv_data);
        void HandleQueryInspectAchievementsOpcode(WorldPacket& recv_data);
        void HandleEquipmentSetSaveOpcode(WorldPacket& recv_data);
        void HandleEquipmentSetDeleteOpcode(WorldPacket& recv_data);
        void HandleEquipmentSetUseOpcode(WorldPacket& recv_data);
        void HandleUITimeRequestOpcode(WorldPacket& recv_data);
        void HandleReadyForAccountDataTimesOpcode(WorldPacket& recv_data);
        void HandleQueryQuestsCompletedOpcode(WorldPacket& recv_data);
        void HandleQuestPOIQueryOpcode(WorldPacket& recv_data);

        // Dungeon Finder
        void HandleLfgGetPlayerInfo(WorldPacket& recv_data);
        void HandleLfgGetPartyInfo(WorldPacket& recv_data);
        void HandleLfgGetStatus(WorldPacket& recv_data);
        void HandleLfgSetRoles(WorldPacket& recv_data);
        void HandleLfgProposalResponse(WorldPacket& recv_data);
        void HandleLfgTeleportRequest(WorldPacket& recv_data);
        void HandleLfgBootVote(WorldPacket& recv_data);

    private:
        // private trade methods
        void moveItems(Item* myItems[], Item* hisItems[]);
        bool VerifyMovementInfo(MovementInfo const& movementInfo, ObjectGuid const& guid) const;
        bool VerifyMovementInfo(MovementInfo const& movementInfo) const;
        void HandleMoverRelocation(MovementInfo& movementInfo);

        void ExecuteOpcode(OpcodeHandler const& opHandle, WorldPacket* packet);

        // logging helper
        void LogUnexpectedOpcode(WorldPacket* packet, const char* reason);
        void LogUnprocessedTail(WorldPacket* packet);

        uint32 m_GUIDLow;                                   // set logged or recently logout player (while m_playerRecentlyLogout set)
        Player* _player;
        WorldSocket* m_Socket;
        std::string m_Address;

        AccountTypes _security;
        uint32 _accountId;
        uint8 m_expansion;

        // Warden
        Warden* _warden;                                    // Remains NULL if Warden system is not enabled by config
        uint16 _build;                                      // connected client build

        time_t _logoutTime;
        bool m_inQueue;                                     // session wait in auth.queue
        bool m_playerLoading;                               // code processed in LoginPlayer
        bool m_playerLogout;                                // code processed in LogoutPlayer
        bool m_playerRecentlyLogout;
        bool m_playerSave;                                  // code processed in LogoutPlayer with save request
        LocaleConstant m_sessionDbcLocale;
        int m_sessionDbLocaleIndex;
        uint32 m_latency;
        AccountData m_accountData[NUM_ACCOUNT_DATA_TYPES];
        uint32 m_Tutorials[8];
        TutorialDataState m_tutorialState;
        AddonsList m_addonsList;
        ACE_Based::LockedQueue<WorldPacket*, ACE_Thread_Mutex> _recvQueue;
};
#endif
/// @}


# Check 64bit AVX512BW swap instructions

	.allow_index_reg
	.text
_start:
	vpextrw	$0xab, %xmm29, %rax	 # AVX512BW
	vpextrw.s	$0xab, %xmm29, %rax	 # AVX512BW
	vpextrw	$123, %xmm29, %rax	 # AVX512BW
	vpextrw.s	$123, %xmm29, %rax	 # AVX512BW
	vpextrw	$123, %xmm29, %r8	 # AVX512BW
	vpextrw.s	$123, %xmm29, %r8	 # AVX512BW
	vpextrw	$0xab, %xmm29, %rax	 # AVX512BW
	vpextrw.s	$0xab, %xmm29, %rax	 # AVX512BW
	vpextrw	$123, %xmm29, %rax	 # AVX512BW
	vpextrw.s	$123, %xmm29, %rax	 # AVX512BW
	vpextrw	$123, %xmm29, %r8	 # AVX512BW
	vpextrw.s	$123, %xmm29, %r8	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu8	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu8.s	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu16	%zmm29, %zmm30	 # AVX512BW
	vmovdqu16.s	%zmm29, %zmm30	 # AVX512BW
	vmovdqu16	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu16.s	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu16	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu16.s	%zmm29, %zmm30{%k7}{z}	 # AVX512BW
	vmovdqu16	%zmm29, %zmm30	 # AVX512BW
	vmovdqu16.s	%zmm29, %zmm30	 # AVX512BW
	vmovdqu16	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu16.s	%zmm29, %zmm30{%k7}	 # AVX512BW
	vmovdqu16	%zmm29,


�用于该系统的 10 月补丁并安装：

https://msrc.microsoft.com/update-guide/releaseNote/2024-Oct

5

参考链接

```
```
```
```
```
```

![](https://mmbiz.qpic.cn/mmbiz_jpg/OT1Aib4N17tOicAE1WiaS3ibBFkRvmNLYPgnjJib9OMGzuSeZfBdE1EHFI0QyyZZ10fkTdUkhibW90vhvua9AVWYoGng/640?wx_fmt=jpeg "")

**白盾，实时阻断有害攻击**

#  【漏洞通告】Redis 缓冲区溢出漏洞(CVE-2024-31449)
深瞳漏洞实验室  深信服千里目安全技术中心   2024-10-09 17:37

![](https://mmbiz.qpic.cn/mmbiz_gif/w8NHw6tcQ5yz6QNasicKG1KKve4hbibBFibfrFZoFn8ECmo3KlJaHjrbUSt0JfF3P1yGSJX9puo5ZdYBXZQG0MFgA/640?wx_fmt=gif&from=appmsg "")

**漏洞名称：**

Redis 缓冲区溢出漏洞(CVE-2024-31449)

**组件名称：**

Redis

**影响范围**：

2.6 ≤ Redis < 6.2.167.0.0 ≤ Redis < 7.2.67.4.0 ≤ Redis < 7.4.1

**漏洞类型：**

缓冲区溢出

**利用条件：**

1、用户认证：需要用户认证

2、前置条件：需要特殊条件

3、触发方式：本地

**综合评价：**

<综合评定利用难度>：困难，授权用户能造成远程代码执行。

<综合评定威胁等级>：高危，能造成远程代码执行。

**官方解决方案：**

已发布

**漏洞分析**

![](https://mmbiz.qpic.cn/mmbiz_gif/w8NHw6tcQ5yz6QNasicKG1KKve4hbibBFibcVuDaVUic8jLeU6icdiaMBlIugeuG5tNhuQWFp09xIxR8lh48Twg5jWbA/640?wx_fmt=gif&from=appmsg "")

**组件介绍**

Redis 是一个开源（BSD 许可）的内存数据结构存储，用作数据库、缓存、消息代理和流引擎。Redis 提供数据结构，例如 字符串、散列、列表、集合、带范围查询的排序集合、位图、超日志、地理空间索引和流。Redis 内置了复制、Lua 脚本、LRU 驱逐、事务和不同级别的磁盘持久性，并通过Redis Sentinel和Redis Cluster自动分区提供高可用性。


    details,
    address,
    circles,
    checkedIn,
  ];

  ContactTemporaryLocation copyWith({
    String? coagContactId,
    double? longitude,
    double? latitude,
    String? name,
    DateTime? start,
    DateTime? end,
    String? details,
    String? address,
    List<String>? circles,
    bool? checkedIn,
  }) => ContactTemporaryLocation(
    coagContactId: coagContactId ?? this.coagContactId,
    longitude: longitude ?? this.longitude,
    latitude: latitude ?? this.latitude,
    name: name ?? this.name,
    start: start ?? this.start,
    end: end ?? this.end,
    details: details ?? this.details,
    address: address ?? this.address,
    circles: circles ?? this.circles,
    checkedIn: checkedIn ?? this.checkedIn,
  );
}
// Copyright 2024 - 2025 The Reunicorn Authors. All rights reserved.
// SPDX-License-Identifier: MPL-2.0

import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/foundation.dart';
import 'package:veilid_support/veilid_support.dart';

import '../../models/backup.dart';
import '../../models/coag_contact.dart';
import 'base.dart';

String? tryUtf8Decode(Uint8List? content) {
  if (content == null) {
    return null;
  }
  try {
    return utf8.decode(content);
  } on FormatException catch (e) {
    debugPrint('UTF-8 decode attempt lead to $e');
    return null;
  }
}

Future<Uint8List> getChunkedPayload(
  DHTRecord record,
  CryptoCodec crypto,
  DHTRecordRefreshMode refreshMode, {
  required int numChunks,
  int chunkOffset = 0,
}) async {
  // Combine the remaining subkeys into the picture
  final chunks = await Future.wait(
    List.generate(numChunks, (i) => i + chunkOffset).map(
      (i) => record.get(crypto: crypto, refreshMode: refreshMode, subkey: i),
    ),
  );
  final payload = Uint8List.fromList(
    chunks.map((e) => e ?? Uint8List(0)).expand((x) => x).toList(),
  );
  return payload;
}

/// From an opened record, get app specific content and picture data from
/// corresponding subkeys
Future<(String?, Uint8List?)> _getJsonProfileAndPictureFromRecord(
  DHTRecord record,
  CryptoCodec crypto,
  DHTRecordRefreshMode refreshMode,
) async {
  // Get main profile content from first subkey
  final mainContent = await record.get(
    crypto: crypto,
    refreshMode: refreshMode,
    subkey: 0,
  );
  final jsonString = tryUtf8Decode(mainContent);

  final picture = await getChunkedPayload(
    record,
    crypto,
    refreshMode,
    numChunks: 31,
    chunkOffset: 1,
  );

  return (jsonString, (picture.isEmpty) ? null : picture);
}

Iterable<Uint8List> chopPayloadChunks(
  Uint8List payload, {
  int chunkMaxBytes = 32000,
  int numChunks = 31,
}) =>
    List.generate(
      numChunks,
      (i) => (payload.length > i * chunkMaxBytes)
          ? payload.sublist(
              i * chunkMaxBytes,
              min(payload.length, (i + 1) * chunkMaxBytes),
            )
          : Uint8List(0),
    );

DhtSettings rotateKeysInDhtSettings(
  DhtSettings settings,
  PublicKey? usedPublicKey,
  KeyPair? usedKeyPair,
  bool ackHandshakeJustCompleted,
) {
  // If we have received handshake complete signal for the first time, or our
  // next key pair's public key was used
  final rotateKeyPair = ackHandshakeJustCompleted ||
      (usedKeyPair != null && settings.myNextKeyPair == usedKeyPair);

  // If their next public key was used


from base import *

DOMAIN = "server_domain_to_domain1"
PATH   = "/file1/param"

CONF = """
vserver!1250!nick = <domain>
vserver!1250!document_root = /faked

vserver!1250!rule!10!match = default
vserver!1250!rule!10!handler = redir
vserver!1250!rule!10!handler!rewrite!1!show = 1
vserver!1250!rule!10!handler!rewrite!1!regex = ^/(.*)$
vserver!1250!rule!10!handler!rewrite!1!substring = http://www.<domain>/$1

vserver!1251!nick = www.<domain>
vserver!1251!document_root = %s
vserver!1251!match = wildcard
vserver!1251!match!domain!1 = www.<domain>
"""

class Test (TestBase):
    def __init__ (self):
        TestBase.__init__ (self, __file__)
        self.name = "Domain to Domain I"

        self.request           = "GET %s HTTP/1.1\r\n" %(PATH) +\
                                 "Host: %s\r\n" %(DOMAIN)      +\
                                 "Connection: Close\r\n"

        self.expected_error    = 301
        self.expected_content  = "http://www.%s%s" % (DOMAIN, PATH)

    def Prepare (self, www):
        srvr = self.Mkdir (www, "domain_%s" % (DOMAIN))

        self.conf = CONF % (srvr)
        self.conf = self.conf.replace ('<domain>', DOMAIN)


properties(registerer);
    padding::register_properties(registerer);
}
<gh_stars>100-1000
use algo::tree::binary::Tree;

#[test]
fn rb_tree_height() {
    use algo::tree::binary::rb::RedBlackTree;
    let mut tree = Tree::default();
    for v in 0..100 {
        tree.insert(v, v);
    }
    // 即使输入升序数列，rb tree仍然是平衡的
    // 证明：含有n个节点的红黑树，其高度不会超过 2 * lg(n + 1)
    assert!(tree.height() as f32 <= 2.0 * 100.0f32.log2())
}
use crate::component::{Component, DefaultStorage};
use crate::entity::Entity;
use crate::world::{Fetch, World};

pub struct FetchNot<'data, C>
where
    C: Component,
{
    storage: Option<&'data DefaultStorage<C>>,
}

impl<'data, C> TryFrom<&'data World> for FetchNot<'data, C>
where
    C: Component,
{
    type Error = ();

    // noinspection DuplicatedCode
    fn try_from(world: &'data World) -> Result<Self, Self::Error> {
        let storage = world.registry().get_storage::<C>();
        Ok(Self { storage })
    }
}

impl<'data, C> Fetch<'data> for FetchNot<'data, C>
where
    C: Component,
{
    type Item = ();

    fn fetch(&self, entity: Entity) -> Result<Self::Item, ()> {
        match self.storage {
            None => Ok(()),
            Some(storage) => {
                let component = storage.get(entity);
                match component {
                    None => Ok(()),
                    Some(_) => Err(()),
                }
            }
        }
    }
}
use crate::support::FullyQualifiedName;
use std::ops::Deref;
use truc::record::definition::RecordVariantId;

/// Defines the type of records going through a given stream.
#[derive(PartialEq, Eq, Clone, Hash, Default, Display, Debug, From)]
pub struct StreamRecordType(FullyQualifiedName);

impl Deref for StreamRecordType {
    type Target = Box<[Box<str>]>;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

/// Defines the source of a node stream, i.e. the way to connect to the source of records.
#[derive(PartialEq, Eq, Clone, Hash, Default, Display, Debug, From)]
pub struct NodeStreamSource(FullyQualifiedName);

impl Deref for NodeStreamSource {
    type Target = Box<[Box<str>]>;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

/// Node stream information
#[derive(Clone, Debug, new, Getters, CopyGetters, MutGetters)]
pub struct NodeStream {
    /// The type of the records going through the entire stream.
    #[getset(get = "pub")]
    record_type: StreamRecordType,
    /// The record variant for a specific node.
    #[getset(get_copy = "pub")]
    variant_id: RecordVariantId,
    /// The source to connect to in order to read records from it.
    #[getset(get = "pub")]
    source: NodeStreamSource,
}

impl NodeStream {
    /// Creates a new stream with a different source.
    pub fn with_source(&self, source: NodeStreamSource) -> Self {
        Self {
            source,
            ..self.clone()
        }
    }

    pub fn definition_fragments<'a>(
        &'a self,
        module_prefix: &'a FullyQualifiedName,
    ) -> RecordDefinitionFragments<'a> {
        RecordDefinitionFragments {
            stream: self,
            module_prefix,
        }
    }
}

pub struct RecordDefiniti


 "../") and returning an absolute path of the
/// destination.
///
/// The dst will be copied to if it is an existing directory.
/// The dst will be a clone of the src if it doesn't exist.
/// Doesn't follow links
///
/// ### Examples
/// ```
/// use fungus::prelude::*;
///
/// let tmpdir = PathBuf::from("tests/temp").abs().unwrap().mash("file_doc_copy");
/// assert!(sys::remove_all(&tmpdir).is_ok());
/// assert!(sys::mkdir(&tmpdir).is_ok());
/// let file1 = tmpdir.mash("file1");
/// let file2 = tmpdir.mash("file2");
/// assert!(sys::touch(&file1).is_ok());
/// assert!(sys::copy(&file1, &file2).is_ok());
/// assert_eq!(file2.exists(), true);
/// assert!(sys::remove_all(&tmpdir).is_ok());
/// ```
pub fn copy<T: AsRef<Path>, U: AsRef<Path>>(src: T, dst: U) -> FuResult<PathBuf> {
    let mut clone = true;
    let dstabs = dst.as_ref().abs()?;

    // Handle globbing
    let sources = sys::glob(&src)?;
    if sources.is_empty() {
        return Err(PathError::does_not_exist(&src).into());
    }

    // Copy into destination vs clone as destination
    if dstabs.is_dir() || sources.len() > 1 {
        clone = false;
    }

    // Recurse on sources
    for srcroot in sources {
        for entry in WalkDir::new(&srcroot).follow_links(false).sort_by(|x, y| x.file_name().cmp(y.file_name())) {
            let srcpath = entry?.into_path();

            // Set proper dst path
            let dstpath = match clone {
                true => dstabs.mash(srcpath.trim_prefix(&srcroot)),
                false => dstabs.mash(srcpath.trim_prefix(srcroot.dir()?)),
            };
            match &srcpath {
                // Copy dir links needs to be first as is_dir follows links
                x if x.is_symlink_dir() => {
                    symlink(&dstpath, srcpath.readlink()?)?;
                },

                // Create destination directories as needed
                x if x.is_dir() => {
                    mkdir(dstpath)?;
                },

                // Copy file
                _ => {
                    copyfile(&srcpath, &dstpath)?;
                },
            }
        }
    }

    Ok(dstabs)
}

/// Copyfile provides a flexible options for copying files
#[derive(Debug)]
pub struct Copyfile {
    src: PathBuf,       // source file
    dst: PathBuf,       // destination path
    mode: Option<u32>,  // mode to chmod the file to if set
    follow_links: bool, // follow links when copying files
}

impl Copyfile {
    /// Update the `follow` option. Default is disabled.
    /// When `yes` is `true`, links are followed.
    pub fn follow(&mut self, yes: bool) -> &mut Self {
        self.follow_links = yes;
        self
    }

    /// Update the `mode` option. Default is disabled.
    pub fn mode(&mut self, mode: u32) -> &mut Self {
        self.mode = Some(mode);
        self
    }

    /// Execute the copyfile operation with the current options.
    pub fn copy(&mut self) -> FuResult<PathBuf> {
        // Configure and check source
        if !self.src.exists() {
            return Err(PathError::does_not_exist(&self.src).into());
        }
        if self.src.is_dir() || self.src.is_symlink_dir() {
            return Err(PathError::is_not_file


olSpec.BOOSTCUT = ControlSpec.new(-20, 20, "lin", 0, 0, "dB")
--- converts to a panning range (-1 - 1)
ControlSpec.PAN = ControlSpec.new(-1, 1, "lin", 0, 0, "")
--- converts to a detune range
ControlSpec.DETUNE = ControlSpec.new(-20, 20, "lin", 0, 0, "Hz")
--- converts to a sensible range for playback rate
ControlSpec.RATE = ControlSpec.new(0.125, 8, "exp", 0, 1, "")
--- convert to a good range for beats
ControlSpec.BEATS = ControlSpec.new(0, 20, "lin", 0, 0, "Hz")
--- converts to a good range for delay
ControlSpec.DELAY = ControlSpec.new(0.0001, 1, "exp", 0, 0.3, "secs")

return ControlSpec


极限",
"rate limiting":"[电] 速率定限",
"rate making":"[经] 制订费率",
"rate multiplier":"[计] 比率乘数",
"rate network":"[计] 比率网络",
"rate of accumulation":"[经] 积累率",
"rate of advance":"[经] 前进速度, 钻井速度, 贷款费率",
"rate of assessment":"[经] 估价比率, 摊派税率",
"rate of attrition":"[网络] 磨损率",
"rate of call":"[经] 活期利率",
"rate of capacity utilization":"[经] 产能利用率",
"rate of change":"[电] 变率",
"rate of combustion":"[机] 燃烧率",
"rate of component control":"[电] 分率控制",
"rate of consumer price inflation":"[经] 消费物价指数计算的通货膨胀率",
"rate of contribution margin":"[经] 贡献毛益率",
"rate of conversion":"[经] 兑换率, 换算率",
"rate of cooling":"[化] 冷却速率",
"rate of corrosion":"[化] 腐蚀速率",
"rate of cracking":"[化] 裂化速率",
"rate of creep":"[化] 蠕变速率",
"rate of crystallization":"[化] 结晶速率",
"rate of data signalling":"[计] 数据传输速率",
"rate of decarburization":"[机] 脱碳率",
"rate of decay":"[化] 衰减速率",
"rate of deformation":"[化] 形变速率",
"rate of deposition":"[机] 熔接堆积率",
"rate of depreciation":"[化] 折旧率\\n[经] 折旧率",
"rate of despatch money":"[经] 速遣费率",
"rate of detonation":"[化] 爆轰速率; 爆炸速率",
"rate of dividend":"[经] 股利率",
"rate of drilling":"[经] 钻速",
"rate of duty":"[经] 税率",
"rate of economic growth":"[经] 经济发展率, 经济发展速度",
"rate of entropy production":"[化] 熵产生率",
"rate of estate duty":"[经] 遗产税率",
"rate of estimated depreciation":"[经] 估计折旧率",
"rate of evaporation":"[化] 汽化速率; 蒸发率",
"rate of exchange":"兑换率\\n[经] 汇兑率, 兑换率",
"rate of extension":"[化] 拉伸速率",
"rate of extrusion":"[化] 挤出速率",
"rate of feed":"[化] 进料速率",
"rate of final product":"[经] 最终产品率",
"rate of final products":"[


 nil
}

// This method get the Linux distribution Codename. This logic works on ubuntu
// Here assumption is all edge nodes are running with lsb modules.
// It returns empty string in case of error
func GetPlatform() (string, error) {

	linuxDistrib := execCommand("lsb_release", "-cs")
	var out bytes.Buffer
	linuxDistrib.Stdout = &out

	if err := linuxDistrib.Run(); err != nil {
		return "", fmt.Errorf("l3afd/nf : Failed to run command with error: %w", err)
	}

	return strings.TrimSpace(out.String()), nil
}

func IsProcessRunning(pid int, name string) (bool, error) {
	procState, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
	if err != nil {
		return false, fmt.Errorf("BPF Program not running %s because of error: %w", name, err)
	}
	var u1, u2, state string
	_, err = fmt.Sscanf(string(procState), "%s %s %s", &u1, &u2, &state)
	if err != nil {
		return false, fmt.Errorf("failed to scan proc state with error: %w", err)
	}
	if state == "Z" {
		return false, fmt.Errorf("process %d in Zombie state", pid)
	}

	return true, nil
}

// VerifyNCreateTCDirs - Creating BPF sudo FS for pinning TC maps
func VerifyNCreateTCDirs() error {
	path := "/sys/fs/bpf/tc/globals"
	if _, err := os.Stat(path); err == nil {
		log.Debug().Msgf(" %s tc directory exists", path)
		return nil
	}
	log.Info().Msgf(" %s tc directory doesn't exists, creating", path)

	if err := os.MkdirAll(path, 0700); err != nil {
		return fmt.Errorf("unable to create directories to pin tc maps %s : %w", path, err)
	}
	return nil
}

// LoadTCAttachProgram - Load and attach tc root program filters or any tc program when chaining is disabled
func (b *BPF) LoadTCAttachProgram(ifaceName, direction string) error {
	iface, err := net.InterfaceByName(ifaceName)
	if err != nil {
		log.Error().Err(err).Msgf("LoadTCAttachProgram - look up network iface %q", ifaceName)
		return err
	}
	if err := b.LoadBPFProgram(ifaceName); err != nil {
		return err
	}
	// verify and add attribute clsact
	tcgo, err := tc.Open(&tc.Config{})
	if err != nil {
		return fmt.Errorf("could not open rtnetlink socket for interface %s : %w", ifaceName, err)
	}
	clsactFound := false
	htbFound := false
	ingressFound := false
	var htbHandle uint32
	var ingressHandle uint32
	var parentHandle uint32
	// get all the qdiscs from all interfaces
	qdiscs, err := tcgo.Qdisc().Get()
	if err != nil {
		return fmt.Errorf("could not get qdiscs for interface %s : %w", ifaceName, err)
	}

	for _, qdisc := range qdiscs {
		iface, err := net.InterfaceByIndex(int(qdisc.Ifindex))
		if err != nil {
			return fmt.Errorf("could not get interface %s from id %d: %w", ifaceName, qdisc.Ifindex, err)
		}
		if iface.Name == ifaceName {
			switch qdisc.Kind {
			case "clsact":
				clsactFound = true
			case "htb":
				htbFound = true
				htbHandle = qdisc


						Primary: &hclspec.Spec{
							Block: &hclspec.Spec_Attr{
								Attr: &hclspec.Attr{
									Name:     "foo",
									Type:     "string",
									Required: true,
								},
							},
						},
						Default: &hclspec.Spec{
							Block: &hclspec.Spec_Literal{
								Literal: &hclspec.Literal{
									Value: "\"hi\"",
								},
							},
						},
					},
				},
			},
			Expected: &hcldec.DefaultSpec{
				Primary: &hcldec.AttrSpec{
					Name:     "foo",
					Type:     cty.String,
					Required: true,
				},
				Default: &hcldec.LiteralSpec{
					Value: cty.StringVal("hi"),
				},
			},
		},
	}

	testSpecConversions(t, tests)
}

func TestDec_Convert_Literal(t *testing.T) {
	ci.Parallel(t)

	tests := []testConversions{
		{
			Name: "bool: true",
			Input: &hclspec.Spec{
				Block: &hclspec.Spec_Literal{
					Literal: &hclspec.Literal{
						Value: "true",
					},
				},
			},
			Expected: &hcldec.LiteralSpec{
				Value: cty.BoolVal(true),
			},
		},
		{
			Name: "bool: false",
			Input: &hclspec.Spec{
				Block: &hclspec.Spec_Literal{
					Literal: &hclspec.Literal{
						Value: "false",
					},
				},
			},
			Expected: &hcldec.LiteralSpec{
				Value: cty.BoolVal(false),
			},
		},
		{
			Name: "string",
			Input: &hclspec.Spec{
				Block: &hclspec.Spec_Literal{
					Literal: &hclspec.Literal{
						Value: "\"hi\"",
					},
				},
			},
			Expected: &hcldec.LiteralSpec{
				Value: cty.StringVal("hi"),
			},
		},
		{
			Name: "string w/ func",
			Input: &hclspec.Spec{
				Block: &hclspec.Spec_Literal{
					Literal: &hclspec.Literal{
						Value: "reverse(\"hi\")",
					},
				},
			},
			Expected: &hcldec.LiteralSpec{
				Value: cty.StringVal("ih"),
			},
		},
		{
			Name: "list string",
			Input: &hclspec.Spec{
				Block: &hclspec.Spec_Literal{
					Literal: &hclspec.Literal{
						Value: "[\"hi\", \"bye\"]",
					},
				},
			},
			Expected: &hcldec.LiteralSpec{
				Value: cty.TupleVal([]cty.Value{cty.StringVal("hi"), cty.StringVal("bye")}),
			},
		},
	}

	testSpecConversions(t, tests)
}
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1

package structs

import (
	log "github.com/hashicorp/go-hclog"

	"github.com/hashicorp/go-memdb"
	"github.com/hashicorp/go-version"
	"github.com/hashicorp/nomad/nomad/state"
	"github.com/hashicorp/nomad/nomad/structs"
)

/*
 * This package contains top-level interfaces used throughout the scheduler.
 */

// Factory is used to instantiate a new Scheduler
type Factory func(log.Logger, chan<- interface{}, State, Planner) Scheduler

// Scheduler is the top level instance for a scheduler. A scheduler is
// meant to only encapsulate business logic, pushing the various plumbing
// into Nomad itself. They are invoked to process a single evaluation at
// a time. The evaluation may result in task allocations which are computed
// optimistically, as there are many concurrent evaluations being processed.
// The task allocations are submitted as a plan, and the current leader will
// coordinate the commits to prevent oversubscription or improper allocations
// based on stale state.
type Scheduler interface {
	// Process is used to handle a


10b10 = PIXMAN_FORMAT(32,PIXMAN_TYPE_ARGB,2,10,10,10),
    PIXMAN_x2b10g10r10 = PIXMAN_FORMAT(32,PIXMAN_TYPE_ABGR,0,10,10,10),
    PIXMAN_a2b10g10r10 = PIXMAN_FORMAT(32,PIXMAN_TYPE_ABGR,2,10,10,10),

/* 24bpp formats */
    PIXMAN_r8g8b8 =      PIXMAN_FORMAT(24,PIXMAN_TYPE_ARGB,0,8,8,8),
    PIXMAN_b8g8r8 =      PIXMAN_FORMAT(24,PIXMAN_TYPE_ABGR,0,8,8,8),

/* 16bpp formats */
    PIXMAN_r5g6b5 =      PIXMAN_FORMAT(16,PIXMAN_TYPE_ARGB,0,5,6,5),
    PIXMAN_b5g6r5 =      PIXMAN_FORMAT(16,PIXMAN_TYPE_ABGR,0,5,6,5),

    PIXMAN_a1r5g5b5 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ARGB,1,5,5,5),
    PIXMAN_x1r5g5b5 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ARGB,0,5,5,5),
    PIXMAN_a1b5g5r5 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ABGR,1,5,5,5),
    PIXMAN_x1b5g5r5 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ABGR,0,5,5,5),
    PIXMAN_a4r4g4b4 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ARGB,4,4,4,4),
    PIXMAN_x4r4g4b4 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ARGB,0,4,4,4),
    PIXMAN_a4b4g4r4 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ABGR,4,4,4,4),
    PIXMAN_x4b4g4r4 =    PIXMAN_FORMAT(16,PIXMAN_TYPE_ABGR,0,4,4,4),

/* 8bpp formats */
    PIXMAN_a8 =          PIXMAN_FORMAT(8,PIXMAN_TYPE_A,8,0,0,0),
    PIXMAN_r3g3b2 =      PIXMAN_FORMAT(8,PIXMAN_TYPE_ARGB,0,3,3,2),
    PIXMAN_b2g3r3 =      PIXMAN_FORMAT(8,PIXMAN_TYPE_ABGR,0,3,3,2),
    PIXMAN_a2r2g2b2 =    PIXMAN_FORMAT(8,PIXMAN_TYPE_ARGB,2,2,2,2),
    PIXMAN_a2b2g2r2 =    PIXMAN_FORMAT(8,PIXMAN_TYPE_ABGR,2,2,2,2),

    PIXMAN_c8 =          PIXMAN_FORMAT(8,PIXMAN_TYPE_COLOR,0,0,0,0),
    PIXMAN_g8 =          PIXMAN_FORMAT(8,PIXMAN_TYPE_GRAY,0,0,0,0),

    PIXMAN_x4a4 =        PIXMAN_FORMAT(8,PIXMAN_TYPE_A,4,0,0,0),

    PIXMAN_x4c4 =        PIXMAN_FORMAT(8,PIXMAN_TYPE_COLOR,0,0,0,0),
    PIXMAN_x4g4 =        PIXMAN_FORMAT(8,PIXMAN_TYPE_GRAY,0,0,0,0),

/* 4bpp formats */
    PIXMAN_a4 =          PIXMAN_FORMAT(4,PIXMAN_TYPE_A,4,0,0,0),
    PIXMAN_r1g2b1 =      PIXMAN_FORMAT(4,PIXMAN_TYPE_ARGB,0,1,2,1),
    PIXMAN_b1g2r1 =      PIXMAN_FORMAT(4,PIXMAN_TYPE_ABGR,0,1,2,1),
    PIXMAN_a1r1g1b1 =    PIXMAN_FORMAT(4,PIXMAN_TYPE_ARGB,1,1,1,1),
    PIXMAN_a1b1g1r1 =    PIXMAN_FORMAT(4,PIXMAN_TYPE_ABGR,1,1,1,1),

    PIXMAN_c4 =          PIXMAN_FORMAT(4,PIXMAN_TYPE_COLOR,0,0,0,0),
    PIXMAN_g4 =          PIXMAN_FORMAT(4,PIXMAN_TYPE_GRAY,0,0,0,0),

/* 1bpp formats */
    PIXMAN_a1 =          PIXMAN_FORMAT(1,PIXMAN_TYPE_A,1,0,0,0),

    PIXMAN_g1 =          PIXMAN_FORMAT(1,PIXMAN_TYPE_GRAY,0,0,0,0),

/* YUV formats */
    PIXMAN_yuy2 =        PIXMAN_FORMAT(16,PIXMAN_TYPE_YUY2,0,0,0,0),
    PIXMAN_yv12 =        PIXMAN_FORMAT(12,PIXMAN_TYPE_YV12,0,0,0,0)
} pixman_format_code_t;

/* Querying supported


= Array.Empty<DeclarationType>();
        /// <summary>
        /// If true (default), results will include user-defined items.
        /// </summary>
        public bool IncludeUserDefined { get; set; } = true;
        /// <summary>
        /// If true, results will only include user-defined items. false by default.
        /// </summary>
        /// <remarks>This option takes precedence over <c>IncludeUserDefined</c> if the latter is <c>false</c> but the former is <c>true</c>.</remarks>
        public bool IsUserDefinedOnly { get; set; }

        public string ToWhereClause()
        {
            var criterion = new List<string>();
            if (DeclarationId.Any())
            {
                criterion.Add($" [DeclarationId] IN({string.Join(",", DeclarationId)}) ");
            }

            if (Folder.Any())
            {
                criterion.Add($" [Folder] IN ('{string.Join("','", Folder)}') ");
            }

            if (DeclarationTypes.Any())
            {
                criterion.Add($" [DeclarationType] IN ('{string.Join("','", DeclarationTypes)}') ");
            }

            if (!IncludeUserDefined)
            {
                criterion.Add($" [IsUserDefined] = 0 ");
            }
            else if (IsUserDefinedOnly)
            {
                criterion.Add($" [IsUserDefined] = 1 ");
            }

            return string.Join(" AND ", criterion);
        }
    }

}


		switch (param) {
#ifdef __linux__
		case param_line:
			mode.c_line = xatoul_sfx(argnext, stty_suffixes);
			stty_state |= STTY_require_set_attr;
			break;
#endif
#ifdef TIOCGWINSZ
		case param_cols:
		case param_columns:
			set_window_size(-1, xatoul_sfx(argnext, stty_suffixes));
			break;
		case param_size:
			display_window_size(0);
			break;
		case param_rows:
			set_window_size(xatoul_sfx(argnext, stty_suffixes), -1);
			break;
#endif
		case param_speed:
			display_speed(&mode, 0);
			break;
		case param_ispeed:
			set_speed_or_die(input_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		case param_ospeed:
			set_speed_or_die(output_speed, argnext, &mode);
			stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			break;
		default:
			if (recover_mode(arg, &mode) == 1)
				stty_state |= STTY_require_set_attr;
			else /* true: if (tty_value_to_baud(xatou(arg)) != (speed_t) -1) */{
				set_speed_or_die(both_speeds, arg, &mode);
				stty_state |= (STTY_require_set_attr | STTY_speed_was_set);
			} /* else - impossible (caught in the first pass):
				bb_error_msg_and_die("invalid argument '%s'", arg); */
		}
	}

	if (stty_state & STTY_require_set_attr) {
		struct termios new_mode;

		if (tcsetattr(STDIN_FILENO, TCSADRAIN, &mode))
			perror_on_device_and_die("%s");

		/* POSIX (according to Zlotnick's book) tcsetattr returns zero if
		   it performs *any* of the requested operations.  This means it
		   can report 'success' when it has actually failed to perform
		   some proper subset of the requested operations.  To detect
		   this partial failure, get the current terminal attributes and
		   compare them to the requested ones */

		/* Initialize to all zeroes so there is no risk memcmp will report a
		   spurious difference in an uninitialized portion of the structure */
		memset(&new_mode, 0, sizeof(new_mode));
		if (tcgetattr(STDIN_FILENO, &new_mode))
			perror_on_device_and_die("%s");

		if (memcmp(&mode, &new_mode, sizeof(mode)) != 0) {
/*
 * I think the below chunk is not necessary on Linux.
 * If you are deleting it, also delete STTY_speed_was_set bit -
 * it is only ever checked here.
 */
#if 0 /* was "if CIBAUD" */
			/* SunOS 4.1.3 (at least) has the problem that after this sequence,
			   tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2);
			   sometimes (m1 != m2).  The only difference is in the four bits
			   of the c_cflag field corresponding to the baud rate.  To save
			   Sun users a little confusion, don't report an error if this
			   happens.  But suppress the error only if we haven't tried to
			   set the baud rate explicitly -- otherwise we'd never give an
			   error for a true failure to set the baud rate */

			new_mode.c_cflag &= (~CIBAUD);
			if ((stty_state & STTY_speed_was_set)
			 || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif
				perror_on_device_and_die("%s: cannot perform all requested operations");
		}
	}

	return EXIT_SUCCESS;
}


<__PRETTY_FUNCTION__.11795+0x238>
  410674:	b00002a1 	adrp	x1, 465000 <free_category+0xe8>
  410678:	d00002a0 	adrp	x0, 466000 <__PRETTY_FUNCTION__.11795+0x238>
  41067c:	a904efba 	stp	x26, x27, [x29, #72]
  410680:	913fe063 	add	x3, x3, #0xff8
  410684:	52816e22 	mov	w2, #0xb71                 	// #2929
  410688:	913ce021 	add	x1, x1, #0xf38
  41068c:	910f0000 	add	x0, x0, #0x3c0
  410690:	f90013b5 	str	x21, [x29, #32]
  410694:	f9002fbc 	str	x28, [x29, #88]
  410698:	97fff916 	bl	40eaf0 <__malloc_assert>
  41069c:	d503201f 	nop
  4106a0:	540002e0 	b.eq	4106fc <_int_free+0x624>  // b.none
  4106a4:	91000821 	add	x1, x1, #0x2
  4106a8:	f9000a60 	str	x0, [x19, #16]
  4106ac:	8b010f18 	add	x24, x24, x1, lsl #3
  4106b0:	c85f7f01 	ldxr	x1, [x24]
  4106b4:	eb00003f 	cmp	x1, x0
  4106b8:	54000061 	b.ne	4106c4 <_int_free+0x5ec>  // b.any
  4106bc:	c802ff13 	stlxr	w2, x19, [x24]
  4106c0:	35ffff82 	cbnz	w2, 4106b0 <_int_free+0x5d8>
  4106c4:	eb00003f 	cmp	x1, x0
  4106c8:	54000161 	b.ne	4106f4 <_int_free+0x61c>  // b.any
  4106cc:	17fffedb 	b	410238 <_int_free+0x160>
  4106d0:	f9000a61 	str	x1, [x19, #16]
  4106d4:	c85f7f00 	ldxr	x0, [x24]
  4106d8:	eb01001f 	cmp	x0, x1
  4106dc:	54000061 	b.ne	4106e8 <_int_free+0x610>  // b.any
  4106e0:	c802ff13 	stlxr	w2, x19, [x24]
  4106e4:	35ffff82 	cbnz	w2, 4106d4 <_int_free+0x5fc>
  4106e8:	eb00003f 	cmp	x1, x0
  4106ec:	540007a0 	b.eq	4107e0 <_int_free+0x708>  // b.none
  4106f0:	aa0003e1 	mov	x1, x0
  4106f4:	eb13003f 	cmp	x1, x19
  4106f8:	54fffec1 	b.ne	4106d0 <_int_free+0x5f8>  // b.any
  4106fc:	d00002a0 	adrp	x0, 466000 <__PRETTY_FUNCTION__.11795+0x238>
  410700


# -*- coding: utf-8 -*-

# Created on 2018-08-15
# author: 欧度智能，https://www.odooai.cn
# email: 300883@qq.com
# resource of odooai
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).

# Odoo在线中文用户手册（长期更新）
# https://www.odooai.cn/documentation/user/10.0/zh_CN/index.html

# Odoo10离线中文用户手册下载
# https://www.odooai.cn/odoo10_user_manual_document_offline/
# Odoo10离线开发手册下载-含python教程，jquery参考，Jinja2模板，PostgresSQL参考（odoo开发必备）
# https://www.odooai.cn/odoo10_developer_document_offline/
# description:

{
    'name': "Event advance search browse by stage and date",
    'version': '16.24.07.18',
    'author': 'odooai.cn',
    'category': 'Extra tools',
    'website': 'https://www.odooai.cn',
    'live_test_url': 'https://demo.odooapp.cn',
    'license': 'LGPL-3',
    'sequence': 2,
    'summary': """
    Browse event by stage. Use for parent children tree list kanban navigator.
    ztree widget.
    """,
    'description': """
    Superbar, zTree widget.
    Advance search with real parent children tree, ListView or KanbanView. parent tree, children tree,
    eg: Product category tree ,Department tree, stock location tree.
    超级方便的查询，树状视图。
    """,
    'price': 0.00,
    'currency': 'EUR',
    'depends': [
        'event',
    ],
    'images': ['static/description/banner.png'],
    'data': [
        'views/event_event_views.xml',
    ],
    'demo': [
    ],
    'test': [
    ],
    'post_load': None,
    'post_init_hook': 'post_init_hook',
    'installable': True,
    'application': True,
    'auto_install': False,
}


printf(o, "Usage: mlr %s [options] [one or more directories/files]\n", verbName)
	fmt.Fprintf(o, "If no directories/files are specified, the directory %s is used by default.\n", defaultPath)
	fmt.Fprintf(o, "Recursively walks the directory/ies looking for foo.cmd files having Miller command-lines,\n")
	fmt.Fprintf(o, "with foo.expout and foo.experr files having expected stdout and stderr, respectively.\n")
	fmt.Fprintf(o, "If foo.should-fail exists and is a file, the command is expected to exit non-zero back to\n")
	fmt.Fprintf(o, "the shell.\n")
	fmt.Fprintf(o, "\n")
	fmt.Fprintf(o, "Options:\n")
	fmt.Fprintf(o, "[none] Print directory-level pass/fails, and overall pass/fail.\n")
	fmt.Fprintf(o, "-m {...} Specify name of Miller executable to use.\n")
	fmt.Fprintf(o, "-c       Shorthand for -m ../c/mlr.\n")
	fmt.Fprintf(o, "-p       Create the .expout and .experr files, rather than checking them.\n")
	fmt.Fprintf(o, "-v       Also include pass/fail at command-file level.\n")
	fmt.Fprintf(o, "-vv      Also include pass/fail reasons for each command-file.\n")
	fmt.Fprintf(o, "-vvv     Also include full stdout/stderr/exit-code for each command-file.\n")
	fmt.Fprintf(o, "-j       Just show the Miller command-line, put/filter script if any, and output.\n")
	fmt.Fprintf(o, "-s {n}   After running tests, re-run first n failed .cmd files with verbosity level 3.\n")
	fmt.Fprintf(o, "-S       After running tests, re-run all failed .cmd files with verbosity level 3.\n")
	os.Exit(exitCode)
}

// Here the args are the full Miller command line: "mlr regtest --foo bar".
func RegTestMain(args []string) int {

	exeName := os.Args[0]
	verbName := args[0]
	argc := len(args)
	argi := 1
	verbosityLevel := 0
	doPopulate := false
	plainMode := false
	firstNFailsToShow := 0

	for argi < argc /* variable increment: 1 or 2 depending on flag */ {
		arg := args[argi]

		if !strings.HasPrefix(arg, "-") {
			break // No more flag options to process
		}
		argi++

		if arg == "-h" || arg == "--help" {
			regTestUsage(verbName, os.Stdout, 0)

		} else if arg == "-m" {
			if argi >= argc {
				regTestUsage(verbName, os.Stderr, 1)
			}
			exeName = args[argi]
			argi++

		} else if arg == "-s" {
			if argi >= argc {
				regTestUsage(verbName, os.Stderr, 1)
			}
			temp, err := strconv.Atoi(args[argi])
			if err != nil {
				regTestUsage(verbName, os.Stderr, 1)
			}
			firstNFailsToShow = temp
			argi++

		} else if arg == "-S" {
			firstNFailsToShow = 1000000000

		} else if arg == "-p" {
			doPopulate = true

		} else if arg == "-v" {
			verbosityLevel++

		} else if arg == "-j" {
			plainMode = true

		} else {
			regTestUsage(verbName, os.Stderr, 1)
		}
	}
	casePaths := args[argi:]
	if len(casePaths) == 0 {
		casePaths = []string{defaultPath}
	}

	regtester := NewRegTester(
		exeName,
		doPopulate,
		verbosityLevel,
		plainMode,
		firstNFailsToShow,
	)

	ok := regtester.Execute(casePaths)

	if !ok {
		return 1
	}

	return 0
}
// ================


value = (field.value==1) ? true : false;
        engine.setValue(button.group,button.name,value);
    }
}

KontrolF1.switchControlMode = function(field) {
    if (field.name=='quant') {
        KontrolF1.setControlMode("samplers");
    } else if (field.name=='capture') {
        KontrolF1.setControlMode("decks");
    } else {
        HIDDebug("Unconfigured mode selector button: " + field.name);
    }
}

KontrolF1.setControlMode = function(mode) {
    if (mode==KontrolF1.controlMode)
        return;
    if (!(mode in KontrolF1.controlModeButtons)) {
        HIDDebug("Unconfigured control mode: " + mode);
        return;
    }

    if (KontrolF1.controlMode!=undefined) {
        KontrolF1.disconnectModeLEDs(KontrolF1.controlMode);
        KontrolF1.setButtonBrightness(
            KontrolF1.controlModeButtons[KontrolF1.controlMode],0
        );
    }
    KontrolF1.controlMode = mode;
    led = KontrolF1.controlModeButtons[mode];
    KontrolF1.connectModeLEDs(KontrolF1.controlMode);
    KontrolF1.setButtonBrightness(
        KontrolF1.controlModeButtons[KontrolF1.controlMode],0x7f
    );
    KontrolF1.updateLEDs();
}

KontrolF1.registerCallbacks = function() {
    var controller = KontrolF1.controller;

    HIDDebug("Registering HID callbacks");

    controller.linkControl("hid", "select_encoder", "[Playlist]", "SelectTrackKnob");
    controller.linkControl("hid", "select_push", "[Playlist]", "LoadSelectedIntoFirstStopped");
    controller.linkModifier("hid", "shift", "shift");

    controller.setCallback("control", "hid", "capture", KontrolF1.switchControlMode);
    controller.setCallback("control", "hid", "quant", KontrolF1.switchControlMode);

    controller.setCallback("control", "hid", "knob_1", KontrolF1.knob);
    controller.setCallback("control", "hid", "knob_2", KontrolF1.knob);
    controller.setCallback("control", "hid", "knob_3", KontrolF1.knob);
    controller.setCallback("control", "hid", "knob_4", KontrolF1.knob);

    controller.setCallback("control", "hid", "fader_1", KontrolF1.fader);
    controller.setCallback("control", "hid", "fader_2", KontrolF1.fader);
    controller.setCallback("control", "hid", "fader_3", KontrolF1.fader);
    controller.setCallback("control", "hid", "fader_4", KontrolF1.fader);

    controller.setCallback("control", "hid", "grid_1", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_2", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_3", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_4", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_5", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_6", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_7", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_8", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_9", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_10", KontrolF1.grid);
    controller.setCallback("control", "hid", "grid_


    ALOGV("CreateAction %s, %" PRIi32, actionName, countSubactionPaths);

    XrActionCreateInfo aci = {XR_TYPE_ACTION_CREATE_INFO};
    aci.actionType = type;
    if (countSubactionPaths > 0) {
        aci.countSubactionPaths = countSubactionPaths;
        aci.subactionPaths = subactionPaths;
    }
    strcpy(aci.actionName, actionName);
    strcpy(aci.localizedActionName, localizedName ? localizedName : actionName);
    XrAction action = XR_NULL_HANDLE;
    OXR(xrCreateAction(actionSet, &aci, &action));
    return action;
}

XrActionSuggestedBinding
ActionSuggestedBinding(App& app, XrAction action, const char* bindingString) {
    XrActionSuggestedBinding asb;
    asb.action = action;
    XrPath bindingPath;
    OXR(xrStringToPath(app.Instance, bindingString, &bindingPath));
    asb.binding = bindingPath;
    return asb;
}

XrSpace CreateActionSpace(App& app, XrAction poseAction, XrPath subactionPath) {
    XrActionSpaceCreateInfo asci = {XR_TYPE_ACTION_SPACE_CREATE_INFO};
    asci.action = poseAction;
    asci.poseInActionSpace.orientation.w = 1.0f;
    asci.subactionPath = subactionPath;
    XrSpace actionSpace = XR_NULL_HANDLE;
    OXR(xrCreateActionSpace(app.Session, &asci, &actionSpace));
    return actionSpace;
}

XrActionStateBoolean GetActionStateBoolean(App& app, XrAction action) {
    XrActionStateGetInfo getInfo = {XR_TYPE_ACTION_STATE_GET_INFO};
    getInfo.action = action;

    XrActionStateBoolean state = {XR_TYPE_ACTION_STATE_BOOLEAN};
    OXR(xrGetActionStateBoolean(app.Session, &getInfo, &state));
    return state;
}

bool ActionPoseIsActive(App& app, XrAction action, XrPath subactionPath) {
    XrActionStateGetInfo getInfo = {XR_TYPE_ACTION_STATE_GET_INFO};
    getInfo.action = action;
    getInfo.subactionPath = subactionPath;

    XrActionStatePose state = {XR_TYPE_ACTION_STATE_POSE};
    OXR(xrGetActionStatePose(app.Session, &getInfo, &state));
    return state.isActive != XR_FALSE;
}

XrActionSet runningActionSet = XR_NULL_HANDLE;

XrAction aimPoseAction = XR_NULL_HANDLE;
XrAction gripPoseAction = XR_NULL_HANDLE;

XrAction boolAction = XR_NULL_HANDLE;
XrPath leftHandPath = XR_NULL_PATH;
XrPath rightHandPath = XR_NULL_PATH;
} // namespace

XrActionStateBoolean boolState;

bool leftControllerActive = false;
bool rightControllerActive = false;

XrSpace leftControllerAimSpace = XR_NULL_HANDLE;
XrSpace rightControllerAimSpace = XR_NULL_HANDLE;
XrSpace leftControllerGripSpace = XR_NULL_HANDLE;
XrSpace rightControllerGripSpace = XR_NULL_HANDLE;

void AppInput_init(App& app) {
    // Actions
    runningActionSet =
        CreateActionSet(app.Instance, 1, "running_action_set", "Action Set used on main loop");
    boolAction = CreateAction(runningActionSet, XR_ACTION_TYPE_BOOLEAN_INPUT, "toggle", "Toggle");

    OXR(xrStringToPath(app.Instance, "/user/hand/left", &leftHandPath));
    OXR(xrStringToPath(app.Instance, "/user/hand/right", &rightHandPath));
    XrPath handSubactionPaths[2] = {leftHandPath, rightHandPath};

    aimPoseAction = CreateAction(
        runningActionSet, XR_ACTION_TYPE_POSE_INPUT, "aim_pose", nullptr, 2, handSubactionPaths);

    gripPoseAction = CreateAction(
        runningActionS


            if (param.isNotEmpty()) {
                val (key, value) = param.split("=")
                acc[key] = value
            }
        }
    }

val separator = """\s*[\^\\]\s+""".toRegex()
val winEscapeReg = """\^([\W\dA-Fa-f])""".toRegex()

fun String.winEscape() = replace("^\\^\"", "\"").replace(winEscapeReg, "$1")

fun String.parseCurl(): Request {
    var r = this.winEscape()
    // 兼容旧版
    if (r.contains("\n") && !r.contains(separator)) {
        r = r.replace("\n", " \\\n")
    }

    return r.split(separator)
        .map { it.trim() }
        .fold(Request("")) { req, s ->
            val startIndex = s.indexOf(" ") + 1
            when {
                s.startsWith("-X ") -> req.method = s.removeFirstAndEndQuotes(startIndex).trim()
                s.startsWith("-H ") ->
                    with(s.removeFirstAndEndQuotes(startIndex)) {
                        req.headers[substringBefore(":")] = substringAfter(":").trim()
                    }
                s.startsWith("--data-binary ") || s.startsWith("--data-raw ") -> {
                    if (req.method == "GET") {
                        req.method = "POST"
                    }
                    val offset =
                        if (s.substring(startIndex).startsWith("$")) {
                            1
                        } else {
                            0
                        }
                    req.rawBody = s.removeFirstAndEndQuotes(startIndex + offset)
                }
                s.startsWith("--data") -> {
                    if (req.method == "GET") {
                        req.method = "POST"
                    }
                    s.properBody(req, r, startIndex)
                }
                s.startsWith("-d ") -> {
                    if (req.method == "GET") {
                        req.method = "POST"
                    }
                    s.properBody(req, r, startIndex)
                }
                s.startsWith("curl ") ->
                    with(s.removeFirstAndEndQuotes(startIndex)) {
                        if (startsWith("-X")) {
                            val str = substring(3)
                            req.method = str.substringBefore(" ").trim()
                            req.url = str.substringAfter(" ").removeFirstAndEndQuotes()
                        } else {
                            req.url = this
                        }
                    }
                else ->
                    if (s.startsWith("http")) {
                        req.url = this
                    }
            }
            req
        }
}

private fun String.properBody(acc: Request, s: String, from: Int = 3) {
    val value = removeFirstAndEndQuotes(from)
    if (value.contains("@file")) {
        if (value.startsWith("{") || value.startsWith("[")) {
            acc.params.putAll(value.fromJson(MutableMap::class.java) as Map<out String, Any>)
        } else {
            acc.params.putAll(value.paramsParse())
        }
    } else if (s.contains("Content-Type: application/json", true)) {
        acc.rawBody = value
    } else {
        acc.params.putAll(value.paramsParse())
    }
}

fun Request.toCurl(): String =
    buildString {
            append("curl \"$url\"  \\")
            if (method == "GET" && params.isNotEmpty()) append("?").append(params.toParams())
            appendLine()
            append("-X $method  \\")
            if (headers.isNotEmpty() || params.isNotEmpty() || rawBody.isNotEmpty()) {
                appendLine()
            }
            for ((key, value) in


returns gross estimation of the in-memory size of this instance. The estimation is expected not to be
	 * a precise one. Please use constants from {@link MemoryMeasuringConstants} for size computation.
	 */
	int estimateSize();

	/**
	 * Comparison uses price key for comparation.
	 */
	@Override
	default int compareTo(PriceContract o) {
		return priceKey().compareTo(o.priceKey());
	}

	/**
	 * Returns true if this price differs in any business related data from the other value.
	 */
	@Override
	default boolean differsFrom(@Nullable PriceContract otherPrice) {
		if (otherPrice == null) return true;
		if (!Objects.equals(innerRecordId(), otherPrice.innerRecordId())) return true;
		if (!Objects.equals(priceWithoutTax(), otherPrice.priceWithoutTax())) return true;
		if (!Objects.equals(priceWithTax(), otherPrice.priceWithTax())) return true;
		if (!Objects.equals(taxRate(), otherPrice.taxRate())) return true;
		if (!Objects.equals(validity(), otherPrice.validity())) return true;
		if (indexed() != otherPrice.indexed()) return true;
		return dropped() != otherPrice.dropped();
	}
}
/*
 *
 *                         _ _        ____  ____
 *               _____   _(_) |_ __ _|  _ \| __ )
 *              / _ \ \ / / | __/ _` | | | |  _ \
 *             |  __/\ V /| | || (_| | |_| | |_) |
 *              \___| \_/ |_|\__\__,_|____/|____/
 *
 *   Copyright (c) 2023-2024
 *
 *   Licensed under the Business Source License, Version 1.1 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   https://github.com/FgForrest/evitaDB/blob/master/LICENSE
 *
 *   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 io.evitadb.api.requestResponse.data;

/**
 * This interface marks all objects that are immutable and versioned. Whenever new instance of the class instance is
 * created and takes place of another class instance (i.e. is successor of that data) its version must be increased
 * by one.
 *
 * Versioned data are used for handling [optimistic locking](https://en.wikipedia.org/wiki/Optimistic_concurrency_control).
 *
 * @author Jan Novotný (novotny@fg.cz), FG Forrest a.s. (c) 2021
 */
public interface Versioned {

	/**
	 * Returns version of the object.
	 */
	int version();

}
/*
 *
 *                         _ _        ____  ____
 *               _____   _(_) |_ __ _|  _ \| __ )
 *              / _ \ \ / / | __/ _` | | | |  _ \
 *             |  __/\ V /| | || (_| | |_| | |_) |
 *              \___| \_/ |_|\__\__,_|____/|____/
 *
 *   Copyright (c) 2023-2025
 *
 *   Licensed under the Business Source License, Version 1.1 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   https://github.com/FgForrest/evitaDB/blob/master/LICENSE
 *
 *   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 io.evitadb.api.requestResponse.data;

import io.evitadb.api.exception.PrimaryKeyNotAssignedException;
import io.evitadb.api.query.filter.EntityPrimaryKeyInSet;
import io.evitadb.api.requestResponse.schema.EntitySchemaContract;

import javax.annotation.


import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px

data = pd.read_csv('brazilian_amazon_fires_1999_2019.csv')

print(data) #print all the data

df = pd.read_csv('brazilian_amazon_fires_1999_2019.csv', nrows=5)#print the first n rows of the file
print(df)
print("The total number of firespots is: " ,data["firespots"].sum())#displays total sum of firespots
print("The most common state of the fires is ", data["state"].mode())#Finds the mode of states
print("The average number of firespots is ", data["firespots"].mean())
print("The median of firespots is ", data["firespots"].median())#median of firespots
print("Here is the average number of firespots by state:")
print(data[["state", "firespots"]].groupby("state").mean())# print mean of firespots by states
print("Here is the total number of firespots by state:")
print(data[["state", "firespots"]].groupby("state").sum())# print sum of firespots by state
print(data.isnull())# shows data is null

avg_firespots = data.groupby("state")["firespots"].mean().sort_values()#sorts state by ascending order in mean of firespots

# Plotting the bar chart
plt.figure(figsize=(10, 6))
avg_firespots.plot(kind='bar', color='red')

plt.xlabel('State')
plt.ylabel('Average Firespots')
plt.title('Average Firespots by State')
plt.xticks(rotation=45)

# Display the chart
plt.show()

fires=pd.read_csv("brazilian_amazon_fires_1999_2019.csv")
fig = px.density_mapbox(fires, lat='latitude', lon='longitude',z='firespots', radius=10,
                        center=dict(lat=0, lon=180), zoom=0,
                        mapbox_style="open-street-map")
fig.show()

print(data["firespots"].sum())#displays total sum of firespots


ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;"]
    #[doc = ""]
    #[doc = "                  if( ulStatsAsPercentage > 0UL )"]
    #[doc = "                  {"]
    #[doc = "                      sprintf( pcWriteBuffer, \"%s\\t\\t%lu\\t\\t%lu%%\\r\\n\", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );"]
    #[doc = "                  }"]
    #[doc = "                  else"]
    #[doc = "                  {"]
    #[doc = "                      // If the percentage is zero here then the task has"]
    #[doc = "                      // consumed less than 1% of the total run time."]
    #[doc = "                      sprintf( pcWriteBuffer, \"%s\\t\\t%lu\\t\\t<1%%\\r\\n\", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );"]
    #[doc = "                  }"]
    #[doc = ""]
    #[doc = "                  pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );"]
    #[doc = "              }"]
    #[doc = "          }"]
    #[doc = ""]
    #[doc = "          // The array is no longer needed, free the memory it consumes."]
    #[doc = "          vPortFree( pxTaskStatusArray );"]
    #[doc = "      }"]
    #[doc = "  }"]
    #[doc = "
"]
    pub fn uxTaskGetSystemState(
        pxTaskStatusArray: *mut TaskStatus_t,
        uxArraySize: UBaseType_t,
        pulTotalRunTime: *mut u32,
    ) -> UBaseType_t;
}
extern "C" {
    #[doc = " task. h"]
    #[doc = "
void vTaskList( char *pcWriteBuffer );
"]
    #[doc = ""]
    #[doc = " configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must"]
    #[doc = " both be defined as 1 for this function to be available.  See the"]
    #[doc = " configuration section of the FreeRTOS.org website for more information."]
    #[doc = ""]
    #[doc = " NOTE 1: This function will disable interrupts for its duration.  It is"]
    #[doc = " not intended for normal application runtime use but as a debug aid."]
    #[doc = ""]
    #[doc = " Lists all the current tasks, along with their current state and stack"]
    #[doc = " usage high water mark."]
    #[doc = ""]
    #[doc = " Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or"]
    #[doc = " suspended ('S')."]
    #[doc = ""]
    #[doc = " PLEASE NOTE:"]
    #[doc = ""]
    #[doc = " This function is provided for convenience only, and is used by many of the"]
    #[doc = " demo applications.  Do not consider it to be part of the scheduler."]
    #[doc = ""]
    #[doc = " vTaskList() calls uxTaskGetSystemState(), then formats part of the"]
    #[doc = " uxTaskGetSystemState() output into a human readable table that displays task:"]
    #[doc = " names, states, priority, stack usage and task number."]
    #[doc = " Stack usage specified as the number of unused StackType_t words stack can hold"]
    #[doc = " on top of stack - not the number of bytes."]
    #[doc = ""]
    #[doc = " vTaskList() has a dependency on the sprintf() C library function that might"]
    #[doc = " bloat the code size, use a lot of stack, and provide different results on"]
    #[doc = " different platforms.  An alternative, tiny, third party, and limited"]
    #[doc = " functionalit


_SHM */
	case _DRM_SHM:
		vma->vm_ops = &drm_vm_shm_ops;
		vma->vm_private_data = (void *)map;
		/* Don't let this area swap.  Change when
		   DRM_KERNEL advisory is supported. */
		vma->vm_flags |= VM_RESERVED;
		break;
	case _DRM_SCATTER_GATHER:
		vma->vm_ops = &drm_vm_sg_ops;
		vma->vm_private_data = (void *)map;
		vma->vm_flags |= VM_RESERVED;
		vma->vm_page_prot = drm_dma_prot(map->type, vma);
		break;
	default:
		return -EINVAL;	/* This should never happen. */
	}
	vma->vm_flags |= VM_RESERVED;	/* Don't swap */
	vma->vm_flags |= VM_DONTEXPAND;

	drm_vm_open_locked(vma);
	return 0;
}

int drm_mmap(struct file *filp, struct vm_area_struct *vma)
{
	struct drm_file *priv = filp->private_data;
	struct drm_device *dev = priv->minor->dev;
	int ret;

	if (drm_device_is_unplugged(dev))
		return -ENODEV;

	mutex_lock(&dev->struct_mutex);
	ret = drm_mmap_locked(filp, vma);
	mutex_unlock(&dev->struct_mutex);

	return ret;
}
EXPORT_SYMBOL(drm_mmap);


_12.flow_schedule_type.display = function(value)
  -- Check if field has value
  if value == 127 then
    return "Flow Schedule Type: No Value"
  end

  return "Flow Schedule Type: "..value
end

-- Dissect: Flow Schedule Type
cme_futures_mdp3_sbe_v1_12.flow_schedule_type.dissect = function(buffer, offset, packet, parent)
  local length = cme_futures_mdp3_sbe_v1_12.flow_schedule_type.size
  local range = buffer(offset, length)
  local value = range:le_int()
  local display = cme_futures_mdp3_sbe_v1_12.flow_schedule_type.display(value, buffer, offset, packet, parent)

  parent:add(omi_cme_futures_mdp3_sbe_v1_12.fields.flow_schedule_type, range, value, display)

  return offset + length, value
end

-- Contract Multiplier Unit
cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit = {}

-- Size: Contract Multiplier Unit
cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit.size = 1

-- Display: Contract Multiplier Unit
cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit.display = function(value)
  -- Check if field has value
  if value == 127 then
    return "Contract Multiplier Unit: No Value"
  end

  return "Contract Multiplier Unit: "..value
end

-- Dissect: Contract Multiplier Unit
cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit.dissect = function(buffer, offset, packet, parent)
  local length = cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit.size
  local range = buffer(offset, length)
  local value = range:le_int()
  local display = cme_futures_mdp3_sbe_v1_12.contract_multiplier_unit.display(value, buffer, offset, packet, parent)

  parent:add(omi_cme_futures_mdp3_sbe_v1_12.fields.contract_multiplier_unit, range, value, display)

  return offset + length, value
end

-- Contract Multiplier
cme_futures_mdp3_sbe_v1_12.contract_multiplier = {}

-- Size: Contract Multiplier
cme_futures_mdp3_sbe_v1_12.contract_multiplier.size = 4

-- Display: Contract Multiplier
cme_futures_mdp3_sbe_v1_12.contract_multiplier.display = function(value)
  -- Check if field has value
  if value == 2147483647 then
    return "Contract Multiplier: No Value"
  end

  return "Contract Multiplier: "..value
end

-- Dissect: Contract Multiplier
cme_futures_mdp3_sbe_v1_12.contract_multiplier.dissect = function(buffer, offset, packet, parent)
  local length = cme_futures_mdp3_sbe_v1_12.contract_multiplier.size
  local range = buffer(offset, length)
  local value = range:le_int()
  local display = cme_futures_mdp3_sbe_v1_12.contract_multiplier.display(value, buffer, offset, packet, parent)

  parent:add(omi_cme_futures_mdp3_sbe_v1_12.fields.contract_multiplier, range, value, display)

  return offset + length, value
end


set(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_undefined(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_modified(), RflagsBits::OF | RflagsBits::SF | RflagsBits::ZF | RflagsBits::AF | RflagsBits::CF | RflagsBits::PF);
	///
	/// // xor rdi,5Ah
	/// let instr = decoder.decode();
	/// assert_eq!(instr.rflags_read(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_written(), RflagsBits::SF | RflagsBits::ZF | RflagsBits::PF);
	/// assert_eq!(instr.rflags_cleared(), RflagsBits::OF | RflagsBits::CF);
	/// assert_eq!(instr.rflags_set(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_undefined(), RflagsBits::AF);
	/// assert_eq!(instr.rflags_modified(), RflagsBits::OF | RflagsBits::SF | RflagsBits::ZF | RflagsBits::AF | RflagsBits::CF | RflagsBits::PF);
	/// ```
	#[must_use]
	#[inline]
	pub fn rflags_undefined(&self) -> u32 {
		crate::info::rflags_table::FLAGS_UNDEFINED[self.rflags_info() as usize] as u32
	}

	/// All flags that are modified by the CPU. This is `rflags_written() + rflags_cleared() + rflags_set() + rflags_undefined()`. This method returns an [`RflagsBits`] value.
	///
	/// [`RflagsBits`]: struct.RflagsBits.html
	///
	/// # Examples
	///
	/// ```
	/// use iced_x86::*;
	///
	/// // adc rsi,rcx
	/// // xor rdi,5Ah
	/// let bytes = b"\x48\x11\xCE\x48\x83\xF7\x5A";
	/// let mut decoder = Decoder::new(64, bytes, DecoderOptions::NONE);
	///
	/// // adc rsi,rcx
	/// let instr = decoder.decode();
	/// assert_eq!(instr.rflags_read(), RflagsBits::CF);
	/// assert_eq!(instr.rflags_written(), RflagsBits::OF | RflagsBits::SF | RflagsBits::ZF | RflagsBits::AF | RflagsBits::CF | RflagsBits::PF);
	/// assert_eq!(instr.rflags_cleared(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_set(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_undefined(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_modified(), RflagsBits::OF | RflagsBits::SF | RflagsBits::ZF | RflagsBits::AF | RflagsBits::CF | RflagsBits::PF);
	///
	/// // xor rdi,5Ah
	/// let instr = decoder.decode();
	/// assert_eq!(instr.rflags_read(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_written(), RflagsBits::SF | RflagsBits::ZF | RflagsBits::PF);
	/// assert_eq!(instr.rflags_cleared(), RflagsBits::OF | RflagsBits::CF);
	/// assert_eq!(instr.rflags_set(), RflagsBits::NONE);
	/// assert_eq!(instr.rflags_undefined(), RflagsBits::AF);
	/// assert_eq!(instr.rflags_modified(), RflagsBits::OF | RflagsBits::SF | RflagsBits::ZF | RflagsBits::AF | RflagsBits::CF | RflagsBits::PF);
	/// ```
	#[must_use]
	#[inline]
	pub fn rflags_modified(&self) -> u32 {
		crate::info::rflags_table::FLAGS_MODIFIED[self.rflags_info() as usize] as u32
	}

	/// Checks if it