,
		},
	}

	spreadFactorCases := []string{"0", "0.001", "0.1", "0.5", "0.99"}

	getTestCaseName := func(tc testcase, spreadFactorDec string) string {
		return fmt.Sprintf("initialPoolOut: %d, initialCalcOut: %d, initialWeightOut: %d, initialWeightIn: %d, spreadFactor: %s",
			tc.initialPoolOut,
			tc.tokenOut,
			tc.initialWeightOut,
			tc.initialWeightIn,
			spreadFactorDec,
		)
	}

	for _, tc := range testcases {
		for _, spreadFactor := range spreadFactorCases {
			t.Run(getTestCaseName(tc, spreadFactor), func(t *testing.T) {
				spreadFactorDec, err := osmomath.NewDecFromStr(spreadFactor)
				require.NoError(t, err)

				initialPoolBalanceOut := osmomath.NewInt(tc.initialPoolOut)

				initialWeightOut := osmomath.NewInt(tc.initialWeightOut)
				initialWeightIn := osmomath.NewInt(tc.initialWeightIn)

				initialTotalShares := types.InitPoolSharesSupply.ToLegacyDec()
				initialCalcTokenOut := osmomath.NewInt(tc.tokenOut)

				actualSharesOut := balancer.CalcPoolSharesOutGivenSingleAssetIn(
					initialPoolBalanceOut.ToLegacyDec(),
					initialWeightOut.ToLegacyDec().Quo(initialWeightOut.Add(initialWeightIn).ToLegacyDec()),
					initialTotalShares,
					initialCalcTokenOut.ToLegacyDec(),
					spreadFactorDec,
				)

				inverseCalcTokenOut := balancer.CalcSingleAssetInGivenPoolSharesOut(
					initialPoolBalanceOut.Add(initialCalcTokenOut).ToLegacyDec(),
					initialWeightOut.ToLegacyDec().Quo(initialWeightOut.Add(initialWeightIn).ToLegacyDec()),
					initialTotalShares.Add(actualSharesOut),
					actualSharesOut,
					spreadFactorDec,
				)

				tol := osmomath.NewDec(1)
				osmoassert.DecApproxEq(t, initialCalcTokenOut.ToLegacyDec(), inverseCalcTokenOut, tol)
			})
		}
	}
}

// Expected is un-scaled
func testTotalWeight(t *testing.T, expected osmomath.Int, pool balancer.Pool) {
	t.Helper()
	scaledExpected := expected.MulRaw(balancer.GuaranteedWeightPrecision)
	require.Equal(t,
		scaledExpected.String(),
		pool.GetTotalWeight().String())
}

// TODO: Refactor this into multiple tests
func TestBalancerPoolUpdatePoolAssetBalance(t *testing.T) {
	var poolId uint64 = 10

	initialAssets := []balancer.PoolAsset{
		{
			Weight: osmomath.NewInt(100),
			Token:  sdk.NewCoin("test1", osmomath.NewInt(50000)),
		},
		{
			Weight: osmomath.NewInt(200),
			Token:  sdk.NewCoin("test2", osmomath.NewInt(50000)),
		},
	}

	pacc, err := balancer.NewBalancerPool(poolId, defaultBalancerPoolParams, initialAssets, defaultFutureGovernor, defaultCurBlockTime)
	require.NoError(t, err)

	_, err = pacc.GetPoolAsset("unknown")
	require.Error(t, err)
	_, err = pacc.GetPoolAsset("")
	require.Error(t, err)

	testTotalWeight(t, osmomath.NewInt(300), pacc)

	// Break abstractions and start reasoning about the underlying internal representation's API


[dim];
				for(int i = 0; i < dim; i++) {
					result[i] = 1.0;
				}
				resPoint = (new Point(result)).normalize();
			}
			return resPoint;
		}

		int epsilonCoord = dim + 1;
		//int numVars = dim + 1;
		double[] d;
		try {
			lpsolve.LpSolve solver = lpsolve.LpSolve.makeLp(0,dim + 2);
			solver.setVerbose(lpsolve.LpSolve.CRITICAL);

			//for some strange reason the 0th element of an array is ignored by addConstraint
			d = new double[dim + 3];
			for (int i = 0; i< dim; i++) {
				d[i + 1] = point.getCoord(i);
			}

			d[dim + 2] = -1.0;

			//System.out.println(Arrays.toString(d));
			solver.addConstraint(d, lpsolve.LpSolve.GE, 0.0);

			for (Point p : computedPoints)
			{
				d = new double[dim + 3];
				for (int i = 0; i< dim; i++) {
					d[i + 1] = p.getCoord(i);
				}
				d[epsilonCoord] = 1;

				d[dim + 2] = -1.0;

				solver.addConstraint(d, lpsolve.LpSolve.LE, 0.0);
			}

			for(int i = 0; i < dim; i++) {
				d = new double[dim + 3];
				d[i + 1] = 1;

				solver.addConstraint(d, lpsolve.LpSolve.GE, 0.0);
			}

			d = new double[dim + 3];

			for(int i = 0; i < dim; i++) {
				d[i + 1] = 1;
			}

			solver.addConstraint(d, lpsolve.LpSolve.LE, 1.0);

			d = new double[dim + 3];
			d[epsilonCoord] = 1;

			solver.setBounds(dim + 2, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY);

			solver.setObjFn(d);
			solver.setMaxim();

			int r = solver.solve();

			if (r == lpsolve.LpSolve.INFEASIBLE) {
				System.out.println("The solution is infeasible");
				return null;
			} else if (r == lpsolve.LpSolve.UNBOUNDED) {
				//this should never happen
				throw new PrismException("The solution of a linear program is unbounded.");
			} if (r != lpsolve.LpSolve.OPTIMAL)
				//this should also never happen
				throw new PrismException("LpSolve returns an unexpected value: " + r);

			double[] resultSolver = solver.getPtrVariables();
			//solver.printLp();
			if (resultSolver[epsilonCoord-1] == 0.0) {
				//there is no _strictly_ separating hyperplane (i.e. one that doesn't touch any of the points)
				return null;
			}

			//solver.printLp();
		    //System.out.println("solver says:" + r);
		    //System.out.println("solver results:" + Arrays.toString(resultSolver));

			double[] result = new double[dim];
			//copy all coordinates and ignore auxiliary variables
			for(int i = 0; i < dim; i++)
				result[i] = resultSolver[i];

			Point resPoint = new Point(result).normalize();

			return resPoint;
		} catch (lpsolve.LpSolveException ex) {
			PrismException ex2 = new PrismException("lpsolve threw an exception: " + ex.getMessage());
			throw ex2;
		}
	}

	/**
	 * Prints an auxiliary graph file in gnuplot format. Points must be 2D.
	 *
	 * NOTE: not very nice now, should be enhanced in the future...
	 *
	 * @param target Current target
	 * @param points Corner points of the


   * Constructor instantiated by the DOM when a custom element has been created.
   *
   * This can only be called by subclasses from their created constructor.
   */
  StopElement.created() : super.created();

  @JSName('offset')
  AnimatedNumber get gradientOffset native;
}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@Unstable()
@Native("SVGStringList")
class StringList extends JavaScriptObject
    with ListMixin<String>, ImmutableListMixin<String>
    implements List<String> {
  // To suppress missing implicit constructor warnings.
  factory StringList._() {
    throw new UnsupportedError("Not supported");
  }

  int get length => JS("int", "#.length", this);

  int? get numberOfItems native;

  String operator [](int index) {
    if (JS("bool", "# >>> 0 !== # || # >= #", index, index, index, length))
      throw new RangeError.index(index, this);
    return this.getItem(index);
  }

  void operator []=(int index, String value) {
    throw new UnsupportedError("Cannot assign element of immutable List.");
  }
  // -- start List<String> mixins.
  // String is the element type.

  set length(int value) {
    throw new UnsupportedError("Cannot resize immutable List.");
  }

  String get first {
    if (this.length > 0) {
      return JS('String', '#[0]', this);
    }
    throw new StateError("No elements");
  }

  String get last {
    int len = this.length;
    if (len > 0) {
      return JS('String', '#[#]', this, len - 1);
    }
    throw new StateError("No elements");
  }

  String get single {
    int len = this.length;
    if (len == 1) {
      return JS('String', '#[0]', this);
    }
    if (len == 0) throw new StateError("No elements");
    throw new StateError("More than one element");
  }

  String elementAt(int index) => this[index];
  // -- end List<String> mixins.

  void __setter__(int index, String newItem) native;

  String appendItem(String newItem) native;

  void clear() native;

  String getItem(int index) native;

  String initialize(String newItem) native;

  String insertItemBefore(String item, int index) native;

  String removeItem(int index) native;

  String replaceItem(String newItem, int index) native;
}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@Native("SVGStyleElement")
class StyleElement extends SvgElement {
  // To suppress missing implicit constructor warnings.
  factory StyleElement._() {
    throw new UnsupportedError("Not supported");
  }

  factory StyleElement() =>
      _SvgElementFactoryProvider.createSvgElement_tag("style") as StyleElement;
  /**
   * Constructor instantiated by the DOM when a custom element has been created.
   *
   * This can only be called by subclasses from their created constructor.
   */
  StyleElement.created() : super.created();

  bool? get disabled native;

  set disabled(bool? value) native;

  String? get media native;

  set media(String? value) native;

  StyleSheet? get sheet native;

  // Use implementation from Element.
  // String? get title native;
  // void set title(String? value) native;

  String? get type native;

  set type(String? value) native;
}
// Copyright (c) 2011, the Dart project au


