text:
<?php

namespace MongoDB\Tests;

use MongoDB\Client;
use MongoDB\Driver\Command;
use MongoDB\Model\DatabaseInfo;

/**
 * Functional tests for the Client class.
 */
class ClientFunctionalTest extends FunctionalTestCase
{
    private $client;

    public function setUp()
    {
        parent::setUp();

        $this->client = new Client($this->getUri());
        $this->client->dropDatabase($this->getDatabaseName());
    }

    public function testDropDatabase()
    {
        $writeResult = $this->manager->executeInsert($this->getNamespace(), array('x' => 1));
        $this->assertEquals(1, $writeResult->getInsertedCount());

        $commandResult = $this->client->dropDatabase($this->getDatabaseName());
        $this->assertCommandSucceeded($commandResult);
        $this->assertCollectionCount($this->getNamespace(), 0);
    }

    public function testListDatabases()
    {
        $writeResult = $this->manager->executeInsert($this->getNamespace(), array('x' => 1));
        $this->assertEquals(1, $writeResult->getInsertedCount());

        $databases = $this->client->listDatabases();

        $this->assertInstanceOf('MongoDB\Model\DatabaseInfoIterator', $databases);

        foreach ($databases as $database) {
            $this->assertInstanceOf('MongoDB\Model\DatabaseInfo', $database);
        }

        $that = $this;
        $this->assertDatabaseExists($this->getDatabaseName(), function(DatabaseInfo $info) use ($that) {
            $that->assertFalse($info->isEmpty());
            $that->assertGreaterThan(0, $info->getSizeOnDisk());
        });
    }

    /**
     * Asserts that a database with the given name exists on the server.
     *
     * An optional $callback may be provided, which should take a DatabaseInfo
     * argument as its first and only parameter. If a DatabaseInfo matching
     * the given name is found, it will be passed to the callback, which may
     * perform additional assertions.
     *
     * @param callable $callback
     */
    private function assertDatabaseExists($databaseName, $callback = null)
    {
        if ($callback !== null && ! is_callable($callback)) {
            throw new InvalidArgumentException('$callback is not a callable');
        }

        $databases = $this->client->listDatabases();

        $foundDatabase = null;

        foreach ($databases as $database) {
            if ($database->getName() === $databaseName) {
                $foundDatabase = $database;
                break;
            }
        }

        $this->assertNotNull($foundDatabase, sprintf('Found %s database on the server', $databaseName));

        if ($callback !== null) {
            call_user_func($callback, $foundDatabase);
        }
    }
}


text:
START_ATF_NAMESPACE
    #pragma pack(push, 8)
    struct CObjectList
    {
        CObjectListVtbl *vfptr;
        _object_list_point m_Head;
        _object_list_point m_Tail;
        int m_nSize;
    public:
        CObjectList();
        void ctor_CObjectList();
        struct CGameObject* CopyItem(unsigned int dwIndex);
        bool DeleteItem(struct _object_list_point* pItem);
        int GetSize();
        void InitList();
        bool PushItem(struct _object_list_point* pItem);
        ~CObjectList();
        void dtor_CObjectList();
    };
    #pragma pack(pop)
END_ATF_NAMESPACE

redpajama_set_name: RedPajamaGithub


text:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <hashtable.h>
#include <hashtable_itr.h>

#include <util/hash.h>
#include <util/io.h>
#include <util/string.h>

#include "symbols.h"

#define INIT_TABLE_SIZE 16

static struct hashtable *symbol_table;

struct symbol {
    const char *name;
    void *addr;
    const char *decl;
};

DEFINE_HASHTABLE_INSERT(insert_symbol, const char, struct symbol);
DEFINE_HASHTABLE_SEARCH(search_symbol, const char, struct symbol);
DEFINE_HASHTABLE_REMOVE(remove_symbol, const char, struct symbol);

void symbols_init(void) {
    symbol_table = create_hashtable(INIT_TABLE_SIZE,
            (unsigned int (*)(void *)) hash_djb2,
            (int (*)(void *, void *)) streq);
}

void add_symbol(const char *name, void *addr, const char *decl) {
    if(!addr) return;
    struct symbol *s;
    if((s = remove_symbol(symbol_table, name))) {
        fprintf(stderr, "Warning: '%s' redeclared as '%s'\n", s->decl, decl);
        free((void *) s->decl);
        free(s);
    }
    s = malloc(sizeof(struct symbol));
    s->name = strdup(name);
    s->addr = addr;
    s->decl = strdup(decl);
    insert_symbol(symbol_table, s->name, s);
}

void delete_symbol(const char *name) {
    struct symbol *s;
    if((s = remove_symbol(symbol_table, name))) {
        free((void *) s->decl);
        free(s);
    }
}

void provide_symbols(TCCState *tccs) {
    if(hashtable_count(symbol_table)) {
        struct hashtable_itr *itr = hashtable_iterator(symbol_table);
        do {
            struct symbol *s = hashtable_iterator_value(itr);
            tcc_add_symbol(tccs, s->name, s->addr);
        } while(hashtable_iterator_advance(itr));
        free(itr);
    }
}

char *symbol_declarations(void) {
    char *decls = strdup("");
    if(hashtable_count(symbol_table)) {
        struct hashtable_itr *itr = hashtable_iterator(symbol_table);
        do {
            struct symbol *s = hashtable_iterator_value(itr);
            asprintfa(&decls, "extern %s;\n", s->decl);
        } while(hashtable_iterator_advance(itr));
        free(itr);
    }
    return decls;
}

const char *symbol_declaration(const char *name) {
    struct symbol *symbol = search_symbol(symbol_table, name);
    if(!symbol)
        return NULL;
    return symbol->decl;
}

void symbols_close(void) {
    if(hashtable_count(symbol_table)) {
        struct hashtable_itr *itr = hashtable_iterator(symbol_table);
        do {
            struct symbol *s = hashtable_iterator_value(itr);
            free((void *) s->decl);
            free(s);
        } while(hashtable_iterator_remove(itr));
        free(itr);
    }
    hashtable_destroy(symbol_table, 0);
}


