//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <UIKit/UIViewController.h>

@class NSString, UIImage, _UIResilientRemoteViewContainerViewController, _UIShareInvitationRemoteViewController;
@protocol _UISharingViewControllerDelegate;

@interface _UISharingViewController : UIViewController
{
    _Bool _collaborationUIEnabled;
    id <_UISharingViewControllerDelegate> __privateDelegate;
    UIImage *_thumbnail;
    NSString *_auxiliaryActionTitle;
    NSString *_mailTemplate;
    NSString *_messageTemplate;
    NSString *_mailSubject;
    NSString *_initialHeaderSubtitle;
    NSString *_headerSubtitle;
    NSString *_headerActionTitle;
    NSString *_appName;
    _UIResilientRemoteViewContainerViewController *_childViewController;
}

@property(retain, nonatomic, getter=_childViewController, setter=_setChildViewController:) _UIResilientRemoteViewContainerViewController *childViewController; // @synthesize childViewController=_childViewController;
@property(copy, nonatomic, getter=_appName, setter=_setAppName:) NSString *appName; // @synthesize appName=_appName;
@property(copy, nonatomic, getter=_headerActionTitle, setter=_setHeaderActionTitle:) NSString *headerActionTitle; // @synthesize headerActionTitle=_headerActionTitle;
@property(copy, nonatomic, getter=_headerSubtitle, setter=_setHeaderSubtitle:) NSString *headerSubtitle; // @synthesize headerSubtitle=_headerSubtitle;
@property(copy, nonatomic, getter=_initialHeaderSubtitle, setter=_setInitialHeaderSubtitle:) NSString *initialHeaderSubtitle; // @synthesize initialHeaderSubtitle=_initialHeaderSubtitle;
@property(nonatomic, getter=_collaborationUIEnabled, setter=_setCollaborationUIEnabled:) _Bool collaborationUIEnabled; // @synthesize collaborationUIEnabled=_collaborationUIEnabled;
@property(copy, nonatomic, getter=_mailSubject, setter=_setMailSubject:) NSString *mailSubject; // @synthesize mailSubject=_mailSubject;
@property(copy, nonatomic, getter=_messageTemplate, setter=_setMessageTemplate:) NSString *messageTemplate; // @synthesize messageTemplate=_messageTemplate;
@property(copy, nonatomic, getter=_mailTemplate, setter=_setMailTemplate:) NSString *mailTemplate; // @synthesize mailTemplate=_mailTemplate;
@property(copy, nonatomic, getter=_auxiliaryActionTitle, setter=_setAuxiliaryActionTitle:) NSString *auxiliaryActionTitle; // @synthesize auxiliaryActionTitle=_auxiliaryActionTitle;
@property(copy, nonatomic, getter=_thumbnail, setter=_setThumbnail:) UIImage *thumbnail; // @synthesize thumbnail=_thumbnail;
@property(nonatomic, getter=_privateDelegate, setter=_setPrivateDelegate:) __weak id <_UISharingViewControllerDelegate> _privateDelegate; // @synthesize _privateDelegate=__privateDelegate;
- (void).cxx_destruct;
- (void)_setMailSubject:(id)arg1 template:(id)arg2;
- (void)_shareWasMadePrivate;
- (void)_shareDidChange;
- (void)_performHeaderActionWithCompletion:(CDUnknownBlockType)arg1;
- (void)_performAuxiliaryActionWithCompletion:(CDUnknownBlockType)arg1;
@property(nonatomic) __weak id <_UISharingViewControllerDelegate> delegate;
@property(readonly, nonatomic, getter=_remoteViewController) _UIShareInvitationRemoteViewController *remoteViewController;
- (void)dealloc;
- (id)initWithURL:(id)arg1;

@end


yerBoard() {
        this._playerGrid = this._getEmptyGrid(null);
    }

    private _initMines() {
        // (1) ADD UNIQUE CELL CORDINATES TO _bombs
        // (2) ADD MARK BOMB CORDINTE IN _grid
        this._mines = []
        let currentNumberOfMines = 0;
        while(currentNumberOfMines < this._numberOfMines) {
            let randomCell = getRandomCell(this._sizeOfGrid);
            if( containsCell(this._mines, randomCell) )
                continue;
            this._mines.push(randomCell)                   // (1)
            this._grid[randomCell.x][randomCell.y] = -1;  // (2)
            currentNumberOfMines++;
        }
    }

    private _initNumbers() {
        for(let cell of this._mines) {
            let neighbors = this._getNeighborCells(cell);
            for(let {x, y} of neighbors)
                if(this._grid[x][y] !== -1)
                    this._grid[x][y]++;
        }
    }

    private _getNeighborCells(cell: Cell) {
        let neighbors: Cell[] = []
        for(let x = cell.x - 1; x < cell.x + 2; x++)
            for(let y = cell.y - 1; y < cell.y + 2; y++) {
                if(x === cell.x && y === cell.y)
                    continue;
                if(-1 < x && x < this._sizeOfGrid && -1 < y && y < this._sizeOfGrid)
                    neighbors.push({x, y} as Cell);
            }
        return neighbors;
    }

    private _getEmptyGrid(value: any = 0) {
        let board: any[][] = [];
        for(let i = 0; i < this._sizeOfGrid; i++) {
            board[i] = [];
            for(let j = 0; j < this._sizeOfGrid; j++)
                board[i][j] = value;
        }
        return board;
    }

    private _spreadCells(origin: Cell) {
        let checked     : Cell[] = [];
        let notChecked  : Cell[] = [origin]; // queue to be checked
        while(notChecked.length > 0) {
            let popCell = notChecked[0];
            notChecked.splice(0, 1);
            this._markCell(popCell);
            if(!containsCell(checked, popCell))
                checked.push(popCell);
            let zeroNeighbors = this._getNeighborCells(popCell).filter(({x,y}) => this._grid[x][y] === 0);
            for(let zeroNeighbor of zeroNeighbors)
                if(!containsCell(checked, zeroNeighbor) && !containsCell(notChecked, zeroNeighbor))
                    notChecked.push(zeroNeighbor);
        }
        let newCells:Cell[]  = [...checked];
        for(let zeroCell of checked) {
            let numberNeighbors = this._getNeighborCells(zeroCell).filter(({x,y}) => this._grid[x][y] !== 0);
            for(let numberNeighbor of numberNeighbors){
                this._markCell(numberNeighbor);
                if(!containsCell(newCells, numberNeighbor)){
                    newCells.push(numberNeighbor)
                }
            }
        }
        return newCells
    }

    private _markCell({x, y}: Cell


old += Math.round(this.damage /2);
            }
        }
    }

    private addGold() {
        this.goldholder += this.goldsec;
        if (this.goldholder >= 24) {
            this.goldholder-= 24;
            this.gold += 24;
        }
        else if (this.goldholder >= 20) {
            this.goldholder-= 20;
            this.gold += 20;
        }
        else if (this.goldholder >= 16) {
            this.goldholder-= 16;
            this.gold += 16;
        }
        else if (this.goldholder >= 12) {
            this.goldholder-= 12;
            this.gold += 12;
        }
        else if (this.goldholder >= 8) {
            this.goldholder-= 8;
            this.gold += 8;
        }
        else if (this.goldholder >= 6) {
                this.goldholder -= 6;
                this.gold += 6;
            }
            else if (this.goldholder >= 4) {
                    this.goldholder -= 4;
                    this.gold += 4;
                }
                else if (this.goldholder >= 2) {
                        this.goldholder -= 2;
                        this.gold += 2;
                    }
                    else if (this.goldholder >= 1) {
                            this.goldholder -= 1;
                            this.gold += 1;
                        }
    }

    public showStats() {
        this.goldsec = Item.numSquire /60 + Item.numKnight * 4/60 + Item.numPaladin * 8/60;
        this.goldshower = Item.numSquire + Item.numKnight * 4 + Item.numPaladin * 8;
        this.damage = 1 + Item.useSlimeSword * 2 + Item.useOrcSword * 13 + Item.useDragonSword * 30;

        document.getElementById("health").innerHTML = "
Health: " + Math.floor(this.monsterhealth) + "
";
        document.getElementById("damage").innerHTML = "
" + this.damage + " Damage/click
";
        document.getElementById("gold").innerHTML = "
" + this.gold + " gold
";
        document.getElementById("goldsec").innerHTML = "
" + this.goldshower + " gold/sec
";
    }
}import { EOL } from 'os'

export function parseDSL(input: string) {
  const inputLines: string[] = []
  const expectedLines: string[] = []
  let template = ''
  let cursorLine = 0
  let cursorCharacter = 0

  const lines = input.split(/\r?\n/).filter(l => l.length > 0)

  for (let i = 0; i < lines.length; i++) {
    let [input, expected] = lines[i].split('>> ')
    input = input.trimEnd()

    const leadingMark = /^\s*\| /.exec(input)
    if (leadingMark !== null) {
      input = input.replace(leadingMark[0], '')
    }

    const match = /(?<!\$)\{(\w+)\}/.exec(input)
    if (match !== null) {
      template = match[1]
      input = input.replace(match[0], `.${template}`)

      cursorLine = i
      cursorCharacter = match.index + template.length + 1
    }

    inputLines.push(input)
    expectedLines.push(expected)
  }

  if (template.length === 0) {
    throw new Error('DSL must contain template placeholder (ie. {let})')
  }

  return {
    input: inputLines.join(EOL),
    template: template,
    expected: expectedLines.join(EOL),
    cursorPosition: {
      line: cursorLine,
      character: cursorCharacter
    }
  } as ITestDSL
}

export interface ITestDSL {
  input: string,
  template: string,
  expected: string,
  cursorPosition: {
    line: number,
    character: number
  }


p:12;-ms-flex-order:11;order:11}.fb-lg-order-12{-webkit-box-ordinal-group:13;-ms-flex-order:12;order:12}}.nav.nav-pills[class*=fb-][class*=-parent] li+li,.nav.nav-pills[class*=fb-][class*=-parent]>* li+li{margin-left:0}.fileoperations[class*=fb-][class*=-parent]:after,.fileoperations[class*=fb-][class*=-parent]:before,.fileoperations[class*=fb-][class*=-parent]>:after,.fileoperations[class*=fb-][class*=-parent]>:before,.fileselection[class*=fb-][class*=-parent]:after,.fileselection[class*=fb-][class*=-parent]:before,.fileselection[class*=fb-][class*=-parent]>:after,.fileselection[class*=fb-][class*=-parent]>:before,.row[class*=fb-][class*=-parent]:after,.row[class*=fb-][class*=-parent]:before,.row[class*=fb-][class*=-parent]>:after,.row[class*=fb-][class*=-parent]>:before{content:none}.breadcrumb>li+li:before{content:'\00a0 /'}.breadcrumb>li>.active,.breadcrumb>li>.selectedcrumb{color:#777777}#gallerynav .btn:active,.SiteSearch [type=submit]:active,.addnewtemplate>a[id*=_lnkAddNew]:active,.ec-next-prev a:active,.eventNextPrevious:active,.fileinput-button:active,.newpost:active,.newthread:active,.poll [id*=_lnkNewPoll]:active,.search-button:active,.ui-datepicker-trigger:active,.uploadfilelist .ui-button:active,[id*=PasswordRecovery][id*=SubmitButton]:active{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,0.125);box-shadow:inset 0 3px 5px rgba(0,0,0,0.125)}#gallerynav .btn,.SiteSearch [type=submit],.addnewtemplate>a[id*=_lnkAddNew],.btn-default,.ec-next-prev a,.eventNextPrevious,.fileinput-button,.newpost,.newthread,.poll [id*=_lnkNewPoll],.search-button,.ui-datepicker-trigger,.uploadfilelist .ui-button,[id*=PasswordRecovery][id*=SubmitButton]{background-image:-webkit-gradient(linear,left top,left bottom,from(#fff),to(#f5f5f5));background-image:linear-gradient(to bottom,#fff 0%,#f5f5f5 100%);background-repeat:repeat-x;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075);box-shadow:inset 0 1px 0 rgba(255,255,255,0.15),0 1px 1px rgba(0,0,0,0.075);text-shadow:0 1px 0 #fff}#gallerynav .btn:active,#gallerynav .btn:active:focus,#gallerynav .btn:active:hover,.SiteSearch [type=submit]:active,.SiteSearch [type=submit]:active:focus,.SiteSearch [type=submit]:active:hover,.addnewtemplate>a[id*=_lnkAddNew]:active,.addnewtemplate>a[id*=_lnkAddNew]:active:focus,.addnewtemplate>a[id*=_lnkAddNew]:active:hover,.btn-default:active,.btn-default:active:focus,.btn-default:active:hover,.ec-next-prev a:active,.ec-


                    };

                    good.insert(
                        splits[0].to_string(),
                        Value::Number(serde_json::Number::from(order_id)),
                    );
                    good.insert(
                        "count".to_string(),
                        Value::Number(serde_json::Number::from(value)),
                    );
                    goods.push(Value::Object(good));
                } else {
                    json.insert(key, Value::String(value));
                }
            }
        }

        i += 2;
    }

    json.insert("goods".to_string(), Value::Array(goods));
    Some(json)
}