90 80227780 2610C2E0 */  addiu $s0, %lo(D_800EC2E0) # addiu $s0, $s0, -0x3d20
/* 247E94 80227784 2673C4A0 */  addiu $s3, %lo(D_800EC4A0) # addiu $s3, $s3, -0x3b60
/* 247E98 80227788 2412FFFF */  li    $s2, -1
/* 247E9C 8022778C 8E270000 */  lw    $a3, ($s1)
.L80227790_ovl19:
/* 247EA0 80227790 8CE90000 */  lw    $t1, ($a3)
/* 247EA4 80227794 00095080 */  sll   $t2, $t1, 2
/* 247EA8 80227798 020A5821 */  addu  $t3, $s0, $t2
/* 247EAC 8022779C 8D620000 */  lw    $v0, ($t3)
/* 247EB0 802277A0 1242001D */  beq   $s2, $v0, .L80227818_ovl19
/* 247EB4 802277A4 00000000 */   nop
/* 247EB8 802277A8 10400019 */  beqz  $v0, .L80227810_ovl19
/* 247EBC 802277AC 00002025 */   move  $a0, $zero
/* 247EC0 802277B0 24040001 */  li    $a0, 1
/* 247EC4 802277B4 0C02BEED */  jal   func_800AFBB4
/* 247EC8 802277B8 00E02825 */   move  $a1, $a3
/* 247ECC 802277BC 8E2C0000 */  lw    $t4, ($s1)
/* 247ED0 802277C0 8D820000 */  lw    $v0, ($t4)
/* 247ED4 802277C4 00021080 */  sll   $v0, $v0, 2
/* 247ED8 802277C8 02626821 */  addu  $t5, $s3, $v0
/* 247EDC 802277CC 8DA30000 */  lw    $v1, ($t5)
/* 247EE0 802277D0 50600007 */  beql  $v1, $zero, .L802277F0_ovl19
/* 247EE4 802277D4 02027021 */   addu  $t6, $s0, $v0
/* 247EE8 802277D8 0C02A806 */  jal   func_800AA018
/* 247EEC 802277DC 00602025 */   move  $a0, $v1
/* 247EF0 802277E0 8E2F0000 */  lw    $t7, ($s1)
/* 247EF4 802277E4 8DE20000 */  lw    $v0, ($t7)
/* 247EF8 802277E8 00021080 */  sll   $v0, $v0, 2
/* 247EFC 802277EC 0202702


tId());

   for (int i=0;i<comps.size();i++)
   {
    // add components to app
    Component comp = comps.get(i);

    String res = getComp2Endpoints(comp.getId()).getJSON();
    JsonArray endpoints = new JsonParser().parse(res).getAsJsonArray();

    HashMap<Integer,Integer> srv4comps = new HashMap<Integer, Integer>();

    for (int x=0;x<endpoints.size();x++)
    {
     JsonObject obj = endpoints.get(x).getAsJsonObject();
     Integer id = new Integer(obj.get("id").getAsString());
     srv4comps.put(id, null);
    }

    if (!added.contains(comp.getOtid().toString()))
    {
     added.add(comp.getOtid().toString());
     nodes.add(new DeployDepsNode(comp.getOtid().toString(), comp.getName()).getJSON());
    }
    if (!edges_added.add(comp.getOtid().toString() + "-" + d.getApplication().getOtid().toString()))
    {
    edges_added.add(comp.getOtid().toString() + "-" + d.getApplication().getOtid().toString());
    edges.add(new DeployDepsEdge(comp.getOtid().toString(), d.getApplication().getOtid().toString()).getJSON());
    }

    List <Server> srvlist = GetServersWithComponentsDeployed(d.getEnvironment().getId(),comp.getId());

    for (int k=0;k<srvlist.size();k++)
    {
     // add components to server
     Server s = srvlist.get(k);

     if (!srv4comps.containsKey(new Integer(s.getId())))
      continue;

     if (!edges_added.contains(s.getOtid() + "-" + comp.getOtid()))
     {
      edges_added.add(s.getOtid() + "-" + comp.getOtid());
      edges.add(new DeployDepsEdge(comp.getOtid().toString(), s.getOtid().toString()).getJSON());
     }
    }
   }

   // Now handle other components on the servers
//   for (int i=0;i<servers.size();i++)
//   {
//    comps = this.getComponentsOnServerList(servers.get(i));
//    for (int k=0;k<comps.size();k++)
//    {
//     // add other components to servers
//     Component comp = comps.get(k);
//     if (!added.contains(comp.getOtid().toString()))
//     {
//      added.add(comp.getOtid().toString());
//      nodes.add(new DeployDepsNode(comp.getOtid().toString(), comp.getName()).getJSON());
//     }
//
//     if (!edges_added.contains(servers.get(i).getOtid() + "-" + comp.getOtid()))
//     {
//      edges_added.add(servers.get(i).getOtid() + "-" + comp.getOtid());
//      edges.add(new DeployDepsEdge(comp.getOtid().toString(), servers.get(i).getOtid().toString(),true).getJSON());
//     }
//
//     comp = getComponent(comp.getId(),true);
//
//     defects = getDefectsForComponent(comp.getId());
//
//     for (int j=0;j<defects.getDefects().size();j++)
//     {
//      Defect defect = defects.getDefects().get(j);
//
//      // add defects to component
//      if (!added.contains("df" + defect.getId()))
//      {
//       added.add("df" + defect.getId());
//       nodes.add(new DeployDepsNode("df" + defect.getId(), "CR " + defect.getName()).getJSON());
//      }
//      if (!edges_added.contains("df" + defect.getId() + "-" + comp.getOtid().toString()))
//      {
//       edges_


 hubo un error.', m);
  }

  const videoUrl = result.data.url;

  if (!videoUrl) {
    return conn.reply(m.chat, 'No se encontró un enlace de video válido.', m);
  }

  const caption = '🍬 Aquí está tu video de Snapchat:';
  const maxRetries = 3;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      await conn.sendMessage(m.chat, { video: { url: videoUrl }, caption }, { quoted: m });
      await m.react('✅');
      break;
    } catch (e) {
      if (attempt === maxRetries) {
        await m.react('❌');
        return conn.reply(m.chat, 'Error al enviar el video después de varios intentos.', m);
      }
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
}

handler.help = ['snapchat'];
handler.tags = ['descargas'];
handler.command = ['snapchat', 'snapdl'];
handler.register = true;

export default handler;let users = {};

let handler = async (m, { conn, text, usedPrefix, command }) => {
    let [eleccion, cantidad] = text.split(' ');
    if (!eleccion || !cantidad) {
        return m.reply(`${emoji} Por favor, elige cara o cruz y una cantidad de ${moneda} para apostar.\nEjemplo: *${usedPrefix + command} cara 50*`);
    }

    eleccion = eleccion.toLowerCase();
    cantidad = parseInt(cantidad);
    if (eleccion !== 'cara' && eleccion !== 'cruz') {
        return m.reply(`${emoji2} Elección no válida. Por favor, elige cara o cruz.\nEjemplo: *${usedPrefix + command} cara*`);
    }

    if (isNaN(cantidad) || cantidad <= 0) {
        return m.reply(`${emoji2} Cantidad no válida. Por favor, elige una cantidad de ${moneda} para apostar.\nEjemplo: *${usedPrefix + command} cara 50*`);
    }

    let userId = m.sender;
    if (!users[userId]) users[userId] = { coin: 100 };
    let user = global.db.data.users[m.sender];
    if (user.coin < cantidad) {
        return m.reply(`${emoji2} No tienes suficientes ${moneda} para apostar. Tienes ${user.coin} ${moneda}.`);
    }

    let resultado = Math.random() < 0.5 ? 'cara' : 'cruz';
   let mensaje = `${emoji} La moneda ha caído en `
    if (resultado === eleccion) {
        user.coin += cantidad;
    mensaje += `*${resultado}* y has ganado *${cantidad} ${moneda}*!`;
    } else {
        user.coin -= cantidad;
        mensaje += `*${resultado}* y has perdido *${cantidad} ${moneda}*!`;
    }

    await conn.reply(m.chat, mensaje, m);
};

handler.help = ['cf'];
handler.tags = ['economy'];
handler.command = ['cf', 'suerte', 'caracruz'];
handler.group = true;
handler.register = true;

export default handler;
import {format} from 'util';
const debug


�费内存，得不偿失。
  2. 每个需要使用对象池的对象都需要继承对象池的基类对象，这样在初始化时可以针对不同对象做重载，区别对待不同类型的对象。让不同对象的初始化方法根据各自的情况分别处理。
  3. 销毁操作时使用对象池接口进行销毁。在销毁物体时要使用对象池提供的销毁接口，让对象池来决定是真销毁，还是只是隐藏对象。
  4. 场景结束时要及时销毁整个对象池，避免无意义的内存驻留。当场景结束后，在对象池内的物体，已经不再适合新的场景了，或者说面临的环境情况与旧场景不同时所以需要及时清理对象池，把内存空出来留给新场景使用。

### UI贴图设置的优化

* 为什么要关心UI贴图设置？

  首先我们得知道，Unity3D会重置全部贴图格式。可以理解为，无论你是JPG，PNG，PSD等，只要放在Unity3D中，Unity3D会读取图片内容，然后重新生成一个自己格式的图，在引擎中使用的是自己生成的图和格式。因此在Unity3D中使用图片其实不必关心用什么格式的图，只要你做好内容就可以了，比如JPG是没有alhpa通道的，通常做透贴都是PNG，这些图形或颜色内容上的东西是我们需要关心的，其他的交给Unity3D就可以。

  Unity3D中图片的设置也有很多讲究，因为关系到重新生成的图片的格式，最终将决定加载入引擎的是什么样格式的图片，所以我们不得不要研究下贴图的设置问题。

* UI的选项的优化，我们可以通过写脚本的方式，把放入UI的贴图自动设置我们规定好的图片选项，辅助我们更改UI贴图设置，省去不少二次检查时间。例如以下这段，就是利用Unity3D的 Editor API 来自动设置UGUI的精灵图片。

  要完全省去检查时间是不可能的，在实际项目中我们也不得不从头检查一遍所有贴图的设置情况，来确认是否是我们所期望的设置，不过工作量比以前少了很多，可靠性也增强了许多。

### 内存泄露

* 什么是内存泄露？

  内存泄漏，简单来说就是由程序向系统申请内存，使用完毕后并没有将内存还给系统导致


这些基因．

![](../img/18/fig18.3.png)

图 18.4（上图）演示了收缩的影响．没有收缩时我们在测试数据上有 5/20 的误差，并且在训练和 CV 数据上有一些误差．当 $\Delta$ 在相当宽的区域中，收缩重心达到零测试误差．图 18.4 的下图显示了 SRBCT 数据（灰色）的四个重心，这是相对整体重心来说．蓝色条状是这些重心的收缩版本，这是通过取 $\Delta=4.3$ 对灰色条状进行软阈值得到的．判别分数 \eqref{18.2} 可以用来构造类别概率估计：

$$
\hat p_k(x^*)=\frac{e^{\frac{1}{2}\delta_k(x^*)}}{\sum_{\ell=1}^Ke^{\frac{1}{2}\delta_\ell(x^*)}}\tag{18.8}
$$

!!! note "Recall"
    $$
    \hat\gamma_{im}=\frac{\hat\alpha_m\phi(x_i;\hat\mu_m,\hat\Sigma_m)}{\sum_{k=1}^M\hat\alpha_k\phi(x_i;\hat\mu_k,\hat\Sigma_k)}\tag{6.33}
    $$

这些可以用来评估分类，或者决定不对某个样本分类．

注意到特征选择的其它形式也可以用在这种设定中，包括硬阈值．Fan and Fan (2008)[^2] 理论上证明了高维问题中用对角线性判别分析进行某些特征选择的重要性．

[^1]: Bickel, P. J., Ritov, Y. and Tsybakov, A. (2008). Simultaneous analysis of lasso and Dantzig selector, Annals of Statistics. to appear.
[^2]: Fan, J. and Fan, Y. (2008). High dimensional classification using features annealed independence rules, Annals of Statistics. to appear.
# 11.7 例子：邮编数据

| 原文   | [The Elements of Statistical Learning](https://esl.hohoweiya.xyz/book/The%20Elements%20of%20Statistical%20Learning.pdf) |
| ---- | ---------------------------------------- |
| 翻译   | szcf-weiya                               |
| 发布 | 2017-12-28 |

这个例子是字体识别任务：对手写字母分类．这个问题引起了机器学习和神经网络社区数年的关注，并且仍是该领域的基准问题．图11.9展示了标准化手写字体的一些例子，这是从美国邮局服务的信封中自动扫描得到的．原始的扫描数字是二值的且有不同的大小和朝向；这里展示的图象已经被deslanted且大小被标准化了，最终得到$16\times 16$的灰白图象（


575254,
                '青海': 5626722,
                '宁夏': 6301350,
                '新疆': 21813334,
                '香港': 7097600,
                '澳门': 552300,
                '台湾': 0
            }
          }
        };
        //make cache for city data
        (function () {
          var makeCityHash = function(stage, cityListName, cityHashName){
            var cityHash = data[stage][cityHashName] = {};
            data[stage][cityListName].forEach(function (d, i) {
              cityHash[d.name] = d;
            });
          };
          makeCityHash('tgi', 'searchTopCities', 'searchCityHash');
          makeCityHash('tgi', 'tradeTopCities', 'tradeCityHash');
          makeCityHash('popu', 'searchTopCities', 'searchCityHash');
          makeCityHash('popu', 'tradeTopCities', 'tradeCityHash');
        }());

        var highlightCityPoint = function (cityName) {
          var cityData = data[stage].searchCityHash[cityName] || data[stage].tradeCityHash[cityName];
          highlightedCityPoint = chinamap.createCityPoints([cityData], function (city) {
                        return this.paper.circle(city.coord[0], city.coord[1], 30)
                            .attr({
                                "stroke-width": 4,
                                "stroke": "steelblue",
                                "fill": "#fff"
                                })
                            .data("cityInfo", city)
                            .mouseout(function () {
                              //lowlightCity(city.name);
                              chinamap.fire("cityMouseout", city.name);
                            });
                    })[0];
          var cityInfo = highlightedCityPoint.data("cityInfo");
          chinamap.floatTag.html("
" + cityInfo.name + "
"
              + "
" + (stage === 'tgi' ? "搜索tgi排名： " : "搜索人群占比排名：") + cityInfo.search + "
"
              + "
" + (stage === 'tgi' ? "成交tgi排名： " : "成交人群占比排名：") + cityInfo.trade + "
")
              .css("visibility", "visible");
          chinamap.floatTag.creator.changeLoc(cityInfo.pointLoc);
        };

        var lowlightCityPoint = function () {
          if (typeof highlightedCityPoint !== 'undefined') {
            highlightedCityPoint.remove();
            highlightedCityPoint = undefined;
            chinamap.floatTag.css("visibility", "hidden");
          }
        };
        var fillTable = function () {
          var getProvince = function (stage, indexType) {
            var stageData = data[stage];
            var provinceData;
            var html = '';
            if (indexType === 'search') {
              provinceData = stageData['searchTopProvinces'];
            } else {
              provinceData = stageData['tradeTopProvinces'];
            }
            html += '
';
            provinceData.forEach(function (d, i) {
              html += '
' + (i + 1) + ' ' + d + '
';
            });
            html +=


buffered
	// request about to be written. Writing requests only grabs the batch
	// mu, not the recBuf mu.
	batch0.mu.Lock()
	batch0.tries++
	var (
		canFail        = !recBuf.cl.idempotent() || batch0.canFailFromLoadErrs // we can only fail if we are not idempotent or if we have no outstanding requests
		batch0Fail     = batch0.maybeFailErr(&recBuf.cl.cfg) != nil            // timeout, retries, or aborting
		netErr         = isRetryableBrokerErr(err) || isDialNonTimeoutErr(err) // we can fail if this is *not* a network error
		retryableKerr  = kerr.IsRetriable(err)                                 // we fail if this is not a retryable kerr,
		isUnknownLimit = recBuf.checkUnknownFailLimit(err)                     // or if it is, but it is UnknownTopicOrPartition and we are at our limit

		willFail = canFail && (batch0Fail || !netErr && (!retryableKerr || retryableKerr && isUnknownLimit))
	)
	batch0.isFailingFromLoadErr = willFail
	batch0.mu.Unlock()

	recBuf.cl.cfg.logger.Log(LogLevelWarn, "produce partition load error, bumping error count on first stored batch",
		"broker", logID(recBuf.sink.nodeID),
		"topic", recBuf.topic,
		"partition", recBuf.partition,
		"err", err,
		"can_fail", canFail,
		"batch0_should_fail", batch0Fail,
		"is_network_err", netErr,
		"is_retryable_kerr", retryableKerr,
		"is_unknown_limit", isUnknownLimit,
		"will_fail", willFail,
	)

	if willFail {
		recBuf.failAllRecords(err)
	}
}

// Called locked, if err is an unknown error, bumps our limit, otherwise resets
// it. This returns if we have reached or exceeded the limit.
func (recBuf *recBuf) checkUnknownFailLimit(err error) bool {
	if errors.Is(err, kerr.UnknownTopicOrPartition) {
		recBuf.unknownFailures++
	} else {
		recBuf.unknownFailures = 0
	}
	return recBuf.cl.cfg.maxUnknownFailures >= 0 && recBuf.unknownFailures > recBuf.cl.cfg.maxUnknownFailures
}

// failAllRecords fails all buffered records in this recBuf.
// This is used anywhere where we have to fail and remove an entire batch,
// if we just removed the one batch, the seq num chain would be broken.
//
//   - from fatal InitProducerID or AddPartitionsToTxn
//   - from client closing
//   - if not idempotent && hit retry / timeout limit
//   - if batch fails fatally when producing
func (recBuf *recBuf) failAllRecords(err error) {
	recBuf.lockedStopLinger()
	for _, batch := range recBuf.batches {
		// We need to guard our clearing of records against a
		// concurrent produceRequest's write, which can have this batch
		// buffered wile we are failing.
		//
		// We do not need to worry about concurrent recBuf
		// modifications to this batch because the recBuf is already
		// locked.
		batch.mu.Lock()
		records := batch.records
		batch.records = nil
		batch.mu.Unlock()

		recBuf.cl.producer.promiseBatch(batchPromise{
			recs: records,
			err:  err,
		})
	}
	recBuf.resetBatchDrainIdx()
	recBuf.buffered.Store(0)
	recBuf.batches = nil
}

// clearFailing clears a buffer's failing state if it is failing.
//
// This is called when a buffer is added to a sink (to clear a failing state
// from migrating buffers between


>

deviceTag

private java.lang.String deviceTag

Constructor Detail

CctvPopId

public CctvPopId()

CctvPopId

public CctvPopId(java.lang.String computerId,
                 java.lang.String deviceTag)

Method Detail

getComputerId

public java.lang.String getComputerId()

setComputerId

public void setComputerId(java.lang.String computerId)

getDeviceTag

public java.lang.String getDeviceTag()

setDeviceTag

public void setDeviceTag(java.lang.String deviceTag)

equals

public boolean equals(java.lang.Object other)

Overrides:
equals in class java.lang.Object

hashCode

public int hashCode()

Overrides:
hashCode in class java.lang.Object


td>
          </ng-container>

    <button type="button" class="btn btn-success ms-2"
      (click)="close('confirmed')" i18n>Close</button>

</ng-template>

<button *ngIf="viaContextMenu" class="dropdown-item"
  (click)="openCopyToClipboard()" type="button">

Copy to Clipboard

</button>

<eg-clipboard-dialog #clipboardDialog></eg-clipboard-dialog>

<ng-container
  *ngFor="let action of gridContext.toolbarActions; let idx = index">
  <button ngbDropdownItem class="dropdown-item" *ngIf="!action.hidden"
    [disabled]="shouldDisable(action)"
    (click)="performAction(action)" type="button">
    <ng-container *ngIf="action.isGroup">
      {{action.label}}
    </ng-container>
    <ng-container *ngIf="action.isSeparator">

    </ng-container>
    <ng-container *ngIf="!action.isGroup && !action.isSeparator">

      {{action.label}}
    </ng-container>
  </button>
</ng-container>
<eg-grid-toolbar-actions-editor #toolbarActionsEditor [gridContext]="gridContext">
</eg-grid-toolbar-actions-editor>

<eg-grid-manage-filters-dialog #gridManageFiltersDialog [gridContext]="gridContext">
</eg-grid-manage-filters-dialog>

      {{gridContext.toolbarLabel}}

        <button *ngIf="!gridContext.allowNamedFilterSets" type="button"
          class="btn btn-outline-dark btn-sm" (click)="gridContext.removeFilters()"
          [disabled]="!gridContext.filtersSet() || gridContext.dataSource.requestingData" i18n>
          Remove Filters
        </button>
        <button *ngIf="gridContext.allowNamedFilterSets"
          class="btn btn-outline-dark btn-sm" type="button"
          (click)="gridManageFiltersDialog.open().subscribe()"
          [disabled]="gridContext.dataSource.requestingData" i18n>
          Manage Grid Filters
        </button>

      <ng-container *ngFor="let btn of gridContext.toolbarButtons">

            {{btn.adjacentPreceedingLabel}}

          <ng-container *ngIf="btn.adjacentPreceedingTemplateRef">
              <ng-container *ngTemplateOutlet="bt


 and std 3`() {
        val n = 100000
        val r = RandomKey()
        val gaussian = r.gaussian(Shape(n), FloatScalar(2f), FloatScalar(3f))

        val expectedMean = 2f
        // variance is the square of the standard deviation
        val expectedVariance = 9f
        stats(gaussian) shouldBeCloseTo Pair(expectedMean, expectedVariance)

    }

    @Test fun `gaussian test with mean -5 and std 0,5`() {
        val n = 100000
        val r = RandomKey()
        val gaussian = r.gaussian(Shape(n), FloatScalar(-5f), FloatScalar(0.5f))

        val expectedMean = -5f
        // variance is the square of the standard deviation
        val expectedVariance = 0.25f
        stats(gaussian) shouldBeCloseTo Pair(expectedMean, expectedVariance)

    }

    @Test fun `cauchy with loc 0 and scale 1`() {
        val n = 100000
        val r = RandomKey(1411587246503371L)
        val shape = Shape(n)

        val loc = FloatTensor.const(0f, shape)
        val scale = FloatTensor.const(1f, shape)
        val cauchy = r.cauchy(shape, loc, scale)

        // the mean and variance of a cauchy distribution is undefined
        // the output of the cdf should be a uniform distribution
        val uniform = atan((cauchy - loc) / scale) * (1f/ FloatScalar.PI) + 0.5f

        val numBuckets = 10
        val t = (uniform * numBuckets.toFloat()) as FloatTensor
        val buckets = IntArray(numBuckets)
        for (i in 0 until t.size) {
            val bucket = ((t[i] as FloatScalar).value * 1f.nextDown()).toInt()
            buckets[bucket]++
        }
        val expected = n.toFloat() / numBuckets
        for (element in buckets) {
            element.toFloat() shouldBeCloseTo expected
        }
    }

    @Test fun `cauchy with loc 10 and scale 5`() {
        val n = 100000
        val r = RandomKey(1411587246503371L)
        val shape = Shape(n)

        val loc = FloatTensor.const(10f, shape)
        val scale = FloatTensor.const(5f, shape)
        val cauchy = r.cauchy(shape, loc, scale)

        val uniform = atan((cauchy - loc) / scale) * (1f/ FloatScalar.PI) + 0.5f

        val numBuckets = 10
        val t = (uniform * numBuckets.toFloat()) as FloatTensor
        val buckets = IntArray(numBuckets)
        for (i in 0 until t.size) {
            val bucket = ((t[i] as FloatScalar).value * 1f.nextDown()).toInt()
            buckets[bucket]++
        }
        val expected = n.toFloat() / numBuckets
        for (element in buckets) {
            element.toFloat() shouldBeCloseTo expected
        }
    }

    @Test fun `chi square test with dof 1`() {
        val n = 100000
        val r = RandomKey()

        val dof = FloatScalar.ONE
        val chiSquare = r.chiSquare(Shape(n), dof)

        // chi square has the mean of dof and variance of 2 * dof
        val expectedMean = 1f
        val expectedVariance = 2f
        stats(chiSquare) shouldB


K_Greek_alpha:                   { code: 0x07e1, description: "(\u03B1) GREEK SMALL LETTER ALPHA" },
  XK_Greek_beta:                    { code: 0x07e2, description: "(\u03B2) GREEK SMALL LETTER BETA" },
  XK_Greek_gamma:                   { code: 0x07e3, description: "(\u03B3) GREEK SMALL LETTER GAMMA" },
  XK_Greek_delta:                   { code: 0x07e4, description: "(\u03B4) GREEK SMALL LETTER DELTA" },
  XK_Greek_epsilon:                 { code: 0x07e5, description: "(\u03B5) GREEK SMALL LETTER EPSILON" },
  XK_Greek_zeta:                    { code: 0x07e6, description: "(\u03B6) GREEK SMALL LETTER ZETA" },
  XK_Greek_eta:                     { code: 0x07e7, description: "(\u03B7) GREEK SMALL LETTER ETA" },
  XK_Greek_theta:                   { code: 0x07e8, description: "(\u03B8) GREEK SMALL LETTER THETA" },
  XK_Greek_iota:                    { code: 0x07e9, description: "(\u03B9) GREEK SMALL LETTER IOTA" },
  XK_Greek_kappa:                   { code: 0x07ea, description: "(\u03BA) GREEK SMALL LETTER KAPPA" },
  XK_Greek_lamda:                   { code: 0x07eb, description: "(\u03BB) GREEK SMALL LETTER LAMDA" },
  XK_Greek_lambda:                  { code: 0x07eb, description: "(\u03BB) GREEK SMALL LETTER LAMDA" },
  XK_Greek_mu:                      { code: 0x07ec, description: "(\u03BC) GREEK SMALL LETTER MU" },
  XK_Greek_nu:                      { code: 0x07ed, description: "(\u03BD) GREEK SMALL LETTER NU" },
  XK_Greek_xi:                      { code: 0x07ee, description: "(\u03BE) GREEK SMALL LETTER XI" },
  XK_Greek_omicron:                 { code: 0x07ef, description: "(\u03BF) GREEK SMALL LETTER OMICRON" },
  XK_Greek_pi:                      { code: 0x07f0, description: "(\u03C0) GREEK SMALL LETTER PI" },
  XK_Greek_rho:                     { code: 0x07f1, description: "(\u03C1) GREEK SMALL LETTER RHO" },
  XK_Greek_sigma:                   { code: 0x07f2, description: "(\u03C3) GREEK SMALL LETTER SIGMA" },
  XK_Greek_finalsmallsigma:         { code: 0x07f3, description: "(\u03C2) GREEK SMALL LETTER FINAL SIGMA" },
  XK_Greek_tau:                     { code: 0x07f4, description: "(\u03C4) GREEK SMALL LETTER TAU" },
  XK_Greek_upsilon:                 { code: 0x07f5, description: "(\u03C5) GREEK SMALL LETTER UPSILON" },
  XK_Greek_phi:                     { code: 0x07f6, description: "(\u03C6) GREEK SMALL LETTER PHI" },
  XK_Greek_chi:                     { code: 0x07f7, description: "(\u03C7) GREEK SMALL LETTER CHI" },
  XK_Greek_psi:                     { code: 0x07f8, description: "(\u03C8) GREEK SMALL LETTER PSI" },
  XK_Greek_omega:                   { code: 0x07f9, description: "(\u03C9) GREEK SMALL LETTER OMEGA" },
  XK_Greek_switch:                  { code: 0xff7e, description: "Alias for mode_switch" },

/*
 * Technical
 * (from the DEC VT330/VT4


CannotParseQuery(s: OCamlBytes),
        ProtocolRpcError::RPCErrorInvalidMethodString(s: OCamlBytes),
        ProtocolRpcError::RPCErrorMethodNotAllowed(m: OCamlList<RpcMethod>),
        ProtocolRpcError::RPCErrorServiceNotFound,
    }
}

impl_from_ocaml_record! {
    RpcArgDesc {
        name: OCamlBytes,
        descr: Option<OCamlBytes>,
    }
}

impl_from_ocaml_variant! {
    RpcMethod {
        RpcMethod::DELETE,
        RpcMethod::GET,
        RpcMethod::PATCH,
        RpcMethod::POST,
        RpcMethod::PUT,
    }
}

// TODO: remove this after TE-207 has been solved
impl_from_ocaml_variant! {
    FfiPath => FfiPath {
        Left(path: FfiPath, right: OCamlHash) => {
            let path: FfiPath = path;
            FfiPath::Left(
                Box::new(
                    FfiPathLeft {
                        path,
                        right,
                    }))
        },
        Right(left: OCamlHash, path: FfiPath) => {
            let path: FfiPath = path;
            FfiPath::Right(
                Box::new(
                    FfiPathRight {
                        left,
                        path,
                    }))
        },
        Op => FfiPath::Op,
    }
}
<reponame>lemonrock/simple-http-server<filename>workspace/simple-http-server-epoll/src/posix_message_queues/OpenOrCreatePosixMessageQueue.rs
// This file is part of simple-http-server. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT. No part of simple-http-server, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2018 The developers of simple-http-server. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/simple-http-server/master/COPYRIGHT.

/// How to open or create (or both) a message queue.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum OpenOrCreatePosixMessageQueue
{
	/// Opens the queue if it already exists; fails if it does not.
	OpenIfAlreadyExistsOrFail,

	/// Opens the queue if it already exists; creates (and implicitly opens) it is it does not.
	OpenOrCreateIfDoesNotExist(PosixMessageQueueCreateSettings),

	/// Creates (and implicitly opens) the queue if it does not already exist; fails if it does exist.
	CreateIfItDoesNotExistOrFail(PosixMessageQueueCreateSettings),
}

impl OpenOrCreatePosixMessageQueue
{
	#[inline(always)]
	pub(crate) fn invoke_mq_open(&self, send_or_receive: PosixMessageQueueCreateSendOrReceive, name: &CStr) -> Result<PosixMessageQueueFileDescriptor, CreationError>
	{
		PosixMessageQueueFileDescriptor::guard_name(name);

		use self::OpenOrCreatePosixMessageQueue::*;

		let oflag = send_or_receive as i32;

		let name_pointer = name.as_ptr();

		use self::CreationError::*;

		match self
		{
			&OpenIfAlreadyExistsOrFail =>
			{
				let result = unsafe { mq_open(name_pointer, oflag) };

				if likely!(result >= 0)
				{
					Ok(PosixMessageQueueFileDescriptor(result))
				}
				else if likely!(result == 0)
				{
					Err
					(
						match errno().0
						{
							EACCES => PermissionDenied,

							EMFILE => PerProcessLimitOnNumberOfFileDescriptorsWo


affordances -= excluded_affordances
            return affordance_types & included_affordances

    FACTORY_TYPE = _filter

    def __init__(self, description='An affordance filter.', **kwargs):
        AffordanceReference = TunableReference(services.get_instance_manager(sims4.resources.Types.INTERACTION), pack_safe=True)
        super().__init__(default_inclusion=TunableVariant(include_all=TunableTuple(include_all_by_default=Tunable(bool, True, description=''), include_affordances=TunableList(AffordanceReference, display_name='Filter Exception Items'), exclude_affordances=TunableList(AffordanceReference, display_name='Blacklist Items'), include_lists=TunableList(TunableAffordanceListReference(pack_safe=True), display_name='Filter Exception Lists'), exclude_lists=TunableList(TunableAffordanceListReference(pack_safe=True), display_name='Blacklist Lists'), locked_args={'include_all_by_default': True}, description='\n                        This will create compatibility with all interactions by default,\n                        except those that are blacklisted, from which you can define\n                        exceptions.'), exclude_all=TunableTuple(include_all_by_default=Tunable(bool, False, description=''), include_affordances=TunableList(AffordanceReference, display_name='Whitelist Items'), exclude_affordances=TunableList(AffordanceReference, display_name='Filter Exception Items'), include_lists=TunableList(TunableAffordanceListReference(pack_safe=True), display_name='Whitelist Lists'), exclude_lists=TunableList(TunableAffordanceListReference(pack_safe=True), display_name='Filter Exception Lists'), locked_args={'include_all_by_default': False}, description='\n                        This will create incompatibility with all interactions by\n                        default, except those that are whitelisted, from which you\n                        can define exceptions.'), default='include_all', description='\n                    This defines the default compatibility with other interactions.'), description=description, **kwargs)

(TunableAffordanceFilterReference, TunableAffordanceFilterSnippet) = define_snippet(AFFORDANCE_FILTER, _TunableAffordanceFilter)
(TunableColorReference, TunableColorSnippet) = define_snippet(COLOR, TunableColor())


 return nullptr;
    adj_fnum = field_num - fstart;
    uint32_t skip_num = adj_fnum / 16;
    if (PROTOBUF_PREDICT_TRUE(skip_num < num_skip_entries)) {
      // for each group of 16 fields we have:
      // a bitmap of 16 bits
      // a 16-bit field-entry offset for the first of them.
      auto* skip_data = lookup_table + (adj_fnum / 16) * (sizeof(SkipEntry16) /
                                                          sizeof(uint16_t));
      SkipEntry16 se = {skip_data[0], skip_data[1]};
      adj_fnum &= 15;
      uint32_t skipmap = se.skipmap;
      uint16_t skipbit = 1 << adj_fnum;
      if (PROTOBUF_PREDICT_FALSE(skipmap & skipbit)) return nullptr;
      skipmap &= skipbit - 1;
      adj_fnum += se.field_entry_offset;
#if (__GNUC__ || __clang__) && __POPCNT__
      adj_fnum -= __builtin_popcount(skipmap);
#else
      while (skipmap) {
        --adj_fnum;
        skipmap &= skipmap - 1;
      }
#endif
      auto* entry = field_entries + adj_fnum;
      PROTOBUF_ASSUME(entry != nullptr);
      return entry;
    }
    lookup_table +=
        num_skip_entries * (sizeof(SkipEntry16) / sizeof(*lookup_table));
  }
}

// Field names are stored in a format of:
//
// 1) A table of name sizes, one byte each, from 1 to 255 per name.
//    `entries` is the size of this first table.
// 1a) padding bytes, so the table of name sizes is a multiple of
//     eight bytes in length. They are zero.
//
// 2) All the names, concatenated, with neither separation nor termination.
//
// This is designed to be compact but not particularly fast to retrieve.
// In particular, it takes O(n) to retrieve the name of the n'th field,
// which is usually fine because most protos have fewer than 10 fields.
static StringPiece FindName(const char* name_data, size_t entries,
                                  size_t index) {
  // The compiler unrolls these... if this isn't fast enough,
  // there's an AVX version at https://godbolt.org/z/eojrjqzfr
  // ARM-compatible version at https://godbolt.org/z/n5YT5Ee85

  // The field name sizes are padded up to a multiple of 8, so we
  // must pad them here.
  size_t num_sizes = (entries + 7) & -8;
  auto* uint8s = reinterpret_cast<const uint8_t*>(name_data);
  size_t pos = std::accumulate(uint8s, uint8s + index, num_sizes);
  size_t size = name_data[index];
  auto* start = &name_data[pos];
  return {start, size};
}

StringPiece TcParser::MessageName(const TcParseTableBase* table) {
  return FindName(table->name_data(), table->num_field_entries + 1, 0);
}

StringPiece TcParser::FieldName(const TcParseTableBase* table,
                                      const FieldEntry* field_entry) {
  const FieldEntry* const field_entries = table->field_entries_begin();
  auto field_index = static_cast<size_t>(field_entry - field_entries);
  return FindName(table->name_data(), table->num_field_entries + 1,
                  field_index + 1);
}

const char* TcParser::MiniParse(PROTOBUF_TC_PARAM_DECL) {
  uint32_t tag;
  ptr = ReadTagInlined(ptr, &tag);
  if (PROTOBUF_PREDICT_FALSE(ptr == nullptr)) return nullptr;

  auto* entry = FindFieldEntry(table, tag >> 3);
  if (


   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6assignEPKcj(i5, 34438, 49);
   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6__initEPKcj(i6, 34488, 13);
   break;
  }
  i7 = _memcmp(i2, 34327, i3) | 0;
  if (!(((i7 | 0) == 0 ? i1 : i7) | 0)) {
   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6assignEPKcj(i5, 34502, 49);
   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6__initEPKcj(i6, 34552, 13);
   break;
  }
  i3 = i4 >>> 0 > 13;
  i7 = _memcmp(i2, 34340, i3 ? 13 : i4) | 0;
  if (!(((i7 | 0) == 0 ? (i4 >>> 0 < 13 ? -1 : i3 & 1) : i7) | 0)) {
   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6assignEPKcj(i5, 34566, 50);
   __ZNSt3__112basic_stringIcNS_11char_traitsIcEEN10__cxxabiv112_GLOBAL__N_112malloc_allocIcEEE6__initEPKcj(i6, 34617, 14);
   break;
  }
  i1 = i2 + i4 | 0;
  L16 : do if ((HEAP8[i1 + -1 >> 0] | 0) == 62) {
   i4 = 1;
   L17 : while (1) {
    i3 = i1;
    L19 : while (1) {
     i1 = i3 + -1 | 0;
     if ((i1 | 0) == (i2 | 0)) break L17;
     i3 = i3 + -2 | 0;
     switch (HEAP8[i3 >> 0] | 0) {
     case 60:
      {
       i5 = 18;
       break L19;
      }
     case 62:
      {
       i5 = 19;
       break L19;
      }
     default:
      i3 = i1;
     }
    }
    if ((i5 | 0) == 18) {
     i4 = i4 + -1 | 0;
     if (!i4) {
      i1 = i3;
      break L16;
     } else continue;
    } else if ((i5 | 0) == 19) {
     i4 = i4 + 1 | 0;
     continue;
    }
   }
   i1 = 0;
   while (1) {
    if ((i1 | 0) == 3) break L1;
    HEAP32[i6 + (i1 << 2) >> 2] = 0;
    i1 = i1 + 1 | 0;
   }
  } while (0);
  i4 = i1;
  while (1) {
   i3 = i4 + -1 | 0;
   if ((i3 | 0) == (i2 | 0)) break;
   if ((HEAP8[i3 >> 0] | 0) == 58) {
    i2 = i4;
    break;
   } else i4 = i3;
  }
  i5 = i1 - i2 | 0;


AL_DIGITS_hasINTERIMValue_mdrReqINTERVAL_3S1() throws SQLException {
    assertThat(getIntOrNull(mdrReqINTERVAL_3S, "DECIMAL_DIGITS")).isEqualTo(6);
  }

  @Test
  @Ignore("TODO(DRILL-3253): unignore when we have all-types test storage plugin")
  public void test_DECIMAL_DIGITS_hasRightValue_tdbARRAY() throws SQLException {
    assertThat(getIntOrNull(mdrReqARRAY, "DECIMAL_DIGITS")).isNull();
  }

  @Test
  @Ignore("TODO(DRILL-3253): unignore when we have all-types test storage plugin")
  public void test_DECIMAL_DIGITS_hasRightValue_tbdMAP() throws SQLException {
    assertThat(getIntOrNull(mdrReqMAP, "DECIMAL_DIGITS")).isNull();
  }

  @Test
  @Ignore("TODO(DRILL-3253): unignore when we have all-types test storage plugin")
  public void test_DECIMAL_DIGITS_hasRightValue_tbdSTRUCT() throws SQLException {
    assertThat(getIntOrNull(mdrUnkSTRUCT, "DECIMAL_DIGITS")).isNull();
  }

  @Test
  @Ignore("TODO(DRILL-3253): unignore when we have all-types test storage plugin")
  public void test_DECIMAL_DIGITS_hasRightValue_tbdUnion() throws SQLException {
    assertThat(getIntOrNull(mdrUnkUnion, "DECIMAL_DIGITS")).isNull();
  }

  @Test
  public void test_DECIMAL_DIGITS_hasSameNameAndLabel() throws SQLException {
    assertThat(rowsMetadata.getColumnName(9)).isEqualTo("DECIMAL_DIGITS");
  }

  @Test
  public void test_DECIMAL_DIGITS_hasRightTypeString() throws SQLException {
    assertThat(rowsMetadata.getColumnTypeName(9)).isEqualTo("INTEGER");
  }

  @Test
  public void test_DECIMAL_DIGITS_hasRightTypeCode() throws SQLException {
    assertThat(rowsMetadata.getColumnType(9)).isEqualTo(Types.INTEGER);
  }

  @Test
  public void test_DECIMAL_DIGITS_hasRightClass() throws SQLException {
    assertThat(rowsMetadata.getColumnClassName(9)).isEqualTo(Integer.class.getName());
  }

  @Test
  public void test_DECIMAL_DIGITS_hasRightNullability() throws SQLException {
    assertThat(rowsMetadata.isNullable(9)).isEqualTo(columnNullable);
  }

  ////////////////////////////////////////////////////////////
  // #10: NUM_PREC_RADIX:
  // - JDBC:  "10. ... int => Radix (typically either 10 or 2)"
  //   - Seems should be null for non-numeric, but unclear.
  // - Dremio:  ?
  // - (Meta): INTEGER?; Nullable?;
  //
  // Note:  Some MS page says NUM_PREC_RADIX specifies the units (decimal digits
  // or binary nodes COLUMN_SIZE, and is NULL for non-numeric columns.

  @Test
  public void test_NUM_PREC_RADIX_isAtRightPosition() throws SQLException {
    assertThat(rowsMetadata.getColumnLabel(10)).isEqualTo("NUM_PREC_RADIX");
  }

  @Test
  public void test_NUM_PREC_RADIX_hasRightValue_mdrOptBOOLEAN() throws SQLException {
    assertThat(getIntOrNull(mdrOptBOOLEAN, "NUM_PREC_RADIX")).isNull();
  }

  @Ignore("TODO(DRILL-2470): unign


晰以便AI 識別。",
  "短信%0/条，自动从企业账务中心扣费。70字计一条短信，超过70字以67字每条计费。每个标点、空格、英文字母都算一个字。短信实际发送可能有10-20分钟的延时。": "簡訊%0/條，自動向企業帳務中心扣費。 70字計一條簡訊，超過70字以67字每條計費。每個標點、空格、英文字母都算算一個字。簡訊實際發送可能有10-20分鐘的延遲。",
  "纯文本": "純文字",
  "邮件%0/封，将自动从企业账户扣除。": "郵件%0/封，將自企業帳戶自動扣除。",
  "实际运行时停留的秒钟数可能比设置的时间略长": "實際運行時停留的秒鐘數可能比設定的時間略長",
  "暂停运行当前流程，并在到达指定时间后继续执行": "暫停運行當前流程，並在到達指定時間後繼續執行",
  "将发送 API 请求、代码块、AI 获取数据对象节点中的JSON 对象解析为后续节点可使用的参数": "將發送 API 請求、代碼區塊、AI 取得資料對象節點中的 JSON 對象解析為後續節點可使用的參數",
  "人脸识别链接获取失败": "人臉識別鏈接獲取失敗",
  "今天人脸识别次数已用完": "今天人臉識別次數已用完",
  "人脸识别失败": "人臉識別失敗",
  "图形验证码错误": "圖形驗證碼錯誤",
  "操作账号": "操作帳號",
  "下次不再提示": "下次不再提示",
  "仅对主流程进行测试执行。引用的子流程、PBP、审批流程将跳过执行，可单独前往测试这些流程。": "僅對主流程進行測試執行。引用的子流程、PBP、審核流程將跳過執行，可單獨前往測試這些流程。",
  "审批、填写节点无需操作，将会自动通过。": "審核、填寫節點無需操作，將會自動通過。",
  "执行当前运行中的流程": "執行當前運行中的流程",
  "查询或获取一条符合条件的工作表记录": "查詢或取得一條符合條件的工作表紀錄",
  "获取操作明细": "取得操作明細",
  "获取关联记录": "取得關聯資料",
  "获取批量新增结果": "取得批次新增結果",


.x + normal.x * j,
                                newVelocity.y + normal.y * j
                            )
                        }

                        // Prevent ball overlap (position correction)
                        val overlap = ball.radius + otherBall.radius - distance
                        if (overlap > 0) {
                            val separationVector = normal * overlap * 0.5f
                            newPosition = Offset(
                                newPosition.x + separationVector.x,
                                newPosition.y + separationVector.y
                            )
                        }
                    }
                }
            }
        }

        // Return updated ball state
        ball.copy(position = newPosition, velocity = newVelocity)
    }
}
package mods.eln.mechanical

import mods.eln.cable.CableRender
import mods.eln.cable.CableRenderDescriptor
import mods.eln.cable.CableRenderType
import mods.eln.misc.*
import mods.eln.node.transparent.*
import mods.eln.sim.process.destruct.WorldExplosion
import mods.eln.sound.LoopedSound
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraftforge.client.IItemRenderer
import org.lwjgl.opengl.GL11
import java.io.DataInputStream
import java.io.DataOutputStream
import kotlin.reflect.KClass

abstract class SimpleShaftDescriptor(name: String, elm: KClass<out TransparentNodeElement>, render: KClass<out TransparentNodeElementRender>, tag: EntityMetaTag) :
    TransparentNodeDescriptor(name, elm.java, render.java, tag) {

    abstract val obj: Obj3D
    abstract val static: Array<out Obj3D.Obj3DPart>
    abstract val rotating: Array<out Obj3D.Obj3DPart>
    // If you set this you should also set volumeSetting in render.
    // (Otherwise it'll stick to 100% volume.)
    internal open val sound: String? = null

    init {
        voltageLevelColor = VoltageLevelColor.Neutral
    }

    open fun draw(angle: Double) {
        for (part in static) {
            part.draw()
        }
        preserveMatrix {
            assert(rotating.size > 0)
            val bb = rotating[0].boundingBox()
            val centre = bb.centre()
            val ox = centre.xCoord
            val oy = centre.yCoord
            val oz = centre.zCoord
            GL11.glTranslated(ox, oy, oz)
            GL11.glRotatef(((angle * 360).toDouble() / 2.0 / Math.PI).toFloat(), 0f, 0f, 1f)
            GL11.glTranslated(-ox, -oy, -oz)
            for (part in rotating) {
                part.draw()
            }
        }
    }

    override fun renderItem(type: IItemRenderer.ItemRenderType, item: ItemStack, vararg data: Any) {
        if (type == IItemRenderer.ItemRenderType.INVENTORY) {
            super.renderItem(type, item, *data)
        } else {
            objItemScale(obj)
            preserveMatrix {
                Direction.ZN.glRotateXnRef()
                GL11.glTranslatef(0f, -1f, 0f)
                GL11.glScalef(0.6f, 0.6f, 0.6f)
                draw(0.0)
            }
        }
    }

    override fun handleRenderType(item: ItemStack, type: IItemRenderer.ItemRenderType) = true
    override fun shouldUseRenderHelper(type: IItemRenderer.ItemRenderType, item: ItemStack, helper: IItemRenderer.ItemRendererHelper) =
        type != IItemRenderer.ItemRenderType.INVENTORY
}

open class ShaftRender(entity: TransparentNodeEntity, desc: TransparentNodeDescriptor) : TransparentNodeElementRender(entity, desc) {
    private val desc = desc as SimpleShaftDescriptor
    var rads = 0.0
    var logRads =


 salga de las demás herramientas. Conoce el [¿por qué pensamos que deberías utilizar Defold aquí?](/why).

## ¿Por dónde comenzar?

Te animamos a que experimentes, sigas los tutoriales, leas nuestros manuales, la documentación de la API, y a estar activo en el foro para aprender de otros usuarios y seguir el desarrollo de Defold. Existe mucha documentación disponible, en forma de manuales, referencias a la documentación de la API, ejemplos y tutoriales. Si no sabes por dónde comenzar, aquí van algunos puntos:

#### El editor
![Editor overview](images/introduction/editor.png){.left} [La visión general del editor](/manuals/editor/) es una buena introducción debido a que te ayudará a familiarizarte con el entorno, usar las herramientas visuales y escribir código. Si estas familiarizado con programas de modelado 3D y programar con un IDE, deberías tener pocas sorpresas, aunque siempre habrá cosas un poco diferentes de tus productos de software favoritos.

#### Ejemplos sencillos
![Examples](images/introduction/examples.jpg){.left} [Nuestra colección de ejemplos sencillos](/examples/) es una buena introducción de cómo colocar elementos juntos en algo que funcione. Además, podrás encontrar ejemplos pequeños de cómo hacer una gran variedad de cosas comunes en Defold.

#### El lenguaje Lua
![Lua overview](images/introduction/lua.png){.left} [Defold utiliza Lua](/manuals/lua/) para toda su lógica de control. El motor es una pieza de maquinaria rápida escrita en C++, pero es controlada desde un alto nivel por programas escritos en Lua. Si has programado en Python, Javascript o cualquier otro lenguaje de alto nivel, podrás darte cuenta de que Lua es muy fácil de entender y posiblemente podrás seguir de principio a fin los tutoriales sin problemas. De lo contrario, puedes comenzar leyendo nuestro manual de Lua.

#### Tutoriales de Juegos
![Tutorials](images/introduction/tutorials.jpg){.left} Nostros creememos que la mejor forma de aprender es haciendo. Es por eso que tenemos una selección de tutoriales para diferentes niveles, habilidades y complejidades disponibles directamente en [el editor](/manuals/editor). Ábrelo y sigue uno o dos de los tutoriales para aprender cómo construir cosas y cómo Defold funciona.

#### Los bloques de construcción de Defold
![Building blocks](images/introduction/building_blocks.png){.left} [Los juegos de Defold son construidos agrupando bloques simples](/manuals/building-blocks/), algunos de ellos son familiares si ya has utilizado otros motores. Hay algunas decisiones de diseño arquitectónico que hacen que los bloques de Defold sean especiales y se necesita un poco de tiempo para sentirse a gusto trabajando con ellos. Nuestro manual de bloques de construcción e


econds
 * @ts:		pointer to the timespec64 variable to be converted
 *
 * Returns the scalar nanosecond representation of the timespec64
 * parameter.
 */
