text:
package master.flame.danmaku.ui.widget;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.TextureView;
import android.view.View;

import master.flame.danmaku.controller.DanmakuFilters;
import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.controller.DrawHandler.Callback;
import master.flame.danmaku.controller.DrawHelper;
import master.flame.danmaku.controller.IDanmakuView;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;

import java.util.LinkedList;
import java.util.Locale;

/**
 * DanmakuTextureView需要开启GPU加速才能显示弹幕
 * 很遗憾...经过测试TextureView没有提升绘制速度,也许哪里用的不对
 * @author ch
 *
 */
@SuppressLint("NewApi")
public class DanmakuTextureView extends TextureView implements IDanmakuView,
        TextureView.SurfaceTextureListener, View.OnClickListener {

    public static final String TAG = "DanmakuTextureView";

    private Callback mCallback;

    private HandlerThread mDrawThread;

    private DrawHandler handler;

    private boolean isSurfaceCreated;

    private boolean mEnableDanmakuDrwaingCache = true;

    private OnClickListener mOnClickListener;

    private boolean mShowFps;

    private boolean mDanmakuVisibile = true;

    protected int mDrawingThreadType = THREAD_TYPE_NORMAL_PRIORITY;

    public DanmakuTextureView(Context context) {
        super(context);
        init();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void init() {
        setOpaque(false);
        setWillNotCacheDrawing(true);
        setDrawingCacheEnabled(false);
        setWillNotDraw(true);
        setSurfaceTextureListener(this);
        setOnClickListener(this);
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        if (l != this) {
            mOnClickListener = l;
        } else
            super.setOnClickListener(l);
    }

    public DanmakuTextureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DanmakuTextureView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public void addDanmaku(BaseDanmaku item) {
        if (handler != null) {
            handler.addDanmaku(item);
        }
    }

    @Override
    public void removeAllDanmakus() {
        if (handler != null) {
            handler.removeAllDanmakus();
        }
    }

    @Override
    public void removeAllLiveDanmakus() {
        if (handler != null) {
            handler.removeAllLiveDanmakus();
        }
    }

    public void setCallback(Callback callback) {
        mCallback = callback;
        if (handler != null) {
            handler.setCallback(callback);
        }
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        isSurfaceCreated = true;
    }

    @Override
    public synchronized boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        isSurfaceCreated = false;
        return true;
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        if (handler != null) {
            handler.notifyDispSizeChanged(width, height);
        }
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public void release() {
        stop();
        DanmakuFilters.getDefault().clear();
    }

    @Override
    public void stop() {
        stopDraw();
    }

    private void stopDraw() {
        if (handler != null) {
            handler.quit();
            handler = null;
        }
        if (mDrawThread != null) {
            try {
                mDrawThread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mDrawThread.quit();
            mDrawThread = null;
        }
    }

    protected Looper getLooper(int type){
        if (mDrawThread != null) {
            mDrawThread.quit();
            mDrawThread = null;
        }

        int priority;
        switch (type) {
            case THREAD_TYPE_MAIN_THREAD:
                return Looper.getMainLooper();
            case THREAD_TYPE_HIGH_PRIORITY:
                priority = android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY;
                break;
            case THREAD_TYPE_LOW_PRIORITY:
                priority = android.os.Process.THREAD_PRIORITY_LOWEST;
                break;
            case THREAD_TYPE_NORMAL_PRIORITY:
            default:
                priority = android.os.Process.THREAD_PRIORITY_DEFAULT;
                break;
        }
        String threadName = "DFM Drawing thread #"+priority;
        mDrawThread = new HandlerThread(threadName, priority);
        mDrawThread.start();
        return mDrawThread.getLooper();
    }

    private void prepare() {
        if (handler == null)
            handler = new DrawHandler(getLooper(mDrawingThreadType), this, mDanmakuVisibile);
    }

    @Override
    public void prepare(BaseDanmakuParser parser) {
        prepare();
        handler.setParser(parser);
        handler.setCallback(mCallback);
        handler.prepare();
    }

    @Override
    public boolean isPrepared() {
        return handler != null && handler.isPrepared();
    }

    @Override
    public void showFPS(boolean show) {
        mShowFps = show;
    }
    private static final int MAX_RECORD_SIZE = 50;
    private static final int ONE_SECOND = 1000;
    private LinkedList<Long> mDrawTimes;
    private float fps() {
        long lastTime = System.currentTimeMillis();
        mDrawTimes.addLast(lastTime);
        float dtime = lastTime - mDrawTimes.getFirst();
        int frames = mDrawTimes.size();
        if (frames > MAX_RECORD_SIZE) {
            mDrawTimes.removeFirst();
        }
        return dtime > 0 ? mDrawTimes.size() * ONE_SECOND / dtime : 0.0f;
    }

    @Override
    public synchronized long drawDanmakus() {
        if (!isSurfaceCreated)
            return 0;
        long stime = System.currentTimeMillis();
        if (!isShown())
            return -1;
        long dtime = 0;
        Canvas canvas = lockCanvas();
        if (canvas != null) {
            if (handler != null) {
                handler.draw(canvas);
                if (mShowFps) {
                    if(mDrawTimes == null) mDrawTimes = new LinkedList<Long>();
                    dtime = System.currentTimeMillis() - stime;  //not so accurate
                    String fps = String.format(Locale.getDefault(), "%02d MS, fps %.2f", dtime,
                            fps());
                    DrawHelper.drawFPS(canvas, fps);
                }
            }
            if (isSurfaceCreated)
                unlockCanvasAndPost(canvas);
        }
        dtime = System.currentTimeMillis() - stime;
        return dtime;
    }

    public void toggle() {
        if (isSurfaceCreated) {
            if (handler == null)
                start();
            else if (handler.isStop()) {
                resume();
            } else
                pause();
        }
    }

    @Override
    public void pause() {
        if (handler != null)
            handler.pause();
    }

    @Override
    public void resume() {
        if (handler != null && mDrawThread != null && handler.isPrepared())
            handler.resume();
        else {
            restart();
        }
    }

    public void restart() {
        stop();
        start();
    }

    @Override
    public void start() {
        start(0);
    }

    @Override
    public void start(long postion) {
        if (handler == null) {
            prepare();
        } else {
            handler.removeCallbacksAndMessages(null);
        }
        handler.obtainMessage(DrawHandler.START, postion).sendToTarget();
    }

    @Override
    public void onClick(View view) {
        if (mOnClickListener != null) {
            mOnClickListener.onClick(view);
        }
    }

    public void seekTo(Long ms) {
        if (handler != null) {
            handler.seekTo(ms);
        }
    }

    public void enableDanmakuDrawingCache(boolean enable) {
        mEnableDanmakuDrwaingCache = enable;
    }

    @Override
    public boolean isDanmakuDrawingCacheEnabled() {
        return mEnableDanmakuDrwaingCache;
    }

    @Override
    public boolean isViewReady() {
        return isSurfaceCreated;
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void show() {
        showAndResumeDrawTask(null);
    }

    @Override
    public void showAndResumeDrawTask(Long position) {
        mDanmakuVisibile = true;
        if (handler == null) {
            return;
        }
        handler.showDanmakus(position);
    }

    @Override
    public void hide() {
        mDanmakuVisibile = false;
        if (handler == null) {
            return;
        }
        handler.hideDanmakus(false);
    }

    @Override
    public long hideAndPauseDrawTask() {
        mDanmakuVisibile = false;
        if (handler == null) {
            return 0;
        }
        return handler.hideDanmakus(true);
    }

    @Override
    public synchronized void clear() {
        if (!isViewReady()) {
            return;
        }
        Canvas canvas = lockCanvas();
        if (canvas != null) {
            DrawHelper.clearCanvas(canvas);
            unlockCanvasAndPost(canvas);
        }

    }

    @Override
    public boolean isShown() {
        if (handler == null || !isViewReady()) {
            return false;
        }
        return handler.getVisibility();
    }

    @Override
    public void setDrawingThreadType(int type) {
        mDrawingThreadType = type;
    }

    @Override
    public long getCurrentTime() {
        if (handler != null) {
            return handler.getCurrentTime();
        }
        return 0;
    }

}


text:
/*
 * This file is part of Zql.
 *
 * Zql 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 3 of the License, or
 * (at your option) any later version.
 *
 * Zql 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.
 *
 * You should have received a copy of the GNU General Public License
 * along with Zql.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gibello.zql.data;

import java.sql.SQLException;
import java.util.Vector;
import java.io.*;

import org.gibello.zql.*;

/**
 * Evaluate SQL expressions
 */
public class ZEval {

  /**
   * Evaluate a boolean expression to true or false (for example, SQL WHERE
   * clauses are boolean expressions)
   * @param tuple The tuple on which to evaluate the expression
   * @param exp The expression to evaluate
   * @return true if the expression evaluate to true for this tuple,
   * false if not.
   */
  public boolean eval(ZTuple tuple, ZExp exp) throws SQLException {

    if(tuple == null || exp == null)  {
      throw new SQLException("ZEval.eval(): null argument or operator");
    }
    if(! (exp instanceof ZExpression))
      throw new SQLException("ZEval.eval(): only expressions are supported");

    ZExpression pred = (ZExpression)exp;
    String op = pred.getOperator();

    if(op.equals("AND")) {
      boolean and = true;
      for(int i = 0; i<pred.nbOperands(); i++) {
        and &= eval(tuple, pred.getOperand(i));
      }
      return and;
    } else if(op.equals("OR")) {
      boolean or = false;
      for(int i = 0; i<pred.nbOperands(); i++) {
        or |= eval(tuple, pred.getOperand(i));
      }
      return or;
    } else if(op.equals("NOT")) {
      return ! eval(tuple, pred.getOperand(0));

    } else if(op.equals("=")) {
      return evalCmp(tuple, pred.getOperands()) == 0;
    } else if(op.equals("!=")) {
      return evalCmp(tuple, pred.getOperands()) != 0;
    } else if(op.equals("<>")) {
      return evalCmp(tuple, pred.getOperands()) != 0;
    } else if(op.equals("#")) {
      throw new SQLException("ZEval.eval(): Operator # not supported");
    } else if(op.equals(">")) {
      return evalCmp(tuple, pred.getOperands()) > 0;
    } else if(op.equals(">=")) {
      return evalCmp(tuple, pred.getOperands()) >= 0;
    } else if(op.equals("<")) {
      return evalCmp(tuple, pred.getOperands()) < 0;
    } else if(op.equals("<=")) {
      return evalCmp(tuple, pred.getOperands()) <= 0;

    } else if(op.equals("BETWEEN") || op.equals("NOT BETWEEN")) {

      // Between: borders included
      ZExpression newexp = new ZExpression("AND",
        new ZExpression(">=", pred.getOperand(0), pred.getOperand(1)),
        new ZExpression("<=", pred.getOperand(0), pred.getOperand(2)));

      if(op.equals("NOT BETWEEN"))
        return ! eval(tuple, newexp);
      else
        return eval(tuple, newexp);

    } else if(op.equals("LIKE") || op.equals("NOT LIKE")) {
      boolean like = evalLike(tuple, pred.getOperands());
      return op.equals("LIKE") ? like : !like;

    } else if(op.equals("IN") || op.equals("NOT IN")) {

      ZExpression newexp = new ZExpression("OR");

      for(int i = 1; i < pred.nbOperands(); i++) {
        newexp.addOperand(new ZExpression("=",
          pred.getOperand(0), pred.getOperand(i)));
      }

      if(op.equals("NOT IN"))
        return ! eval(tuple, newexp);
      else
        return eval(tuple, newexp);

    } else if(op.equals("IS NULL")) {

      if(pred.nbOperands() <= 0 || pred.getOperand(0) == null) return true;
      ZExp x = pred.getOperand(0);
      if(x instanceof ZConstant) {
        return (((ZConstant)x).getType() == ZConstant.NULL);
      } else {
        throw new SQLException("ZEval.eval(): can't eval IS (NOT) NULL");
      }

    } else if(op.equals("IS NOT NULL")) {

      ZExpression x = new ZExpression("IS NULL");
      x.setOperands(pred.getOperands());
      return ! eval(tuple, x);

    } else {
      throw new SQLException("ZEval.eval(): Unknown operator " + op);
    }

  }

  double evalCmp(ZTuple tuple, Vector operands) throws SQLException {

    if(operands.size() < 2) {
      throw new SQLException(
        "ZEval.evalCmp(): Trying to compare less than two values");
    }
    if(operands.size() > 2) {
      throw new SQLException(
        "ZEval.evalCmp(): Trying to compare more than two values");
    }

    Object o1 = null, o2 = null, obj;

    o1 = evalExpValue(tuple, (ZExp)operands.elementAt(0));
    o2 = evalExpValue(tuple, (ZExp)operands.elementAt(1));

    if(o1 instanceof String || o2 instanceof String) {
      return(o1.equals(o2) ? 0 : -1);
    }

    if(o1 instanceof Number && o2 instanceof Number) {
      return ((Number)o1).doubleValue() - ((Number)o2).doubleValue();
    } else {
      throw new SQLException("ZEval.evalCmp(): can't compare (" + o1.toString()
        + ") with (" + o2.toString() + ")");
    }
  }

  // -------------------------------------------------------------------------
  /**
   * evalLike
   * evaluates the LIKE operand
   *
   * @param tuple the tuple to evaluate
   * @param operands the operands
   * @return true-> the expression matches
   * @throws SQLException
   */
  private boolean evalLike(ZTuple tuple, Vector operands) throws SQLException
  {
    if(operands.size() < 2) {
      throw new SQLException(
        "ZEval.evalCmp(): Trying to compare less than two values");
    }
    if(operands.size() > 2) {
      throw new SQLException(
        "ZEval.evalCmp(): Trying to compare more than two values");
    }

    Object o1 = evalExpValue(tuple, (ZExp)operands.elementAt(0));
    Object o2 = evalExpValue(tuple, (ZExp)operands.elementAt(1));

    if ( (o1 instanceof String) && (o2 instanceof String) ) {
      String s1 = (String)o1;
      String s2 = (String)o2;
      if ( s2.startsWith("%") ) {
        return s1.endsWith(s2.substring(1));
      } else if ( s2.endsWith("%") ) {
        return s1.startsWith(s2.substring(0,s2.length()-1));
      } else {
        return s1.equalsIgnoreCase(s2);
      }
    }
    else {
      throw new SQLException("ZEval.evalLike(): LIKE can only compare strings");
    }

  }

  double evalNumericExp(ZTuple tuple, ZExpression exp)
  throws SQLException {

    if(tuple == null || exp == null || exp.getOperator() == null)  {
      throw new SQLException("ZEval.eval(): null argument or operator");
    }

    String op = exp.getOperator();

    Object o1 = evalExpValue(tuple, (ZExp)exp.getOperand(0));
    if(! (o1 instanceof Double))
      throw new SQLException("ZEval.evalNumericExp(): expression not numeric");
    Double dobj = (Double)o1;

    if(op.equals("+")) {

      double val = dobj.doubleValue();
      for(int i = 1; i < exp.nbOperands(); i++) {
        Object obj = evalExpValue(tuple, (ZExp)exp.getOperand(i));
        val += ((Number)obj).doubleValue();
      }
      return val;

    } else if(op.equals("-")) {

      double val = dobj.doubleValue();
      if(exp.nbOperands() == 1) return -val;
      for(int i = 1; i < exp.nbOperands(); i++) {
        Object obj = evalExpValue(tuple, (ZExp)exp.getOperand(i));
        val -= ((Number)obj).doubleValue();
      }
      return val;

    } else if(op.equals("*")) {

      double val = dobj.doubleValue();
      for(int i = 1; i < exp.nbOperands(); i++) {
        Object obj = evalExpValue(tuple, (ZExp)exp.getOperand(i));
        val *= ((Number)obj).doubleValue();
      }
      return val;

    } else if(op.equals("/")) {

      double val = dobj.doubleValue();
      for(int i = 1; i < exp.nbOperands(); i++) {
        Object obj = evalExpValue(tuple, (ZExp)exp.getOperand(i));
        val /= ((Number)obj).doubleValue();
      }
      return val;

    } else if(op.equals("**")) {

      double val = dobj.doubleValue();
      for(int i = 1; i < exp.nbOperands(); i++) {
        Object obj = evalExpValue(tuple, (ZExp)exp.getOperand(i));
        val = Math.pow(val, ((Number)obj).doubleValue());
      }
      return val;

    } else {
      throw new SQLException("ZEval.evalNumericExp(): Unknown operator " + op);
    }
  }

  /**
   * Evaluate a numeric or string expression (example: a+1)
   * @param tuple The tuple on which to evaluate the expression
   * @param exp The expression to evaluate
   * @return The expression's value
   */
  public Object evalExpValue(ZTuple tuple, ZExp exp) throws SQLException {

    Object o2 = null;

    if(exp instanceof ZConstant) {

      ZConstant c = (ZConstant)exp;

      switch(c.getType()) {

        case ZConstant.COLUMNNAME:

          Object o1 = tuple.getAttValue(c.getValue());
          if(o1 == null)
            throw new SQLException("ZEval.evalExpValue(): unknown column "
             + c.getValue());
          try {
            o2 = new Double(o1.toString());
          } catch(NumberFormatException e) {
            o2 = o1;
          }
          break;

        case ZConstant.NUMBER:
          o2 = new Double(c.getValue());
          break;

        case ZConstant.STRING:
        default:
          o2 = c.getValue();
          break;
      }
    } else if(exp instanceof ZExpression) {
      o2 = new Double(evalNumericExp(tuple, (ZExpression)exp));
    }
    return o2;
  }

  // test
  public static void main(String args[]) {
    try {
      BufferedReader db = new BufferedReader(new FileReader("test.db"));
      String tpl = db.readLine();
      ZTuple t = new ZTuple(tpl);

      ZqlParser parser = new ZqlParser();
      ZEval evaluator = new ZEval();

      while((tpl = db.readLine()) != null) {
        t.setRow(tpl);
        BufferedReader sql = new BufferedReader(new FileReader("test.sql"));
        String query;
        while((query = sql.readLine()) != null) {
          parser.initParser(new ByteArrayInputStream(query.getBytes()));
          ZExp exp = parser.readExpression();
          System.out.print(tpl + ", " + query + ", ");
          System.out.println(evaluator.eval(t, exp));
        }
        sql.close();
      }
      db.close();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
};

redpajama_set_name: RedPajamaGithub


text:
let qs = location.search.substring(1);
let hostName = location.hostname;
let url = location.href;


text:
<meta charset="utf-8">
(#) Frequently changing state should not  be directly read in composable function

!!! WARNING: Frequently changing state should not  be directly read in composable function
   This is a warning.

Id
:   `FrequentlyChangedStateReadInComposition`
Summary
:   Frequently changing state should not  be directly read in composable function
Severity
:   Warning
Category
:   Performance
Platform
:   Any
Vendor
:   Jetpack Compose
Identifier
:   androidx.compose.foundation
Feedback
:   https://issuetracker.google.com/issues/new?component=612128
Affects
:   Kotlin and Java files and test sources
Editing
:   This check runs on the fly in the IDE editor
Implementation
:   [Source Code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/foundation/foundation-lint/src/main/java/androidx/compose/foundation/lint/LazyLayoutStateReadInCompositionDetector.kt)
Tests
:   [Source Code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/foundation/foundation-lint/src/test/java/androidx/compose/foundation/lint/LazyLayoutStateReadInCompositionDetectorTest.kt)
Copyright Year
:   2022

This property is observable and is updated after every scroll or
remeasure. If you use it in the composable function directly, it will be
recomposed on every change, causing potential performance issues
including infinity recomposition loops. Prefer wrapping it with
derivedStateOf to use calculation based on this property in composition
or collect changes inside LaunchedEffect instead.

!!! Tip
   This lint check has an associated quickfix available in the IDE.

(##) Example

Here is an example of lint warnings produced by this check:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~text
src/androidx/compose/foundation/foo/test.kt:10:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val index = state.firstVisibleItemIndex
                ---------------------------

src/androidx/compose/foundation/foo/test.kt:11:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val offset = state.firstVisibleItemScrollOffset
                 ----------------------------------

src/androidx/compose/foundation/foo/test.kt:12:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val layoutInfo = state.layoutInfo
                     ----------------

src/androidx/compose/foundation/foo/test.kt:17:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val index = state.firstVisibleItemIndex
                ---------------------------

src/androidx/compose/foundation/foo/test.kt:18:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val offset = state.firstVisibleItemScrollOffset
                 ----------------------------------

src/androidx/compose/foundation/foo/test.kt:19:Warning: Frequently
changing state should not be directly read in composable function
[FrequentlyChangedStateReadInComposition]

    val layoutInfo = state.layoutInfo
                     ----------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Here is the source file referenced above:

`src/androidx/compose/foundation/foo/test.kt`:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~kotlin linenumbers
package androidx.compose.foundation.foo

import androidx.compose.runtime.Composable
import androidx.compose.foundation.lazy.grid.LazyGridState
import androidx.compose.foundation.lazy.LazyListState

@Composable
fun TestGrid(state: LazyGridState) {
    val index = state.firstVisibleItemIndex
    val offset = state.firstVisibleItemScrollOffset
    val layoutInfo = state.layoutInfo
}

@Composable
fun TestList(state: LazyListState) {
    val index = state.firstVisibleItemIndex
    val offset = state.firstVisibleItemScrollOffset
    val layoutInfo = state.layoutInfo
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also visit the
[source code](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:/compose/foundation/foundation-lint/src/test/java/androidx/compose/foundation/lint/LazyLayoutStateReadInCompositionDetectorTest.kt)
for the unit tests for this check to see additional scenarios.

The above example was automatically extracted from the first unit test
found for this lint check, `LazyLayoutStateReadInCompositionDetector.observablePropertiesUsedInComposableFunction`.
To report a problem with this extracted sample, visit
https://issuetracker.google.com/issues/new?component=612128.

(##) Suppressing

You can suppress false positives using one of the following mechanisms:

* Using a suppression annotation like this on the enclosing
  element:

  ```kt
  // Kotlin
  @Suppress("FrequentlyChangedStateReadInComposition")
  fun method() {
     problematicStatement()
  }
  ```

  or

  ```java
  // Java
  @SuppressWarnings("FrequentlyChangedStateReadInComposition")
  void method() {
     problematicStatement();
  }
  ```

* Using a suppression comment like this on the line above:

  ```kt
  //noinspection FrequentlyChangedStateReadInComposition
  problematicStatement()
  ```

* Using a special `lint.xml` file in the source tree which turns off
  the check in that folder and any sub folder. A simple file might look
  like this:
  ```xml
  <?xml version="1.0" encoding="UTF-8"?>
  <lint>
      <issue id="FrequentlyChangedStateReadInComposition" severity="ignore" />
  </lint>
  ```
  Instead of `ignore` you can also change the severity here, for
  example from `error` to `warning`. You can find additional
  documentation on how to filter issues by path, regular expression and
  so on
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/lintxml.md.html).

* In Gradle projects, using the DSL syntax to configure lint. For
  example, you can use something like
  ```gradle
  lintOptions {
      disable 'FrequentlyChangedStateReadInComposition'
  }
  ```
  In Android projects this should be nested inside an `android { }`
  block.

* For manual invocations of `lint`, using the `--ignore` flag:
  ```
  $ lint --ignore FrequentlyChangedStateReadInComposition ...`
  ```

* Last, but not least, using baselines, as discussed
  [here](https://googlesamples.github.io/android-custom-lint-rules/usage/baselines.md.html).

<!-- Markdeep: --><style class="fallback">body{visibility:hidden;white-space:pre;font-family:monospace}</style><script src="markdeep.min.js" charset="utf-8"></script><script src="https://morgan3d.github.io/markdeep/latest/markdeep.min.js" charset="utf-8"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility="visible")</script>


text:
namespace mtao::geometry::grid {
    template <int Dim, typename StaggeredGridType, typename FormStorage>
    class FormInterpolator {
        public:
            using PointType = typename StaggeredGridType::Vec;
            using Scalar = typename StaggeredGridType::Scalar;
            static constexpr int D = StaggeredGridType::D;
            static constexpr int ValSize = StaggeredGridType::template form_grid_size<Dim>();
            static constexpr bool return_scalar() { return ValSize == 1; }
            using VecType = Vector<Scalar,ValSize>;

            //using GridData= GridDataType;

            using RetType = std::conditional_t<return_scalar(), Scalar, VecType>;
            //using FormStorage = std::conditional<return_scalar(), GridType, std::array<GridData,ValSize>>;
            //using GridType = StaggeredGridType::GridType;

            FormInterpolator(const StaggeredGridType& b, const FormStorage& form_data): _base(b), _form_data(form_data) {}

            template <typename Derived>
                RetType operator()(const Eigen::MatrixBase<Derived>& x) const {
                    RetType r;
                    eval(x,r);
                    return r;
                }
            template <typename Derived, typename RetType>
                void eval(const Eigen::MatrixBase<Derived>& x, RetType& r) const {
                    if constexpr(return_scalar()) {
                        r = mtao::lerp(_form_data[0],_base.template grid<Dim,0>().local_coord(x));
                    } else {
                        for(auto&& [i,f,g]: mtao::iterator::enumerate(_form_data,_base.template grids<Dim>())) {
                            r(i) = mtao::lerp(f,g.local_coord(x));
                        }
                    }
                }
        private:
            const StaggeredGridType& _base;
            const FormStorage&_form_data;
    };
    template <int Dim, typename StaggeredGridType, typename GridDataType>
    auto form_interpolator(const StaggeredGridType& s, const GridDataType& g) {
        return FormInterpolator<Dim,StaggeredGridType, GridDataType>(s,g);
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>MapTableModelListener — LBD Mobile client Alpha documentation</title>

    <link rel="stylesheet" href="../../../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="LBD Mobile client Alpha documentation" href="../../../../index.html" />
    <link rel="up" title="fi.lbd.mobile.mapobjects" href="package-index.html" />
    <link rel="next" title="MarkerProducer" href="MarkerProducer.html" />
    <link rel="prev" title="MapTableModel" href="MapTableModel.html" />

Navigation

          index

          next |

          previous |

LBD Mobile client Alpha documentation »

fi.lbd.mobile.mapobjects »

MapTableModelListener¶

public interface <tt class="descname">MapTableModelListener</tt><T>¶

Listener for MapTableModel changes. Created by Tommi.

Methods¶

objectRemoved¶

 void <tt class="descname">objectRemoved</tt><big>(</big>T obj<big>)</big>¶

Invoked when the parameter object is removed from the model.

<col class="field-name" />
<col class="field-body" />

Parameters:

obj – Object which is removed.

requestCache¶

 void <tt class="descname">requestCache</tt><big>(</big>double latGridStart, double lonGridStart, double latGridEnd, double lonGridEnd<big>)</big>¶

Invoked when the model wants to cache certain region.

<col class="field-name" />
<col class="field-body" />

Parameters:

latGridStart – Start coordinate.

lonGridStart – Start coordinate.

latGridEnd – End coordinate.

lonGridEnd – End coordinate.

requestObjects¶

 void <tt class="descname">requestObjects</tt><big>(</big>double latGridStart, double lonGridStart, double latGridEnd, double lonGridEnd<big>)</big>¶

Invoked when the model wants to load objects for the given region. Objects should be set with MapTableModel addObjects method.

<col class="field-name" />
<col class="field-body" />

Parameters:

latGridStart – Start coordinate.

lonGridStart – Start coordinate.

latGridEnd – End coordinate.

lonGridEnd – End coordinate.

Table Of Contents

MapTableModelListener

Methods

objectRemoved

requestCache

requestObjects

Previous topic

MapTableModel

Next topic

MarkerProducer

This Page

Show Source

Quick search

    <form class="search" action="../../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

LBD Mobile client Alpha documentation »

fi.lbd.mobile.mapobjects »

        © Copyright 2015, Tommi und Ossi.
      Created using Sphinx 1.2.2.


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\ProjectsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Projects';
$this->params['breadcrumbs'][] = $this->title;
?>

                Jhon Doe

My Projects

Clients

Bugs

My Team

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Projects', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'project_id',
            'project_name',
            'project_description:ntext',
            'project_client:ntext',
            'project_startdate',
            // 'project_enddate',
            // 'user_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
import aplib.net.ip as ip
import time

"""
ConnectionManager manages ConnectionPools.

A ConnectionPool is associated with a particular host,port combo

A ConnectionPool contains 1 or more connections, zero of which are guaranteed
to be in a free and connected state.

A connection maintains a socket that is connected to an end point. If the
connection times out either locally or on the remote end the socket is closed.

The ConnectionPool periodically checks the state of its Connections and destroys any inactive Connection objects.

The ConnectionManager periodically checks the state of its ConnectionPools and removes reference to any that have zero Connections left.

A ConnectionManager has limits on the maximum number of ConnectionPools it will create.

Exceeding any of these limits results in an exception being raised and the
connection is not created. This behavior is preferred over creating a queue for
two reasons: This is simpler and the queue only introduces latency.

"""

# How long to not use a socket before we decide to close it
sock_timeout = 40

class MaxConnectionsLimit(Exception):

    """Max connections limit exceeded for a connection
    pool."""

    def __init__(self, host, port):
        self.host = host
        self.port = port

class IfaceNotCompatible(Exception):

    """IP family of the interface to bind to and remote host do not match."""

    def __init__(self, host, port):
        self.host = host
        self.port = port

class Connection(object):
    __slots__ = ('host', 'port', 'bind_address', 'last_used_time', 'in_use',
                 'sock')
    def __init__(self, host, port, bind_address):
        self.host = host
        self.port = port
        self.bind_address = bind_address
        self.last_used_time = time.time()
        self.in_use = False
        self.sock = None

        self.init_socket()

    def init_socket(self):
        """Initialize socket.  This method MUST be implemented by child
        classes."""
        raise NotImplementedError

    def close(self):
        """Close this connection."""
        if self.sock is not None:
            self.sock.close()
            self.sock = None

    def is_usable(self):
        """
        Return True if the connection is still usable.
        False otherwise.
        """
        if self.sock is not None:
            conn_old = time.time() - self.last_used_time > sock_timeout
            if self.in_use or not conn_old:
                return True

        return False

    def is_ready(self):
        """
        Return True if the connection is ready.
        False otherwise.
        """
        if self.sock is not None and not self.in_use:
            return True
        else:
            return False

    def mark_used(self):
        """Mark the connection used."""
        self.in_use = True
        self.last_used_time = time.time()

class ConnectionPool(object):

    conn_class = None
    """This must be set by child class."""

    __slots__ = ('host', 'port', 'connections', 'max_connections',
                 'no_of_connections')

    def __init__(self, host, port, max_connections=10):
        self.host = host
        self.port = port
        self.connections = []
        self.no_of_connections = 0
        self.max_connections = max_connections

    def clean_connections(self):
        conns_to_keep = []
        conns_to_orphan = self.no_of_connections - self.max_connections
        for connection in self.connections:
            if conns_to_orphan > 0 and not connection.in_use:
                connection.close()
                conns_to_orphan -= 1
                continue

            if connection.is_usable():
                conns_to_keep.append(connection)
            else:
                connection.close()

        self.connections = conns_to_keep
        self.no_of_connections = len(conns_to_keep)

    def get_connection(self, bind_address):
        """Get a connection if already available in connections or create a new
        one and return."""

        return self.get_ready_connection(bind_address) or \
            self.get_new_connection(bind_address)

    def get_ready_connection(self, bind_address):
        """Return a ready connection"""
        for connection in self.connections:
            if connection.is_ready() and \
               connection.bind_address in bind_address:
                connection.mark_used()
                return connection
        else:
            return None

    def get_new_connection(self, bind_address):
        """Return a new connection"""
        if len(self.connections) >= self.max_connections:
            raise MaxConnectionsLimit(self.host, self.port)
        else:
            try:
                self.no_of_connections += 1
                if ip.is_ipv6(self.host):
                    bind_ip = bind_address[1]
                else:
                    bind_ip = bind_address[0]

                if bind_ip is None:
                    raise IfaceNotCompatible(self.host, self.port)
                new_connection = self.conn_class(self.host, self.port,
                                                 bind_ip)
            except:
                self.no_of_connections -= 1
                raise

            new_connection.mark_used()
            self.connections.append(new_connection)

        return new_connection


text:
"""Text/number formatting"""

class ByteCountFormatter(object):
    #pylint: disable=too-few-public-methods

    """Human-readable display of byte counts in various formats.

    By default, the formatter uses SI and bytes, so 1000 => "1 KB". All
    combinations of (byte, bit) x (SI, binary) are supported, though you
    probably shouldn't use bits with the binary prefixes.

    Attributes:
        unit_bits    True for bits or False for bytes
        prefix_si    True for SI or False for binary prefixes
    """

    SI_prefixes = ('k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    binary_prefixes = ('Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi')

    def __init__(self):
        self.unit_bits = False
        self.prefix_si = True

    def __call__(self, count):

        """Formats a byte count using the configured settings."""

        if self.unit_bits:
            count *= 8
            unit = 'b'
        else:
            unit = 'B'

        if self.prefix_si:
            factor = 1000.
            prefixes = self.SI_prefixes
        else:
            factor = 1024.
            prefixes = self.binary_prefixes

        if abs(count) < factor:
            return u'%d %c' % (count, unit)
        size = float(count)
        prefix_index = 0
        while abs(size) >= factor and prefix_index < len(prefixes):
            size /= factor
            prefix_index += 1
        return u'%.2f %s%c' % (size, prefixes[prefix_index-1], unit)


text:
from common import BaseTest

class AccountTests(BaseTest):

    def test_root_mfa_enabled(self):
        session_factory = self.replay_flight_data('test_account_root_mfa')
        p = self.load_policy({
            'name': 'root-mfa',
            'resource': 'account',
            'filters': [
                {'type': 'iam-summary',
                 'key': 'AccountMFAEnabled', 'value': False}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 0)

    def test_root_api_keys(self):
        session_factory = self.replay_flight_data('test_account_root_api_keys')
        p = self.load_policy({
            'name': 'root-api',
            'resource': 'account',
            'filters': [
                {'type': 'iam-summary'}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 0)

    def test_cloudtrail_enabled(self):
        session_factory = self.replay_flight_data('test_account_trail')
        p = self.load_policy({
            'name': 'trail-enabled',
            'resource': 'account',
            'filters': [
                {'type': 'check-cloudtrail',
                 'multi-region': True,
                 'kms': True,
                 'file-digest': True,
                 'global-events': True}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 0)

    def test_cloudtrail_notifies(self):
        session_factory = self.replay_flight_data('test_account_trail')
        p = self.load_policy({
            'name': 'trail-enabled',
            'resource': 'account',
            'filters': [
                {'type': 'check-cloudtrail',
                 'notifies': True}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_config_enabled(self):
        session_factory = self.replay_flight_data('test_account_config')
        p = self.load_policy({
            'name': 'config-enabled',
            'resource': 'account',
            'filters': [
                {'type': 'check-config',
                 'all-resources': True,
                 'running': True}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 0)

    def test_config_enabled_global(self):
        session_factory = self.replay_flight_data('test_account_config_global')
        p = self.load_policy({
            'name': 'config-enabled',
            'resource': 'account',
            'filters': [
                {'type': 'check-config',
                 'global-resources': True}
            ]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)

    def test_service_limit(self):
        session_factory = self.replay_flight_data('test_account_service_limit')
        p = self.load_policy({
            'name': 'service-limit',
            'resource': 'account',
            'filters': [{
                'type': 'service-limit',
                'threshold': 0}]}, session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(len(resources[0]['ServiceLimitsExceeded']), 50)

    def test_service_limit_specific_check(self):
        session_factory = self.replay_flight_data('test_account_service_limit')
        p = self.load_policy({
            'name': 'service-limit',
            'resource': 'account',
            'filters': [{
                'type': 'service-limit',
                'limits': ['DB security groups'],
                'threshold': 1.0
            }]},
            session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            set([l['service'] for l in resources[0]['ServiceLimitsExceeded']]),
            set(['RDS']))
        self.assertEqual(
            set([l['region'] for l in resources[0]['ServiceLimitsExceeded']]),
            set(['us-east-1', 'us-west-2', 'us-west-1']))
        self.assertEqual(
            set([l['check'] for l in resources[0]['ServiceLimitsExceeded']]),
            set(['DB security groups']))
        self.assertEqual(len(resources[0]['ServiceLimitsExceeded']), 3)

    def test_service_limit_specific_service(self):
        session_factory = self.replay_flight_data('test_account_service_limit')
        p = self.load_policy({
            'name': 'service-limit',
            'resource': 'account',
            'filters': [{
                'type': 'service-limit', 'services': ['IAM'], 'threshold': 1.0
            }]},
            session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 1)
        self.assertEqual(
            set([l['service'] for l in resources[0]['ServiceLimitsExceeded']]),
            set(['IAM']))
        self.assertEqual(len(resources[0]['ServiceLimitsExceeded']), 2)

    def test_service_limit_no_threshold(self):
        # only warns when the default threshold goes to warning or above
        session_factory = self.replay_flight_data('test_account_service_limit')
        p = self.load_policy({
            'name': 'service-limit',
            'resource': 'account',
            'filters': [{
                'type': 'service-limit'}]},
            session_factory=session_factory)
        resources = p.run()
        self.assertEqual(len(resources), 0)


text:
<?php namespace CoandaCMS\Coanda\Pages\PageTypes;

class MissingPageType extends \CoandaCMS\Coanda\Pages\PageType {

    /**
     * @var string
     */
    protected $name = 'Missing Page Type';
    /**
     * @var string
     */
    protected $identifier = 'missing';
    /**
     * @var string
     */
    protected $icon = 'fa-question-circle';

    /**
     * @var array
     */
    protected $schema = [
        'name' => 'Name|textline|required|generates_slug'
    ];

    /**
     * @param $version
     * @param array $data
     * @return string
     */
    public function template($version, $data = [])
    {
        return 'coanda::missing_page_type';
    }
}


text:
$packageName = 'meld'
$version = '3.12.0'
$uninstallRegistryPath_x86 = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Meld"
$uninstallRegistryPath_x64 = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Meld"
$installerType = 'MSI'
$silentArgs = '/quiet'
$url = 'https://download.gnome.org/binaries/win32/meld/3.12/Meld-3.12.0-win32.msi'
$validExitCodes = @(0) #please insert other valid exit codes here, exit codes for ms http://msdn.microsoft.com/en-us/library/aa368542(VS.85).aspx
$maintainer = 'tonigellida'

try {
	$processor = Get-WmiObject Win32_Processor
	$is64bit = $processor.AddressWidth -eq 64

	if ($is64bit) {
 		if (Test-Path $uninstallRegistryPath_x64) {
			$installedVersion = (Get-ItemProperty $uninstallRegistryPath_x64).DisplayVersion
		}
	} else {
		if (Test-Path $uninstallRegistryPath_x86) {
			$installedVersion = (Get-ItemProperty $uninstallRegistryPath_x86).DisplayVersion
		}
	}

	if ($installedVersion -gt $version) {
		Write-Host "Your $packageName $installedVersion is higher than the $version provided by chocolatey repo."
		Write-Host "Please wait or contact the maintainer $maintainer to update this package."
		Write-Host "When the package is updated try installing again. Thanks."

	} elseif ($installedVersion -eq $version) {
		Write-Host "$packageName $version is already installed."

	} else {

    # Download and install the program
		Install-ChocolateyPackage "$packageName" "$installerType" "$silentArgs" "$url" "$url64" -validExitCodes $validExitCodes

	}
	Write-ChocolateySuccess $packageName
} catch {
	Write-ChocolateyFailure $packageName "$($_.Exception.Message)"
	throw
}


text:
/**
Represents a single texture atlas with several sprites and its corresponding base {@link external:Texture|`THREE.Texture`}. You do not interact with this class directly, it is entirely managed for you by a {@link module:texture-manager|`TextureManager`} instance. Documented only to satisfy the curiosity of fellow developers stumbling upon this.

@module texture-manager/knapsack
 */

import * as THREE from 'three/build/three.js';
import KnapsackNode from './knapsack/node.js';

/**
  * @constructor
  * @param {TextureManager} textureManager - The {@link module:texture-manager|`TextureManager`} which created this `Knapsack`
  * @param {integer} size - The size of the texture
  */
class Knapsack {
  constructor( textureManager, size ) {
    this.textureManager = textureManager;
    this.textureSize = size;
    this.textureLoaded = false;
    this.rootNode = new KnapsackNode( this );
    // Lazy initialising these:
    this._rootTexture = null;
    this._canvas = null;
  }

  /**
   * Lazily built HTML `<canvas>` element for this `Knapsack`.
   * @type {external:canvas}
   * @readonly
   */
  get canvas () {
    if ( ! this._canvas ) {
      this._canvas = document.createElement(`canvas`);
      this._canvas.width  = this.textureSize;
      this._canvas.height = this.textureSize;
    }
    return this._canvas;
  }

  /**
   * Lazily built {@link external:Texture|`THREE.Texture`}, this is created as a "master" texture. Each node will get its own `.clone()`, which should be shared in memory.
   * @type {external:Texture}
   * @readonly
   */
  get rootTexture () {
    if ( ! this._rootTexture ) {
      this._rootTexture = new THREE.Texture( this.canvas, THREE.UVMapping );
    }
    return this._rootTexture;
  }

  /**
   * Proxy method, allocate a texture atlas node for a sprite image of `width` by `height` pixels.
   * @param {integer} width
   * @param {integer} height
   * @returns {external:Promise}
   */
  allocateNode( width, height ) {
    return this.rootNode.allocate( width, height );
  }
}

export default Knapsack;


text:
module ActiveModel
  class Serializer
    class Adapter
      class JsonApi < Adapter
        class FragmentCache

          def fragment_cache(root, cached_hash, non_cached_hash)
            hash              = {}
            core_cached       = cached_hash.first
            core_non_cached   = non_cached_hash.first
            no_root_cache     = cached_hash.delete_if {|key, value| key == core_cached[0] }
            no_root_non_cache = non_cached_hash.delete_if {|key, value| key == core_non_cached[0] }
            cached_resource   = (core_cached[1]) ? core_cached[1].merge(core_non_cached[1]) : core_non_cached[1]
            hash = (root) ? { root => cached_resource } : cached_resource
            hash.merge no_root_non_cache.merge no_root_cache
          end

        end
      end
    end
  end
end


text:
#ifndef _GROK_PATTERN_H_
#define _GROK_PATTERN_H_

#include "grok.h"
#include <tcutil.h>

TCLIST *grok_pattern_name_list(const grok_t *grok);

int grok_pattern_add(const grok_t *grok, const char *name, size_t name_len,
                      const char *regexp, size_t regexp_len);
int grok_pattern_find(const grok_t *grok, const char *name, size_t name_len,
                      const char **regexp, size_t *regexp_len);
int grok_patterns_import_from_file(const grok_t *grok, const char *filename);
int grok_patterns_import_from_string(const grok_t *grok, const char *buffer);
bool grok_pattern_delete(const grok_t *grok, const char *name, size_t name_len);
/* Exposed only for testing */
void _pattern_parse_string(const char *line,
                           const char **name, size_t *name_len,
                           const char **regexp, size_t *regexp_len);

#endif /* _GROK_PATTERN_H_ */


text:
package com.katas.algo.sorting;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.Arrays;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

class QuickSortShould {

    private SortingAlgorithm quickSort = new QuickSort();

    private static Stream<Arguments> provideArraysForTest() {

        return Stream.of(
                Arguments.of((Object) new Integer[]{44, 12, 566, 1212, 56436, 7233}),
                Arguments.of((Object) new Integer[]{-22, 2, 16, 1212, 36, 36, 36, 0, 55})
        );

    }

    @ParameterizedTest
    @MethodSource("provideArraysForTest")
    public void sortArrayInAscendingOrder(Integer[] inputArray) {

        //setup
        Integer[] sortedByJava = Arrays.copyOf(inputArray, inputArray.length);

        //execute
        quickSort.sort(inputArray);

        //verify
        Arrays.sort(sortedByJava);
        assertArrayEquals(sortedByJava, inputArray);

    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Threading;
using System.Threading.Tasks;
using Azure.Test.Perf;

namespace Azure.Containers.ContainerRegistry.Perf
{
    public sealed class ListRepositories : ContainerRegistryPerfTest
    {
        private readonly ContainerRegistryClient _client;

        public ListRepositories(PerfOptions options) : base(options)
        {
            _client = new ContainerRegistryClient(new Uri(PerfTestEnvironment.Instance.Endpoint), PerfTestEnvironment.Instance.Credential,
                new ContainerRegistryClientOptions()
                {
                    Audience = ContainerRegistryAudience.AzureResourceManagerPublicCloud
                });
        }

        public override void Run(CancellationToken cancellationToken)
        {
            foreach (var repositoryName in _client.GetRepositoryNames())
            {
                _client.GetRepository(repositoryName);
            }
        }

        public override async Task RunAsync(CancellationToken cancellationToken)
        {
            await foreach (var repositoryName in _client.GetRepositoryNamesAsync())
            {
                _client.GetRepository(repositoryName);
            }
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Paleontol Zh 1, January-February: 8.

#### Original name
null

### Remarks
null


text:
package com.github.anba.es6draft.runtime.objects;

import static com.github.anba.es6draft.runtime.AbstractOperations.*;
import static com.github.anba.es6draft.runtime.internal.Errors.newTypeError;
import static com.github.anba.es6draft.runtime.internal.Properties.createProperties;
import static com.github.anba.es6draft.runtime.types.Null.NULL;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.github.anba.es6draft.runtime.ExecutionContext;
import com.github.anba.es6draft.runtime.Realm;
import com.github.anba.es6draft.runtime.internal.CompatibilityOption;
import com.github.anba.es6draft.runtime.internal.Initialisable;
import com.github.anba.es6draft.runtime.internal.Messages;
import com.github.anba.es6draft.runtime.internal.Properties.Accessor;
import com.github.anba.es6draft.runtime.internal.Properties.CompatibilityExtension;
import com.github.anba.es6draft.runtime.internal.Properties.Function;
import com.github.anba.es6draft.runtime.internal.Properties.Prototype;
import com.github.anba.es6draft.runtime.internal.Properties.Value;
import com.github.anba.es6draft.runtime.internal.ScriptException;
import com.github.anba.es6draft.runtime.types.BuiltinSymbol;
import com.github.anba.es6draft.runtime.types.Intrinsics;
import com.github.anba.es6draft.runtime.types.Property;
import com.github.anba.es6draft.runtime.types.ScriptObject;
import com.github.anba.es6draft.runtime.types.Symbol;
import com.github.anba.es6draft.runtime.types.Type;
import com.github.anba.es6draft.runtime.types.builtins.BuiltinFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArguments;
import com.github.anba.es6draft.runtime.types.builtins.ExoticArray;
import com.github.anba.es6draft.runtime.types.builtins.ExoticBoundFunction;
import com.github.anba.es6draft.runtime.types.builtins.ExoticProxy;
import com.github.anba.es6draft.runtime.types.builtins.ExoticString;
import com.github.anba.es6draft.runtime.types.builtins.FunctionObject;
import com.github.anba.es6draft.runtime.types.builtins.OrdinaryObject;

/**
 *
19 Fundamental Objects

 *
19.1 Object Objects

 *

 *
19.1.4 Properties of the Object Prototype Object
 *
19.1.5 Properties of Object Instances
 *

 */
public final class ObjectPrototype extends OrdinaryObject implements Initialisable {
    public ObjectPrototype(Realm realm) {
        super(realm);
    }

    @Override
    public void initialise(ExecutionContext cx) {
        createProperties(this, cx, Properties.class);
        createProperties(this, cx, AdditionalProperties.class);
    }

    public enum Properties {
        ;

        @Prototype
        public static final ScriptObject __proto__ = null;

        /**
         * 19.1.4.1 Object.prototype.constructor
         */
        @Value(name = "constructor")
        public static final Intrinsics constructor = Intrinsics.Object;

        /**
         * 19.1.4.6 Object.prototype.toString ( )
         */
        @Function(name = "toString", arity = 0)
        public static Object toString(ExecutionContext cx, Object thisValue) {
            /* step 1 */
            if (Type.isUndefined(thisValue)) {
                return "[object Undefined]";
            }
            /* step 2 */
            if (Type.isNull(thisValue)) {
                return "[object Null]";
            }
            /* step 3 */
            ScriptObject o = ToObject(cx, thisValue);
            /* steps 4-15 */
            String builtinTag;
            if (o instanceof ExoticArray) {
                builtinTag = "Array";
            } else if (o instanceof ExoticString) {
                builtinTag = "String";
            } else if (o instanceof ExoticProxy) {
                builtinTag = "Proxy";
            } else if (o instanceof ExoticArguments) {
                builtinTag = "Arguments";
            } else if (o instanceof FunctionObject || o instanceof BuiltinFunction
                    || o instanceof ExoticBoundFunction) {
                builtinTag = "Function";
            } else if (o instanceof ErrorObject) {
                builtinTag = "Error";
            } else if (o instanceof BooleanObject) {
                builtinTag = "Boolean";
            } else if (o instanceof NumberObject) {
                builtinTag = "Number";
            } else if (o instanceof DateObject) {
                builtinTag = "Date";
            } else if (o instanceof RegExpObject) {
                builtinTag = "RegExp";
            } else {
                builtinTag = "Object";
            }
            /* steps 15-16 */
            boolean hasTag = HasProperty(cx, o, BuiltinSymbol.toStringTag.get());
            /* steps 17-18 */
            String tag;
            if (!hasTag) {
                tag = builtinTag;
            } else {
                try {
                    Object ttag = Get(cx, o, BuiltinSymbol.toStringTag.get());
                    if (Type.isString(ttag)) {
                        tag = Type.stringValue(ttag).toString();
                    } else {
                        tag = "???";
                    }
                } catch (ScriptException e) {
                    tag = "???";
                }
                // FIXME: spec bug? (censor 'Object' again, but see Bug 1148) (Bug 1408/1459)
                if (censoredNames.contains(tag) && !builtinTag.equals(tag)) {
                    tag = "~" + tag;
                }
            }
            /* step 19 */
            return "[object " + tag + "]";
        }

        private static final Set<String> censoredNames;
        static {
            List<String> names = Arrays.asList("Arguments", "Array", "Boolean", "Date", "Error",
                    "Function", "Number", "RegExp", "String");
            censoredNames = new HashSet<>(names);
        }

        /**
         * 19.1.4.5 Object.prototype.toLocaleString ( )
         */
        @Function(name = "toLocaleString", arity = 0)
        public static Object toLocaleString(ExecutionContext cx, Object thisValue) {
            /* steps 1-3 */
            return Invoke(cx, thisValue, "toString");
        }

        /**
         * 19.1.4.7 Object.prototype.valueOf ( )
         */
        @Function(name = "valueOf", arity = 0)
        public static Object valueOf(ExecutionContext cx, Object thisValue) {
            /* step 1 */
            ScriptObject o = ToObject(cx, thisValue);
            /* step 2 */
            return o;
        }

        /**
         * 19.1.4.2 Object.prototype.hasOwnProperty (V)
         */
        @Function(name = "hasOwnProperty", arity = 1)
        public static Object hasOwnProperty(ExecutionContext cx, Object thisValue, Object v) {
            /* steps 1-2 */
            Object p = ToPropertyKey(cx, v);
            /* steps 3-4 */
            ScriptObject o = ToObject(cx, thisValue);
            /* step 5 */
            if (p instanceof String) {
                return HasOwnProperty(cx, o, (String) p);
            } else {
                return HasOwnProperty(cx, o, (Symbol) p);
            }
        }

        /**
         * 19.1.4.3 Object.prototype.isPrototypeOf (V)
         */
        @Function(name = "isPrototypeOf", arity = 1)
        public static Object isPrototypeOf(ExecutionContext cx, Object thisValue, Object v) {
            /* step 1 */
            if (!Type.isObject(v)) {
                return false;
            }
            ScriptObject _v = Type.objectValue(v);
            /* steps 2-3 */
            ScriptObject o = ToObject(cx, thisValue);
            /* step 4 */
            for (;;) {
                _v = _v.getPrototypeOf(cx);
                if (_v == null) {
                    return false;
                }
                if (SameValue(o, _v)) {
                    return true;
                }
            }
        }

        /**
         * 19.1.4.4 Object.prototype.propertyIsEnumerable (V)
         */
        @Function(name = "propertyIsEnumerable", arity = 1)
        public static Object propertyIsEnumerable(ExecutionContext cx, Object thisValue, Object v) {
            /* steps 1-2 */
            String p = ToFlatString(cx, v);
            /* steps 3-4 */
            ScriptObject o = ToObject(cx, thisValue);
            /* step 5 */
            Property desc = o.getOwnProperty(cx, p);
            /* step 6 */
            if (desc == null) {
                return false;
            }
            /* step 7 */
            return desc.isEnumerable();
        }
    }

    /**
     * B.2.2 Additional Properties of the Object.prototype Object
     */
    @CompatibilityExtension(CompatibilityOption.ObjectPrototype)
    public enum AdditionalProperties {
        ;

        /**
         * B.2.2.1 Object.prototype.__proto__

         * B.2.2.1.1 get Object.prototype.__proto__
         */
        @Accessor(name = "__proto__", type = Accessor.Type.Getter)
        public static Object getPrototype(ExecutionContext cx, Object thisValue) {
            /* steps 1-2 */
            ScriptObject o = ToObject(cx, thisValue);
            /* step 3 */
            ScriptObject p = o.getPrototypeOf(cx);
            return p != null ? p : NULL;
        }

        /**
         * B.2.2.1 Object.prototype.__proto__

         * B.2.2.1.2 set Object.prototype.__proto__
         */
        @Accessor(name = "__proto__", type = Accessor.Type.Setter)
        public static Object setPrototype(ExecutionContext cx, Object thisValue, Object proto) {
            /* steps 1-2 */
            Object o = CheckObjectCoercible(cx, thisValue);
            /* step 3 */
            if (!Type.isObjectOrNull(proto)) {
                return proto;
            }
            /* step 4 */
            if (!Type.isObject(o)) {
                return proto;
            }
            /* steps 5-6 */
            ScriptObject obj = Type.objectValue(o);
            ScriptObject p = Type.objectValueOrNull(proto);
            boolean status = obj.setPrototypeOf(cx, p);
            /* step 7 */
            if (!status) {
                // provide better error messages for ordinary objects
                if (obj instanceof OrdinaryObject) {
                    if (!obj.isExtensible(cx)) {
                        throw newTypeError(cx, Messages.Key.NotExtensible);
                    }
                    throw newTypeError(cx, Messages.Key.CyclicProto);
                }
                throw newTypeError(cx, Messages.Key.IncompatibleObject);
            }
            /* step 8 */
            return proto;
        }
    }
}


text:
<?php

namespace Predis\Command;

/**
 * @group commands
 * @group realm-list
 */
class ListPushHeadXTest extends PredisCommandTestCase
{
    /**
     * {@inheritdoc}
     */
    protected function getExpectedCommand()
    {
        return 'Predis\Command\ListPushHeadX';
    }

    /**
     * {@inheritdoc}
     */
    protected function getExpectedId()
    {
        return 'LPUSHX';
    }

    /**
     * @group disconnected
     */
    public function testFilterArguments()
    {
        $arguments = array('key', 'value');
        $expected = array('key', 'value');

        $command = $this->getCommand();
        $command->setArguments($arguments);

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testParseResponse()
    {
        $this->assertSame(1, $this->getCommand()->parseResponse(1));
    }

    /**
     * @group disconnected
     */
    public function testPrefixKeys()
    {
        $arguments = array('key', 'value');
        $expected = array('prefix:key', 'value');

        $command = $this->getCommandWithArgumentsArray($arguments);
        $command->prefixKeys('prefix:');

        $this->assertSame($expected, $command->getArguments());
    }

    /**
     * @group disconnected
     */
    public function testPrefixKeysIgnoredOnEmptyArguments()
    {
        $command = $this->getCommand();
        $command->prefixKeys('prefix:');

        $this->assertSame(array(), $command->getArguments());
    }

    /**
     * @group connected
     */
    public function testPushesElementsToHeadOfExistingList()
    {
        $redis = $this->getClient();

        $redis->lpush('metavars', 'foo');

        $this->assertSame(2, $redis->lpushx('metavars', 'hoge'));
        $this->assertSame(array('hoge', 'foo'), $redis->lrange('metavars', 0, -1));
    }

    /**
     * @group connected
     */
    public function testDoesNotPushElementOnNonExistingKey()
    {
        $redis = $this->getClient();

        $this->assertSame(0, $redis->lpushx('metavars', 'foo'));
        $this->assertSame(0, $redis->lpushx('metavars', 'hoge'));
        $this->assertFalse($redis->exists('metavars'));
    }

    /**
     * @group connected
     * @expectedException Predis\ServerException
     * @expectedExceptionMessage Operation against a key holding the wrong kind of value
     */
    public function testThrowsExceptionOnWrongType()
    {
        $redis = $this->getClient();

        $redis->set('metavars', 'foo');
        $redis->lpushx('metavars', 'hoge');
    }
}


text:
import os
import random as rn
import unittest as ut

import simple_ann.dataModel.inputDataModel as id
import simple_ann.module.activationFunction as af
import simple_ann.module.backwardFunction as bf
import simple_ann.module.forewardFunction as sf
import simple_ann.utility.utility as util
import simple_ann.utility.utilityDataModel as utilModel
import simple_ann.module.initiationValueGenerator as init
import simple_ann.dataModel.trainingResultModel as tr

class trainingTest(ut.TestCase):

    def testInputFile(self):
        """
        :return:
        """

        #Sample input data file, to compare with
        inputDataSample = {
          "epoch":50,
          "bias":0.001,
          "learningRate":0.012,
          "threshold":0.05,
          "activationFunction":"hardLimit",
          "nInput":6,
          "weight":"zero",
          "inputStructure":{
            "nRows":5,
            "nColumns":5
          },
          "dataDetail":[
            {
              "target":1,
              "input":[0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0,0,1,1,1,0]
            },
            {
              "target":1,
              "input":[0,1,1,1,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,1,1,0]
            },
            {
              "target":1,
              "input":[0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0,0,0,1,0,0]
            },
            {
              "target":0,
              "input":[0,1,1,1,1,0,1,0,1,0,0,1,1,1,0,0,1,0,1,0,1,1,1,0,0]
            },
            {
              "target":0,
              "input":[0,1,1,1,1,1,1,0,1,0,0,1,0,0,0,0,1,0,1,0,1,1,1,0,0]
            },
            {
              "target":0,
              "input":[0,0,1,1,1,0,0,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0]
            }
          ]
        }

        dataSample = id.as_inputData(inputDataSample)

        #real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")

        self.assertEqual(dataSample.epoch, inputData.epoch)
        self.assertEqual(dataSample.bias, inputData.bias)
        self.assertEqual(dataSample.learningRate, inputData.learningRate)
        self.assertEqual(dataSample.threshold, inputData.threshold)
        self.assertEqual(dataSample.activationFunction, inputData.activationFunction)
        self.assertEqual(dataSample.nInput, inputData.nInput)
        self.assertEqual(dataSample.weight, inputData.weight)
        self.assertEqual(dataSample.inputStructure['nRows'], inputData.inputStructure.nRows)
        self.assertEqual(dataSample.inputStructure['nColumns'], inputData.inputStructure.nColumns)
        self.assertEqual(dataSample.dataDetail[0]['target'], inputData.dataDetail[0].target)
        self.assertEqual(dataSample.dataDetail[0]['input'], inputData.dataDetail[0].input)

    def testWeightZeroInitiation(self):
        #test zero initiation
        nInitiation = 25
        zeroWeight = init.generateZeroList(nInitiation)

        #check length of list
        self.assertEqual(len(zeroWeight), nInitiation)

        #check value inside of list
        for value in zeroWeight:
            self.assertEqual(value, 0)

    def testWeightRandomInitiation(self):
        #test random initiation
        nInitiation = 25
        randomWeight = init.generateRandomList(nInitiation)

        #check length of list
        self.assertEqual(len(randomWeight), nInitiation)

        #check value inside of list
        for value in randomWeight:
            self.assertNotAlmostEqual(value,1.1)

    def testIntegrationZeroRandomInitiation(self):
        nInitiation = 25
        typeListOne = 'zero'
        typeListTwo = 'random'

        zeroWeight = init.automaticGeneratorList(nInitiation, typeListOne)
        randomWeight = init.automaticGeneratorList(nInitiation, typeListTwo)

        # check length of list
        self.assertEqual(len(zeroWeight), nInitiation)
        self.assertEqual(len(randomWeight), nInitiation)

        # check value inside of list
        for index in range(0, len(zeroWeight)-1):
            self.assertEqual(zeroWeight[index], 0)
            self.assertNotAlmostEqual(randomWeight[index], 1.1)

    def testSummingFunctionFromFile(self):
        #test method summing function, from file
        nInitiation = 25

        #real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")
        dataDetail = inputData.dataDetail

        self.assertIsInstance(inputData, id.inputData)
        self.assertIsInstance(dataDetail[0].input, list)

        #use random weight list generator
        weightList = init.generateRandomList(nInitiation)
        summingFunctionValue = sf.summingFunction(dataDetail[0].input, weightList)

        manualCounting = 0.0
        for index in range(0, len(dataDetail[0].input) - 1):
            manualCounting = manualCounting + (dataDetail[0].input[index] * weightList[index])

        self.assertEqual(manualCounting, summingFunctionValue)

    def testSummingFunctionWithBiasFromFile(self):
        # test method summing function, from file
        nInitiation = 25
        bias = 0.02

        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")
        dataDetail = inputData.dataDetail

        self.assertIsInstance(inputData, id.inputData)
        self.assertIsInstance(dataDetail[0].input, list)

        # use random weight list generator
        weightList = init.generateRandomList(nInitiation)
        summingFunctionValue = sf.summingFunctionWithBias(dataDetail[0].input, weightList, bias)

        manualCounting = 0.0
        for index in range(0, len(dataDetail[0].input) - 1):
            manualCounting = manualCounting + (dataDetail[0].input[index] * weightList[index])
        manualCounting = manualCounting + bias

        self.assertEqual(manualCounting, summingFunctionValue)

    def testSummingFunctionBackwardsFromFile(self):
        # test method summing function, from file
        nInitiation = 25

        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")
        dataDetail = inputData.dataDetail

        self.assertIsInstance(inputData, id.inputData)
        self.assertIsInstance(dataDetail[0].input, list)

        # use random weight list generator
        weightList = init.generateRandomList(nInitiation)
        addWeightList = init.generateRandomList(nInitiation)
        newWeightList = sf.addingValueWeight(weightList, addWeightList)

        summingFunctionValue, weight = sf.summingFunctionBackwards(dataDetail[0].input, weightList, addWeightList)

        manualCounting = 0.0
        for index in range(0, len(dataDetail[0].input) - 1):
            manualCounting = manualCounting + (dataDetail[0].input[index] * newWeightList[index])

        self.assertEqual(manualCounting, summingFunctionValue)
        self.assertListEqual(newWeightList, weight)

    def testSummingFunctionWithBiasBackwardFromFile(self):
        # test method summing function, from file
        nInitiation = 25
        bias = 0.02
        addBias = rn.uniform(0.0, 1.0)
        newBias = sf.addingValueBias(bias, addBias)

        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")
        dataDetail = inputData.dataDetail

        self.assertIsInstance(inputData, id.inputData)
        self.assertIsInstance(dataDetail[0].input, list)

        # use random weight list generator
        weightList = init.generateRandomList(nInitiation)
        addWeightList = init.generateRandomList(nInitiation)
        newWeightList = sf.addingValueWeight(weightList, addWeightList)

        summingFunctionValue, weight, bias2 = sf.summingFunctionWithBiasBackward(dataDetail[0].input, weightList,
                                                                                addWeightList, bias, addBias)
        manualCounting = 0.0
        for index in range(0, len(dataDetail[0].input) - 1):
            manualCounting = manualCounting + (dataDetail[0].input[index] * newWeightList[index])
        manualCounting = manualCounting + newBias

        self.assertEqual(manualCounting, summingFunctionValue)
        self.assertEqual(newBias, bias2)
        self.assertListEqual(weight, newWeightList)

    def testActivationFunction(self):
        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")

        activationFunction = inputData.activationFunction
        threshold = inputData.threshold
        summingValue = 0.7

        activationResult = af.hardLimit(summingValue, threshold)

        #Comparison
        if summingValue>= threshold:
            activationResult2 = 1
        else:
            activationResult2 = 0

        self.assertEqual(activationResult, activationResult2)

    def testBackward(self):
        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")

        learningRate = inputData.learningRate
        dataDetail = inputData.dataDetail
        value = dataDetail[0].input
        target = dataDetail[0].target
        result = 1
        inputStructure = inputData.inputStructure
        nRows = inputStructure.nRows
        nColumns = inputStructure.nColumns

        tempBias, addWeightData= bf.updateBackward(learningRate, target, result, value, nRows, nColumns)

        #Comparison
        tempBiasB = learningRate * (target - result)
        addWeightDataB = [0] * (nRows * nColumns)
        for index in range(0, len(addWeightDataB) - 1):
            addWeightDataB[index] = learningRate * value[index] * (target - result)

        self.assertEqual(tempBias, tempBiasB)
        self.assertListEqual(addWeightData, addWeightDataB)

    def testEndOfLearning(self):
        # real data reader from file
        inputData = utilModel.dataInputDumpGenerator("tests", "sample_data/testingPurpose", "inputData_sample.json")
        weightData = inputData.weight
        weightDataPrev = inputData.weight
        similarWeightCount = 0

        status = False

        for iteration in range(20):
            status, similarWeightCount = util.endOfLearning(weightData, weightDataPrev, similarWeightCount)

        self.assertIs(status, True)

    #TODO add training test for whole system
    def testTrainingResult(self):
        pass

    def testWriteTrainingResultToJson(self):
        pathProject, none = os.getcwd().split("/tests")
        mode = 'w'
        nameFileSample = "trainingResult_sample.json"
        pathTrainingResultSample = os.path.join(pathProject, "sample_data/testingPurpose", nameFileSample)
        bias = 0.08
        trainingResultData = [
            0.0,
            0.012,
            -0.036000000000000004,
            0.012,
            -0.036000000000000004,
            0.0,
            0.012,
            0.0,
            0.012,
            0.0,
            0.0,
            0.012,
            0.012,
            0.012,
            0.0,
            0.0,
            0.012,
            0.0,
            0.012,
            0.0,
            -0.036000000000000004,
            0.012,
            0.012,
            0.048,
            0
        ]

        trainingResult = tr.trainingResult()
        trainingResult.pathInputData = pathTrainingResultSample
        trainingResult.bias = bias
        trainingResult.trainingResult = trainingResultData

        listDir = os.listdir(os.path.join(pathProject, "sample_data/testingPurpose"))
        util.writeToJsonFromObject(trainingResult, pathTrainingResultSample, mode)
        result = False

        for value in listDir:
            if value == nameFileSample:
                result = True
        self.assertIs(result, True)

    def testReadConfigFileAll(self):
        pathIni = util.pathGenerator("tests", "configurations", "configTemplate.ini")
        sectionName = 'inputDataValue'
        parser = util.readConfigFileAll(pathIni)
        optionNameOne = "activationFunction"
        optionNameTwo = "weight"

        activationList = ['hardLimit', 'linear', 'exponential', 'sigmoid']
        weightList = ['zero', 'random']

        activationListConfig = parser.get(sectionName, optionNameOne).replace(' ','').split(',')
        weightListConfig = parser.get(sectionName, optionNameTwo).replace(' ','').split(',')

        self.assertListEqual(activationListConfig, activationList)
        self.assertListEqual(weightListConfig, weightList)

    def testReadConfigFileSection(self):
        pathIni = util.pathGenerator("tests", "configurations", "configTemplate.ini")
        sectionName = 'inputDataValue'
        parser = util.readConfigFileSection(pathIni, sectionName)

        activationList = ['hardLimit', 'linear', 'exponential', 'sigmoid']
        weightList = ['zero', 'random']

        activationListConfig = parser[0][1].replace(' ','').split(',')
        weightListConfig = parser[1][1].replace(' ','').split(',')

        self.assertListEqual(activationList, activationListConfig)
        self.assertListEqual(weightList, weightListConfig)

    def testReadConfigFileSectionOption(self):
        pathIni = util.pathGenerator("tests", "configurations", "configTemplate.ini")
        sectionName = 'inputDataValue'
        optionNameOne = "activationFunction"
        optionNameTwo = "weight"

        activationList = ['hardLimit', 'linear', 'exponential', 'sigmoid']
        weightList = ['zero', 'random']

        activationListConfig = util.readConfigFileSectionOption(pathIni, sectionName, optionNameOne)
        weightListConfig = util.readConfigFileSectionOption(pathIni, sectionName, optionNameTwo)

        self.assertListEqual(activationList, activationListConfig)
        self.assertListEqual(weightList, weightListConfig)

if __name__ == '__main__':
    ut.main()


text:
export interface BeforeListen {
  $beforeListen(): void | Promise<any>;
}


text:
package net.schmizz.sshj.transport.kex;

import net.schmizz.sshj.transport.digest.SHA1;

import javax.crypto.spec.DHParameterSpec;
import java.security.GeneralSecurityException;

/**
 * Diffie-Hellman key exchange with SHA-1 and Oakley Group 2 [RFC2409] (1024-bit MODP Group).
 *
 * @see RFC 4253
 *
 * TODO refactor away the (unneeded) class
 * @deprecated Replaced by {@link com.hierynomus.sshj.transport.kex.DHG} with {@link com.hierynomus.sshj.transport.kex.DHGroups}
 */
public class DHG1
        extends AbstractDHG {

    /** Named factory for DHG1 key exchange */
    public static class Factory
            implements net.schmizz.sshj.common.Factory.Named<KeyExchange> {

        @Override
        public KeyExchange create() {
            return new DHG1();
        }

        @Override
        public String getName() {
            return "diffie-hellman-group1-sha1";
        }
    }

    public DHG1() {
        super(new DH(), new SHA1());
    }

    @Override
    protected void initDH(DHBase dh) throws GeneralSecurityException {
        dh.init(new DHParameterSpec(DHGroupData.P1, DHGroupData.G), trans.getConfig().getRandomFactory());
    }
}


text:
worldPing requires a Grafana.net account. Generate a new API key or sign up for free.

<form name="editForm">

				Grafana.net API Key
				<input type="password" class="gf-form-input input-xlarge" ng-model="ctrl.appModel.secureJsonData.apiKey" ng-if="!ctrl.appModel.jsonData.apiKeySet" required>
				<input type="text" class="gf-form-input max-width-12" disabled="disabled" value="complete" ng-if="ctrl.appModel.jsonData.apiKeySet">

				reset

			 worldPing is enabled. Next up: Go to worldPing Home Dashboard

Error

{{ctrl.errorMsg}}

Account Details

			Org Name
			{{ctrl.org.name}}

			Org Slug
			{{ctrl.org.slug}}

			Org ID
			{{ctrl.org.id}}

			Plan
			{{ctrl.org.wpPlan || 'Free'}}

			Est. Checks/Mo
			{{ctrl.org.strChecksPerMonth}}

</form>