pub fn get_orders(
    req: HttpRequest,
    user_id: web::Path<String>,
    db: web::Data<r2d2::Pool<RedisConnectionManager>>,
) -> HttpResponse {
    let query = qstring::QString::from(req.query_string());
    let limit = match query.get("limit") {
        Some(limit) if limit.parse::<i64>().unwrap_or(100) > 0 => limit,
        _ => "100",
    };

    let mut conn = match db.get() {
        Ok(conn) => conn,
        Err(e) => {
            error!("{}:Couldn't get connection to database: {}", line!(), e);
            return HttpResponse::InternalServerError().finish();
        }
    };

    let key_matcher = &format!("user_id:{}:order_id:*", user_id);

    let result = match redis::cmd("SCAN")
        .cursor_arg(0)
        .arg(&["MATCH", key_matcher, "COUNT", &limit])
        .query::<Vec<redis::Value>>(conn.deref_mut())
    {
        Ok(r) => r,
        Err(e) => {
            error!(
                "{}:Error happened on cmd to redis 'SCAN 0 MATCH {} COUNT ': {}",
                key_matcher, limit, e
            );
            return HttpResponse::InternalServerError().finish();
        }
    };

    let mut pipe = redis::pipe();
    let mut keys = Vec::new();

    for x in result {
        match x {
            redis::Value::Bulk(data) => {
                for x in data {
                    if let redis::Value::Data(s) = x {
                        let key = match String::from_utf8(s) {
                            Ok(s) => s,
                            Err(e) => {
                                error!("{}:Couldn't deserialize redis answer: {}", line!(), e);
                                return HttpResponse::InternalServerError().finish();
                            }
                        };

                        pipe.cmd("HGETALL").arg(&key);

                        let values: Vec<&str> = key.split(":").collect();

                        if let Some(key) = values.last() {
                            match key.parse::<u32>() {
                                Ok(key) => {
                                    keys.push(key);
                                }
                                Err(e) => {
                                    error!("{}:Couldn't convert string to number: {}", line!(), e);
                                    return HttpResponse::InternalServerError().finish();
                                }
                            }
                        }
                    }
                }
            }
            _ => (),
        }
    }

    let items: redis::Value = match pipe.query(conn.deref_mut()) {
        Ok(x) => x,
        Err(e) => {
            error!("{}:Couldn't execute redis pipeline request: {}", line!(), e);
            return HttpResponse::InternalServerError().finish();
        }
    };

    if let redis::Value::Bulk(data) = items {
        let mut result: Vec<Map<String, Value>> = Vec::new();

        for x in data {
            if let redis::Value::Bulk(bulk) = x {
                if let S


Buffer) WriteTo(w io.Writer) (int64, error) {
	n, err := w.Write(b.Bytes)
	return int64(n), err
}

// Buffer pool
var bufpool = sync.Pool{
	New: func() interface{} { return &Buffer{} },
}

// NewBufferFromPool returns a pointer to a zerod Buffer. This may be retrieved from a
// pool. When you're done with it, call 'ReturnToPool'.
func NewBufferFromPool() *Buffer {
	b := bufpool.Get().(*Buffer)
	b.Reset()
	return b
}

// NewBufferFromPoolWithCap returns a pointer to a zero'd Buffer with its underlying
// capacity set. This may be retrieved from a pool. When you're done with it, call 'ReturnToPool'.
func NewBufferFromPoolWithCap(size int) *Buffer {
	b := bufpool.Get().(*Buffer)

	if c := cap(b.Bytes); c < size {
		b.Bytes = make([]byte, 0, size)
	} else if c > 0 {
		b.Reset()
	}

	return b
}

// ReturnToPool puts this instance back in the underlying pool. Reading from or using this instance
// in any way after calling this is invalid.
func (b *Buffer) ReturnToPool() {
	bufpool.Put(b)
}
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/tidwall/evio"
)

func main() {
	// var pduplicates, puniques int
	// var ticks int
	// var logidx int
	// var requests int
	var events evio.Events
	streams := make(map[int]*evio.InputStream)
	// numbers := make(map[int]int)

	for i := 0; ; i++ {
		if err := os.Remove(fmt.Sprintf("data.%d.log", i)); err != nil {
			if os.IsNotExist(err) {
				break
			}
			log.Fatal(err)
		}
	}
	f, err := os.Create("data.0.log")
	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	events.Opened = func(id int, _ evio.Info) (_ []byte, _ evio.Options, action evio.Action) {
		if len(streams) == 6 {
			action = evio.Close
		} else {
			streams[id] = new(evio.InputStream)
		}
		return
	}
	events.Closed = func(id int, _ error) (_ evio.Action) {
		delete(streams, id)
		return
	}
	events.Data = func(id int, in []byte) (out []byte, action evio.Action) {
		s := streams[id]
		data := s.Begin(in)
		f.Write(data)
		// nextLine:
		// 	if len(data) >= 8 && data[0] == 's' && string(data[:8]) == "shutdown" {
		// 		log.Printf("shutdown received")
		// 		return nil, evio.Shutdown
		// 	}
		// 	var number int
		// 	for i, j := 0, 0; i < len(data); i++ {
		// 		switch {
		// 		default:
		// 			number, j = number*10+int(data[i]-'0'), j+1

		// 		case data[i] == '\r' && i < len(data)-1 && data[i+1] == '\n':
		// 			i++
		// 			fallthrough
		// 		case data[i] == '\n':
		// 			n := len(numbers)
		// 			numbers[number]++
		// 			if n ==


[ii] + "  " + ends[ii];
            assertEquals(SearchCommand.ResultType.LOCUS, cmd.checkTokenType(tstr));
        }

        String[] errors = {"egfr:1-100", "   ", "chr1\t1\t100\tchr2"};
        for (String s : errors) {
            //System.out.println(s);
            assertEquals(SearchCommand.ResultType.ERROR, cmd.checkTokenType(s));
        }
    }

    @Test
    public void testMutationSearch() throws Exception {

        String name = "EGFR";
        // EGFR starts with proteins MRPSG
        String[] symbols = new String[]{"M", "R", "P", "S", "G"};
        //All of these should be possible with a SNP from the EGFR sequence
        String[] muts = new String[]{"I", "R", "P", "P", "R"};
        Map<Integer, BasicFeature> matches;
        List<NamedFeature> possibles = genome.getFeatureDB().getFeaturesMatching(name);
        for (int ii = 0; ii < symbols.length; ii++) {
            matches = SearchCommand.getMutationAA(possibles, ii + 1, symbols[ii], muts[ii], genome);
            assertEquals(1, matches.size());
            for (int pos : matches.keySet()) {
                assertEquals(name, matches.get(pos).getName());
            }
        }

        name = "EGFLAM";
        int exp_start = 38439399;
        possibles = genome.getFeatureDB().getFeaturesMatching(name);
        matches = SearchCommand.getMutationAA(possibles, 2, "H", "H", genome);
        assertEquals(1, matches.size());
        for (int geneloc : matches.keySet()) {
            assertEquals(exp_start, matches.get(geneloc).getStart());
        }

        String[] others = new String[]{"I", "M", "T"};
        for (String c : others) {
            matches = SearchCommand.getMutationAA(possibles, 2, "H", c, genome);
            assertEquals(0, matches.size());
        }
    }

    @Test
    public void testMutationSearchNegStrand() throws Exception {
        String name = "KRAS";
        int exp_start = 25249446;
        List<NamedFeature> possibles = genome.getFeatureDB().getFeaturesMatching(name);
        Map<Integer, BasicFeature> matches =SearchCommand.getMutationAA(possibles, 1, "M", "I", genome);
        assertEquals(1, matches.size());
        for (int geneloc : matches.keySet()) {
            assertEquals(exp_start, matches.get(geneloc).getStart());
        }

    }

    @Test
    public void testMutationSearchFail() throws Exception {
        String name = "EGFR";
        String[] symbols = "R,P,S,G,M".split(",");
        List<NamedFeature> possibles = genome.getFeatureDB().getFeaturesMatching(name);
        for (int ii = 0; ii < symbols.length; ii++) {
            Map<Integer, BasicFeature>  matches = SearchCommand.getMutationAA(possibles, ii + 1, symbols[ii], "M", genome);
            assertEquals(0, matches.size());
        }
    }

    @Test
    public void testMutationSearchNT() throws Exception {
        String name = "EGFR";
        String[] bps = new String[]{"A", "T", "G"};
        List<NamedFeature> possibles = genome.getFeatureDB().getFeaturesMatching(name);
        for (int ii = 0; ii < bps.length; ii++) {
            Map<Integer, BasicFeature> matches = SearchCommand.getMutationNT(possibles, ii + 1, bps[ii], genome);
            assertEquals(1, matches.size());
        }
    }

    @Test
    public void testMutationSearchNTNegStrand() throws Exception {
        String name = "KRAS";
        String[] bps = new String[]{"A", "T", "G"};
        List<NamedFeature> possibles = genome.getFeatureDB().getFeaturesMatching(name);

        for (int ii = 0; ii < bps.length; ii++) {
            Map<Integer,


            + "date_trunc('YEAR', date '2011-2-2') as DATE2 "
            + "from cp.\"employee.json\" where employee_id < 2";

    LocalDateTime time1 = formatTime.parseLocalDateTime("2:30:00.0");
    LocalDateTime time2 = formatTime.parseLocalDateTime("2:30:21.0");
    LocalDateTime ts1 = formatTimeStampMilli.parseLocalDateTime("1991-05-05 10:00:00.0");
    LocalDateTime ts2 = formatTimeStampMilli.parseLocalDateTime("1991-05-05 10:11:12.0");
    LocalDateTime date1 = formatDate.parseLocalDateTime("2011-02-01");
    LocalDateTime date2 = formatDate.parseLocalDateTime("2011-01-01");

    testBuilder()
        .sqlQuery(query)
        .unOrdered()
        .baselineColumns("TIME1", "TIME2", "TS1", "TS2", "DATE1", "DATE2")
        .baselineValues(time1, time2, ts1, ts2, date1, date2)
        .go();
  }

  @Test // DX-8689
  public void testDateTruncMultipleRows() throws Exception {
    String query =
        "SELECT date_trunc('QUARTER', dateCol) as res FROM (values"
            + "(date '2017-06-14'),"
            + "(date '2017-06-14'),"
            + "(date '2000-04-04'),"
            + "(date '2005-02-01'),"
            + "(date '2015-11-01'),"
            + "(cast(null as date))) as t(dateCol)";

    testBuilder()
        .sqlQuery(query)
        .unOrdered()
        .baselineColumns("res")
        .baselineValues(formatDate.parseLocalDateTime("2017-04-01"))
        .baselineValues(formatDate.parseLocalDateTime("2017-04-01"))
        .baselineValues(formatDate.parseLocalDateTime("2000-04-01"))
        .baselineValues(formatDate.parseLocalDateTime("2005-01-01"))
        .baselineValues(formatDate.parseLocalDateTime("2015-10-01"))
        .baselineValues(new Object[] {null})
        .go();
  }

  @Test
  public void testDateTruncOnStrings() throws Exception {
    String query =
        "SELECT date_trunc('QUARTER', dateCol) as res FROM (values"
            + "('2017-06-14'),"
            + "('2017-06-14 12:28:33')) as t(dateCol)";

    testBuilder()
        .sqlQuery(query)
        .unOrdered()
        .baselineColumns("res")
        .baselineValues(formatDate.parseLocalDateTime("2017-04-01"))
        .baselineValues(formatDate.parseLocalDateTime("2017-04-01"))
        .go();
  }
}
/*
 * Copyright (C) 2017-2019 Dremio Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dremio.exec.planner.sql;

import com.dremio.PlanTestBase;
import com.dremio.exec.planner.physical.PlannerSettings;
import org.junit.Test;

public class TestAliasExpansion extends PlanTestBase {

  @Test
  public void testSimpleAliasExpansionForWhereClause() throws Exception {
    try (AutoCloseable c = withOption(PlannerSettings.EXTENDED_ALIAS, true)) {
      String query = "SELECT c_custkey AS c FROM cp.tpch.\"customer.parquet\" WHERE c = 3 ";
      testBuilde


 (typeof def === 'function' && def.cid === undefined) {
        hasAsync = true
        pending++

        const resolve = once(resolvedDef => {
          if (isESModule(resolvedDef)) {
            resolvedDef = resolvedDef.default
          }
          def.resolved = typeof resolvedDef === 'function'
            ? resolvedDef
            : _Vue.extend(resolvedDef)
          match.components[key] = resolvedDef
          pending--
          if (pending <= 0) {
            next()
          }
        })

        const reject = once(reason => {
          const msg = `Failed to resolve async component ${key}: ${reason}`
          process.env.NODE_ENV !== 'production' && warn(false, msg)
          if (!error) {
            error = isError(reason)
              ? reason
              : new Error(msg)
            next(error)
          }
        })

        let res
        try {
          res = def(resolve, reject)
        } catch (e) {
          reject(e)
        }
        if (res) {
          if (typeof res.then === 'function') {
            res.then(resolve, reject)
          } else {
            const comp = res.component
            if (comp && typeof comp.then === 'function') {
              comp.then(resolve, reject)
            }
          }
        }
      }
    })

    if (!hasAsync) next()
  }
}
```

`resolveAsyncComponents` 返回的是一个导航守卫函数，有标准的 `to`、`from`、`next` 参数。它的内部实现很简单，利用了 `flatMapComponents` 方法从 `matched` 中获取到每个组件的定义，判断如果是异步组件，则执行异步组件加载逻辑，这块和我们之前分析 `Vue` 加载异步组件很类似，加载成功后会执行 ` match.components[key] = resolvedDef` 把解析好的异步组件放到对应的 `components` 上，并且执行 `next` 函数。

这样在 `resolveAsyncComponents(activated)` 解析完所有激活的异步组件后，我们就可以拿到这一次所有激活的组件。这样我们在做完这 5 步后又做了一些事情：

```js
runQueue(queue, iterator, () => {
  const postEnterCbs = []
  const isValid = () => this.current === route
  const enterGuards = extractEnterGuards(activated, postEnterCbs, isValid)
  const queue = enterGuards.concat(this.router.resolveHooks)
  runQueue(queue, iterator, () => {
    if (this.pending !== route) {
      return abort()
    }
    this.pending = null
    onComplete(route)
    if (this.router.app) {
      this.router.app.$nextTick(() => {
        postEnterCbs.forEach(cb => { cb() })


       /**< LPI data */
   SCIP_TREE*            tree,               /**< tree data */
   SCIP_AGGRROW*         farkasrow,          /**< aggregated row representing the proof */
   SCIP_Real*            farkasact,          /**< maximal activity of the proof constraint */
   int*                  validdepth,         /**< pointer to store the valid depth of the proof constraint */
   SCIP_Real*            curvarlbs,          /**< current lower bounds of active problem variables */
   SCIP_Real*            curvarubs,          /**< current upper bounds of active problem variables */
   SCIP_Bool*            valid               /**< pointer store whether the proof constraint is valid */
   );

/** calculates a dual proof from the current dual LP solution */
SCIP_RETCODE SCIPgetDualProof(
   SCIP_SET*             set,                /**< global SCIP settings */
   SCIP_PROB*            transprob,          /**< transformed problem */
   SCIP_LP*              lp,                 /**< LP data */
   SCIP_LPI*             lpi,                /**< LPI data */
   SCIP_TREE*            tree,               /**< tree data */
   SCIP_AGGRROW*         farkasrow,          /**< aggregated row representing the proof */
   SCIP_Real*            farkasact,          /**< maximal activity of the proof constraint */
   int*                  validdepth,         /**< pointer to store the valid depth of the proof constraint */
   SCIP_Real*            curvarlbs,          /**< current lower bounds of active problem variables */
   SCIP_Real*            curvarubs,          /**< current upper bounds of active problem variables */
   SCIP_Bool*            valid               /**< pointer store whether the proof constraint is valid */
   );

/** calculates the minimal activity of a given aggregation row
 *
 *  @note in exact solving mode, this returns a safe underestimation of the minimal activity
 */
SCIP_Real SCIPaggrRowGetMinActivity(
   SCIP_SET*             set,                /**< global SCIP settings */
   SCIP_PROB*            transprob,          /**< transformed problem data */
   SCIP_AGGRROW*         aggrrow,            /**< aggregation row */
   SCIP_Real*            curvarlbs,          /**< current lower bounds of active problem variables (or NULL for global bounds) */
   SCIP_Real*            curvarubs,          /**< current upper bounds of active problem variables (or NULL for global bounds) */
   SCIP_Bool*            infdelta            /**< pointer to store whether at least one variable contributes with an infinite value */
   );
#ifdef __cplusplus
}
#endif

