answer stringlengths 15 1.25M |
|---|
// Compare ptp time and system time
#include "time.h"
#include "stdio.h"
#include "fcntl.h"
#include <unistd.h>
#include <stdlib.h>
#define DEVICE "/dev/ptp0"
#define CLOCKFD 3
#define FD_TO_CLOCKID(fd) ((~(clockid_t) (fd) << 3) | CLOCKFD)
#define CLOCKID_TO_FD(clk) ((unsigned int) ~((clk) >> 3))
#define CLOCK_INVALID -1
clockid_t phc_open(char *phc)
{
clockid_t clkid;
int fd = open(phc, O_RDWR);
if (fd < 0)
return CLOCK_INVALID;
clkid = FD_TO_CLOCKID(fd);
return clkid;
}
void phc_close(clockid_t clkid)
{
if (clkid == CLOCK_INVALID)
return;
close(CLOCKID_TO_FD(clkid));
}
long delta_ns(struct timespec begin, struct timespec end) {
return (end.tv_sec - begin.tv_sec) * 1000000000 + end.tv_nsec - begin.tv_nsec;
}
int main(int argc, char **argv) {
struct timespec sys_start, phc_start, sys_ts, phc_ts;
clockid_t phc_clock;
long i, n;
if (argc < 2) {
fprintf(stderr, "Set number of measurements");
exit(EXIT_FAILURE);
}
n = atol(argv[1]);
phc_clock = phc_open(DEVICE);
if (clock_gettime(CLOCK_REALTIME, &sys_start))
perror("clock_gettime() CLOCK_REALTIME");
if (clock_gettime(phc_clock, &phc_start))
perror("clock_gettime() phc device");
for (i = 0; i < n; i++) {
clock_gettime(CLOCK_REALTIME, &sys_ts);
clock_gettime(phc_clock, &phc_ts);
printf("%li %li\n", delta_ns(sys_start, sys_ts), delta_ns(phc_start, phc_ts));
}
exit(EXIT_SUCCESS);
} |
<?php
class CalculadoraDePrecos {
private $tabela;
private $entrega;
public function __construct(TabelaDePreco $tabela, ServicoDeEntrega $frete) {
$this->tabela = $tabela;
$this->entrega = $frete;
}
public function calcula(Compra $produto) {
$desconto = $this->tabela->descontoPara($produto->getValor());
$frete = $this->entrega->para($produto->getCidade());
return $produto->getValor() * (1-$desconto) + $frete;
}
}
?> |
// <API key>.h
// WJActivityIndicator
#import <Foundation/Foundation.h>
@interface <API key> : NSObject
@end |
@(guildShortName: String, steps: Seq[bot.VerificationStep], tosForm: Form[controllers.TOSFormData])(implicit messages: Messages, flash: Flash)
@verify(guildShortName, steps) {
<h1>Welcome</h1>
<p>Please complete the following steps to be invited to the @guildShortName server.</p>
@helper.form(action = routes.HomeController.verify(guildShortName).copy(method = "POST")) {
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" name="agreed" id="tos-agreed" value="true">
Do you agree to the @guildShortName terms of service?
</label>
</div>
<input type="hidden" name="fingerprint" id="tos-fingerprint" value="NOJS">
<input type="hidden" name="componentsJSON" id="tos-components-json" value="NOJS">
<input type="hidden" name="timeZone" id="tos-time-zone" value="NOJS">
<button type="submit" id="tos-submit" class="btn btn-primary" disabled>Submit</button>
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fingerprintjs2/1.5.1/fingerprint2.min.js"></script>
<script src="@routes.Assets.at("scripts/detect-fingerprint.js")"></script>
} |
'
' Inicio del codigo
'
' Importando librerias
'
Imports System.Data
'
' Inicio de clase "<API key>"
'
Partial Class <API key>
Inherits vis2formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim <API key> As New StringBuilder()
<API key>.AppendLine("SELECT Cuentas_Pagar.Tip_Ori AS Tipo_Origen,")
<API key>.AppendLine(" Cuentas_Pagar.Fec_Ini AS Fecha_Retencion,")
<API key>.AppendLine(" Cuentas_Pagar.Doc_Ori AS Numero_Pago,")
<API key>.AppendLine(" <API key>.Cod_Tip AS Tipo_Documento,")
<API key>.AppendLine(" <API key>.Doc_Ori AS Numero_Documento,")
<API key>.AppendLine(" Renglones_Pagos.Control AS Control_Documento,")
<API key>.AppendLine(" Renglones_Pagos.Factura AS Factura_Documento,")
<API key>.AppendLine(" Renglones_Pagos.Fec_Ini AS Fecha_Factura,")
<API key>.AppendLine(" Renglones_Pagos.Mon_Net AS Monto_Documento,")
<API key>.AppendLine(" Renglones_Pagos.Mon_Abo AS Monto_Abonado,")
<API key>.AppendLine(" <API key>.Num_Com AS Comprobante,")
<API key>.AppendLine(" <API key>.Mon_Bas AS Base_Retencion,")
<API key>.AppendLine(" <API key>.Por_Ret AS Porcentaje_Retenido,")
<API key>.AppendLine(" <API key>.Mon_Sus AS Sustraendo_Retenido,")
<API key>.AppendLine(" <API key>.Mon_Ret AS Monto_Retenido,")
<API key>.AppendLine(" Cuentas_Pagar.Cod_Pro AS Cod_Pro,")
<API key>.AppendLine(" Proveedores.Nom_Pro AS Nom_Pro,")
<API key>.AppendLine(" Proveedores.Rif AS Rif,")
<API key>.AppendLine(" Proveedores.Nit AS Nit,")
<API key>.AppendLine(" Proveedores.Dir_Fis AS Direccion")
<API key>.AppendLine("FROM Cuentas_Pagar")
<API key>.AppendLine(" JOIN Pagos ON Pagos.documento = Cuentas_Pagar.Doc_Ori")
<API key>.AppendLine(" JOIN <API key> ON <API key>.Documento = Pagos.documento")
<API key>.AppendLine(" AND <API key>.doc_des = Cuentas_Pagar.documento")
<API key>.AppendLine(" AND <API key>.clase = 'PATENTE'")
<API key>.AppendLine(" JOIN Renglones_Pagos ON Renglones_Pagos.Documento = Pagos.documento")
<API key>.AppendLine(" AND Renglones_Pagos.Doc_Ori = <API key>.Doc_Ori")
<API key>.AppendLine(" JOIN Proveedores ON Proveedores.Cod_Pro = Cuentas_Pagar.Cod_Pro")
<API key>.AppendLine(" LEFT JOIN Retenciones ON Retenciones.Cod_Ret = <API key>.Cod_Ret")
<API key>.AppendLine(" WHERE " & cusAplicacion.goFormatos.<API key>)
'Me.mEscribirConsulta(<API key>.ToString)
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.<API key>(<API key>.ToString(), "curReportes")
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
'
' Verificando si el select (tabla nº 0) trae registros
'
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.<API key>.<API key>("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.<API key>.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("<API key>", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.<API key>(loObjetoReporte)
Me.<API key>.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.<API key>.<API key>("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.<API key>.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'
' Fin del codigo '
'
' RJG: 09/04/15: Codigo inicial, a partir de <API key>. '
' |
export { default } from 'ember-flexberry-gis/utils/layer-to-jsts'; |
import React from 'react';
import { Route, RouteComponentProps, Redirect, Switch } from 'react-router-dom';
import { App } from 'modules/App';
import { routes } from 'modules/routes';
import { IModule } from 'shared/types/app';
function getRoutes(modules: IModule[]): React.ReactElement<RouteComponentProps<any>> {
return (
<Route path="/">
<App>
<Switch>
{modules.map(module => (module.getRoutes ? module.getRoutes() : null))}
<Redirect to={routes.search.users.getRedirectPath()} />
</Switch>
</App>
</Route>
);
}
export { getRoutes }; |
using System;
using System.Collections.Generic;
namespace MediaManager.Library
{
public interface IRadio : IContentItem
{
string Uri { get; set; }
string Title { get; set; }
string Description { get; set; }
string Tags { get; set; }
string Genre { get; set; }
object Image { get; set; }
string ImageUri { get; set; }
object Rating { get; set; }
DateTime CreatedAt { get; set; }
DateTime UpdatedAt { get; set; }
SharingType SharingType { get; set; }
IList<IMediaItem> MediaItems { get; set; }
}
} |
package invoices
import (
"io/ioutil"
"os"
"testing"
"time"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
)
var (
testTimeout = 5 * time.Second
preimage = lntypes.Preimage{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
}
hash = preimage.Hash()
testHtlcExpiry = uint32(5)
<API key> = uint32(4)
<API key> = int32(4)
testCurrentHeight = int32(1)
)
var (
testInvoice = &channeldb.Invoice{
Terms: channeldb.ContractTerm{
PaymentPreimage: preimage,
Value: lnwire.MilliSatoshi(100000),
},
}
)
func newTestContext(t *testing.T) (*InvoiceRegistry, func()) {
cdb, cleanup, err := newDB()
if err != nil {
t.Fatal(err)
}
// Instantiate and start the invoice registry.
registry := NewRegistry(cdb, <API key>)
err = registry.Start()
if err != nil {
cleanup()
t.Fatal(err)
}
return registry, func() {
registry.Stop()
cleanup()
}
}
func getCircuitKey(htlcID uint64) channeldb.CircuitKey {
return channeldb.CircuitKey{
ChanID: lnwire.ShortChannelID{
BlockHeight: 1, TxIndex: 2, TxPosition: 3,
},
HtlcID: htlcID,
}
}
// TestSettleInvoice tests settling of an invoice and related notifications.
func TestSettleInvoice(t *testing.T) {
registry, cleanup := newTestContext(t)
defer cleanup()
allSubscriptions := registry.<API key>(0, 0)
defer allSubscriptions.Cancel()
// Subscribe to the not yet existing invoice.
subscription, err := registry.<API key>(hash)
if err != nil {
t.Fatal(err)
}
defer subscription.Cancel()
if subscription.hash != hash {
t.Fatalf("expected subscription for provided hash")
}
// Add the invoice.
addIdx, err := registry.AddInvoice(testInvoice, hash)
if err != nil {
t.Fatal(err)
}
if addIdx != 1 {
t.Fatalf("expected addIndex to start with 1, but got %v",
addIdx)
}
// We expect the open state to be sent to the single invoice subscriber.
select {
case update := <-subscription.Updates:
if update.Terms.State != channeldb.ContractOpen {
t.Fatalf("expected state ContractOpen, but got %v",
update.Terms.State)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// We expect a new invoice notification to be sent out.
select {
case newInvoice := <-allSubscriptions.NewInvoices:
if newInvoice.Terms.State != channeldb.ContractOpen {
t.Fatalf("expected state ContractOpen, but got %v",
newInvoice.Terms.State)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
hodlChan := make(chan interface{}, 1)
// Settle invoice with a slightly higher amount.
amtPaid := lnwire.MilliSatoshi(100500)
_, err = registry.NotifyExitHopHtlc(
hash, amtPaid, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatal(err)
}
// We expect the settled state to be sent to the single invoice
// subscriber.
select {
case update := <-subscription.Updates:
if update.Terms.State != channeldb.ContractSettled {
t.Fatalf("expected state ContractOpen, but got %v",
update.Terms.State)
}
if update.AmtPaid != amtPaid {
t.Fatal("invoice AmtPaid incorrect")
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// We expect a settled notification to be sent out.
select {
case settledInvoice := <-allSubscriptions.SettledInvoices:
if settledInvoice.Terms.State != channeldb.ContractSettled {
t.Fatalf("expected state ContractOpen, but got %v",
settledInvoice.Terms.State)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// Try to settle again with the same htlc id. We need this idempotent
// behaviour after a restart.
event, err := registry.NotifyExitHopHtlc(
hash, amtPaid, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
}
if event.Preimage == nil {
t.Fatal("expected settle event")
}
// Try to settle again with a new higher-valued htlc. This payment
// should also be accepted, to prevent any change in behaviour for a
// paid invoice that may open up a probe vector.
event, err = registry.NotifyExitHopHtlc(
hash, amtPaid+600, testHtlcExpiry, testCurrentHeight,
getCircuitKey(1), hodlChan, nil,
)
if err != nil {
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
}
if event.Preimage == nil {
t.Fatal("expected settle event")
}
// Try to settle again with a lower amount. This should fail just as it
// would have failed if it were the first payment.
event, err = registry.NotifyExitHopHtlc(
hash, amtPaid-600, testHtlcExpiry, testCurrentHeight,
getCircuitKey(2), hodlChan, nil,
)
if err != nil {
t.Fatalf("unexpected NotifyExitHopHtlc error: %v", err)
}
if event.Preimage != nil {
t.Fatal("expected cancel event")
}
// Check that settled amount is equal to the sum of values of the htlcs
// 0 and 1.
inv, err := registry.LookupInvoice(hash)
if err != nil {
t.Fatal(err)
}
if inv.AmtPaid != amtPaid+amtPaid+600 {
t.Fatal("amount incorrect")
}
// Try to cancel.
err = registry.CancelInvoice(hash)
if err != channeldb.<API key> {
t.Fatal("expected cancelation of a settled invoice to fail")
}
// As this is a direct sette, we expect nothing on the hodl chan.
select {
case <-hodlChan:
t.Fatal("unexpected event")
default:
}
}
// TestCancelInvoice tests cancelation of an invoice and related notifications.
func TestCancelInvoice(t *testing.T) {
registry, cleanup := newTestContext(t)
defer cleanup()
allSubscriptions := registry.<API key>(0, 0)
defer allSubscriptions.Cancel()
// Try to cancel the not yet existing invoice. This should fail.
err := registry.CancelInvoice(hash)
if err != channeldb.ErrInvoiceNotFound {
t.Fatalf("expected ErrInvoiceNotFound, but got %v", err)
}
// Subscribe to the not yet existing invoice.
subscription, err := registry.<API key>(hash)
if err != nil {
t.Fatal(err)
}
defer subscription.Cancel()
if subscription.hash != hash {
t.Fatalf("expected subscription for provided hash")
}
// Add the invoice.
amt := lnwire.MilliSatoshi(100000)
_, err = registry.AddInvoice(testInvoice, hash)
if err != nil {
t.Fatal(err)
}
// We expect the open state to be sent to the single invoice subscriber.
select {
case update := <-subscription.Updates:
if update.Terms.State != channeldb.ContractOpen {
t.Fatalf(
"expected state ContractOpen, but got %v",
update.Terms.State,
)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// We expect a new invoice notification to be sent out.
select {
case newInvoice := <-allSubscriptions.NewInvoices:
if newInvoice.Terms.State != channeldb.ContractOpen {
t.Fatalf(
"expected state ContractOpen, but got %v",
newInvoice.Terms.State,
)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// Cancel invoice.
err = registry.CancelInvoice(hash)
if err != nil {
t.Fatal(err)
}
// We expect the canceled state to be sent to the single invoice
// subscriber.
select {
case update := <-subscription.Updates:
if update.Terms.State != channeldb.ContractCanceled {
t.Fatalf(
"expected state ContractCanceled, but got %v",
update.Terms.State,
)
}
case <-time.After(testTimeout):
t.Fatal("no update received")
}
// We expect no cancel notification to be sent to all invoice
// subscribers (backwards compatibility).
// Try to cancel again.
err = registry.CancelInvoice(hash)
if err != nil {
t.Fatal("expected cancelation of a canceled invoice to succeed")
}
// Notify arrival of a new htlc paying to this invoice. This should
// succeed.
hodlChan := make(chan interface{})
event, err := registry.NotifyExitHopHtlc(
hash, amt, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatal("expected settlement of a canceled invoice to succeed")
}
if event.Preimage != nil {
t.Fatal("expected cancel hodl event")
}
}
// TestHoldInvoice tests settling of a hold invoice and related notifications.
func TestHoldInvoice(t *testing.T) {
defer timeout(t)()
cdb, cleanup, err := newDB()
defer cleanup()
// Instantiate and start the invoice registry.
registry := NewRegistry(cdb, <API key>)
err = registry.Start()
if err != nil {
t.Fatal(err)
}
defer registry.Stop()
allSubscriptions := registry.<API key>(0, 0)
defer allSubscriptions.Cancel()
// Subscribe to the not yet existing invoice.
subscription, err := registry.<API key>(hash)
if err != nil {
t.Fatal(err)
}
defer subscription.Cancel()
if subscription.hash != hash {
t.Fatalf("expected subscription for provided hash")
}
// Add the invoice.
invoice := &channeldb.Invoice{
Terms: channeldb.ContractTerm{
PaymentPreimage: channeldb.UnknownPreimage,
Value: lnwire.MilliSatoshi(100000),
},
}
_, err = registry.AddInvoice(invoice, hash)
if err != nil {
t.Fatal(err)
}
// We expect the open state to be sent to the single invoice subscriber.
update := <-subscription.Updates
if update.Terms.State != channeldb.ContractOpen {
t.Fatalf("expected state ContractOpen, but got %v",
update.Terms.State)
}
// We expect a new invoice notification to be sent out.
newInvoice := <-allSubscriptions.NewInvoices
if newInvoice.Terms.State != channeldb.ContractOpen {
t.Fatalf("expected state ContractOpen, but got %v",
newInvoice.Terms.State)
}
// Use slightly higher amount for accept/settle.
amtPaid := lnwire.MilliSatoshi(100500)
hodlChan := make(chan interface{}, 1)
// NotifyExitHopHtlc without a preimage present in the invoice registry
// should be possible.
event, err := registry.NotifyExitHopHtlc(
hash, amtPaid, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatalf("expected settle to succeed but got %v", err)
}
if event != nil {
t.Fatalf("expected htlc to be held")
}
// Test idempotency.
event, err = registry.NotifyExitHopHtlc(
hash, amtPaid, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatalf("expected settle to succeed but got %v", err)
}
if event != nil {
t.Fatalf("expected htlc to be held")
}
// Test replay at a higher height. We expect the same result because it
// is a replay.
event, err = registry.NotifyExitHopHtlc(
hash, amtPaid, testHtlcExpiry, testCurrentHeight+10,
getCircuitKey(0), hodlChan, nil,
)
if err != nil {
t.Fatalf("expected settle to succeed but got %v", err)
}
if event != nil {
t.Fatalf("expected htlc to be held")
}
// Test a new htlc coming in that doesn't meet the final cltv delta
// requirement. It should be rejected.
event, err = registry.NotifyExitHopHtlc(
hash, amtPaid, 1, testCurrentHeight,
getCircuitKey(1), hodlChan, nil,
)
if err != nil {
t.Fatalf("expected settle to succeed but got %v", err)
}
if event == nil || event.Preimage != nil {
t.Fatalf("expected htlc to be cancelled")
}
// We expect the accepted state to be sent to the single invoice
// subscriber. For all invoice subscribers, we don't expect an update.
// Those only get notified on settle.
update = <-subscription.Updates
if update.Terms.State != channeldb.ContractAccepted {
t.Fatalf("expected state ContractAccepted, but got %v",
update.Terms.State)
}
if update.AmtPaid != amtPaid {
t.Fatal("invoice AmtPaid incorrect")
}
// Settling with preimage should succeed.
err = registry.SettleHodlInvoice(preimage)
if err != nil {
t.Fatal("expected set preimage to succeed")
}
hodlEvent := (<-hodlChan).(HodlEvent)
if *hodlEvent.Preimage != preimage {
t.Fatal("unexpected preimage in hodl event")
}
// We expect a settled notification to be sent out for both all and
// single invoice subscribers.
settledInvoice := <-allSubscriptions.SettledInvoices
if settledInvoice.Terms.State != channeldb.ContractSettled {
t.Fatalf("expected state ContractSettled, but got %v",
settledInvoice.Terms.State)
}
if settledInvoice.AmtPaid != amtPaid {
t.Fatalf("expected amount to be %v, but got %v",
amtPaid, settledInvoice.AmtPaid)
}
update = <-subscription.Updates
if update.Terms.State != channeldb.ContractSettled {
t.Fatalf("expected state ContractSettled, but got %v",
update.Terms.State)
}
// Idempotency.
err = registry.SettleHodlInvoice(preimage)
if err != channeldb.<API key> {
t.Fatalf("expected <API key> but got %v", err)
}
// Try to cancel.
err = registry.CancelInvoice(hash)
if err == nil {
t.Fatal("expected cancelation of a settled invoice to fail")
}
}
func newDB() (*channeldb.DB, func(), error) {
// First, create a temporary directory to be used for the duration of
// this test.
tempDirName, err := ioutil.TempDir("", "channeldb")
if err != nil {
return nil, nil, err
}
// Next, create channeldb for the first time.
cdb, err := channeldb.Open(tempDirName)
if err != nil {
os.RemoveAll(tempDirName)
return nil, nil, err
}
cleanUp := func() {
cdb.Close()
os.RemoveAll(tempDirName)
}
return cdb, cleanUp, nil
}
// TestUnknownInvoice tests that invoice registry returns an error when the
// invoice is unknown. This is to guard against returning a cancel hodl event
// for forwarded htlcs. In the link, NotifyExitHopHtlc is only called if we are
// the exit hop, but in <API key> it is called with forwarded
// htlc hashes as well.
func TestUnknownInvoice(t *testing.T) {
registry, cleanup := newTestContext(t)
defer cleanup()
// Notify arrival of a new htlc paying to this invoice. This should
// succeed.
hodlChan := make(chan interface{})
amt := lnwire.MilliSatoshi(100000)
_, err := registry.NotifyExitHopHtlc(
hash, amt, testHtlcExpiry, testCurrentHeight,
getCircuitKey(0), hodlChan, nil,
)
if err != channeldb.ErrInvoiceNotFound {
t.Fatal("expected invoice not found error")
}
} |
#include <inttypes.h>
#include <csp/csp_debug.h>
#include <stddef.h>
#if (<API key>)
void csp_hex_dump_format(const char * desc, void * addr, int len, int format) {
int i;
unsigned char buff[17];
unsigned char * pc = (unsigned char *)addr;
// Output description if given.
if (desc != NULL)
csp_print("%s\n", desc);
if (!(len > 0))
return;
// Process every byte in the data.
for (i = 0; i < len; i++) {
// Multiple of 16 means new line (with line offset).
if ((i % 16) == 0) {
// Just don't print ASCII for the zeroth line.
if (i != 0)
csp_print(" %s\n", buff);
// Output the offset.
if (format & 0x1) {
csp_print(" %p ", ((uint8_t *)addr) + i);
} else {
csp_print(" ");
}
}
// Now the hex code for the specific character.
csp_print(" %02x", pc[i]);
// And store a printable ASCII character for later.
if ((pc[i] < 0x20) || (pc[i] > 0x7e))
buff[i % 16] = '.';
else
buff[i % 16] = pc[i];
buff[(i % 16) + 1] = '\0';
}
// Pad out last line if not exactly 16 characters.
while ((i % 16) != 0) {
csp_print(" ");
i++;
}
// And print the final ASCII bit.
csp_print(" %s\n", buff);
}
void csp_hex_dump(const char * desc, void * addr, int len) {
csp_hex_dump_format(desc, addr, len, 0);
}
#else
void csp_hex_dump(const char * desc, void * addr, int len) {};
#endif |
import { readFile, sanityCheck } from '../src/file';
import { lexFile } from '../src/lexer';
import { parseFile } from '../src/parser';
import {
FILENAME_4,
} from '../__mocks__/fs';
import {
AMBIGUOUS,
} from '../src/parser';
jest.mock('fs');
jest.unmock('../src/file');
jest.unmock('../src/lexer');
jest.unmock('../src/parser');
jest.unmock('../src/checksum');
describe('User Story 4: Error Correction', () => {
// Feed it the first use case data.
pit('', () => readFile(FILENAME_4)
.then(sanityCheck)
.then(lexFile)
.then(parseFile)
.then(data => {
let first = data[0];
expect(first.number).toContain('711111111');
expect(first.status).toBeNull;
expect(first.guesses).toBeNull();
let second = data[1];
expect(second.number).toContain('777777177');
expect(second.status).toBeNull;
expect(second.guesses).toBeNull();
let third = data[2];
expect(third.number).toContain('200800000');
expect(third.status).toBeNull;
expect(third.guesses).toBeNull();
let fourth = data[3];
expect(fourth.number).toContain('333393333');
expect(fourth.status).toBeNull;
expect(fourth.guesses).toBeNull();
let fifth = data[4];
expect(fifth.number).toContain('888888888');
expect(fifth.status).toEqual(AMBIGUOUS);
expect(fifth.guesses).toEqual(['888886888', '888888880', '888888988']);
let sixth = data[5];
expect(sixth.number).toContain('555555555');
expect(sixth.status).toEqual(AMBIGUOUS);
expect(sixth.guesses).toEqual(['555655555', '559555555']);
let seventh = data[6];
expect(seventh.number).toContain('666666666');
expect(seventh.status).toEqual(AMBIGUOUS);
expect(seventh.guesses).toEqual(['666566666', '686666666']);
let eighth = data[7];
expect(eighth.number).toContain('999999999');
expect(eighth.status).toEqual(AMBIGUOUS);
expect(eighth.guesses).toEqual(['899999999', '993999999', '999959999']);
let ninth = data[8];
expect(ninth.number).toContain('490067715');
expect(ninth.status).toEqual(AMBIGUOUS);
expect(ninth.guesses).toEqual(['490067115', '490067719', '490867715']);
let tenth = data[9];
expect(tenth.number).toContain('123456789');
expect(tenth.status).toBeNull();
expect(tenth.guesses).toBeNull();
let eleventh = data[10];
expect(eleventh.number).toContain('000000051');
expect(eleventh.status).toBeNull();
expect(eleventh.guesses).toBeNull();
let twelfth = data[11];
expect(twelfth.number).toContain('490867715');
expect(twelfth.status).toBeNull();
expect(twelfth.guesses).toBeNull();
}));
}); |
'use strict';
System.register(['aurelia-templating', '<API key>', 'aurelia-framework', '../common/attributeManager', '../common/attributes', '../element/element'], function (_export, _context) {
"use strict";
var bindable, customElement, noView, inject, computedFrom, AttributeManager, <API key>, Ui5Element, _createClass, _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8, _descriptor9, Ui5gridTableRow;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function <API key>(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function <API key>(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function <API key>(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that <API key> is enabled.');
}
return {
setters: [function (_aureliaTemplating) {
bindable = _aureliaTemplating.bindable;
customElement = _aureliaTemplating.customElement;
noView = _aureliaTemplating.noView;
}, function (<API key>) {
inject = <API key>.inject;
}, function (_aureliaFramework) {
computedFrom = _aureliaFramework.computedFrom;
}, function (<API key>) {
AttributeManager = <API key>.AttributeManager;
}, function (_commonAttributes) {
<API key> = _commonAttributes.<API key>;
}, function (_elementElement) {
Ui5Element = _elementElement.Ui5Element;
}],
execute: function () {
_createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
_export('Ui5gridTableRow', Ui5gridTableRow = (_dec = customElement('ui5-grid-table-row'), _dec2 = inject(Element), _dec3 = bindable(), _dec4 = bindable(), _dec5 = bindable(), _dec6 = bindable(), _dec7 = bindable(), _dec8 = computedFrom('_gridtablerow'), _dec(_class = _dec2(_class = (_class2 = function (_Ui5Element) {
_inherits(Ui5gridTableRow, _Ui5Element);
function Ui5gridTableRow(element) {
_classCallCheck(this, Ui5gridTableRow);
var _this = <API key>(this, _Ui5Element.call(this, element));
_this._gridtablerow = null;
_this._parent = null;
_this._relation = null;
_initDefineProp(_this, 'ui5Id', _descriptor, _this);
_initDefineProp(_this, 'ui5Class', _descriptor2, _this);
_initDefineProp(_this, 'ui5Tooltip', _descriptor3, _this);
_initDefineProp(_this, 'prevId', _descriptor4, _this);
_initDefineProp(_this, 'validationSuccess', _descriptor5, _this);
_initDefineProp(_this, 'validationError', _descriptor6, _this);
_initDefineProp(_this, 'parseError', _descriptor7, _this);
_initDefineProp(_this, 'formatError', _descriptor8, _this);
_initDefineProp(_this, 'modelContextChange', _descriptor9, _this);
_this.element = element;
_this.attributeManager = new AttributeManager(_this.element);
return _this;
}
Ui5gridTableRow.prototype.fillProperties = function fillProperties(params) {
_Ui5Element.prototype.fillProperties.call(this, params);
};
Ui5gridTableRow.prototype.defaultFunc = function defaultFunc() {};
Ui5gridTableRow.prototype.attached = function attached() {
var that = this;
var params = {};
this.fillProperties(params);
if (this.ui5Id) this._gridtablerow = new sap.ui.table.Row(this.ui5Id, params);else this._gridtablerow = new sap.ui.table.Row(params);
if (this.ui5Class) this._gridtablerow.addStyleClass(this.ui5Class);
if (this.ui5Tooltip) this._gridtablerow.setTooltip(this.ui5Tooltip);
if ($(this.element).closest("[ui5-container]").length > 0) {
this._parent = $(this.element).closest("[ui5-container]")[0].au.controller.viewModel;
if (!this._parent.UIElement || this._parent.UIElement.sId != this._gridtablerow.sId) {
var prevSibling = null;
this._relation = this._parent.addChild(this._gridtablerow, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
} else {
this._parent = $(this.element.parentElement).closest("[ui5-container]")[0].au.controller.viewModel;
var prevSibling = null;
this._relation = this._parent.addChild(this._gridtablerow, this.element, this.prevId);
this.attributeManager.addAttributes({ "ui5-container": '' });
}
} else {
if (this._gridtablerow.placeAt) this._gridtablerow.placeAt(this.element.parentElement);
this.attributeManager.addAttributes({ "ui5-container": '' });
this.attributeManager.addClasses("ui5-hide");
}
this.attributeManager.addAttributes({ "ui5-id": this._gridtablerow.sId });
};
Ui5gridTableRow.prototype.detached = function detached() {
try {
if ($(this.element).closest("[ui5-container]").length > 0) {
if (this._parent && this._relation) {
if (this._gridtablerow) this._parent.<API key>(this._gridtablerow, this._relation);
}
} else {
this._gridtablerow.destroy();
}
_Ui5Element.prototype.detached.call(this);
} catch (err) {}
};
Ui5gridTableRow.prototype.addChild = function addChild(child, elem, afterElement) {
var path = jQuery.makeArray($(elem).parentsUntil(this.element));
for (var _iterator = path, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
if (_isArray) {
if (_i >= _iterator.length) break;
elem = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
elem = _i.value;
}
try {
if (elem.localName == 'cells') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerow.insertCell(child, _index);else this._gridtablerow.addCell(child, 0);return elem.localName;
}
if (elem.localName == 'tooltip') {
this._gridtablerow.setTooltip(child);return elem.localName;
}
if (elem.localName == 'customdata') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerow.insertCustomData(child, _index);else this._gridtablerow.addCustomData(child, 0);return elem.localName;
}
if (elem.localName == 'layoutdata') {
this._gridtablerow.setLayoutData(child);return elem.localName;
}
if (elem.localName == 'dependents') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerow.insertDependent(child, _index);else this._gridtablerow.addDependent(child, 0);return elem.localName;
}
if (elem.localName == 'dragdropconfig') {
var _index = afterElement ? Math.floor(afterElement + 1) : null;if (_index) this._gridtablerow.<API key>(child, _index);else this._gridtablerow.addDragDropConfig(child, 0);return elem.localName;
}
} catch (err) {}
}
};
Ui5gridTableRow.prototype.<API key> = function <API key>(child, relation) {
try {
if (relation == 'cells') {
this._gridtablerow.removeCell(child);
}
if (relation == 'tooltip') {
this._gridtablerow.destroyTooltip(child);
}
if (relation == 'customdata') {
this._gridtablerow.removeCustomData(child);
}
if (relation == 'layoutdata') {
this._gridtablerow.destroyLayoutData(child);
}
if (relation == 'dependents') {
this._gridtablerow.removeDependent(child);
}
if (relation == 'dragdropconfig') {
this._gridtablerow.<API key>(child);
}
} catch (err) {}
};
Ui5gridTableRow.prototype.<API key> = function <API key>(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerow !== null) {
this._gridtablerow.<API key>(newValue);
}
};
Ui5gridTableRow.prototype.<API key> = function <API key>(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerow !== null) {
this._gridtablerow.<API key>(newValue);
}
};
Ui5gridTableRow.prototype.parseErrorChanged = function parseErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerow !== null) {
this._gridtablerow.attachParseError(newValue);
}
};
Ui5gridTableRow.prototype.formatErrorChanged = function formatErrorChanged(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerow !== null) {
this._gridtablerow.attachFormatError(newValue);
}
};
Ui5gridTableRow.prototype.<API key> = function <API key>(newValue) {
if (newValue != null && newValue != undefined && this._gridtablerow !== null) {
this._gridtablerow.<API key>(newValue);
}
};
_createClass(Ui5gridTableRow, [{
key: 'UIElement',
get: function get() {
return this._gridtablerow;
}
}]);
return Ui5gridTableRow;
}(Ui5Element), (_descriptor = <API key>(_class2.prototype, 'ui5Id', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor2 = <API key>(_class2.prototype, 'ui5Class', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor3 = <API key>(_class2.prototype, 'ui5Tooltip', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor4 = <API key>(_class2.prototype, 'prevId', [bindable], {
enumerable: true,
initializer: function initializer() {
return null;
}
}), _descriptor5 = <API key>(_class2.prototype, 'validationSuccess', [_dec3], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor6 = <API key>(_class2.prototype, 'validationError', [_dec4], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor7 = <API key>(_class2.prototype, 'parseError', [_dec5], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor8 = <API key>(_class2.prototype, 'formatError', [_dec6], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), _descriptor9 = <API key>(_class2.prototype, 'modelContextChange', [_dec7], {
enumerable: true,
initializer: function initializer() {
return this.defaultFunc;
}
}), <API key>(_class2.prototype, 'UIElement', [_dec8], Object.<API key>(_class2.prototype, 'UIElement'), _class2.prototype)), _class2)) || _class) || _class));
_export('Ui5gridTableRow', Ui5gridTableRow);
}
};
});
//# sourceMappingURL=../dist/dev/grid-table-row/grid-table-row.js.map |
using System;
using System.Diagnostics;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using InnerFence.ChargeDemo.Phone.Resources;
using InnerFence.ChargeAPI;
using Microsoft.Xna.Framework.GamerServices;
using System.Text.RegularExpressions;
using System.Globalization;
namespace InnerFence.ChargeDemo.Phone
{
public partial class App : Application
{
private static readonly Regex RecordIdPattern = new Regex("^[0-9]+$");
<summary>
Provides easy access to the root frame of the Phone Application.
</summary>
<returns>The root frame of the Phone Application.</returns>
public static <API key> RootFrame { get; private set; }
<summary>
Gets the current application.
</summary>
public new static App Current
{
get
{
return (App)Application.Current;
}
}
<summary>
Constructor for the Application object.
</summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += <API key>;
// Standard XAML initialization
InitializeComponent();
// Phone-specific initialization
<API key>();
// Language display initialization
InitializeLanguage();
// Show graphics profiling information while debugging.
if (Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.<API key> = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are handed off to GPU with a colored overlay.
//Application.Current.Host.Settings.<API key> = true;
// Prevent the screen from turning off while under the debugger by disabling
// the application's idle detection.
// Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
// and consume battery power when the user is not using the phone.
<API key>.Current.<API key> = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void <API key>(object sender, LaunchingEventArgs e)
{
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void <API key>(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void <API key>(object sender, <API key> e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void <API key>(object sender, <API key> e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void <API key>(object sender, <API key> e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
#region Phone application initialization
// Avoid <API key>
private bool <API key> = false;
// Do not add any additional code to this method
private void <API key>()
{
if (<API key>)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new <API key>();
RootFrame.Navigated += <API key>;
// Assign the URI-mapper class to the application frame.
// This is required if you want to handle incoming responses from Credit Card Terminal
RootFrame.UriMapper = new ProtocolUriMapper();
// Handle navigation failures
RootFrame.NavigationFailed += <API key>;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += <API key>;
// Ensure we don't initialize again
<API key> = true;
}
// Do not add any additional code to this method
private void <API key>(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= <API key>;
}
private void <API key>(object sender, NavigationEventArgs e)
{
// If the app has received a 'reset' navigation, then we need to check
// on the next navigation to see if the page stack should be reset
if (e.NavigationMode == NavigationMode.Reset)
RootFrame.Navigated += <API key>;
}
private void <API key>(object sender, NavigationEventArgs e)
{
// Unregister the event so it doesn't get called again
RootFrame.Navigated -= <API key>;
// Only clear the stack for 'new' (forward) and 'refresh' navigations
if (e.NavigationMode != NavigationMode.New && e.NavigationMode != NavigationMode.Refresh)
return;
// For UI consistency, clear the entire page stack
while (RootFrame.RemoveBackEntry() != null)
{
; // do nothing
}
}
#endregion
// Initialize the app's font and flow direction as defined in its localized resource strings.
// To ensure that the font of your application is aligned with its supported languages and that the
// FlowDirection for each of those languages follows its traditional direction, ResourceLanguage
// and <API key> should be initialized in each resx file to match these values with that
// file's culture. For example:
// AppResources.es-ES.resx
// ResourceLanguage's value should be "es-ES"
// <API key>'s value should be "LeftToRight"
// AppResources.ar-SA.resx
// ResourceLanguage's value should be "ar-SA"
// <API key>'s value should be "RightToLeft"
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the <API key> resource string for each
// supported language.
// If a compiler error is hit then <API key> is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.<API key>);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or <API key> is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
public void HandleResponse(Uri responseUri)
{
ChargeResponse response;
try
{
// Creating the ChargeResponse object will throw an exception
// if there's a problem with the response URL parameters
response = new ChargeResponse(responseUri);
}
catch (ChargeException ex)
{
// In the event the parsing fails, we will throw an exception
// and you should handle the error.
ShowMessage(ex.Message);
return;
}
// You may want to perform different actions based on the
// response code. This example shows an message dialog with
// the response data when the charge is approved.
if (response.ResponseCode == ChargeResponse.Code.APPROVED)
{
// Any extra params we included with the return URL can be
// queried from the ExtraParams dictionary.
string recordId;
response.ExtraParams.TryGetValue("record_id", out recordId);
// The URL is a public attack vector for the app, so it's
// important to validate any parameters.
if (!this.IsValidRecordId(recordId))
{
ShowMessage("Invalid Record ID");
return;
}
string message = String.Format(
CultureInfo.CurrentCulture,
"Charged!\n" +
"Record: {0}\n" +
"Transaction ID: {1}\n" +
"Amount: {2} {3}\n" +
"Card Type: {4}\n" +
"Redacted Number: {5}",
recordId,
response.TransactionId,
response.Amount,
response.Currency,
response.CardType,
response.RedactedCardNumber);
// Generally you would do something app-specific here,
// like load the record specified by recordId, record the
// success or failure, etc. Since this sample doesn't
// actually do much, we'll just pop a message dialog.
ShowMessage(message);
}
else // other response code values are documented in ChargeResponse.cs
{
string recordId;
response.ExtraParams.TryGetValue("record_id", out recordId);
string message = String.Format(
CultureInfo.CurrentCulture,
"Not Charged!\n" +
"Record: {0}",
recordId);
ShowMessage(message);
}
}
private bool IsValidRecordId(string recordId)
{
return null != recordId && RecordIdPattern.Match(recordId).Success;
}
private void ShowMessage(string message)
{
if (!Guide.IsVisible)
{
// Show message dialog
Guide.BeginShowMessageBox(
"Credit Card Terminal",
message,
new string[] { "ok" },
0,
MessageBoxIcon.None,
null,
null);
}
}
}
} |
-- phpMyAdmin SQL Dump
-- version 4.1.6
-- http:
-- Client : localhost
-- Version du serveur : 5.6.15
-- Version de PHP : 5.3.28
SET time_zone = "+00:00";
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET @<API key>=@@<API key> */;
/*!40101 SET NAMES utf8 */;
-- Structure de la table `article`
CREATE TABLE IF NOT EXISTS `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`categorie_id` int(11) DEFAULT NULL,
`thread_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`titre` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`content` longtext COLLATE utf8_unicode_ci NOT NULL,
`urlAlias` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`dateModif` date NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `<API key>` (`urlAlias`),
UNIQUE KEY `<API key>` (`thread_id`),
KEY `<API key>` (`categorie_id`),
KEY `<API key>` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=15 ;
-- Contenu de la table `article`
INSERT INTO `article` (`id`, `categorie_id`, `thread_id`, `user_id`, `titre`, `content`, `urlAlias`, `dateModif`) VALUES
(1, 1, 'Titre1', 1, 'Titre 1', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre1', '2014-03-23'),
(2, 5, 'Titre2', 1, 'Titre 2', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre2', '2014-03-24'),
(3, 3, 'Titre3', 1, 'Titre 3', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre3', '2014-03-24'),
(4, 2, 'Titre4', 1, 'Titre 4', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre4', '2014-03-24'),
(5, 3, 'Titre5', 1, 'Titre 5', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre5', '2014-03-24'),
(6, 4, 'Titre6', 1, 'Titre 6', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre6', '2014-03-24'),
(7, 3, 'Titre7', 1, 'Titre 7', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre7', '2014-03-24'),
(8, 4, 'Titre8', 1, 'Titre 8', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre8', '2014-03-24'),
(10, 4, 'Titre10', 1, 'Titre 10', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre10', '2014-03-24'),
(11, 2, 'Titre11', 1, 'Titre 11', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rhoncus quam lectus, eget accumsan mauris feugiat sit amet. Nullam scelerisque nec magna vitae cursus. Suspendisse fermentum tempor blandit. Donec convallis vel augue sollicitudin cursus. Mauris id pretium nunc, eu cursus lectus. Cras at condimentum urna, imperdiet porttitor est. In volutpat congue ligula ac varius. Proin euismod ac lectus vitae mollis.', 'Titre11', '2014-03-24'),
(12, 4, 'Titre12', 2, 'Titre 12', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec est a nisi vehicula consequat. Ut vehicula neque tincidunt rhoncus tristique. Nullam fringilla augue vitae imperdiet fermentum. Quisque aliquam est eget urna semper venenatis. Mauris rhoncus egestas erat, eget malesuada risus eleifend sed.', 'Titre12', '2014-04-07'),
(13, 5, 'Titre13', 2, 'Titre 13', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nec est a nisi vehicula consequat. Ut vehicula neque tincidunt rhoncus tristique. Nullam fringilla augue vitae imperdiet fermentum. Quisque aliquam est eget urna semper venenatis. Mauris rhoncus egestas erat, eget malesuada risus eleifend sed. test', 'Titre13', '2014-04-07');
-- Structure de la table `categorie`
CREATE TABLE IF NOT EXISTS `categorie` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `<API key>` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
-- Contenu de la table `categorie`
INSERT INTO `categorie` (`id`, `name`) VALUES
(1, 'Default'),
(5, 'Friends Of Symfony'),
(4, 'NodeJs'),
(2, 'SEO'),
(3, 'Symfony');
-- Structure de la table `comment`
CREATE TABLE IF NOT EXISTS `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`thread_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`author_id` int(11) DEFAULT NULL,
`body` longtext COLLATE utf8_unicode_ci NOT NULL,
`ancestors` varchar(1024) COLLATE utf8_unicode_ci NOT NULL,
`depth` int(11) NOT NULL,
`created_at` datetime NOT NULL,
`state` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `<API key>` (`thread_id`),
KEY `<API key>` (`author_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=9 ;
-- Contenu de la table `comment`
INSERT INTO `comment` (`id`, `thread_id`, `author_id`, `body`, `ancestors`, `depth`, `created_at`, `state`) VALUES
(1, 'Titre1', NULL, 'Commentaire numero 1', '', 0, '2014-03-24 13:00:44', 0),
(2, 'Titre1', NULL, 'commentaire numero 2', '', 0, '2014-03-29 19:43:26', 0),
(3, 'Titre1', 1, 'réponse au commentaire 1', '1', 1, '2014-03-29 19:45:00', 0),
(4, 'Titre2', NULL, 'coucou la galerie', '', 0, '2014-04-01 03:20:24', 0),
(5, 'Titre2', NULL, 'salut la companie', '', 0, '2014-04-01 03:20:48', 0),
(6, 'Titre2', NULL, 'please leave a message', '', 0, '2014-04-01 03:22:01', 0),
(7, 'Titre1', NULL, 'reponse de la reponse a admin', '1/3', 2, '2014-04-06 21:13:07', 0),
(8, 'Titre1', NULL, 'tata toto tutu', '', 0, '2014-04-06 21:13:39', 0);
-- Structure de la table `thread`
CREATE TABLE IF NOT EXISTS `thread` (
`id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`article_id` int(11) DEFAULT NULL,
`permalink` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`is_commentable` tinyint(1) NOT NULL,
`num_comments` int(11) NOT NULL,
`last_comment_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `<API key>` (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- Contenu de la table `thread`
INSERT INTO `thread` (`id`, `article_id`, `permalink`, `is_commentable`, `num_comments`, `last_comment_at`) VALUES
('Titre1', NULL, 'Titre1', 1, 5, '2014-04-06 21:13:39'),
('Titre10', NULL, 'Titre10', 1, 0, NULL),
('Titre11', NULL, 'Titre11', 1, 0, NULL),
('Titre12', NULL, 'Titre12', 1, 0, NULL),
('Titre13', NULL, 'Titre13', 1, 0, NULL),
('Titre2', NULL, 'Titre2', 1, 3, '2014-04-01 03:22:01'),
('Titre3', NULL, 'Titre3', 1, 0, NULL),
('Titre4', NULL, 'Titre4', 1, 0, NULL),
('Titre5', NULL, 'Titre5', 1, 0, NULL),
('Titre6', NULL, 'Titre6', 1, 0, NULL),
('Titre7', NULL, 'Titre7', 1, 0, NULL),
('Titre8', NULL, 'Titre8', 1, 0, NULL);
-- Structure de la table `user`
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`username_canonical` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`email_canonical` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`enabled` tinyint(1) NOT NULL,
`salt` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`last_login` datetime DEFAULT NULL,
`locked` tinyint(1) NOT NULL,
`expired` tinyint(1) NOT NULL,
`expires_at` datetime DEFAULT NULL,
`confirmation_token` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`<API key>` datetime DEFAULT NULL,
`roles` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:array)',
`credentials_expired` tinyint(1) NOT NULL,
`<API key>` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `<API key>` (`username_canonical`),
UNIQUE KEY `<API key>` (`email_canonical`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;
-- Contenu de la table `user`
INSERT INTO `user` (`id`, `username`, `username_canonical`, `email`, `email_canonical`, `enabled`, `salt`, `password`, `last_login`, `locked`, `expired`, `expires_at`, `confirmation_token`, `<API key>`, `roles`, `credentials_expired`, `<API key>`) VALUES
(1, 'admin', 'admin', 'admin@admin.fr', 'admin@admin.fr', 1, '<API key>', 'X7/<API key>+<API key>/<API key>==', '2014-04-07 05:29:55', 0, 0, NULL, NULL, NULL, 'a:1:{i:0;s:10:"ROLE_ADMIN";}', 0, NULL),
(2, 'dejonghe91', 'dejonghe91', 'dejonghe91@gmail.com', 'dejonghe91@gmail.com', 1, '<API key>', 'wbPJ7yJI3ryf/<API key>==', '2014-04-07 16:11:08', 0, 0, NULL, NULL, NULL, 'a:0:{}', 0, NULL);
-- Contraintes pour la table `article`
ALTER TABLE `article`
ADD CONSTRAINT `FK_CD8737FAA76ED395` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
ADD CONSTRAINT `FK_CD8737FABCF5E72D` FOREIGN KEY (`categorie_id`) REFERENCES `categorie` (`id`),
ADD CONSTRAINT `FK_CD8737FAE2904019` FOREIGN KEY (`thread_id`) REFERENCES `thread` (`id`);
-- Contraintes pour la table `comment`
ALTER TABLE `comment`
ADD CONSTRAINT `FK_5BC96BF0E2904019` FOREIGN KEY (`thread_id`) REFERENCES `thread` (`id`),
ADD CONSTRAINT `FK_5BC96BF0F675F31B` FOREIGN KEY (`author_id`) REFERENCES `user` (`id`);
-- Contraintes pour la table `thread`
ALTER TABLE `thread`
ADD CONSTRAINT `FK_368C49B57294869C` FOREIGN KEY (`article_id`) REFERENCES `article` (`id`);
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */;
/*!40101 SET <API key>=@<API key> */; |
author: robmyers
comments: true
date: 2006-07-03 09:39:25+00:00
layout: post
slug: i-heart-my-roomba
title: I Heart My Roomba
wordpress_id: 1019
categories:
- Personal
- Reviews

I like my [roomba](http://store.irobot.com/product/index.jsp?productId=2172860). It actually works. Occasionally it gets stuck under the sofa, but that's only because I don't use the light barrier thing. The kids are a lot happier tidying their rooms for the robot to vacuum than for me to vacuum.
There was an old Isaac Asimov story about the introduction of humanoid robots. People couldn't handle them, so the company scaled back to selling little fruit-fly catching autonomous flyers and other obviously beneficial non-threatening devices to socially engineer attitudes towards robots. I think that the roomba is just such a project. iRobot, the manufacturer, also make military robots. |
package org.crossfit.app.web.rest.dto;
import java.util.ArrayList;
import java.util.List;
import org.crossfit.app.domain.TimeSlot;
import org.crossfit.app.domain.TimeSlotType;
import org.crossfit.app.domain.util.<API key>;
import org.crossfit.app.domain.util.<API key>;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDate;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
public class TimeSlotInstanceDTO {
private DateTime date;
private TimeSlot slot;
private List<BookingDTO> bookings = new ArrayList<>();
private <API key> timeSlotStatus;
private int totalBooking;
public TimeSlotInstanceDTO(DateTime date, TimeSlot slot) {
super();
this.date = date;
this.slot = slot;
}
public Long getId() {
return slot.getId();
}
public String getName() {
return slot.getName();
}
@JsonDeserialize(using = <API key>.class)
public LocalDate getDate() {
return date.toLocalDate();
}
@JsonSerialize(using = <API key>.class)
public DateTime getStart() {
return date.withTime(slot.getStartTime().getHourOfDay(), slot.getStartTime().getMinuteOfHour(), 0, 0);
}
@JsonSerialize(using = <API key>.class)
public DateTime getEnd() {
DateTime returnDate = date.withTime(slot.getEndTime().getHourOfDay(), slot.getEndTime().getMinuteOfHour(), 0, 0);
if (returnDate.isBefore(getStart())){
returnDate = returnDate.plusDays(1);
}
return returnDate;
}
public Integer getMaxAttendees() {
return slot.getMaxAttendees();
}
public TimeSlotType getTimeSlotType() {
return slot.getTimeSlotType();
}
public List<BookingDTO> getBookings() {
return bookings;
}
public void setBookings(List<BookingDTO> bookings) {
this.bookings = bookings;
this.totalBooking = this.bookings.size();
}
/*
public void setBookings(List<Booking> bookings) {
this.bookings = bookings.stream().map(b->{
Subscription s = new Subscription();
s.setId(b.getSubscription().getId());
s.setMember(b.getSubscription().getMember());
Membership membership = new Membership();
membership.setName(b.getSubscription().getMembership().getName());
s.setMembership(membership);
BookingDTO dto = new BookingDTO(b.getId(), b.getStartAt().toLocalDate(), b.getStatus(), slot, s);
return dto;
}).collect(Collectors.toList());
this.totalBooking = this.bookings.size();
}
*/
public <API key> getTimeSlotStatus() {
return timeSlotStatus;
}
public void setTimeSlotStatus(<API key> timeSlotStatus) {
this.timeSlotStatus = timeSlotStatus;
}
public int getTotalBooking() {
return totalBooking;
}
public void setTotalBooking(int totalBooking) {
this.totalBooking = totalBooking;
}
public boolean isPast(){
return getStart().isBeforeNow();
}
@Override
public String toString() {
return "[" + getStart() + "->" + getEnd() + "]";
}
public boolean equalsDate(DateTime start, DateTime end) {
return this.getStart().equals(start) && this.getEnd().equals(end);
}
} |
package com.puzzletimer.parsers;
import java.util.HashMap;
public class <API key> {
private ScrambleParser[] scrambleParsers;
private HashMap<String, ScrambleParser> scrambleParserMap;
public <API key>() {
this.scrambleParsers = new ScrambleParser[] {
new EmptyScrambleParser(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
new SkewbScrambleParser(),
new <API key>(),
new <API key>(),
new <API key>(),
new <API key>(),
};
this.scrambleParserMap = new HashMap<String, ScrambleParser>();
for (ScrambleParser scrambleParser : this.scrambleParsers) {
this.scrambleParserMap.put(scrambleParser.getPuzzleId(), scrambleParser);
}
}
public ScrambleParser get(String puzzleId) {
return this.scrambleParserMap.get(puzzleId);
}
} |
module Assembler.Types where
import Data.Word
-- Constant is either an int or a label which resolves to an int
type Label = String
type Constant = Either Int Label
type RegId = Word8
data Instr = Halt
| Nop
| Rrmovl RegId RegId
| Irmovl RegId Constant
| Rmmovl RegId RegId Int
| Mrmovl RegId RegId Int
| Addl RegId RegId
| Subl RegId RegId
| Andl RegId RegId
| Xorl RegId RegId
| Jmp Label
| Jle Label
| Jl Label
| Je Label
| Jne Label
| Jge Label
| Jg Label
| Cmovle RegId RegId
| Cmovl RegId RegId
| Cmove RegId RegId
| Cmovne RegId RegId
| Cmovge RegId RegId
| Cmovg RegId RegId
| Call Label
| Ret
| Pushl RegId
| Popl RegId
deriving Show
data Entity = Instr (Instr, Int)
| Directive (String, Int)
| Label Label
deriving Show |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AltTabHelperV2
{
using System.Runtime.InteropServices;
using HWND = IntPtr;
<summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
public static int GetZOrder(IntPtr hWnd, GetWindowParameters parm = GetWindowParameters.GW_HWNDPREV)
{
var z = 0;
for (var h = hWnd; h != IntPtr.Zero; h = GetWindow(h, (int) parm)) z++;
return z;
}
private const int <API key> = 0x0400;
private const int PROCESS_VM_READ = 0x0010;
public static int[] GetZOrder(params IntPtr[] hWnds)
{
var z = new int[hWnds.Length];
for (var i = 0; i < hWnds.Length; i++) z[i] = -1;
var index = 0;
var numRemaining = hWnds.Length;
EnumWindows((wnd, param) =>
{
var searchIndex = Array.IndexOf(hWnds, wnd);
if (searchIndex != -1)
{
z[searchIndex] = index;
numRemaining
if (numRemaining == 0) return false;
}
index++;
return true;
}, 0);
return z;
}
public static List<HWND> GetAllOpenWindows()
{
var shellWindow = GetShellWindow();
var windowList = new List<HWND>();
EnumWindows(delegate (HWND hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
if (GetWindowTextLength(hWnd) == 0) return true;
windowList.Add(hWnd);
return true;
}, 0);
return windowList;
}
public static List<HWND> <API key>()
{
var shellWindow = GetShellWindow();
var windowList = new List<HWND>();
var currentProcess = <API key>();
var processNameBuilder = new StringBuilder(1000);
EnumWindows(delegate (HWND hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
if (GetWindowTextLength(hWnd) == 0) return true;
var processName = GetModuleFileName(hWnd, processNameBuilder);
if (processName == currentProcess)
{
windowList.Add(hWnd);
}
return true;
}, 0);
return windowList;
}
public static List<IntPtr> <API key>()
{
var shellWindow = GetShellWindow();
var windowList = new List<IntPtr>();
EnumWindows(delegate (IntPtr hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
if (GetWindowTextLength(hWnd) == 0) return true;
if (IsZoomed(hWnd)) return true;
if (IsIconic(hWnd)) return true;
windowList.Add(hWnd);
return true;
}, 0);
return windowList;
}
public static string GetProcessInfo(IntPtr hWnd)
{
uint pid;
<API key>(hWnd, out pid);
var length = GetWindowTextLength(hWnd);
var output = new StringBuilder(1000);
var output2 = new StringBuilder(1000);
GetWindowText(hWnd, output, length + 1);
var zOrder = GetZOrder(hWnd);
var desktop = "";
try {
desktop = GetWindowDesktopId(hWnd).ToString(); ;
}catch(Exception) { }
var isMaximized = IsZoomed(hWnd);
return String.Format("zIndex: {5} - virtualDesktopGuid: {6} - hWnd: {0} - pid: {1} - exe: {2} - {3} {4}",
hWnd.ToInt64(), pid, GetModuleFileName(hWnd, output2),
output,
isMaximized ? " MAXIMIZED" : "",
zOrder,
desktop
);
}
public static Guid? GetWindowDesktopId(HWND hWnd)
{
var blah = new <API key>();
return blah.GetWindowDesktopId(hWnd);
}
private static string GetModuleFileName(HWND hWnd, StringBuilder processNameBuilder)
{
uint pid;
<API key>(hWnd, out pid);
var newHandle = OpenProcess(<API key> | PROCESS_VM_READ, false, pid);
processNameBuilder.Clear();
GetModuleFileNameEx(newHandle, IntPtr.Zero, processNameBuilder, processNameBuilder.Capacity);
CloseHandle(newHandle);
return processNameBuilder.ToString();
}
private static string <API key>()
{
return <API key>(GetCurrentPid());
}
private static string <API key>(uint pid)
{
var maxSize = 1000;
var output = new StringBuilder(maxSize);
var newHandle = OpenProcess(<API key> | PROCESS_VM_READ, false, pid);
GetModuleFileNameEx(newHandle, IntPtr.Zero, output, output.Capacity);
CloseHandle(newHandle);
return output.ToString();
}
private static uint GetCurrentPid()
{
var windowInForeground = GetForegroundWindow();
uint pid;
var result = <API key>(windowInForeground, out pid);
return pid;
}
private delegate bool EnumWindowsProc(HWND hWnd, int lParam);
public enum GetWindowParameters
{
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6,
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4
}
[DllImport("USER32.DLL")]
public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern int GetWindowTextLength(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern bool IsWindowVisible(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern IntPtr GetShellWindow();
[DllImport("psapi.dll")]
private static extern uint GetModuleBaseName(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
[DllImport("psapi.dll")]
private static extern uint GetModuleFileNameEx(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
[DllImport("psapi.dll")]
private static extern uint <API key>(IntPtr hWnd, StringBuilder lpFileName, int nSize);
// Retrieves the identifier of the thread that created the specified window and, optionally, the identifier of the process that created the window.
[DllImport("user32.dll", SetLastError = true)]
public static extern uint <API key>(IntPtr hWnd, out uint processId);
[DllImport("Kernel32.dll")]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint pid);
[DllImport("Kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
// Retrieves a handle to the foreground window (the window with which the user is currently working). The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads.
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool ShowWindowAsync(IntPtr windowHandle, int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, uint windowStyle);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
public static extern int SetActiveWindow(IntPtr hWnd);
// The return value is the handle to the active window attached to the calling thread's message queue. Otherwise, the return value is NULL.
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
public static extern bool IsIconic(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern bool IsZoomed(IntPtr hwnd);
public enum ShowWindowEnum
{
Hide = 0,
ShowNormal = 1, ShowMinimized = 2, ShowMaximized = 3,
Maximize = 3, <API key> = 4, Show = 5,
Minimize = 6, ShowMinNoActivate = 7, ShowNoActivate = 8,
Restore = 9, ShowDefault = 10, ForceMinimized = 11
};
}
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HCI Project Portfolio</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</head>
<body>
<div class="navigationbar">
<div class="navigation">
<div class="<API key>">
<div class="myimage">
<img class="profileimg" src="me.png"></img>
</div>
<img id="homebutton" src="/Home.png"/> <a class="navigationlink" style="text-decoration:none" href="/">Home</a>
<a class="navigationlink" style="text-decoration:none" href="scoop.html">Scoop App</a>
<a class="navigationlink" style="text-decoration:none" href="firefly.html">Firefly Smart Mirror</a>
<a class="navigationlink" style="text-decoration:none" href="safetypal.html">SafetyPal</a>
</div>
</div>
</div>
<div class="gallary">
<img class="projectImg" src="scoop/1.png">
<img class="projectImg" src="scoop/2.png">
<img class="projectImg" src="scoop/3.png">
</div>
<div class="projectContainer">
<div id="project1">
<p>Scoop is a dating application that has ambitious goals
in its matching algorithm.
I picked it up for fun and to learn some good design patterns.
It is an app originally founded by Thomas Rushing and my role
in his project is to extend it with features,
add necessary optimizations, and to make sure that it's even more
maintainable in the future.</p>
</div>
</div>
</body>
</html> |
package org.gete.android.dorongkotak;
import android.graphics.Canvas;
import android.util.Log;
import android.view.SurfaceHolder;
/**
* Kelas yang digunakan untuk menangani proses kecil
* @author Adnanto Ahmad Ramadhon
*
*/
public class PanelThread extends Thread {
private SurfaceHolder surfaceHolder;
private DrawingPanel drawingPanel;
private boolean run = false;
private Canvas canvas;
private static String TAG = "PanelThread";
public PanelThread(SurfaceHolder surfaceHolder, DrawingPanel drawingPanel) {
this.surfaceHolder = surfaceHolder;
this.drawingPanel = drawingPanel;
}
public void setRunning(boolean run) {
this.run = run;
}
@Override
public void run() {
super.run();
while (this.run) {
canvas = null;
try {
canvas = this.surfaceHolder.lockCanvas(null);
synchronized (this.surfaceHolder) {
drawingPanel.draw(canvas);
}
} catch (Exception e) {
Log.d(TAG, "run() is " + e.getMessage());
} finally {
if (canvas != null) {
this.surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
} |
import pickle
import unittest
import numpy as np
import scipy.sparse as sp
from sklearn import linear_model, datasets, metrics
from sklearn.base import clone
from sklearn.linear_model import SGDClassifier, SGDRegressor
from sklearn.preprocessing import LabelEncoder, scale, MinMaxScaler
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import <API key>
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_false, assert_true
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_less
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import <API key>
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import raises
class SparseSGDClassifier(SGDClassifier):
def fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return super(SparseSGDClassifier, self).fit(X, y, *args, **kw)
def partial_fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return super(SparseSGDClassifier, self).partial_fit(X, y, *args, **kw)
def decision_function(self, X):
X = sp.csr_matrix(X)
return super(SparseSGDClassifier, self).decision_function(X)
def predict_proba(self, X):
X = sp.csr_matrix(X)
return super(SparseSGDClassifier, self).predict_proba(X)
class SparseSGDRegressor(SGDRegressor):
def fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return SGDRegressor.fit(self, X, y, *args, **kw)
def partial_fit(self, X, y, *args, **kw):
X = sp.csr_matrix(X)
return SGDRegressor.partial_fit(self, X, y, *args, **kw)
def decision_function(self, X, *args, **kw):
X = sp.csr_matrix(X)
return SGDRegressor.decision_function(self, X, *args, **kw)
# Test Data
# test sample 1
X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])
Y = [1, 1, 1, 2, 2, 2]
T = np.array([[-1, -1], [2, 2], [3, 2]])
true_result = [1, 2, 2]
# test sample 2; string class labels
X2 = np.array([[-1, 1], [-0.75, 0.5], [-1.5, 1.5],
[1, 1], [0.75, 0.5], [1.5, 1.5],
[-1, -1], [0, -0.5], [1, -1]])
Y2 = ["one"] * 3 + ["two"] * 3 + ["three"] * 3
T2 = np.array([[-1.5, 0.5], [1, 2], [0, -2]])
true_result2 = ["one", "two", "three"]
# test sample 3
X3 = np.array([[1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 1],
[0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0]])
Y3 = np.array([1, 1, 1, 1, 2, 2, 2, 2])
# test sample 4 - two more or less redundant feature groups
X4 = np.array([[1, 0.9, 0.8, 0, 0, 0], [1, .84, .98, 0, 0, 0],
[1, .96, .88, 0, 0, 0], [1, .91, .99, 0, 0, 0],
[0, 0, 0, .89, .91, 1], [0, 0, 0, .79, .84, 1],
[0, 0, 0, .91, .95, 1], [0, 0, 0, .93, 1, 1]])
Y4 = np.array([1, 1, 1, 1, 2, 2, 2, 2])
iris = datasets.load_iris()
# test sample 5 - test sample 1 as binary classification problem
X5 = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])
Y5 = [1, 1, 1, 2, 2, 2]
true_result5 = [0, 1, 1]
# Classification Test Case
class CommonTest(object):
def factory(self, **kwargs):
if "random_state" not in kwargs:
kwargs["random_state"] = 42
return self.factory_class(**kwargs)
# a simple implementation of ASGD to use for testing
# uses squared loss to find the gradient
def asgd(self, X, y, eta, alpha, weight_init=None, intercept_init=0.0):
if weight_init is None:
weights = np.zeros(X.shape[1])
else:
weights = weight_init
average_weights = np.zeros(X.shape[1])
intercept = intercept_init
average_intercept = 0.0
decay = 1.0
# sparse data has a fixed decay of .01
if (isinstance(self, <API key>) or
isinstance(self, <API key>)):
decay = .01
for i, entry in enumerate(X):
p = np.dot(entry, weights)
p += intercept
gradient = p - y[i]
weights *= 1.0 - (eta * alpha)
weights += -(eta * gradient * entry)
intercept += -(eta * gradient) * decay
average_weights *= i
average_weights += weights
average_weights /= i + 1.0
average_intercept *= i
average_intercept += intercept
average_intercept /= i + 1.0
return average_weights, average_intercept
def _test_warm_start(self, X, Y, lr):
# Test that explicit warm restart...
clf = self.factory(alpha=0.01, eta0=0.01, n_iter=5, shuffle=False,
learning_rate=lr)
clf.fit(X, Y)
clf2 = self.factory(alpha=0.001, eta0=0.01, n_iter=5, shuffle=False,
learning_rate=lr)
clf2.fit(X, Y,
coef_init=clf.coef_.copy(),
intercept_init=clf.intercept_.copy())
# ... and implicit warm restart are equivalent.
clf3 = self.factory(alpha=0.01, eta0=0.01, n_iter=5, shuffle=False,
warm_start=True, learning_rate=lr)
clf3.fit(X, Y)
assert_equal(clf3.t_, clf.t_)
<API key>(clf3.coef_, clf.coef_)
clf3.set_params(alpha=0.001)
clf3.fit(X, Y)
assert_equal(clf3.t_, clf2.t_)
<API key>(clf3.coef_, clf2.coef_)
def <API key>(self):
self._test_warm_start(X, Y, "constant")
def <API key>(self):
self._test_warm_start(X, Y, "invscaling")
def <API key>(self):
self._test_warm_start(X, Y, "optimal")
def test_input_format(self):
# Input format tests.
clf = self.factory(alpha=0.01, n_iter=5,
shuffle=False)
clf.fit(X, Y)
Y_ = np.array(Y)[:, np.newaxis]
Y_ = np.c_[Y_, Y_]
assert_raises(ValueError, clf.fit, X, Y_)
def test_clone(self):
# Test whether clone works ok.
clf = self.factory(alpha=0.01, n_iter=5, penalty='l1')
clf = clone(clf)
clf.set_params(penalty='l2')
clf.fit(X, Y)
clf2 = self.factory(alpha=0.01, n_iter=5, penalty='l2')
clf2.fit(X, Y)
assert_array_equal(clf.coef_, clf2.coef_)
def <API key>(self):
clf = self.factory(average=True, eta0=.01)
clf.fit(X, Y)
assert_true(hasattr(clf, 'average_coef_'))
assert_true(hasattr(clf, 'average_intercept_'))
assert_true(hasattr(clf, 'standard_intercept_'))
assert_true(hasattr(clf, 'standard_coef_'))
clf = self.factory()
clf.fit(X, Y)
assert_false(hasattr(clf, 'average_coef_'))
assert_false(hasattr(clf, 'average_intercept_'))
assert_false(hasattr(clf, 'standard_intercept_'))
assert_false(hasattr(clf, 'standard_coef_'))
def <API key>(self):
clf1 = self.factory(average=600)
clf2 = self.factory()
for _ in range(100):
if isinstance(clf1, SGDClassifier):
clf1.partial_fit(X, Y, classes=np.unique(Y))
clf2.partial_fit(X, Y, classes=np.unique(Y))
else:
clf1.partial_fit(X, Y)
clf2.partial_fit(X, Y)
<API key>(clf1.coef_, clf2.coef_, decimal=16)
assert_almost_equal(clf1.intercept_, clf2.intercept_, decimal=16)
def <API key>(self):
eta0 = .001
alpha = .0001
Y_encode = np.array(Y)
Y_encode[Y_encode == 1] = -1.0
Y_encode[Y_encode == 2] = 1.0
clf1 = self.factory(average=7, learning_rate="constant",
loss='squared_loss', eta0=eta0,
alpha=alpha, n_iter=2, shuffle=False)
clf2 = self.factory(average=0, learning_rate="constant",
loss='squared_loss', eta0=eta0,
alpha=alpha, n_iter=1, shuffle=False)
clf1.fit(X, Y_encode)
clf2.fit(X, Y_encode)
average_weights, average_intercept = \
self.asgd(X, Y_encode, eta0, alpha,
weight_init=clf2.coef_.ravel(),
intercept_init=clf2.intercept_)
<API key>(clf1.coef_.ravel(),
average_weights.ravel(),
decimal=16)
assert_almost_equal(clf1.intercept_, average_intercept, decimal=16)
@raises(ValueError)
def <API key>(self):
# Check whether expected ValueError on bad alpha, i.e. 0
# since alpha is used to compute the optimal learning rate
self.factory(alpha=0, learning_rate="optimal")
class <API key>(unittest.TestCase, CommonTest):
"""Test suite for the dense representation variant of SGD"""
factory_class = SGDClassifier
def test_sgd(self):
# Check that SGD gives any results :-)
for loss in ("hinge", "squared_hinge", "log", "modified_huber"):
clf = self.factory(penalty='l2', alpha=0.01, fit_intercept=True,
loss=loss, n_iter=10, shuffle=True)
clf.fit(X, Y)
# assert_almost_equal(clf.coef_[0], clf.coef_[1], decimal=7)
assert_array_equal(clf.predict(T), true_result)
@raises(ValueError)
def <API key>(self):
# Check whether expected ValueError on bad l1_ratio
self.factory(l1_ratio=1.1)
@raises(ValueError)
def <API key>(self):
# Check whether expected ValueError on bad learning_rate
self.factory(learning_rate="<unknown>")
@raises(ValueError)
def test_sgd_bad_eta0(self):
# Check whether expected ValueError on bad eta0
self.factory(eta0=0, learning_rate="constant")
@raises(ValueError)
def test_sgd_bad_alpha(self):
# Check whether expected ValueError on bad alpha
self.factory(alpha=-.1)
@raises(ValueError)
def <API key>(self):
# Check whether expected ValueError on bad penalty
self.factory(penalty='foobar', l1_ratio=0.85)
@raises(ValueError)
def test_sgd_bad_loss(self):
# Check whether expected ValueError on bad loss
self.factory(loss="foobar")
@raises(ValueError)
def <API key>(self):
# Test parameter validity check
self.factory(n_iter=-10000)
@raises(ValueError)
def <API key>(self):
# Test parameter validity check
self.factory(shuffle="false")
@raises(TypeError)
def test_argument_coef(self):
# Checks coef_init not allowed as model argument (only fit)
# Provided coef_ does not match dataset.
self.factory(coef_init=np.zeros((3,))).fit(X, Y)
@raises(ValueError)
def test_provide_coef(self):
# Checks coef_init shape for the warm starts
# Provided coef_ does not match dataset.
self.factory().fit(X, Y, coef_init=np.zeros((3,)))
@raises(ValueError)
def test_set_intercept(self):
# Checks intercept_ shape for the warm starts
# Provided intercept_ does not match dataset.
self.factory().fit(X, Y, intercept_init=np.zeros((3,)))
def <API key>(self):
# Checks intercept_ shape for the warm starts in binary case
self.factory().fit(X5, Y5, intercept_init=0)
def <API key>(self):
# Checks the SGDClassifier correctly computes the average weights
eta = .1
alpha = 2.
n_samples = 20
n_features = 10
rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features))
w = rng.normal(size=n_features)
clf = self.factory(loss='squared_loss',
learning_rate='constant',
eta0=eta, alpha=alpha,
fit_intercept=True,
n_iter=1, average=True, shuffle=False)
# simple linear function without noise
y = np.dot(X, w)
y = np.sign(y)
clf.fit(X, y)
average_weights, average_intercept = self.asgd(X, y, eta, alpha)
average_weights = average_weights.reshape(1, -1)
<API key>(clf.coef_,
average_weights,
decimal=14)
assert_almost_equal(clf.intercept_, average_intercept, decimal=14)
def <API key>(self):
# Checks intercept_ shape consistency for the warm starts
# Inconsistent intercept_ shape.
clf = self.factory().fit(X5, Y5)
self.factory().fit(X5, Y5, intercept_init=clf.intercept_)
clf = self.factory().fit(X, Y)
self.factory().fit(X, Y, intercept_init=clf.intercept_)
@raises(ValueError)
def <API key>(self):
# Target must have at least two labels
self.factory(alpha=0.01, n_iter=20).fit(X2, np.ones(9))
def <API key>(self):
# partial_fit with class_weight='balanced' not supported"""
<API key>(ValueError,
"class_weight 'balanced' is not supported for "
"partial_fit. In order to use 'balanced' weights, "
"use <API key>\('balanced', classes, y\). "
"In place of y you can us a large enough sample "
"of the full training set target to properly "
"estimate the class frequency distributions. "
"Pass the resulting weights as the class_weight "
"parameter.",
self.factory(class_weight='balanced').partial_fit,
X, Y, classes=np.unique(Y))
def test_sgd_multiclass(self):
# Multi-class test case
clf = self.factory(alpha=0.01, n_iter=20).fit(X2, Y2)
assert_equal(clf.coef_.shape, (3, 2))
assert_equal(clf.intercept_.shape, (3,))
assert_equal(clf.decision_function([[0, 0]]).shape, (1, 3))
pred = clf.predict(T2)
assert_array_equal(pred, true_result2)
def <API key>(self):
eta = .001
alpha = .01
# Multi-class average test case
clf = self.factory(loss='squared_loss',
learning_rate='constant',
eta0=eta, alpha=alpha,
fit_intercept=True,
n_iter=1, average=True, shuffle=False)
np_Y2 = np.array(Y2)
clf.fit(X2, np_Y2)
classes = np.unique(np_Y2)
for i, cl in enumerate(classes):
y_i = np.ones(np_Y2.shape[0])
y_i[np_Y2 != cl] = -1
average_coef, average_intercept = self.asgd(X2, y_i, eta, alpha)
<API key>(average_coef, clf.coef_[i], decimal=16)
assert_almost_equal(average_intercept,
clf.intercept_[i],
decimal=16)
def <API key>(self):
# Multi-class test case
clf = self.factory(alpha=0.01, n_iter=20)
clf.fit(X2, Y2, coef_init=np.zeros((3, 2)),
intercept_init=np.zeros(3))
assert_equal(clf.coef_.shape, (3, 2))
assert_true(clf.intercept_.shape, (3,))
pred = clf.predict(T2)
assert_array_equal(pred, true_result2)
def <API key>(self):
# Multi-class test case with multi-core support
clf = self.factory(alpha=0.01, n_iter=20, n_jobs=2).fit(X2, Y2)
assert_equal(clf.coef_.shape, (3, 2))
assert_equal(clf.intercept_.shape, (3,))
assert_equal(clf.decision_function([[0, 0]]).shape, (1, 3))
pred = clf.predict(T2)
assert_array_equal(pred, true_result2)
def <API key>(self):
# Checks coef_init and intercept_init shape for for multi-class
# problems
# Provided coef_ does not match dataset
clf = self.factory()
assert_raises(ValueError, clf.fit, X2, Y2, coef_init=np.zeros((2, 2)))
# Provided coef_ does match dataset
clf = self.factory().fit(X2, Y2, coef_init=np.zeros((3, 2)))
# Provided intercept_ does not match dataset
clf = self.factory()
assert_raises(ValueError, clf.fit, X2, Y2,
intercept_init=np.zeros((1,)))
# Provided intercept_ does match dataset.
clf = self.factory().fit(X2, Y2, intercept_init=np.zeros((3,)))
def test_sgd_proba(self):
# Check SGD.predict_proba
# Hinge loss does not allow for conditional prob estimate.
# We cannot use the factory here, because it defines predict_proba
# anyway.
clf = SGDClassifier(loss="hinge", alpha=0.01, n_iter=10).fit(X, Y)
assert_false(hasattr(clf, "predict_proba"))
assert_false(hasattr(clf, "predict_log_proba"))
# log and modified_huber losses can output probability estimates
# binary case
for loss in ["log", "modified_huber"]:
clf = self.factory(loss="modified_huber", alpha=0.01, n_iter=10)
clf.fit(X, Y)
p = clf.predict_proba([[3, 2]])
assert_true(p[0, 1] > 0.5)
p = clf.predict_proba([[-1, -1]])
assert_true(p[0, 1] < 0.5)
p = clf.predict_log_proba([[3, 2]])
assert_true(p[0, 1] > p[0, 0])
p = clf.predict_log_proba([[-1, -1]])
assert_true(p[0, 1] < p[0, 0])
# log loss multiclass probability estimates
clf = self.factory(loss="log", alpha=0.01, n_iter=10).fit(X2, Y2)
d = clf.decision_function([[.1, -.1], [.3, .2]])
p = clf.predict_proba([[.1, -.1], [.3, .2]])
assert_array_equal(np.argmax(p, axis=1), np.argmax(d, axis=1))
assert_almost_equal(p[0].sum(), 1)
assert_true(np.all(p[0] >= 0))
p = clf.predict_proba([[-1, -1]])
d = clf.decision_function([[-1, -1]])
assert_array_equal(np.argsort(p[0]), np.argsort(d[0]))
l = clf.predict_log_proba([[3, 2]])
p = clf.predict_proba([[3, 2]])
<API key>(np.log(p), l)
l = clf.predict_log_proba([[-1, -1]])
p = clf.predict_proba([[-1, -1]])
<API key>(np.log(p), l)
# Modified Huber multiclass probability estimates; requires a separate
# test because the hard zero/one probabilities may destroy the
# ordering present in decision_function output.
clf = self.factory(loss="modified_huber", alpha=0.01, n_iter=10)
clf.fit(X2, Y2)
d = clf.decision_function([[3, 2]])
p = clf.predict_proba([[3, 2]])
if not isinstance(self, <API key>):
assert_equal(np.argmax(d, axis=1), np.argmax(p, axis=1))
else: # XXX the sparse test gets a different X2 (?)
assert_equal(np.argmin(d, axis=1), np.argmin(p, axis=1))
# the following sample produces decision_function values < -1,
# which would cause naive normalization to fail (see comment
# in SGDClassifier.predict_proba)
x = X.mean(axis=0)
d = clf.decision_function([x])
if np.all(d < -1): # XXX not true in sparse test case (why?)
p = clf.predict_proba([x])
<API key>(p[0], [1 / 3.] * 3)
def test_sgd_l1(self):
# Test L1 regularization
n = len(X4)
rng = np.random.RandomState(13)
idx = np.arange(n)
rng.shuffle(idx)
X = X4[idx, :]
Y = Y4[idx]
clf = self.factory(penalty='l1', alpha=.2, fit_intercept=False,
n_iter=2000, shuffle=False)
clf.fit(X, Y)
assert_array_equal(clf.coef_[0, 1:-1], np.zeros((4,)))
pred = clf.predict(X)
assert_array_equal(pred, Y)
# test sparsify with dense inputs
clf.sparsify()
assert_true(sp.issparse(clf.coef_))
pred = clf.predict(X)
assert_array_equal(pred, Y)
# pickle and unpickle with sparse coef_
clf = pickle.loads(pickle.dumps(clf))
assert_true(sp.issparse(clf.coef_))
pred = clf.predict(X)
assert_array_equal(pred, Y)
def test_class_weights(self):
# Test class weights.
X = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0],
[1.0, 1.0], [1.0, 0.0]])
y = [1, 1, 1, -1, -1]
clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False,
class_weight=None)
clf.fit(X, y)
assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1]))
# we give a small weights to class 1
clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False,
class_weight={1: 0.001})
clf.fit(X, y)
# now the hyperplane should rotate clock-wise and
# the prediction on this point should shift
assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1]))
def <API key>(self):
# Test if equal class weights approx. equals no class weights.
X = [[1, 0], [1, 0], [0, 1], [0, 1]]
y = [0, 0, 1, 1]
clf = self.factory(alpha=0.1, n_iter=1000, class_weight=None)
clf.fit(X, y)
X = [[1, 0], [0, 1]]
y = [0, 1]
clf_weighted = self.factory(alpha=0.1, n_iter=1000,
class_weight={0: 0.5, 1: 0.5})
clf_weighted.fit(X, y)
# should be similar up to some epsilon due to learning rate schedule
assert_almost_equal(clf.coef_, clf_weighted.coef_, decimal=2)
@raises(ValueError)
def <API key>(self):
# ValueError due to not existing class label.
clf = self.factory(alpha=0.1, n_iter=1000, class_weight={0: 0.5})
clf.fit(X, Y)
@raises(ValueError)
def <API key>(self):
# ValueError due to wrong class_weight argument type.
clf = self.factory(alpha=0.1, n_iter=1000, class_weight=[0.5])
clf.fit(X, Y)
def <API key>(self):
# Tests that class_weight and sample_weight are multiplicative
class_weights = {1: .6, 2: .3}
sample_weights = np.random.random(Y4.shape[0])
multiplied_together = np.copy(sample_weights)
multiplied_together[Y4 == 1] *= class_weights[1]
multiplied_together[Y4 == 2] *= class_weights[2]
clf1 = self.factory(alpha=0.1, n_iter=20, class_weight=class_weights)
clf2 = self.factory(alpha=0.1, n_iter=20)
clf1.fit(X4, Y4, sample_weight=sample_weights)
clf2.fit(X4, Y4, sample_weight=multiplied_together)
assert_almost_equal(clf1.coef_, clf2.coef_)
def <API key>(self):
# Test class weights for imbalanced data"""
# compute reference metrics on iris dataset that is quite balanced by
# default
X, y = iris.data, iris.target
X = scale(X)
idx = np.arange(X.shape[0])
rng = np.random.RandomState(6)
rng.shuffle(idx)
X = X[idx]
y = y[idx]
clf = self.factory(alpha=0.0001, n_iter=1000,
class_weight=None, shuffle=False).fit(X, y)
assert_almost_equal(metrics.f1_score(y, clf.predict(X), average='weighted'), 0.96,
decimal=1)
# make the same prediction using balanced class_weight
clf_balanced = self.factory(alpha=0.0001, n_iter=1000,
class_weight="balanced",
shuffle=False).fit(X, y)
assert_almost_equal(metrics.f1_score(y, clf_balanced.predict(X), average='weighted'), 0.96,
decimal=1)
# Make sure that in the balanced case it does not change anything
# to use "balanced"
<API key>(clf.coef_, clf_balanced.coef_, 6)
# build an very very imbalanced dataset out of iris data
X_0 = X[y == 0, :]
y_0 = y[y == 0]
X_imbalanced = np.vstack([X] + [X_0] * 10)
y_imbalanced = np.concatenate([y] + [y_0] * 10)
# fit a model on the imbalanced data without class weight info
clf = self.factory(n_iter=1000, class_weight=None, shuffle=False)
clf.fit(X_imbalanced, y_imbalanced)
y_pred = clf.predict(X)
assert_less(metrics.f1_score(y, y_pred, average='weighted'), 0.96)
# fit a model with balanced class_weight enabled
clf = self.factory(n_iter=1000, class_weight="balanced", shuffle=False)
clf.fit(X_imbalanced, y_imbalanced)
y_pred = clf.predict(X)
assert_greater(metrics.f1_score(y, y_pred, average='weighted'), 0.96)
# fit another using a fit parameter override
clf = self.factory(n_iter=1000, class_weight="balanced", shuffle=False)
clf.fit(X_imbalanced, y_imbalanced)
y_pred = clf.predict(X)
assert_greater(metrics.f1_score(y, y_pred, average='weighted'), 0.96)
def test_sample_weights(self):
# Test weights on individual samples
X = np.array([[-1.0, -1.0], [-1.0, 0], [-.8, -1.0],
[1.0, 1.0], [1.0, 0.0]])
y = [1, 1, 1, -1, -1]
clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False)
clf.fit(X, y)
assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1]))
# we give a small weights to class 1
clf.fit(X, y, sample_weight=[0.001] * 3 + [1] * 2)
# now the hyperplane should rotate clock-wise and
# the prediction on this point should shift
assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1]))
@raises(ValueError)
def <API key>(self):
# Test if ValueError is raised if sample_weight has wrong shape
clf = self.factory(alpha=0.1, n_iter=1000, fit_intercept=False)
# provided sample_weight too long
clf.fit(X, Y, sample_weight=np.arange(7))
@raises(ValueError)
def <API key>(self):
clf = self.factory(alpha=0.01)
# classes was not specified
clf.partial_fit(X3, Y3)
def <API key>(self):
third = X.shape[0]
clf = self.factory(alpha=0.01)
classes = np.unique(Y)
clf.partial_fit(X[:third], Y[:third], classes=classes)
assert_equal(clf.coef_.shape, (1, X.shape[1]))
assert_equal(clf.intercept_.shape, (1,))
assert_equal(clf.decision_function([[0, 0]]).shape, (1,))
id1 = id(clf.coef_.data)
clf.partial_fit(X[third:], Y[third:])
id2 = id(clf.coef_.data)
# check that coef_ haven't been re-allocated
assert_true(id1, id2)
y_pred = clf.predict(T)
assert_array_equal(y_pred, true_result)
def <API key>(self):
third = X2.shape[0]
clf = self.factory(alpha=0.01)
classes = np.unique(Y2)
clf.partial_fit(X2[:third], Y2[:third], classes=classes)
assert_equal(clf.coef_.shape, (3, X2.shape[1]))
assert_equal(clf.intercept_.shape, (3,))
assert_equal(clf.decision_function([[0, 0]]).shape, (1, 3))
id1 = id(clf.coef_.data)
clf.partial_fit(X2[third:], Y2[third:])
id2 = id(clf.coef_.data)
# check that coef_ haven't been re-allocated
assert_true(id1, id2)
def <API key>(self):
third = X2.shape[0]
clf = self.factory(alpha=0.01, average=X2.shape[0])
classes = np.unique(Y2)
clf.partial_fit(X2[:third], Y2[:third], classes=classes)
assert_equal(clf.coef_.shape, (3, X2.shape[1]))
assert_equal(clf.intercept_.shape, (3,))
clf.partial_fit(X2[third:], Y2[third:])
assert_equal(clf.coef_.shape, (3, X2.shape[1]))
assert_equal(clf.intercept_.shape, (3,))
def <API key>(self):
# Partial_fit should work after initial fit in the multiclass case.
# Non-regression test for #2496; fit would previously produce a
# Fortran-ordered coef_ that subsequent partial_fit couldn't handle.
clf = self.factory()
clf.fit(X2, Y2)
clf.partial_fit(X2, Y2) # no exception here
def <API key>(self, lr):
for X_, Y_, T_ in ((X, Y, T), (X2, Y2, T2)):
clf = self.factory(alpha=0.01, eta0=0.01, n_iter=2,
learning_rate=lr, shuffle=False)
clf.fit(X_, Y_)
y_pred = clf.decision_function(T_)
t = clf.t_
classes = np.unique(Y_)
clf = self.factory(alpha=0.01, eta0=0.01, learning_rate=lr,
shuffle=False)
for i in range(2):
clf.partial_fit(X_, Y_, classes=classes)
y_pred2 = clf.decision_function(T_)
assert_equal(clf.t_, t)
<API key>(y_pred, y_pred2, decimal=2)
def <API key>(self):
self.<API key>("constant")
def <API key>(self):
self.<API key>("optimal")
def <API key>(self):
self.<API key>("invscaling")
def <API key>(self):
clf = self.factory(alpha=0.01, learning_rate="constant",
eta0=0.1, loss="epsilon_insensitive")
clf.fit(X, Y)
assert_equal(1.0, np.mean(clf.predict(X) == Y))
clf = self.factory(alpha=0.01, learning_rate="constant",
eta0=0.1, loss="<API key>")
clf.fit(X, Y)
assert_equal(1.0, np.mean(clf.predict(X) == Y))
clf = self.factory(alpha=0.01, loss="huber")
clf.fit(X, Y)
assert_equal(1.0, np.mean(clf.predict(X) == Y))
clf = self.factory(alpha=0.01, learning_rate="constant", eta0=0.01,
loss="squared_loss")
clf.fit(X, Y)
assert_equal(1.0, np.mean(clf.predict(X) == Y))
def <API key>(self):
self._test_warm_start(X2, Y2, "optimal")
def test_multiple_fit(self):
# Test multiple calls of fit w/ different shaped inputs.
clf = self.factory(alpha=0.01, n_iter=5,
shuffle=False)
clf.fit(X, Y)
assert_true(hasattr(clf, "coef_"))
# Non-regression test: try fitting with a different label set.
y = [["ham", "spam"][i] for i in LabelEncoder().fit_transform(Y)]
clf.fit(X[:, :-1], y)
class <API key>(<API key>):
"""Run exactly the same tests using the sparse representation variant"""
factory_class = SparseSGDClassifier
# Regression Test Case
class <API key>(unittest.TestCase, CommonTest):
"""Test suite for the dense representation variant of SGD"""
factory_class = SGDRegressor
def test_sgd(self):
# Check that SGD gives any results.
clf = self.factory(alpha=0.1, n_iter=2,
fit_intercept=False)
clf.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
assert_equal(clf.coef_[0], clf.coef_[1])
@raises(ValueError)
def <API key>(self):
# Check whether expected ValueError on bad penalty
self.factory(penalty='foobar', l1_ratio=0.85)
@raises(ValueError)
def test_sgd_bad_loss(self):
# Check whether expected ValueError on bad loss
self.factory(loss="foobar")
def <API key>(self):
# Tests the average regressor matches the naive implementation
eta = .001
alpha = .01
n_samples = 20
n_features = 10
rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features))
w = rng.normal(size=n_features)
# simple linear function without noise
y = np.dot(X, w)
clf = self.factory(loss='squared_loss',
learning_rate='constant',
eta0=eta, alpha=alpha,
fit_intercept=True,
n_iter=1, average=True, shuffle=False)
clf.fit(X, y)
average_weights, average_intercept = self.asgd(X, y, eta, alpha)
<API key>(clf.coef_,
average_weights,
decimal=16)
assert_almost_equal(clf.intercept_, average_intercept, decimal=16)
def <API key>(self):
# Tests whether the partial fit yields the same average as the fit
eta = .001
alpha = .01
n_samples = 20
n_features = 10
rng = np.random.RandomState(0)
X = rng.normal(size=(n_samples, n_features))
w = rng.normal(size=n_features)
# simple linear function without noise
y = np.dot(X, w)
clf = self.factory(loss='squared_loss',
learning_rate='constant',
eta0=eta, alpha=alpha,
fit_intercept=True,
n_iter=1, average=True, shuffle=False)
clf.partial_fit(X[:int(n_samples / 2)][:], y[:int(n_samples / 2)])
clf.partial_fit(X[int(n_samples / 2):][:], y[int(n_samples / 2):])
average_weights, average_intercept = self.asgd(X, y, eta, alpha)
<API key>(clf.coef_,
average_weights,
decimal=16)
assert_almost_equal(clf.intercept_[0], average_intercept, decimal=16)
def test_average_sparse(self):
# Checks the average weights on data with 0s
eta = .001
alpha = .01
clf = self.factory(loss='squared_loss',
learning_rate='constant',
eta0=eta, alpha=alpha,
fit_intercept=True,
n_iter=1, average=True, shuffle=False)
n_samples = Y3.shape[0]
clf.partial_fit(X3[:int(n_samples / 2)][:], Y3[:int(n_samples / 2)])
clf.partial_fit(X3[int(n_samples / 2):][:], Y3[int(n_samples / 2):])
average_weights, average_intercept = self.asgd(X3, Y3, eta, alpha)
<API key>(clf.coef_,
average_weights,
decimal=16)
assert_almost_equal(clf.intercept_, average_intercept, decimal=16)
def <API key>(self):
xmin, xmax = -5, 5
n_samples = 100
rng = np.random.RandomState(0)
X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1)
# simple linear function without noise
y = 0.5 * X.ravel()
clf = self.factory(loss='squared_loss', alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_greater(score, 0.99)
# simple linear function with noise
y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel()
clf = self.factory(loss='squared_loss', alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_greater(score, 0.5)
def <API key>(self):
xmin, xmax = -5, 5
n_samples = 100
X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1)
# simple linear function without noise
y = 0.5 * X.ravel()
clf = self.factory(loss='epsilon_insensitive', epsilon=0.01,
alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_true(score > 0.99)
# simple linear function with noise
y = 0.5 * X.ravel() \
+ np.random.randn(n_samples, 1).ravel()
clf = self.factory(loss='epsilon_insensitive', epsilon=0.01,
alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_true(score > 0.5)
def test_sgd_huber_fit(self):
xmin, xmax = -5, 5
n_samples = 100
rng = np.random.RandomState(0)
X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1)
# simple linear function without noise
y = 0.5 * X.ravel()
clf = self.factory(loss="huber", epsilon=0.1, alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_greater(score, 0.99)
# simple linear function with noise
y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel()
clf = self.factory(loss="huber", epsilon=0.1, alpha=0.1, n_iter=20,
fit_intercept=False)
clf.fit(X, y)
score = clf.score(X, y)
assert_greater(score, 0.5)
def <API key>(self):
# Check that the SGD output is consistent with coordinate descent
n_samples, n_features = 1000, 5
rng = np.random.RandomState(0)
X = np.random.randn(n_samples, n_features)
# ground_truth linear model that generate y from X and to which the
# models should converge if the regularizer would be set to 0.0
ground_truth_coef = rng.randn(n_features)
y = np.dot(X, ground_truth_coef)
# XXX: alpha = 0.1 seems to cause convergence problems
for alpha in [0.01, 0.001]:
for l1_ratio in [0.5, 0.8, 1.0]:
cd = linear_model.ElasticNet(alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=False)
cd.fit(X, y)
sgd = self.factory(penalty='elasticnet', n_iter=50,
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=False)
sgd.fit(X, y)
err_msg = ("cd and sgd did not converge to comparable "
"results for alpha=%f and l1_ratio=%f"
% (alpha, l1_ratio))
assert_almost_equal(cd.coef_, sgd.coef_, decimal=2,
err_msg=err_msg)
@ignore_warnings
def test_partial_fit(self):
third = X.shape[0]
clf = self.factory(alpha=0.01)
clf.partial_fit(X[:third], Y[:third])
assert_equal(clf.coef_.shape, (X.shape[1],))
assert_equal(clf.intercept_.shape, (1,))
assert_equal(clf.predict([[0, 0]]).shape, (1,))
id1 = id(clf.coef_.data)
clf.partial_fit(X[third:], Y[third:])
id2 = id(clf.coef_.data)
# check that coef_ haven't been re-allocated
assert_true(id1, id2)
def <API key>(self, lr):
clf = self.factory(alpha=0.01, n_iter=2, eta0=0.01,
learning_rate=lr, shuffle=False)
clf.fit(X, Y)
y_pred = clf.predict(T)
t = clf.t_
clf = self.factory(alpha=0.01, eta0=0.01,
learning_rate=lr, shuffle=False)
for i in range(2):
clf.partial_fit(X, Y)
y_pred2 = clf.predict(T)
assert_equal(clf.t_, t)
<API key>(y_pred, y_pred2, decimal=2)
def <API key>(self):
self.<API key>("constant")
def <API key>(self):
self.<API key>("optimal")
def <API key>(self):
self.<API key>("invscaling")
def <API key>(self):
clf = self.factory(epsilon=0.9)
clf.set_params(epsilon=0.1)
assert clf.loss_functions['huber'][1] == 0.1
class <API key>(<API key>):
# Run exactly the same tests using the sparse representation variant
factory_class = SparseSGDRegressor
def test_l1_ratio():
# Test if l1 ratio extremes match L1 and L2 penalty settings.
X, y = datasets.make_classification(n_samples=1000,
n_features=100, n_informative=20,
random_state=1234)
# test if elasticnet with l1_ratio near 1 gives same result as pure l1
est_en = SGDClassifier(alpha=0.001, penalty='elasticnet',
l1_ratio=0.9999999999, random_state=42).fit(X, y)
est_l1 = SGDClassifier(alpha=0.001, penalty='l1', random_state=42).fit(X, y)
<API key>(est_en.coef_, est_l1.coef_)
# test if elasticnet with l1_ratio near 0 gives same result as pure l2
est_en = SGDClassifier(alpha=0.001, penalty='elasticnet',
l1_ratio=0.0000000001, random_state=42).fit(X, y)
est_l2 = SGDClassifier(alpha=0.001, penalty='l2', random_state=42).fit(X, y)
<API key>(est_en.coef_, est_l2.coef_)
def <API key>():
with np.errstate(all='raise'):
# Generate some weird data with hugely unscaled features
rng = np.random.RandomState(0)
n_samples = 100
n_features = 10
X = rng.normal(size=(n_samples, n_features))
X[:, :2] *= 1e300
assert_true(np.isfinite(X).all())
# Use MinMaxScaler to scale the data without introducing a numerical
# instability (computing the standard deviation naively is not possible
# on this data)
X_scaled = MinMaxScaler().fit_transform(X)
assert_true(np.isfinite(X_scaled).all())
# Define a ground truth on the scaled data
ground_truth = rng.normal(size=n_features)
y = (np.dot(X_scaled, ground_truth) > 0.).astype(np.int32)
assert_array_equal(np.unique(y), [0, 1])
model = SGDClassifier(alpha=0.1, loss='squared_hinge', n_iter=500)
# smoke test: model is stable on scaled data
model.fit(X_scaled, y)
assert_true(np.isfinite(model.coef_).all())
# model is numerically unstable on unscaled data
msg_regxp = (r"Floating-point under-/overflow occurred at epoch
" Scaling input data with StandardScaler or MinMaxScaler"
" might help.")
<API key>(ValueError, msg_regxp, model.fit, X, y)
def <API key>():
# Non regression test case for numerical stability on scaled problems
# where the gradient can still explode with some losses
model = SGDClassifier(loss='squared_hinge', n_iter=10, shuffle=True,
penalty='elasticnet', l1_ratio=0.3, alpha=0.01,
eta0=0.001, random_state=0)
with np.errstate(all='raise'):
model.fit(iris.data, iris.target)
assert_true(np.isfinite(model.coef_).all())
def <API key>():
# Non regression tests for numerical stability issues caused by large
# regularization parameters
for penalty in ['l2', 'l1', 'elasticnet']:
model = SGDClassifier(alpha=1e5, learning_rate='constant', eta0=0.1,
n_iter=5, penalty=penalty, shuffle=False)
with np.errstate(all='raise'):
model.fit(iris.data, iris.target)
<API key>(model.coef_, np.zeros_like(model.coef_)) |
package com.progrexor.hive.udaf;
import java.util.HashMap;
import java.util.Map.Entry;
import org.apache.hadoop.hive.ql.exec.UDAF;
import org.apache.hadoop.hive.ql.exec.UDAFEvaluator;
@SuppressWarnings("deprecation")
public final class Mode extends UDAF {
public static class Evaluator implements UDAFEvaluator {
private HashMap<String, Long> buffer;
public Evaluator() {
init();
}
public void init() {
buffer = new HashMap<String, Long>();
}
public boolean iterate(String key) {
if (!buffer.containsKey(key)) {
buffer.put(key, 1L);
} else {
Long val = buffer.get(key);
buffer.put(key, val + 1);
}
return true;
}
public HashMap<String, Long> terminatePartial() {
return buffer;
}
public boolean merge(HashMap<String, Long> another) {
if (another == null) {
return true;
}
for (String key : another.keySet()) {
if (!buffer.containsKey(key)) {
buffer.put(key, another.get(key));
} else {
buffer.put(key, buffer.get(key) + another.get(key));
}
}
return true;
}
public String terminate() {
if (buffer.size() == 0) {
return null;
}
return findMax(buffer);
}
public String findMax(HashMap<String, Long> buffer) {
Entry<String, Long> maxEntry = null;
for (Entry<String, Long> entry : buffer.entrySet()) {
if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
maxEntry = entry;
}
}
return maxEntry.getKey();
}
}
} |
import Vue from "vue";
const template = '<div class="confirm-modal modal-box" v-if="display">' +
'<div class="modal-overlay"></div>' +
'<div class="modal-container">' +
'<div :class="contentClass">' +
'<p class="title"></p>' +
'<p class="text">{{text}}</p>' +
'<div class="handle">' +
'<button class="btn" @click="onConfirm"><span class="text-link"></span></button>' +
'<button class="btn" @click="onCancel"></button>' +
'</div></div></div></div>';
const animationName = "animation-zoomIn";
let promise;
let _resolve;
let _reject;
let _arg = [];
export default new Vue({
el: document.createElement("div"),
template: template,
name: "confirmPromise",
data: {
display: false,
main: ""
},
computed: {
text() {
return this.main ? this.main : "";
},
contentClass() {
let className = "modal-content";
if(this.display) {
className += " " + animationName;
}
return className;
}
},
methods: {
show(...args) {
promise = new Promise((resolve, reject) => {
_resolve = resolve;
_reject = reject;
});
this.main = args[0];
args.shift();
this.arg = args;
this.display = true;
promise.then(() => {
this.main = "";
this.display = false;
_arg = [];
}).catch(() => {
this.main = "";
this.display = false;
});
return promise;
},
onConfirm() {
_resolve(..._arg);
},
onCancel() {
_reject(..._arg);
}
},
mounted() {
document.body.appendChild(this.$el);
}
}); |
<?php
declare(strict_types=1);
namespace Orchid\Press\Entities;
use Illuminate\Foundation\Validation\ValidatesRequests;
trait Structure
{
use ValidatesRequests;
/**
* Visible name of entity.
*
* @var string
*/
public $name = '';
/**
* Visible description of entity.
*
* @var string
*/
public $description = '';
/**
* A unique name for entity.
*
* @var string
*/
public $slug = '';
/**
* Display Icon.
*
* @var string
*/
public $icon = 'icon-folder';
/**
* @var string
*/
public $prefix = 'content';
/**
* Menu title name.
*
* @var null
*/
public $title;
/**
* Show the data to the user.
*
* @var bool
*/
public $display = true;
/**
* Priority display in menu.
*
* @var int
*/
public $sort = 0;
/**
* Basic statuses possible for the object.
*
* @return array
*/
public function status(): array
{
return [
'publish' => __('Published'),
'draft' => __('Draft'),
];
}
/**
* Request Validation.
*
* @return array
*/
public function isValid(): array
{
return $this->validate(request(), $this->rules());
}
/**
* Validation Request Rules.
*
* @return array
*/
public function rules(): array
{
return [];
}
/**
* Registered fields for main.
*
* @return array
*/
abstract public function main(): array;
/**
* Registered fields for filling.
*
* @return array
*/
abstract public function fields(): array;
/**
* Registered fields for options.
*
* @return array
*/
abstract public function options(): array;
/**
* Language support for recording.
*
* @return array
*/
public function locale(): array
{
return config('press.locales', []);
}
/**
* @return string
*/
public function __toString()
{
return $this->slug;
}
} |
Arena = class()
function Arena:init(l, b, r, t)
self.robots = {}
self.timer = 0
self.tourney = false
self.gameOver = false
self.game = 1
self.pulse = 0
self.pulseDirection = 2
self.skeet = {}
self.walls = {}
self.tracks = {}
self.launchTime = ElapsedTime
self:sizeFrames(l, b, r, t)
end
function Arena:sizeFrames(l, b, r, t)
-- define bounds for the arena
self.frame = Frame(l, b, r, t)
self.panel = Frame(l + 1, t - 90, r - 1, t - 1)
self.stop = Frame(r - 70, t - 65, r - 30, t - 25)
self.field = Frame(l + 5, b + 20, r - 5, t - 90)
self.launch = Frame(self.frame:midX() - 30, self.frame.bottom - 15,
self.frame:midX() + 30, self.frame.bottom + 30)
for i,r in ipairs(self.robots) do
r.limits = self.field
end
end
function Arena:loadRobot(r, x, y)
-- copy a robot into the arena, and set up for action
-- much of this is only needed because deep copy is losing
-- table order.
local i, nr
-- nr = Robot(math.random(self.field:width() - 90) + 30,
-- math.random(self.field:height() - 90) + 30)
nr = Robot(x, y)
nr.hp = r.hp
nr.direction = math.random(4)
for i = 1, table.maxn(r.program) do
nr.program[i] = r.program[i]
end
nr.bounds = Frame(nr.x, nr.y, nr.x + 60, nr.y + 60)
nr.program = r.program
nr.bump = false
nr.radar = false
nr.heat = 0
nr.step = 1
nr.wins = r.wins
nr.losses = r.losses
nr.name = r.name
nr.repeatCounter = 1
nr.points = 0
nr.treadColor = r.treadColor
nr.bodyColor = r.bodyColor
nr.headColor = r.headColor
nr.dishColor = r.dishColor
nr.head = r.head
nr.dish = r.dish
nr.body = r.body
nr.tread = r.tread
nr.limits = self.field
i = #self.robots + 1
-- design stuff here for now. should probably move.
nr.speed = r.tread * 4 - (r.body - 1)
nr.turnDelay = r.tread * 15 - 10
nr.shield = (r.head - 1) * 3.5
nr.repairRate = 1 / r.head
nr.weaponStrength = nr.dish * 2.5 - 2
self.robots[i] = nr
self.robots[i]:createImage()
end
function Arena:copyRobot(r)
-- copy using deepcopy
-- seems to have trouble with otder of code
local i, nr
nr = deepcopy(r)
nr.direction = math.random(4)
nr.bounds = Frame(nr.x, nr.y, nr.x + 60, nr.y + 60)
nr.bump = false
nr.radar = false
nr.heat = 0
nr.step = 1
nr.points = 0
i = table.maxn(self.robots) + 1
self.robots[i] = nr
end
function Arena:skeetMatch(r)
self.game = 2
self.robots ={}
self.tracks = {}
self.walls = {}
self:loadRobot(r, arena.field:midX(), arena.field:midY())
self.robots[1].bounds = Frame(self.robots[1].x,
self.robots[1].y, self.robots[1].x + 60, self.robots[1].y + 60)
self.skeet[1] = Skeet(30, 30, self.field)
self.skeet[2] = Skeet(30, self.field:height() / 2, self.field)
self.skeet[3] = Skeet(30, self.field:height() - 30, self.field)
self.skeet[4] = Skeet(self.field:width() / 2,
self.field:height() - 30, self.field)
self.skeet[5] = Skeet(self.field:width() - 30,
self.field:height() - 30, self.field)
self.skeet[6] = Skeet(self.field:width() - 30,
self.field:height() / 2, self.field)
self.skeet[7] = Skeet(self.field:width() - 30, 30, self.field)
self.skeet[8] = Skeet(self.field:width() / 2, 30, self.field)
self.timer = 300
self.tourney = true
end
function Arena:mazeRace(r)
self.game = 3
self:loadRobot(r, 10, 10)
self.robots[1].bounds = Frame(self.robots[1].x,
self.robots[1].y, self.robots[1].x + 60, self.robots[1].y + 60)
self.robots[1].dir = 3
-- base walls
self.walls[1] = Frame(80, 10, 81, self.field:height() - 80)
self.walls[2] = Frame(160, 90, 161, self.field:height() + 20)
self.walls[3] = Frame(240, 10, 241, self.field:height() - 80)
self.walls[4] = Frame(325, 510, 326, self.field:height())
self.walls[5] = Frame(245, 415, 400, 416)
self.walls[6] = Frame(325, 505, 480, 506)
self.walls[7] = Frame(485, 340, 486, 500)
self.walls[8] = Frame(325, 330, 580, 331)
self.walls[9] = Frame(325, 90, 326, 330)
self.walls[10] = Frame(405, 10, 406, 235)
self.walls[11] = Frame(500, 85, 501, 235)
self.walls[12] = Frame(580, 85, 581, 330)
self.walls[13] = Frame(500, 80, 660, 81)
self.walls[14] = Frame(660, 85, 661, 330)
self.walls[15] = Frame(575, 410, self.field:width(), 411)
self.walls[16] = Frame(570, 415, 571, self.field:height() - 80)
self.walls[17] = Frame(405, 585, 565, 586)
self.walls[18] = Frame(405, 590, 406, self.field:height() - 80)
self.walls[19] = Frame(485, 670, 486, self.field:height() + 20)
self.walls[20] = Frame(660, 505, 661, self.field:height() + 20)
self.tracks = {}
self.tracks[1] = Track(40, 300, 0)
self.tracks[2] = Track(40, 600, 0)
self.tracks[3] = Track(40, 820, -45)
self.tracks[4] = Track(120, 820, 225)
self.tracks[5] = Track(120, 500, 180)
self.tracks[6] = Track(120, 200, 180)
self.tracks[7] = Track(120, 50, 225)
self.tracks[8] = Track(200, 50, -45)
self.tracks[9] = Track(200, 500, 0)
self.tracks[10] = Track(200, 830, -45)
self.tracks[11] = Track(280, 830, 225)
self.tracks[12] = Track(280, 455, 225)
self.tracks[13] = Track(440, 455, 225)
self.tracks[14] = Track(440, 375, 225)
self.tracks[15] = Track(285, 375, 135)
self.tracks[16] = Track(285, 50, 225)
self.tracks[17] = Track(365, 50, -45)
self.tracks[18] = Track(365, 280, -45)
self.tracks[19] = Track(445, 280, 225)
self.tracks[20] = Track(450, 50, 225)
self.tracks[21] = Track(705, 50, -45)
self.tracks[22] = Track(705, 370, 45)
self.tracks[23] = Track(525, 370, 45)
self.tracks[24] = Track(525, 540, 45)
self.tracks[25] = Track(365, 540, 45)
self.tracks[26] = Track(365, 830, -45)
self.tracks[27] = Track(445, 830, 225)
self.tracks[28] = Track(445, 625, 225)
self.tracks[29] = Track(525, 625, -45)
self.tracks[30] = Track(525, 830, -45)
self.tracks[31] = Track(615, 830, 225)
self.tracks[32] = Track(615, 625, 180)
self.tracks[33] = Track(615, 460, 225)
self.tracks[34] = Track(700, 460, -45)
self.tracks[35] = Track(700, 830, 0)
self.timer = 1000
self.tourney = true
end
function Arena:clear()
-- pop robots from arena
sound(SOUND_POWERUP, 2591)
self.robots = {}
self.skeet = {}
self.walls = {}
self.tracks = {}
self.timer = 0
self.game = 1
self.gameOver = false
self.tourney = false
end
function Arena:testBounds(type, num, bounds)
for i, r in ipairs(self.robots) do
if type ~= 1 or num ~= i then
if r.bounds:overlaps(bounds) and r.hp > 0 then
if r.bounds.left < bounds.left then
return 1
elseif r.bounds.left > bounds.left then
return 2
elseif r.bounds.top < bounds.top then
return 3
elseif r.bounds.top > bounds.left then
return 4
end
end
end
end
for i, s in ipairs(self.skeet) do
if (type ~= 2 or num ~= i) and s.active == 1 then
if s.bounds:overlaps(bounds) then
if s.bounds.left < bounds.left then
return 1
elseif s.bounds.left > bounds.left then
return 2
elseif s.bounds.top < bounds.top then
return 3
elseif s.bounds.top > bounds.left then
return 4
end
end
end
end
return 0
end
function Arena:checkRadar(k, r)
local i, robot
r.radar = false
-- trim against walls
for i, wall in ipairs(self.walls) do
if r.rf:overlaps(wall) then
if r.direction == 1 then
r.rf.top = wall.bottom
elseif r.direction == 2 then
r.rf.right = wall.left
elseif r.direction == 3 then
r.rf.bottom = wall.top
elseif r.direction == 4 then
r.rf.left = wall.right
end
end
end
for i, robot in ipairs(self.robots) do
if i ~= k then
if r.rf:overlaps(robot.bounds) and robot.hp > 0 then
r.radar = true
end
end
end
for i, skeet in ipairs(self.skeet) do
if r.rf:overlaps(skeet.bounds) and skeet.active == 1 then
r.radar = true
end
end
for i, track in ipairs(self.tracks) do
if r.rf:overlaps(track.bounds) and track.active == 1 then
r.radar = true
end
end
pushStyle()
fill(90, 181, 230, 74)
noStroke()
r.rf:draw()
popStyle()
r.fireRadar = false
end
function Arena:checkLaser(k, r)
local i, robot
for i, robot in ipairs(self.robots) do
if i ~= k then
if r.rf:overlaps(robot.bounds) then
if robot.hp > 0 then
-- distance between
--d = robot.bounds.
robot.hp = robot.hp - r.weaponStrength
r.points = r.points + 1
if robot.heat < 20 then
robot.heat = robot.heat + 5
end
end
end
end
end
for i, s in ipairs(self.skeet) do
if r.rf:overlaps(s.bounds) and s.active == 1 then
r.points = r.points + 1
s.active = 2
end
end
r.fireLaser = false
end
function Arena:checkCollisions(k, r)
local i, b
-- test outer walls
if r.x < 5 then
r.x = r.oldX
r.bump = true
elseif r.x > self.field:width() - 50 then
r.x = r.oldX
r.bump = true
elseif r.y < 5 then
r.y = r.oldY
r.bump = true
elseif r.y > self.field:height() - 30 then
r.y = r.oldY
r.bump = true
end
-- test interior walls
for w, wall in ipairs(self.walls) do
--wall:draw()
if r.bounds:overlaps(wall) then
r.bump = true
r.y = r.oldY
r.x = r.oldX
--displayMode(STANDARD)
--print(w)
end
end
-- test tracks
-- track collisions do not activate the bump sensor
for i, track in ipairs(self.tracks) do
if r.bounds:overlaps(track.bounds) and track.active == 1 then
r.points = r.points + 1
track.active = 2
sound(SOUND_POWERUP, 7170)
end
end
-- test other bot collisions
b = self:testBounds(1, k, r.bounds)
if b == 1 then
-- hit from left
if r.x < self.field:width() - 60 then r.x = r.x + 5 end
elseif b == 2 then
-- hit from right
if r.x > 30 then r.x = r.x - 5 end
elseif b == 1 then
-- hit from bottom
if r.y < self.field:height() - 30 then r.y = r.y + 5 end
elseif b == 1 then
-- hit from top
if r.y > 30 then r.y = r.y - 5 end
end
if b > 0 then r.bump = true end
end
function Arena:<API key>(k, s)
local i, b
b = self:testBounds(2, k, s.bounds)
if b > 0 then
s.dx = - s.dx
s.dy = - s.dy
end
end
function Arena:setMatch(a, b, c, d)
self.robots = {}
self:loadRobot(a, 60, 60)
self:loadRobot(b, 60, self.field:height() - 60)
self:loadRobot(c, self.field:width() - 60, 60)
self:loadRobot(d, self.field:width() - 60, self.field:height() - 60)
self.timer = 100
end
function Arena:drawPen(r)
local prevX, prevY, prevStatus, i, p
prevStatus = false
pushStyle()
stroke(111, 333 - self.pulse, 111, 111)
for i, p in ipairs(r.pen) do
if prevStatus then
line(prevX, prevY, p.x, p.y)
end
prevX = p.x
prevY = p.y
prevStatus = p.status
end
popStyle()
end
function Arena:draw()
local k, robot, liveCount, i
-- base elements
pushStyle()
stroke(255, 255, 255, 255)
strokeWidth(2)
noFill()
self.frame:draw()
self.panel:inset(10, 10)
self.panel:draw()
self.panel:inset(-10, -10)
line(20, 40, WIDTH - 20, 40)
if self.game == 2 then
if self.robots[1].points == 8 or self.timer == 0 then
self.gameOver = true
end
end
if self.game == 3 then
if self.robots[1].points == 30 or self.timer == 0 then
self.gameOver = true
end
end
self.stop:draw()
for i = 1,3 do
y = self.field.bottom + self.field:height() / 4 * i
line(self.field.left, y, self.field.left + 10, y)
line(self.field.right - 10, y, self.field.right, y)
end
self.pulse = self.pulse + self.pulseDirection
if self.pulse > 255 or self.pulse < 0 then
self.pulseDirection = 0 - self.pulseDirection
end
stroke(255, 55, 55, self.pulse)
ellipse(self.stop:midX(), self.stop:midY(), 30)
ellipse(self.stop:midX(), self.stop:midY(), 20)
fill(255, 255, 255, 255)
fontSize(36)
text("Battle Chips",self.panel.left + 50, self.panel.top - 60)
noFill()
stroke(255, 255, 255, 255)
pushMatrix()
translate(self.panel.left + 32, self.panel.top - 40)
for i = 0, 8 do
rotate(i * 45)
rect(-3,0,3,15)
end
fill(25, 27, 46, 255)
ellipse(0, 0, 25)
popMatrix()
fill(255, 255, 255, 255)
-- translate to field
pushMatrix()
translate(self.frame.left, self.frame.bottom)
if not self.gameOver then
-- draw walls
stroke(111 + self.pulse, 111 + self.pulse, 255,
111 + self.pulse)
for i, w in ipairs(self.walls) do
w:draw()
end
-- draw skeet
for i, s in ipairs(self.skeet) do
if s.active < 10 then
s:draw()
self:<API key>(i, s)
end
end
-- draw tracks
for t, track in ipairs(self.tracks) do
if track.active < 10 then
track:draw()
end
end
-- draw robots
noSmooth()
liveCount = 0
for k, robot in ipairs(self.robots) do
self:drawPen(robot)
if robot.hp > 0 then liveCount = liveCount + 1 end
if robot.fireRadar then
self:checkRadar(k, robot)
end
if robot.fireLaser then
self:checkLaser(k, robot)
end
self:checkCollisions(k, robot)
robot:draw(1)
if robot.hp > 0 then
robot:run()
else
robot.hp = 0
end
end
if liveCount < 2 and self.game == 4 then
self.timer = self.timer - 1
else
self.timer = self.timer - 0.1
end
if self.timer < 0 then self.timer = 0 end
popMatrix()
fontSize(12)
textMode(LEFT)
for k, robot in ipairs(self.robots) do
if self.game < 2 then
fill(159, 201, 223, 255)
text(robot.name, 30, 900)
s = robot.step - 30 * math.floor(robot.step / 30)
if robot.program[robot.step] ~= nil and
robot.program[robot.step].code ~= nil then
--displayMode(STANDARD)
s = s.." "..robot.program[robot.step].code.long1
--print(s)
else
fill(223, 174, 174, 255)
s = s.." NIL"
end
x = math.floor(robot.step / 30) * 250 + 50
y = 850 - robot.step * 15 +
math.floor(robot.step / 30) * 450
text(s, x, y)
end
x = self.frame.right - k * 60 - 100
y = self.panel.bottom + 35
sprite(robot.img, x - 15, y, x + 15, y + 30)
fill(26, 26, 26, 255)
stroke(130, 154, 221, 255)
rect(self.frame.right - k * 60 - 127,
self.panel.bottom + 35,
self.frame.right - k * 60 - 120, self.panel.bottom + 65)
if robot.hp > 7 then
fill(72, 255, 0, 255)
elseif robot.hp > 4 then
fill(244, 255, 0, 255)
else
fill(255, 0, 13, 255)
end
noStroke()
rect(self.frame.right - k * 60 - 126,
self.panel.bottom + 36,
self.frame.right - k * 60 - 121, self.panel.bottom + 36 +
robot.hp * 3)
fill(248, 248, 248, 255)
text(robot.points, self.frame.right - k * 60 - 100,
self.panel.bottom + 25)
end
if self.tourney then
textMode(CORNER)
fontSize(48)
fill(218, 214, 214, 81)
if self.game == 1 then
text("Melee", self.field.left + 15, self.field.top - 60)
end
if self.game == 2 then
text("Skeet", self.field.left + 15, self.field.top - 60)
end
if self.game == 3 then
text("Maze", self.field.left + 15, self.field.top - 60)
end
text(math.floor(self.timer),
self.frame.left + 15, self.field.bottom)
else
strokeWidth(1)
stroke(255, 255, 255, 255)
line(self.field:midX() - 5, self.field.bottom ,
self.field:midX() + 5, self.field.bottom )
line(self.field:midX(), self.field.bottom + 5,
self.field:midX(), self.field.bottom - 5)
line(self.field:midX() - 5, self.field.bottom + 5,
self.field:midX() + 5, self.field.bottom - 5)
line(self.field:midX() - 5, self.field.bottom - 5,
self.field:midX() + 5, self.field.bottom + 5)
end
else
-- game over
if self.game == 2 then
self.robots[1].x = 100
self.robots[1].y = 700
self.robots[1]:draw(1)
fontSize(32)
text("Skeet Results", 100, 800)
fontSize(24)
text(self.robots[1].name, 200, 700)
text("Skeet destroyed", 100, 600)
text("Time remaining", 100, 500)
text("Total Score", 100, 400)
text(self.robots[1].points, 500, 600)
text(math.floor(self.timer), 500, 500)
score = self.robots[1].points * 10 + math.floor(self.timer)
text(score, 500, 400)
end
if self.game == 3 then
self.robots[1].x = 100
self.robots[1].y = 700
self.robots[1]:draw(1)
fontSize(32)
text("Maze Results", 100, 800)
fontSize(24)
text(self.robots[1].name, 200, 700)
text("Tracks stomped", 100, 600)
text("Time remaining", 100, 500)
text("Total Score", 100, 400)
text(self.robots[1].points, 500, 600)
text(math.floor(self.timer), 500, 500)
score = self.robots[1].points * 5 + math.floor(self.timer)
text(score, 500, 400)
end
end
popStyle()
end
function Arena:touched(touch)
if self.launch:touched(touch) and
ElapsedTime > self.launchTime + 1 then
sound(SOUND_POWERUP, 26548)
self.skeet[#self.skeet + 1] = Skeet(self.field:midX(),
20, self.field)
self.launchTime = ElapsedTime
end
if self.frame:touched(touch) then
return true
end
return false
end |
package com.j0rsa.caricyno.vk.query;
import com.j0rsa.caricyno.vk.actor.ServiceActorData;
import com.vk.api.sdk.exceptions.ApiException;
import com.vk.api.sdk.exceptions.ClientException;
import com.vk.api.sdk.objects.wall.responses.GetResponse;
import com.vk.api.sdk.queries.wall.WallGetFilter;
import com.vk.api.sdk.queries.wall.WallGetQuery;
import lombok.Builder;
import static com.j0rsa.caricyno.vk.query.WallQuery.wall;
@Builder
public class WallRequest {
private ServiceActorData service;
private WallGetFilter filter;
private Integer count;
private Integer owner;
public GetResponse execute() throws ClientException, ApiException {
WallGetQuery query = query();
query = <API key>(query);
return query.execute();
}
private WallGetQuery <API key>(WallGetQuery query) {
if (filter != null) {
query = query.filter(filter);
}
return query;
}
private WallGetQuery query() {
return wall(service).query()
.ownerId(owner)
.count(count);
}
} |
<?php
namespace MusicCast\Api;
/**
* @author Sam Van der Borght <samvanderborght@gmail.com>
* @author Damien Surot <damien@toxeek.com>
*/
/**
* @author Sam Van der Borght <samvanderborght@gmail.com>
*/
class System extends AbstractApi
{
/**
* For retrieving basic information of a Device
*
* @return array
*/
public function getDeviceInfo()
{
return $this->call('getDeviceInfo');
}
/**
* For retrieving feature information equipped with a Device
*
* @return array
*/
public function getFeatures()
{
return $this->call('getFeatures');
}
/**
* For retrieving network related setup / information
*
* @return array
*/
public function getNetworkStatus()
{
return $this->call('getNetworkStatus');
}
public function getFuncStatus()
{
return $this->call('getFuncStatus');
}
/**
* For setting Auto Power Standby status. Actual operations/reactions of enabling Auto Power
* Standby depend on each Device
*
* @param bool $enable Specifies Auto Power Standby status
* @return array
*/
public function setAutoPowerStandby($enable = true)
{
return $this->call('setAutoPowerStandby?enable=' . rawurlencode($enable ? 'true' : 'false'));
}
/**
* For retrieving Location information
* @return array
*/
public function getLocationInfo()
{
return $this->call('getLocationInfo');
}
public function sendIrCode($code)
{
return $this->call('sendIrCode?code=' . rawurlencode($code));
}
/**
* @return array
*/
public function getNameText()
{
return $this->call('getNameText');
}
/**
* @param string $type
* @return array
*/
public function <API key>($type = 'network')
{
return $this->call('<API key>?type=' . rawurlencode($type));
}
/**
* @return array
*/
public function getTag()
{
return $this->call('getTag');
}
/**
* @return array
*/
public function <API key>()
{
return $this->call('<API key>');
}
/**
* @return array
*/
public function <API key>()
{
return $this->call('<API key>');
}
/**
* @param $path
* @return array
*/
private function call($path)
{
return $this->get('/system/' . $path);
}
} |
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { createUserGroup } from 'actions'
import GroupCreate from 'components/admin/Group/GroupCreate'
export default connect(
state => ({}),
dispatch => bindActionCreators({createUserGroup}, dispatch),
)(GroupCreate) |
"use strict";
const tap = require('tap')
const mocks = require('pom-test-stubs')
const PluginFinder = require('../../lib/PluginFinder')
const PluginValidator = require('../../lib/PluginValidator')
tap.test('Validating plugins', (t) => {
let mockDir = mocks.findMockDir(__dirname, '../mocks/unit/PluginValidator/mixedPlugins')
let mockedDependencies = []
let mockedApplication = mocks.registerMocks(mockDir, mockedDependencies)
let frameworkInjector = mocks.<API key>(false, {}, mockDir)
let FoundPlugins = PluginFinder(mockedDependencies, frameworkInjector)
let RawPlugins = PluginValidator(FoundPlugins, frameworkInjector)
t.type(RawPlugins, 'Array', 'Plugin validator is an array.')
t.equal(RawPlugins.length, 4, 'Found 2 plugins.')
RawPlugins.forEach((v, k) => {
t.type(v, 'DependencyRawPlugin',`${v.moduleName} is DependencyRawPlugin`)
})
t.end()
})
tap.test('Validating nested multiple plugins', (t) => {
let mockDir = mocks.findMockDir(__dirname, '../mocks/unit/PluginValidator/multiplePlugins')
let mockedDependencies = []
let mockedApplication = mocks.registerMocks(mockDir, mockedDependencies)
let frameworkInjector = mocks.<API key>(false, {}, mockDir)
let FoundPlugins = PluginFinder(mockedDependencies, frameworkInjector)
let RawPlugins = PluginValidator(FoundPlugins, frameworkInjector)
t.type(RawPlugins, 'Array', 'Plugin validator is an array.')
t.equal(RawPlugins.length, 7, 'Found 2 plugins.')
RawPlugins.forEach((v, k) => {
t.type(v, 'DependencyRawPlugin',`${v.moduleName} is DependencyRawPlugin`)
})
t.end()
})
tap.test('Handling non existent plugins.', (t) => {
let mockDir = mocks.findMockDir(__dirname, '../mocks/unit/PluginValidator/mixedPlugins')
let frameworkInjector = mocks.<API key>(false, {}, mockDir)
let FakeModules = [{
require: __dirname + '/<API key>.js',
external: false,
internal: false,
systemPlugin: true,
moduleName: 'FakeModule',
loaded:
{ options: { checkExistence: [] },
metadata: { name: 'Fake', type: 'action' },
plugin:
{
load: function(){},
start: function(){},
stop: function(){}
}
}
}]
t.throws(function() {
PluginValidator(FakeModules, frameworkInjector)
}, 'Throws an error after exhausing all attempts to load a module.')
t.end()
}) |
package eu.bcvsolutions.idm.core.model.service.impl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import eu.bcvsolutions.idm.core.api.config.domain.<API key>;
import eu.bcvsolutions.idm.core.api.dto.IdmConfigurationDto;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.api.service.ConfidentialStorage;
import eu.bcvsolutions.idm.core.api.service.<API key>;
import eu.bcvsolutions.idm.core.api.service.<API key>;
import eu.bcvsolutions.idm.core.security.api.domain.GuardedString;
import eu.bcvsolutions.idm.test.api.<API key>;
@Transactional
public class <API key> extends <API key> {
private static final String TEST_PROPERTY_KEY = "test.property";
private static final String <API key> = "test.db.property";
public static final String <API key> = "idm.sec.core.password.test";
private static final String <API key> = "secret_password";
@Autowired private ApplicationContext context;
@Autowired private ConfidentialStorage confidentialStorage;
@Autowired private <API key> <API key>;
private <API key> <API key>;
@Before
public void init() {
<API key> = context.<API key>().createBean(<API key>.class);
}
@Test
public void testReadNotExists() {
Assert.assertNull(<API key>.getValue(getHelper().createName()));
}
@Test
public void <API key>() {
Assert.assertEquals("true", <API key>.getValue(getHelper().createName(), "true"));
}
@Test
public void <API key>() {
Assert.assertTrue(<API key>.getBooleanValue(getHelper().createName(), true));
}
@Test
public void <API key>() {
Assert.assertEquals("true", <API key>.getValue(TEST_PROPERTY_KEY));
}
@Test
public void <API key>() {
Assert.assertTrue(<API key>.getBooleanValue(TEST_PROPERTY_KEY));
}
@Test
public void <API key>() {
<API key>.saveConfiguration(new IdmConfigurationDto(<API key>, "true"));
Assert.assertTrue(<API key>.getBooleanValue(<API key>));
}
@Test
public void <API key>() {
<API key>.saveConfiguration(new IdmConfigurationDto(TEST_PROPERTY_KEY, "false"));
Assert.assertEquals("false", <API key>.getValue(TEST_PROPERTY_KEY));
}
@Test
public void <API key>() {
Assert.assertEquals(<API key>, <API key>.getValue(<API key>));
}
@Test
public void <API key>() {
<API key>.saveConfiguration(new IdmConfigurationDto(<API key>, "secured_change"));
Assert.assertEquals("secured_change", <API key>.getValue(<API key>));
}
@Test
public void <API key>() {
final String format = "dd.MM";
<API key>.setValue(<API key>.<API key>, format);
Assert.assertEquals(format, <API key>.getDateFormat());
<API key>.setValue(<API key>.<API key>, <API key>.<API key>);
Assert.assertEquals(<API key>.<API key>, <API key>.getDateFormat());
}
@Test
public void <API key>() {
Assert.assertEquals(<API key>.<API key>, <API key>.getDateTimeFormat());
}
@Test(expected = ResultCodeException.class)
public void <API key>() {
<API key>.setValue(<API key>.<API key>, "wrong");
}
@Test
public void <API key>() {
String confidentialKey = String.format("%s.%s", GuardedString.<API key>[0], getHelper().createName());
String value = getHelper().createName();
// empty at start - null
<API key>.setValue(confidentialKey, "");
IdmConfigurationDto <API key> = <API key>.getByCode(confidentialKey);
Assert.assertTrue(<API key>.isConfidential());
Assert.assertNull(<API key>.getValue());
Assert.assertNull(confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
// filled correctly
<API key>.setValue(confidentialKey, value);
<API key> = <API key>.getByCode(confidentialKey);
Assert.assertTrue(<API key>.isConfidential());
String proxyValue = <API key>.getValue();
Assert.assertTrue(proxyValue.startsWith(<API key>.<API key>));
Assert.assertEquals(value, confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
// null => no change => previous proxy value
<API key>.setValue(confidentialKey, null);
<API key> = <API key>.getByCode(confidentialKey);
Assert.assertEquals(proxyValue, <API key>.getValue());
Assert.assertEquals(value, confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
// same value => same proxy value
<API key>.setValue(confidentialKey, value);
<API key> = <API key>.getByCode(confidentialKey);
Assert.assertEquals(proxyValue, <API key>.getValue());
Assert.assertEquals(value, confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
// different value => new proxy value
<API key>.setValue(confidentialKey, "updateValue");
<API key> = <API key>.getByCode(confidentialKey);
Assert.assertNotEquals(proxyValue, <API key>.getValue());
Assert.assertEquals("updateValue", confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
// empty value => null
<API key>.setValue(confidentialKey, "");
<API key> = <API key>.getByCode(confidentialKey);
Assert.assertNull(<API key>.getValue());
Assert.assertNull(confidentialStorage.get(<API key>, <API key>.<API key>, String.class));
}
} |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Inventory : MonoBehaviour
{
GameObject inventoryPanel;
GameObject slotPanel;
ItemDatabase database;
public GameObject inventorySlot;
public GameObject inventoryItem;
private int slotAmount;
public List<Item> items = new List<Item>();
public List<GameObject> slots = new List<GameObject>();
void Start()
{
database = GetComponent<ItemDatabase>();
slotAmount = 16;
inventoryPanel = GameObject.Find("InventoryPanel");
slotPanel = inventoryPanel.transform.FindChild("SlotPanel").gameObject;
for (int i = 0; i < slotAmount; i++)
{
items.Add(new Item());
slots.Add(Instantiate(inventorySlot));
slots[i].GetComponent<Slot>().id = i;
slots[i].transform.SetParent(slotPanel.transform);
}
AddItem(0);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(1);
AddItem(2);
}
public void AddItem(int id)
{
Item itemToAdd = database.FetchItemById(id);
if (itemToAdd.Stackable && <API key>(itemToAdd))
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].Id == id)
{
ItemData data = slots[i].transform.GetChild(0).GetComponent<ItemData>();
data.amount++;
data.transform.GetChild(0).GetComponent<Text>().text = data.amount.ToString();
break;
}
}
}
else
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].Id == -1)
{
items[i] = itemToAdd;
GameObject itemObj = Instantiate(inventoryItem);
itemObj.GetComponent<ItemData>().item = itemToAdd;
itemObj.GetComponent<ItemData>().slotId = i;
itemObj.transform.SetParent(slots[i].transform);
itemObj.transform.position = Vector2.zero;
itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
itemObj.name = "Item: " + itemToAdd.Title;
slots[i].name = "Slot: " + itemToAdd.Title;
break;
}
}
}
}
bool <API key>(Item item)
{
for (int i = 0; i < items.Count; i++)
{
if (items[i].Id == item.Id)
{
return true;
}
}
return false;
}
} |
import Ember from 'ember';
import EmberValidations from 'ember-validations';
export default Ember.Controller.extend(EmberValidations.Mixin, {
validations: {
"model.def": {
generic: true,
definitionlike: true,
},
"model.example": {
generic: true,
nongendered: true,
sentencelike: true,
}
},
actions: {
submitProposal: function() {
var _this = this;
var proposal = this.get("model");
proposal.set("type", "MeaningChange");
proposal.save().then(function() {
_this.get("parentController").set("editing", false);
_this.set("meaning.hasProposal", true);
_this.set("meaning.openProposal", _this.get("model"));
_this.send("log", "proposal", "meaning change");
},
function(errors) {
_this.set("errors", errors.errors);
});
},
<API key>: function() {
var _this = this;
var proposal = this.store.createRecord("proposal", {
type: "MeaningRemoval",
meaning: this.get("model.meaning")
});
proposal.save().then(function() {
_this.get("parentController").set("editing", false);
_this.set("model.meaning.hasProposal", true);
_this.set("model.meaning.openProposal", proposal);
_this.send("log", "proposal", "meaning change");
_this.get("model").destroy();
}, function(errors) {
_this.set("errors", errors.errors);
});
}
}
}); |
namespace FreshBooks.Api.PaymentList {
<remarks/>
[System.CodeDom.Compiler.<API key>("System.Xml", "4.6.81.0")]
[System.<API key>()]
[System.Diagnostics.<API key>()]
[System.ComponentModel.<API key>("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:
[System.Xml.Serialization.XmlRootAttribute(Namespace="http:
public partial class response: BaseResponse {
private responsePayments paymentsField;
private string statusField;
<remarks/>
public responsePayments payments {
get {
return this.paymentsField;
}
set {
this.paymentsField = value;
}
}
<remarks/>
[System.Xml.Serialization.<API key>()]
public string status {
get {
return this.statusField;
}
set {
this.statusField = value;
}
}
}
<remarks/>
[System.CodeDom.Compiler.<API key>("System.Xml", "4.6.81.0")]
[System.<API key>()]
[System.Diagnostics.<API key>()]
[System.ComponentModel.<API key>("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:
public partial class responsePayments {
private <API key>[] paymentField;
private byte pageField;
private byte per_pageField;
private byte pagesField;
private byte totalField;
<remarks/>
[System.Xml.Serialization.XmlElementAttribute("payment")]
public <API key>[] payment {
get {
return this.paymentField;
}
set {
this.paymentField = value;
}
}
<remarks/>
[System.Xml.Serialization.<API key>()]
public byte page {
get {
return this.pageField;
}
set {
this.pageField = value;
}
}
<remarks/>
[System.Xml.Serialization.<API key>()]
public byte per_page {
get {
return this.per_pageField;
}
set {
this.per_pageField = value;
}
}
<remarks/>
[System.Xml.Serialization.<API key>()]
public byte pages {
get {
return this.pagesField;
}
set {
this.pagesField = value;
}
}
<remarks/>
[System.Xml.Serialization.<API key>()]
public byte total {
get {
return this.totalField;
}
set {
this.totalField = value;
}
}
}
<remarks/>
[System.CodeDom.Compiler.<API key>("System.Xml", "4.6.81.0")]
[System.<API key>()]
[System.Diagnostics.<API key>()]
[System.ComponentModel.<API key>("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:
public partial class <API key> {
private byte payment_idField;
private byte invoice_idField;
private string dateField;
private string typeField;
private object notesField;
private byte client_idField;
private string currency_codeField;
private string updatedField;
private <API key> <API key>;
private decimal amountField;
<remarks/>
public byte payment_id {
get {
return this.payment_idField;
}
set {
this.payment_idField = value;
}
}
<remarks/>
public byte invoice_id {
get {
return this.invoice_idField;
}
set {
this.invoice_idField = value;
}
}
<remarks/>
public string date {
get {
return this.dateField;
}
set {
this.dateField = value;
}
}
<remarks/>
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
<remarks/>
public object notes {
get {
return this.notesField;
}
set {
this.notesField = value;
}
}
<remarks/>
public byte client_id {
get {
return this.client_idField;
}
set {
this.client_idField = value;
}
}
<remarks/>
public string currency_code {
get {
return this.currency_codeField;
}
set {
this.currency_codeField = value;
}
}
<remarks/>
public string updated {
get {
return this.updatedField;
}
set {
this.updatedField = value;
}
}
<remarks/>
public <API key> gateway_transaction {
get {
return this.<API key>;
}
set {
this.<API key> = value;
}
}
<remarks/>
public decimal amount {
get {
return this.amountField;
}
set {
this.amountField = value;
}
}
}
<remarks/>
[System.CodeDom.Compiler.<API key>("System.Xml", "4.6.81.0")]
[System.<API key>()]
[System.Diagnostics.<API key>()]
[System.ComponentModel.<API key>("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http:
public partial class <API key> {
private uint reference_idField;
private string gateway_nameField;
<remarks/>
public uint reference_id {
get {
return this.reference_idField;
}
set {
this.reference_idField = value;
}
}
<remarks/>
public string gateway_name {
get {
return this.gateway_nameField;
}
set {
this.gateway_nameField = value;
}
}
}
} |
import webtools
import re
class Trip():
""" Models a megabus trip."""
def __init__(self, data, number, mode, crawling_day):
""" Initializes basic trip Data."""
self.data = data
self.trip_number = number
self.mode = mode
self.day = crawling_day
def price(self, verbose=True):
"""
Returns the price of the trip, and prints the price if verbose is set to True
:return: price = int
"""
data = self.data
price_regex = re.compile(r"\$\d\d") # Dollard Sign followed by two digits.
matches = price_regex.findall(data)
price = matches[0]
if verbose == True:
print('Price: ', price)
price = price.replace('$', '') # Cleans up data, so it can be converted to int easier later.
return int(price)
def departure_time(self):
"""Gets & Prints the departure time, :Returns: departure_time = str """
data = self.data
departure_regex = re.compile(r"^(Departs\d+:\d\d...)") # DepartsDigitormore, :, two more digits
matches = departure_regex.findall(data)
departure_time = matches[0]
departure_time = departure_time.replace('Departs', '')
print('Departing: ', departure_time)
return departure_time
def arrival_time(self):
"""Gets & Prints the arrival time, :Returns: arrival_time = str """
data = self.data
arrival_regex = re.compile(r"(Arrives\d+:\d\d...)")
matches = arrival_regex.findall(data)
arrival_time = matches[0]
arrival_time = arrival_time.replace('Arrives', '')
print('Arriving: ', arrival_time)
return arrival_time
def display_trip(self):
""" Displays some of the current trip attributes. """
print('\n')
if self.mode == 'inbound':
print(' Outbound Trip {0} '.center(50, '=').format(self.trip_number + 1))
if self.mode == 'outbound':
print(' Inbound Trip {0} '.center(50, '=').format(self.trip_number + 1))
self.price()
self.departure_time()
self.arrival_time()
def generate_city_code(citi):
"""
A dictionary of city codes used by megabus to identify each city.
:return: The proper city code, string.
"""
citi = citi.strip() # Strips the city provided of any extra spaces
citi = citi.upper()
citi_codes = {
'ALBANY, NY': '89',
'AMHERST, MA': '90',
'ANN ARBOR, MI': '91',
'ATLANTIC CITY, NJ': '92',
'BINGHAMTON, NY': '93',
'BOSTON, MA': '94',
'BUFFALO, NY': '95',
'BURLINGTON, VT': '96',
'CAMDEN': '97',
'CHAMPAIGN, IL': '98',
'CHARLOTTE, NC': '99',
'CHICAGO, IL': '100',
'CHRISTIANSBURG, VA': '101',
'CINCINNATI, OH': '102',
'CLEVELAND, OH': '103',
'COLUMBIA, MO': '104',
'COLUMBUS, OH': '105',
'DES MOINES, IA': '106',
'DETROIT, MI': '107',
'ERIE, PA': '108',
'FREDERICK, MD': '109',
'HAMPTON, VA': '110',
'HARRISBURG, PA': '111',
'HARTFORD, CT': '112',
'HOLYOKE, CT': '113',
'HYANNIS, MA': '114',
'INDIANAPOLIS, IN': '115',
'IOWA CITY, IA': '116',
'KANSAS CITY, MO': '117',
'KNOXVILLE, TN': '118',
'MADISON, WI': '119',
'MEMPHIS, TN': '120',
'MILWAUKEE, WI': '121',
'NEW HAVEN, CT': '122',
'NEW YORK, NY': '123',
'NIAGARA FALLS, ON': '124',
'NORMAL, IL': '125',
'OMAHA, NE': '126',
'PHILADELPHIA, PA': '127',
'PITTSBURGH, PA': '128',
'PORTLAND, ME': '129',
'PROVIDENCE, RI': '130',
'DURHAM, NC': '131',
'RICHMOND, VA': '132',
'RIDGEWOOD, NJ': '133',
'ROCHESTER, NY': '134',
'SECAUCUS, NJ': '135',
'ST LOUIS, MO': '136',
'STATE COLLEGE, PA': '137',
'STORRS, CT': '138',
'SYRACUSE, NY': '139',
'TOLEDO, OH': '140',
}
return citi_codes[citi] # Returns the city code to be formatted into an URL.
def generate_date(date):
"""
Formats the provided date, returns: String
"""
date = date
date = date.replace('/', '\n')
date = date.split()
month, day, year = date[0], date[1], date[2]
date = month + '%2f' + day + '%2f' + year
return date
def format(origin, destination, crawling_date, passengers='2'):
""" Formats a Megabus URL with the destination information."""
base = 'http://us.megabus.com/JourneyResults.aspx?'
origincode = 'originCode=' + generate_city_code(origin)
destinationcode = '&destinationCode=' + generate_city_code(destination) # Crawling date is provided twice
departuredate = '&<API key>=' + generate_date(crawling_date) # This is done to get both outgoing
coming_back = '&<API key>=' + generate_date(crawling_date) # and ingoing trips with the same URL
passengers = '&passengerCount=' + passengers
rest_of_url = '&transportType=0&concessionCount=0&nusCount=0&<API key>=0&<API key>=0&<API key>=0&<API key>=0&outboundPcaCount=0&inboundPcaCount=0&promotionCode=&withReturn=1'
url = base + origincode + destinationcode + departuredate + coming_back + passengers + rest_of_url
return url
def params_message(soup):
""" prints a consise message of the search being done """
soup = soup
message = []
# The message is stored under tag div, in class "search_params"
print('|SEARCHING FOR TRIP TO|')
for word in soup.findAll('div', {"class": "search_params"}):
message.append(word.getText())
for word in message:
# Removes tabs and space.
word = word.replace('\t', '')
word = word.replace('\n', '')
print(word)
def format_trip_id(number, mode):
"""formats the ID to be search with the numerical id(number)"""
# This functions returns the link to be used to search for trips.
# mode refers to whereever the trip is inbound or outbound.
# This function is equipped to deal with both
# incoming trips and outgoing trips.
# ID is converted from int to str to be able to concantanate with url.
if mode == 'inbound':
if number > 9:
# If ID is a two digit number, it formats the last two digits.
number = str(number)
id = '<API key>'
id = id.replace('07', number)
return id
else:
# If Id is a one digit number, it formats the last digit only.
number = str(number)
id = '<API key>'
id = id.replace('7', number)
return id # returns the formatted ID to be used to search for trips
if mode == 'outbound':
if number > 9:
number = str(number)
id = '<API key>'
id = id.replace('09', number)
return id
else:
number = str(number)
id = '<API key>'
id = id.replace('9', number)
return id
else:
print("Something is wrong with Mode")
def download_trips(url, id, mode):
"""Returns a string with the trip information """
identification = format_trip_id(id, mode)
html = webtools.DownloadData(url)
temp = []
trip = []
for trip_data in html.findAll('ul', id=identification):
temp.append(trip_data.getText())
for word in temp:
word = word.replace('\t', '')
word = word.replace('\n', '')
word = word.replace('\r', '')
trip.append(word)
return trip |
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <chainparams.h>
#include <chainparamsbase.h>
#include <logging.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <util/translation.h>
#include <wallet/wallettool.h>
#include <functional>
#include <stdio.h>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
static void SetupWalletToolArgs()
{
SetupHelpOptions(gArgs);
<API key>();
gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-wallet=<wallet-name>", "Specify wallet name", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-debug=<category>", "Output debugging information (default: 0).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -debug is true, 0 otherwise).", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("info", "Get wallet info", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
gArgs.AddArg("create", "Create new wallet file", ArgsManager::ALLOW_ANY, OptionsCategory::COMMANDS);
}
static bool WalletAppInit(int argc, char* argv[])
{
SetupWalletToolArgs();
std::string error_message;
if (!gArgs.ParseParameters(argc, argv, error_message)) {
tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error_message.c_str());
return false;
}
if (argc < 2 || HelpRequested(gArgs)) {
std::string usage = strprintf("%s feathercoin-wallet version", PACKAGE_NAME) + " " + FormatFullVersion() + "\n\n" +
"wallet-tool is an offline tool for creating and interacting with Feathercoin Core wallet files.\n" +
"By default wallet-tool will act on wallets in the default mainnet wallet directory in the datadir.\n" +
"To change the target wallet, use the -datadir, -wallet and -testnet/-regtest arguments.\n\n" +
"Usage:\n" +
" feathercoin-wallet [options] <command>\n\n" +
gArgs.GetHelpMessage();
tfm::format(std::cout, "%s", usage.c_str());
return false;
}
// check for printtoconsole, allow -debug
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", gArgs.GetBoolArg("-debug", false));
if (!CheckDataDirOption()) {
tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
SelectParams(gArgs.GetChainName());
return true;
}
int main(int argc, char* argv[])
{
#ifdef WIN32
util::WinCmdLineArgs winArgs;
std::tie(argc, argv) = winArgs.get();
#endif
SetupEnvironment();
RandomInit();
try {
if (!WalletAppInit(argc, argv)) return EXIT_FAILURE;
} catch (const std::exception& e) {
<API key>(&e, "WalletAppInit()");
return EXIT_FAILURE;
} catch (...) {
<API key>(nullptr, "WalletAppInit()");
return EXIT_FAILURE;
}
std::string method {};
for(int i = 1; i < argc; ++i) {
if (!IsSwitchChar(argv[i][0])) {
if (!method.empty()) {
tfm::format(std::cerr, "Error: two methods provided (%s and %s). Only one method should be provided.\n", method.c_str(), argv[i]);
return EXIT_FAILURE;
}
method = argv[i];
}
}
if (method.empty()) {
tfm::format(std::cerr, "No method provided. Run `feathercoin-wallet -help` for valid methods.\n");
return EXIT_FAILURE;
}
// A name must be provided when creating a file
if (method == "create" && !gArgs.IsArgSet("-wallet")) {
tfm::format(std::cerr, "Wallet name must be provided when creating a new wallet.\n");
return EXIT_FAILURE;
}
std::string name = gArgs.GetArg("-wallet", "");
ECCVerifyHandle globalVerifyHandle;
ECC_Start();
if (!WalletTool::<API key>(method, name))
return EXIT_FAILURE;
ECC_Stop();
return EXIT_SUCCESS;
} |
package pt.utl.ist.cmov.bomberman.game.drawing;
import pt.utl.ist.cmov.bomberman.util.Position;
public class RobotDrawing extends Drawing {
private static final long serialVersionUID = -<API key>;
public RobotDrawing() {
super();
}
public RobotDrawing(Integer id, Position pos) {
super(id, pos, "images/robot.png");
}
} |
gulp is a toolkit for automating painful or time-consuming tasks in your development workflow, so you can stop messing around and build something.
Gulp
Node.js IO
Gulp
API Gulp
http:
gulp
http://gulpjs.com/
1. gulp
$ npm install --global gulp
2. devDependencies
$ npm install --save-dev gulp
3. gulpfile.js
var gulp = require('gulp');
gulp.task('default', function() {
});
4. gulp
$ gulp |
/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
jQuery(function($){
$.datepicker.regional.nl = {
closeText: 'Sluiten',
prevText: '←',
nextText: '→',
currentText: 'Vandaag',
monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun',
'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
weekHeader: 'Wk',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional.nl);
}); |
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { createPost } from '../actions';
class PostsNew extends Component {
renderField(field) {
const className = `form-group ${field.meta.touched && field.meta.error ? 'has-danger' : ""}`;
return (
<div className={className}>
<label>{field.label}</label>
<input className="form-control"
type="text"
{...field.input}
/>
<div className="text-help">{field.meta.touched ? field.meta.error : ''}</div>
</div>
);
}
onSubmit(values) {
this.props.createPost(values, () => {
this.props.history.push('/');
});
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Post Title"
name="title"
component={this.renderField}
/>
<Field
label="Caregories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
<Link to="/" className="btn btn-danger">Cancel</Link>
</form>
);
}
}
function validate(values) {
const errors = {};
if (!values.title || values.title.length < 3) {
errors.title = "Title must be at least 3 characters long"
};
if (!values.categories) {
errors.categories = "Enter some categories"
};
if (!values.content) {
errors.content = "Enter some content"
}
return errors;
};
export default reduxForm({
validate,
form: 'PostsNewForm'
})(
connect(null, { createPost })(PostsNew)
); |
#ifndef <API key>
#define <API key>
#include "agraph.hpp"
template<typename Node>
class Graph : public AbstractGraph<Node> {
public:
using super = AbstractGraph<Node>;
using nodes = typename super::nodes;
using edges = typename super::edges;
Graph() : super() {}
explicit Graph(edges es) : super(es) {}
void add_edge(Node n1, Node n2) override {
this->es.insert({n1, nodes{}});
this->es.insert({n2, nodes{}});
this->es[n1].push_back(n2);
this->es[n2].push_back(n1);
}
void del_edge(Node n1, Node n2) override {
auto i1 = this->es.find(n1);
auto i2 = this->es.find(n2);
const auto end = this->es.end();
if (i1 == end || i2 == end) {
return;
}
auto &v1 = i1->second;
auto &v2 = i2->second;
v1.erase(std::remove(v1.begin(), v1.end(), n2), v1.end());
v2.erase(std::remove(v2.begin(), v2.end(), n1), v2.end());
}
};
template<typename Node>
class DiGraph : public AbstractGraph<Node> {
public:
using super = AbstractGraph<Node>;
using nodes = typename super::nodes;
using edges = typename super::edges;
DiGraph() : super() {}
explicit DiGraph(edges es) : super(es) {}
void add_edge(Node n1, Node n2) override {
this->es.insert({n1, nodes{}});
this->es.insert({n2, nodes{}});
this->es[n1].push_back(n2);
}
void del_edge(Node n1, Node n2) override {
auto i1 = this->es.find(n1);
if (i1 == this->es.end()) {return;}
auto &v1 = i1->second;
v1.erase(std::remove(v1.begin(), v1.end(), n2), v1.end());
}
};
#endif // <API key> |
#!/usr/bin/env python3
import calendar
if __name__ == "__main__":
for num in range(1, 13):
month = calendar.month_name[num]
print(f"{num:02} - {month}") |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>: 2016/8 | </title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description">
<meta property="og:type" content="website">
<meta property="og:title" content="">
<meta property="og:url" content="http://yoursite.com/archives/2016/08/page/2/index.html">
<meta property="og:site_name" content="">
<meta property="og:description">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="">
<meta name="<TwitterConsumerkey>">
<link rel="stylesheet" href="/vendor/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/vendor/titillium-web/styles.css">
<link rel="stylesheet" href="/vendor/source-code-pro/styles.css">
<link rel="stylesheet" href="/css/style.css">
<script src="/vendor/jquery/2.0.3/jquery.min.js"></script>
<link rel="stylesheet" href="/vendor/fancybox/jquery.fancybox.css">
<link rel="stylesheet" href="/vendor/scrollLoading/style.css">
<script type="text/javascript">
(function(i,s,o,g,r,a,m) {i['<API key>']=r;i[r]=i[r]||function() {
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.<API key>(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','
ga('create', 'UA-75836479-1', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div id="wrap">
<header id="header">
<div id="header-outer" class="outer">
<div class="container">
<div class="container-inner">
<div id="header-title">
<h1 class="logo-wrap">
<a href="/" class="logo"></a>
</h1>
</div>
<div id="header-inner" class="nav-container">
<a id="main-nav-toggle" class="nav-icon fa fa-bars"></a>
<div class="nav-container-inner">
<ul id="main-nav">
<li class="main-nav-list-item" >
<a class="main-nav-list-link" href="/"></a>
</li>
<li class="main-nav-list-item" >
<a class="main-nav-list-link" href="/"></a>
</li>
</ul>
<nav id="sub-nav">
<div id="search-form-wrap">
<form action="
</div>
</nav>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container">
<div class="main-body container-inner">
<div class="main-body-inner">
<section id="main">
<div class="main-body-header">
<h1 class="header">
<i class="icon fa fa-archive"></i>: 2016/8
</h1>
</div>
<div class="main-body-content">
<section class="archives-wrap">
<div class="archive-year-wrap">
<a href="/archives/2016" class="archive-year"><i class="icon fa fa-calendar-o"></i>2016</a>
</div>
<div class="archives">
<div class="article-row">
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/314/" class="thumbnail">
<span style="background-image:url(/./images/314/0001.jpg)" alt="N00564 ailin 48P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/314/">N00564 ailin 48P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/313/" class="thumbnail">
<span style="background-image:url(/./images/313/0001.jpg)" alt="VOL.014 52P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/313/">VOL.014 52P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
</div>
<div class="article-row">
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/312/" class="thumbnail">
<span style="background-image:url(/./images/312/0001.jpg)" alt="VOL.013 57P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/312/">VOL.013 57P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/311/" class="thumbnail">
<span style="background-image:url(/./images/311/0001.jpg)" alt="Vol.019 Mandy 50P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/311/">Vol.019 Mandy 50P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
</div>
<div class="article-row">
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/310/" class="thumbnail">
<span style="background-image:url(/./images/310/0001.jpg)" alt="VOL.012 72P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/310/">VOL.012 72P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/309/" class="thumbnail">
<span style="background-image:url(/./images/309/0001.jpg)" alt="VOL.010 53P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/309/">VOL.010 53P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
</div>
<div class="article-row">
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/308/" class="thumbnail">
<span style="background-image:url(/./images/308/0001.jpg)" alt="VOL.011 52P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/308/">VOL.011 52P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/307/" class="thumbnail">
<span style="background-image:url(/./images/307/0001.jpg)" alt="VOL.008 53P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/307/">VOL.008 53P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
</div>
<div class="article-row">
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/306/" class="thumbnail">
<span style="background-image:url(/./images/306/0001.jpg)" alt="VOL.009 48P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/306/">VOL.009 48P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
<article class="article article-summary">
<div class="<API key>">
<a href="/2016/08/31/305/" class="thumbnail">
<span style="background-image:url(/./images/305/0001.jpg)" alt="Vol.017 51P" class="thumbnail-image"></span>
<span class="comment-counter">
<i class="fa fa-comments-o"></i>
</span>
</a>
<div class="article-meta">
<p class="category">
</p>
<p class="date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
<h1 class="article-title" itemprop="name">
<a href="/2016/08/31/305/">Vol.017 51P</a>
</h1>
<p class="article-excerpt">
</p>
</div>
</article>
</div>
</div></section>
<nav id="page-nav">
<span class="pages"> 2 12 </span>
<a class="extend prev" rel="prev" href="/archives/2016/08/">«</a><a class="page-number" href="/archives/2016/08/">1</a><span class="page-number current">2</span><a class="page-number" href="/archives/2016/08/page/3/">3</a><a class="page-number" href="/archives/2016/08/page/4/">4</a><span class="space">…</span><a class="page-number" href="/archives/2016/08/page/12/">12</a><a class="extend next" rel="next" href="/archives/2016/08/page/3/">»</a>
</nav>
</div>
</section>
<aside id="sidebar">
<a class="sidebar-toggle" title="Expand Sidebar"><i class="toggle icon"></i></a>
<div class="sidebar-top">
<p> :</p>
<ul class="social-links">
</ul>
</div>
<div class="widgets-container">
<div class="widget-wrap">
<h3 class="widget-title"></h3>
<div class="widget">
<ul id="recent-post" class="">
<li>
<div class="item-thumbnail">
<a href="/2016/08/31/258/" class="thumbnail">
<span style="background-image:url(/./images/258/4267775750.jpeg)" alt=" – Violet 110P" class="thumbnail-image"></span>
</a>
</div>
<div class="item-inner">
<p class="item-category"></p>
<p class="item-title"><a href="/2016/08/31/258/" class="title"> – Violet 110P</a></p>
<p class="item-date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
</li>
<li>
<div class="item-thumbnail">
<a href="/2016/08/31/226/" class="thumbnail">
<span style="background-image:url(/./images/226/1136181514.jpeg)" alt="Cherish 45P" class="thumbnail-image"></span>
</a>
</div>
<div class="item-inner">
<p class="item-category"></p>
<p class="item-title"><a href="/2016/08/31/226/" class="title">Cherish 45P</a></p>
<p class="item-date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
</li>
<li>
<div class="item-thumbnail">
<a href="/2016/08/31/322/" class="thumbnail">
<span style="background-image:url(/./images/322/0001.jpg)" alt="N00331 Faye 53P" class="thumbnail-image"></span>
</a>
</div>
<div class="item-inner">
<p class="item-category"></p>
<p class="item-title"><a href="/2016/08/31/322/" class="title">N00331 Faye 53P</a></p>
<p class="item-date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
</li>
<li>
<div class="item-thumbnail">
<a href="/2016/08/31/321/" class="thumbnail">
<span style="background-image:url(/./images/321/0001.jpg)" alt="VOL.017 Barbie 58P" class="thumbnail-image"></span>
</a>
</div>
<div class="item-inner">
<p class="item-category"></p>
<p class="item-title"><a href="/2016/08/31/321/" class="title">VOL.017 Barbie 58P</a></p>
<p class="item-date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
</li>
<li>
<div class="item-thumbnail">
<a href="/2016/08/31/320/" class="thumbnail">
<span style="background-image:url(/./images/320/0001.jpg)" alt="VOL.016 Kety 54P" class="thumbnail-image"></span>
</a>
</div>
<div class="item-inner">
<p class="item-category"></p>
<p class="item-title"><a href="/2016/08/31/320/" class="title">VOL.016 Kety 54P</a></p>
<p class="item-date"><time datetime="2016-09-01T01:06:00.000Z" itemprop="datePublished">2016-08-31</time></p>
</div>
</li>
</ul>
</div>
</div>
<div class="widget-wrap widget-list">
<h3 class="widget-title"></h3>
<div class="widget">
<ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/08/">August 2016</a><span class="archive-list-count">120</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">July 2016</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">June 2016</a><span class="archive-list-count">127</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/04/">April 2016</a><span class="archive-list-count">71</span></li></ul>
</div>
</div>
<div class="widget-wrap widget-list">
<h3 class="widget-title"></h3>
<div class="widget">
<ul>
</ul>
</div>
</div>
</div>
</aside>
</div>
</div>
</div>
<footer id="footer">
<div class="container">
<div class="container-inner">
<a id="back-to-top" href="javascript:;"><i class="icon fa fa-angle-up"></i></a>
<div class="credit">
<h1 class="logo-wrap">
<a href="/" class="logo"></a>
</h1>
<p>© 2016 laomao</p>
<p>Powered by <a href="//hexo.io/" target="_blank">Hexo</a>. Theme by <a href="//github.com/ppoffice" target="_blank">PPOffice</a></p>
</div>
</div>
</div>
</footer>
<script src="/vendor/fancybox/jquery.fancybox.pack.js"></script>
<script src="/vendor/scrollLoading/jquery.scrollLoading.js"></script>
<script src="/vendor/scrollLoading/main.js"></script>
<!-- Custom Scripts -->
<script src="/js/main.js"></script>
</div>
</body>
</html> |
layout: single
title: RGB LED POV Globe - Parts shopping
date: 2011-03-23 21:30
categories: Development News
I spent most of the last week doing research and ordering parts samples and testing equipment, trying to get everything set up for this project.
<strong>Things I have ordered.</strong>
<ul>
<li>$75 USD - <a href="http:
<li>$0 - Sample chips from <a href="http:
<ul>
<li>2x, <a href="http://focus.ti.com/docs/prod/folders/print/tlc5947.html">TLC5947 - 24-Channel, 12-Bit PWM LED Driver with Internal Oscillato</a>r</li>
<li>2x, <a href="http://focus.ti.com/docs/prod/folders/print/tlc5952.html">TLC5952 - 24-Channel Constant-Current LED Driver with Global Brightness and LED Open Short Detection</a></li>
<li>2x, <a href="http://focus.ti.com/docs/prod/folders/print/tlc5951.html">TLC5951 - 24 Channel, 12Bit PWM LED Driver w/ 7Bit Dot Correction and 3-Group, 8Bit Global Brightness Control</a></li>
</ul>
</li>
<li>$33 USD - 1x, <a href="http://macetech.com/store/index.php?main_page=product_info&cPath=1&products_id=22">OctoBrite DEFILIPPI</a> ($20 for the board and $13 for shipping). Got one for testing before I buy the rest of the boards. This is one of the most expensive parts of this project and if it doesn't work right it will be the most costly mistake.</li>
<li>$40 CND - ~1750 RPM AC motor with 1/4 shaft. Found a junkyard and priced by its weight. Tested and it works great comes with a pulley as well. Going to do more extensive testing this weekend.</li>
</ul>
<strong>Things I still need to get</strong>
<ul>
<li>A <a href="http:
<li><a href="http:
<li><a href="http:
<li>The main pole. I am looking for a hollow 6 foot pole with heavy walls. I plan to run wires up the center of the pole and distribute them across the spinning ring.</li>
<li>A wooden box to house the motor, power supply and other electronics below the spinning ring.</li>
<li>Micro-controller, Still deciding what one to use.</li>
<li>Cables and connectors, I will decide this after I do testing on the OctoBrite boards.</li>
</ul>
<strong>RGB LED POV Globe</strong>
<ol>
<li><a href="/<API key>/">RGB LED POV Globe - Research</a><strong>
</strong></li>
<li><a href="/rgb-led-pov-globe-%E2%80%93-research-led/">RGB LED POV Globe - Research LED</a></li>
<li><a href="/<API key>/">RGB LED POV Globe</a><a href="/rgb-led-pov-globe-%E2%80%93-research-led/"> - Parts shopping</a></li>
<li><a href="http:
<li><a href="/rgb-led-pov-globe-%e2%80%93-software/">RGB LED POV Globe - Software</a></li>
</ol>
<strong>
</strong> |
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for lib/</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../prettify.css">
<style>
body, html {
margin:0; padding: 0;
}
body {
font-family: Helvetica Neue, Helvetica,Arial;
font-size: 10pt;
}
div.header, div.footer {
background: #eee;
padding: 1em;
}
div.header {
z-index: 100;
position: fixed;
top: 0;
border-bottom: 1px solid #666;
width: 100%;
}
div.footer {
border-top: 1px solid #666;
}
div.body {
margin-top: 10em;
}
div.meta {
font-size: 90%;
text-align: center;
}
h1, h2, h3 {
font-weight: normal;
}
h1 {
font-size: 12pt;
}
h2 {
font-size: 10pt;
}
pre {
font-family: Consolas, Menlo, Monaco, monospace;
margin: 0;
padding: 0;
line-height: 14px;
font-size: 14px;
-moz-tab-size: 2;
-o-tab-size: 2;
tab-size: 2;
}
div.path { font-size: 110%; }
div.path a:link, div.path a:visited { color: #000; }
table.coverage { border-collapse: collapse; margin:0; padding: 0 }
table.coverage td {
margin: 0;
padding: 0;
color: #111;
vertical-align: top;
}
table.coverage td.line-count {
width: 50px;
text-align: right;
padding-right: 5px;
}
table.coverage td.line-coverage {
color: #777 !important;
text-align: right;
border-left: 1px solid #666;
border-right: 1px solid #666;
}
table.coverage td.text {
}
table.coverage td span.cline-any {
display: inline-block;
padding: 0 5px;
width: 40px;
}
table.coverage td span.cline-neutral {
background: #eee;
}
table.coverage td span.cline-yes {
background: #b5d592;
color: #999;
}
table.coverage td span.cline-no {
background: #fc8c84;
}
.cstat-yes { color: #111; }
.cstat-no { background: #fc8c84; color: #111; }
.fstat-no { background: #ffc520; color: #111 !important; }
.cbranch-no { background: yellow !important; color: #111; }
.missing-if-branch {
display: inline-block;
margin-right: 10px;
position: relative;
padding: 0 4px;
background: black;
color: yellow;
xtext-decoration: line-through;
}
.missing-if-branch .typ {
color: inherit !important;
}
.entity, .metric { font-weight: bold; }
.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; }
.metric small { font-size: 80%; font-weight: normal; color: #666; }
div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; }
div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; }
div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; }
div.coverage-summary th.file { border-right: none !important; }
div.coverage-summary th.pic { border-left: none !important; text-align: right; }
div.coverage-summary th.pct { border-right: none !important; }
div.coverage-summary th.abs { border-left: none !important; text-align: right; }
div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; }
div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; }
div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; }
div.coverage-summary td.pic { min-width: 120px !important; }
div.coverage-summary a:link { text-decoration: none; color: #000; }
div.coverage-summary a:visited { text-decoration: none; color: #333; }
div.coverage-summary a:hover { text-decoration: underline; }
div.coverage-summary tfoot td { border-top: 1px solid #666; }
div.coverage-summary .<API key>, div.coverage-summary .<API key> {
height: 10px;
width: 7px;
display: inline-block;
margin-left: 0.5em;
}
div.coverage-summary .<API key> {
background: url("http://yui.yahooapis.com/3.6.0/build/datatable-sort/assets/skins/sam/sort-arrow-sprite.png") no-repeat scroll 0 0 transparent;
}
div.coverage-summary .<API key> .<API key> {
background-position: 0 -20px;
}
div.coverage-summary .<API key> .<API key> {
background-position: 0 -10px;
}
.high { background: #b5d592 !important; }
.medium { background: #ffe87c !important; }
.low { background: #fc8c84 !important; }
span.cover-fill, span.cover-empty {
display:inline-block;
border:1px solid #444;
background: white;
height: 12px;
}
span.cover-fill {
background: #ccc;
border-right: 1px solid #444;
}
span.cover-empty {
background: white;
border-left: none;
}
span.cover-full {
border-right: none !important;
}
pre.prettyprint {
border: none !important;
padding: 0 !important;
margin: 0 !important;
}
.com { color: #999 !important; }
</style>
</head>
<body>
<div class="header high">
<h1>Code coverage report for <span class="entity">lib/</span></h1>
<h2>
Statements: <span class="metric">91.49% <small>(43 / 47)</small></span>
Branches: <span class="metric">100% <small>(27 / 27)</small></span>
Functions: <span class="metric">66.67% <small>(4 / 6)</small></span>
Lines: <span class="metric">91.49% <small>(43 / 47)</small></span>
</h2>
<div class="path"><a href="../index.html">All files</a> » lib/</div>
</div>
<div class="body">
<div class="coverage-summary">
<table>
<thead>
<tr>
<th data-col="file" data-fmt="html" data-html="true" class="file">File</th>
<th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th>
<th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th>
<th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th>
<th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th>
<th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th>
<th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th>
<th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th>
</tr>
</thead>
<tbody><tr>
<td class="file high" data-value="imageresizer.js"><a href="imageresizer.js.html">imageresizer.js</a></td>
<td data-value="91.49" class="pic high"><span class="cover-fill" style="width: 91px;"></span><span class="cover-empty" style="width:9px;"></span></td>
<td data-value="91.49" class="pct high">91.49%</td>
<td data-value="47" class="abs high">(43 / 47)</td>
<td data-value="100" class="pct high">100%</td>
<td data-value="27" class="abs high">(27 / 27)</td>
<td data-value="66.67" class="pct medium">66.67%</td>
<td data-value="6" class="abs medium">(4 / 6)</td>
<td data-value="91.49" class="pct high">91.49%</td>
<td data-value="47" class="abs high">(43 / 47)</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="footer">
<div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Fri Oct 25 2013 23:40:17 GMT+0100 (BST)</div>
</div>
<script src="../prettify.js"></script>
<script src="http://yui.yahooapis.com/3.6.0/build/yui/yui-min.js"></script>
<script>
YUI().use('datatable', function (Y) {
var formatters = {
pct: function (o) {
o.className += o.record.get('classes')[o.column.key];
try {
return o.value.toFixed(2) + '%';
} catch (ex) { return o.value + '%'; }
},
html: function (o) {
o.className += o.record.get('classes')[o.column.key];
return o.record.get(o.column.key + '_html');
}
},
defaultFormatter = function (o) {
o.className += o.record.get('classes')[o.column.key];
return o.value;
};
function getColumns(theadNode) {
var colNodes = theadNode.all('tr th'),
cols = [],
col;
colNodes.each(function (colNode) {
col = {
key: colNode.getAttribute('data-col'),
label: colNode.get('innerHTML') || ' ',
sortable: !colNode.getAttribute('data-nosort'),
className: colNode.getAttribute('class'),
type: colNode.getAttribute('data-type'),
allowHTML: colNode.getAttribute('data-html') === 'true' || colNode.getAttribute('data-fmt') === 'html'
};
col.formatter = formatters[colNode.getAttribute('data-fmt')] || defaultFormatter;
cols.push(col);
});
return cols;
}
function getRowData(trNode, cols) {
var tdNodes = trNode.all('td'),
i,
row = { classes: {} },
node,
name;
for (i = 0; i < cols.length; i += 1) {
name = cols[i].key;
node = tdNodes.item(i);
row[name] = node.getAttribute('data-value') || node.get('innerHTML');
row[name + '_html'] = node.get('innerHTML');
row.classes[name] = node.getAttribute('class');
//Y.log('Name: ' + name + '; Value: ' + row[name]);
if (cols[i].type === 'number') { row[name] = row[name] * 1; }
}
//Y.log(row);
return row;
}
function getData(tbodyNode, cols) {
var data = [];
tbodyNode.all('tr').each(function (trNode) {
data.push(getRowData(trNode, cols));
});
return data;
}
function replaceTable(node) {
if (!node) { return; }
var cols = getColumns(node.one('thead')),
data = getData(node.one('tbody'), cols),
table,
parent = node.get('parentNode');
table = new Y.DataTable({
columns: cols,
data: data,
sortBy: 'file'
});
parent.set('innerHTML', '');
table.render(parent);
}
Y.on('domready', function () {
replaceTable(Y.one('div.coverage-summary table'));
if (typeof prettyPrint === 'function') {
prettyPrint();
}
});
});
</script>
</body>
</html> |
var requirejs = require('requirejs');
requirejs.config({nodeRequire: require});
requirejs(['./srv.app', './srv.socket'],function(app, io) {
var kickstart = app.kickstart,
router = kickstart.listen();
console.log("Listening on http://%s:%d", kickstart.conf().name, router.address().port);
}); |
var webpack = require('webpack')
var WebpackDevServer = require('webpack-dev-server')
var config = require('./webpack.config')
var express = require('express')
const PORT = 3009
var app = new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
contentBase: __dirname + '/'
})
app.use('/audio', express.static(__dirname + '/../../../audio-for-testing/'))
app.listen(PORT, 'localhost', function (err, result) {
if (err) {
console.log(err)
}
console.log('Listening at localhost:' + PORT)
}) |
<header id="header">
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<button type="button" id="nav-toggle" class="navbar-toggle" data-toggle="collapse" data-target="#navigation-menu">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#top-page-banner"><img src="<?php echo base_url() ?>assets/img/logo.png" alt="logo" role="banner"></a>
</div>
<nav id="navigation-menu" class="collapse navbar-collapse" role="navigation">
<ul class="nav navbar-nav navbar-right">
<li><a id="GoToHome" class="selected-nav" href="#top-page-banner">Home</a></li>
<li><a id="GoToFeatures" href="#features">Features</a></li>
<li><a id="GoToScreens" href="#screens">Screens</a></li>
<li><a id="GoToTeam" href="#team">Team</a></li>
<!-- <li><a id="GoToPricing" href="#pricing">Pricing</a></li> -->
<li><a id="GoToFaq" href="#faq">FAQ</a></li>
<li><a id="GoToContact" href="#contact">Contact</a></li>
</ul>
</nav> <!-- /.nav-collapse -->
</div> <!-- /.container -->
</div> <!-- /.navbar -->
</header> <!-- END HEADER --> |
// Generated by class-dump 3.5 (64 bit).
#import "NSView.h"
@interface NSView (IBViewAdditions)
+ (id)ib_viewWithSize:(struct CGSize)arg1;
- (void)<API key>;
- (void)<API key>:(id)arg1;
- (id)<API key>;
- (void)<API key>:(struct CGRect)arg1;
- (id)<API key>;
- (BOOL)isMouse:(struct CGPoint)arg1 inRect:(struct CGRect)arg2;
- (id)<API key>:(CDUnknownBlockType)arg1;
- (void)scrollRectToVisible:(struct CGRect)arg1 <API key>:(BOOL)arg2 duration:(double)arg3;
- (void)scrollRectToVisible:(struct CGRect)arg1 <API key>:(BOOL)arg2;
- (struct CGRect)<API key>:(struct CGRect)arg1 keepingRectVisible:(struct CGRect)arg2;
- (CDStruct_f6143a38)convertLine:(CDStruct_f6143a38)arg1 fromView:(id)arg2;
- (CDStruct_f6143a38)convertLine:(CDStruct_f6143a38)arg1 toView:(id)arg2;
- (long long)convertKnobPosition:(long long)arg1 fromView:(id)arg2;
- (long long)convertKnobPosition:(long long)arg1 toView:(id)arg2;
- (unsigned long long)convertRectEdge:(unsigned long long)arg1 fromView:(id)arg2;
- (unsigned long long)convertRectEdge:(unsigned long long)arg1 toView:(id)arg2;
- (id)<API key>:(id)arg1;
- (id)<API key>:(id)arg1;
- (id)<API key>:(id)arg1;
- (struct CGRect)<API key>;
- (struct CGPoint)<API key>:(struct CGPoint)arg1;
- (struct CGPoint)<API key>:(struct CGPoint)arg1;
- (struct CGSize)convertSizeToScreen:(struct CGSize)arg1;
- (struct CGSize)<API key>:(struct CGSize)arg1;
- (struct CGRect)<API key>:(struct CGRect)arg1;
- (struct CGRect)convertRectToScreen:(struct CGRect)arg1;
- (struct CGSize)<API key>:(struct CGSize)arg1;
- (struct CGSize)<API key>:(struct CGSize)arg1;
- (struct CGSize)<API key>:(struct CGSize)arg1;
- (struct CGSize)convertSizeToWindow:(struct CGSize)arg1;
- (struct CGPoint)<API key>:(struct CGPoint)arg1;
- (struct CGPoint)<API key>:(struct CGPoint)arg1;
- (struct CGRect)<API key>:(struct CGRect)arg1;
- (struct CGRect)convertRectToWindow:(struct CGRect)arg1;
- (CDStruct_c519178c)<API key>:(CDStruct_c519178c)arg1;
- (CDStruct_c519178c)<API key>:(CDStruct_c519178c)arg1;
- (CDStruct_c519178c)convertInset:(CDStruct_c519178c)arg1 fromView:(id)arg2;
- (CDStruct_c519178c)convertInset:(CDStruct_c519178c)arg1 toView:(id)arg2;
- (struct CGRect)<API key>:(id)arg1 convertedToView:(id)arg2;
- (struct CGRect)<API key>:(id)arg1;
- (struct CGRect)<API key>;
- (void)makeRectVisible:(struct CGRect)arg1 ofView:(id)arg2;
- (void)makeRectVisible:(struct CGRect)arg1;
- (void)insertSubview:(id)arg1 atIndex:(long long)arg2;
- (void)<API key>:(CDUnknownBlockType)arg1;
- (BOOL)isVisible;
- (void)<API key>:(id)arg1 block:(CDUnknownBlockType)arg2;
- (BOOL)<API key>;
@end |
#ifndef _CPP_LOAD_JPEG_H_
#define _CPP_LOAD_JPEG_H_
#include "../export.h"
#include <dlib/image_io.h>
#include "../shared.h"
#include "../template.h"
using namespace dlib;
using namespace std;
#pragma region template
#define load_jpeg_template(__TYPE__, error, type, ...) \
dlib::load_jpeg(*((array2d<__TYPE__>*)image), std::string(file_name, file_name_length));
#pragma endregion template
DLLEXPORT int load_jpeg(array2d_type type,
void* image,
const char* file_name,
const int file_name_length,
std::string** error_message)
{
int error = ERR_OK;
try
{
array2d_template(type,
error,
load_jpeg_template,
image,
file_name,
file_name_length);
}
catch(dlib::image_load_error& e)
{
error = <API key>;
*error_message = new std::string(e.what());
}
return error;
}
#endif |
export { default } from 'ember-cli-uniq/components/uni-mobile-number'; |
path: "/article/change-log"
date: "2018-03-22"
title: "Change Log SUT 2.0 Neo"
author: "Daivd Kviloria"
| |
|
| ```sut.createHistory``` | ```ADD``` | ```2.0-NEO``` |
| ```Assert.Obj``` | ```Removed``` | ```2.0-NEO``` |
| ```sut.connect``` | ```ADD``` | ```2.0-NEO``` |
| ```sut.template``` | ```ADD``` | ```2.0-NEO``` | |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cadastrar Funcionário</title>
<link rel="stylesheet" href="css/bootstrap.min.css" media="screen" title="no title">
<link rel="stylesheet" href="css/vanilla.css" media="screen" title="no title">
<script src="js/jquery.js" charset="utf-8"></script>
<script src="js/bootstrap.min.js" charset="utf-8"></script>
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top navbar-cor">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="
<img class="alinha-icone-navbar" src="imgs/icone-navbar.png" height="35">
</a>
<p class="navbar-text">Gerencia Estoque Show</p>
</div>
<ul class="nav navbar-nav">
<li><a class="navbar-link-ativo" href="
<li><a href="#">Produtos</a></li>
<li><a href="
</ul>
<div class="pull-right">
<ul class="nav navbar-nav">
<li><a href="
<li><a href="#">Sair <i class="glyphicon glyphicon-remove"></i></a></li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
<ol class="breadcrumb">
<li><a href="#">Home</a></li>
<li><a href="
<li class="active"><a href="
</ol>
</div>
<div class="col-xs-12">
<form>
<div class="form-group">
<label for="nome">Nome:</label>
<input type="text" class="form-control" id="nome" placeholder="Insira um Nome:">
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label for="cpf">CPF:</label>
<input type="number" class="form-control" name="cpf" id="cpf" placeholder="Insira um CPF:">
</div>
<div class="col-xs-6">
<label for="rg">RG:</label>
<input type="text" class="form-control" name="rg" id="senha_confirma" placeholder="Insira um RG:">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Insira um Email:">
</div>
<div class="col-xs-6">
<label for="sexo">Sexo:</label>
<select class="form-control" name="sexo">
<option>Masculino</option>
<option>Feminino</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label for="senha">Senha:</label>
<input type="password" class="form-control" name="senha" id="senha" placeholder="Insira a Senha:">
</div>
<div class="col-xs-6">
<label for="senha_confirma">Confirmação de Senha:</label>
<input type="password" class="form-control" name="senha_confirma" id="senha_confirma" placeholder="Confirme a Senha:">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<button type="submit" class="btn btn-success btn-block"><p>Cadastrar Funcionário</p><p><i class="glyphicon glyphicon-ok"></i></p></button>
</div>
<div class="col-xs-6">
<button type="submit" class="btn btn-danger btn-block"><p>Cancelar</p><p><i class="glyphicon glyphicon-remove"></i></p></button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<nav class="navbar navbar-default navbar-fixed-bottom navbar-cor">
<div class="container-fluid">
</div>
</nav>
</body>
</html> |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public interface ICoinCollector {
int CollectedCoins { get; set; }
// give coin to collector
void GiveCoins(int coins);
// recive coins from collector
int TakeCoins();
} |
module.exports = {
port: 8089,
devServerPort: 8088
} |
class DefinitionDslTest < ActiveSupport::TestCase
def definition_dsl
MergingQueue::DefinitionDSL.new(:new_enquiry)
end
def <API key>
assert definition_dsl.attributes[:name] == :new_enquiry
end
def <API key>
dsl = definition_dsl
dsl.actor(:User)
assert dsl.attributes[:actor] == :User
end
def <API key>
dsl = definition_dsl
dsl.act_object(:Article)
assert dsl.attributes[:act_object] == :Article
end
def <API key>
dsl = definition_dsl
dsl.act_target(:Volume)
assert dsl.attributes[:act_target] == :Volume
end
end |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>moo-java: com.msu.moo.model.interfaces.IFactory< T extends IVariable > Interface Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">moo-java
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Variables</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>com</b></li><li class="navelem"><b>msu</b></li><li class="navelem"><b>moo</b></li><li class="navelem"><b>model</b></li><li class="navelem"><b>interfaces</b></li><li class="navelem"><a class="el" href="interfacecom_1_1msu_1_1moo_1_1model_1_1interfaces_1_1IFactory_3_01T_01extends_01IVariable_01_4.html">IFactory< T extends IVariable ></a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="interfacecom_1_1msu_1_1moo_1_1model_1_1interfaces_1_1IFactory_3_01T_01extends_01IVariable_01_4-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">com.msu.moo.model.interfaces.IFactory< T extends IVariable > Interface Reference</div> </div>
</div><!--header
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">T </td><td class="memItemRight" valign="bottom"><a class="el" href="interfacecom_1_1msu_1_1moo_1_1model_1_1interfaces_1_1IFactory_3_01T_01extends_01IVariable_01_4.html#<API key>">create</a> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>This class represents a factory class that could construct new variable randomly.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname"><T></td><td>variable type </td></tr>
</table>
</dd>
</dl>
</div><h2 class="groupheader">Member Function Documentation</h2>
<a class="anchor" id="<API key>"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">T com.msu.moo.model.interfaces.IFactory< T extends <a class="el" href="<API key>.html">IVariable</a> >.create </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Create a new object from the class. </p>
<dl class="section return"><dt>Returns</dt><dd>new random instance. </dd></dl>
</div>
</div>
<hr/>The documentation for this interface was generated from the following file:<ul>
<li>src/main/java/com/msu/moo/model/interfaces/IFactory.java</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Tue Sep 15 2015 11:05:33 for moo-java by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html> |
var Promise = require('bluebird')
, _ = require('lodash')
, passport = require('passport')
, config = require('config-url')
, strategy = require('./strategy')
, handler = require('./handler')
, User = require('../model/User')
, { URL, URLSearchParams } = require('url')
;
let strategies = strategy.enabled();
_.each(strategies, (s) => passport.use(s));
passport.serializeUser((user, done) => done(null, user._id));
passport.deserializeUser((_id, done) => {
// set user to false will invalidate user and del session
User
.findById(_id)
.exec()
.then((user) => {
return !!user? user : false;
})
.catch((err) => {
return false;
})
.asCallback(done);
});
function authenticate(provider, req, res, next) {
let { config:strategy_config } = strategies[provider] || {}
, impersonate = config.has('account.impersonate.username')
? config.get('account.impersonate.username')
: undefined
;
let rdns = User.reverseDNS(provider);
Promise
.resolve(impersonate)
.then((impersonate) => {
if (impersonate) {
return User
.findOne({ provider, [`accounts.${rdns}.username`] : impersonate })
.exec()
.then((user) => {
if (!user) {
throw new Error('debug profile not found');
}
let profile = _.get(user.accounts, rdns)
, { _token, _tokenSecret} = profile
;
req.provider = provider;
return handler.handler(req, _token, _tokenSecret, profile);
});
}
// todo [akamel] we call this twice in both /auth and then in /callback; in /callback we don't need the params
// todo [akamel] /login doesn't exist here
var params = {
failureRedirect : '/login'
, state : JSON.stringify(req.query)
, scope : strategy_config.scope
};
return Promise.fromCallback((cb) => passport.authenticate(provider, params, cb)(req, res, next));
})
.then((user) => {
return Promise
.fromCallback((cb) => req.logIn(user, cb))
.then(() => {
return user.issueJWT({ expiresIn : 60 /*seconds*/ })
})
.then((token) => {
let uri = new URL(config.getUrl('account.oauth.callback'))
, search = new URLSearchParams('')
;
search.append('token', token);
search.append('sid', user._id.toString());
uri.search = search;
res.redirect(uri.toString());
});
})
.catch((err) => {
console.error(err);
throw err;
})
.asCallback(next);
};
function login(req, res, next) {
let { provider } = req.params;
if (config.has('account.impersonate.username')) {
res.redirect(`/auth/${provider}/callback`);
return;
}
authenticate(provider, req, res, next);
}
function logout(req, res, next) {
req.logout();
next();
}
function callback(req, res, next) {
let { provider } = req.params;
authenticate(provider, req, res, next);
}
module.exports = {
login
, logout
, callback
, passport
}; |
#import "MOBProjection.h"
@interface <API key> : MOBProjection
@end |
#include "<API key>.h"
void init_trampoline(int running_mode)
{
continuation_stack = (void_ptr_ptr_func*) malloc(sizeof(void_ptr_ptr_func) * <API key>);
<API key> = continuation_stack;
<API key> = &(continuation_stack[<API key>]);
}
void shutdown_trampoline()
{
free(continuation_stack);
continuation_stack = NULL;
<API key> = NULL;
<API key> = NULL;
}
void execute_trampoline(void_ptr_ptr_func function)
{
while (function != NULL) {
function = (void_ptr_ptr_func)((*function)());
}
}
void grow_cp_stack()
{
int size = <API key> - continuation_stack;
continuation_stack = (void_ptr_ptr_func*) realloc(continuation_stack, sizeof(void_ptr_ptr_func) * (size*2));
<API key> = &continuation_stack[size];
<API key> = &(continuation_stack[size*2]);
}
void_ptr_ptr_func <API key>()
{
sm_obj expr, obj, env;
expr = POP_M();
env = POP_M();
switch (get_tag(expr)) {
case TAG_SYMBOL:
obj = get_binding(expr, env);
if (obj == NULL)
ERROR_CODE("Unknown variable or function given.", 44);
PUSH_M(obj);
return LOAD_CP();
case TAG_CONS:
PUSH_M(env);
PUSH_M(expr);
PUSH_M(env);
PUSH_M(car(expr));
SAVE_CP(contparse_func_eval);
return <API key>;
default:
PUSH_M(expr);
return LOAD_CP();
}
}
void_ptr_ptr_func contparse_func_eval()
{
sm_obj data, func, func_args, env;
func = POP_M();
data = POP_M();
env = POP_M();
func_args = cdr(data);
switch (get_tag(func)) {
case TAG_SYS_SYNTAX:
return (*func->sm_sys_syntax.code)(func_args, env);
case TAG_SYS_FUNC:
case TAG_USER_FUNC:
{
if (is_nil(func_args)) {
if (get_tag(func) == TAG_SYS_FUNC)
(*func->sm_sys_func.code)(0);
return LOAD_CP();
}
// Function with first argument
PUSH_M(func);
PUSH_M(env);
PUSH_M(data);
PUSH_M(cdr(func_args));
PUSH_M(new_int(0));
PUSH_M(env);
PUSH_M(car(func_args));
SAVE_CP(contparse_args_eval);
return <API key>;
}
default:
ERROR_CODE("Unknown function reference.", 53);
return NULL;
}
}
void_ptr_ptr_func contparse_args_eval()
{
sm_obj data, func, eval_arg, rest_args, num_args, env;
eval_arg = POP_M();
num_args = POP_M();
int nargs = int_val(num_args) + 1;
rest_args = POP_M();
data = POP_M();
env = POP_M();
func = POP_M();
PUSH_M(eval_arg);
// This is the 1+x argument but not the last
if (!is_nil(rest_args)) {
PUSH_M(func);
PUSH_M(env);
PUSH_M(data);
PUSH_M(cdr(rest_args));
PUSH_M(new_int(nargs));
PUSH_M(env);
PUSH_M(car(rest_args));
SAVE_CP(contparse_args_eval);
return <API key>;
}
// All arguments have been evaluated, we can execute
if (func->sm_any.tag == TAG_SYS_FUNC) {
(*func->sm_sys_func.code)(nargs);
return LOAD_CP();
}
PUSH_M(new_int(nargs));
PUSH_M(env);
PUSH_M(func);
SAVE_CP(<API key>);
return <API key>;
}
void_ptr_ptr_func <API key>()
{
sm_obj func, nargs_obj;
func = POP_M();
nargs_obj = POP_M();
int nargs = int_val(nargs_obj);
// Create environment for user function
sm_obj func_args = func->sm_user_func.args;
sm_obj func_body = func->sm_user_func.body;
sm_obj body_result = sm_nil();
sm_obj func_env = allocate_env(INIT_USER_ENV_SIZE, MAIN_ENV);
while (nargs
sm_obj arg_name = car(func_args);
func_args = cdr(func_args);
sm_obj arg_input = POP_M();
sm_obj arg_value = sm_eval(arg_input, func_env);
add_binding(arg_name, arg_value, &func_env);
}
PUSH_M(func_env);
PUSH_M(func_body);
return <API key>;
}
void_ptr_ptr_func <API key>()
{
sm_obj env, body;
body = POP_M();
env = POP_M();
if(is_nil(cdr(body))) {
PUSH_M(env);
PUSH_M(car(body));
return <API key>;
}
// Save rest of body to evaluate
PUSH_M(env);
PUSH_M(cdr(body));
// Evaluate the next one
PUSH_M(env);
PUSH_M(car(body));
SAVE_CP(<API key>);
return <API key>;
}
void_ptr_ptr_func <API key>()
{
sm_obj env, body, last;
last = POP_M();
body = POP_M();
env = POP_M();
if(is_nil(cdr(body))) {
PUSH_M(env);
PUSH_M(car(body));
return <API key>;
}
// Save rest of body to evaluate
PUSH_M(env);
PUSH_M(cdr(body));
// Evaluate the next one
PUSH_M(env);
PUSH_M(car(body));
SAVE_CP(<API key>);
return <API key>;
}
// Built in cp based syntax
// Helper function for contparse set/define to avoid code duplication
static void assign_symbol(sm_obj args, sm_obj env)
{
sm_obj literal = car(args);
sm_obj data = cdr(args);
if (is_symbol(literal)) {
sm_obj object = car(data);
sm_obj value = sm_eval(object, env);
add_binding(literal, value, &env);
PUSH(sm_void(), MAIN_STACK);
return;
}
if (is_cons(literal)) {
sm_obj object = car(literal);
if (is_symbol(object)) {
sm_obj args = cdr(literal);
sm_obj func = new_user_func(args, data);
add_binding(object, func, &env);
PUSH(sm_void(), MAIN_STACK);
return;
}
}
}
void_ptr_ptr_func <API key>(sm_obj args, sm_obj env)
{
sm_obj literal = car(args);
sm_obj entry = sm_nil();
if (is_symbol(literal))
entry = get_binding(literal, env);
if (is_cons(literal)) {
entry = get_binding(car(literal), env);
literal = car(literal);
}
if (entry != NULL)
ERROR_CODE("define tried to redefine existing symbol, use set! instead.", 54);
PUSH_M(env);
PUSH_M(args);
SAVE_CP(<API key>);
return <API key>;
}
void_ptr_ptr_func <API key>()
{
sm_obj args, env;
args = POP_M();
env = POP_M();
assign_symbol(args, env);
PUSH_M(sm_void());
return LOAD_CP();
}
void_ptr_ptr_func contparse_set_front(sm_obj args, sm_obj env)
{
sm_obj literal = car(args);
sm_obj entry = sm_nil();
if (is_symbol(literal))
entry = get_binding(literal, env);
if (is_cons(literal)) {
entry = get_binding(car(literal), env);
literal = car(literal);
}
if (entry == NULL)
ERROR_CODE("set tried to set non-existing symbol, use define instead.", 54);
PUSH_M(env);
PUSH_M(args);
SAVE_CP(<API key>);
return contparse_set_back;
}
void_ptr_ptr_func contparse_set_back()
{
sm_obj args, env;
args = POP_M();
env = POP_M();
assign_symbol(args, env);
PUSH_M(sm_void());
return LOAD_CP();
}
void_ptr_ptr_func contparse_lambda(sm_obj args, sm_obj env)
{
if (!is_cons(args))
ERROR_CODE("lambda function expects at least 2 arguments.", 45);
sm_obj lambda_args = car(args);
sm_obj body_args = cdr(args);
if(!is_cons(body_args))
ERROR_CODE("lambda function expects two list objects (cons) as parameters.", 45);
sm_obj lambda_func = new_user_func(lambda_args, body_args);
PUSH_M(lambda_func);
return LOAD_CP();
}
void_ptr_ptr_func contparse_display(sm_obj args, sm_obj env)
{
sm_obj literal = car(args);
sm_obj end = cdr(args);
if (end != sm_nil())
ERROR_CODE("display function expects exactly 1 argument.", 45);
sm_print(literal, true);
PUSH_M(sm_void());
return LOAD_CP();
}
void_ptr_ptr_func contparse_quote(sm_obj args, sm_obj env)
{
PUSH_M(args);
return LOAD_CP();
}
void_ptr_ptr_func contparse_if_front(sm_obj args, sm_obj env)
{
if (!is_cons(args))
ERROR_CODE("if function expects at least 2 arguments.", 45);
sm_obj test_cond = car(args);
sm_obj true_cond = car(cdr(args));
sm_obj false_cond = cdr(cdr(args));
sm_obj result = sm_eval(test_cond, MAIN_ENV);
PUSH_M(env);
PUSH_M(result);
PUSH_M(true_cond);
PUSH_M(false_cond);
SAVE_CP(<API key>);
return contparse_if_back;
}
void_ptr_ptr_func contparse_if_back()
{
sm_obj env, result, true_cond, false_cond;
false_cond = POP_M();
true_cond = POP_M();
result = POP_M();
env = POP_M();
if (result == sm_true() || (is_int(result) && int_val(result) > 0)) {
sm_obj true_branch = sm_eval(true_cond, MAIN_ENV);
PUSH_M(true_branch);
return LOAD_CP();
}
else if(false_cond != sm_nil()) {
sm_obj false_branch = sm_eval(false_cond, MAIN_ENV);
PUSH_M(false_branch);
return LOAD_CP();
}
PUSH_M(sm_void());
return LOAD_CP();
} |
order: 10
title:
en-US: size
zh-CN:
## zh-CN
## en-US
Two compacted table size: `middle` and `small`, `small` size is used in Modal only.
`jsx
import { Table } from 'igroot';
const columns = [{
title: 'Name',
dataIndex: 'name',
}, {
title: 'Age',
dataIndex: 'age',
}, {
title: 'Address',
dataIndex: 'address',
}];
const data = [{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
}, {
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
}, {
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park',
}];
ReactDOM.render(
<div>
<h4>Middle size table</h4>
<Table columns={columns} dataSource={data} size="middle" />
<h4>Small size table</h4>
<Table columns={columns} dataSource={data} size="small" />
</div>,
mountNode);
`
<style>#<API key> h4 { margin-bottom: 16px; }</style> |
(function() {
define([
'angular',
'user/services/session',
'messenger/services/messenger',
'$socket'
], function (
angular,
SessionService,
MessengerService,
$socket
) {
return angular.module("application.controllers")
.controller("MessengerCtrl", [
"$rootScope",
"$scope",
"$socket",
"$location",
"SessionService",
"MessengerService",
function($rootScope, $scope,$socket, $location, SessionService, MessengerService) {
var init;
var startMessenger;
var moduleUrl = '/app/messenger';
$scope.contacts = {};
$scope.contactsOpen = [];
$scope.templates = {};
$scope.contactList = {};
init = function() {
$scope.contactList.show = false;
$scope.templates.messengerBox = {
name: 'messenger-box.html',
url: moduleUrl + '/views/messenger-box.html'
};
/*
$scope.templates.messageFrom = '';
$scope.templates.messageTo = {
name: 'messenger-box.html',
url: '/templates/messenger-box.html'
};
*/
//$scope.templates.;
//$scope.template = $scope.templates[1];
$scope.contacts = {};
$scope.user = SessionService.getUser();
//if($scope.user.authorized){
startMessenger($scope);
};
/**
* Get messenger data and start
* @return {[type]} [description]
*/
startMessenger = function ($scope){
MessengerService.start(
//success
function(data) {
angular.forEach(data.friendList, function(contact, key){
// set default values for every contact
if(!contact.messages){
contact.messages = [];
}
if(!contact.messengerBox){
contact.messengerBox = {};
}
$scope.contacts[contact.id] = contact;
});
},
// error
function(data) {
console.log('Error on startMessegner', data);
}
);
/*
$socket.get('/messenger/start', function (response) {
console.log(response);
console.log('starting messenger socket io');
});
*/
}
$scope.contactList.open = function (){
$scope.contactList.show = true;
}
$scope.contactList.close = function (){
$scope.contactList.show = false;
}
$scope.startTalk = function (contactId){
$scope.contacts[contactId].messengerBox.show = true;
$scope.contacts[contactId].messengerBox.opened = true;
}
$scope.messengerBoxClose = function(contactId) {
$scope.contacts[contactId].messengerBox.show = false;
}
$scope.messengerBoxToggle = function(contactId) {
console.log('togle: ',$scope);
if($scope.contacts[contactId].messengerBox.opened){
$scope.contacts[contactId].messengerBox.opened = false;
}else{
$scope.contacts[contactId].messengerBox.opened = true;
}
}
$scope.<API key> = function (contactId){
console.log($scope);
$scope.startTalk(contactId);
$scope.$apply();
}
$scope.send = function (newMessage, toId, event){
event.preventDefault();
event.stopPropagation();
var user = SessionService.getUser();
var newMessageObj = {};
console.log(user);
newMessageObj.content = newMessage;
newMessageObj.toId = [ toId ];
newMessageObj.fromId = user.id;
newMessageObj.status = 'sending';
$scope.contacts[toId].messages.push(newMessageObj);
$scope.contacts[toId].newMessage = '';
$socket.post(
'/users/'+toId+'/messenger',
newMessageObj ,
function (response) {
console.log(response);
});
}
/*
var scope = SessionService;
if(!scope.user) scope.user = {};
*/
$rootScope.$watch('user', function(newValue, oldValue) {
$scope.user = newValue;
});
// Socket IO
/**
* Receive a messenger message
* @param Object data
*/
$socket.on("receive:message", function(data) {
var newMessageObj = {};
var user = SessionService.getUser();
newMessageObj.content = data.message.content;
newMessageObj.toId = user.id ;
newMessageObj.fromId = data.message.fromId;
newMessageObj.status = 'sending';
$scope.contacts[data.message.fromId].messages.push(data.message);
/*
var objDiv = document.getElementById("messengerBox-" + newMessageObj.fromId);
objDiv.prop({ scrollTop: $("#chatbox").prop("scrollHeight") });
*/
console.log($scope);
$scope.<API key>(newMessageObj.fromId);
});
/**
* Message receveid after a contact disconect
* @param object data
*/
$socket.on("contact:connect", function(data) {
var user = SessionService.getUser();
var contact = data.contact;
if(user.id != contact.id){
// set default values for every contact
if(!contact.messages){
contact.messages = [];
}
if(!contact.messengerBox){
contact.messengerBox = {};
}
$scope.contacts[contact.id] = contact;
//$scope.contacts[data.contact.id] = ;
$scope.$apply();
}
});
/**
* Message receveid after a contact disconect
* @param object data
*/
$socket.on("contact:disconnect", function(data) {
delete $scope.contacts[data.contact.id];
$scope.$apply();
});
return init();
}
]);
});
}()); |
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
namespace Autofac.Features.OpenGenerics {
using System;
using System.Reflection;
<summary>
A strongly-typed resource class, for looking up localized strings, etc.
</summary>
// This class was auto-generated by the <API key>
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.<API key>("System.Resources.Tools.<API key>", "15.0.0.0")]
[global::System.Diagnostics.<API key>()]
[global::System.Runtime.CompilerServices.<API key>()]
internal class <API key> {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.<API key>("Microsoft.Performance", "CA1811:<API key>")]
internal <API key>() {
}
<summary>
Returns the cached ResourceManager instance used by this class.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Autofac.Features.OpenGenerics.<API key>", typeof(<API key>).GetTypeInfo().Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
<summary>
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
</summary>
[global::System.ComponentModel.<API key>(global::System.ComponentModel.<API key>.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
<summary>
Looks up a localized string similar to The service '{0}' is not an open generic type..
</summary>
internal static string <API key> {
get {
return ResourceManager.GetString("<API key>", resourceCulture);
}
}
}
} |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C
#region Using directives
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceProcess;
using ManagedIrbis;
using Telegram.Bot.Types.Enums;
#endregion
// ReSharper disable LocalizableElement
namespace IrbisBot
{
class Program
{
private static void RunService()
{
ServiceBase[] servicesToRun = new ServiceBase[]
{
new BotService()
};
ServiceBase.Run(servicesToRun);
}
private static void InstallService()
{
<API key>.Install();
}
private static void UninstallService()
{
<API key>.Uninstall();
}
private static void StartService()
{
try
{
ServiceController controller
= new ServiceController(BotService.IrbisBot);
controller.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static void StopService()
{
try
{
ServiceController controller
= new ServiceController(BotService.IrbisBot);
controller.Stop();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static void ShowVersion()
{
Console.WriteLine
(
"IrbisBot - Telegram bot for IBRIS64\n"
+ "version {0}",
IrbisConnection.ClientVersion
);
}
static void <API key>()
{
Console.WriteLine("IrbisBot version {0}", IrbisConnection.ClientVersion);
Console.WriteLine("Running as console application");
Console.WriteLine();
var client = Bot.GetClient();
Bot.MessageLoop();
//client.StartReceiving(new UpdateType[0]);
Console.WriteLine("Start listening");
Console.WriteLine("Press ENTER to stop");
Console.ReadLine();
client.StopReceiving();
Console.WriteLine("Stopped");
Console.WriteLine();
}
private static void ShowHelp()
{
Console.WriteLine
(
"IrbisBot - Telegram bot for IRBIS64\n\n"
+ "\t-install \tinstall the service\n"
+ "\t-uninstall \tuninstall the service\n"
+ "\t-start \t\tstart the service\n"
+ "\t-stop \t\tstop the service\n"
+ "\t-console \trun the service as console application\n"
+ "\t-version \tshow version and exit\n"
+ "\t-help \t\tshow this screen and exit\n\n"
);
}
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol =
// <API key>.Ssl3 |
// <API key>.Tls |
// <API key>.Tls11 |
<API key>.Tls12;
ServicePointManager.<API key> = false;
ServicePointManager.<API key>
= <API key>;
if (args.Length == 0)
{
if (Debugger.IsAttached)
{
<API key>();
}
else if (Environment.UserInteractive)
{
ShowHelp();
}
else
{
RunService();
}
}
else if (args.Length == 1)
{
switch (args[0].ToLowerInvariant())
{
case "-install":
case "/install":
case "-i":
case "/i":
InstallService();
break;
case "-uninstall":
case "/uninstall":
case "-u":
case "/u":
UninstallService();
break;
case "-start":
case "/start":
case "-run":
case "/run":
case "-r":
case "/r":
case "/1":
case "-1":
StartService();
break;
case "-stop":
case "/stop":
case "-s":
case "/s":
case "-0":
case "/0":
StopService();
break;
case "-console":
case "/console":
case "-c":
case "/c":
<API key>();
break;
case "-version":
case "/version":
case "-v":
case "/v":
ShowVersion();
break;
default:
ShowHelp();
break;
}
}
else
{
ShowHelp();
}
}
private static bool <API key>
(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslpolicyerrors
)
{
return true;
}
}
} |
<aside class="{{ include.classes }}" style="background-color:{{ include.bgcolor }};">
<h2>Resurrecting the Past?</h2>
{% asset 2015/cover-shapiro-book.jpg @magick:resize=200 alt:"How to clone a mammoth by Beth Shapiro" class:"left" %}
<p>Shapiro's brand-new book, How to Clone a Mammoth: The Science of De-Extinction, isn't a how-to manual.
Making an exact copy of an extinct animal is impossible. But some day, an animal might be assembled with some of the genetic code from an extinct one.</p>
<p>The idea is controversial, scientifically difficult, maybe unattainable, and poses all kinds of quandaries. Yet it's worth exploring the ideas, the goals, the impacts and the ethics, said Shapiro.
Her book disentangles current-day science from science fiction, and argues that reviving individual species is misguided and probably unethical.</p>
<p>But she sees value in resurrecting extinct traits to "help living species adapt to a changing environment," and to revitalize and restore ecosystems and biological interactions.</p>
<p>Shapiro is a faculty member of the UCSC Genomics Institute's Genome 10K Project, which aims "to understand how complex animal life evolved through changes in DNA and use this knowledge to become better stewards of the planet." The project is working toward assembling a collection of DNA sequences that represent the genomic diversity of 10,000 vertebrate species.</p>
<p>One of the possibilities, she said, is to identify mutations or diversity that once existed within a population, "and then come up with new technologies to reengineer these populations on the brink of extinction to contain diversity that's recently been lost."</p>
<p>"De-extinction could be a game changer for our modern conservation crisis and that is what makes the science potentially so useful," she concluded.</p>
</aside> |
import $ from "jquery";
import { getCLS, getFID, getLCP } from "web-vitals";
export class GoogleAnalytics {
<API key>({ name, delta, id }) {
window.gtag("event", name, {
event_category: "web_vitals",
event_label: id,
value: Math.round(name === "CLS" ? delta * 1000 : delta),
non_interaction: true,
});
}
trackCoreWebVitals() {
getCLS(this.<API key>);
getFID(this.<API key>);
getLCP(this.<API key>);
}
}
$(function () {
$.ajax(window.BASE_PREFIX + "/dropdown/templates.json").done(function (data) {
const GAInstance = new GoogleAnalytics();
GAInstance.trackCoreWebVitals();
// bootstrap select2
$("#input-gitignore").select2({
data: data,
theme: "toptal", // customized theme
multiple: true,
allowClear: false,
minimumInputLength: 1,
selectOnClose: true,
placeholder: $("#<API key>").text(),
sorter: function (results) {
const query = $(".<API key>").val().toLowerCase();
return results.sort(function (a, b) {
return (
a.text.toLowerCase().indexOf(query) -
b.text.toLowerCase().indexOf(query)
);
});
},
});
// load pre-selected tags from URL search params
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("templates") != null) {
const <API key> = urlParams
.get("templates")
.replace(/\s/g, "+")
.toLowerCase()
.split(",");
const validIDs = data.map(function (datum) {
return datum.id;
});
const <API key> = <API key>.filter(function (
term
) {
return validIDs.indexOf(term) >= 0;
});
$("#input-gitignore")
.val(<API key>)
.trigger("change.select2");
} else {
// in order to fix the problem where placeholder gets cut off
$("#input-gitignore").val("").trigger("change.select2");
}
// Highlight input on site load
setTimeout(function () {
$(".<API key>").focus();
// prevent dropdown opening on page load focus
$("#input-gitignore").on("select2:opening", function (e) {
e.preventDefault();
$("#input-gitignore").off("select2:opening");
});
});
});
// All users to press ctrl+enter to create template
$("#input-gitignore").on("select2:selecting", function (e) {
setTimeout(function () {
$(".<API key>").keydown(function (e) {
if (e.keyCode == 13 && (e.metaKey || e.ctrlKey)) {
generateGitIgnore();
}
});
});
});
// prevent auto sorting of tags selection, keep the order in which they are added
$("#input-gitignore").on("select2:select", function (e) {
var id = e.params.data.id;
var option = $(e.target).children('[value="' + id + '"]');
option.detach();
$(e.target).append(option).change();
});
// bind click handler to "Create" button
$("#btn-gitignore").click(function () {
generateGitIgnore();
});
// Delete selections by tag instead of individual letter
$.fn.select2.amd.require(["select2/selection/search"], function (Search) {
Search.prototype.searchRemoveChoice = function (decorated, item) {
this.trigger("unselect", {
data: item,
});
this.$search.val("");
this.handleSearch();
};
});
// Generate gitignore template
function generateGitIgnore() {
const searchString = $("#input-gitignore")
.map(function () {
return $(this).val();
})
.get()
.join(",");
const searchLength = searchString.length;
if (searchLength > 0) {
const files = searchString.replace(/^,/, "");
window.location = window.BASE_PREFIX + "/api/" + files;
$("#input-gitignore").val("");
}
}
// Generate gitignore file template
function <API key>() {
const searchString = $("#input-gitignore")
.map(function () {
return $(this).val();
})
.get()
.join(",");
const searchLength = searchString.length;
if (searchLength > 0) {
const files = searchString.replace(/^,/, "");
window.location = window.BASE_PREFIX + "/api/f/" + files;
}
}
}); |
import pygame as pg
class Spritesheet:
def __init__(self, filename, tile_size):
self.sheet = pg.image.load(filename).convert_alpha()
self.tile_size = tile_size
def get_image(self, x, y, width, height):
image = pg.Surface((width, height))
image.blit(self.sheet, (0, 0), (x, y, width, height))
return image
def get_image_alpha(self, x, y, width, height):
image = pg.Surface((width, height), pg.SRCALPHA)
image.blit(self.sheet, (0, 0), (x, y, width, height))
return image
def <API key>(self, col, row):
return self.get_image(col * self.tile_size, row * self.tile_size, self.tile_size, self.tile_size)
def <API key>(self, col, row):
return self.get_image_alpha(col * self.tile_size, row * self.tile_size, self.tile_size, self.tile_size) |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Dice: dice::decomposition< ValueType, ProbabilityType > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Dice
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="<API key>">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>dice</b></li><li class="navelem"><a class="el" href="<API key>.html">decomposition</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#pub-types">Public Types</a> |
<a href="#pub-methods">Public Member Functions</a> |
<a href="#friends">Friends</a> |
<a href="<API key>.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">dice::decomposition< ValueType, ProbabilityType > Class Template Reference</div> </div>
</div><!--header
<div class="contents">
<p>Object representing a decomposition of a function of random variables.
<a href="<API key>.html#details">More...</a></p>
<p><code>#include <<a class="el" href="<API key>.html">decomposition.hpp</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a>
Public Types</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b>var_type</b> = <a class="el" href="<API key>.html">random_variable</a>< ValueType, ProbabilityType ></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b><API key></b> = <a class="el" href="<API key>.html"><API key></a>< ValueType, ProbabilityType ></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b>value_type</b> = ValueType</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b>probability_type</b> = ProbabilityType</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b>frequency_list</b> = typename var_type::frequency_list</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
using </td><td class="memItemRight" valign="bottom"><b>probability_list</b> = typename var_type::probability_list</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">decomposition</a> (const <a class="el" href="<API key>.html">var_type</a> &variable)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Create decomposition from <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">decomposition</a> (<a class="el" href="<API key>.html">var_type</a> &&variable)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Create decomposition from <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><b>decomposition</b> (std::vector< std::pair< value_type, std::size_t >> &&list)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><b>decomposition</b> (<a class="el" href="<API key>.html">bernoulli_tag</a>, ProbabilityType success)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><b>decomposition</b> (<a class="el" href="<API key>.html">constant_tag</a>, value_type value)</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><b>decomposition</b> (const <a class="el" href="<API key>.html">decomposition</a> &)=default</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
<a class="el" href="<API key>.html">decomposition</a> & </td><td class="memItemRight" valign="bottom"><b>operator=</b> (const <a class="el" href="<API key>.html">decomposition</a> &)=default</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
 </td><td class="memItemRight" valign="bottom"><b>decomposition</b> (<a class="el" href="<API key>.html">decomposition</a> &&)=default</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
<a class="el" href="<API key>.html">decomposition</a> & </td><td class="memItemRight" valign="bottom"><b>operator=</b> (<a class="el" href="<API key>.html">decomposition</a> &&)=default</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator+</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute sum of 2 random variables. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator-</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Subtract other random variable from this. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator*</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute product of 2 random variables. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator/</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Divide this variable by other variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator-</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Multiply this random variable with -1. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">less_than</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A < B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">less_than_or_equal</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A <= B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">equal</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A = B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">not_equal</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A != B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">greater_than</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A > B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A >= B (where A is this random variale). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memTemplParams" colspan="2">template<typename T > </td></tr>
<tr class="memitem:<API key>"><td class="memTemplItemLeft" align="right" valign="top">auto </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">in</a> (const T &lower_bound, const T &upper_bound) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute indicator: A in [a, b] (where A is this random variable). <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">expected_value</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute expected value of this random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">variance</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute variance of this random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">deviation</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute standard deviation of this random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">quantile</a> (ProbabilityType probability) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute quantile of this random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memTemplParams" colspan="2">template<typename <API key> > </td></tr>
<tr class="memitem:<API key>"><td class="memTemplItemLeft" align="right" valign="top">auto </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">combine</a> (const <a class="el" href="<API key>.html">decomposition</a> &other, <API key> combination) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute function of 2 random variables: A and B. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a class="el" href="<API key>.html">var_type</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">to_random_variable</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Convert this decomposition to basic random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">has_dependencies</a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Check whether this decomposition depends on other random variables. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>"><API key></a> () const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Compute the decomposition of this random variable. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">operator==</a> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Check whether this is exactly equal to other decomposition. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
bool </td><td class="memItemRight" valign="bottom"><b>operator!=</b> (const <a class="el" href="<API key>.html">decomposition</a> &other) const</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
auto </td><td class="memItemRight" valign="bottom"><b>begin</b> () const</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
auto </td><td class="memItemRight" valign="bottom"><b>end</b> () const</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
std::size_t </td><td class="memItemRight" valign="bottom"><b>size</b> () const</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
auto & </td><td class="memItemRight" valign="bottom"><b>variables_internal</b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
auto & </td><td class="memItemRight" valign="bottom"><b><API key></b> ()</td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a>
Friends</h2></td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top"><a id="<API key>"></a>
class </td><td class="memItemRight" valign="bottom"><b><API key>< ValueType, ProbabilityType ></b></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:<API key>"><td class="memItemLeft" align="right" valign="top">auto </td><td class="memItemRight" valign="bottom"><a class="el" href="<API key>.html#<API key>">roll</a> (const <a class="el" href="<API key>.html">decomposition</a> &num_rolls, const <a class="el" href="<API key>.html">decomposition</a> &num_sides)</td></tr>
<tr class="memdesc:<API key>"><td class="mdescLeft"> </td><td class="mdescRight">Roll num_rolls times with a dice of num_sides. <a href="#<API key>">More...</a><br /></td></tr>
<tr class="separator:<API key>"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><h3>template<typename ValueType, typename ProbabilityType><br />
class dice::decomposition< ValueType, ProbabilityType ></h3>
<p>Object representing a decomposition of a function of random variables. </p>
<p>It is an adapter for <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>.</p>
<p>It uses the Law of total probability to decompose varibales to conditional variables which are then treated as independent.</p>
<p>Variables are organized in a tree structure. Only leaf nodes are stored in the vars_ list. Inner nodes are implicitly given by the deps_ list. Each variable in the deps_ list corresponds to a level of this tree.</p>
<p>An inner node in this tree is a random variable. It has children corresponding to its values. For example: a random variable whose values are 1 or 2 whould have 2 children labeled 1 and 2. A leaf node is a random variable without children nodes.</p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname">ValueType</td><td>type of a value (same as in <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>) </td></tr>
<tr><td class="paramname">ProbabilityType</td><td>type of probability (same as in <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>)</td></tr>
</table>
</dd>
</dl>
<dl class="section see"><dt>See also</dt><dd><a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a> </dd></dl>
</div><h2 class="groupheader">Constructor & Destructor Documentation</h2>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>decomposition() <span class="overload">[1/2]</span></h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::<a class="el" href="<API key>.html">decomposition</a> </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">var_type</a> & </td>
<td class="paramname"><em>variable</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">explicit</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Create decomposition from <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">variable</td><td>random variable </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>decomposition() <span class="overload">[2/2]</span></h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::<a class="el" href="<API key>.html">decomposition</a> </td>
<td>(</td>
<td class="paramtype"><a class="el" href="<API key>.html">var_type</a> && </td>
<td class="paramname"><em>variable</em></td><td>)</td>
<td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">explicit</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Create decomposition from <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">variable</td><td>random variable </td></tr>
</table>
</dd>
</dl>
</div>
</div>
<h2 class="groupheader">Member Function Documentation</h2>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>combine()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<div class="memtemplate">
template<typename <API key> > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::combine </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"><API key> </td>
<td class="paramname"><em>combination</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute function of 2 random variables: A and B. </p>
<p>Variables does not need to be independent.</p>
<dl class="tparams"><dt>Template Parameters</dt><dd>
<table class="tparams">
<tr><td class="paramname"><API key></td><td>Combination function of 2 independent random variables. It taks 2 <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a> types and return <a class="el" href="<API key>.html" title="Discrete random variable. ">random_variable</a>.</td></tr>
</table>
</dd>
</dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable B </td></tr>
<tr><td class="paramname">combination</td><td>function of 2 independent random variables</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>random variable that is a function of A and B </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span><API key>()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::<API key> </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute the decomposition of this random variable. </p>
<p>Random variables in leafs (in the vars_ list) are made constants. This makes them independent at the cost of adding new dependencies and thus increasing the size.</p>
<dl class="section return"><dt>Returns</dt><dd>new decomposition </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>deviation()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::deviation </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute standard deviation of this random variable. </p>
<dl class="section return"><dt>Returns</dt><dd>standard deviation </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>equal()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::equal </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A = B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable B</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A = B (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>expected_value()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::expected_value </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute expected value of this random variable. </p>
<dl class="section return"><dt>Returns</dt><dd>expected value of this variable </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>greater_than()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::greater_than </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A > B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable B</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A > B (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span><API key>()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::<API key> </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A >= B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable Y</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A >= YB (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>has_dependencies()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::has_dependencies </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Check whether this decomposition depends on other random variables. </p>
<dl class="section return"><dt>Returns</dt><dd>true iff it has at least 1 dependency </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>in()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<div class="memtemplate">
template<typename T > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::in </td>
<td>(</td>
<td class="paramtype">const T & </td>
<td class="paramname"><em>lower_bound</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const T & </td>
<td class="paramname"><em>upper_bound</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A in [a, b] (where A is this random variable). </p>
<p>The interval is closed.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">lower_bound</td><td>of the interval (a) </td></tr>
<tr><td class="paramname">upper_bound</td><td>of the interval (b)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A in <a href="i.e. a random variable with a bernoulli distribution">a, b</a> </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>less_than()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::less_than </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A < B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable B</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A < B (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>less_than_or_equal()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::less_than_or_equal </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A <= B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable B</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A <= B (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>not_equal()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::not_equal </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute indicator: A != B (where A is this random variale). </p>
<p>Variables does not need to be indepedent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable Y</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>indicator of A != B (i.e. a random variable with a bernoulli distribution) </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator*()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator* </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute product of 2 random variables. </p>
<p>Random variables don't need to be indendent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable (RHS of the operator)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>result of the product </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator+()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator+ </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute sum of 2 random variables. </p>
<p>Random variables don't need to be indendent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable (RHS of the operator)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>distribution of the sum </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator-() <span class="overload">[1/2]</span></h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator- </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Subtract other random variable from this. </p>
<p>Random variables don't need to be indendent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable (RHS of the operator)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>result of the subtraction </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator-() <span class="overload">[2/2]</span></h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator- </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Multiply this random variable with -1. </p>
<dl class="section return"><dt>Returns</dt><dd>negated random variable </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator/()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator/ </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Divide this variable by other variable. </p>
<p>Random variables don't need to be indendent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable (RHS of the operator)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>result of the division </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>operator==()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">bool <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::operator== </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>other</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Check whether this is exactly equal to other decomposition. </p>
<dl class="section attention"><dt>Attention</dt><dd>This test is exact and expensive. It is mainly provided so we can use this type as a value in dice expressions.</dd></dl>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">other</td><td>random variable </td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>true iff the values are exactly equal </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>quantile()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::quantile </td>
<td>(</td>
<td class="paramtype">ProbabilityType </td>
<td class="paramname"><em>probability</em></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute quantile of this random variable. </p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">probability</td><td>between 0 and 1 (not including 0 and 1)</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>quantile </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>to_random_variable()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname"><a class="el" href="<API key>.html">var_type</a> <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::to_random_variable </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Convert this decomposition to basic random variable. </p>
<p>Notice, by performing this operation, we lose information about (in)dependence.</p>
<dl class="section return"><dt>Returns</dt><dd>plain random variable </dd></dl>
</div>
</div>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>variance()</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto <a class="el" href="<API key>.html">dice::decomposition</a>< ValueType, ProbabilityType >::variance </td>
<td>(</td>
<td class="paramname"></td><td>)</td>
<td> const</td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">inline</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Compute variance of this random variable. </p>
<dl class="section return"><dt>Returns</dt><dd>variance of this variable </dd></dl>
</div>
</div>
<h2 class="groupheader">Friends And Related Function Documentation</h2>
<a id="<API key>"></a>
<h2 class="memtitle"><span class="permalink"><a href="#<API key>">◆ </a></span>roll</h2>
<div class="memitem">
<div class="memproto">
<div class="memtemplate">
template<typename ValueType , typename ProbabilityType > </div>
<table class="mlabels">
<tr>
<td class="mlabels-left">
<table class="memname">
<tr>
<td class="memname">auto roll </td>
<td>(</td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>num_rolls</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const <a class="el" href="<API key>.html">decomposition</a>< ValueType, ProbabilityType > & </td>
<td class="paramname"><em>num_sides</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</td>
<td class="mlabels-right">
<span class="mlabels"><span class="mlabel">friend</span></span> </td>
</tr>
</table>
</div><div class="memdoc">
<p>Roll num_rolls times with a dice of num_sides. </p>
<p>Random variables don't have to be independent.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramname">num_rolls</td><td>number of rolls </td></tr>
<tr><td class="paramname">num_sides</td><td>number of faces of each die</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>distribution of the dice roll </dd></dl>
</div>
</div>
<hr/>The documentation for this class was generated from the following file:<ul>
<li>C:/projects/dice/src/<a class="el" href="<API key>.html">decomposition.hpp</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by &
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.14
</small></address>
</body>
</html> |
#include <debug.h>
#include <dev/gpio.h>
#include <kernel/thread.h>
#include "gpio_hw.h"
#include "panel.h"
#include <platform/machtype.h>
#include <dev/lcdc.h>
#if DISPLAY_TYPE_MDDI
#include <mddi.h>
#define <API key> 0x108000
#define <API key> 0x110000
#define SPI_BLOCK_BASE 0x120000
#define I2C_BLOCK_BASE 0x130000
#define PWM_BLOCK_BASE 0x140000
#define GPIO_BLOCK_BASE 0x150000
#define SYSTEM_BLOCK1_BASE 0x160000
#define SYSTEM_BLOCK2_BASE 0x170000
#define MDDICAP0 (<API key>|0x00)
#define MDDICAP1 (<API key>|0x04)
#define MDDICAP2 (<API key>|0x08)
#define MDDICAP3 (<API key>|0x0C)
#define MDCAPCHG (<API key>|0x10)
#define MDCRCERC (<API key>|0x14)
#define TTBUSSEL (<API key>|0x18)
#define DPSET0 (<API key>|0x1C)
#define DPSET1 (<API key>|0x20)
#define DPSUS (<API key>|0x24)
#define DPRUN (<API key>|0x28)
#define SYSCKENA (<API key>|0x2C)
#define TESTMODE (<API key>|0x30)
#define FIFOMONI (<API key>|0x34)
#define INTMONI (<API key>|0x38)
#define MDIOBIST (<API key>|0x3C)
#define MDIOPSET (<API key>|0x40)
#define BITMAP0 (<API key>|0x44)
#define BITMAP1 (<API key>|0x48)
#define BITMAP2 (<API key>|0x4C)
#define BITMAP3 (<API key>|0x50)
#define BITMAP4 (<API key>|0x54)
#define SRST (<API key>|0x00)
#define PORT_ENB (<API key>|0x04)
#define START (<API key>|0x08)
#define PORT (<API key>|0x0C)
#define CMN (<API key>|0x10)
#define GAMMA (<API key>|0x14)
#define INTFLG (<API key>|0x18)
#define INTMSK (<API key>|0x1C)
#define MPLFBUF (<API key>|0x20)
#define HDE_LEFT (<API key>|0x24)
#define VDE_TOP (<API key>|0x28)
#define PXL (<API key>|0x30)
#define HCYCLE (<API key>|0x34)
#define HSW (<API key>|0x38)
#define HDE_START (<API key>|0x3C)
#define HDE_SIZE (<API key>|0x40)
#define VCYCLE (<API key>|0x44)
#define VSW (<API key>|0x48)
#define VDE_START (<API key>|0x4C)
#define VDE_SIZE (<API key>|0x50)
#define WAKEUP (<API key>|0x54)
#define WSYN_DLY (<API key>|0x58)
#define REGENB (<API key>|0x5C)
#define VSYNIF (<API key>|0x60)
#define WRSTB (<API key>|0x64)
#define RDSTB (<API key>|0x68)
#define ASY_DATA (<API key>|0x6C)
#define ASY_DATB (<API key>|0x70)
#define ASY_DATC (<API key>|0x74)
#define ASY_DATD (<API key>|0x78)
#define ASY_DATE (<API key>|0x7C)
#define ASY_DATF (<API key>|0x80)
#define ASY_DATG (<API key>|0x84)
#define ASY_DATH (<API key>|0x88)
#define ASY_CMDSET (<API key>|0x8C)
#define MONI (<API key>|0xB0)
#define Current (<API key>|0xC0)
#define LCD (<API key>|0xC4)
#define COMMAND (<API key>|0xC8)
#define SSICTL (SPI_BLOCK_BASE|0x00)
#define SSITIME (SPI_BLOCK_BASE|0x04)
#define SSITX (SPI_BLOCK_BASE|0x08)
#define SSIRX (SPI_BLOCK_BASE|0x0C)
#define SSIINTC (SPI_BLOCK_BASE|0x10)
#define SSIINTS (SPI_BLOCK_BASE|0x14)
#define SSIDBG1 (SPI_BLOCK_BASE|0x18)
#define SSIDBG2 (SPI_BLOCK_BASE|0x1C)
#define SSIID (SPI_BLOCK_BASE|0x20)
#define I2CSETUP (I2C_BLOCK_BASE|0x00)
#define I2CCTRL (I2C_BLOCK_BASE|0x04)
#define TIMER0LOAD (PWM_BLOCK_BASE|0x00)
#define TIMER0VALUE (PWM_BLOCK_BASE|0x04)
#define TIMER0CONTROL (PWM_BLOCK_BASE|0x08)
#define TIMER0INTCLR (PWM_BLOCK_BASE|0x0C)
#define TIMER0RIS (PWM_BLOCK_BASE|0x10)
#define TIMER0MIS (PWM_BLOCK_BASE|0x14)
#define TIMER0BGLOAD (PWM_BLOCK_BASE|0x18)
#define PWM0OFF (PWM_BLOCK_BASE|0x1C)
#define TIMER1LOAD (PWM_BLOCK_BASE|0x20)
#define TIMER1VALUE (PWM_BLOCK_BASE|0x24)
#define TIMER1CONTROL (PWM_BLOCK_BASE|0x28)
#define TIMER1INTCLR (PWM_BLOCK_BASE|0x2C)
#define TIMER1RIS (PWM_BLOCK_BASE|0x30)
#define TIMER1MIS (PWM_BLOCK_BASE|0x34)
#define TIMER1BGLOAD (PWM_BLOCK_BASE|0x38)
#define PWM1OFF (PWM_BLOCK_BASE|0x3C)
#define TIMERITCR (PWM_BLOCK_BASE|0x60)
#define TIMERITOP (PWM_BLOCK_BASE|0x64)
#define PWMCR (PWM_BLOCK_BASE|0x68)
#define PWMID (PWM_BLOCK_BASE|0x6C)
#define PWMMON (PWM_BLOCK_BASE|0x70)
#define GPIODATA (GPIO_BLOCK_BASE|0x00)
#define GPIODIR (GPIO_BLOCK_BASE|0x04)
#define GPIOIS (GPIO_BLOCK_BASE|0x08)
#define GPIOIBE (GPIO_BLOCK_BASE|0x0C)
#define GPIOIEV (GPIO_BLOCK_BASE|0x10)
#define GPIOIE (GPIO_BLOCK_BASE|0x14)
#define GPIORIS (GPIO_BLOCK_BASE|0x18)
#define GPIOMIS (GPIO_BLOCK_BASE|0x1C)
#define GPIOIC (GPIO_BLOCK_BASE|0x20)
#define GPIOOMS (GPIO_BLOCK_BASE|0x24)
#define GPIOPC (GPIO_BLOCK_BASE|0x28)
#define GPIOID (GPIO_BLOCK_BASE|0x30)
#define WKREQ (SYSTEM_BLOCK1_BASE|0x00)
#define CLKENB (SYSTEM_BLOCK1_BASE|0x04)
#define DRAMPWR (SYSTEM_BLOCK1_BASE|0x08)
#define INTMASK (SYSTEM_BLOCK1_BASE|0x0C)
#define CNT_DIS (SYSTEM_BLOCK1_BASE|0x10)
#define GPIOSEL (SYSTEM_BLOCK2_BASE|0x00)
void panel_init(struct mddi_client_caps *client_caps)
{
}
#endif //mddi
void panel_poweron(void)
{
}
void panel_backlight(int on)
{
} |
package de.npe.gameanalytics.events;
import de.npe.gameanalytics.Analytics;
import de.npe.gameanalytics.util.JSON;
/**
* @author NPException
*/
public class GAErrorEvent extends GAEvent {
public enum Severity {
critical,
error,
warning,
info,
debug
}
private final String message;
private final String severity;
public GAErrorEvent(Analytics an, Severity severity, String message) {
super(an);
this.severity = severity.name();
this.message = message;
}
@Override
public String category() {
return "error";
}
@Override
public void toJSON(StringBuilder sb) {
sb.append("\"message\":\"").append(JSON.escape(message)).append("\",");
sb.append("\"severity\":\"").append(JSON.escape(severity)).append("\",");
super.toJSON(sb);
}
} |
<?php
return array (
'id' => 'agfa_40970_ver1',
'fallback' => '<API key>',
'capabilities' =>
array (
'is_tablet' => 'true',
'model_name' => '40970',
'brand_name' => 'Agfa',
'<API key>' => 'false',
'<API key>' => '160',
'<API key>' => '80',
'resolution_width' => '400',
'resolution_height' => '800',
),
); |
#include <iostream>
#include "reader.h"
using namespace std;
using AMOS::Overlap;
int main(int argc, char** argv) {
auto reader = new AMOS::Reader(cin);
while (reader->has_next()) {
Overlap o;
reader->next(&o);
cout << o.adjacency << " " << o.a_id << " " << o.b_id << " " << o.a_hang << " " << o.b_hang << endl;
}
} |
$(document).ready(function() {
$(".myChart").each(function( index ) {
//console.log( index + ": " + $( this ).text() );
//Get context with jQuery - using jQuery's .get() method.
var ctx = $(".myChart").get(index).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
var data = [
{
value: $(this).data("used"),
color:"#c92525"
},
{
value : $(this).data("free"),
color : "#8cc951"
}
]
var options =
{
segmentStrokeColor : "#1e1e1e",
segmentStrokeWidth : 2,
}
new Chart(ctx).Doughnut(data,options);
});
$("#content").on("submit", ".ajaxupdate", function(e) {
var url = $(this).attr('action');
var postdata = $(this).serialize();
alert( postdata );
$.post( url, postdata, function( data ) {
$( ".result" ).html( data );
});
e.preventDefault();
})
$('#status,#docker').on('mouseenter', '.status_button', function() {
$(this).parent().addClass("active");
}).on('mouseleave', '.status_button', function() {
$(this).parent().removeClass("active");
});
$('#status').on('click', '.status_button', function() {
$(this).parent().addClass("active");
}).on('click', '.status_button', function() {
$(this).parent().removeClass("active");
});
var piesize = ( $('#status').hasClass('mini') ) ? 120 : 250;
var barwidth = ( $('#status').hasClass('mini') ) ? 3 : 5;
$('#status').on('click', 'canvas', function() {
$(".status_container", $(this).parent()).addClass("active");
});
$('#status_capacity').easyPieChart({
barColor: function (percent) {
return (percent < 75 ? '#A4BB44' : percent < 90 ? '#f0ad4e' : '#cb3935');
},
trackColor: false,
size: piesize,
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
if($('#download_image').length) {
var tid = setInterval(get_current, 500);
function get_current() {
var img = $('#download_image').data('img');
$.getJSON('/index.php/docker/process_download/'+img, function( data ) {
if( data.percent > 0 ) $('#download_image').data('easyPieChart').update(data.percent);
$('#download_status').html(data.dstatus);
$('#download_percent').html(data.percent);
if( data.dstatus == 'Extracting' && data.percent >= 100 ) abortTimer();
});
}
function abortTimer() { // to be called when you want to stop the timer
clearInterval(tid);
}
$('#download_image').easyPieChart({
barColor: '#A4BB44',
trackColor: false,
size: piesize,
animate: {
duration: 250,
enabled: true
},
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
}
$('.dockerbutton.stopped').easyPieChart({
barColor: '#cb3935',
trackColor: false,
size: piesize,
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
$('.dockerbutton.running').easyPieChart({
barColor: '#A4BB44',
trackColor: false,
size: piesize,
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
$('#status_array').easyPieChart({
barColor: function (percent) {
return ($('#status_array').hasClass('error') ? '#cb3935' : $('#status_array').hasClass('warning') ? '#f0ad4e' : '#A4BB44');
},
trackColor: false,
size: piesize,
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
$('#status_disks').easyPieChart({
barColor: function (percent) {
return ($('#status_disks').hasClass('error') ? '#cb3935' : $('#status_disks').hasClass('warning') ? '#f0ad4e' : '#A4BB44');
},
trackColor: false,
size: piesize,
scaleColor: false,
trackWidth: barwidth,
lineWidth: barwidth,
});
$(window).on("scroll", function() {
var fromTop = $("body").scrollTop();
$('#sticky-main-nav').toggleClass("show", (fromTop > 200));
});
//$("div.tab_container").css("height", $(this).find("div.showscale").outerHeight()+"px");
//$( ".tabs" ).tabs();
$( ".toggle_hidden" ).on("change", function() {
var toggle = $( this ).data( 'toggle' );
if( $(this).is(':checked') ) $( toggle ).slideDown();
else $( toggle ).slideUp();
});
$( ".tabs li a" ).on("click", function() {
$( ".tabs li" ).removeClass("active");
$( this ).parent().addClass("active");
var ind = $(".tabs li a").index(this);
var allbox = $( ".tabs .addontab" );
var box = $( ".tabs .addontab" ).eq(ind);
allbox.removeClass("active");
box.addClass("active");
/*var current = $( ".tabs .addontab .showscale" );
var newheight = box.outerHeight();
current.removeClass("showscale");
current.one('transitionend', function(e) {
box.closest("div.tab_container").css("height", newheight+"px");
box.addClass("showscale");
}); */
if($(this).data("follow") == true) return true;
else return false;
});
}); |
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev <API key>
productionGzip: false,
<API key>: ['js', 'css']
},
dev: {
env: require('./dev.env'),
port: 8881,
proxyTable: {}
}
} |
#ifndef ADC_H_
#define ADC_H_
#define MUX5 3
extern void init_adc();
extern void check_adc();
extern void adc_msg_all(char *txtbuffer);
#endif /* ADC_H_ */ |
package org.openapitools.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.openapitools.model.Link;
import javax.validation.constraints.*;
import io.swagger.annotations.*;
import java.util.Objects;
public class <API key> {
private Link self;
private String propertyClass;
public <API key> self(Link self) {
this.self = self;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("self")
public Link getSelf() {
return self;
}
public void setSelf(Link self) {
this.self = self;
}
public <API key> propertyClass(String propertyClass) {
this.propertyClass = propertyClass;
return this;
}
@ApiModelProperty(value = "")
@JsonProperty("_class")
public String getPropertyClass() {
return propertyClass;
}
public void setPropertyClass(String propertyClass) {
this.propertyClass = propertyClass;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
<API key> <API key> = (<API key>) o;
return Objects.equals(self, <API key>.self) &&
Objects.equals(propertyClass, <API key>.propertyClass);
}
@Override
public int hashCode() {
return Objects.hash(self, propertyClass);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class <API key> {\n");
sb.append(" self: ").append(toIndentedString(self)).append("\n");
sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} |
namespace CloudTemple.SQLServer.Contracts
{
using System;
using System.Linq;
using System.Linq.Expressions;
public interface IGenericRepository<T>
where T : class
{
IQueryable<T> All();
void Add(T entity);
T Delete(T entity);
IQueryable<T> Search(Expression<Func<T, bool>> predicate);
T GetById(int id);
void Detach(T entity);
void SaveChanges();
}
} |
export function resizeImg(img, maxWidth = 1920, maxHeight = 1080) {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
height = Math.round(height);
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
width = Math.round(width);
height = maxHeight;
}
}
// resize the canvas and draw the image data into it
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
return canvas.toDataURL('image/jpeg', 0.7);
}
export function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
let byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
let ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
} |
import {createAction} from 'redux-actions'
import type from '../../constants/actionType'
import ActionCreator from '../../actionCreators/me'
const mockRegister = createAction(type.MOVIE_LIST, ActionCreator.register, ActionCreator.registerValidator)
const actionCreators = {
mockRegister
}
export default {actionCreators} |
title: "Failures"
date: 2017-08-23 03:30
tags: [Ramblings,Poetry]
I know you're my weakness,
and I know you're aware.
I try to compose melodies,
they end up a prayer.
They say you make me strong,
but do they even care ?
For I am tired of asking you for strength,
when you visit my nightmares.
You've toyed with my laughter,
You've kindled my despair.
You make me claustrophobic,
when the wind blows my hair.
But fear is a dark room,
for only so long can he scare.
Soon your eyes adjust,
and then everything's laid bare.
Our next rendezvous is around the corner,
and I have secrets to share.
The dark room is lit up,
You better beware ! |
Example of calling Twitter's API
This is an example of consuming Twitter's REST API using Application-only Authentication.
It uses the standard `HttpURLConnection` of Java for making the requests.
Application-only authentication uses OAuth.
The code currently fetches the most recent tweet of the user whose screen_name is given.
More examples will be added later. |
// Queue(Vector).h
// Algorithm(C++)
#ifndef <API key>
#define <API key>
#include <iostream>
#include <vector>
using namespace std;
template <class Type>
class Queue {
public:
private:
unsigned int capacity_;
unsigned int size_;
typename vector<Type>::iterator front;
typename vector<Type>::iterator rear;
};
#endif /* defined(<API key>) */ |
'use strict';var <API key> = require('./application_common');
exports.bootstrap = <API key>.commonBootstrap;
var application_ref_1 = require('./application_ref');
exports.ApplicationRef = application_ref_1.ApplicationRef;
//# sourceMappingURL=application.js.map |
'use strict';
const Hapi = require('hapi');
const Inert = require('inert');
const Vision = require('vision');
const Handlebars = require('handlebars');
const Config = require('./config');
const Models = require('./models');
const Handlers = require('./handlers');
const Routes = require('./routes');
const server = new Hapi.Server(Config.options);
server.connection({ port: Config.port });
server.register([Inert, Vision]);
server.views({ engines: { hbs: Handlebars }, path: Config.templates });
server.method(Models.authorModel);
server.method(Models.bookModel);
server.method(Models.userModel);
server.ext('onPostHandler', Handlers.postHandler);
server.handler('authors', Handlers.authorHandler);
server.handler('books', Handlers.bookHandler);
server.handler('users', Handlers.userHandler);
server.handler('www', Handlers.wwwHandler);
server.route(Routes.authorRoute);
server.route(Routes.bookRoute);
server.route(Routes.userRoute);
server.route(Routes.wwwRoute);
module.exports = server; |
package models;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class Student {
private String academicTermUid;
private String name;
private String studentGroupUid;
@JsonIgnore
private String key;
public Student() {
}
public String getAcademicTermUid() {
return academicTermUid;
}
public String getName() {
return name;
}
public String getStudentGroupUid() {
return studentGroupUid;
}
@JsonIgnore
public String getKey() {
return key;
}
@JsonIgnore
public void setKey(String key) {
this.key = key;
}
} |
#! /usr/bin/python
#-*- coding:utf-8 -*
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.3 $"
__date__ = "$Date: 2015/08/31$"
__revision__ = "$Date: 2015/10/26 $"
__copyright__ = ""
__license__ = ""
import sys
import requests
import json
import pickle
import clusters
import list_clusters
def recommend(user_id, <API key>, <API key>,
service_url):
"""
Select talks/booths/poster to recommend from clusters.
"""
recommended_talks = []
request = requests.get(service_url + "/api/v1.0/profiles.json/" + user_id,
auth=(<API key>, <API key>))
if request.status_code == 200:
program = json.loads(request.text)["program"]
progam_id = [talk["id"] for talk in program]
with open("clusters", 'rb') as f:
kclust = pickle.load(f)
rownames, colnames, data = clusters.readfile("vectors.txt")
for idx, cluster in enumerate(kclust):
current_cluster = [rownames[r] for r in cluster]
if set(progam_id).intersection(current_cluster):
recommended_talks.extend(current_cluster)
else:
print(request.reason)
return recommended_talks
def <API key>(user_id, <API key>,
<API key>,
recommended_talks):
"""
Update the profile of the user with the previously calculated
recommendations.
"""
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
data = []
for talk_id in recommended_talks:
data.append({"id":talk_id})
payload = {"op":"add", "path":"/recommended_talks", "value":data}
r = requests.patch(service_url + "/api/v1.0/profiles.json/" + user_id,
auth=(<API key>, <API key>),
headers=headers, data=json.dumps(payload))
if r.status_code == 201:
print("Profile updated.")
else:
print r.reason
print r.text
if __name__ == "__main__":
# Point of entry in execution mode
user_id = sys.argv[1]
<API key> = sys.argv[2]
<API key> = sys.argv[3]
try:
service_url = sys.argv[4]
except Exception as e:
service_url = ""
recommended_talks = recommend(user_id, <API key>,
<API key>, service_url)
if len(recommended_talks) != 0:
print("Talks to recommend:")
print(recommended_talks)
print("Updating profile...")
<API key>(user_id, <API key>,
<API key>,
recommended_talks)
else:
print("Nothing to recommend.") |
import os
from django.core.wsgi import <API key>
os.environ.setdefault("<API key>", "django_shopfront.settings")
application = <API key>() |
'use strict';
/**
* Module dependencies.
*/
var log4js = require('log4js');
var log = log4js.getLogger('controller/render.js');
var config = require('nconf');
// End of dependencies.
/**
* Wrapper over res.render().
*/
module.exports = function(template, variables) {
return function (req, res) {
res.render(template, variables);
};
}; |
from django.apps import AppConfig
class ClothesConfig(AppConfig):
name = 'clothes' |
# postimg
:rocket: upload images on imgur & share instantly.(link will be copied to clipboard automatically)
<img src="http://i.imgur.com/aBoKRZe.png" alt="snap" height="200">
[ IMGUR_CLIENT_ID and save it as an environment variable.(although default is hardcoded)
export IMGUR_CLIENT_ID='xxxxxx'
## Installation
pip install postimg
## Usage
$ postimg --help
usage: postimg [-h] [--github] [--html] [--reddit] img_path
Post/upload image on imgur.com
positional arguments:
img_path image path of file
optional arguments:
-h, --help show this help message and exit
--github Github markdown code of imgur url
--html html <img> code of imgur url
--reddit reddit markdown code of imgur url
-q, --quiet print only img url without verbose output
link will automatically copied to clipboard
## Demo
 |
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b> </b></th><td class="std2"></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><sup class="subfont">ˋ</sup><sup class="subfont">ˊ</sup><sup class="subfont">ˋ</sup><sup class="subfont">ˇ</sup></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><font class="english_word">zhào yíng yìng xuě</font></td></tr>
<tr><th class="std1"><b> </b></th><td class="std2"><img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>˙˙<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center><img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center></td></tr>
<tr><th class="std1"><b><font class="fltypefont"></font> </b></th><td class="std2"></td></tr>
</td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table> |
#!/bin/bash
SAVEIMAGES=""
COMPAREIMAGES=""
ARGS=""
RED='\e[0;31m'
GREEN='\e[0;32m'
NOCOLOR='\e[0m'
RETVAL=0
# run all of the samples
# parse the arguments
while test $# -gt 0; do
case "$1" in
--save-images)
SAVEIMAGES="true"
ARGS="$ARGS --save-images"
;;
--compare-images)
COMPAREIMAGES="true"
ARGS="$ARGS --save-images"
;;
-)
echo "error: unknown option"
usage
;;
esac
shift
done
if ! test -z $COMPAREIMAGES; then
if ! test -d 'golden'; then
{ echo >&2 "I require golden images but no golden directory. Aborting."; exit 1; }
fi
type compare >/dev/null 2>&1 || { echo >&2 "I require ImageMagick compare but it's not installed. Aborting."; exit 1; }
fi
# save command directory; note that this file is a link to file of same
# name in samples/src/
CMDDIR="$(dirname "$(readlink -f ${BASH_SOURCE[0]})")"
# get the list of built samples to run
SAMP2RUN=`find $CMDDIR -name *.cpp -not -path "*util*"`
#echo "SAMP2RUN is $SAMP2RUN"
# display short description of the sample and run it
for f in $SAMP2RUN
do
# get short description of the sample source file
DESCRIPT=`$CMDDIR/get-short-descripts.sh --nofname --sampfname $f`
BNAME=$(basename $f)
echo "RUNNING SAMPLE: $BNAME"
echo " ** $DESCRIPT"
# run the built sample; need to remove .cpp from name
RNAME=./${BNAME%.cpp}
$RNAME $ARGS
echo ""
if ! test -z $COMPAREIMAGES; then
GOLDNAME="golden/${RNAME}.ppm"
if test -f $GOLDNAME; then
THISNAME="${RNAME}.ppm"
CMDRES=`compare -metric AE -fuzz 3% $THISNAME $GOLDNAME ${RNAME}-diff.ppm 2>&1`
if [ $CMDRES == "0" ]; then
>&2 echo -e "${GREEN}${RNAME} PASS${NOCOLOR}"
else
>&2 echo -e "${RED}${RNAME} FAIL${NOCOLOR} : pixel error count is ${CMDRES}"
$SAVEIMAGES="true"
RETVAL=1
fi
fi
fi
if test -z $SAVEIMAGES; then
`rm ${RNAME}.ppm > /dev/null 2>&1`
`rm ${RNAME}-diff.ppm > /dev/null 2>&1`
fi
done
exit $RETVAL |
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
zip = require('gulp-zip'),
pack = require('./package.json');
gulp.task('sass', [], function() { |
<?php
namespace Colin\Bundle\ActionBundle\Action;
use Symfony\Component\Form\<API key>;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;
class ReadAction implements ActionInterface
{
private $templating;
private $entityManager;
private $configs;
public function __construct(
EngineInterface $templating,
EntityManager $entityManager,
array $configs
) {
$this->templating = $templating;
$this->entityManager = $entityManager;
$this->configs = $configs;
}
public function execute(Request $request)
{
$repository = $this->entityManager->getRepository($this->configs['entity_class']);
$method = 'find';
$entity = $repository->$method($request->get('id'));
if (!$entity) {
throw new <API key>('Entity not found.');
}
return new Response($this->templating->render($this->configs['template'], [
'entity' => $entity,
]));
}
} |
package jdk.util;
import java.util.Arrays;
import java.util.Optional;
public final class Optionals {
private Optionals() { }
@SafeVarargs
public static <T> T any(Optional<T>... optionals) {
return Arrays
.stream(optionals)
.filter(Optional::isPresent)
.findFirst()
.map(Optional::get)
.orElseThrow( () -> new <API key>("None of the given optionals did return a value"));
}
} |
import React, { Component } from 'react' // eslint-disable-line no-unused-vars
class MainModOptions extends Component {
componentWillMount(){
this.data = {}
fetch('/mods/mainModData/' + this.props.modId)
.then(res => res.json())
.then(result => {
this.setState({data: result})
console.log(this.state)
console.log(this.state.data.stringsfolder)
this.data.stringsfolder.value = this.state.data.stringsfolder
})
.catch(e => alert(e))
}
change(e) {
let value = e.target.value
let name = e.target.name
this.setState(state => {
state.data = {}
state.data[name] = value
})
}
upload(e) {
for(let data in this.state.data){
if(!this.state.data.hasOwnProperty(data)) continue
fetch('/mods/mainModData/' + this.props.modId + '/' + data + '/' + this.data.stringsfolder.value, {method: 'POST'})
.then(res => res.json())
.then(() => this.props.update())
.catch(() => {
alert(e)
})
}
e.preventDefault()
}
render() {
return (
<div>
<form>
<p className="title">Mod Options</p>
<label>Strings Folder for Language Files</label>
<input type="text" name="stringsfolder" placeholder="Folder for languages"
ref={input => this.data.stringsfolder = input}/>
<button onClick={(e) => this.upload(e)}>{'Save changes'}</button>
</form>
</div>
)
}
}
export default MainModOptions |
$var title:
<div class="row">
<div class="col-md-12">
<div class="jumbotron">
<h1></h1>
<p class="lead">
Web API</p>
$if 'user' not in session:
<p>
<a href="/qq_login"><img src="static/qq_login.png" /></a>
</p>
</div>
<h2>API</h2>
<p>https://warnings.sinaapp.com/send_warning/{user_id}</p>
<p>POST</p>
<p>URL</p>
<ul>
<li>user_id: id</li>
</ul>
<p>POST</p>
<ul>
<li>app_id: id</li>
<li>title: </li>
<li>content: CPU,</li>
<li>cate: nginxA</li>
<li>host: </li>
<li>appname: </li>
<li>level: </li>
</ul>
<p></p>
<pre>curl https://warnings.sinaapp.com/send_warning/1 -d "app_id=<API key>&title=&content=300M"
</pre>
<p></p>
<ol>
<li>apihttpsbad request</li>
<li>app_id</li>
</ol>
<h2></h2>
<p><a href="https://github.com/onlytiancai/warning-collector" >Github code</a></p>
</div>
</div> |
using System.Linq;
using System.Text;
using Spreadsheet.Core.Utils;
namespace Spreadsheet.Core.Cells
{
public struct CellAddress
{
public int Row { get; }
public int Column { get; }
public CellAddress(int row, int column)
{
Row = row;
if (row < 0)
throw new <API key>(Resources.NegetiveCellRow);
Column = column;
if (column < 0)
throw new <API key>(Resources.NegativeCellColumn);
}
public void Validate(int maxRow, int maxColumn)
{
if (maxRow <= Row)
throw new <API key>(Resources.WrongCellRow);
if (maxColumn <= Column)
throw new <API key>(Resources.WrongCellColumn);
}
public bool Equals(CellAddress other)
{
return Row == other.Row && Column == other.Column;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is CellAddress && Equals((CellAddress)obj);
}
public override int GetHashCode()
{
unchecked
{
return (Row * 397) ^ Column;
}
}
//Slow method with large memory allocation, done for debug purpose
public override string ToString() => <API key>.GetString(this);
}
} |
<ion-view>
<ion-content>
<<API key>></<API key>>
</ion-content>
</ion-view> |
using System;
using <API key>.Foundation.MSSDK.Enums;
using <API key>.Foundation.SCSDK.Wrappers;
using <API key>.Foundation.MSSDK.Repositories.Bing;
using System.Threading.Tasks;
using <API key>.Foundation.MSSDK;
using <API key>.Foundation.MSSDK.Models.Bing.WebSearch;
using <API key>.Foundation.SCSDK.Policies;
namespace <API key>.Foundation.SCSDK.Services.MSSDK.Bing
{
public class WebSearchService : IWebSearchService
{
protected readonly <API key> ApiKeys;
protected readonly IMSSDKPolicyService PolicyService;
protected readonly <API key> WebSearchRepository;
protected readonly ILogWrapper Logger;
public WebSearchService(
<API key> apiKeys,
IMSSDKPolicyService policyService,
<API key> webSearchRepository,
ILogWrapper logger)
{
ApiKeys = apiKeys;
PolicyService = policyService;
WebSearchRepository = webSearchRepository;
Logger = logger;
}
public virtual WebSearchResponse WebSearch(string text, int countOffset = 0, string languageCode = "", SafeSearchOptions safeSearch = SafeSearchOptions.Off)
{
return PolicyService.<API key>(
"WebSearchService.WebSearch",
ApiKeys.<API key>,
() =>
{
var result = WebSearchRepository.WebSearch(text, countOffset, languageCode, safeSearch);
return result;
},
null);
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.