static inline s64 timespec64_to_ns(const struct timespec64 *ts)
{
	return ((s64) ts->tv_sec * NSEC_PER_SEC) + ts->tv_nsec;
}

/**
 * ns_to_timespec64 - Convert nanoseconds to timespec64
 * @nsec:	the nanoseconds value to be converted
 *
 * Returns the timespec64 representation of the nsec parameter.
 */
extern struct timespec64 ns_to_timespec64(const s64 nsec);

/**
 * timespec64_add_ns - Adds nanoseconds to a timespec64
 * @a:		pointer to timespec64 to be incremented
 * @ns:		unsigned nanoseconds value to be added
 *
 * This must always be inlined because its used from the x86-64 vdso,
 * which cannot call other kernel functions.
 */
static __always_inline void timespec64_add_ns(struct timespec64 *a, u64 ns)
{
	a->tv_sec += __iter_div_u64_rem(a->tv_nsec + ns, NSEC_PER_SEC, &ns);
	a->tv_nsec = ns;
}

#endif

/*
 * timespec64_add_safe assumes both values are positive and checks for
 * overflow. It will return TIME64_MAX in case of overflow.
 */
extern struct timespec64 timespec64_add_safe(const struct timespec64 lhs,
					 const struct timespec64 rhs);

#endif /* _LINUX_TIME64_H */


 {
        for (SiteTile t in levelMap.allOnFloor(locz)) {
          t.flag = 0;
          if (t.y == 0) t.exit = true;
        }

        locx = 1 + lcsRandom(MAPX - 1);
        locy = 1 + lcsRandom(18 - 1);
      }
      if (exhaustlocation > 1000) {
        locx = lcsRandom(MAPX);
        locy = lcsRandom(18);
        exhaustlocation++;
      } else {
        exhaustlocation++;
      }

      //if(locy<3) locy=3;
      locz = 0;
    } while (currentTile.wall || currentTile.door || currentTile.burning);

    //PLACE LOOT
    int lootnum = loc.loot.length;
    if (lootnum > 10) lootnum = 10;

    SiteTile tile;
    for (int l = 0; l < lootnum; l++) {
      Iterable<SiteTile> options = levelMap
          .allOnFloor(0)
          .where((t) => !t.wall && !t.door && !t.exit && !t.loot);
      if (options.isEmpty) break;
      tile = options.where((t) => !t.outdoor).randomOrNull ?? options.random;
      tile.loot = true;
    }

    //PLACE TRAPS
    if (loc.compound.boobyTraps) {
      int trapnum = 30;
      for (int t = 0; t < trapnum; t++) {
        tile = levelMap.allOnFloor(0).randomWhere(
            (tile) => !tile.wall && !tile.door && !tile.exit && !tile.loot);
        tile.siegeTrap = true;
      }
    }

    //PLACE UNITS
    int unitnum = 6;
    int count = 50000;
    for (int t = 0; t < unitnum; t++) {
      do {
        tile = levelMap[lcsRandom(11) + MAPX ~/ 2 - 5][lcsRandom(8)][0];
        count--;
        if (count == 0) break;
      } while (tile.wall ||
          tile.door ||
          tile.exit ||
          tile.siegeUnit ||
          tile.siegeHeavyUnit ||
          tile.siegeTrap);

      tile.siegeUnit = true;
    }

    if (!loc.compound.bollards &&
        loc.siege.activeSiegeType == SiegeType.police &&
        loc.siege.escalationState.index >= 2) {
      levelMap[MAPX ~/ 2][1][0].siegeHeavyUnit = true;
      loc.siege.tanks = 1;
    }
  }

  await _siteModeAux();

  encounter.clear();
}