#endif


si), %ecx
        addl $4, %esi
        imull %ecx
        movl %eax, (%esi)
        ret
END_WORD(times)

BUILTIN_WORD_NAME(plus, "+")
        movl (%esi), %eax
        addl $4, %esi
        addl %eax, (%esi)
        ret
END_WORD(plus)

BUILTIN_WORD_NAME(minus, "-")
        movl (%esi), %eax
        addl $4, %esi
        subl %eax, (%esi)
        ret
END_WORD(minus)

BUILTIN_WORD_NAME(divide, "/")
        movl 4(%esi), %eax
        cdq
        idivl (%esi)
	addl $4, %esi
        movl %eax, (%esi)
        ret
END_WORD(divide)

BUILTIN_WORD_NAME(udivide, "u/")
        xorl %edx, %edx
        movl 4(%esi), %eax
        divl (%esi)
	addl $4, %esi
        movl %eax, (%esi)
        ret
END_WORD(udivide)

BUILTIN_WORD(mod)
        movl 4(%esi), %eax
        cdq
        idivl (%esi)
        addl $4, %esi
        movl %edx, (%esi)
        ret
END_WORD(mod)

BUILTIN_WORD(and)
        movl (%esi), %eax
        andl %eax, 4(%esi)
        addl $4, %esi
        ret
END_WORD(and)

BUILTIN_WORD(or)
        movl (%esi), %eax
        orl %eax, 4(%esi)
        addl $4, %esi
        ret
END_WORD(or)

BUILTIN_WORD(xor)
        movl (%esi), %eax
        xorl %eax, 4(%esi)
        addl $4, %esi
        ret
END_WORD(xor)

BUILTIN_WORD(invert)
        notl (%esi)
        ret
END_WORD(invert)

/* u n -- u */
BUILTIN_WORD(lshift)
        movl (%esi), %ecx
        addl $4, %esi
        shll %cl, (%esi)
        ret
END_WORD(lshift)

/* u n -- u */
BUILTIN_WORD(rshift)
        movl (%esi), %ecx
        addl $4, %esi
        shrl %cl, (%esi)
        ret
END_WORD(rshift)

BUILTIN_WORD_NAME(two_times, "2*")
        sall $1, (%esi)
        ret
END_WORD(two_times)

BUILTIN_WORD_NAME(two_divides, "2/")
        sarl $1, (%esi)
        ret
END_WORD(two_divides)

BUILTIN_WORD_ENTRY(to_r, ">r", F_COMPILE_TIME)
        /* Skip the stored %eip. */
        movl (%esi), %eax
        addl $4, %esi
        movl %esp, %ebp
	subl $4, %esp
        movl (%ebp), %edx
        movl %edx, -4(%ebp)
        movl %eax,   (%ebp)
        ret
END_WORD(to_r)

BUILTIN_WORD_ENTRY(r_from, "r>", F_COMPILE_TIME)
        subl $4, %esi
        movl 4(%esp), %eax
        movl %eax, (%esi)
        movl (%esp), %ebx
        movl %ebx, 4(%esp)
        addl $4, %esp
        ret
END_WORD(r_from)

BUILTIN_WORD_ENTRY(r_fetch, "r@", F_COMPILE_TIME)
        movl 4(%esp), %eax
        subl $4, %esi
        movl %eax, (%esi)
        ret
END_


SOUND_MIDIDRIVER = MAKE_MENUOPTION( &MF_Redfont, &MEOS_SOUND_MIDIDRIVER, &musicdevice );
static MenuEntry_t ME_SOUND_MIDIDRIVER = MAKE_MENUENTRY( "MIDI driver:", &MF_Redfont, &MEF_BigOptionsRt, &MEO_SOUND_MIDIDRIVER, Option );

static MenuLink_t MEO_SOUND_DEVSETUP = { MENU_SOUND_DEVSETUP, MA_Advance, };
static MenuEntry_t ME_SOUND_DEVSETUP = MAKE_MENUENTRY( "Device configuration", &MF_Redfont, &MEF_BigOptionsRt, &MEO_SOUND_DEVSETUP, Link );

static MenuLink_t MEO_SOUND_SF2 = { MENU_SOUND_SF2, MA_Advance, };
static MenuEntry_t ME_SOUND_SF2 = MAKE_MENUENTRY( sf2bankfile, &MF_Redfont, &MEF_BigOptionsRtSections, &MEO_SOUND_SF2, Link );
#endif

static MenuEntry_t ME_SOUND_RESTART = MAKE_MENUENTRY( "Apply Changes", &MF_Redfont, &MEF_BigOptions_Apply, &MEO_NULL, Link );

static MenuEntry_t *MEL_SOUND[] = {
    &ME_SOUND,
    &ME_SOUND_VOLUME_MASTER,
    &ME_SOUND_VOLUME_FX,
    &ME_SOUND_VOLUME_VOICE,
    &ME_SOUND_MUSIC,
    &ME_SOUND_VOLUME_MUSIC,
    &ME_SOUND_DUKETALK,
#ifndef EDUKE32_RETAIL_MENU
    &ME_SOUND_DEVSETUP,
#endif
};

static MenuEntry_t *MEL_SOUND_DEVSETUP[] = {
    &ME_SOUND_SAMPLINGRATE,
#ifndef EDUKE32_RETAIL_MENU
    &ME_SOUND_NUMVOICES,
    &ME_SOUND_MIDIDRIVER,
#ifdef __linux__
    &ME_SOUND_ALSADEVICE,
#endif
    &ME_SOUND_OPL3AMP,
    &ME_SOUND_OPL3STEREO,
    &ME_SOUND_SF2,
#ifdef FORMAT_UPGRADE_ELIGIBLE
    &ME_SOUND_EXTMUSIC,
#endif
#endif
    &ME_Space4_Redfont,
    &ME_SOUND_RESTART,
};

static MenuOption_t MEO_SAVESETUP_AUTOSAVE = MAKE_MENUOPTION( &MF_Redfont, &MEOS_OffOn, &ud.autosave );
static MenuEntry_t ME_SAVESETUP_AUTOSAVE = MAKE_MENUENTRY( "Checkpoints:", &MF_Redfont, &MEF_BigOptionsRt, &MEO_SAVESETUP_AUTOSAVE, Option );

static MenuOption_t MEO_SAVESETUP_AUTOSAVEDELETION = MAKE_MENUOPTION( &MF_Redfont, &MEOS_NoYes, &ud.autosavedeletion );
static MenuEntry_t ME_SAVESETUP_AUTOSAVEDELETION = MAKE_MENUENTRY( "Auto-Delete:", &MF_Redfont, &MEF_BigOptions_Apply, &MEO_SAVESETUP_AUTOSAVEDELETION, Option );
static MenuRangeInt32_t MEO_SAVESETUP_MAXAUTOSAVES = MAKE_MENURANGE( &ud.maxautosaves, &MF_Redfont, 1, 10, 0, 10, DisplayTypeInteger );
static MenuEntry_t ME_SAVESETUP_MAXAUTOSAVES = MAKE_MENUENTRY( "Limit:", &MF_Redfont, &MEF_BigOptions_Apply, &MEO_SAVESETUP_MAXAUTOSAVES, RangeInt32 );

static MenuEntry_t ME_SAVESETUP_CLEANUP = MAKE_MENUENTRY