text:
// Copyright 2014 Software Freedom Conservancy. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Defines common conditions for use with
 * {@link webdriver.WebDriver#wait WebDriver wait}.
 *
 *
Sample usage:
 *

 *   driver.get('http://www.google.com/ncr');
 *
 *   var query = driver.wait(until.elementLocated(By.name('q')));
 *   query.sendKeys('webdriver\n');
 *
 *   driver.wait(until.titleIs('webdriver - Google Search'));
 *

 *
 *
To define a custom condition, simply call WebDriver.wait with a function
 * that will eventually return a truthy-value (neither null, undefined, false,
 * 0, or the empty string):
 *

 *   driver.wait(function() {
 *     return driver.getTitle().then(function(title) {
 *       return title === 'webdriver - Google Search';
 *     });
 *   }, 1000);
 *

 */

goog.provide('webdriver.until');

goog.require('bot.ErrorCode');
goog.require('goog.array');
goog.require('goog.string');

goog.scope(function() {

var until = webdriver.until;

/**
 * Defines a condition to
 * @param {string} message A descriptive error message. Should complete the
 *     sentence "Waiting [...]"
 * @param {function(!webdriver.WebDriver): OUT} fn The condition function to
 *     evaluate on each iteration of the wait loop.
 * @constructor
 * @struct
 * @final
 * @template OUT
 */
until.Condition = function(message, fn) {
  /** @private {string} */
  this.description_ = 'Waiting ' + message;

  /** @type {function(!webdriver.WebDriver): OUT} */
  this.fn = fn;
};

/** @return {string} A description of this condition. */
until.Condition.prototype.description = function() {
  return this.description_;
};

/**
 * Creates a condition that will wait until the input driver is able to switch
 * to the designated frame. The target frame may be specified as:
 *

 *
A numeric index into {@code window.frames} for the currently selected
 *       frame.
 *
A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME
 *       element on the current page.
 *
A locator which may be used to first locate a FRAME or IFRAME on the
 *       current page before attempting to switch to it.
 *

 *
 *
Upon successful resolution of this condition, the driver will be left
 * focused on the new frame.
 *
 * @param {!(number|webdriver.WebElement|
 *           webdriver.Locator|webdriver.By.Hash|
 *           function(!webdriver.WebDriver): !webdriver.WebElement)} frame
 *     The frame identifier.
 * @return {!until.Condition.<boolean>} A new condition.
 */
until.ableToSwitchToFrame = function(frame) {
  var condition;
  if (goog.isNumber(frame) || frame instanceof webdriver.WebElement) {
    condition = attemptToSwitchFrames;
  } else {
    condition = function(driver) {
      var locator =
          /** @type {!(webdriver.Locator|webdriver.By.Hash|Function)} */(frame);
      return driver.findElements(locator).then(function(els) {
        if (els.length) {
          return attemptToSwitchFrames(driver, els[0]);
        }
      });
    };
  }

  return new until.Condition('to be able to switch to frame', condition);

  function attemptToSwitchFrames(driver, frame) {
    return driver.switchTo().frame(frame).then(
        function() { return true; },
        function(e) {
          if (e && e.code !== bot.ErrorCode.NO_SUCH_FRAME) {
            throw e;
          }
        });
  }
};

/**
 * Creates a condition that waits for an alert to be opened. Upon success, the
 * returned promise will be fulfilled with the handle for the opened alert.
 *
 * @return {!until.Condition.<!webdriver.Alert>} The new condition.
 */
until.alertIsPresent = function() {
  return new until.Condition('for alert to be present', function(driver) {
    return driver.switchTo().alert().thenCatch(function(e) {
      if (e && e.code !== bot.ErrorCode.NO_SUCH_ALERT) {
        throw e;
      }
    });
  });
};

/**
 * Creates a condition that will wait for the current page's title to match the
 * given value.
 *
 * @param {string} title The expected page title.
 * @return {!until.Condition.<boolean>} The new condition.
 */
until.titleIs = function(title) {
  return new until.Condition(
      'for title to be ' + goog.string.quote(title),
      function(driver) {
        return driver.getTitle().then(function(t) {
          return t === title;
        });
      });
};

/**
 * Creates a condition that will wait for the current page's title to contain
 * the given substring.
 *
 * @param {string} substr The substring that should be present in the page
 *     title.
 * @return {!until.Condition.<boolean>} The new condition.
 */
until.titleContains = function(substr) {
  return new until.Condition(
      'for title to contain ' + goog.string.quote(substr),
      function(driver) {
        return driver.getTitle().then(function(title) {
          return title.indexOf(substr) !== -1;
        });
      });
};

/**
 * Creates a condition that will wait for the current page's title to match the
 * given regular expression.
 *
 * @param {!RegExp} regex The regular expression to test against.
 * @return {!until.Condition.<boolean>} The new condition.
 */
until.titleMatches = function(regex) {
  return new until.Condition('for title to match ' + regex, function(driver) {
    return driver.getTitle().then(function(title) {
      return regex.test(title);
    });
  });
};

/**
 * Creates a condition that will loop until an element is
 * {@link webdriver.WebDriver#findElement found} with the given locator.
 *
 * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator
 *     to use.
 * @return {!until.Condition.<!webdriver.WebElement>} The new condition.
 */
until.elementLocated = function(locator) {
  var locatorStr = goog.isFunction(locator) ? 'function()' : locator + '';
  return new until.Condition('element to be located by ' + locatorStr,
      function(driver) {
        return driver.findElements(locator).then(function(elements) {
          return elements[0];
        });
      });
};

/**
 * Creates a condition that will loop until at least one element is
 * {@link webdriver.WebDriver#findElement found} with the given locator.
 *
 * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator
 *     to use.
 * @return {!until.Condition.<!Array.<!webdriver.WebElement>>} The new
 *     condition.
 */
until.elementsLocated = function(locator) {
  var locatorStr = goog.isFunction(locator) ? 'function()' : locator + '';
  return new until.Condition(
      'at least one element to be located by ' + locatorStr,
      function(driver) {
        return driver.findElements(locator).then(function(elements) {
          return elements.length > 0 ? elements : null;
        });
      });
};

/**
 * Creates a condition that will wait for the given element to become stale. An
 * element is considered stale once it is removed from the DOM, or a new page
 * has loaded.
 *
 * @param {!webdriver.WebElement} element The element that should become stale.
 * @return {!until.Condition.<boolean>} The new condition.
 */
until.stalenessOf = function(element) {
  return new until.Condition('element to become stale', function() {
    return element.getTagName().then(
        function() { return false; },
        function(e) {
          if (e.code === bot.ErrorCode.STALE_ELEMENT_REFERENCE) {
            return true;
          }
          throw e;
        });
  });
};

/**
 * Creates a condition that will wait for the given element to become visible.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isDisplayed
 */
until.elementIsVisible = function(element) {
  return new until.Condition('until element is visible', function() {
    return element.isDisplayed();
  });
};

/**
 * Creates a condition that will wait for the given element to be in the DOM,
 * yet not visible to the user.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isDisplayed
 */
until.elementIsNotVisible = function(element) {
  return new until.Condition('until element is not visible', function() {
    return element.isDisplayed().then(function(v) {
      return !v;
    });
  });
};

/**
 * Creates a condition that will wait for the given element to be enabled.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isEnabled
 */
until.elementIsEnabled = function(element) {
  return new until.Condition('until element is enabled', function() {
    return element.isEnabled();
  });
};

/**
 * Creates a condition that will wait for the given element to be disabled.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isEnabled
 */
until.elementIsDisabled = function(element) {
  return new until.Condition('until element is disabled', function() {
    return element.isEnabled().then(function(v) {
      return !v;
    });
  });
};

/**
 * Creates a condition that will wait for the given element to be selected.
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isSelected
 */
until.elementIsSelected = function(element) {
  return new until.Condition('until element is selected', function() {
    return element.isSelected();
  });
};

/**
 * Creates a condition that will wait for the given element to be deselected.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#isSelected
 */
until.elementIsNotSelected = function(element) {
  return new until.Condition('until element is not selected', function() {
    return element.isSelected().then(function(v) {
      return !v;
    });
  });
};

/**
 * Creates a condition that will wait for the given element's
 * {@link webdriver.WebDriver#getText visible text} to match the given
 * {@code text} exactly.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @param {string} text The expected text.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#getText
 */
until.elementTextIs = function(element, text) {
  return new until.Condition('until element text is', function() {
    return element.getText().then(function(t) {
      return t === text;
    });
  });
};

/**
 * Creates a condition that will wait for the given element's
 * {@link webdriver.WebDriver#getText visible text} to contain the given
 * substring.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @param {string} substr The substring to search for.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#getText
 */
until.elementTextContains = function(element, substr) {
  return new until.Condition('until element text contains', function() {
    return element.getText().then(function(t) {
      return t.indexOf(substr) != -1;
    });
  });
};

/**
 * Creates a condition that will wait for the given element's
 * {@link webdriver.WebDriver#getText visible text} to match a regular
 * expression.
 *
 * @param {!webdriver.WebElement} element The element to test.
 * @param {!RegExp} regex The regular expression to test against.
 * @return {!until.Condition.<boolean>} The new condition.
 * @see webdriver.WebDriver#getText
 */
until.elementTextMatches = function(element, regex) {
  return new until.Condition('until element text matches', function() {
    return element.getText().then(function(t) {
      return regex.test(t);
    });
  });
};
});  // goog.scope


text:
archive: tag
layout: archive
permalink: /tag/Apple/
tag: Apple
title: Archive for Apple

---


text:
package vgrechka.phizdetsidea.phizdets.inspections;

import com.intellij.codeInspection.LocalInspectionToolSession;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
import com.intellij.openapi.util.Key;
import com.intellij.psi.PsiElementVisitor;
import vgrechka.phizdetsidea.phizdets.PyBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

/**
 * @author oleg
 */
public class PyUnusedLocalInspection extends PyInspection {
  private static Key<PyUnusedLocalInspectionVisitor> KEY = Key.create("PyUnusedLocal.Visitor");

  public boolean ignoreTupleUnpacking = true;
  public boolean ignoreLambdaParameters = true;
  public boolean ignoreLoopIterationVariables = true;

  @NotNull
  @Nls
  public String getDisplayName() {
    return PyBundle.message("INSP.NAME.unused");
  }

  @NotNull
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder,
                                        final boolean isOnTheFly,
                                        @NotNull LocalInspectionToolSession session) {
    final PyUnusedLocalInspectionVisitor visitor = new PyUnusedLocalInspectionVisitor(holder,
                                                                                session,
                                                                                ignoreTupleUnpacking,
                                                                                ignoreLambdaParameters,
                                                                                ignoreLoopIterationVariables);
    // buildVisitor() will be called on injected files in the same session - don't overwrite if we already have one
    final PyUnusedLocalInspectionVisitor existingVisitor = session.getUserData(KEY);
    if (existingVisitor == null) {
      session.putUserData(KEY, visitor);
    }
    return visitor;
  }

  @Override
  public void inspectionFinished(@NotNull LocalInspectionToolSession session, @NotNull ProblemsHolder holder) {
    final PyUnusedLocalInspectionVisitor visitor = session.getUserData(KEY);
    if (visitor != null) {
      visitor.registerProblems();
      session.putUserData(KEY, null);
    }
  }

  @Override
  public JComponent createOptionsPanel() {
    MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this);
    panel.addCheckbox("Ignore variables used in tuple unpacking", "ignoreTupleUnpacking");
    panel.addCheckbox("Ignore lambda parameters", "ignoreLambdaParameters");
    panel.addCheckbox("Ignore range iteration variables", "ignoreLoopIterationVariables");
    return panel;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
    <mapping directory="$PROJECT_DIR$/DataProductionTools/libs/graphhopper" vcs="Git" />
  </component>
</project>


text:
@interface UIButton (PSKit)

+ (UIButton *)buttonWithFrame:(CGRect)frame andStyle:(NSString *)style target:(id)target action:(SEL)action;
+ (UIButton *)buttonWithStyle:(NSString *)style;

@end


text:
package endpoints

import (
	"context"

	"github.com/giantswarm/microerror"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"github.com/giantswarm/aws-operator/v14/service/controller/key"
)

func (r *Resource) GetCurrentState(ctx context.Context, obj interface{}) (interface{}, error) {
	cr, err := key.ToCluster(ctx, obj)
	if err != nil {
		return nil, microerror.Mask(err)
	}

	var endpoints *corev1.Endpoints
	{
		r.logger.Debugf(ctx, "finding endpoint")

		manifest, err := r.k8sClient.CoreV1().Endpoints(key.ClusterNamespace(cr)).Get(ctx, masterEndpointsName, metav1.GetOptions{})
		if apierrors.IsNotFound(err) {
			r.logger.Debugf(ctx, "did not find endpoint")
		} else if err != nil {
			return nil, microerror.Mask(err)
		} else {
			r.logger.Debugf(ctx, "found endpoint")
			endpoints = manifest
		}
	}

	return endpoints, nil
}


text:
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:fitsSystemWindows="true"
    android:layout_marginTop="24dp"
    android:id="@+id/tool_bar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/primary"
    app:titleTextColor="@android:color/white"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:contentInsetStart="8dp"
    app:contentInsetEnd="4dp"
    app:layout_scrollFlags="scroll|enterAlwaysCollapsed">
</android.support.v7.widget.Toolbar>


text:
title: M/01
fullname: M/01 Desert version
nickname: T/99
family: flecktarn
terrain: desert
country: dk
image: m01.jpg
cover: m01-cover.jpg
---
It is a 3 colour camouflage pattern, similar in design to the Danish M/84 pattern. It is considered to be the desert counterpart of M/84, and consists of different colors better suited for arid climates. The uniform contains splotches of earthy red and dark green on a sand-coloured background.

History
-------
The first version of T/99 was trialled in 1999 and issued in 2000 to Danish personnel attached to the Multinational High Readiness Standby Brigade for United Nations Operations. These service personnel were dispatched to Africa under the United Nations banner to enforce and uphold a ceasefire line between the nations of Eritrea and Ethiopia, as part of the United Nations mission in these two countries.

Danish soldier (on right) wearing a T/99 patterned uniform in Kabul, Afghanistan.
In 2001, the pattern was further researched and improved upon, with a new variant coming into existence later that same year. The new variant, known as Kampuniform M/01 Ørken (desert) was first seen on members of the Danish ISAF contingent. The desert camouflage uniform is issued in relatively small quantities, and only to troops actually deploying to Afghanistan.

While T/99 is rumoured to be a modified variant of German Desert Flecktarn (Tropentarn) camouflage, it is actually a recoloured variant of the original Danish M84 Pletsløring (spot camouflage) pattern, in which earthy red has replaced black, dark green has replaced light green, and the sand colour has replaced the olive green of the original M/84.

Sources
-------
[Wikipedia](https://en.wikipedia.org/wiki/M84_camouflage_pattern)
[Wikipedia](https://en.wikipedia.org/wiki/T99_(camouflage))


text:
import { RowNode } from "../../entities/rowNode";
import { IRowNodeStage, StageExecuteParams } from "../../interfaces/iRowNodeStage";
export declare class FlattenStage implements IRowNodeStage {
    private gridOptionsWrapper;
    private selectionController;
    private eventService;
    private context;
    private columnController;
    execute(params: StageExecuteParams): RowNode[];
    private resetRowTops(rowNode);
    private recursivelyAddToRowsToDisplay(rowsToFlatten, result, nextRowTop, skipLeafNodes, uiLevel);
    private addRowNodeToRowsToDisplay(rowNode, result, nextRowTop, uiLevel);
    private ensureFooterNodeExists(groupNode);
    private createDetailNode(masterNode);
}


text:
// Copyright (C) 2014 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 12.2.8
description: Template caching using distinct expressions
info: >
    Previously-created template objects should be retrieved from the internal
    template registry when their source is identical but their expressions
    evaluate to different values.
---*/
function tag(templateObject) {
  previousObject = templateObject;
}
var a = 1;
var b = 2;
var firstObject = null;
var previousObject = null;

tag`head${a}tail`;
firstObject = previousObject;
assert(firstObject !== null);
previousObject = null;

tag`head${b}tail`;
assert.sameValue(previousObject, firstObject);


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#include "AvfMediaPrivatePCH.h"
#include "IMediaModule.h"
#include "IMediaPlayerFactory.h"
#include "ModuleInterface.h"
#include "ModuleManager.h"

DEFINE_LOG_CATEGORY(LogAvfMedia);

#define LOCTEXT_NAMESPACE "FAvfMediaModule"

/**
 * Implements the AVFMedia module.
 */
class FAvfMediaModule
	: public IModuleInterface
	, public IMediaPlayerFactory
{
public:

	/** Default constructor. */
	FAvfMediaModule()
		: Initialized(false)
	{ }

public:

	// IModuleInterface interface

	virtual void StartupModule() override
	{
		// load required libraries
		IMediaModule* MediaModule = FModuleManager::LoadModulePtr<IMediaModule>("Media");

		if (MediaModule == nullptr)
		{
			UE_LOG(LogAvfMedia, Warning, TEXT("Failed to load Media module"));

			return;
		}

		// initialize supported media formats
		SupportedFileTypes.Add(TEXT("avi"), LOCTEXT("FormatAvi", "Audio Video Interleave File"));
		SupportedFileTypes.Add(TEXT("m4v"), LOCTEXT("FormatM4v", "Apple MPEG-4 Video"));
		SupportedFileTypes.Add(TEXT("mov"), LOCTEXT("FormatMov", "Apple QuickTime Movie"));
		SupportedFileTypes.Add(TEXT("mp4"), LOCTEXT("FormatMp4", "MPEG-4 Movie"));

		// register factory
		MediaModule->RegisterPlayerFactory(*this);

		Initialized = true;
	}

	virtual void ShutdownModule() override
	{
		if (!Initialized)
		{
			return;
		}

		Initialized = false;

		// unregister video player factory
		IMediaModule* MediaModule = FModuleManager::GetModulePtr<IMediaModule>("Media");

		if (MediaModule != nullptr)

		{
			MediaModule->UnregisterPlayerFactory(*this);
		}
	}

public:

	// IMediaPlayerFactory interface

	virtual TSharedPtr<IMediaPlayer> CreatePlayer() override
	{
		if (Initialized)
		{
			return MakeShareable(new FAvfMediaPlayer());
		}

		return nullptr;
	}

	virtual const FMediaFileTypes& GetSupportedFileTypes() const override
	{
		return SupportedFileTypes;
	}

	virtual bool SupportsUrl(const FString& Url) const override
	{
		return SupportedFileTypes.Contains(FPaths::GetExtension(Url));
	}

protected:

	/**
	 * Loads all required Windows libraries.
	 *
	 * @return true on success, false otherwise.
	 */
	bool LoadRequiredLibraries()
    {
		return true;
	}

private:

	/** Whether the module has been initialized. */
	bool Initialized;

	/** The collection of supported media file types. */
	FMediaFileTypes SupportedFileTypes;
};

IMPLEMENT_MODULE(FAvfMediaModule, AvfMedia);

#undef LOCTEXT_NAMESPACE


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.2">
<title>Interceptors and events</title>
<link rel="stylesheet" href="./css/hibernate.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.min.css">

Interceptors and events

It is useful for the application to react to certain events that occur inside Hibernate.
This allows for the implementation of generic functionality and the extension of Hibernate functionality.

Interceptors

The org.hibernate.Interceptor interface provides callbacks from the session to the application,
allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.

One possible use for this is to track auditing information.
The following example shows an Interceptor implementation that automatically logs when an entity is updated.

public static class LoggingInterceptor extends EmptyInterceptor {
    @Override
    public boolean onFlushDirty(
        Object entity,
        Serializable id,
        Object[] currentState,
        Object[] previousState,
        String[] propertyNames,
        Type[] types) {
            LOGGER.debugv( "Entity {0}#{1} changed from {2} to {3}",
                entity.getClass().getSimpleName(),
                id,
                Arrays.toString( previousState ),
                Arrays.toString( currentState )
            );
            return super.onFlushDirty( entity, id, currentState,
                previousState, propertyNames, types
        );
    }
}

You can either implement Interceptor directly or extend org.hibernate.EmptyInterceptor.

An Interceptor can be either Session-scoped or SessionFactory-scoped.

A Session-scoped interceptor is specified when a session is opened.

SessionFactory sessionFactory = entityManagerFactory.unwrap( SessionFactory.class );
Session session = sessionFactory
    .withOptions()
    .interceptor(new LoggingInterceptor() )
    .openSession();

Customer customer = session.get( Customer.class, customerId );
customer.setName( "Mr. John Doe" );
//Entity Customer#1 changed from [John Doe, 0] to [Mr. John Doe, 0]
session.flush();

A SessionFactory-scoped interceptor is registered with the Configuration object prior to building the SessionFactory.
Unless a session is opened explicitly specifying the interceptor to use, the SessionFactory-scoped interceptor will be applied to all sessions opened from that SessionFactory.
SessionFactory-scoped interceptors must be thread safe.
Ensure that you do not store session-specific states since multiple sessions will use this interceptor potentially concurrently.

SessionFactory sessionFactory = new MetadataSources( new StandardServiceRegistryBuilder().build() )
    .addAnnotatedClass( Customer.class )
    .getMetadataBuilder()
    .build()
    .getSessionFactoryBuilder()
    .applyInterceptor( new LoggingInterceptor() )
    .build();

Native Event system

If you have to react to particular events in the persistence layer, you can also use the Hibernate event architecture.
The event system can be used in place of or in addition to interceptors.

Many methods of the Session interface correlate to an event type.
The full range of defined event types is declared as enum values on org.hibernate.event.spi.EventType.
When a request is made of one of these methods, the Session generates an appropriate event and passes it to the configured event listener(s) for that type.

Applications are free to implement a customization of one of the listener interfaces (i.e., the LoadEvent is processed by the registered implementation of the LoadEventListener interface), in which case their implementation would
be responsible for processing any load() requests made of the Session.

The listeners should be considered stateless; they are shared between requests, and should not save any state as instance variables.

A custom listener implements the appropriate interface for the event it wants to process and/or extend one of the convenience base classes
(or even the default event listeners used by Hibernate out-of-the-box as these are declared non-final for this purpose).
Here is an example of a custom load event listener:

Example 1. Custom LoadListener example

EntityManagerFactory entityManagerFactory = entityManagerFactory();
SessionFactoryImplementor sessionFactory = entityManagerFactory.unwrap( SessionFactoryImplementor.class );
sessionFactory
    .getServiceRegistry()
    .getService( EventListenerRegistry.class )
    .prependListeners( EventType.LOAD, new SecuredLoadEntityListener() );

Customer customer = entityManager.find( Customer.class, customerId );

Hibernate declarative security

Usually, declarative security in Hibernate applications is managed in a session facade layer.
Hibernate allows certain actions to be authorized via JACC and JAAS.
This is an optional functionality that is built on top of the event architecture.

First, you must configure the appropriate event listeners, to enable the use of JACC authorization.
Again, see Event Listener Registration for the details.

Below is an example of an appropriate org.hibernate.integrator.spi.Integrator implementation for this purpose.

Example 2. JACC listener registration example

public static class JaccIntegrator implements ServiceContributingIntegrator {

    private static final Logger log = Logger.getLogger( JaccIntegrator.class );

    private static final DuplicationStrategy DUPLICATION_STRATEGY =
            new DuplicationStrategy() {
        @Override
        public boolean areMatch(Object listener, Object original) {
            return listener.getClass().equals( original.getClass() ) &&
                    JaccSecurityListener.class.isInstance( original );
        }

        @Override
        public Action getAction() {
            return Action.KEEP_ORIGINAL;
        }
    };

    @Override
    public void prepareServices(
            StandardServiceRegistryBuilder serviceRegistryBuilder) {
        boolean isSecurityEnabled = serviceRegistryBuilder
                .getSettings().containsKey( AvailableSettings.JACC_ENABLED );
        final JaccService jaccService = isSecurityEnabled ?
                new StandardJaccServiceImpl() : new DisabledJaccServiceImpl();
        serviceRegistryBuilder.addService( JaccService.class, jaccService );
    }

    @Override
    public void integrate(
            Metadata metadata,
            SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        doIntegration(
                serviceRegistry
                        .getService( ConfigurationService.class ).getSettings(),
                // pass no permissions here, because atm actually injecting the
                // permissions into the JaccService is handled on SessionFactoryImpl via
                // the org.hibernate.boot.cfgxml.spi.CfgXmlAccessService
                null,
                serviceRegistry
        );
    }

    private void doIntegration(
            Map properties,
            JaccPermissionDeclarations permissionDeclarations,
            SessionFactoryServiceRegistry serviceRegistry) {
        boolean isSecurityEnabled = properties
                .containsKey( AvailableSettings.JACC_ENABLED );
        if ( ! isSecurityEnabled ) {
            log.debug( "Skipping JACC integration as it was not enabled" );
            return;
        }

        final String contextId = (String) properties
                .get( AvailableSettings.JACC_CONTEXT_ID );
        if ( contextId == null ) {
            throw new IntegrationException( "JACC context id must be specified" );
        }

        final JaccService jaccService = serviceRegistry
                .getService( JaccService.class );
        if ( jaccService == null ) {
            throw new IntegrationException( "JaccService was not set up" );
        }

        if ( permissionDeclarations != null ) {
            for ( GrantedPermission declaration : permissionDeclarations
                    .getPermissionDeclarations() ) {
                jaccService.addPermission( declaration );
            }
        }

        final EventListenerRegistry eventListenerRegistry =
                serviceRegistry.getService( EventListenerRegistry.class );
        eventListenerRegistry.addDuplicationStrategy( DUPLICATION_STRATEGY );

        eventListenerRegistry.prependListeners(
                EventType.PRE_DELETE, new JaccPreDeleteEventListener() );
        eventListenerRegistry.prependListeners(
                EventType.PRE_INSERT, new JaccPreInsertEventListener() );
        eventListenerRegistry.prependListeners(
                EventType.PRE_UPDATE, new JaccPreUpdateEventListener() );
        eventListenerRegistry.prependListeners(
                EventType.PRE_LOAD, new JaccPreLoadEventListener() );
    }

    @Override
    public void disintegrate(SessionFactoryImplementor sessionFactory,
                             SessionFactoryServiceRegistry serviceRegistry) {
        // nothing to do
    }
}

You must also decide how to configure your JACC provider. Consult your JACC provider documentation.

JPA Callbacks

JPA also defines a more limited set of callbacks through annotations.

Table 1. Callback annotations

<colgroup>
<col style="width: %;">
<col style="width: %;">
</colgroup>

Type
Description

@PrePersist

Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.

@PreRemove

Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.

@PostPersist

Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.

@PostRemove

Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.

@PreUpdate

Executed before the database UPDATE operation.

@PostUpdate

Executed after the database UPDATE operation.

@PostLoad

Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.

There are two available approaches defined for specifying callback handling:

The first approach is to annotate methods on the entity itself to receive notification of particular entity life cycle event(s).

The second is to use a separate entity listener class.
An entity listener is a stateless class with a no-arg constructor.
The callback annotations are placed on a method of this class instead of the entity class.
The entity listener class is then associated with the entity using the javax.persistence.EntityListeners annotation

Example 3. Example of specifying JPA callbacks

@Entity
@EntityListeners( LastUpdateListener.class )
public static class Person {

    @Id
    private Long id;

    private String name;

    private Date dateOfBirth;

    @Transient
    private long age;

    private Date lastUpdate;

    public void setLastUpdate(Date lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    /**
     * Set the transient property at load time based on a calculation.
     * Note that a native Hibernate formula mapping is better for this purpose.
     */
    @PostLoad
    public void calculateAge() {
        age = ChronoUnit.YEARS.between( LocalDateTime.ofInstant(
                Instant.ofEpochMilli( dateOfBirth.getTime()), ZoneOffset.UTC),
            LocalDateTime.now()
        );
    }
}

public static class LastUpdateListener {

    @PreUpdate
    @PrePersist
    public void setLastUpdate( Person p ) {
        p.setLastUpdate( new Date() );
    }
}

These approaches can be mixed, meaning you can use both together.

Regardless of whether the callback method is defined on the entity or on an entity listener, it must have a void-return signature.
The name of the method is irrelevant as it is the placement of the callback annotations that makes the method a callback.
In the case of callback methods defined on the entity class, the method must additionally have a no-argument signature.
For callback methods defined on an entity listener class, the method must have a single argument signature; the type of that argument can be either java.lang.Object (to facilitate attachment to multiple entities) or the specific entity type.

A callback method can throw a RuntimeException.
If the callback method does throw a RuntimeException, then the current transaction, if any, must be rolled back.

A callback method must not invoke EntityManager or Query methods!

It is possible that multiple callback methods are defined for a particular lifecycle event.
When that is the case, the defined order of execution is well defined by the JPA spec (specifically section 3.5.4):

Any default listeners associated with the entity are invoked first, in the order they were specified in the XML. See the javax.persistence.ExcludeDefaultListeners annotation.

Next, entity listener class callbacks associated with the entity hierarchy are invoked, in the order they are defined in the EntityListeners.
If multiple classes in the entity hierarchy define entity listeners, the listeners defined for a superclass are invoked before the listeners defined for its subclasses.
See the `javax.persistence.ExcludeSuperclassListener`s annotation.

Lastly, callback methods defined on the entity hierarchy are invoked.
If a callback type is annotated on both an entity and one or more of its superclasses without method overriding, both would be called, the most general superclass first.
An entity class is also allowed to override a callback method defined in a superclass in which case the super callback would not get invoked; the overriding method would get invoked provided it is annotated.

Last updated 2017-01-19 00:14:28 EST


text:
#ifndef _VK_DEVICE_H_
#define _VK_DEVICE_H_

#include <gst/gst.h>
#include "vk.h"

G_BEGIN_DECLS

#define GST_TYPE_VULKAN_DEVICE         (gst_vulkan_device_get_type())
#define GST_VULKAN_DEVICE(o)           (G_TYPE_CHECK_INSTANCE_CAST((o), GST_TYPE_VULKAN_DEVICE, GstVulkanDevice))
#define GST_VULKAN_DEVICE_CLASS(k)     (G_TYPE_CHECK_CLASS_CAST((k), GST_TYPE_VULKAN_DEVICE, GstVulkanDeviceClass))
#define GST_IS_VULKAN_DEVICE(o)        (G_TYPE_CHECK_INSTANCE_TYPE((o), GST_TYPE_VULKAN_DEVICE))
#define GST_IS_VULKAN_DEVICE_CLASS(k)  (G_TYPE_CHECK_CLASS_TYPE((k), GST_TYPE_VULKAN_DEVICE))
#define GST_VULKAN_DEVICE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS((o), GST_TYPE_VULKAN_DEVICE, GstVulkanDeviceClass))
GType gst_vulkan_device_get_type       (void);

#define GST_VULKAN_DEVICE_CONTEXT_TYPE_STR "gst.vulkan.device"

typedef gboolean (*GstVulkanDeviceForEachQueueFunc) (GstVulkanDevice * device, GstVulkanQueue * queue, gpointer user_data);

struct _GstVulkanDevice
{
  GstObject parent;

  GstVulkanInstance *instance;

  guint device_index;
  VkDevice device; /* hides a pointer */
  VkPhysicalDeviceProperties gpu_props;
  VkPhysicalDeviceFeatures gpu_features;
  VkPhysicalDeviceMemoryProperties memory_properties;

  VkQueueFamilyProperties *queue_family_props;
  guint32 n_queue_families;

  guint32 queue_family_id;
  guint32 n_queues;

  VkCommandPool cmd_pool;

  GstVulkanDevicePrivate *priv;
};

struct _GstVulkanDeviceClass
{
  GstObjectClass parent_class;
};

GstVulkanDevice *   gst_vulkan_device_new                   (GstVulkanInstance * instance);
GstVulkanInstance * gst_vulkan_device_get_instance           (GstVulkanDevice * device);
gboolean            gst_vulkan_device_open                  (GstVulkanDevice * device,
                                                             GError ** error);

gpointer            gst_vulkan_device_get_proc_address      (GstVulkanDevice * device,
                                                             const gchar * name);
void                gst_vulkan_device_foreach_queue         (GstVulkanDevice * device,
                                                             GstVulkanDeviceForEachQueueFunc func,
                                                             gpointer user_data);
GstVulkanQueue *    gst_vulkan_device_get_queue             (GstVulkanDevice * device,
                                                             guint32 queue_family,
                                                             guint32 queue_i);
VkPhysicalDevice    gst_vulkan_device_get_physical_device   (GstVulkanDevice * device);
gboolean            gst_vulkan_device_create_cmd_buffer     (GstVulkanDevice * device,
                                                             VkCommandBuffer * cmd,
                                                             GError ** error);

void                gst_context_set_vulkan_device           (GstContext * context,
                                                             GstVulkanDevice * device);
gboolean            gst_context_get_vulkan_device           (GstContext * context,
                                                             GstVulkanDevice ** device);
gboolean            gst_vulkan_device_handle_context_query  (GstElement * element,
                                                             GstQuery * query,
                                                             GstVulkanDevice ** device);
gboolean            gst_vulkan_device_run_context_query     (GstElement * element,
                                                             GstVulkanDevice ** device);

G_END_DECLS

#endif /* _VK_DEVICE_H_ */


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/autofill_assistant/browser/actions/js_flow_action.h"
#include "base/base64.h"
#include "base/json/json_writer.h"
#include "base/metrics/field_trial.h"
#include "components/autofill_assistant/browser/actions/action_delegate.h"
#include "components/autofill_assistant/browser/js_flow_executor_impl.h"
#include "components/autofill_assistant/browser/js_flow_util.h"
#include "components/autofill_assistant/browser/protocol_utils.h"

namespace autofill_assistant {

namespace {

// When starting a JS flow action, a synthetic field trial is recorded. This is
// used to allow tracking stability metrics as we start using this new action.
// Note there is no control group - this is purely for stability tracking.
const char kJsFlowActionSyntheticFieldTrialName[] =
    "AutofillAssistantJsFlowAction";
const char kJsFlowActionEnabledGroup[] = "Enabled";

}  // namespace

JsFlowAction::JsFlowAction(ActionDelegate* delegate, const ActionProto& proto)
    : Action(delegate, proto),
      js_flow_executor_(std::make_unique<JsFlowExecutorImpl>(
          /* delegate= */ this,
          delegate->GetJsFlowDevtoolsWrapper())) {
  DCHECK(proto_.has_js_flow());
}

JsFlowAction::JsFlowAction(ActionDelegate* delegate,
                           const ActionProto& proto,
                           std::unique_ptr<JsFlowExecutor> js_flow_executor)
    : Action(delegate, proto), js_flow_executor_(std::move(js_flow_executor)) {
  DCHECK(proto_.has_js_flow());
}

JsFlowAction::~JsFlowAction() = default;

Action::ActionData& JsFlowAction::GetActionData() {
  if (!current_native_action_) {
    return Action::GetActionData();
  }
  return current_native_action_->GetActionData();
}

void JsFlowAction::RunNativeAction(
    int action_id,
    const std::string& action,
    base::OnceCallback<void(const ClientStatus& result_status,
                            std::unique_ptr<base::Value> result_value)>
        finished_callback) {
  DCHECK(!current_native_action_) << "Must not call RunNativeAction while "
                                     "already executing a native action";
  std::string error_message;
  absl::optional<ActionProto> action_proto =
      ProtocolUtils::ParseFromString(action_id, action, &error_message);
  if (!action_proto) {
    VLOG(1) << error_message;
    std::move(finished_callback).Run(ClientStatus(INVALID_ACTION), nullptr);
    return;
  }

  if (action_proto->action_info_case() ==
      ActionProto::ActionInfoCase::kJsFlow) {
    LOG(ERROR) << "Nested JS flow actions are not allowed!";
    std::move(finished_callback).Run(ClientStatus(INVALID_ACTION), nullptr);
    return;
  }

  current_native_action_ =
      ProtocolUtils::CreateAction(delegate_, *action_proto);
  VLOG(2) << "Running native action: " << action_proto->action_info_case();
  current_native_action_->ProcessAction(base::BindOnce(
      &JsFlowAction::OnNativeActionFinished, weak_ptr_factory_.GetWeakPtr(),
      std::move(finished_callback)));
}

void JsFlowAction::OnNativeActionFinished(
    base::OnceCallback<void(const ClientStatus& result_status,
                            std::unique_ptr<base::Value> result_value)>
        finished_callback,
    std::unique_ptr<ProcessedActionProto> processed_action) {
  // Intentionally left empty to make output more readable in combination with
  // the start message above.
  VLOG(2) << "                       " << processed_action->status();

  current_native_action_.reset();

  delegate_->MaybeSetPreviousAction(*processed_action);

  std::move(finished_callback)
      .Run(ClientStatus(processed_action->status(),
                        processed_action->status_details()),
           js_flow_util::NativeActionResultToResultValue(*processed_action));
}

void JsFlowAction::InternalProcessAction(ProcessActionCallback callback) {
  base::FieldTrialList::CreateFieldTrial(kJsFlowActionSyntheticFieldTrialName,
                                         kJsFlowActionEnabledGroup);

  js_flow_executor_->Start(
      proto_.js_flow().js_flow(),
      base::BindOnce(&JsFlowAction::OnFlowFinished,
                     weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}

void JsFlowAction::OnFlowFinished(ProcessActionCallback callback,
                                  const ClientStatus& status,
                                  std::unique_ptr<base::Value> return_value) {
  // Since we can not know in advance how many native actions need to be run
  // we will create a dangling promise. By destroying the flow executor we make
  // sure that these will not be executed.
  js_flow_executor_.reset(nullptr);

  UpdateProcessedAction(status);

  // If the flow returned a value, we extract the status and possibly a flow
  // return value from that, and the overall action result will be whatever the
  // flow returned. Flows that don't return a value are assumed to have
  // succeeded. See js_flow_util::ExtractJsFlowActionReturnValue for details.
  if (return_value) {
    std::unique_ptr<base::Value> out_return_value;
    UpdateProcessedAction(js_flow_util::ExtractJsFlowActionReturnValue(
        *return_value, out_return_value));
    if (out_return_value) {
      base::JSONWriter::Write(*out_return_value,
                              processed_action_proto_->mutable_js_flow_result()
                                  ->mutable_result_json());
    }
  }

  // Since JS flows have the potential to be quite big, we remove them from the
  // action response. The backend has access to the full script anyway.
  processed_action_proto_->mutable_action()->mutable_js_flow()->clear_js_flow();

  std::move(callback).Run(std::move(processed_action_proto_));
}

}  // namespace autofill_assistant


text:
# trunc10

> Round a numeric value to the nearest power of 10 toward zero.

## Usage

```javascript
var trunc10 = require( '@stdlib/math/base/special/trunc10' );
```

#### trunc10( x )

Rounds a `numeric` value to the nearest power of 10 toward zero.

```javascript
var v = trunc10( -4.2 );
// returns -1.0

v = trunc10( -4.5 );
// returns -1.0

v = trunc10( -4.6 );
// returns -1.0

v = trunc10( 9.99999 );
// returns 1.0

v = trunc10( 9.5 );
// returns 1.0

v = trunc10( 13.0 );
// returns 10.0

v = trunc10( -13.0 );
// returns -10.0

v = trunc10( 0.0 );
// returns 0.0

v = trunc10( -0.0 );
// returns -0.0

v = trunc10( Infinity );
// returns Infinity

v = trunc10( -Infinity );
// returns -Infinity

v = trunc10( NaN );
// returns NaN
```

## Notes

-   The function may not return accurate results for subnormals due to a general loss in precision.

    ```javascript
    var v = trunc10( 1.0e-323 ); // should return 1.0e-323
    // returns 0.0
    ```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var trunc10 = require( '@stdlib/math/base/special/trunc10' );

var x;
var v;
var i;

for ( i = 0; i < 100; i++ ) {
    x = (randu()*100.0) - 50.0;
    v = trunc10( x );
    console.log( 'Value: %d. Rounded: %d.', x, v );
}
```

* * *

## See Also

-   [`@stdlib/math/base/special/ceil10`][@stdlib/math/base/special/ceil10]: round a numeric value to the nearest power of 10 toward positive infinity.
-   [`@stdlib/math/base/special/floor10`][@stdlib/math/base/special/floor10]: round a numeric value to the nearest power of 10 toward negative infinity.
-   [`@stdlib/math/base/special/round10`][@stdlib/math/base/special/round10]: round a numeric value to the nearest power of 10 on a linear scale.
-   [`@stdlib/math/base/special/trunc`][@stdlib/math/base/special/trunc]: round a double-precision floating-point number toward zero.
-   [`@stdlib/math/base/special/trunc2`][@stdlib/math/base/special/trunc2]: round a numeric value to the nearest power of two toward zero.

[@stdlib/math/base/special/ceil10]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/math/base/special/ceil10

[@stdlib/math/base/special/floor10]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/math/base/special/floor10

[@stdlib/math/base/special/round10]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/math/base/special/round10

[@stdlib/math/base/special/trunc]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/math/base/special/trunc

[@stdlib/math/base/special/trunc2]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/math/base/special/trunc2


text:
package org.huahinframework.tools.wc;

import java.io.IOException;

import org.huahinframework.core.Filter;
import org.huahinframework.core.io.Record;
import org.huahinframework.core.writer.Writer;

/**
 *
 */
public class WcFilter extends Filter {
    /* (non-Javadoc)
     * @see org.huahinframework.core.Filter#init()
     */
    @Override
    public void init() {
    }

    /* (non-Javadoc)
     * @see org.huahinframework.core.Filter#filter(org.huahinframework.core.io.Record, org.huahinframework.core.writer.Writer)
     */
    @Override
    public void filter(Record record, Writer writer)
            throws IOException, InterruptedException {
        Record emitRecord = new Record();
        emitRecord.addGrouping("FILE_NAME", record.getGroupingString("FILE_NAME"));
        emitRecord.addValue("FILE_LENGTH", record.getGroupingLong("FILE_LENGTH"));
        writer.write(emitRecord);
    }

    /* (non-Javadoc)
     * @see org.huahinframework.core.Filter#filterSetup()
     */
    @Override
    public void filterSetup() {
    }
}


text:
from django.utils.translation import ugettext_lazy as _

import horizon

class TemplatesVitrage(horizon.Panel):
    name = _("Templates")
    slug = "vitragetemplates"


text:
namespace audio {

LogAdapter::LogAdapter(mojo::PendingRemote<media::mojom::AudioLog> audio_log)
    : audio_log_(std::move(audio_log)) {}

LogAdapter::~LogAdapter() = default;

void LogAdapter::OnCreated(const media::AudioParameters& params,
                           const std::string& device_id) {
  audio_log_->OnCreated(params, device_id);
}

void LogAdapter::OnStarted() {
  audio_log_->OnStarted();
}

void LogAdapter::OnStopped() {
  audio_log_->OnStopped();
}

void LogAdapter::OnClosed() {
  audio_log_->OnClosed();
}

void LogAdapter::OnError() {
  audio_log_->OnError();
}

void LogAdapter::OnSetVolume(double volume) {
  audio_log_->OnSetVolume(volume);
}

void LogAdapter::OnProcessingStateChanged(const std::string& message) {
  audio_log_->OnProcessingStateChanged(message);
}

void LogAdapter::OnLogMessage(const std::string& message) {
  audio_log_->OnLogMessage(message);
}

}  // namespace audio


text:
using System;
using System.Collections.Generic;
using BackendlessAPI.Async;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Backendless.Test;

namespace BackendlessAPI.Test.UserService.AsyncTests
{
  [Ignore]
  [TestClass]
  public class TestsFrame : IAsyncTest
  {
    public Random Random = new Random();
    public List<String> UsedProperties = new List<String>();

    public const string LOGIN_KEY = "email";
    public const string EMAIL_KEY = "email";
    public const string PASSWORD_KEY = "password";
    public const string ID_KEY = "id";

    public BackendlessUser GetRandomNotRegisteredUser()
    {
      var timestamp = (DateTime.UtcNow.Ticks + Random.Next()).ToString();
      BackendlessUser result = new BackendlessUser();
      result.SetProperty( LOGIN_KEY, "bot" + timestamp );
      result.SetProperty( EMAIL_KEY, result.GetProperty( LOGIN_KEY ) + "@backendless.com" );
      result.Password = "somepass_" + timestamp;

      return result;
    }

    public BackendlessUser GetRandomRegisteredUser( AsyncCallback<BackendlessUser> callback )
    {
      BackendlessUser user = GetRandomNotRegisteredUser();

      if( callback == null )
        Backendless.UserService.Register( user );
      else
        Backendless.UserService.Register( user, callback );

      return user;
    }

    public void GetRandomLoggedInUser( AsyncCallback<BackendlessUser> callback )
    {
      GetRandomRegisteredUser(
        new AsyncCallback<BackendlessUser>(
          response =>
          Backendless.UserService.Login( (string) response.GetProperty( LOGIN_KEY ), response.Password,
                                         new AsyncCallback<BackendlessUser>( r =>
                                           {
                                             if( callback != null )
                                             {
                                               callback.ResponseHandler.Invoke( response );
                                             }
                                           }, fault =>
                                             {
                                               if( callback != null )
                                               {
                                                 callback.ErrorHandler.Invoke( fault );
                                               }
                                             } ) ), fault =>
                                               {
                                                 if( callback != null )
                                                 {
                                                   callback.ErrorHandler.Invoke( fault );
                                                 }
                                               } ) );
    }

    [TestInitialize]
    public void SetUp()
    {
      Backendless.URL = "http://" + Defaults.BACKENDLESS_HOST + ":9000";
      Backendless.InitApp( Defaults.TEST_APP_ID, Defaults.TEST_SECRET_KEY );
    }

    [TestCleanup]
    public void TearDown()
    {
      if( Backendless.UserService.CurrentUser != null )
      {
        Backendless.UserService.Logout();
      }
    }
  }
}


text:
- Preparing for upcoming changes in the Dart SDK.
- Bugfixes.

## 0.0.1

- Initial version, created by Stagehand


text:
package stamina

import scala.util._
import akka.serialization._

/**
 * A custom Akka Serializer specifically designed for use with Akka Persistence.
 */
abstract class StaminaAkkaSerializer(persisters: Persisters, encoding: PersistedCodec = DefaultPersistedCodec) extends Serializer {
  /** We don't need class manifests since we're using keys to identify types. */
  val includeManifest: Boolean = false

  /** Uniquely identifies this Serializer by combining the encoding with a unique number. */
  val identifier = 42 * encoding.identifier

  /**
   * @throws UnregisteredTypeException when the specified object is not supported by the persisters.
   */
  def toBinary(obj: AnyRef): Array[Byte] = {
    if (!persisters.canPersist(obj)) throw UnregisteredTypeException(obj)

    encoding.writePersisted(persisters.persist(obj))
  }

  /**
   * @throws UnsupportedDataException when the persisted key and/or version is not supported.
   * @throws UnrecoverableDataException when the key and version are supported but recovery throws an exception.
   */
  def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]]): AnyRef = {
    val persisted = encoding.readPersisted(bytes)

    if (!persisters.canUnpersist(persisted)) throw UnsupportedDataException(persisted)

    persisters.unpersist(persisted)
  }
}


text:
<?php
if (!defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
 * PostTaxRequest.class.php
 */

/**
 * Data to pass to {@link TaxServiceSoap#commitTax}.
 * <p>
 * The request must specify all of CompanyCode, DocCode, and DocType in order to uniquely identify the document.
 * </p>
 *
 * @see PostTaxResult
 *
 * @author    Avalara
 * @copyright � 2004 - 2011 Avalara, Inc.  All rights reserved.
 * @package   Tax
 */

class PostTaxRequest extends TaxRequest
{
	private $DocDate;  //date
	private $TotalAmount;  // decimal
	private $TotalTax;  // decimal
	private $Commit=false; // boolean
	private $NewDocCode;  //string

	public function __construct()
	{
		parent::__construct();

	}

	public function getDocDate() { return $this->DocDate; }
	public function getTotalAmount() { return $this->TotalAmount; }
	public function getTotalTax() { return $this->TotalTax; }
	public function getCommit() { return $this->Commit; }
	public function getNewDocCode() { return $this->NewDocCode; }

	/**
	 * DocDate should be in the format yyyy-mm-dd
	 *
	 * @param date $value
	 */
	public function setDocDate($value) { $this->DocDate = $value; return $this; }

	/**
	 *The total amount (not including tax) for the document.
	 *
	 * @param decimal $value
	 */
	public function setTotalAmount($value) { $this->TotalAmount = $value; return $this; }

	/**
	 * The total tax for the document.
	 *
	 * @param decimal $value
	 */
	public function setTotalTax($value) { $this->TotalTax = $value; return $this; }

	/**
	 * If this is set to True, AvaTax will Post and Commit the document in one call.
	 * A very useful feature if you want to Post/Commit the document in one call this avoides one round trip to AvaTax server.
	 *
	 * @param string $value
	 */
	public function setCommit($value) { $this->Commit = ($value ? true : false); return $this; }

	/**
	 * New Document Code for the document.
	 * As on this version of SDK DocCode can be changed during post using NewDocCode.

	 * @param string $value
	 */
	public function setNewDocCode($value) { $this->NewDocCode = $value; }

	}

?>


text:
__author__ = "Javier de la Rosa"
__license__ = "GPL 3"
__version__ = "2.0.4"
__email__ = "versae@gmail.com"
__url__ = "https://github.com/versae/neo4j-rest-client"
__description__ = """Object-oriented Python library to interact with """ \
                  """Neo4j standalone REST server"""
__status__ = "Stable"
# Order
BREADTH_FIRST = "breadth_first"
DEPTH_FIRST = "depth_first"
# Relationships
RELATIONSHIPS_ALL = "all"
RELATIONSHIPS_IN = "in"
RELATIONSHIPS_OUT = "out"
# Return
RETURN_ALL_NODES = "all"
RETURN_ALL_BUT_START_NODE = "all_but_start_node"
# Stop
STOP_AT_DEPTH_ONE = 1
STOP_AT_END_OF_GRAPH = "none"
# Uniqueness
NONE = "none"
NODE_GLOBAL = "node_global"
NODE_PATH = "node_path"
NODE_RECENT = "node recent"  # Deprecated
RELATIONSHIP_GLOBAL = "relationship_global"
RELATIONSHIP_PATH = "relationship_path"
RELATIONSHIP_RECENT = "relationship recent"  # Deprecated
# Returns
NODE = "node"
RELATIONSHIP = "relationship"
PATH = "path"
FULLPATH = "fullpath"
POSITION = "position"
RAW = "raw"
ITERABLE = "iterable"
# Indexes
INDEX = "index"
INDEX_NODE = "index_node"
INDEX_RELATIONSHIP = "index_relationship"
INDEX_EXACT = "exact"
INDEX_FULLTEXT = "fulltext"
# Cypher ordering
ASC = "asc"
DESC = "desc"
# Transactions
TX_GET = "GET"
TX_PUT = "PUT"
TX_POST = "POST"
TX_DELETE = "DELETE"


text:
package ar.edu.ungs.persistence.dao.impl.profesionales;

import java.util.List;
import java.util.Map;

import javax.inject.Named;

import ar.edu.ungs.commons.exception.DaoException;
import ar.edu.ungs.persistence.dao.impl.JpaEntityDaoImpl;
import ar.edu.ungs.persistence.entities.profesionales.Agenda;

@Named
public class AgendaDao extends JpaEntityDaoImpl<Integer, Agenda> {

	@SuppressWarnings("unchecked")
	public List<Agenda> obtenerTurnosDisponibles(Map<String, Object> parametros)
			throws DaoException {
		StringBuilder query = new StringBuilder(
				"SELECT a FROM Agenda a LEFT JOIN a.turno t");
		query.append(" WHERE t IS null ");
		armarQuery(query, parametros);
		return (List<Agenda>) createQuery(query.toString(), parametros);
	}

	@SuppressWarnings("unchecked")
	public List<Agenda> obtenerTurnosOcupados(Map<String, Object> parametros)
			throws DaoException {
		StringBuilder query = new StringBuilder(
				"SELECT a FROM Agenda a LEFT JOIN a.turno t");
		query.append(" WHERE t IS NOT null ");
		armarQuery(query, parametros);
		return (List<Agenda>) createQuery(query.toString(), parametros);
	}

	@SuppressWarnings("unchecked")
	public List<Agenda> obtenerTurnos(Map<String, Object> parametros)
			throws DaoException {
		StringBuilder query = new StringBuilder(
				"SELECT a FROM Agenda a LEFT JOIN a.turno t");
		query.append(" WHERE 1 = 1 ");
		armarQuery(query, parametros);
		return (List<Agenda>) createQuery(query.toString(), parametros);
	}

	@SuppressWarnings("unchecked")
	public List<Agenda> obtenerAgendaByParams(Map<String, Object> parametros)
			throws DaoException {
		StringBuilder query = new StringBuilder("SELECT a FROM Agenda a ");
		query.append(" WHERE 1 = 1 ");
		armarQuery(query, parametros);
		return (List<Agenda>) createQuery(query.toString(), parametros);
	}

	private void armarQuery(StringBuilder query, Map<String, Object> parametros) {

		if (parametros.containsKey("especialidad")) {
			query.append(" AND a.especialidadProfesional.especialidad.id = :especialidad");
		}
		if (parametros.containsKey("profesional")) {
			query.append(" AND a.especialidadProfesional.profesional.id = :profesional");
		}
		if (parametros.containsKey("horarioDesde")) {
			query.append(" AND FUNCTION('TIME',a.horarioDesde) >= FUNCTION('TIME',:horarioDesde)");
		}
		if (parametros.containsKey("horarioHasta")) {
			query.append(" AND FUNCTION('TIME',a.horarioDesde) < FUNCTION('TIME',:horarioHasta)");
		}
		if (parametros.containsKey("fechaDesde")) {
			query.append(" AND a.fecha >= :fechaDesde");
		}
		if (parametros.containsKey("fechaHasta")) {
			query.append(" AND a.fecha <= :fechaHasta");
		}
		if (parametros.containsKey("disponible")) {
			query.append(" AND a.disponible = :disponible");
		}
		if (parametros.containsKey("fecha")) {
			query.append(" AND a.fecha = :fecha");
		}
		query.append(" ORDER BY a.fecha, a.horarioDesde");
	}
}


text:
layout: post
date: 2016-01-03
title: "Nicole Spose Colet of MODEL COAB16260 2016 Sleeveless Chapel Train Ballgown"
category: Nicole Spose
tags: [Nicole Spose,Ballgown,Sweetheart,Chapel Train,Sleeveless,2016]
---
### Nicole Spose Colet of MODEL COAB16260
Just **$349.99**
### 2016  Sleeveless Chapel Train Ballgown

BRANDS	Nicole Spose

Silhouette	Ballgown

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2016

Buy it: [https://www.readybrides.com/en/nicole-spose/3816-nicole-spose-coab16260.html](https://www.readybrides.com/en/nicole-spose/3816-nicole-spose-coab16260.html)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Media;
using System.Runtime.CompilerServices;

namespace TestWPF.Settings
{
    [Serializable]
    public class DisplaySettings : INotifyPropertyChanged
    {
        private FontFamily _font;
        public FontFamily Font
        {
            get { return _font; }
            set { _font = value; OnPropertyChanged(); }
        }

        private decimal _fontSize = 15;
        public decimal FontSize
        {
            get { return _fontSize; }
            set { _fontSize = value; OnPropertyChanged(); }
        }

        [field: NonSerialized]
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using Bytescout.BarCodeReader;

namespace ImagePreprocessingFilters
{
    /// <summary>
    /// This exmaple demonstrates the use of image filters to improve the decoding or speed.
    /// </summary>
    class Program
    {
        static void Main()
        {
            using (Reader reader = new Reader("demo", "demo"))
            {
                // Set barcode type to find
                reader.BarcodeTypesToFind.Code128 = true;

                // WORKING WITH LOW CONTRAST BARCODE IMAGES

                // Add contrast adjustment for low-contrast image
                reader.ImagePreprocessingFilters.AddContrast(40);

                Console.WriteLine("Image {0}", "low-contrast-barcode.png");

                FoundBarcode[] barcodes = reader.ReadFrom("low-contrast-barcode.png");

                if (barcodes.Length == 0)
                    Console.WriteLine("No barcode found!");
                else
                    foreach (FoundBarcode barcode in barcodes)
                        Console.WriteLine("Found barcode {0} with value '{1}'", barcode.Type, barcode.Value);

                reader.ImagePreprocessingFilters.Clear();
                Console.WriteLine();

                // WORKING WITH NOISY BARCODE IMAGES

                // Add the median filter to lower the noise
                reader.ImagePreprocessingFilters.AddMedian();

                Console.WriteLine("Image {0}", "noisy-barcode.png");

                /* -----------------------------------------------------------------------
                NOTE: We can read barcodes from specific page to increase performance.
                For sample please refer to "Decoding barcodes from PDF by pages" program.
                ----------------------------------------------------------------------- */

                barcodes = reader.ReadFrom("noisy-barcode.png");

                if (barcodes.Length == 0)
                    Console.WriteLine("No barcode found!");
                else
                    foreach (FoundBarcode barcode in barcodes)
                        Console.WriteLine("Found barcode {0} with value '{1}'", barcode.Type, barcode.Value);

                reader.ImagePreprocessingFilters.Clear();
                Console.WriteLine();

                // WORKING WITH DENSE AND ILLEGIBLE BARCODES

                // Add the scale filter to enlarge the barcode to make gaps between bars more distinguishable
                reader.ImagePreprocessingFilters.AddScale(2d); // enlarge twice

                Console.WriteLine("Image {0}", "too-dense-barcode.png");

                barcodes = reader.ReadFrom("too-dense-barcode.png");

                if (barcodes.Length == 0)
                    Console.WriteLine("No barcode found!");
                else
                    foreach (FoundBarcode barcode in barcodes)
                        Console.WriteLine("Found barcode {0} with value '{1}'", barcode.Type, barcode.Value);

                reader.ImagePreprocessingFilters.Clear();
                Console.WriteLine();

                // REMOVE EMPTY MARGINS FROM IMAGE TO SPEED UP THE PROCESSING

                // Add the crop filter to cut off empty margins from the image.
                // This will not improve the recognition quality but may speed up the processing
                // if you enabled multiple barcode types to search.
                reader.ImagePreprocessingFilters.AddCropDark();

                Console.WriteLine("Image {0}", "barcode-with-large-margins.png");

                barcodes = reader.ReadFrom("barcode-with-large-margins.png");

                if (barcodes.Length == 0)
                    Console.WriteLine("No barcode found!");
                else
                    foreach (FoundBarcode barcode in barcodes)
                        Console.WriteLine("Found barcode {0} with value '{1}'", barcode.Type, barcode.Value);

                reader.ImagePreprocessingFilters.Clear();
                Console.WriteLine();
            }

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();
        }
    }
}


text:
package ru.job4j.monitsync;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
 * Класс ParallelSearchTest тестирует класс ParallelSearch.
 *
 * @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
 * @version 2018-07-11
 * @since 2017-07-31
 */
public class ParallelSearchTest  {
    /**
     * Тестирует работу класса ParallelSearch.
     */
    @Test
    public void testingParallelSearch() {
        String localFileName = "D:\\web";
        File dir = new File(localFileName);
        if (dir.isDirectory()) {
            ParallelSearch ps = new ParallelSearch(localFileName, "TPLURI", Arrays.asList(new String[]{"php", "js"}));

            List<String> result = ps.result();
            assertEquals(137, result.size());
        }
    }
    /**
     * Тестирует исключение PathIsNotDirException.
     */
    @Test(expected = PathIsNotDirException.class)
    public void testPathIsNotDirException() {
        new ParallelSearch("^&%^&$%", "ololo", Arrays.asList(new String[]{"php", "xml"}));
    }
    /**
     * Тестирует исключение SearchStringIsEmptyException.
     */
    @Test(expected = SearchStringIsEmptyException.class)
    public void testSearchStringIsEmptyException() {
        new ParallelSearch("/", "    ", Arrays.asList(new String[]{"php", "xml"}));
    }
}


text:
module QACG.CircGen.Bit.Equal
( equal
  ,mkEqualOutOfPlace
  ,mkNotEqualOutOfPlace
) where

import QACG.CircUtils.Circuit
import QACG.CircUtils.CircuitState
import Control.Monad.State
import Control.Exception

import QACG.CircGen.Bit.MCToff

equal :: [String] -> [String] -> String -> CircuitState ()
equal x y targ = assert (length x == length y) $ go x y
  where go (a:as) (b:bs) =  do cnot a b
                               go as bs
                               cnot a b
        go [] [] = do applyNots y
                      mcToff y targ
                      applyNots y
        go _ _ = assert False $ return () --Should never happen!
        applyNots (l:ls) = do notgate l
                              applyNots ls
        applyNots [] = return ()

notEqual :: [String] -> [String] -> String -> CircuitState ()
notEqual x y targ = do equal x y targ
                       notgate targ

mkEq :: ([String] -> [String] -> String -> CircuitState ()) -> [String]-> [String] -> String -> Circuit
mkEq f a b targ = circ
  where (_,(_,_,circ)) = runState go ([], map (\x->'c':show x) [0..(3 * length a)] , Circuit (LineInfo [] [] [] []) [] [])
        go             = do as <- initLines a
                            bs <- initLines b
                            t <- initLines [targ]
                            f a b (head t)
                            setOutputs $ as ++ bs ++ t

mkEqualOutOfPlace, mkNotEqualOutOfPlace
    :: [String]-> [String] -> String -> Circuit

mkEqualOutOfPlace = mkEq equal
mkNotEqualOutOfPlace = mkEq notEqual


text:
<?php

use diversen\conf;
use diversen\file;
use diversen\cli\common;

/**
 * executes a command on all coscms systems install in parent dir (../) from
 * current dir
 * @param array $options array ('command' => $command);
 * @return int $res
 */
function multi_exec_command ($options = null) {

    $path = conf::pathBase() . "/../";
    if (!isset($options['command'])) {
        common::abort('Specify a command');
        return 1;
    }

    $command = $options['command'];
    $dirs = file::getDirsGlob($path, array ('basename' => 1));
    foreach ($dirs as $domain) {
        if (!file_exists("../$domain/config/config.ini")) {
            continue;
        }
        $exec_command = "cd ../$domain && ./coscli.sh $command";
        multi_passthru($exec_command);
    }
}

/**
 * passthru wrapper which print command being passthru'ed
 * @param string $command
 * @return int $res result from passthrou
 */
function multi_passthru ($command) {
    common::echoStatus('NOTICE', 'g', "Executing command: $command");
    passthru($command, $ret);
    return $ret;
}

/**
 * executes a shell command on all coscms systems install in parent dir (../) from
 * current dir
 * @param string $command
 * @return int $ret
 */
function multi_exec_shell_command ($options = array ()) {
    $path = conf::pathBase() . "/../";
    if (!isset($options['command'])) {
        common::abort('Specify a command');
        return 1;
    }

    $command = $options['command'];
    $dirs = file::getDirsGlob($path, array ('basename' => 1));
    foreach ($dirs as $domain) {
        if (!file_exists("../$domain/config/config.ini")) {
            continue;
        }
        $exec_command = "cd ../$domain && $command";
        multi_passthru($exec_command);
    }

}

self::setCommand('multi', array(
    'description' => 'Commands used on a multiple domains found in same path',
));

self::setOption('multi_exec_command', array(
    'long_name'   => '--exec',
    'description' => 'Will execute given command on all sites found in path. E.g: ./coscli.sh multi --exec \'git --all-up --master\'',
    'action'      => 'StoreTrue'
));

self::setOption('multi_exec_shell_command', array(
    'long_name'   => '--exec-shell',
    'description' => 'Will execute given command on all sites found in path. E.g: ./coscli.sh multi --exec \'git --all-up --master\'',
    'action'      => 'StoreTrue'
));

self::setArgument(
    'command',
    array('description'=> 'Specify a command to execute on all sites',
        'optional' => true,
));


text:
#ifndef RenderScrollbar_h
#define RenderScrollbar_h

#include "core/layout/style/LayoutStyleConstants.h"
#include "platform/heap/Handle.h"
#include "platform/scroll/Scrollbar.h"
#include "wtf/HashMap.h"

namespace blink {

class LocalFrame;
class Node;
class RenderBox;
class RenderScrollbarPart;
class LayoutStyle;

class RenderScrollbar final : public Scrollbar {
public:
    static PassRefPtrWillBeRawPtr<Scrollbar> createCustomScrollbar(ScrollableArea*, ScrollbarOrientation, Node*, LocalFrame* owningFrame = 0);
    virtual ~RenderScrollbar();

    RenderBox* owningRenderer() const;

    IntRect buttonRect(ScrollbarPart);
    IntRect trackRect(int startLength, int endLength);
    IntRect trackPieceRectWithMargins(ScrollbarPart, const IntRect&);

    int minimumThumbLength();

    virtual bool isOverlayScrollbar() const override { return false; }

    RenderScrollbarPart* getPart(ScrollbarPart partType) { return m_parts.get(partType); }

    virtual void trace(Visitor*) override;

protected:
    RenderScrollbar(ScrollableArea*, ScrollbarOrientation, Node*, LocalFrame*);

private:
    friend class Scrollbar;

    virtual void setParent(Widget*) override;
    virtual void setEnabled(bool) override;

    virtual void setHoveredPart(ScrollbarPart) override;
    virtual void setPressedPart(ScrollbarPart) override;

    virtual void styleChanged() override;

    virtual bool isCustomScrollbar() const override { return true; }

    void updateScrollbarParts(bool destroy = false);

    PassRefPtr<LayoutStyle> getScrollbarPseudoStyle(ScrollbarPart, PseudoId);
    void updateScrollbarPart(ScrollbarPart, bool destroy = false);

    // This Scrollbar(Widget) may outlive the DOM which created it (during tear down),
    // so we keep a reference to the Node which caused this custom scrollbar creation.
    // This will not create a reference cycle as the Widget tree is owned by our containing
    // FrameView which this Node pointer can in no way keep alive. See webkit bug 80610.
    RefPtrWillBeMember<Node> m_owner;

    RawPtrWillBeMember<LocalFrame> m_owningFrame;

    HashMap<unsigned, RenderScrollbarPart*> m_parts;
};

DEFINE_TYPE_CASTS(RenderScrollbar, ScrollbarThemeClient, scrollbar, scrollbar->isCustomScrollbar(), scrollbar.isCustomScrollbar());

} // namespace blink

#endif // RenderScrollbar_h


text:
""" Tests for glm function in glm module
This checks the glm function with the procedure in the "Basic linear
modeling" exercise from Day 14.

Run at the project directory with:
    nosetests code/utils/tests/test_glm.py
"""
# Loading modules.
import numpy as np
import numpy.linalg as npl
import nibabel as nib
import os
import sys
from numpy.testing import assert_almost_equal, assert_array_equal

# Path to the subject 009 fMRI data used in class.
pathtoclassdata = "data/ds114/"

# Add path to functions to the system path.
sys.path.append(os.path.join(os.path.dirname(__file__), "../functions/"))

# Load our GLM functions.
from glm import glm, glm_diagnostics, glm_multiple

def test_glm():
    # Read in the image data.
    img = nib.load(pathtoclassdata + "ds114_sub009_t2r1.nii")
    data = img.get_data()[..., 4:]
    # Read in the convolutions.
    convolved = np.loadtxt(pathtoclassdata + "ds114_sub009_t2r1_conv.txt")[4:]
    # Create design matrix.
    actual_design = np.ones((len(convolved), 2))
    actual_design[:, 1] = convolved

    # Calculate betas, copied from the exercise.
    data_2d = np.reshape(data, (-1, data.shape[-1]))
    actual_B = npl.pinv(actual_design).dot(data_2d.T)
    actual_B_4d = np.reshape(actual_B.T, img.shape[:-1] + (-1,))

    # Run function.
    exp_B_4d, exp_design = glm(data, convolved)
    assert_almost_equal(actual_B_4d, exp_B_4d)
    assert_almost_equal(actual_design, exp_design)

    # Pick a single voxel to check diagnostics.
    # Calculate actual fitted values, residuals, and MRSS of voxel.
    actual_fitted = actual_design.dot(actual_B_4d[42, 32, 19])
    actual_residuals = data[42, 32, 19] - actual_fitted
    actual_MRSS = np.sum(actual_residuals**2)/(actual_design.shape[0] - npl.matrix_rank(actual_design))

    # Calculate using glm_diagnostics function.
    exp_MRSS, exp_fitted, exp_residuals = glm_diagnostics(exp_B_4d, exp_design, data)
    assert_almost_equal(actual_fitted, exp_fitted[42, 32, 19])
    assert_almost_equal(actual_residuals, exp_residuals[42, 32, 19])
    assert_almost_equal(actual_MRSS, exp_MRSS[42, 32, 19])

def test_glm_multiple():
    # example from http://www.jarrodmillman.com/rcsds/lectures/glm_intro.html
    # it should be pointed out that hypothesis just looks at simple linear regression

    psychopathy = [11.416,   4.514,  12.204,  14.835,
    8.416,   6.563,  17.343, 13.02,
    15.19 ,  11.902,  22.721,  22.324]
    clammy = [0.389,  0.2  ,  0.241,  0.463,
    4.585,  1.097,  1.642,  4.972,
    7.957,  5.585,  5.527,  6.964]
    berkeley_indicator = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
    stanford_indicator = [0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
    mit_indicator      = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]
    schools=[berkeley_indicator,stanford_indicator,mit_indicator]

    Y = np.array([psychopathy,clammy])

    X = np.ones((len(berkeley_indicator),3)) # we aren't including the [1] as a column here

    for i,school in enumerate(schools):
        X[:,i]=school

    b,X =glm_multiple(Y,X)

    # from lecture notes
    assert round(b[0,0],5) == 10.74225
    assert round(b[0,1],5) == 11.3355
    assert round(b[0,2],5) == 18.03425


text:
<?php
/** snippit to use when extending Modules
class PropertiesModule extends Module {

	function PropertiesModule($row) {
		parent::Module($row);

		define('AT_PRIV_ADMIN', $row['privilege']);
	}

	function delete() {

	}
}
return;
**/

if (!defined('AT_INCLUDE_PATH')) { exit; }
if (!isset($this) || (isset($this) && (strtolower(get_class($this)) != 'module'))) { exit(__FILE__ . ' is not a Module'); }

if (!defined('AT_PRIV_ADMIN')) {
	define('AT_PRIV_ADMIN', $this->getPrivilege());
}

//admin pages
$this->_pages['mods/_core/properties/admin/edit_course.php']['title_var'] = 'course_properties';
$this->_pages['mods/_core/properties/admin/edit_course.php']['parent']    = 'mods/_core/courses/admin/courses.php';

$this->_pages['mods/_core/properties/admin/delete_course.php']['title_var'] = 'delete_course';
$this->_pages['mods/_core/properties/admin/delete_course.php']['parent']    = 'mods/_core/courses/admin/courses.php';

//instructor pages
$this->_pages['mods/_core/properties/course_properties.php']['title_var'] = 'properties';
$this->_pages['mods/_core/properties/course_properties.php']['parent']    = 'tools/index.php';
$this->_pages['mods/_core/properties/course_properties.php']['img']       = 'mods/_core/properties/home-properties.png';
$this->_pages['mods/_core/properties/course_properties.php']['children']  = array('mods/_core/properties/delete_course.php', 'mods/_core/properties/access.php');
$this->_pages['mods/_core/properties/course_properties.php']['guide']     = 'instructor/?p=properties.php';

	$this->_pages['mods/_core/properties/delete_course.php']['title_var'] = 'delete_course';
	$this->_pages['mods/_core/properties/delete_course.php']['parent']    = 'mods/_core/properties/course_properties.php';

	$this->_pages['mods/_core/properties/access.php']['title_var'] = 'authenticated_access';
	$this->_pages['mods/_core/properties/access.php']['parent']    = 'mods/_core/properties/course_properties.php';
	$this->_pages['mods/_core/properties/access.php']['guide']     = 'instructor/?p=authenticated_access.php';

if($_SESSION['is_admin'] > 0 || authenticate(AT_PRIV_ADMIN, TRUE)){
   $this->_pages_i['mods/_core/properties/course_properties.php']['title_var'] = 'properties';
   $this->_pages_i['mods/_core/properties/course_properties.php']['other_parent']    = 'index.php';
   $this->_pages_i['index.php']['children']  = array('mods/_core/properties/course_properties.php');
   $this->_pages['index.php']['children']  = array();
}
?>


text:
This is a very simple example showing how to integrate Verilog modules
generated Vivado HLS into BSV.

## TL;DR:

Having installed connectal, verilator and bluespec, to build and run this example:

    make -j22 build.verilator ; make run.verilator

## Description of the code structure

The HLS source code is:

    void vectoradd(const int in0[64], const int in1[64], int out[64])
    {
    #pragma HLS interface ap_hs port=in0
    #pragma HLS interface ap_hs port=in1
    #pragma HLS interface ap_hs port=out
	    for (int i = 0; i < 64; i++)
    #pragma unroll 4
		    out[i] = in0[i] + in1[i];
    }

The Makefile does not currently run vivado_hls, but the generated
verilog is in the repo.

The `HLS interface ap_hs` pragma directs Vivado HLS to generate a port
with valid/ack handshaking. It's similar to AXI stream, but I chose
this option because it's easier to remember that `ack` is the response
than `ready`.

The generated Verilog module has the following interface:

    module vectoradd (
	input   ap_clk,
	input   ap_rst,
	input   ap_start,
	output   ap_done,
	output   ap_idle,
	output   ap_ready,
	input  [31:0] in0,
	input   in0_ap_vld,
	output   in0_ap_ack,
	input  [31:0] in1,
	input   in1_ap_vld,
	output   in1_ap_ack,
	output  [31:0] out_r,
	output   out_r_ap_vld,
	input   out_r_ap_ack);

Connectal's importbvi.py script produces a basic `import "BVI"`
definition for the module so we can invoke it from BSV. Matching the
port declarations against the Vivado HLS conventions, importbvi.py
could generate the following BSV interface for the module:

    interface Vaddhls;
       interface Put#(Bit#(32)) in0;
       interface Put#(Bit#(32)) in1;
       interface Get#(Bit#(32)) out;
       method Action start();
       method ActionValue#(Bit#(1)) done();
    endinterface

I write my test benches in software, which is quite easy to do with
Connectal. So even though this is about the slowest way possible to
run this "accelerator", I wrapped it up in the following top level BSV
module:

    // requests from software to hardware
    interface VaddRequest;
       method Action data(Bit#(32) in0, Bit#(32) in1);
       method Action start();
    endinterface

    // responses from hardware to software
    interface VaddResponse;
       method Action data(Bit#(32) out);
       method Action done();
    endinterface

    interface Vadd;
       interface VaddRequest request;
    endinterface

    module mkVadd#(VaddResponse response)(Vadd);
       Vaddhls vaddhls <- mkVaddhls(64);

       rule rl_response;
	  let v <- vaddhls.out.get();
	  response.data(v);
       endrule

       rule rl_done;
	  let v <- vaddhls.done();
	  response.done();
       endrule

       interface VaddRequest request;
	  method Action data(Bit#(32) in0, Bit#(32) in1);
	     vaddhls.in0.put(in0);
	     vaddhls.in1.put(in1);
	  endmethod
	  method Action start();
	     vaddhls.start();
	  endmethod
       endinterface
    endmodule

And finally the test driver:

    #include <stdio.h>
    #include <VaddRequest.h>
    #include <VaddResponse.h>

    volatile int finished = 0;
    class VaddResponse : public VaddResponseWrapper
    {
    private:
      int i;
      int received_done;
    public:
      virtual void data ( const uint32_t out ) {
	fprintf(stderr, "data[%d] = %d\n", i, out);
	i = i + 1;
	if (i >= 64 && received_done)
	  finished = 1;
      }
      virtual void done() {
	fprintf(stderr, "done\n");
	received_done = 1;
	if (i >= 64 && received_done)
	  finished = 1;
      }
      void clear() {
	i = 0;
	received_done = 0;
	finished = 0;
      }
      VaddResponse(unsigned int id, PortalTransportFunctions *transport = 0, void *param = 0, PortalPoller *poller = 0)
	: VaddResponseWrapper(id, transport, param, poller) {
	i = 0;
	received_done = 0;
      }
    };

    int main(int argc, const char **argv)
    {
      // Instantiate response handler, which will run in a second thread
      VaddResponse response(IfcNames_VaddResponseH2S);
      // Instantiate the request proxy
      VaddRequestProxy *request = new VaddRequestProxy(IfcNames_VaddRequestS2H);

      // [1] Batch processing mode

      // send the data to the logic
      for (int i = 0; i < 64; i++) {
	request->data(i, i*2);
      }
      // start the computation
      request->start();

      // wait for responses
      while (!finished)
	sleep(1);

      // clear the response handler so we can use it again
      response.clear();

      // [2] Pipelined processing mode

      // start the computation
      request->start();

      // send the data
      for (int i = 0; i < 64; i++) {
	request->data(i, i*2);
      }

      // wait for responses
      while (!finished)
	sleep(1);

      return 0;
    }


text:
@extends('core::layouts.app')

@section('content')

{{ __('Cadastrar Usuário') }}

                  <form action="{{ route('admin::users::users.store') }}" method="POST">
                      @csrf

                          Nome

                              <input maxlength="50" id="name" type="text" class="form-control{{ $errors->has('name') ? ' is-invalid' : '' }}" value="{{ old('name') }}" name="name" autofocus required>
                              @if ($errors->has('name'))

                                      {{ $errors->first('name') }}

                              @endif

                          Email

                              <input maxlength="255" id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" value="{{ old('email') }}" name="email" autofocus required>
                              @if ($errors->has('email'))

                                      {{ $errors->first('email') }}

                              @endif

                          Senha

                              <input maxlength="255" id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" value="{{ old('password') }}" name="password" autofocus required>
                              @if ($errors->has('password'))

                                      {{ $errors->first('password') }}

                              @endif

                          Confirmar Senha

                              <input maxlength="255" id="password_confirmation" type="password" class="form-control{{ $errors->has('password_confirmation') ? ' is-invalid' : '' }}" value="{{ old('password_confirmation') }}" name="password_confirmation" autofocus required>
                              @if ($errors->has('password_confirmation'))

                                      {{ $errors->first('password_confirmation') }}

                              @endif

                          <input id="is_admin" type="checkbox" name="is_admin" value="1"> Administrador

                              <button class="btn btn-primary" type="submit">
                                  Salvar
                              </button>

                  </form>

@endsection