Future<void> _siteModeAux() async {
  int u, x;
  if (activeSquad == null) return;

  for (Creature c in squad) {
    c.location = activeSite;
  }

  await reloadparty(false);

  bool bailOnBase = true;
  if (activeSite == squad.first.base) bailOnBase = false;

  knowmap(locx, locy, locz);

  bool hostcheck = false;

  int encounterTimer = 0;

  while (true) {
    int partysize = squad.length;
    bool partyalive = activeSquad!.livingMembers.isNotEmpty;
    int hostages = 0, encsize = 0, freeable = 0, talkers = 0;
    bool enemy = false;
    for (Creature p in squad) {
      if (p.prisoner != null && p.prisoner!.align != Alignment.liberal) {
        hostages++;
      }
    }
    for (Creature e in encounter) {
      encsize++;
      if (e.isEnemy) enemy = true;
      if (e.type.freeable ||
          ((e.name == "Prisoner") && e.align == Alignment.liberal)) {
        freeable++;
      } else if ((e.isWillingToTalk || (e.isEnemy && siteAlarm)) &&
          !(!e.isEnemy && siteAlarm && enemy)) {
        talkers++;
      }


         Description = "Set thirty years after the events of the 1984 All Valley Karate Tournament, the series focuses on Johnny Lawrence reopening the Cobra Kai dojo, which causes his rivalry with Daniel LaRusso to be reignited.",
                Category = actionCategory
            });

            dbContext.Products.Add(new Product
            {
                Name = "The Kissing Booth",
                Description = "A high school student is forced to confront her secret crush at a kissing booth.",
                Category = romanceCategory
            });

            dbContext.Products.Add(new Product
            {
                Name = "Shadowhunters: The Mortal Instruments",
                Description = "After her mother disappears, Clary must venture into the dark world of demon hunting, and embrace her new role among the Shadowhunters.",
                Category = romanceCategory
            });

            dbContext.SaveChanges();
        }

        private static void GenerateForTenant3(ApplicationDbContext dbContext)
        {
            var winesCategory = new ProductCategory { Name = "Wines" };
            var beersCategory = new ProductCategory { Name = "Beers" };

            dbContext.Categories.Add(winesCategory);
            dbContext.Categories.Add(beersCategory);

            dbContext.Products.Add(new Product
            {
                Name = "Cramele Tataran ITCamp Edition",
                Description = "Special edition for ITCamp 2018 speakers. Cheers, Romania!",
                Category = winesCategory
            });

            dbContext.Products.Add(new Product
            {
                Name = "Kagor Osobхi",
                Description = "Uuh.....",
                Category = winesCategory
            });

            dbContext.Products.Add(new Product
            {
                Name = "La Trappe Bockbier (7%)",
                Description = "La Trappe Bock beer is an all-malt, multigrain Bock beer that undergoes secondary fermentation. La Trappe Bock beer is the only Trappist Bock beer in the world. It is brewed with nothing but natural ingredients and goes through a light secondary fermentation in the bottle.",
                Category = beersCategory
            });

            dbContext.Products.Add(new Product
            {
                Name = "La Trappe Quadrupel (10%)",
                Description = "In 1991, The Koningshoeven brewery baptized her beloved Quadrupel under the approving glance of the monks. A closely guarded recipe became reality, and the first Quadrupel beer in the world was born.",
                Category = beersCategory
            });

            dbContext.SaveChanges();
        }
    }
}