oken.LABEL: const ObjectValidator<String>(defaultValue: ''),
            Token.ISSUER: const ObjectValidator<String>(defaultValue: ''),
            OTPToken.SECRET_BASE32: ObjectValidator<String>(transformer: (v) => Encodings.base32.encodeStringTo(Encodings.base32, v)),
            OTPToken.ALGORITHM: const ObjectValidatorNullable<String>(),
            OTPToken.DIGITS: intToStringValidatorNullable,
            TOTPToken.PERIOD_SECONDS: intToStringValidatorNullable,
            HOTPToken.COUNTER: intToStringValidatorNullable,
            Token.PIN: const ObjectValidatorNullable<String>(),
          },
          name: 'aegisV3Entry',
        );
        results.add(
          ProcessorResult.success(
            Token.fromOtpAuthMap(
              otpAuthMap,
              additionalData: {
                Token.ORIGIN: TokenOriginSourceType.backupFile.toTokenOrigin(
                  originName: TokenImportOrigins.aegisAuthenticator.appName,
                  isPrivacyIdeaToken: false,
                  data: jsonEncode(entry),
                ),
              },
            ),
            resultHandlerType: resultHandlerType,
          ),
        );
      } on LocalizedException catch (e) {
        results.add(ProcessorResultFailed((localization) => e.localizedMessage(localization), resultHandlerType: resultHandlerType));
      } catch (e) {
        Logger.error('Failed to parse token.', error: e, stackTrace: StackTrace.current);
        results.add(ProcessorResultFailed((_) => e.toString(), resultHandlerType: resultHandlerType));
      }
    }

    return Future.value(results);
  }

  Future<Uint8List> runIsolatedKdf(ScryptParameters scryptParameters, String password) async {
    final receivePort = ReceivePort();
    try {
      Isolate.spawn(_isolatedKdf, [receivePort.sendPort, scryptParameters, password]);
    } catch (e) {
      receivePort.close();
    }
    final Uint8List keyBytes = await receivePort.first;
    return keyBytes;
  }

  Future<List<ProcessorResult<Token>>> _processEncrypted(Map<String, dynamic> json, String? password) async {
    final String dbEncrypted = json[AEGIS_JSON_DB];
    final Map<String, dynamic> header = json[AEGIS_JSON_HEADER];
    final Map<String, dynamic> headerParams = header[AEGIS_HEADER_HEADERPARAMS];
    final Map<String, dynamic> slot = header[AEGIS_HEADER_SLOTS].first;
    final Map<String, dynamic> keyParams = slot[AEGIS_SLOT_KEYPARAMS];

    final passwordKeyBytes = await runIsolatedKdf(
      ScryptParameters(slot[AEGIS_SLOT_N], slot[AEGIS_SLOT_R], slot[AEGIS_SLOT_P], 32, decodeHexString(slot[AEGIS_SLOT_SALT])),
      password!,
    );
    final slotNonceBytes = decodeHexString(keyParams[AEGIS_KEYPARAMS_NONCE]);
    final cipher = crypto.AesGcm.with256bits(nonceLength: slotNonceBytes.length);
    final List<int> masterKeyBytes;

    try {
      masterKeyBytes = await cipher.decrypt(
        crypto.SecretBox(decodeHexString(slot[AEGIS_SLOT_KEY]), nonce: slotNonceBytes, mac: crypto.Mac(decodeHexString(keyParams[AEGIS_KEYPARAMS_TAG]))),
        secretKey: crypto.SecretKey(passwordKeyBytes),
      );
    } catch (e) {
      throw BadDecryptionPasswordException('Wrong password or corrupted data');
    }
    final dbDecryptedBytes = await cipher.decrypt(
      crypto.SecretBox(
        base64Decode(dbEncrypted),
        nonce: decodeHexString(headerParams[


eld F2m
//         * (having the same representation).
//         * @param a field element.
//         * @param b field element to be compared.
//         * @throws IllegalArgumentException if a and b
//         * are not elements of the same field
//         * F2m (having the same
//         * representation).
//         */
//        public static void checkFieldElements(
//            ECFieldElement a,
//            ECFieldElement b)
//        {
//            if ((!(a instanceof F2m)) || (!(b instanceof F2m)))
//            {
//                throw new IllegalArgumentException("Field elements are not "
//                        + "both instances of ECFieldElement.F2m");
//            }
//
//            if ((a.toBigInteger().signum() < 0) || (b.toBigInteger().signum() < 0))
//            {
//                throw new IllegalArgumentException(
//                        "x value may not be negative");
//            }
//
//            ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a;
//            ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b;
//
//            if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1)
//                    || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3))
//            {
//                throw new IllegalArgumentException("Field elements are not "
//                        + "elements of the same field F2m");
//            }
//
//            if (aF2m.representation != bF2m.representation)
//            {
//                // Should never occur
//                throw new IllegalArgumentException(
//                        "One of the field "
//                                + "elements are not elements has incorrect representation");
//            }
//        }
//
//        /**
//         * Computes z * a(z) mod f(z), where f(z) is
//         * the reduction polynomial of this.
//         * @param a The polynomial a(z) to be multiplied by
//         * z mod f(z).
//         * @return z * a(z) mod f(z)
//         */
//        private BigInteger multZModF(final BigInteger a)
//        {
//            // Left-shift of a(z)
//            BigInteger az = a.shiftLeft(1);
//            if (az.testBit(this.m))
//            {
//                // If the coefficient of z^m in a(z) equals 1, reduction
//                // modulo f(z) is performed: Add f(z) to to a(z):
//                // Step 1: Unset mth coeffient of a(z)
//                az = az.clearBit(this.m);
//
//                // Step 2: Add r(z) to a(z), where r(z) is defined as
//                // f(z) = z^m + r(z), and k1, k2, k3 are the positions of
//                // the non-zero coefficients in r(z)
//                az = az.flipBit(0);
//                az = az.flipBit(this.k1);
//                if (this.representation == PPB)
//                {
//                    az = az.flipBit(this.k2);
//                    az = az.flipBit(this.k3);
//                }
//            }
//            return az;
//        }
//
//        public ECFieldElement add(final ECFieldElement b)
//        {
//            // No check performed


        );
      case 1:
        return ChangeNotifierProvider.value(
          value: _trainingViewModel,
          child: PlanGeneratorPage(
            userInfo: _userInfoViewModel.currentUser,
            showAppBar: false,
            onPlanGenerated: (planId) async {
              await _trainingViewModel.selectTrainingPlan(planId);
              if (!mounted) return;
              // 导航到计划详情页面
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder:
                      (context) => ChangeNotifierProvider.value(
                        value: _trainingViewModel,
                        child: PlanDetailPage(
                          showAppBar: true,
                          onSwitchToStatistics: () {
                            setState(() {
                              _currentIndex = 2; // 切换到统计页面
                            });
                          },
                        ),
                      ),
                ),
              );
            },
          ),
        );
      case 2:
        return ChangeNotifierProvider.value(
          value: _trainingViewModel,
          child: TrainingStatisticsPage(
            userId: _userInfoViewModel.currentUser?.userId ?? '',
            showAppBar: false,
          ),
        );

      default:
        return const Center(child: Text('未知页面'));
    }
  }
}
import 'package:flutter/material.dart';

import '../../../../core/entities/cus_llm_model.dart';
import '../../../../core/entities/user_info.dart';
import '../../data/services/training_assistant_service.dart';
import '../../data/training_dao.dart';
import '../../domain/entities/training_plan.dart';
import '../../domain/entities/training_plan_detail.dart';
import '../../domain/entities/training_record.dart';
import '../../domain/entities/training_record_detail.dart';

class TrainingViewModel extends ChangeNotifier {
  final TrainingDao _trainingDao = TrainingDao();
  final TrainingAssistantService _trainingService = TrainingAssistantService();

  // 当前选中的训练计划
  TrainingPlan? _selectedPlan;
  TrainingPlan? get selectedPlan => _selectedPlan;

  // 当前计划的详情
  List<TrainingPlanDetail> _planDetails = [];
  List<TrainingPlanDetail> get planDetails => _planDetails;

  // 当前用户的所有训练计划
  List<TrainingPlan> _userPlans = [];
  List<TrainingPlan> get userPlans => _userPlans;

  // 当前用户的活跃训练计划
  List<TrainingPlan> _activePlans = [];
  List<TrainingPlan> get activePlans => _activePlans;

  // 当前计划的训练记录
  List<TrainingRecord> _planRecords = [];
  List<TrainingRecord> get planRecords => _planRecords;

  // 状态管理
  bool _isLoading = false;
  bool get isLoading => _isLoading;

  String? _error;
  String? get error => _error;

  // 生成训练计划
  Future<void> generateTrainingPlan({
    required UserInfo userInfo,
    required String targetGoal,
    required List<String> targetMuscleGroups,
    required int duration,
    required String frequency,
    String? equipment,
    required CusLLMSpec model,
  }) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      final result = await _trainingService.generateTrainingPlan(
        userId: us


"Deep-Sleep Mode Clock Gating Control Register 1"]
pub mod dcgc1;
#[doc = "Deep Sleep Mode Clock Gating Control Register 2\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dcgc2](dcgc2) module"]
pub type DCGC2 = crate::Reg<u32, _DCGC2>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DCGC2;
#[doc = "`read()` method returns [dcgc2::R](dcgc2::R) reader structure"]
impl crate::Readable for DCGC2 {}
#[doc = "Deep Sleep Mode Clock Gating Control Register 2"]
pub mod dcgc2;
#[doc = "Deep Sleep Clock Configuration\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dslpclkcfg](dslpclkcfg) module"]
pub type DSLPCLKCFG = crate::Reg<u32, _DSLPCLKCFG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DSLPCLKCFG;
#[doc = "`read()` method returns [dslpclkcfg::R](dslpclkcfg::R) reader structure"]
impl crate::Readable for DSLPCLKCFG {}
#[doc = "`write(|w| ..)` method takes [dslpclkcfg::W](dslpclkcfg::W) writer structure"]
impl crate::Writable for DSLPCLKCFG {}
#[doc = "Deep Sleep Clock Configuration"]
pub mod dslpclkcfg;
#[doc = "System Properties\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sysprop](sysprop) module"]
pub type SYSPROP = crate::Reg<u32, _SYSPROP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SYSPROP;
#[doc = "`read()` method returns [sysprop::R](sysprop::R) reader structure"]
impl crate::Readable for SYSPROP {}
#[doc = "System Properties"]
pub mod sysprop;
#[doc = "Precision Internal Oscillator Calibration\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [piosccal](piosccal) module"]
pub type PIOSCCAL = crate::Reg<u32, _PIOSCCAL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _PIOSCCAL;
#[doc = "`read()` method returns [piosccal::R](piosccal::R) reader structure"]
impl crate::Readable for PIOSCCAL {}
#[doc = "`write(|w| ..)` method takes [piosccal::W](piosccal::W) writer structure"]
impl crate::Writable for PIOSCCAL {}
#[doc = "Precision Internal Oscillator Calibration"]
pub mod piosccal;
#[doc = "Precision Internal Oscillator Statistics\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](


/********************************************************************
Vireio Perception: Open-Source Stereoscopic 3D Driver
Copyright (C) 2012 Andres Hernandez

File <D3DProxyDevice.h> and
Class <D3DProxyDevice> :
Copyright (C) 2012 Andres Hernandez
Modifications Copyright (C) 2013 Chris Drain

Vireio Perception Version History:
v1.0.0 2012 by Andres Hernandez
v1.0.X 2013 by John Hicks, Neil Schneider
v1.1.x 2013 by Primary Coding Author: Chris Drain
Team Support: John Hicks, Phil Larkson, Neil Schneider
v2.0.x 2013 by Denis Reischl, Neil Schneider, Joshua Brown

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
********************************************************************/

#ifndef VIREIOPOPUP_H_INCLUDED
#define VIREIOPOPUP_H_INCLUDED

enum VireioPopupType
{
	VPT_NONE,
	//"splash screen" - shown when Vireio is first injected
	VPT_SPLASH_1,
	//Second "splash" - tells users a couple of helpful hot-keys
	VPT_SPLASH_2,
	VPT_NO_HMD_DETECTED,
	VPT_HMDINITFAIL,
	VPT_VRBOOST_FAILURE,
	VPT_VRBOOST_SCANNING,
	VPT_POSITION_TRACKING_LOST,
	VPT_NO_ORIENTATION,
	//Notification that is only dismissed once user has "calibrated HMD/Tracker"
	VPT_CALIBRATE_TRACKER,
	VPT_STATS,
	//Short notification, such as hot key toggles
	VPT_NOTIFICATION,
	//Short notification of valu adjustment, such as Y Offset, or IPD offset
	VPT_ADJUSTER
};

enum VireioPopupSeverity
{
	//A toast is a notification that is only shown for a short time, triggered by a toggle for exmample
	VPS_TOAST,
	//Information
	VPS_INFO,
	//An issue has occurred
	VPS_ERROR
};

struct VireioPopup
{
	VireioPopup(VireioPopupType type, VireioPopupSeverity sev = VPS_INFO, long duration = -1) :
		popupType(type),
		severity(sev),
		popupDuration(duration)
	{
		if (duration != -1)
			setDuration(duration);

		memset(line, 0, 7 * 256);
	}

	void setDuration(long duration_ms)
	{
		popupDuration = (long)GetTickCount() + duration_ms;
	}

	bool expired()
	{
		if (popupDuration != -1 &&
			((long)GetTickCount()) > popupDuration)
			return true;
		return false;
	}

	void reset()
	{
		popupType = VPT_NONE;
		popupDuration = -1;
		memset(line, 0, 7 * 256);
	}

	VireioPopupType popupType;
	VireioPopupSeverity severity;
	long popupDuration;
	char line[7][256];
};

#endif


    /// - `name` the name of the peer that sent the response
    fn notify_status(&self, files: Vec<String>, name: String);
    /// Notify if a file was changed in the local peer database or was downloaded
    fn local_database_changed(&mut self, name: String, instr: FileStatus);
    /// Notify the application that the player started playing
    /// # Parameters
    /// - `title`: The name of the song has started to play. `None` if streaming.
    fn player_playing(&mut self, title: Option<String>);
    /// Notify the application that the player has stopped (no other song in queue)
    fn player_stopped(&mut self);
}
use std::{convert::TryFrom, fs::File, io::Cursor};
use zen_archive::Vdfs;
use zen_model::{gltf, Model};
use zen_mrm::Mrm;
use zen_types::path::INSTANCE;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let vdf_file = File::open(INSTANCE.meshes())?;
    let vdf = Vdfs::new(vdf_file)?;
    let mesh_entry = vdf
        .get_by_name("ORC_MASTERTHRONE.MRM")
        .expect("Should be there!");
    let cursor = Cursor::new(mesh_entry.data);
    let mesh = Mrm::new(cursor, "ORC_MASTERTHRONE")?;
    let model = Model::try_from(mesh)?;
    for mesh in model.clone().meshes {
        println!("Material: {}", mesh.material);
        println!("Number Elements: {}", mesh.num_elements);
        println!("Indices Len: {}", mesh.indices.len());
        println!("Vertices Len: {}", mesh.vertices.len());
    }
    let _gltf = gltf::to_gltf(model.clone(), gltf::Output::Standard);
    let _gltf = gltf::to_gltf(model, gltf::Output::Binary);

    Ok(())
}
<reponame>stevebob/statecs
pub const ECS_CTX: &'static str = r#"