//----------------------------------------------------------------------------
//  Rise of the Triad Structs
//----------------------------------------------------------------------------
//
//  Copyright (c) 2016 Isotope SoftWorks
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  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 General Public License for more details.
//
//
//
//
//----------------------------------------------------------------------------

#ifndef __ROTT_RAWDEF_H__
#define __ROTT_RAWDEF_H__

#include "../src/w_wad.cc" ///<--- For WAD handling

//!!!!!! FIXME:
#define GAT_PACK  __attribute__ ((packed))

typedef struct {
    int number;
    char mapname[23];
} mapinfo_t;

typedef struct {
    int nummaps;
    mapinfo_t maps[100];
} mapfileinfo_t;

/*---------------------------------------------------------------------
   Map constants
---------------------------------------------------------------------*/

#define MAXLEVELNAMELENGTH           23
#define ALLOCATEDLEVELNAMELENGTH     24
#define NUMPLANES                    3
#define NUMHEADEROFFSETS             100
#define MAPWIDTH                     128
#define MAPHEIGHT                    128
#define MAP_SPECIAL_TOGGLE_PUSHWALLS 0x0001

#define WALL_PLANE    0
#define SPRITE_PLANE  1
#define INFO_PLANE    2

/*---------------------------------------------------------------------
   Type definitions
---------------------------------------------------------------------*/

typedef struct
{
   unsigned long used;
   unsigned long CRC;
   unsigned long RLEWtag;
   unsigned long MapSpecials;
   unsigned long planestart[ NUMPLANES ];
   unsigned long planelength[ NUMPLANES ];
   char          Name[ ALLOCATEDLEVELNAMELENGTH ];
} RTLMAP;

/*---------------------------------------------------------------------
   Global variables
---------------------------------------------------------------------*/

unsigned short *mapplanes[ NUMPLANES ];

/*---------------------------------------------------------------------
   Macros
---------------------------------------------------------------------*/

#define MAPSPOT( x, y, plane ) \
   ( mapplanes[ plane ][ MAPWIDTH * ( y ) + ( x ) ] )

#define WALL_AT( x, y )   ( MAPSPOT( ( x ), ( y ), WALL_PLANE ) )
#define SPRITE_AT( x, y ) ( MAPSPOT( ( x ), ( y ), SPRITE_PLANE ) )
#define INFO_AT( x, y )   ( MAPSPOT( ( x ), ( y ), INFO_PLANE ) )

int GetWallIndex (int texture);

#endif // __ROTT_RAWDEF_H__


.') {
            valStr.truncate(valStr.length()-1);
        }

    }

    return valStr;
}

/**
 * Performs some testing for the math class.
 */
void RS_Math::test() {
    {
        std::cout<<"testing quadratic solver"<<std::endl;
        //equations x^2 + v[0] x + v[1] = 0
        std::vector<std::vector<double>> const eqns{
            {-1., -1.},
            {-101., -1.},
            {-1., -100.},
            {2., 1.},
            {-2., 1.}
        };
        //expected roots
        std::vector<std::vector<double>> roots{
            {-0.6180339887498948, 1.6180339887498948},
            {-0.0099000196991084878, 101.009900019699108},
            {-9.5124921972503929, 10.5124921972503929},
            {-1.},
            {1.}
        };

        for(size_t i=0; i < eqns.size(); i++) {
            std::cout<<"Test quadratic solver, test case: x^2 + ("
                    <<eqns[i].front()<<") x + ("
                   <<eqns[i].back()<<") = 0"<<std::endl;
            auto sol = quadraticSolver(eqns[i]);
            assert(sol.size()==roots[i].size());
            if (sol.front() > sol.back()) {
                std::swap(sol[0], sol[1]);
            }
            auto expected=roots[i];
            if (expected.front() > expected.back()) {
                std::swap(expected[0], expected[1]);
            }
            for (size_t j=0; j < sol.size(); j++) {
                double x0 = sol[j];
                double x1 = expected[j];
                double const prec = (x0 - x1)/(std::abs(x0 + x1) + RS_TOLERANCE2);
                std::cout<<"root "<<j<<" : precision level = "<<prec<<std::endl;
                std::cout<<std::setprecision(17)<<"found: "<<x0<<"\texpected: "<<x1<<std::endl;
                assert(prec < RS_TOLERANCE);
            }
            std::cout<<std::endl;
        }
        return;
    }
    QString s;
    double v;

    std::cout << "RS_Math::test: doubleToString:\n";

    v = 0.1;
    s = RS_Math::doubleToString(v, 0.1);
    assert(s=="0.1");
    s = RS_Math::doubleToString(v, 0.01);
    assert(s=="0.10");

    v = 0.01;
    s = RS_Math::doubleToString(v, 0.1);
    assert(s=="0.0");
    s = RS_Math::doubleToString(v, 0.01);
    assert(s=="0.01");
    s = RS_Math::doubleToString(v, 0.001);
    assert(s=="0.010");

    v = 0.001;
    s = RS_Math::doubleToString(v, 0.1);
    assert(s=="0.0");
    s = RS_Math::doubleToString(v, 0.01);
    assert(s=="0.00");
    s = RS_Math::doubleToString(v, 0.001);
    assert(s=="0.001");

    std::cout << "RS_Math::test: complete"<<std::endl;
}

//Equation solvers

// quadratic, cubic, and quartic equation solver
// @ ce[] contains coefficient of the cubic equation:
// @ returns a vector contains real roots
//
// solvers assume arguments are valid, and there's no attempt to verify validity of the argument pointers
//
// @author Dongxu Li <dongxuli2011@gmail.com>
std::vector<double> RS_Math::quadraticSolver(const std::vector<double>& ce)
//quadratic solver for
// x^2 + ce[0] x + ce


Pass a C-string (zero terminated char array)
// A CR (carriage return) will be added at the end
// to cause the printer to print the text and advance
// the paper one line
//
int tpPrintLine(char *pString);

#define MODE_WITH_RESPONSE 1
#define MODE_WITHOUT_RESPONSE 0
//
// Set the BLE write mode
// MODE_WITH_RESPONSE asks the receiver to ack each packet
// it will be slower, but might be necessary to successfully transmit
// every packet. The default is to wait for a response for each write
//
void tpSetWriteMode(uint8_t bWriteMode);
//
// Draw text into the graphics buffer
//
int tpDrawText(int x, int y, char *pString, int iFontSize, int bInvert);
//
// Load a 1-bpp Windows bitmap into the back buffer
// Pass the pointer to the beginning of the BMP file
// along with a x and y offset (upper left corner)
//
int tpLoadBMP(uint8_t *pBMP, int bInvert, int iXOffset, int iYOffset);

//
// Fill the frame buffer with a byte pattern
// e.g. all off (0x00) or all on (0xff)
//
void tpFill(unsigned char ucData);
//
// Set (or clear) an individual pixel
//
int tpSetPixel(int x, int y, uint8_t ucColor);
//
// Send the graphics to the printer (must be connected over BLE first)
//
void tpPrintBuffer(void);
//
// Same as tpPrintBuffer, but output will be rotated by 90 degrees
//
void tpPrintBufferSide(void);
//
// Draw a line between 2 points
//
void tpDrawLine(int x1, int y1, int x2, int y2, uint8_t ucColor);
//
// Scan for compatible printers
// returns true if found
// and stores the printer address internally
// for use with the tpConnect() function
// szName is the printer device name to match
// iSeconds = how many seconds to scan for devices
//
int tpScan(const char *szName, int iSeconds);
//
// connect to a printer with a macaddress
// returns 1 if successful, 0 for failure
//
int tpConnect(const char *szMacAddress);
//
// Set the text and barcode alignment
// Use ALIGN_LEFT, ALIGN_CENTER or ALIGN_RIGHT
//
void tpAlign(uint8_t ucAlign);
//
// Print a 2D (QR) barcode
//
void tpQRCode(char *szText);
//
// Print a 2D (QR) barcode
// iSize = starting from 1 / standard is 3
//
void tpQRCode(char *szText, int iSize);
//
// Print a 1D barcode
//
void tp1DBarcode(int iType, int iHeight, char *szData, int iTextPos);
//
// Parameterless version
// finds supported printers automatically
//
int tpScan(void);
//
// After a successful scan, connect to the printer
// returns 1 if successful, 0 for failure
//
int tpConnect(void);
void tpDisconnect(void);
int tpIsConnected(void);
#endif // __THERMAL_PRINTER_H__


1
    vsubl.u8    \q3, d6,  d7
.endm

function pixel_satd_4x4_neon
    vld1.32     {d1[]},  [r2], r3
    vld1.32     {d0[]},  [r0,:32], r1
    vld1.32     {d3[]},  [r2], r3
    vld1.32     {d2[]},  [r0,:32], r1
    vld1.32     {d1[1]}, [r2], r3
    vld1.32     {d0[1]}, [r0,:32], r1
    vld1.32     {d3[1]}, [r2], r3
    vld1.32     {d2[1]}, [r0,:32], r1
    vsubl.u8    q0,  d0,  d1
    vsubl.u8    q1,  d2,  d3

    SUMSUB_AB   q2, q3, q0, q1
    SUMSUB_ABCD d0, d2, d1, d3, d4, d5, d6, d7
    HADAMARD    1, sumsub, q2, q3, q0, q1
    HADAMARD    2, amax,   q0,,    q2, q3

    HORIZ_ADD   d0,  d0,  d1
    vmov.32     r0,  d0[0]
    bx          lr
endfunc

function pixel_satd_4x8_neon
    vld1.32     {d1[]},  [r2], r3
    vld1.32     {d0[]},  [r0,:32], r1
    vld1.32     {d3[]},  [r2], r3
    vld1.32     {d2[]},  [r0,:32], r1
    vld1.32     {d5[]},  [r2], r3
    vld1.32     {d4[]},  [r0,:32], r1
    vld1.32     {d7[]},  [r2], r3
    vld1.32     {d6[]},  [r0,:32], r1

    vld1.32     {d1[1]}, [r2], r3
    vld1.32     {d0[1]}, [r0,:32], r1
    vsubl.u8    q0,  d0,  d1
    vld1.32     {d3[1]}, [r2], r3
    vld1.32     {d2[1]}, [r0,:32], r1
    vsubl.u8    q1,  d2,  d3
    vld1.32     {d5[1]}, [r2], r3
    vld1.32     {d4[1]}, [r0,:32], r1
    vsubl.u8    q2,  d4,  d5
    vld1.32     {d7[1]}, [r2], r3
    SUMSUB_AB   q8,  q9,  q0,  q1
    vld1.32     {d6[1]}, [r0,:32], r1
    vsubl.u8    q3,  d6,  d7
    SUMSUB_AB   q10, q11, q2,  q3
    b           satd_4x8_8x4_end_neon
endfunc

function pixel_satd_8x4_neon
    vld1.64     {d1}, [r2], r3
    vld1.64     {d0}, [r0,:64], r1
    vsubl.u8    q0,  d0,  d1
    vld1.64     {d3}, [r2], r3
    vld1.64     {d2}, [r0,:64], r1
    vsubl.u8    q1,  d2,  d3
    vld1.64     {d5}, [r2], r3