pub struct EcsCtx {
{{#each data_components}}
    {{name}}: EcsCtxEntityMap<{{type}}>,
{{/each}}

{{#each cell_components}}
    {{name}}: EcsCtxEntityMap<RefCell<{{type}}>>,
{{/each}}

{{#if combine_flag_set}}
    _flags: EcsCtxEntitySet,
{{else}}
    {{#each flag_components}}
    {{name}}: EcsCtxEntitySet,
    {{/each}}
{{/if}}
{{#if component_bookkeeping}}
    _components: EcsCtxEntityMap<ComponentSet>,
{{/if}}
}

impl EcsCtx {
    pub fn new() -> Self {
        EcsCtx {
{{#each data_components}}
            {{name}}: EcsCtxEntityMap::new(),
{{/each}}

{{#each cell_components}}
            {{name}}: EcsCtxEntityMap::new(),
{{/each}}

{{#if combine_flag_set}}
            _flags: EcsCtxEntitySet::new(),
{{else}}
    {{#each flag_components}}
            {{name}}: EcsCtxEntitySet::new(),
    {{/each}}
{{/if}}
{{#if component_bookkeeping}}
            _components: EcsCtxEntityMap::new(),
{{/if}}
        }
    }

    pub fn max_entity_id(&self) -> EntityId {
        {{entity_mask}}
    }

    pub fn entity(&self, id: EntityId) -> EntityRef {
        EntityRef {
            id: id,
            ecs: self,
        }
    }

    pub fn entity_mut(&mut self, id: EntityId) -> EntityRefMut {
        EntityRefMut {
            id: id


 %l5
mov %o1, %l5
mov %o2, %l5
mov %o3, %l5
mov %o4, %l5
! move %o5(lower) -> %o0(upper)
sllx %o5, 32, %o0
add  %l4, 1, %l4

P706: !ST [10] (maybe <- 0x1ae) (Int)
stw   %l4, [%i2 + 32 ]
add   %l4, 1, %l4

P707: !PREFETCH [5] (Int) (CBR)
prefetch [%i1 + 76], 1

! cbranch
andcc %l0, 1, %g0
be,pt  %xcc, TARGET707
nop
RET707:

! lfsr step begin
srlx %l0, 1, %o5
xnor %o5, %l0, %o5
sllx %o5, 63, %o5
or  %o5, %l0, %l0
srlx %l0, 1, %l0

P708: !CAS [5] (maybe <- 0x1af) (Int)
add %i1, 76, %l6
lduw [%l6], %o5
mov %o5, %l3
! move %l3(lower) -> %o0(lower)
or %l3, %o0, %o0
mov %l4, %o1
cas [%l6], %l3, %o1
! move %o1(lower) -> %o1(upper)
sllx %o1, 32, %o1
add   %l4, 1, %l4

P709: !PREFETCH [5] (Int)
prefetch [%i1 + 76], 1

P710: !DWST [8] (maybe <- 0x1b0) (Int)
mov %l4, %l3
sllx %l3, 32, %l3
stx %l3, [%i1 + 256 ]
add   %l4, 1, %l4

P711: !ST [12] (maybe <- 0x1b1) (Int)
stw   %l4, [%i3 + 0 ]
add   %l4, 1, %l4

P712: !PREFETCH [12] (Int)
prefetch [%i3 + 0], 1

P713: !CASX [15] (maybe <- 0x1b2) (Int) (LE)
! Change single-word-level endianess (big endian <-> little endian)
sethi %hi(0xff00ff00), %o5
or %o5, %lo(0xff00ff00), %o5
and %l4, %o5, %l7
srl %l7, 8, %l7
sll %l4, 8, %l3
and %l3, %o5, %l3
or %l3, %l7, %l3
srl %l3, 16, %l7
sll %l3, 16, %l3
srl %l3, 0, %l3
or %l3, %l7, %l3
wr %g0, 0x88, %asi
add %i3, 192, %o5
ldxa [%o5] %asi, %l6
! move %l6(lower) -> %o1(lower)
srl %l6, 0, %l7
or %l7, %o1, %o1
! move %l6(upper) -> %o2(upper)
or %l6, %g0, %o2
mov  %l6, %l7
mov  %l3, %l6
casxa [%o5] %asi, %l7, %l6
! move %l6(lower) -> %o2(lower)
srlx %o2, 32, %o2
sllx %o2, 32, %o2
srl %l6, 0, %o5
or %o5, %o2, %o2
! move %l6(upper) -> %o3(upper)


dWeapon = {
										2040051,
										2040111,
										2040121,
										2040131
									}
								},
								{
									switchParam = 28,
									switchTo = 2,
									index = 1,
									switchType = 1,
									removeWeapon = {
										2040051,
										2040111,
										2040121,
										2040131
									},
									addWeapon = {
										2040151,
										2040161,
										2040171,
										2040181,
										2040191,
										2040201
									}
								},
								{
									switchParam = 40,
									switchTo = 1,
									index = 2,
									switchType = 1,
									setAI = 100101,
									removeWeapon = {
										2040151,
										2040161,
										2040171,
										2040181,
										2040191,
										2040201
									},
									addWeapon = {
										2040301,
										2040311
									}
								}
							}
						}
					},
					airFighter = {
						{
							interval = 10,
							onceNumber = 6,
							formation = 10009,
							templateID = 2200901,
							delay = 0,
							totalNumber = 30,
							weaponID = {},
							attr = {
								airPower = 40,
								maxHP = 15,
								attackRating = 23
							}
						}
					}
				},
				{
					triggerType = 8,
					waveIndex = 900,
					preWaves = {
						101
					},
					triggerParams = {}
				}
			}
		}
	},
	fleet_prefab = {}
}


 {
        if (config.threadLocalHandshakes) {
            emitThreadLocalPoll(crb, asm, config, atReturn, state, thread, scratch);
        } else {
            emitGlobalPoll(crb, asm, config, atReturn, state, scratch);
        }
    }

    /**
     * Tests if the polling page address can be reached from the code cache with 32-bit
     * displacements.
     */
    private static boolean isPollingPageFar(GraalHotSpotVMConfig config) {
        final long pollingPageAddress = config.safepointPollingAddress;
        return config.forceUnreachable || !isInt(pollingPageAddress - config.codeCacheLowBound) || !isInt(pollingPageAddress - config.codeCacheHighBound);
    }

    private static void emitGlobalPoll(CompilationResultBuilder crb, AMD64MacroAssembler asm, GraalHotSpotVMConfig config, boolean atReturn, LIRFrameState state, Register scratch) {
        assert !atReturn || state == null : "state is unneeded at return";
        if (ImmutableCode.getValue(crb.getOptions())) {
            JavaKind hostWordKind = JavaKind.Long;
            int alignment = hostWordKind.getBitCount() / Byte.SIZE;
            JavaConstant pollingPageAddress = JavaConstant.forIntegerKind(hostWordKind, config.safepointPollingAddress);
            // This move will be patched to load the safepoint page from a data segment
            // co-located with the immutable code.
            if (GeneratePIC.getValue(crb.getOptions())) {
                asm.movq(scratch, asm.getPlaceholder(-1));
            } else {
                asm.movq(scratch, (AMD64Address) crb.recordDataReferenceInCode(pollingPageAddress, alignment));
            }
            final int pos = asm.position();
            crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
            if (state != null) {
                crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
            }
            asm.testl(rax, new AMD64Address(scratch));
        } else if (isPollingPageFar(config)) {
            asm.movq(scratch, config.safepointPollingAddress);
            crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
            final int pos = asm.position();
            if (state != null) {
                crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
            }
            asm.testl(rax, new AMD64Address(scratch));
        } else {
            crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_NEAR : config.MARKID_POLL_NEAR);
            final int pos = asm.position();
            if (state != null) {
                crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
            }
            // The C++ code transforms the polling page offset into an RIP displacement
            // to the real address at that offset in the polling page.
            asm.testl(rax, new AMD64Address(rip, 0));
        }
    }

    private static void emitThreadLocalPoll(CompilationResultBuilder crb, AMD64MacroAssembler asm, GraalHotSpotVMConfig config, boolean atReturn, LIRFrameState state, Register thread,
                    Register scratch) {
        assert !atReturn || state == null : "state is unneeded at return";

        assert config.threadPollingPageOffset >= 0;
        asm.movptr(scratch, new AMD64Address(thread, config.threadPollingPageOffset));
        crb.recordMark(atReturn ? config.MARKID_POLL_RETURN_FAR : config.MARKID_POLL_FAR);
        final int pos = asm.position();
        if (state != null) {
            crb.recordInfopoint(pos, state, InfopointReason.SAFEPOINT);
        }
        asm.testl(rax, new AMD64Address(scratch));
    }
}
/*
 * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This


from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup

from config import SUPPORT_CHAT

def botplaylist_markup(_):
    buttons = [
        [
            InlineKeyboardButton(text=_["S_B_9"], url=SUPPORT_CHAT),
            InlineKeyboardButton(text=_["CLOSE_BUTTON"], callback_data="close"),
        ],
    ]
    return buttons

def close_markup(_):
    upl = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton(
                    text=_["CLOSE_BUTTON"],
                    callback_data="close",
                ),
            ]
        ]
    )
    return upl

def supp_markup(_):
    upl = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton(
                    text=_["S_B_9"],
                    url=SUPPORT_CHAT,
                ),
            ]
        ]
    )
    return upl


  if (!opts::pretty::NoEnumDefs) {
    auto UnderlyingType = Symbol.getUnderlyingType();
    if (!UnderlyingType)
      return;
    if (UnderlyingType->getBuiltinType() != PDB_BuiltinType::Int ||
        UnderlyingType->getLength() != 4) {
      Printer << " : ";
      BuiltinDumper Dumper(Printer);
      Dumper.start(*UnderlyingType);
    }
    auto EnumValues = Symbol.findAllChildren<PDBSymbolData>();
    Printer << " {";
    Printer.Indent();
    if (EnumValues && EnumValues->getChildCount() > 0) {
      while (auto EnumValue = EnumValues->getNext()) {
        if (EnumValue->getDataKind() != PDB_DataKind::Constant)
          continue;
        Printer.NewLine();
        WithColor(Printer, PDB_ColorItem::Identifier).get()
            << EnumValue->getName();
        Printer << " = ";
        WithColor(Printer, PDB_ColorItem::LiteralValue).get()
            << EnumValue->getValue();
      }
    }
    Printer.Unindent();
    Printer.NewLine();
    Printer << "}";
  }
}
//===- MinimalSymbolDumper.cpp -------------------------------- *- C++ --*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MinimalSymbolDumper.h"

#include "FormatUtil.h"
#include "InputFile.h"
#include "LinePrinter.h"

#include "llvm/DebugInfo/CodeView/CVRecord.h"
#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/Formatters.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTable.h"
#include "llvm/Support/FormatVariadic.h"

using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::pdb;

static std::string formatLocalSymFlags(uint32_t IndentLevel,
                                       LocalSymFlags Flags) {
  std::vector<std::string> Opts;
  if (Flags == LocalSymFlags::None)
    return "none";

  PUSH_FLAG(LocalSymFlags, IsParameter, Flags, "param");
  PUSH_FLAG(LocalSymFlags, IsAddressTaken, Flags, "address is taken");
  PUSH_FLAG(LocalSymFlags, IsCompilerGenerated, Flags, "compiler generated");
  PUSH_FLAG(LocalSymFlags, IsAggregate, Flags, "aggregate");
  PUSH_FLAG(LocalSymFlags, IsAggregated, Flags, "aggregated");
  PUSH_FLAG(LocalSymFlags, IsAliased, Flags, "aliased");
  PUSH_FLAG(LocalSymFlags, IsAlias, Flags, "alias");
  PUSH_FLAG(LocalSymFlags, IsReturnValue, Flags, "return val");
  PUSH_FLAG(LocalSymFlags, IsOptimizedOut, Flags, "optimized away");
  PUSH_FLAG(LocalSymFlags, IsEnregisteredGlobal, Flags, "enreg global");
  PUSH_FLAG(LocalSymFlags, IsEnregisteredStatic, Flags, "enreg static");
  return typesetItemList(Opts, 4, IndentLevel, " | ");
}

static std::string formatExportFlags(uint32_t IndentLevel, ExportFlags Flags) {
  std::vector<std::string> Opts;
  if (Flags == ExportFlags::None)
    return "none";

  PUSH_FLAG(ExportFlags, IsConstant, Flags, "constant");
  PUSH_FLAG(ExportFlags, IsData, Flags, "data");
  PUSH_FLAG(ExportFlags, IsPrivate, Flags


this:ActionSafeCall(AmborHide)
    this:SpawnGadget(featherData.FeatherGadgetID, featherData.feather1Pos, featherData.feather1Dir, "Feather1")
end

local function OnStart30403()
    this:NarratorOnlyTask(q304Cfg.AmborNarratorFlow1)
    local quest = actorMgr:GetActor(q304Cfg.ActorAlias)
    if quest ~= nil then
        quest:FinishQuest(false, nil)
    end
end

local function OnStart30404(quest)
    this:SpawnGadget(featherData.FeatherGadgetID, featherData.feather2Pos, featherData.feather2Dir, "Feather2")
end

local function OnStart30405()
    this:NarratorOnlyTask(q304Cfg.AmborNarratorFlow2)
    local quest = actorMgr:GetActor(q304Cfg.ActorAlias)
    if quest ~= nil then
        quest:FinishQuest(false, nil)
    end
end

local function OnStart30406(quest)
    this:SpawnGadget(featherData.FeatherGadgetID, featherData.feather3Pos, featherData.feather3Dir, "Feather3")
end

local function OnStart30407()
    this:NarratorOnlyTask(q304Cfg.AmborNarratorFlow3)
    local quest = actorMgr:GetActor(q304Cfg.ActorAlias)
    if quest ~= nil then
        quest:FinishQuest(false, nil)
    end
end

local function OnStart30408(quest)
    this:SpawnGadget(featherData.FeatherGadgetID, featherData.feather4Pos, featherData.feather4Dir, "Feather4")
end

local function OnStart30409()
    actorMgr:CreateActorWithPos(amborData.Ambor, amborData.AmborScript, amborData.AmborID, 0, amborData.feather4Pos, amborData.feather4Dir, true, false)
    MengdeWindDestroy()
end

local function OnRewind30401()
    actorMgr:CreateActorWithPos(amborData.Ambor, amborData.AmborScript, amborData.AmborID, 0, amborData.feather1P


s", (bytes_ / 1048576.0) / elapsed));
    }
    extra.append(message_.toString());
    double elapsed = (finish_ - start_);
    double throughput = (double) done_ / (elapsed * 1e-9);

    System.out.format("%-12s : %11.3f micros/op %d ops/sec;%s%s\n",
            name, (elapsed * 1e-6) / done_,
            (long) throughput, (extra.length() == 0 ? "" : " "), extra.toString());
  }
}

public class DbBenchmark {
  enum Order {
    SEQUENTIAL,
    RANDOM
  }

  enum DBState {
    FRESH,
    EXISTING
  }

  static {
    RocksDB.loadLibrary();
  }

  abstract class BenchmarkTask implements Callable<Stats> {
    // TODO(yhchiang): use (Integer)Flag.perf_level.
    public BenchmarkTask(
        int tid, long randSeed, long numEntries, long keyRange) {
      tid_ = tid;
      rand_ = new Random(randSeed + tid * 1000);
      numEntries_ = numEntries;
      keyRange_ = keyRange;
      stats_ = new Stats(tid);
    }

    @Override public Stats call() throws RocksDBException {
      stats_.start_ = System.nanoTime();
      runTask();
      stats_.finish_ = System.nanoTime();
      return stats_;
    }

    abstract protected void runTask() throws RocksDBException;

    protected int tid_;
    protected Random rand_;
    protected long numEntries_;
    protected long keyRange_;
    protected Stats stats_;

    protected void getFixedKey(byte[] key, long sn) {
      generateKeyFromLong(key, sn);
    }

    protected void getRandomKey(byte[] key, long range) {
      generateKeyFromLong(key, Math.abs(rand_.nextLong() % range));
    }
  }

  abstract class WriteTask extends BenchmarkTask {
    public WriteTask(
        int tid, long randSeed, long numEntries, long keyRange,
        WriteOptions writeOpt, long entriesPerBatch) {
      super(tid, randSeed, numEntries, keyRange);
      writeOpt_ = writeOpt;
      entriesPerBatch_ = entriesPerBatch;
      maxWritesPerSecond_ = -1;
    }

    public WriteTask(
        int tid, long randSeed, long numEntries, long keyRange,
        WriteOptions writeOpt, long entriesPerBatch, long maxWritesPerSecond) {
      super(tid, randSeed, numEntries, keyRange);
      writeOpt_ = writeOpt;
      entriesPerBatch_ = entriesPerBatch;
      maxWritesPerSecond_ = maxWritesPerSecond;
    }

    @Override public void runTask() throws RocksDBException {
      if (numEntries_ != DbBenchmark.this.num_) {
        stats_.message_.append(String.format(" (%d ops)", numEntries_));
      }
      byte[] key = new byte[keySize_];
      byte[] value = new byte[valueSize_];

      try {
        if (entriesPerBatch_ == 1) {
          for (long i = 0; i < numEntries_; ++i) {
            getKey(key, i, keyRange_);
            DbBenchmark.this.gen_.generate(value);
            db_.put(writeOpt_, key, value);
            stats_.finishedSingleOp(keySize_ + valueSize_);
            writeRateControl(i);
            if (isFinished()) {
              return;
            }
          }
        } else {
          for (long i = 0; i < numEntries_; i += entriesPerBatch_) {
            WriteBatch batch = new WriteBatch();
            for (long j = 0; j < entriesPerBatch_; j++) {
              getKey(key, i + j, keyRange_);
              DbBenchmark.this.gen_.generate(value);
              batch.put(key, value);
              stats_.finishedSingleOp(keySize_ + valueSize_);
            }
            db_.write(writeOpt_, batch);
            batch.dispose();
            writeRateControl(i);
            if (isFinished()) {
              return


The code above only put the argument(s)
	 *	on the stack, now we'll load them.
	 */
1:	la	v0,cthread_body
	lw	a0,0(sp)
	j	v0
	END(cproc_prepare)

/*
 *	int
 *	cthread_sp()
 *
 *	Returns the current stack pointer.
 */

LEAF(cthread_sp)
	move	v0, sp
	j	ra
	END(cthread_sp);


SAFETY_ON_NULL_RETURN_VAL(snapshot, EINA_FALSE);
   server = evas_object_data_get(snapshot, "_ecore_evas.vnc");

   EINA_SAFETY_ON_NULL_RETURN_VAL(server, EINA_FALSE);
   EINA_SAFETY_ON_NULL_RETURN_VAL(pointer, EINA_FALSE);

   itr = rfbGetClientIterator(server->vnc_screen);

   while ((client = rfbClientIteratorNext(itr)))
     {
        cdata = client->clientData;

        if (cdata->mouse == pointer)
          {
             if (x) *x = client->lastPtrX;
             if (y) *y = client->lastPtrY;
             return EINA_TRUE;
          }
     }

   rfbReleaseClientIterator(itr);
   return EINA_FALSE;
}

EINA_MODULE_INIT(_ecore_evas_vnc_server_init);
EINA_MODULE_SHUTDOWN(_ecore_evas_vnc_server_shutdown);


             rightArrow?.Dispose();
                leftArrowHover?.Dispose();
                rightArrowHover?.Dispose();
                _hoverPlayer?.Dispose();
                _selectPlayer?.Dispose();
                _leftArrowSelectPlayer?.Dispose();
                _rightArrowSelectPlayer?.Dispose();
                _libVLC?.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}


u.set_mem(1, noun);
            cpu.set_mem(2, verb);

            while *&cpu.tick() { }

            if cpu.get_mem(0).clone() == 19690720 {
                let result = 100 * noun + verb;
                println!("Part 2: {}", result);
                return;
            }
        }
    }
}#[cfg(test)]
mod test {

    #[test]
    fn base() {
        // 迭代器可以收集到 vector
        let collected_iterator: Vec<i32> = (0..10).collect();
        println!("Collected (0..10) into: {:?}", collected_iterator);

        // `vec!` 宏可用来初始化一个 vector
        let mut xs = vec![1i32, 2, 3];
        println!("Initial vector: {:?}", xs);

        // 在 vector 的尾部插入一个新的元素
        println!("Push 4 into the vector");
        xs.push(4);
        println!("Vector: {:?}", xs);

        // 报错！不可变 vector 不可增长
        //collected_iterator.push(0);
        // 改正 ^ 将此行注释掉

        // `len` 方法获得一个 vector 的当前大小
        println!("Vector size: {}", xs.len());

        // 在中括号上加索引（索引从 0 开始）
        println!("Second element: {}", xs[1]);

        // `pop` 移除 vector 的最后一个元素并将它返回
        println!("Pop last element: {:?}", xs.pop());

        // 超出索引范围将抛出一个 panic
        // println!("Fourth element: {}", xs[3]);
    }

    #[test]
    fn tmain() {
        let mut v: Vec<i32> = Vec::new();

        let v = vec![1, 2, 3];

        {
            let v1 = vec![1, 2, 3];
        }

        let one: &i32 = &v[0];
        println!("one = {}", *one);

        match v.get(1) {
            Some(value) => println!("value = {}", value),
            _ => println!("None"),
        }

        let mut v2: Vec<i32> = Vec::new();
        v2.push(1);
        v2.push(2);
        v2.push(3);

        for i in &v2 {
            println!("i = {}", i);
        }

        for i in &mut v2 {
            *i += 1;
            println!("i = {}", i);
        }

        enum Context {
            Text(String),
            Float(f32),
            Int(i32),
        };

        let c = vec![
            Context::Text(String::from("string")),
            Context::Int(-1),
            Context::Float(0.001),
        ];

        let v = vec![1, 2, 3, 4, 5];
        let first = &v[0]; //不可变引用
                           //v.push(6); //ERROR, 进行可变修改
        println!("first = {}", first); //禁止再使用不可变引用

        println!("Hello, world!");
    }
}
<reponame>ezaanm/mirror-contracts
use cosmwasm_std::{
    from_binary, log, to_binary, Api, Binary, CanonicalAddr, CosmosMsg, Decimal, Env, Extern,
    HandleResponse, HandleResult, HumanAddr, InitResponse, MigrateResponse, MigrateResult, Querier,
    StdError, StdResult, Storage, Uint128, WasmMsg,
};

use crate::{
    asserts::{assert_auction_discount, assert_min_collateral_ratio, assert_protocol_fee},
    migration::{migrate_asset_configs, migrate_config},
    positions::{
        auction, burn, deposit, mint, open_position, query_next_position_idx, query_position,
        query_positions, withdraw,
    },
    querier::load_oracle_feeder,
    state::{
        read_asset_config, read_config, store_asset_config, store_config, store_position_idx,
        AssetConfig, Config,
    },
};

use cw20::Cw20ReceiveMsg;
use mirror_protocol::mint::{
    AssetConfigResponse, ConfigResponse, Cw20HookMsg, HandleMsg, InitMsg, MigrateMsg, QueryMsg,
};
use mirror_protocol::{
    collateral_oracle::{HandleMsg as CollateralOracleHandleMsg, SourceType},


		SELECT user_id, our_uri, their_uri, timestamp, result, broadcasted
		FROM ids_cache WHERE user_id=$1 AND our_uri=$2 AND their_uri = ANY($3)
	`
	// language=sqlite
	getManyIDSCacheEntriesQuerySQLite = `
		SELECT user_id, our_uri, their_uri, timestamp, result, broadcasted
		FROM ids_cache WHERE user_id=?1 AND our_uri=?2 AND their_uri IN (?3)
	`
	// language=postgresql
	markBroadcastedQueryPostgres = `
		UPDATE ids_cache SET broadcasted=true WHERE user_id=$1 AND our_uri=$2 AND their_uri = ANY($3)
	`
	// language=sqlite
	markBroadcastedQuerySQLite = `
		UPDATE ids_cache SET broadcasted=true WHERE user_id=?1 AND our_uri=?2 AND their_uri IN (?3)
	`
	upsertIDSCacheEntryQuery = `
		INSERT INTO ids_cache (user_id, our_uri, their_uri, timestamp, result, broadcasted)
		VALUES ($1, $2, $3, $4, $5, $6)
		ON CONFLICT (user_id, our_uri, their_uri)
		    DO UPDATE SET timestamp=excluded.timestamp, result=excluded.result
	`
	invalidateIDSCacheEntryQuery = `UPDATE ids_cache SET timestamp=MIN(timestamp, $4) WHERE user_id=$1 AND our_uri=$2 AND their_uri=$3`
	deleteIDSCacheEntryQuery     = `DELETE FROM ids_cache WHERE user_id=$1 AND our_uri=$2 AND their_uri=$3`
)

func (iq *IDSCacheQuery) Get(ctx context.Context, userID int, ourURI uri.ParsedURI, theirURI uri.ParsedURI) (*IDSCacheEntry, error) {
	return get[*IDSCacheEntry](iq, ctx, getIDSCacheEntryQuery, userID, ourURI, theirURI)
}

func makeSQLiteArrayParams[T any](dynamic []T, prefix ...any) (params []any, placeholders string) {
	params = make([]any, len(dynamic)+len(prefix))
	placeholderArr := make([]string, len(dynamic))
	copy(params, prefix)
	for i, value := range dynamic {
		params[i+len(prefix)] = value
		placeholderArr[i] = fmt.Sprintf("?%d", i+len(prefix)+1)
	}
	placeholders = strings.Join(placeholderArr, ", ")
	return
}

func (iq *IDSCacheQuery) GetMany(ctx context.Context, userID int, ourURI uri.ParsedURI, theirURIs []uri.ParsedURI) ([]*IDSCacheEntry, error) {
	if iq.db.Dialect == dbutil.Postgres {
		return getAll[*IDSCacheEntry](iq, ctx, getManyIDSCacheEntriesQueryPostgres, userID, ourURI, theirURIs)
	} else {
		params, placeholders := makeSQLiteArrayParams(theirURIs, userID, ourURI)
		query := strings.ReplaceAll(getManyIDSCacheEntriesQuerySQLite, "?3", placeholders)
		return getAll[*IDSCacheEntry](iq, ctx, query, params...)
	}
}

func (iq *IDSCacheQuery) MarkBroadcasted(ctx context.Context, userID int, ourURI uri.ParsedURI, theirURIs []uri.ParsedURI) (err error) {
	if iq.db.Dialect == dbutil.Postgres {
		_, err = iq.db.Conn(ctx).ExecContext(ctx, markBroadcastedQueryPostgres, userID, ourURI, theirURIs)
	} else {
		params, placeholders := makeSQLiteArrayParams(theirURIs, userID, ourURI)
		query := strings.ReplaceAll(markBroadcastedQuerySQLite, "?3", placeholders)
		_, err = iq.db.Conn(ctx).ExecContext(ctx,


 = {
    PROPERTY: 'property',
    VALUE: 'value'
  };

  /**
   * Checks whether the quotes has been opened for style value.
   *
   * @param context Style block parser context.
   *
   * @returns True if style value has already opened quotes.
   */
  const isValueQuotesOpen = context => {
    return context.bufferValue !== '' && context.valueQuoteMark !== null;
  };
  /**
   * Saves parsed property and value to collection of parsed styles.
   * Prunes context buffers for property and value.
   *
   * @param context Style block parser context.
   */

  const collectStyle = context => {
    context.styles.push({
      property: context.bufferProperty.trim(),
      value: context.bufferValue.trim()
    }); // reset buffers

    context.bufferProperty = '';
    context.bufferValue = '';
  };
  /**
   * Handles token which is supposed to be a part of style **property**.
   *
   * @param context Style block parser context.
   * @param styleBlock Whole style block which is being parsed.
   * @param token Current token.
   *
   * @throws An error on invalid token.
   */

  const processPropertyToken = (context, styleBlock, token) => {
    const {
      value: tokenValue
    } = token;

    switch (token.type) {
      case TOKEN_TYPE.WORD:
        if (context.bufferProperty.length > 0) {
          // e.g. 'padding top: 0;' - current tokenValue is 'top' which is not valid
          throw new Error(`Invalid style property in style block: '${styleBlock}'`);
        }

        context.bufferProperty += tokenValue;
        break;

      case TOKEN_TYPE.MARK:
        // only colon and whitespaces are allowed while style property parsing
        if (tokenValue === COLON) {
          if (context.bufferProperty.trim().length === 0) {
            // e.g. such style block: '{ : none; }'
            throw new Error(`Missing style property before ':' in style block: '${styleBlock}'`);
          } // the property successfully collected

          context.bufferProperty = context.bufferProperty.trim(); // prepare for value collecting

          context.processing = DECLARATION_PART.VALUE; // the property buffer shall be reset after the value is successfully collected
        } else if (WHITE_SPACE_CHARACTERS.includes(tokenValue)) ; else {
          // if after the property there is anything other than ':' except whitespace, this is a parse error
          // https://www.w3.org/TR/css-syntax-3/#consume-declaration
          throw new Error(`Invalid style declaration in style block: '${styleBlock}'`);
        }

        break;

      default:
        throw new Error(`Unsupported style property character: '${tokenValue}' in style block: '${styleBlock}'`);
    }
  };
  /**
   * Handles token which is supposed to be a part of style **value**.
   *
   * @param context Style block parser context.
   * @param styleBlock Whole style block which is being parsed.
   * @param token Current token.
   *
   * @throws An error on invalid token.
   */

  const processValueToken = (context, styleBlock, token) => {
    const {
      value: tokenValue
    } = token;

    if (token.type === TOKEN_TYPE.WORD) {
      // simply collect to buffer
      context.bufferValue += tokenValue;
    } else {
      // otherwise check the mark
      switch (tokenValue) {
        case COLON:
          // the ':' character inside of the value should be inside of quotes
          // otherwise the value is not valid
          // e.g. 'content: display: none'
          // parser is here        ↑
          if (!isValueQuotesOpen(context)) {
            // eslint-disable-next-line max-len
            throw new Error(`Invalid style value for property '${context.bufferProperty}' in style block: '${styleBlock}'`);
          } // collect the colon inside quotes
          // e.g. 'content: "test:123"'
          // parser is here


ry commodities, Previous: Specifying Amounts, Up: Journal File Format for Developers   [Contents][Index]

14.2.3 Posting costs

You have seen how to specify either a commoditized or an integer
amount for a posting.  But what if the amount you paid for something
was in one commodity, and the amount received was another?  There are
two main ways to express this:

2010/05/31 Farmer's Market
    Assets:My Larder           100 apples
    Assets:Checking                -$20.00

In this example, you have paid twenty dollars for one hundred apples.
The cost to you is twenty cents per apple, and Ledger calculates this
implied cost for you.  You can also make the cost explicit using a
cost amount:

2010/05/31 Farmer's Market
    Assets:My Larder           100 apples @ $0.200000
    Assets:Checking

Here the per-unit cost is given explicitly in the form of a cost
amount; and since cost amounts are unobserved, the use of six
decimal places has no effect on how dollar amounts are displayed in
the final report.  You can also specify the total cost:

2010/05/31 Farmer's Market
    Assets:My Larder           100 apples @@ $20
    Assets:Checking

These three forms have identical meaning.  In most cases the first is
preferred, but the second two are necessary when more than two
postings are involved:

2010/05/31 Farmer's Market
    Assets:My Larder           100 apples        @ $0.200000
    Assets:My Larder           100 pineapples    @ $0.33
    Assets:My Larder           100 "crab apples" @ $0.04
    Assets:Checking

Here the implied cost is ‘<samp>$57.00</samp>’, which is entered into the null
posting automatically so that the transaction balances.

Previous: Posting costs, Up: Journal File Format for Developers   [Contents][Index]

14.2.4 Primary commodities

In every transaction involving more than one commodity, there is
always one which is the primary commodity.  This commodity
should be thought of as the exchange commodity, or the commodity used
to buy and sell units of the other commodity.  In the fruit examples
above, dollars are the primary commodity.  This is decided by Ledger
based on the placement


() + " " + maxResistance + " " +
    		position + " " + sliderText; }

    void createSlider() {
    	sim.addWidgetToVerticalPanel(label = new Label(sliderText));
    	label.addStyleName("topSpace");
    	int value = (int) Math.round((position-.005)/.0099);
    	sim.addWidgetToVerticalPanel(slider = new Scrollbar(Scrollbar.HORIZONTAL, value, 1, 0, 101, this, this));
   // 	sim.verticalPanel.validate();
   // 	slider.addAdjustmentListener(this);
    }

    public void execute() {
	sim.analyzeFlag = true;
	setPoints();
    }

    void delete() {
	sim.removeWidgetFromVerticalPanel(label);
	sim.removeWidgetFromVerticalPanel(slider);
        super.delete();
    }

    Point post3, corner2, arrowPoint, midpoint, arrow1, arrow2;
    Point ps3, ps4;
    int bodyLen;

    void setPoints() {
	super.setPoints();
	int offset = 0;
	int myLen =0;
	if (abs(dx) > abs(dy) != hasFlag(FLAG_FLIP)) {
	    myLen =  2 * sim.gridSize * Integer.signum(dx) * ((((int)Math.abs(dx))+ 2 * sim.gridSize -1) / (2 * sim.gridSize));
	    point2.x =  point1.x + myLen;
	    offset = (dx < 0) ? dy : -dy;
	    point2.y = point1.y;
	} else {
	    myLen =  2 * sim.gridSize * Integer.signum(dy) * ((((int)Math.abs(dy))+ 2 * sim.gridSize -1) / (2 * sim.gridSize));
	    if (dy != 0) {
		point2.y = point1.y + myLen;
		offset = (dy > 0) ? dx : -dx;
		point2.x = point1.x;
	    }
	}
	if (offset == 0)
	    offset = (hasFlag(FLAG_FLIP_OFFSET)) ? -sim.gridSize : sim.gridSize;
	dn = distance(point1, point2);
	int bodyLen = 32;
	calcLeads(bodyLen);
	position = slider.getValue() * .0099 + .005;
	int soff = (int) ((position - .5) * bodyLen);
	// int offset2 = offset - sign(offset)*4;
	post3 = interpPoint(point1, point2, .5, offset);
	corner2 = interpPoint(point1, point2, soff / dn + .5, offset);
	arrowPoint = interpPoint(point1, point2, soff / dn + .5, 8 * sign(offset));
	midpoint = interpPoint(point1, point2, soff / dn + .5);
	arrow1 = new Point();
	arrow2 = new Point();
	double clen = abs(offset) - 8;
	interpPoint2(corner2, arrowPoint, arrow1, arrow2, (clen - 8) / clen, 8);
	ps3 = new Point();
	ps4 = new Point();
    }

    void draw(Graphics g) {
	int segments = 16;
	int i;
	int ox = 0;
	int hs = sim.euroResistorCheckItem.getState() ? 6 : 8;
	double v1 = volts[0];
	double v2 = volts[1];
	double v3 = volts[2];
	setBbox(point1, point2, hs);
	adjustBbox(post3, post3);
	draw2Leads(g);
	setPowerColor(g, true);
	double segf = 1./segments;
	int divide = (int) (segments*position);
	if (!sim.euroResistorCheckIte


            println!("{}", APP_USER_AGENT);
            return Ok(());
        }
        _ => (),
    }

    // get minimimun(included) and maximum(excluded) crate versions
    let (from, to) = {
        if RE.is_match(&main_arg) {
            let caps = RE.captures(&main_arg).ok_or("")?;
            let from = semver::Version::parse(caps.get(1).ok_or("")?.as_str())?;
            let to = semver::Version::parse(caps.get(2).ok_or("")?.as_str())?;
            (from, to)
        } else {
            (semver::Version::new(0, 0, 0), semver::Version::new(0, 0, 0))
        }
    };

    // read Cargo.toml and deserialize
    let local_toml = std::fs::read_to_string("Cargo.toml")?;
    let local_crate: Config = toml::from_str(&local_toml)?;

    // construct client
    let client = reqwest::Client::builder()
        .user_agent(APP_USER_AGENT)
        .build()?;
    // launch request and deserialize json
    let resp = client
        .get(&format!(
            "https://crates.io/api/v1/crates/{}/versions",
            local_crate.package.name
        ))
        .send()
        .await?
        .json::<Versions>()
        .await?;

    // put matching versions in a Vec
    let versions: Vec<String> = resp
        .versions
        .iter()
        .filter(|item| {
            let yanked = item.yanked;
            if let Ok(item) = semver::Version::parse(&item.version) {
                item >= from && item < to && !yanked
            } else {
                false
            }
        })
        .map(|item| item.version.clone())
        .collect();

    // iterate versions and yank
    for version in versions {
        tokio::process::Command::new("cargo")
            .args(&["yank", "--vers", &version])
            .spawn()?
            .wait()
            .await?;
    }
    Ok(())
}
<filename>leaf/src/util.rs
use std::sync::Arc;

use anyhow::Result;
use log::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::runtime;

#[cfg(feature = "inbound-socks")]
use crate::proxy::socks;

#[cfg(feature = "inbound-http")]
use crate::proxy::http;

#[cfg(all(
    feature = "inbound-tun",
    any(target_os = "ios", target_os = "macos", target_os = "linux")
))]
use crate::proxy::tun;

use crate::{
    app::{
        dispatcher::Dispatcher, handler_manager::HandlerManager, nat_manager::NatManager,
        router::Router,
    },
    config::Config,
    session::{Session, SocksAddr},
    Runner,
};

pub fn create_runners(config: Config) -> Result<Vec<Runner>> {
    let handler_manager = HandlerManager::new(&config.outbounds, config.dns.as_ref().unwrap());
    let router = Router::new(&config.routing_rules);
    let dispatcher = Arc::new(Dispatcher::new(handler_manager, router));
    let nat_manager = Arc::new(NatManager::new(dispatcher.clone()));
    let mut runners: Vec<Runner> =


argets an internal URL.

If you are not using CsrfViewMiddleware, then you must use
    csrf_protect on any views that use the csrf_token
    template tag, as well as those that accept the POST data.

The form has a valid CSRF token. After logging in in another browser
    tab or hitting the back button after a login, you may need to reload the
    page with the form, because the token is rotated after a login.

You’re seeing the help section of this page because you have DEBUG =
  True in your Django settings file. Change that to False,
  and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

{% else %}

{{ more }}

{% endif %}

<!DOCTYPE html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width">
		<title>Messages Relay</title>

Messages Relay

			Both Source Chain and Target Chains have Bridge Messages pallets deployed. They also have required
			finality pallets deployed - we don't care about finality type here - they can be either Bridge GRANDPA,
			or Bridge Parachains finality pallets, or any combination of those.

			Finality Relayer represents two actual relayers - one relays Source Chain Finality to Target Chain.
			And another one relays Target Chain Finality to Source Chain.

			sequenceDiagram
			participant Source Chain
			participant Finality Relayer
			participant Messages Relayer
			participant Target Chain

			Note right of Source Chain: Finalized: 480, Target Finalized: 50, Sent Messages: 42, Confirmed Messages: 42
			Note left of Target Chain: Finalized: 60, Source Finalized: 420, Received Messages: 42

			Source Chain ->> Source Chain: someone Sends Message 43
			Source Chain ->> Source Chain: Import and Finalize Block 481

			Source Chain ->> Messages Relayer: notes new outbound message 43 at Source Chain Block 481
			Note right of Messages Relayer: can't deliver message 43, Source Chain Block 481 is not relayed

			Source Chain ->> Finality Relayer: Read Finality Proof of Block 481
			Finality Relayer ->> Target Chain: Submit Finality Proof of Block 481
			Target Chain ->> Target Chain: Import and Finalize Block 61
			Note left of Target Chain: Finalized: 61, Source Finalized: 481, Received Messages: 42

			Source Chain ->> Messages Relayer: Read Proof of Message 43 at Block 481
			Messages Relayer ->> Target Chain: Submit Proof of Message 43 at Block 481
			Target Chain ->> Target Chain: Import and Finalize Block 62
			Note left of Target Chain: Finalized: 62, Source Finalized: 481, Received Messages: { rewarded: 42, messages-relayer-account: [43] }

			Target Chain ->> Messages Relayer: notes new unrewarded relayer at Target Chain Block 62
			Note right of Messages Relayer: can't relay delivery confirmations because Target Chain Block 62 is not relayed

			Target Chain ->> Finality


ntent="true" /><meta name="container" content="AsterNET.FastAGI" /><meta name="file" content="T_AsterNET_FastAGI_MappingStrategy" /><meta name="guid" content="T_AsterNET_FastAGI_MappingStrategy" /><link rel="stylesheet" type="text/css" href="../styles/branding-Website.css" /><input type="hidden" id="userDataCache" class="userDataStyle" />
AsterNet Class Library (Sandcastle documentation)<form id="SearchForm" method="get" action="#" onsubmit="javascript:TransferToSearchPage(); return false;"><input id="SearchTextBox" type="text" maxlength="200" /><button id="SearchButton" type="submit"></button></form>

AsterNet Class Library (Sandcastle documentation)

AsterNET.FastAGI

MappingStrategy Class

MappingStrategy Constructor

MappingStrategy Methods

MappingStrategy Properties

<img id="ResizeImageReset" src="../icons/TocClose.gif" style="display:none" onclick="OnResetToc()" alt="Click or


/*
 *  linux/arch/i386/kernel/head.S -- the 32-bit startup code.
 *
 *  Copyright (C) 1991, 1992  Linus Torvalds
 *
 *  Enhanced CPU detection and feature setting code by Mike Jagdis
 *  and Martin Mares, November 1997.
 */

.text
#include <linux/threads.h>
#include <linux/linkage.h>
#include <asm/segment.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/desc.h>
#include <asm/cache.h>
#include <asm/thread_info.h>
#include <asm/asm-offsets.h>
#include <asm/setup.h>

/*
 * References to members of the new_cpu_data structure.
 */

#define X86		new_cpu_data+CPUINFO_x86
#define X86_VENDOR	new_cpu_data+CPUINFO_x86_vendor
#define X86_MODEL	new_cpu_data+CPUINFO_x86_model
#define X86_MASK	new_cpu_data+CPUINFO_x86_mask
#define X86_HARD_MATH	new_cpu_data+CPUINFO_hard_math
#define X86_CPUID	new_cpu_data+CPUINFO_cpuid_level
#define X86_CAPABILITY	new_cpu_data+CPUINFO_x86_capability
#define X86_VENDOR_ID	new_cpu_data+CPUINFO_x86_vendor_id

/*
 * This is how much memory *in addition to the memory covered up to
 * and including _end* we need mapped initially.
 * We need:
 *  - one bit for each possible page, but only in low memory, which means
 *     2^32/4096/8 = 128K worst case (4G/4G split.)
 *  - enough space to map all low memory, which means
 *     (2^32/4096) / 1024 pages (worst case, non PAE)
 *     (2^32/4096) / 512 + 4 pages (worst case for PAE)
 *  - a few pages for allocator use before the kernel pagetable has
 *     been set up
 *
 * Modulo rounding, each megabyte assigned here requires a kilobyte of
 * memory, which is currently unreclaimed.
 *
 * This should be a multiple of a page.
 */
LOW_PAGES = 1<<(32-PAGE_SHIFT_asm)

/*
 * To preserve the DMA pool in PAGEALLOC kernels, we'll allocate
 * pagetables from above the 16MB DMA limit, so we'll have to set
 * up pagetables 16MB more (worst-case):
 */
#ifdef CONFIG_DEBUG_PAGEALLOC
LOW_PAGES = LOW_PAGES + 0x1000000
#endif

#if PTRS_PER_PMD > 1
PAGE_TABLE_SIZE = (LOW_PAGES / PTRS_PER_PMD) + PTRS_PER_PGD
#else
PAGE_TABLE_SIZE = (LOW_PAGES / PTRS_PER_PGD)
#endif
BOOTBITMAP_SIZE = LOW_PAGES / 8
ALLOCATOR_SLOP = 4

INIT_MAP_BEYOND_END = BOOTBITMAP_SIZE + (PAGE_TABLE_SIZE + ALLOCATOR_SLOP)*PAGE_SIZE_asm

/*
 * 32-bit kernel entrypoint; only used by the boot CPU.  On entry,
 * %esi points to the real-mode code as a 32-bit pointer.
 * CS and DS must be 4 GB flat segments, but we don't depend on
 * any particular GDT layout, because we load our own as soon as we
 * can.
 */
.section .text.head,"ax",@progbits
ENTRY(startup_32)
	/* check to see if KEEP_SEGMENTS flag is meaningful */
	cmpw $0x207, BP_version(%esi)
	jb 1f

	/* test KEEP_SEGMENTS flag to see if the bootloader is asking
		us to not reload segm


( \"preline\", delay * (j - 1) / maxj, delay * (j - 1) / maxj + 400 ), \"\\\\bs0\\\\1a45\\\\blur0.2\\\\fad(120,120)\", tag.glitter( fx.dur, \"\\\\1c&HFFFFFF&\", \"\\\\1cSC1\" )", "delay = 600", "Lua", false, false )
	Char_Clip_4_I = effector.create_fx( "LIfx", "Char_Clip_4_I", "Char", true, false, "#FFFFFF", "#848484", "#454545", "0", "0", "0", "l.start_time + 25li - 120 - R( 0, 4 ) * 1f", "l.start_time + syl.start_time", "", "", "", "", "char.center", "char.middle", "", "", "5", "0", "fx.pos_x", "fx.pos_y", "", "2, 2", "", "char.text", "tag.clip( ), tag.oscill( 6f, 1f, \"\\\\134a255\", \"\\\\txt.a\" )", "", "Lua", false, false )
	Char_Clip_4_I_buttline = effector.create_fx( "LIfx", "Char_Clip_4_I_buttline", "Char", true, false, "#FFFFFF", "#848484", "#454545", "0", "0", "0", "l.start_time + 25mid2 - 120 - R( 0, 4 ) * 1f", "l.start_time + syl.start_time", "", "", "", "", "char.center", "char.middle", "", "", "5", "0", "fx.pos_x", "fx.pos_y", "", "2, 2", "", "char.text", "tag.clip( ), tag.oscill( 6f, 1f, \"\\\\134a255\", \"\\\\txt.a\" )", "", "Lua", false, false )
	Char_Clip_4_I_inverse = effector.create_fx( "LIfx", "Char_Clip_4_I_inverse", "Char", true, false, "#FFFFFF", "#848484", "#454545", "0", "0", "0", "l.start_time - 25li - 10f - 120 - R( 0, 4 ) * 1f", "l.start_time + syl.start_time", "", "", "", "", "char.center", "char.middle", "", "", "5", "0", "fx.pos_x", "fx.pos_y", "", "2, 2", "", "char.text", "tag.clip( ), tag.oscill( 6f, 1f, \"\\\\134a255\", \"\\\\txt.a\" )", "", "Lua", false, false )
	Char_Clip_4_I_midline = effector.create_fx( "LIfx", "Char_Clip_4_I_midline", "Char", true, false, "#FFFFFF", "#848484", "#454545", "0", "0", "0", "l.start_time + 25mid1 - 120 - R( 0, 4 ) * 1f", "l.start_time + syl.start_time", "", "", "", "", "char.center", "char.middle", "", "", "5", "0", "fx.pos_x", "fx.pos_y", "", "2, 2", "", "char.text", "tag.clip( ), tag.oscill( 6f, 1f, \"\\\\134a255\", \"\\\\txt.a\" )", "", "Lua", false, false )
	Char_Clip_4_II = effector.create_fx( "LIfx", "Char_Clip_4_II", "Char", true, false, "#FFFFFF", "#848484", "#454545", "0", "0", "0", "l.start_time + 25li - 120 - R( 0, 4 ) * 1f", "l.start_time + syl.start_time", "", "", "", "", "char.center", "char.middle", "", "", "5", "0", "fx.pos_x", "fx.pos_y", "", "2, 2", "", "char.text", "tag.clip(


 hostPlatform: str, large: bool) -> None:
        attr = f"packages.{hostPlatform}.{name}"
        super().__init__(name, hostPlatform, attr, large)
        if self.isDarwinHost():
            self.linuxBuilderAttr = f"darwinConfigurations.{name}.config.nix.linux-builder.package.nixosConfig.system.build.toplevel"

class Flake:
    buildables: Sequence[Derivation]
    evalOnly: Sequence[Derivation]

    def __init__(self, hosts: List[Host]) -> None:
        devShells = [DevShell(p) for p in set([h.hostPlatform for h in hosts])]
        buildables, evalOnly = map(
            list, partition(lambda a: a.buildable, itertools.chain(hosts, devShells))
        )
        self.buildables = buildables
        self.evalOnly = evalOnly

    def all(self) -> Iterable[Derivation]:
        return itertools.chain(self.buildables, self.evalOnly)

    @classmethod
    def from_hosts_file(cls) -> Self:
        hosts_path = Flake.find_hosts_file()
        raw = subprocess.run(
            ["nix", "eval", "--json", "-f", hosts_path],
            capture_output=True,
            check=True,
            text=True,
        ).stdout
        parsed = json.loads(raw)
        hosts = []
        for name, cfg in parsed.items():
            hosts.append(Host(name, cfg["hostPlatform"], cfg["large"]))

        return cls(hosts)

    @staticmethod
    def find_hosts_file() -> Path:
        script_dir = Path(__file__).absolute().parent
        toplevel = subprocess.run(
            ["git", "rev-parse", "--show-toplevel"],
            cwd=script_dir,
            capture_output=True,
            check=True,
            text=True,
        )
        toplevel = Path(toplevel.stdout.strip())
        hosts_path = toplevel / "nix" / "hosts.nix"
        if not hosts_path.exists():
            raise RuntimeError(f"did not find host definition in {hosts_path}")
        return hosts_path

if __name__ == "__main__":
    main()


.include "global.s"
.include "mapper_macros.s"

.define .tempA "(REGTEMP+7)"

;
; Banked call support function.
;
;
; For a banked call to function "func", sdcc will generate the following sequence:
;
; jsr __sdcc_bcall  <-- Call to this support function
; .db b_func        <-- Bank of func
; .dw func-1        <-- Address of func - 1.
;
___sdcc_bcall::
    ; save potential function parameter in A
    sta *.tempA
    ; Store old return address to *.tmp, and add +3 to return address on stack (to skip parameters)
    pla
    sta *.tmp
    clc
    adc #3
    tay
    pla
    sta *.tmp+1
    adc #0
    pha
    tya
    pha
    ; Save old bank on stack
    lda