c+11], v[v_a+2], v[v_b+6], a[a_c+8:a_c+11]     ; repeat:0x1, step:0x0, num_a_c:4
    v_add_u32 v[v_move_slice_k_idsx], s[s_move_slice_k_dsx], v[v_move_slice_k_idsx]
    v_mfma_f32_4x4x1f32 a[a_c+12:a_c+15], v[v_a+2], v[v_b+7], a[a_c+12:a_c+15]     ; repeat:0x1, step:0x1, num_a_c:4
    v_cmpx_le_u32 vcc, s[s_gemm_k_num_dsx], v[v_move_slice_k_idsx]
    v_subrev_u32 v[v_move_slice_k_idsx], s[s_gemm_k_num_dsx], v[v_move_slice_k_idsx]
    v_add_u32 v[v_move_slice_k_idsy], 1, v[v_move_slice_k_idsy]
    s_mov_b64 exec, -1
    ds_read_b32 v[v_a+2], v[v_sld_a_os] offset:3072 ; load i_k:3 into local buffer 1, repeat 0
    s_waitcnt lgkmcnt(5)
    v_mfma_f32_4x4x1f32 a[a_c+16:a_c+19], v[v_a+3], v[v_b+4], a[a_c+16:a_c+19]     ; repeat:1x0, step:0x0, num_a_c:4
    v_add_u32 v[v_move_slice_k_idsy], s[s_move_slice_k_dsy], v[v_move_slice_k_idsy]
    v_mfma_f32_4x4x1f32 a[a_c+20:a_c+23], v[v_a+3], v[v_b+5], a[a_c+20:a_c+23]     ; repeat:1x0, step:0x1, num_a_c:4
    v_cmpx_le_u32 vcc, s[s_gemm_k_num_dsy], v[v_move_slice_k_idsy]
    v_subrev_u32 v[v_move_slice_k_idsy], s[s_gemm_k_num_dsy], v[v_move_slice_k_idsy]
    v_add_u32 v[v_move_slice_k_ik1], 1, v[v_move_slice_k_ik1]
    v_add_u32 v[v_out_os_base], s[s_out_stride_k], v[v_out_os_base]
    v_add_u32 v[v_wei_os_base], s[s_wei_stride_k], v[v_wei_os_base]
    s_mov_b64 exec, -1
    ds_read2_b32 v[v_b+4+0:v_b+4+1], v[v_sld_b_os], offset0:96, offset1:100 ; load i_k:3 into local buffer 1, repeat 0
    v_mfma_f32_4x4x1f32 a[a_c+24:a_c+27], v[v_a+3], v[v_b+6], a[a_c+24:a_c+27]     ; repeat:1x1, step:0x0, num_a_c:4
    v_add_u32 v[v_move_slice_k_ik1], s[s_move_slice_k_k1], v[v_move_slice_k_ik


ate;
      imms[imm_count++] = shuffle_mask;
    } else {
      // Swap inputs from the normal order for (v)palignr.
      SwapShuffleInputs(node);
      is_swizzle = false;  // It's simpler to just handle the general case.
      no_same_as_first = use_avx;  // SSE requires same-as-first.
      opcode = kIA32S8x16Alignr;
      // palignr takes a single imm8 offset.
      imms[imm_count++] = offset;
    }
  } else if (TryMatchArchShuffle(shuffle, arch_shuffles,
                                 arraysize(arch_shuffles), is_swizzle,
                                 &arch_shuffle)) {
    opcode = use_avx ? arch_shuffle->avx_opcode : arch_shuffle->opcode;
    src0_needs_reg = !use_avx || arch_shuffle->src0_needs_reg;
    // SSE can't take advantage of both operands in registers and needs
    // same-as-first.
    src1_needs_reg = use_avx && arch_shuffle->src1_needs_reg;
    no_same_as_first = use_avx;
  } else if (wasm::SimdShuffle::TryMatch32x4Shuffle(shuffle, shuffle32x4)) {
    uint8_t shuffle_mask = wasm::SimdShuffle::PackShuffle4(shuffle32x4);
    if (is_swizzle) {
      if (wasm::SimdShuffle::TryMatchIdentity(shuffle)) {
        // Bypass normal shuffle code generation in this case.
        EmitIdentity(node);
        return;
      } else {
        // pshufd takes a single imm8 shuffle mask.
        opcode = kIA32S32x4Swizzle;
        no_same_as_first = true;
        // TODO(v8:9198): This doesn't strictly require a register, forcing the
        // swizzles to always use registers until generation of incorrect memory
        // operands can be fixed.
        src0_needs_reg = true;
        imms[imm_count++] = shuffle_mask;
      }
    } else {
      // 2 operand shuffle
      // A blend is more efficient than a general 32x4 shuffle; try it first.
      if (wasm::SimdShuffle::TryMatchBlend(shuffle)) {
        opcode = kIA32S16x8Blend;
        uint8_t blend_mask = wasm::SimdShuffle::PackBlend4(shuffle32x4);
        imms[imm_count++] = blend_mask;
      } else {
        opcode = kIA32S32x4Shuffle;
        no_same_as_first = true;
        // TODO(v8:9198): src0 and src1 is used by pshufd in codegen, which
        // requires memory to be 16-byte aligned, since we cannot guarantee that
        // yet, force using a register here.
        src0_needs_reg = true;
        src1_needs_reg = true;
        imms[imm_count++] = shuffle_mask;
        int8_t blend_mask = wasm::SimdShuffle::PackBlend4(shuffle32x4);
        imms[imm_count++] = blend_mask;
      }
    }
  } else if (wasm::SimdShuffle::TryMatch16x8Shuffle(shuffle, shuffle16x8)) {
    uint8_t blend_mask;
    if (wasm::SimdShuffle::TryMatchBlend(shuffle)) {
      opcode = kIA32S16x8Blend;
      blend_mask = wasm::SimdShuffle::PackBlend8(shuffle16x8);
      imms[imm_count++] = bl


px; height: 14px;}.dj_ie6 .claro .dijitTooltipConnector {background-image: url("images/tooltip8bit.png");}.claro .dijitTooltipABRight .dijitTooltipConnector {left: auto !important; right: 3px;}.claro .dijitTooltipBelow .dijitTooltipConnector {top: 0; left: 3px; background-position: -31px 0; width: 16px; height: 14px;}.claro .dijitTooltipAbove .dijitTooltipConnector {bottom: 0; left: 3px; background-position: -15px 0; width: 16px; height: 14px;}.dj_ie7 .claro .dijitTooltipAbove .dijitTooltipConnector, .dj_ie6 .claro .dijitTooltipAbove .dijitTooltipConnector {bottom: -1px;}.claro .dijitTooltipLeft {padding-right: 14px;}.claro .dijitTooltipLeft .dijitTooltipConnector {right: 0; background-position: 0 0; width: 16px; height: 14px;}.claro .dijitTooltipRight {padding-left: 14px;}.claro .dijitTooltipRight .dijitTooltipConnector {left: 0; background-position: -48px 0; width: 16px; height: 14px;}.claro .dijitDialogUnderlay {background: #ffffff;}.claro .dijitAccordionContainer {border: none;}.claro .dijitAccordionInnerContainer {background-color: #efefef; border: solid 1px #b5bcc7; margin-bottom: 1px; -webkit-transition-property: background-color, border; -moz-transition-property: background-color, border; transition-property: background-color, border; -webkit-transition-duration: 0.3s; -moz-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-timing-function: linear; -moz-transition-timing-function: linear; transition-timing-function: linear;}.claro .dijitAccordionTitle {background-color: transparent; background-image: url("images/standardGradient.png"); background-repeat: repeat-x; background-image: -moz-linear-gradient(rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 100%); background-image: -webkit-linear-gradient(rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 100%); background-image: -o-linear-gradient(rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 100%); background-image: -ms-linear-gradient(rgba(255, 255, 255, 0.7) 0%, rgba(255, 255, 255, 0) 100%); _background-image: none; padding: 5px 7px 2px 7px; min-height: 17px; color: #494949;}.claro .dijitAccordionContainer .dijitAccordionChildWrapper {background-color: #ffffff; border: 1px solid #759dc0; margin: 0 2px 2px;}.claro .dijitAccordionContainer .dijitAccordionContainer-child {padding: 9px;}.claro .dijitAccordionInnerContainerActive {border: 1px solid #759dc0; background-color: #7dbdfa; -webkit-transition-duration: 0.1s; -moz-transition-duration: 0.1s; transition-duration: 0.1s;}.claro .dijitAccordionInnerContainerActive .dijitAccordionTitle {background-image: url("images/activeGradient.png"); background-repeat: repeat-x; background-image: -moz-linear-gradient(rgba(190, 190, 190, 0.98) 0px, rgba(255, 255, 255, 0.65) 3px, rgba(255, 255, 255, 0) 100%); background-image: -webkit-linear-gradient(rgba(1


      expect(dm.data[0]).toEqual([1, 'C']);
      expect(dm.data[1]).toEqual([2, 'B']);
      expect(dm.data[2]).toEqual([3, 'A']);
    });

    it('should execute sorting in descending order', () => {
      const dm = new LoadedTournament();
      dm.columns = [buildColumn('pos', 0), buildColumn('name', 1)];
      dm.data = [
        [1, 'C'],
        [2, 'B'],
        [3, 'A']
      ];
      dm.sort(buildColumn('pos', 0), 'desc');
      expect(dm.data[0]).toEqual([3, 'A']);
      expect(dm.data[1]).toEqual([2, 'B']);
      expect(dm.data[2]).toEqual([1, 'C']);
    });

    it('should execute sorting in ascending order', () => {
      const dm = new LoadedTournament();
      dm.columns = [buildColumn('pos', 0), buildColumn('name', 1)];
      dm.data = [
        [1, 'C'],
        [2, 'B'],
        [3, 'A']
      ];
      dm.sort(buildColumn('name', 1), 'asc');
      expect(dm.data[0]).toEqual([3, 'A']);
      expect(dm.data[1]).toEqual([2, 'B']);
      expect(dm.data[2]).toEqual([1, 'C']);
    });
  });

  describe('getOpponentsFor', () => {
    const csv = new LoadedTournament();
    csv.columns = testColumns.concat([
      buildColumn('r4', 5),
      buildColumn('r5', 6),
      buildColumn('pts', 7)
    ]);
    csv.data = [
      [1, 'A', '+7B', '+5W', '=2B', '+4W', '=3B', 4],
      [2, 'B', '-3B', '+8W', '=1W', '+5B', '+4W', 3.5],
      [3, 'C', '+2W', '-4B', '=6W', '+7B', '=1W', 3],
      [4, 'D', '+6B', '+3W', '+8W', '-1B', '-2B', 3],
      [5, 'E', '+8B', '-1B', '=7W', '-2W', '+6B', 2.5],
      [6, 'F', '-4W', '+7B', '=3B', '=8W', '-5W', 2],
      [7, 'G', '-1W', '-6W', '=5B', '-3W', '+8B', 1.5],
      [8, 'H', '-5W', '-2B', '-4B', '=6B', '-7W', 0.5]
    ];

    it('should return an empty set if position is undefined', () => {
      expect(csv.getOpponentsFor(undefined)).toEqual(new Set());
    });

    it('should return an empty set if position is negative', () => {
      expect(csv.getOpponentsFor(-1)).toEqual(new Set());
    });

    it('should return an expected set for a valid position', () => {
      expect(csv.getOpponentsFor(0)).toEqual(new Set([7, 5, 2, 4, 3]));
      expect(csv.getOpponentsFor(1)).toEqual(new Set([3, 8, 1, 5, 4]));
      expect(csv.getOpponentsFor(2)).toEqual(new Set([2, 4, 6, 7, 1]));
      expect(csv.getOpponentsFor(3)).toEqual(new Set([6, 3, 8, 1, 2]));
      expect(csv.getOpponentsFor(4)).toEqual(new Set([8, 1, 7, 2, 6]));
    });
  });

  describe('getPositionFor', () => {
    const csv = new LoadedTournament();
    csv.columns = testColumns.concat([


0
1
1

如果指定 A = 60; 及 B = 13; 两个变量对应的二进制为：

A = 0011 1100

B = 0000 1101

进行位运算：

运算符
描述
图解
实例

&
按位与。按位与运算符对两个数进行操作，然后返回一个新的数，这个数的每个位都需要两个输入数的同一位都为1时才为1。

(A & B) 结果为 12, 二进制为 0000 1100

|
按位或。按位或运算符|比较两个数，然后返回一个新的数，这个数的每一位设置1的条件是两个输入数的同一位都不为0(即任意一个为1，或都为1)。

(A | B) 结果为 61, 二进制为 0011 1101

^
按位异或. 按位异或运算符^比较两个数，然后返回一个数，这个数的每个位设为1的条件是两个输入数的同一位不同，如果相同就设为0。

(A ^ B) 结果为 49, 二进制为 0011 0001

~
按位取反运算符~对一个操作数的每一位都取反。

(~A ) 结果为 -61, 二进制为 1100 0011 in 2's complement form.

<<
按位左移。左移操作符（<<）将操作数的所有位向左移动指定的位数。

下图展示了11111111 << 1（11111111 左移一位）的结果。蓝色数字表示被移动位，灰色表示被丢弃位，空位用橙色的0填充。

<img src=


ado para este nivel!",
    "fr_FR": "Cette commande git est désactivée pour ce niveau !",
    "ro": "Această comandă git este dezactivată pentru acest nivel!",
    "ru_RU": "На этом уровне нельзя использовать эту команду!",
    "uk": "На цьому рівні не можна використовувати цю команду!",
    "ko": "그 Git 명령어는 이 레벨에서 사용할 수 없습니다.",
    "vi": "Ở cấp độ này thì lệnh git đó bị vô hiệu hóa!",
    "sl_SI": "Ta git ukaz je onemogočen za to stopnjo!",
    "pl": "To polecenie Gita jest wyłączone na tym poziomie!",
    "it_IT": "Questo comando git è disabilitato per questo livello!",
    "ta_IN": "இந்த நிலையில் அந்த கிட் கட்டளை முடக்கப்பட்டுள்ளது",
    "tr_TR": "Bu seviyede o git komutu devre dışı bırakılmıştır!"
  },
  "share-json": {
    "__desc__": "when you have made the level, prompt to share this",
    "en_US": "Here is the JSON for this level! Share it with someone or send it to me on GitHub",
    "de_DE": "Hier ist das JSON für dieses Level! Teil es mit jemandem or schick es mir über GitHub",
    "zh_CN": "这是一个关卡定义 JSON ！您可以分享它或者发到我的 GitHub 上",
    "zh_TW": "這是本關的 JSON！您可以分享給別人，或是送到 GitHub 上給我",
    "es_AR": "Este es el JSON de este nivel. Compartilo con quien quieras o mandámelo por GitHub",
    "es_MX": "Este es el JSON de éste nivel. Compártelo con quien quieras o mándamelo por GitHub.",
    "es_ES": "Este es el JSON de este nivel. Compártelo con quien quieras o mandámelo por GitHub.",
    "pt_BR": "Aqui está o JSON para este nível! Compartilhe com alguém ou me envie pelo GitHub",
    "gl": "Este é o JSON deste nivel. Comparteo con quen queiras ou mándao por GitHub",
    "fr_FR": "Voici le JSON pour ce niveau ! Partagez-le avec quelqu'un ou envoyez-le moi sur GitHub",
    "ro": "Iată JSON-ul pentru acest nivel! Împărtășește-l cu cineva sau trimite-mi-l pe GitHub",
    "ru_RU": "Вот JSON для этого уровня! Поделись им с кем-нибудь или отправь его нам на GitHub",
    "uk": "Ось JSON для цього рівня! Поділись з кимось чи відправ мені його на GitHub",
    "ko": "이 레벨을 위한 JSON 데이터가 있습니다! 이를 다른 사람들과 공유하거나 GitHub


KLY',
    'DAILY',
    'HOURLY',
    'MINUTELY',
    'SECONDLY'
  ]

  static readonly YEARLY = Frequency.YEARLY
  static readonly MONTHLY = Frequency.MONTHLY
  static readonly WEEKLY = Frequency.WEEKLY
  static readonly DAILY = Frequency.DAILY
  static readonly HOURLY = Frequency.HOURLY
  static readonly MINUTELY = Frequency.MINUTELY
  static readonly SECONDLY = Frequency.SECONDLY

  static readonly MO = Days.MO
  static readonly TU = Days.TU
  static readonly WE = Days.WE
  static readonly TH = Days.TH
  static readonly FR = Days.FR
  static readonly SA = Days.SA
  static readonly SU = Days.SU

  constructor (options: Partial<Options> = {}, calcSunParams: CalcSunParams | null = null) {

    // used by toString()
    this.origOptions = initializeOptions(options)
    const { parsedOptions } = parseOptions(options)
    this.options = parsedOptions
    this.calcSunParams = calcSunParams
  }

  protected _iter <M extends QueryMethodTypes> (iterResult: IterResult<M>): IterResultType<M> {
    return iter(iterResult, this.options, this.calcSunParams)
  }

  /**
   * @param {Function} iterator - optional function that will be called
   *                   on each date that is added. It can return false
   *                   to stop the iteration.
   * @return Array containing all recurrences.
   */
  all (iterator?: (d: Date, len: number) => boolean): Date[] {
    if (iterator) {
      return this._iter(new CallbackIterResult('all', {}, iterator))
    }

    return this._iter(new IterResult('all', {}))
  }

  /**
   * Returns all the occurrences of the rrule between after and before.
   * The inc keyword defines what happens if after and/or before are
   * themselves occurrences. With inc == True, they will be included in the
   * list, if they are found in the recurrence set.
   * @return Array
   */
  between (
    after: Date,
    before: Date,
    inc: boolean = false,
    iterator?: (d: Date, len: number) => boolean
  ): Date[] {
    if (!dateutil.isValidDate(after) || !dateutil.isValidDate(before)) throw new Error('Invalid date passed in to RRule.between')
    const args = {
      before,
      after,
      inc
    }

    if (iterator) {
      return this._iter(
        new CallbackIterResult('between', args, iterator)
      )
    }

    return this._iter(new IterResult('between', args))
  }

  /**
   * Returns the last recurrence before the given datetime instance.
   * The inc keyword defines what happens if dt is an occurrence.
   * With inc == True, if dt itself is an occurrence, it will be returned.
   * @return Date or null
   */
  before (dt: Date, inc = false): Date {
    if (!dateutil.isValidDate(dt)) throw new Error('Invalid date passed in to RRule.before')
    const args = { dt: dt, inc: inc }
    return this._iter(new IterResult('before', args)) as Date
  }

  /**
   * Returns the first recurrence after the given datetime instance.
   * The inc keyword defines what happens if dt is an occurrence.
   * With inc == True, if dt itself is an occurrence, it will be returned.
   * @return Date or null
   */
  after (dt: Date, inc = false): Date {
    if (!dateutil.isValid


Detail(imdbId: String): Flowable<MovieDetail> {
        return localDataStore.getMovieDetail(imdbId)
            .flatMapPublisher { localMovieDetail ->
                Flowable.just(localMovieDetail)
                    .mergeWith(
                        remoteDataStore.getMovieDetail(imdbId)
                            .flatMap { remoteMovieDetail ->
                                localDataStore.addMovieDetail(remoteMovieDetail)
                                    .andThen(Single.just(remoteMovieDetail))
                            }
                            .onErrorComplete()
                    )
            }
            .onErrorResumeNext {
                remoteDataStore.getMovieDetail(imdbId)
                    .flatMap { remoteMovieDetail ->
                        localDataStore.addMovieDetail(remoteMovieDetail)
                            .andThen(Single.just(remoteMovieDetail))
                    }
                    .toFlowable()
            }
    }

    override fun saveSearchResult(list: List<String>): Completable {
        return localDataStore.saveSearchHistory(list = list)
    }

    override fun getSearchHistory(): Single<List<String>> {
        return localDataStore.getSearchHistory()
    }
}plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.example.weatherapp"
    compileSdk = 33

    defaultConfig {
        applicationId = "com.example.weatherapp"
        minSdk = 30
        targetSdk = 33
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }

    buildFeatures {
        viewBinding = true
    }
}

dependencies {

    implementation("androidx.core:core-ktx:1.10.1")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.9.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
    androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")

    // retrofit
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")

    // coroutine
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")

    //picasso
    implementation("com.squareup.picasso:picasso:2.8")

    //barchart
    implementation("com.github.PhilJay:MPAndroidChart:v3.1.0")

    //location
    implementation("com.google.android.gms:play-services-location:21.0.1")
}import com.vanniktech.maven.publish.SonatypeHost
import org.jetbrains.compose.ExperimentalComposeLibrary

plugins {
    kotlin("multiplatform")
    id("com.android.library")
    id("org.jetbrains.compose")
    id("org.jetbrains.dokka")
    id("com.vanniktech.maven.publish")
}

kotlin {
    androidTarget {


а рамки базових кроків та інспекції змінних, такі як зворотне відлагодження (виконання програми у зворотному порядку), умовні точки зупинки та скрипти для автоматизації задач відлагодження.

Хоча GDB є потужним і широко використовуваним, для початківців він може бути складним і незрозумілим. Альтернативні інструменти для відлагодження та інтегровані середовища розробки (IDE), такі як Visual Studio Code, CLion або Eclipse, пропонують більш користувацькі інтерфейси для відлагодження коду на C, часто інтегруючи візуальні допоміжні засоби та більш інтуїтивні керування. Ці альтернативи можуть не пропонувати повної глибини функціональності GDB, але можуть бути більш доступними для новачків у програмуванні на мові C.

Більше того, поява протоколів мовних серверів та стандартів відлагодження сприяла кросплатформним рішенням для відлагодження, роблячи досвід відлагодження більш уніфікованим у різних інструментах та середовищах. Незважаючи на ці досягнення, вивчення основ традиційного відлагоджувача на кшталт GDB забезпечує безцінний увляд у виконання програм на мові C та залишається важливою навичкою в арсеналі розробника.
---
changelog:
- 2024-02-03, gpt-4-0125-preview, translated from English
date: 2024-02-03 18:12:50.619452-07:00
description: "\u042F\u043A: \u0429\u043E\u0431 \u043F\u0440\u0430\u0446\u044E\u0432\
  \u0430\u0442\u0438 \u0437 TOML \u0443 C, \u0441\u043F\u043E\u0447\u0430\u0442\u043A\
  \u0443 \u0432\u0430\u043C \u043F\u043E\u0442\u0440\u0456\u0431\u043D\u0430 \u0431\
  \u0456\u0431\u043B\u0456\u043E\u0442\u0435\u043A\u0430, \u0437\u0434\u0430\u0442\
  \u043D\u0430 \u043F\u0430\u0440\u0441\u0438\u0442\u0438 \u0444\u0430\u0439\u043B\
  \u0438 TOML, \u043E\u0441\u043A\u0456\u043B\u044C\u043A\u0438 \u0441\u0442\u0430\
  \u043D\u0434\u0430\u0440\u044


Name(Color(0xFFC96323), "Piper"),
        ColorName(Color(0xFFC99415), "Pizza"),
        ColorName(Color(0xFFC9A0DC), "Light Wisteria"),
        ColorName(Color(0xFFC9B29B), "Rodeo Dust"),
        ColorName(Color(0xFFC9B35B), "Sundance"),
        ColorName(Color(0xFFC9B93B), "Earls Green"),
        ColorName(Color(0xFFC9C0BB), "Silver Rust"),
        ColorName(Color(0xFFC9D9D2), "Conch"),
        ColorName(Color(0xFFC9FFA2), "Reef"),
        ColorName(Color(0xFFC9FFE5), "Aero Blue"),
        ColorName(Color(0xFFCA3435), "Flush Mahogany"),
        ColorName(Color(0xFFCABB48), "Turmeric"),
        ColorName(Color(0xFFCADCD4), "Paris White"),
        ColorName(Color(0xFFCAE00D), "Bitter Lemon"),
        ColorName(Color(0xFFCAE6DA), "Skeptic"),
        ColorName(Color(0xFFCB8FA9), "Viola"),
        ColorName(Color(0xFFCBCAB6), "Foggy Gray"),
        ColorName(Color(0xFFCBD3B0), "Green Mist"),
        ColorName(Color(0xFFCBDBD6), "Nebula"),
        ColorName(Color(0xFFCC3333), "Persian Red"),
        ColorName(Color(0xFFCC5501), "Burnt Orange"),
        ColorName(Color(0xFFCC7722), "Ochre"),
        ColorName(Color(0xFFCC8899), "Puce"),
        ColorName(Color(0xFFCCCAA8), "Thistle Green"),
        ColorName(Color(0xFFCCCCFF), "Periwinkle"),
        ColorName(Color(0xFFCCFF00), "Electric Lime"),
        ColorName(Color(0xFFCD5700), "Tenn"),
        ColorName(Color(0xFFCD5C5C), "Chestnut Rose"),
        ColorName(Color(0xFFCD8429), "Brandy Punch"),
        ColorName(Color(0xFFCDF4FF), "Onahau"),
        ColorName(Color(0xFFCEB98F), "Sorrell Brown"),
        ColorName(Color(0xFFCEBABA), "Cold Turkey"),
        ColorName(Color(0xFFCEC291), "Yuma"),
        ColorName(Color(0xFFCEC7A7), "Chino"),
        ColorName(Color(0xFFCFA39D), "Eunry"),
        ColorName(Color(0xFFCFB53B), "Old Gold"),
        ColorName(Color(0xFFCFDCCF), "Tasman"),
        ColorName(Color(0xFFCFE5D2), "Surf Crest"),
        ColorName(Color(0xFFCFF9F3), "Humming Bird"),
        ColorName(Color(0xFFCFFAF4), "Scandal"),
        ColorName(Color(0xFFD05F04), "Red Stage"),
        ColorName(Color(0xFFD06DA1), "Hopbush"),
        ColorName(Color(0xFFD07D12), "Meteor"),
        ColorName(Color(0xFFD0BEF8), "Perfume"),
        ColorName(Color(0xFFD0C0E5), "Prelude"),
        ColorName(Color(0xFFD0F0C0), "Tea Green"),
        ColorName(Color(0xFFD18F1B), "Geebung"),
        ColorName(Color(0xFFD1BEA8), "Vanilla"),
        ColorName(Color(0xFFD1C6B4), "Soft Amber"),
        ColorName(Color(0xFFD1D2CA), "Celeste"),
        ColorName(Color(0xFFD1D2DD), "Mischka"),
        ColorName(Color(0xFFD1E231), "Pear"),
        ColorName(Color(0xFFD2691


 {
                customizedList.clear()
                customizedList.addAll(items.filter { it.fileSize > viewModel.getMinFileSize() })
            }
            if (filterType) {
                val temp = customizedList.filter { mediaRegex.find(it.filename) != null }
                customizedList.clear()
                customizedList.addAll(temp)
            }
            if (!filterQuery.isNullOrBlank()) {
                val temp = customizedList.filter { item -> item.filename.contains(filterQuery) }
                customizedList.clear()
                customizedList.addAll(temp)
            }
        }
        // if I get passed an empty list I need to empty the list (shouldn't be possible in this
        // particular fragment)
        when (sortTag) {
            TAG_DEFAULT_SORT -> {
                adapter.submitList(customizedList)
            }

            TAG_SORT_AZ -> {
                adapter.submitList(customizedList.sortedBy { item -> item.filename })
            }

            TAG_SORT_ZA -> {
                adapter.submitList(customizedList.sortedByDescending { item -> item.filename })
            }

            TAG_SORT_SIZE_DESC -> {
                adapter.submitList(customizedList.sortedByDescending { item -> item.fileSize })
            }

            TAG_SORT_SIZE_ASC -> {
                adapter.submitList(customizedList.sortedBy { item -> item.fileSize })
            }

            else -> {
                adapter.submitList(customizedList)
            }
        }
        adapter.notifyDataSetChanged()
    }

    override fun onClick(item: DownloadItem) {
        viewModel.setScrollingAllowed(false)
        val action =
            FolderListFragmentDirections.actionFolderListFragmentToDownloadDetailsDest(item)
        findNavController().navigate(action)
    }

    companion object {
        const val TAG_DEFAULT_SORT = "sort_default_tag"
        const val TAG_SORT_AZ = "sort_az_tag"
        const val TAG_SORT_ZA = "sort_za_tag"
        const val TAG_SORT_SIZE_ASC = "sort_size_asc_tag"
        const val TAG_SORT_SIZE_DESC = "sort_size_desc_tag"
        const val TAG_SORT_SEEDERS = "sort_seeders_tag"
        const val TAG_SORT_ADDED = "sort_added_tag"
    }
}
package com.autolua.autolua2.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.widget.FrameLayout
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import com.autolua.autolua2.R
import com.autolua.autolua2.databinding.ActivityProjectBinding
import com.autolua.autolua2.view.imp.FloatControllerImp
import com.autolua.engine.core.AutoLuaEngineProxy
import com.immomo.luanative.hotreload.HotReloadServer
import com.immomo.mls.MLSBundleUtils
import com.immomo.mls.MLSInstance

class ProjectActivity: AppCompatActivity(){
  private lateinit var binding: ActivityProjectBinding
  private lateinit var instance: MLSInstance;

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityProjectBinding.inflate(layoutInflater)
    setContentView(binding.root)
    val root = binding.root
    val frameLayout = root.findViewById<FrameLayout>(R.id.project_ui)
    val initData = MLSBundleUtils.parseFromBundle(intent.extras)!!.showLoadingView(true)

    instance = MLSInstance(this,false,false)


import numpy as np
import pandas as pd

def Wave_PM(data: pd.Series, period: int = 14, lookback_period: int = 10) -> pd.Series:
    """
    Calculates the Wave PM (Whistler Active Volatility Energy Price Mass) indicator.

    Parameters:
    data (pd.DataFrame): DataFrame containing the close prices.
    period (int): The period used to calculate the moving average and standard deviation. Default is 14.
    lookback_period (int): The number of periods to look back for calculating the power. Default is 100.

    Returns:
    pd.Series: Series containing the Wave PM indicator values.

    Example:
    # Assuming 'data' is a DataFrame containing the close prices
    wave_pm = Wave_PM(data, period=14, lookback_period=100)
    """

    ma = data.rolling(window=period).mean()
    std = data.rolling(window=period).std(ddof=0)

    dev = 3.2 * std
    power = (dev / ma) ** 2

    def tanh(x):
        return (np.exp(2 * x) - 1) / (np.exp(2 * x) + 1)

    variance = power.rolling(window=lookback_period).sum() / lookback_period
    calc_dev = np.sqrt(variance) * ma
    y = (dev / calc_dev)
    oscLine = tanh(y)

    return oscLine