text
stringlengths 12
215k
|
|---|
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:9000/v1/'
});
|
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
describe('my app', function() {
browser.get('index.html');
it('should automatically redirect to /home when location hash/fragment is empty', function() {
expect(browser.getLocationAbsUrl()).toMatch("/home");
});
describe('view1', function() {
beforeEach(function() {
browser.get('index.html#/home');
});
it('should render home when user navigates to /home', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 1/);
});
});
describe('view2', function() {
beforeEach(function() {
browser.get('index.html#/view2');
});
it('should render view2 when user navigates to /view2', function() {
expect(element.all(by.css('[ng-view] p')).first().getText()).
toMatch(/partial for view 2/);
});
});
});
|
b'-1 + -1 + -363 + 347\n'
|
b'Calculate -16 + -15 + -2 + 125 + -125.\n'
|
<?php
/**
* Created by PhpStorm.
* User: robert
* Date: 1/14/15
* Time: 3:06 PM
*/
namespace Skema\Directive;
class Binding extends Base {
}
|
b'13 - 9 - (10 - 0 - -1) - -15\n'
|
b'290 + -287 + (1 + 0 - 11) + 2\n'
|
b'What is 1 + 2 - (-23 + 39 - 16)?\n'
|
b'Calculate -55 - (15 + -49) - -13.\n'
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class Product(Model):
_required = []
_attribute_map = {
'integer': {'key': 'integer', 'type': 'int'},
'string': {'key': 'string', 'type': 'str'},
}
def __init__(self, *args, **kwargs):
"""Product
:param int integer
:param str string
"""
self.integer = None
self.string = None
super(Product, self).__init__(*args, **kwargs)
|
b'Evaluate -24 + 22 - (-1 - -5).\n'
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CssMerger.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CssMerger.Tests")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f7c36817-3ade-4d22-88b3-aca652491500")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
from corecat.constants import OBJECT_CODES, MODEL_VERSION
from ._sqlalchemy import Base, CoreCatBaseMixin
from ._sqlalchemy import Column, \
Integer, \
String, Text
class Project(CoreCatBaseMixin, Base):
"""Project Model class represent for the 'projects' table
which is used to store project's basic information."""
# Add the real table name here.
# TODO: Add the database prefix here
__tablename__ = 'project'
# Column definition
project_id = Column('id', Integer,
primary_key=True,
autoincrement=True
)
project_name = Column('name', String(100),
nullable=False
)
project_description = Column('description', Text,
nullable=True
)
# Relationship
# TODO: Building relationship
def __init__(self, project_name,
created_by_user_id,
**kwargs):
"""
Constructor of Project Model Class.
:param project_name: Name of the project.
:param created_by_user_id: Project is created under this user ID.
:param project_description: Description of the project.
"""
self.set_up_basic_information(
MODEL_VERSION[OBJECT_CODES['Project']],
created_by_user_id
)
self.project_name = project_name
self.project_description = kwargs.get('project_description', None)
|
<div id="container" class="container-fluid" ng-controller="cloudAppController">
<div class="table">
<div class="col-lg-2">
<label for="teamDD">Team:</label>
<select id="teamDD" class="form-control headerSelectWidth" ng-model="filteredTeam"
ng-change="onTeamChange()" ng-options="team.id as team.name for team in teamsOnly"></select>
</div>
<!--<div class="col-lg-2">
<label for="moduleSearch">Module:</label>
<input id="moduleSearch" class="form-control headerSelectWidth" ng-model="search.moduleName"/>
</div>-->
<div class="col-lg-2">
<label for="cloudAppSearch">CloudApp:</label>
<input id="cloudAppSearch" class="form-control headerSelectWidth" ng-model="search.appName"/>
</div>
<div class="col-lg-1">
<div class="spinner" ng-show="isLoading"></div>
</div>
</div>
<div ng-repeat = "module in cloudAddData.modules">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>
<span >{{module.moduleName}}</span>
</th>
</tr>
<tr>
<th>
<span tooltip-placement="top">CloudApp</span>
</th>
<th>
<span tooltip-placement="top">Page</span>
</th>
<th>StoryPoints</th>
<th>Stream</th>
<th>TaskStatus</th>
<th>Blockers</th>
</tr>
</thead>
<tbody>
<tr ng-repeat = "cloudApp in module.cloudApps | filter:search:strict | orderBy:['appName','pageName']:reverse">
<!--
<td class="table_cell_border" ng-if="showCloud(cloudApp.appName)">{{cloudApp.appName}}</td>
<td class="" ng-if="previousCloudSkipped"></td> rowspan="{{module.}}" -->
<td class="table_cell_border" style="vertical-align: middle;" rowspan="{{getSpan(cloudApp.appName, module.cloudAppRowspans)}}" ng-if="showCloud(cloudApp.appName)" >{{cloudApp.appName}}</td>
<td class="table_cell_border">{{cloudApp.pageName}}</td>
<td class="table_cell_border">{{cloudApp.storyPoints}}</td>
<td class="table_cell_border">{{cloudApp.stream}}</td>
<td class="table_cell_border">{{cloudApp.taskStatus}}</td>
<td class="table_cell_border">
<span ng-repeat="blocker in cloudApp.blockers" >
<a ng-if="blocker.status!='Closed'" class="btn btn-primary blocker_style"
ng-style={'background-color':stringToColorCode(blocker.key)}
href="{{blocker.uri}}" target="_blank">
{{blocker.key}} <span class="badge">{{blocker.pagesInvolved}}</span>
</a>
<a ng-if="blocker.status=='Closed'" class="btn btn-primary blocker_style blocker_status_{{blocker.status}}"
href="{{blocker.uri}}" target="_blank">
{{blocker.key}} <span class="badge">{{blocker.pagesInvolved}}</span>
</a>
</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
|
b'-79 + 113 + -1 + -17\n'
|
b'Evaluate -17 + 17 + -6 - -2.\n'
|
---
title: "Bayesian network regression with applications to microbiome data"
collection: talks
type: "Talk"
permalink: /talks/2021_juliacon
venue: "JuliaCon"
date: 2021-07-30
location: "Online"
---
Bayesian network regression with applications to microbiome data, **Samuel Ozminkowski** & Claudia Solís-Lemus,
*JuliaCon*, Online, July 28-30, 2021
[Video](https://juliacon2020-uploads.s3.us-east-2.amazonaws.com/public/Bayesian+network+regression+with+applications+to+microbiome+data%3A+movie2.mp4)
[Abstract](https://pretalx.com/juliacon2021/talk/review/KMKZLBEXJX3U8ZJQB3QHHWLLVUDXC3CG)
|
import {Component} from 'react'
export class Greeter {
constructor (message) {
this.greeting = message;
}
greetFrom (...names) {
let suffix = names.reduce((s, n) => s + ", " + n.toUpperCase());
return "Hello, " + this.greeting + " from " + suffix;
}
greetNTimes ({name, times}) {
let greeting = this.greetFrom(name);
for (let i = 0; i < times; i++) {
console.log(greeting)
}
}
}
new Greeter("foo").greetNTimes({name: "Webstorm", times: 3})
function foo (x, y, z) {
var i = 0;
var x = {0: "zero", 1: "one"};
var a = [0, 1, 2];
var foo = function () {
}
var asyncFoo = async (x, y, z) => {
}
var v = x.map(s => s.length);
if (!i > 10) {
for (var j = 0; j < 10; j++) {
switch (j) {
case 0:
value = "zero";
break;
case 1:
value = "one";
break;
}
var c = j > 5 ? "GT 5" : "LE 5";
}
} else {
var j = 0;
try {
while (j < 10) {
if (i == j || j > 5) {
a[j] = i + j * 12;
}
i = (j << 2) & 4;
j++;
}
do {
j--;
} while (j > 0)
} catch (e) {
alert("Failure: " + e.message);
} finally {
reset(a, i);
}
}
}
|
b'Calculate (1 - -14) + 1452 + -1438.\n'
|
b'Calculate 5 + -26 + 16 + 2 + 1.\n'
|
/**
* Angular 2 decorators and services
*/
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { environment } from 'environments/environment';
import { AppState } from './app.service';
/**
* App Component
* Top Level Component
*/
@Component({
selector: 'my-app',
encapsulation: ViewEncapsulation.None,
template: `
<nav>
<a [routerLink]=" ['./'] "
routerLinkActive="active" [routerLinkActiveOptions]= "{exact: true}">
Index
</a>
</nav>
<main>
<router-outlet></router-outlet>
</main>
<pre class="app-state">this.appState.state = {{ appState.state | json }}</pre>
<footer>
<span>Angular Starter by <a [href]="twitter">@gdi2290</a></span>
<div>
<a [href]="url">
<img [src]="tipe" width="25%">
</a>
</div>
</footer>
`
})
export class AppComponent implements OnInit {
public name = 'Angular Starter';
public tipe = 'assets/img/tipe.png';
public twitter = 'https://twitter.com/gdi2290';
public url = 'https://tipe.io';
public showDevModule: boolean = environment.showDevModule;
constructor(
public appState: AppState
) {}
public ngOnInit() {
console.log('Initial App State', this.appState.state);
}
}
/**
* Please review the https://github.com/AngularClass/angular2-examples/ repo for
* more angular app examples that you may copy/paste
* (The examples may not be updated as quickly. Please open an issue on github for us to update it)
* For help or questions please contact us at @AngularClass on twitter
* or our chat on Slack at https://AngularClass.com/slack-join
*/
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable =['name'];
}
|
b'52 + -43 + (1 - 0) + 0\n'
|
package multiwallet
import (
"errors"
"strings"
"time"
eth "github.com/OpenBazaar/go-ethwallet/wallet"
"github.com/OpenBazaar/multiwallet/bitcoin"
"github.com/OpenBazaar/multiwallet/bitcoincash"
"github.com/OpenBazaar/multiwallet/client/blockbook"
"github.com/OpenBazaar/multiwallet/config"
"github.com/OpenBazaar/multiwallet/litecoin"
"github.com/OpenBazaar/multiwallet/service"
"github.com/OpenBazaar/multiwallet/zcash"
"github.com/OpenBazaar/wallet-interface"
"github.com/btcsuite/btcd/chaincfg"
"github.com/op/go-logging"
"github.com/tyler-smith/go-bip39"
)
var log = logging.MustGetLogger("multiwallet")
var UnsuppertedCoinError = errors.New("multiwallet does not contain an implementation for the given coin")
type MultiWallet map[wallet.CoinType]wallet.Wallet
func NewMultiWallet(cfg *config.Config) (MultiWallet, error) {
log.SetBackend(logging.AddModuleLevel(cfg.Logger))
service.Log = log
blockbook.Log = log
if cfg.Mnemonic == "" {
ent, err := bip39.NewEntropy(128)
if err != nil {
return nil, err
}
mnemonic, err := bip39.NewMnemonic(ent)
if err != nil {
return nil, err
}
cfg.Mnemonic = mnemonic
cfg.CreationDate = time.Now()
}
multiwallet := make(MultiWallet)
var err error
for _, coin := range cfg.Coins {
var w wallet.Wallet
switch coin.CoinType {
case wallet.Bitcoin:
w, err = bitcoin.NewBitcoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates)
if err != nil {
return nil, err
}
if cfg.Params.Name == chaincfg.MainNetParams.Name {
multiwallet[wallet.Bitcoin] = w
} else {
multiwallet[wallet.TestnetBitcoin] = w
}
case wallet.BitcoinCash:
w, err = bitcoincash.NewBitcoinCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates)
if err != nil {
return nil, err
}
if cfg.Params.Name == chaincfg.MainNetParams.Name {
multiwallet[wallet.BitcoinCash] = w
} else {
multiwallet[wallet.TestnetBitcoinCash] = w
}
case wallet.Zcash:
w, err = zcash.NewZCashWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates)
if err != nil {
return nil, err
}
if cfg.Params.Name == chaincfg.MainNetParams.Name {
multiwallet[wallet.Zcash] = w
} else {
multiwallet[wallet.TestnetZcash] = w
}
case wallet.Litecoin:
w, err = litecoin.NewLitecoinWallet(coin, cfg.Mnemonic, cfg.Params, cfg.Proxy, cfg.Cache, cfg.DisableExchangeRates)
if err != nil {
return nil, err
}
if cfg.Params.Name == chaincfg.MainNetParams.Name {
multiwallet[wallet.Litecoin] = w
} else {
multiwallet[wallet.TestnetLitecoin] = w
}
case wallet.Ethereum:
w, err = eth.NewEthereumWallet(coin, cfg.Params, cfg.Mnemonic, cfg.Proxy)
if err != nil {
return nil, err
}
if cfg.Params.Name == chaincfg.MainNetParams.Name {
multiwallet[wallet.Ethereum] = w
} else {
multiwallet[wallet.TestnetEthereum] = w
}
}
}
return multiwallet, nil
}
func (w *MultiWallet) Start() {
for _, wallet := range *w {
wallet.Start()
}
}
func (w *MultiWallet) Close() {
for _, wallet := range *w {
wallet.Close()
}
}
func (w *MultiWallet) WalletForCurrencyCode(currencyCode string) (wallet.Wallet, error) {
for _, wl := range *w {
if strings.EqualFold(wl.CurrencyCode(), currencyCode) || strings.EqualFold(wl.CurrencyCode(), "T"+currencyCode) {
return wl, nil
}
}
return nil, UnsuppertedCoinError
}
|
b'What is the value of 5 + -20 + 2 + 29?\n'
|
b'What is -2 - (2 + -2 + (90 - 93))?\n'
|
#pragma once
#include <rikitiki/http/content_types.h>
#include <vector>
#include <map>
#include <array>
#include <mxcomp/reflection.h>
#ifdef _MSC_VER
#define constexpr
#endif
namespace rikitiki {
class ConnContext;
struct Response;
template <typename T>
struct ContentHandler_ {
static constexpr std::array<ContentType::t, 1> ContentTypes() { return{ { ContentType::DEFAULT } }; };
};
struct OutProvider {
template<typename S, typename T>
static auto Make() -> void(*)(ConnContext&, S&) {
return [](ConnContext& ctx, S& s) {
T t;
t << s;
ctx << t;
};
}
};
struct InProvider {
template<typename S, typename T>
static auto Make() -> void(*)(ConnContext&, S&) {
return [](ConnContext& ctx, S& s) {
T t;
ctx >> t;
t >> s;
};
}
};
template <typename S, typename FProvider, typename... T>
struct TypeConversions {
typedef TypeConversions<S, FProvider, T...> thisType;
typedef TypeConversions<std::vector<S>, FProvider, T...> VectorType;
template <typename Th, typename...Tt>
struct HandlerAdders {
static void Add(thisType* _this){
HandlerAdders<Th>::Add(_this);
HandlerAdders<Tt...>::Add(_this);
}
};
template <typename Th>
struct HandlerAdders<Th> {
static auto Add(thisType* _this) -> void {
for (auto contentType : ContentHandler_<Th>::ContentTypes()){
assert(contentType > ContentType::DEFAULT &&
contentType < ContentType::MAX &&
"Invalid content type value in specialized handler");
_this->handlers[contentType] = FProvider::template Make<S, Th>();
}
}
};
typedef void(*Setter)(ConnContext&, S& s);
std::vector<Setter> handlers;
TypeConversions() {
handlers.resize(ContentType::MAX);
HandlerAdders<T...>::Add(this);
}
static thisType& Instance() {
static thisType Instance;
return Instance;
}
};
template<typename T, typename enable = void >
struct valid_conversions { };
}
#ifdef USE_JSONCPP
#include <rikitiki/jsoncpp/jsoncpp>
namespace rikitiki {
using namespace mxcomp;
template<typename T>
struct valid_conversions<T, typename std::enable_if< std::is_function <decltype(MetaClass_<T>::fields)>::value >::type > {
typedef TypeConversions<T, InProvider, Json::Value> In;
typedef TypeConversions<T, OutProvider, Json::Value> Out;
};
template <typename T>
struct valid_conversions<std::vector<T>, typename std::enable_if< std::is_class<valid_conversions<T> >::value >::type > {
typedef typename valid_conversions<T>::In::VectorType In;
typedef typename valid_conversions<T>::Out::VectorType Out;
};
}
#endif
|
b'What is (1 - (13 + (8 - 9))) + -2?\n'
|
b'10 + (-4 - (-3 - -9)) + 2\n'
|
b'(-30 - -80) + -21 + -1 + -11\n'
|
b'What is the value of 448 - 455 - (-3 - -4 - 43)?\n'
|
import { strictEqual } from 'assert';
import { Config, HttpResponse, HttpResponseOK } from '../core';
import {
SESSION_DEFAULT_COOKIE_HTTP_ONLY,
SESSION_DEFAULT_COOKIE_NAME,
SESSION_DEFAULT_COOKIE_PATH,
SESSION_DEFAULT_CSRF_COOKIE_NAME,
SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED,
SESSION_USER_COOKIE_NAME,
} from './constants';
import { removeSessionCookie } from './remove-session-cookie';
describe('removeSessionCookie', () => {
let response: HttpResponse;
beforeEach(() => response = new HttpResponseOK());
describe('should set a session cookie in the response', () => {
context('given no configuration option is provided', () => {
beforeEach(() => removeSessionCookie(response));
it('with the proper default name and value.', () => {
const { value } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.domain, undefined);
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.httpOnly, SESSION_DEFAULT_COOKIE_HTTP_ONLY);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH);
});
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.sameSite, undefined);
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.secure, undefined);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.maxAge, 0);
});
});
context('given configuration options are provided', () => {
const cookieName = SESSION_DEFAULT_COOKIE_NAME + '2';
beforeEach(() => {
Config.set('settings.session.cookie.name', cookieName);
Config.set('settings.session.cookie.domain', 'example.com');
Config.set('settings.session.cookie.httpOnly', false);
Config.set('settings.session.cookie.path', '/foo');
Config.set('settings.session.cookie.sameSite', 'strict');
Config.set('settings.session.cookie.secure', true);
removeSessionCookie(response);
});
afterEach(() => {
Config.remove('settings.session.cookie.name');
Config.remove('settings.session.cookie.domain');
Config.remove('settings.session.cookie.httpOnly');
Config.remove('settings.session.cookie.path');
Config.remove('settings.session.cookie.sameSite');
Config.remove('settings.session.cookie.secure');
});
it('with the proper default name and value.', () => {
const { value } = response.getCookie(cookieName);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.domain, 'example.com');
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.httpOnly, false);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.path, '/foo');
});
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.sameSite, 'strict');
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.secure, true);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(cookieName);
strictEqual(options.maxAge, 0);
});
});
});
context('given the CSRF protection is enabled in the config', () => {
beforeEach(() => Config.set('settings.session.csrf.enabled', true));
afterEach(() => Config.remove('settings.session.csrf.enabled'));
describe('should set a session cookie in the response', () => {
context('given no configuration option is provided', () => {
beforeEach(() => removeSessionCookie(response));
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.sameSite, SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED);
});
});
context('given configuration options are provided', () => {
beforeEach(() => {
Config.set('settings.session.cookie.sameSite', 'strict');
removeSessionCookie(response);
});
afterEach(() => Config.remove('settings.session.cookie.sameSite'));
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_COOKIE_NAME);
strictEqual(options.sameSite, 'strict');
});
});
});
describe('should set a CSRF cookie in the response', () => {
context('given no configuration option is provided', () => {
beforeEach(() => removeSessionCookie(response));
it('with the proper default name and value.', () => {
const { value } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.domain, undefined);
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.httpOnly, false);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH);
});
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.sameSite, SESSION_DEFAULT_SAME_SITE_ON_CSRF_ENABLED);
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.secure, undefined);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(options.maxAge, 0);
});
});
context('given configuration options are provided', () => {
const csrfCookieName = SESSION_DEFAULT_CSRF_COOKIE_NAME + '2';
beforeEach(() => {
Config.set('settings.session.csrf.cookie.name', csrfCookieName);
Config.set('settings.session.cookie.domain', 'example.com');
Config.set('settings.session.cookie.httpOnly', true);
Config.set('settings.session.cookie.path', '/foo');
Config.set('settings.session.cookie.sameSite', 'strict');
Config.set('settings.session.cookie.secure', 'true');
removeSessionCookie(response);
});
afterEach(() => {
Config.remove('settings.session.csrf.cookie.name');
Config.remove('settings.session.cookie.domain');
Config.remove('settings.session.cookie.httpOnly');
Config.remove('settings.session.cookie.path');
Config.remove('settings.session.cookie.sameSite');
Config.remove('settings.session.cookie.secure');
});
it('with the proper default name and value.', () => {
const { value } = response.getCookie(csrfCookieName);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.domain, 'example.com');
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.httpOnly, false);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.path, '/foo');
});
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.sameSite, 'strict');
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.secure, true);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(csrfCookieName);
strictEqual(options.maxAge, 0);
});
});
});
});
context('given the CSRF protection is disabled in the config', () => {
beforeEach(() => removeSessionCookie(response));
it('should not set a CSRF cookie in the response.', () => {
const { value } = response.getCookie(SESSION_DEFAULT_CSRF_COOKIE_NAME);
strictEqual(value, undefined);
});
});
context('given the "user" argument is true', () => {
describe('should set a "user" cookie in the response', () => {
context('given no configuration option is provided', () => {
beforeEach(() => removeSessionCookie(response, true));
it('with the proper default name and value.', () => {
const { value } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.domain, undefined);
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.httpOnly, false);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.path, SESSION_DEFAULT_COOKIE_PATH);
});
// Adding the sameSite directive is useless. We keep it for consistency.
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.sameSite, undefined);
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.secure, undefined);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.maxAge, 0);
});
});
context('given configuration options are provided', () => {
beforeEach(() => {
Config.set('settings.session.cookie.domain', 'example.com');
Config.set('settings.session.cookie.httpOnly', true);
Config.set('settings.session.cookie.path', '/foo');
Config.set('settings.session.cookie.sameSite', 'strict');
Config.set('settings.session.cookie.secure', 'true');
removeSessionCookie(response, true);
});
afterEach(() => {
Config.remove('settings.session.cookie.domain');
Config.remove('settings.session.cookie.httpOnly');
Config.remove('settings.session.cookie.path');
Config.remove('settings.session.cookie.sameSite');
Config.remove('settings.session.cookie.secure');
});
it('with the proper default name and value.', () => {
const { value } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(value, '');
});
it('with the proper default "domain" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.domain, 'example.com');
});
it('with the proper default "httpOnly" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.httpOnly, false);
});
it('with the proper default "path" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.path, '/foo');
});
// Adding the sameSite directive is useless. We keep it for consistency.
it('with the proper default "sameSite" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.sameSite, 'strict');
});
it('with the proper default "secure" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.secure, true);
});
it('with the proper "maxAge" directive.', () => {
const { options } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(options.maxAge, 0);
});
});
});
});
context('given the "user" argument is false or undefined', () => {
beforeEach(() => removeSessionCookie(response));
it('should not set a "user" cookie in the response.', () => {
const { value } = response.getCookie(SESSION_USER_COOKIE_NAME);
strictEqual(value, undefined);
});
});
});
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using IdentityServer3.Core.Events;
using IdentityServer3.ElasticSearchEventService.Extensions;
using IdentityServer3.ElasticSearchEventService.Mapping;
using IdentityServer3.ElasticSearchEventService.Mapping.Configuration;
using Serilog.Events;
using Unittests.Extensions;
using Unittests.Proofs;
using Unittests.TestData;
using Xunit;
namespace Unittests
{
public class DefaultLogEventMapperTests
{
[Fact]
public void SpecifiedProperties_AreMapped()
{
var mapper = CreateMapper(b => b
.DetailMaps(c => c
.For<TestDetails>(m => m
.Map(d => d.String)
)
));
var details = new TestDetails
{
String = "Polse"
};
var logEvent = mapper.Map(CreateEvent(details));
logEvent.Properties.DoesContain(LogEventValueWith("Details.String", Quote("Polse")));
}
[Fact]
public void AlwaysAddedValues_AreAlwaysAdded()
{
var mapper = CreateMapper(b => b.AlwaysAdd("some", "value"));
var logEvent = mapper.Map(CreateEvent(new object()));
logEvent.Properties.DoesContain(LogEventValueWith("some", Quote("value")));
}
[Fact]
public void MapToSpecifiedName_MapsToSpecifiedName()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.For<TestDetails>(o => o
.Map("specificName", d => d.String)
)
));
var logEvent = mapper.Map(CreateEvent(new TestDetails {String = Some.String}));
logEvent.Properties.DoesContain(LogEventValueWith("Details.specificName", Quote(Some.String)));
}
[Fact]
public void PropertiesThatThrowsException_AreMappedAsException()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.For<TestDetails>(o => o
.Map(d => d.ThrowsException)
)
));
var logEvent = mapper.Map(CreateEvent(new TestDetails()));
logEvent.Properties.DoesContain(LogEventValueWith("Details.ThrowsException", s => s.StartsWith("\"threw")));
}
[Fact]
public void DefaultMapAllMembers_MapsAllPropertiesAndFieldsForDetails()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.DefaultMapAllMembers()
));
var logEvent = mapper.Map(CreateEvent(new TestDetails()));
var members = typeof (TestDetails).GetPublicPropertiesAndFields().Select(m => string.Format("Details.{0}", m.Name));
logEvent.Properties.DoesContainKeys(members);
}
[Fact]
public void ComplexMembers_AreMappedToJson()
{
var mapper = CreateMapper(b => b
.DetailMaps(m => m
.DefaultMapAllMembers()
));
var details = new TestDetails();
var logEvent = mapper.Map(CreateEvent(details));
var logProperty = logEvent.GetProperty<ScalarValue>("Details.Inner");
logProperty.Value.IsEqualTo(details.Inner.ToJsonSuppressErrors());
}
private static string Quote(string value)
{
return string.Format("\"{0}\"", value);
}
private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, Func<string,bool> satisfies)
{
return p => p.Key == key && satisfies(p.Value.ToString());
}
private static Expression<Func<KeyValuePair<string, LogEventPropertyValue>, bool>> LogEventValueWith(string key, string value)
{
return p => p.Key == key && p.Value.ToString() == value;
}
private static Event<T> CreateEvent<T>(T details)
{
return new Event<T>("category", "name", EventTypes.Information, 42, details);
}
private static DefaultLogEventMapper CreateMapper(Action<MappingConfigurationBuilder> setup)
{
var builder = new MappingConfigurationBuilder();
setup(builder);
return new DefaultLogEventMapper(builder.GetConfiguration());
}
}
}
|
b'Evaluate 1 - -3 - (14 + -16 + 2).\n'
|
b'What is -1 - (-11 + 0) - (54 - 48 - 5)?\n'
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>readlines (Buffering)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/openssl/buffering.rb, line 124</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">readlines</span>(<span class="ruby-identifier">eol</span>=<span class="ruby-identifier">$/</span>)
<span class="ruby-identifier">ary</span> = []
<span class="ruby-keyword kw">while</span> <span class="ruby-identifier">line</span> = <span class="ruby-keyword kw">self</span>.<span class="ruby-identifier">gets</span>(<span class="ruby-identifier">eol</span>)
<span class="ruby-identifier">ary</span> <span class="ruby-operator"><<</span> <span class="ruby-identifier">line</span>
<span class="ruby-keyword kw">end</span>
<span class="ruby-identifier">ary</span>
<span class="ruby-keyword kw">end</span></pre>
</body>
</html>
|
<?php
interface Container {
/**
* Checks if a $x exists.
*
* @param unknown $x
*
* @return boolean
*/
function contains($x);
}
|
b'Evaluate (28 - 45) + 10 - (-1 - 14).\n'
|
{% extends "content_template.html" %}
{% from "components/page-header.html" import page_header %}
{% from "components/copy-to-clipboard.html" import copy_to_clipboard %}
{% block per_page_title %}
Billing details
{% endblock %}
{% block content_column_content %}
{{ page_header('Billing details') }}
<p class="govuk-body">
You can use the information on this page to add the Cabinet Office as a supplier. Your organisation may need to do this before you can raise a purchase order (PO).
</p>
<p class="govuk-body">
<a class="govuk-link govuk-link--no-visited-state" href="{{ url_for('main.support') }}">Contact us</a> if you need any other details.
</p>
<h2 class="heading-medium govuk-!-margin-top-7" id="supplier-details">
Supplier details
</h2>
<p class="govuk-body">
Cabinet Office
</p>
<p class="govuk-body">
The White Chapel Building <br>
10 Whitechapel High Street <br>
London <br>
E1 8QS
</p>
<h3 class="heading-small" id="email-addresses">
Email addresses
</h3>
<ul class="govuk-list govuk-list--bullet">
{% for email in billing_details['notify_billing_email_addresses'] %}
<li>
{{ email }}
</li>
{% endfor %}
</ul>
<h3 class="heading-small" id="vat-number">
<abbr title="Value Added Tax">VAT</abbr> number
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
'GB 88 88 010 80',
thing='<abbr title="Value Added Tax">VAT</abbr> number',
) }}
</div>
<h2 class="heading-medium govuk-!-margin-top-7" id="bank-details">
Bank details
</h2>
<p class="govuk-body">
National Westminster Bank PLC (part of RBS group) <br>
Government Banking Services Branch <br>
2nd Floor <br>
280 Bishopsgate <br>
London <br>
EC2M 4RB
</p>
<h3 class="heading-small" id="account-name">
Account name
</h3>
<p class="govuk-body">
Cabinet Office
</p>
<h3 class="heading-small" id="account-number">
Account number
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['account_number'],
thing='account number',
) }}
</div>
<h3 class="heading-small" id="sort-code">
Sort code
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['sort_code'],
thing='sort code',
) }}
</div>
<h3 class="heading-small" id="iban">
<abbr title="International Bank Account Number">IBAN</abbr>
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['IBAN'],
thing='IBAN',
) }}
</div>
<h3 class="heading-small" id="swift-code">
Swift code
</h3>
<div class="govuk-!-margin-bottom-4">
{{ copy_to_clipboard(
billing_details['swift'],
thing='Swift code',
) }}
</div>
<h2 class="heading-medium govuk-!-margin-top-7" id="invoice-address">
Invoice address
</h2>
<p class="govuk-body">
SSCL – Accounts Receivable <br>
PO Box 221 <br>
Thornton-Cleveleys <br>
Blackpool <br>
Lancashire <br>
FY1 9JN
</p>
{% endblock %}
|
package me.breidenbach.asyncmailer
/**
* Copyright © Kevin E. Breidenbach, 5/26/15.
*/
case class MailerException(message: String, cause: Throwable = null) extends Error(message, cause)
|
b'-10 - (7 - -2 - (54 + -69))\n'
|
b'What is the value of -1 + -2 - (-4 + 4 + 4)?\n'
|
b'19 + (11 + 1 - 12) + -5\n'
|
/*
* THIS FILE IS AUTO GENERATED FROM 'lib/lex/lexer.kep'
* DO NOT EDIT
*/
define(["require", "exports", "bennu/parse", "bennu/lang", "nu-stream/stream", "ecma-ast/token", "ecma-ast/position",
"./boolean_lexer", "./comment_lexer", "./identifier_lexer", "./line_terminator_lexer", "./null_lexer",
"./number_lexer", "./punctuator_lexer", "./reserved_word_lexer", "./string_lexer", "./whitespace_lexer",
"./regular_expression_lexer"
], (function(require, exports, parse, __o, __o0, lexToken, __o1, __o2, comment_lexer, __o3, line_terminator_lexer,
__o4, __o5, __o6, __o7, __o8, whitespace_lexer, __o9) {
"use strict";
var lexer, lexStream, lex, always = parse["always"],
attempt = parse["attempt"],
binds = parse["binds"],
choice = parse["choice"],
eof = parse["eof"],
getPosition = parse["getPosition"],
modifyState = parse["modifyState"],
getState = parse["getState"],
enumeration = parse["enumeration"],
next = parse["next"],
many = parse["many"],
runState = parse["runState"],
never = parse["never"],
ParserState = parse["ParserState"],
then = __o["then"],
streamFrom = __o0["from"],
SourceLocation = __o1["SourceLocation"],
SourcePosition = __o1["SourcePosition"],
booleanLiteral = __o2["booleanLiteral"],
identifier = __o3["identifier"],
nullLiteral = __o4["nullLiteral"],
numericLiteral = __o5["numericLiteral"],
punctuator = __o6["punctuator"],
reservedWord = __o7["reservedWord"],
stringLiteral = __o8["stringLiteral"],
regularExpressionLiteral = __o9["regularExpressionLiteral"],
type, type0, type1, type2, type3, p, type4, type5, type6, type7, p0, type8, p1, type9, p2, consume = (
function(tok, self) {
switch (tok.type) {
case "Comment":
case "Whitespace":
case "LineTerminator":
return self;
default:
return tok;
}
}),
isRegExpCtx = (function(prev) {
if ((!prev)) return true;
switch (prev.type) {
case "Keyword":
case "Punctuator":
return true;
}
return false;
}),
enterRegExpCtx = getState.chain((function(prev) {
return (isRegExpCtx(prev) ? always() : never());
})),
literal = choice(((type = lexToken.StringToken.create), stringLiteral.map((function(x) {
return [type, x];
}))), ((type0 = lexToken.BooleanToken.create), booleanLiteral.map((function(x) {
return [type0, x];
}))), ((type1 = lexToken.NullToken.create), nullLiteral.map((function(x) {
return [type1, x];
}))), ((type2 = lexToken.NumberToken.create), numericLiteral.map((function(x) {
return [type2, x];
}))), ((type3 = lexToken.RegularExpressionToken.create), (p = next(enterRegExpCtx,
regularExpressionLiteral)), p.map((function(x) {
return [type3, x];
})))),
token = choice(attempt(((type4 = lexToken.IdentifierToken), identifier.map((function(x) {
return [type4, x];
})))), literal, ((type5 = lexToken.KeywordToken), reservedWord.map((function(x) {
return [type5, x];
}))), ((type6 = lexToken.PunctuatorToken), punctuator.map((function(x) {
return [type6, x];
})))),
inputElement = choice(((type7 = lexToken.CommentToken), (p0 = comment_lexer.comment), p0.map((function(
x) {
return [type7, x];
}))), ((type8 = lexToken.WhitespaceToken), (p1 = whitespace_lexer.whitespace), p1.map((function(x) {
return [type8, x];
}))), ((type9 = lexToken.LineTerminatorToken), (p2 = line_terminator_lexer.lineTerminator), p2.map(
(function(x) {
return [type9, x];
}))), token);
(lexer = then(many(binds(enumeration(getPosition, inputElement, getPosition), (function(start, __o10, end) {
var type10 = __o10[0],
value = __o10[1];
return always(new(type10)(new(SourceLocation)(start, end, (start.file || end.file)),
value));
}))
.chain((function(tok) {
return next(modifyState(consume.bind(null, tok)), always(tok));
}))), eof));
(lexStream = (function(s, file) {
return runState(lexer, new(ParserState)(s, new(SourcePosition)(1, 0, file), null));
}));
var y = lexStream;
(lex = (function(z) {
return y(streamFrom(z));
}));
(exports["lexer"] = lexer);
(exports["lexStream"] = lexStream);
(exports["lex"] = lex);
}));
|
//
// Constants.h
//
//
#define LANGUAGES_API @"https://api.unfoldingword.org/obs/txt/1/obs-catalog.json"
#define SELECTION_BLUE_COLOR [UIColor colorWithRed:76.0/255.0 green:185.0/255.0 blue:224.0/255.0 alpha:1.0]
#define TEXT_COLOR_NORMAL [UIColor colorWithRed:32.0/255.0 green:27.0/255.0 blue:22.0/255.0 alpha:1.0]
#define BACKGROUND_GRAY [UIColor colorWithRed:42.0/255.0 green:34.0/255.0 blue:26.0/255.0 alpha:1.0]
#define BACKGROUND_GREEN [UIColor colorWithRed:170.0/255.0 green:208.0/255.0 blue:0.0/255.0 alpha:1.0]
#define TABBAR_COLOR_TRANSPARENT [UIColor colorWithRed:42.0/255.0 green:34.0/255.0 blue:26.0/255.0 alpha:0.7]
#define FONT_LIGHT [UIFont fontWithName:@"HelveticaNeue-Light" size:17]
#define FONT_NORMAL [UIFont fontWithName:@"HelveticaNeue" size:17]
#define FONT_MEDIUM [UIFont fontWithName:@"HelveticaNeue-Medium" size:17]
#define LEVEL_1_DESC NSLocalizedString(@"Level 1: internal — Translator (or team) affirms that translation is in line with Statement of Faith and Translation Guidelines.", nil)
#define LEVEL_2_DESC NSLocalizedString(@"Level 2: external — Translation is independently checked and confirmed by at least two others not on the translation team.", nil)
#define LEVEL_3_DESC NSLocalizedString(@"Level 3: authenticated — Translation is checked and confirmed by leadership of at least one Church network with native speakers of the language.", nil)
#define LEVEL_1_IMAGE @"level1Cell"
#define LEVEL_2_IMAGE @"level2Cell"
#define LEVEL_3_IMAGE @"level3Cell"
#define LEVEL_1_REVERSE @"level1"
#define LEVEL_2_REVERSE @"level2"
#define LEVEL_3_REVERSE @"level3"
#define IMAGE_VERIFY_GOOD @"verifyGood"
#define IMAGE_VERIFY_FAIL @"verifyFail.png"
#define IMAGE_VERIFY_EXPIRE @"verifyExpired.png"
// Allows us to track the verse for each part of an attributed string
static NSString *const USFM_VERSE_NUMBER = @"USFMVerseNumber";
static NSString *const SignatureFileAppend = @".sig"; // Duplicated in UWConstants.swift
static NSString *const FileExtensionUFW = @"ufw"; /// Duplicated in UWConstants.swift
// Duplicated in UWConstants.swift
static NSString *const BluetoothSend = @"BluetoothSend";
static NSString *const BluetoothReceive = @"BluetoothReceive";
static NSString *const MultiConnectSend = @"MultiConnectSend";
static NSString *const MultiConnectReceive = @"MultiConnectReceive";
static NSString *const iTunesSend = @"iTunesSend";
static NSString *const iTunesReceive = @"iTunesReceive";
static NSString *const IMAGE_DIGLOT = @"diglot";
|
b'Evaluate 2 + -12 + (21 - 7) - (7 - -18).\n'
|
package com.eaw1805.data.model.map;
import com.eaw1805.data.constants.RegionConstants;
import com.eaw1805.data.model.Game;
import java.io.Serializable;
/**
* Represents a region of the world.
*/
public class Region implements Serializable {
/**
* Required by Serializable interface.
*/
static final long serialVersionUID = 42L; //NOPMD
/**
* Region's identification number.
*/
private int id; // NOPMD
/**
* Region's code.
*/
private char code;
/**
* The name of the region.
*/
private String name;
/**
* The game this region belongs to.
*/
private Game game;
/**
* Default constructor.
*/
public Region() {
// Empty constructor
}
/**
* Get the Identification number of the region.
*
* @return the identification number of the region.
*/
public int getId() {
return id;
}
/**
* Set the Identification number of the region.
*
* @param identity the identification number of the region.
*/
public void setId(final int identity) {
this.id = identity;
}
/**
* Get the name of the region.
*
* @return the name of the region.
*/
public String getName() {
return name;
}
/**
* Set the thisName of the region.
*
* @param thisName the name of the region.
*/
public void setName(final String thisName) {
this.name = thisName;
}
/**
* Get the Single-char code of the region.
*
* @return the Single-char code of the region.
*/
public char getCode() {
return code;
}
/**
* Set the single-char code of the region.
*
* @param thisCode the single-char code of the region.
*/
public void setCode(final char thisCode) {
this.code = thisCode;
}
/**
* Get the game this region belongs to.
*
* @return The game of the region.
*/
public Game getGame() {
return game;
}
/**
* Set the game this region belongs to.
*
* @param value The game.
*/
public void setGame(final Game value) {
this.game = value;
}
/**
* Indicates whether some other object is "equal to" this one.
* The <code>equals</code> method implements an equivalence relation
* on non-null object references:
* <ul>
* <li>It is <i>reflexive</i>: for any non-null reference value
* <code>x</code>, <code>x.equals(x)</code> should return
* <code>true</code>.
* <li>It is <i>symmetric</i>: for any non-null reference values
* <code>x</code> and <code>y</code>, <code>x.equals(y)</code>
* should return <code>true</code> if and only if
* <code>y.equals(x)</code> returns <code>true</code>.
* <li>It is <i>transitive</i>: for any non-null reference values
* <code>x</code>, <code>y</code>, and <code>z</code>, if
* <code>x.equals(y)</code> returns <code>true</code> and
* <code>y.equals(z)</code> returns <code>true</code>, then
* <code>x.equals(z)</code> should return <code>true</code>.
* <li>It is <i>consistent</i>: for any non-null reference values
* <code>x</code> and <code>y</code>, multiple invocations of
* <tt>x.equals(y)</tt> consistently return <code>true</code>
* or consistently return <code>false</code>, provided no
* information used in <code>equals</code> comparisons on the
* objects is modified.
* <li>For any non-null reference value <code>x</code>,
* <code>x.equals(null)</code> should return <code>false</code>.
* </ul>
* The <tt>equals</tt> method for class <code>Object</code> implements
* the most discriminating possible equivalence relation on objects;
* that is, for any non-null reference values <code>x</code> and
* <code>y</code>, this method returns <code>true</code> if and only
* if <code>x</code> and <code>y</code> refer to the same object
* (<code>x == y</code> has the value <code>true</code>).
* Note that it is generally necessary to override the <tt>hashCode</tt>
* method whenever this method is overridden, so as to maintain the
* general contract for the <tt>hashCode</tt> method, which states
* that equal objects must have equal hash codes.
*
* @param obj the reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj
* argument; <code>false</code> otherwise.
* @see #hashCode()
* @see java.util.Hashtable
*/
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof Region)) {
return false;
}
final Region region = (Region) obj;
if (code != region.code) {
return false;
}
if (id != region.id) {
return false;
}
if (name != null ? !name.equals(region.name) : region.name != null) {
return false;
}
return true;
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.Hashtable</code>.
* The general contract of <code>hashCode</code> is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the <tt>hashCode</tt> method
* must consistently return the same integer, provided no information
* used in <tt>equals</tt> comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the <tt>equals(Object)</tt>
* method, then calling the <code>hashCode</code> method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the <tt>hashCode</tt> method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hashtables.
* </ul>
* As much as is reasonably practical, the hashCode method defined by
* class <tt>Object</tt> does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java<font size="-2"><sup>TM</sup></font> programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.util.Hashtable
*/
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
final StringBuilder sbld = new StringBuilder();
switch (id) {
case RegionConstants.EUROPE:
sbld.append("E");
break;
case RegionConstants.CARIBBEAN:
sbld.append("C");
break;
case RegionConstants.INDIES:
sbld.append("I");
break;
case RegionConstants.AFRICA:
sbld.append("A");
break;
default:
break;
}
return sbld.toString();
}
}
|
package remove_duplicates_from_sorted_list;
import common.ListNode;
public class RemoveDuplicatesfromSortedList {
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head != null) {
ListNode pre = head;
ListNode p = pre.next;
while (p != null) {
if (p.val == pre.val) {
pre.next = p.next;
} else {
pre = p;
}
p = p.next;
}
}
return head;
}
}
public static class UnitTest {
}
}
|
b'What is -4 + 3 - 0 - (-17 + 16) - -15?\n'
|
var Handler, MiniEventEmitter;
Handler = require("./handler");
MiniEventEmitter = (function() {
function MiniEventEmitter(obj) {
var handler;
handler = new Handler(this, obj);
this.on = handler.on;
this.off = handler.off;
this.emit = handler.emit;
this.emitIf = handler.emitIf;
this.trigger = handler.emit;
this.triggerIf = handler.emitIf;
}
MiniEventEmitter.prototype.listen = function(type, event, args) {};
return MiniEventEmitter;
})();
module.exports = MiniEventEmitter;
|
<!DOCTYPE html>
<html lang="en" ng-app="App">
<head>
<meta charset="UTF-8">
<title>form</title>
<link rel="stylesheet" href="../../js/lib/bootstrap/dist/css/bootstrap.min.css">
<style>
.container {
margin-top: 30px;
}
</style>
</head>
<body ng-controller="MyCtrl">
<div class="container">
<div class="row">
<div class="col-md-12">
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-2">honors</div>
<div class="col-sm-8">
<!-- 从默认数据 model.setting.honors 里面读值 -->
<div ng-repeat="honor in model.setting.honors"
class="checkbox">
<label>
<!-- 被选中的复选框的值(boolean)会直接赋给 model.postData.honors -->
<input ng-model="model.postData.honors[$index].value"
ng-checked="model.postData.honors[$index].value"
ng-value="honor.value"
type="checkbox">{{ honor.name }}
</label>
</div>
<p class="small">{{ model.postData.honors }}</p>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="../../js/lib/jquery/dist/jquery.min.js"></script>
<script src="../../js/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="../../js/lib/angular-v1.4.8/angular.min.js"></script>
<script>
var app = angular.module('App', []);
app
.controller('MyCtrl', function($scope){
var vm = $scope;
vm.model = {
setting: {
honors: [
{
name: 'AllStar',
value: 0
},{
name: 'Champion',
value: 1
},{
name: 'FMVP',
value: 2
}
]
},
postData: {
// honors: null,
honors: [
{value: false},
{value: true},
{value: true}
]
}
};
});
</script>
</body>
</html>
|
//-----------------------------------------------------------------------
// <copyright file="IDemPlateFileGenerator.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation 2011. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Research.Wwt.Sdk.Core
{
/// <summary>
/// Interface for DEM plate file generator.
/// </summary>
public interface IDemPlateFileGenerator
{
/// <summary>
/// Gets the number of processed tiles for the level in context.
/// </summary>
long TilesProcessed { get; }
/// <summary>
/// This function is used to create the plate file from already generated DEM pyramid.
/// </summary>
/// <param name="serializer">
/// DEM tile serializer to retrieve the tile.
/// </param>
void CreateFromDemTile(IDemTileSerializer serializer);
}
}
|
b'What is the value of ((-3 - -11) + -4 - (-2 + 2)) + -1?\n'
|
package minecraft
import (
"testing"
"vimagination.zapto.org/minecraft/nbt"
)
func TestNew(t *testing.T) {
biomes := make(nbt.ByteArray, 256)
biome := int8(-1)
blocks := make(nbt.ByteArray, 4096)
add := make(nbt.ByteArray, 2048)
data := make(nbt.ByteArray, 2048)
for i := 0; i < 256; i++ {
biomes[i] = biome
//if biome++; biome >= 23 {
// biome = -1
//}
}
dataTag := nbt.NewTag("", nbt.Compound{
nbt.NewTag("Level", nbt.Compound{
nbt.NewTag("Biomes", biomes),
nbt.NewTag("HeightMap", make(nbt.IntArray, 256)),
nbt.NewTag("InhabitedTime", nbt.Long(0)),
nbt.NewTag("LastUpdate", nbt.Long(0)),
nbt.NewTag("Sections", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(0)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(1)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(3)),
},
nbt.Compound{
nbt.NewTag("Blocks", blocks),
nbt.NewTag("Add", add),
nbt.NewTag("Data", data),
nbt.NewTag("BlockLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("SkyLight", make(nbt.ByteArray, 2048)),
nbt.NewTag("Y", nbt.Byte(10)),
},
}),
nbt.NewTag("TileEntities", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("id", nbt.String("test1")),
nbt.NewTag("x", nbt.Int(-191)),
nbt.NewTag("y", nbt.Int(13)),
nbt.NewTag("z", nbt.Int(379)),
nbt.NewTag("testTag", nbt.Byte(1)),
},
nbt.Compound{
nbt.NewTag("id", nbt.String("test2")),
nbt.NewTag("x", nbt.Int(-191)),
nbt.NewTag("y", nbt.Int(17)),
nbt.NewTag("z", nbt.Int(372)),
nbt.NewTag("testTag", nbt.Long(8)),
},
}),
nbt.NewTag("Entities", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("id", nbt.String("testEntity1")),
nbt.NewTag("Pos", &nbt.ListDouble{
nbt.Double(-190),
nbt.Double(13),
nbt.Double(375),
}),
nbt.NewTag("Motion", &nbt.ListDouble{
nbt.Double(1),
nbt.Double(13),
nbt.Double(11),
}),
nbt.NewTag("Rotation", &nbt.ListFloat{
nbt.Float(13),
nbt.Float(11),
}),
nbt.NewTag("FallDistance", nbt.Float(0)),
nbt.NewTag("Fire", nbt.Short(-1)),
nbt.NewTag("Air", nbt.Short(300)),
nbt.NewTag("OnGround", nbt.Byte(1)),
nbt.NewTag("Dimension", nbt.Int(0)),
nbt.NewTag("Invulnerable", nbt.Byte(0)),
nbt.NewTag("PortalCooldown", nbt.Int(0)),
nbt.NewTag("UUIDMost", nbt.Long(0)),
nbt.NewTag("UUIDLease", nbt.Long(0)),
nbt.NewTag("Riding", nbt.Compound{}),
},
nbt.Compound{
nbt.NewTag("id", nbt.String("testEntity2")),
nbt.NewTag("Pos", &nbt.ListDouble{
nbt.Double(-186),
nbt.Double(2),
nbt.Double(378),
}),
nbt.NewTag("Motion", &nbt.ListDouble{
nbt.Double(17.5),
nbt.Double(1000),
nbt.Double(54),
}),
nbt.NewTag("Rotation", &nbt.ListFloat{
nbt.Float(11),
nbt.Float(13),
}),
nbt.NewTag("FallDistance", nbt.Float(30)),
nbt.NewTag("Fire", nbt.Short(4)),
nbt.NewTag("Air", nbt.Short(30)),
nbt.NewTag("OnGround", nbt.Byte(0)),
nbt.NewTag("Dimension", nbt.Int(0)),
nbt.NewTag("Invulnerable", nbt.Byte(1)),
nbt.NewTag("PortalCooldown", nbt.Int(10)),
nbt.NewTag("UUIDMost", nbt.Long(1450)),
nbt.NewTag("UUIDLease", nbt.Long(6435)),
nbt.NewTag("Riding", nbt.Compound{}),
},
}),
nbt.NewTag("TileTicks", &nbt.ListCompound{
nbt.Compound{
nbt.NewTag("i", nbt.Int(0)),
nbt.NewTag("t", nbt.Int(0)),
nbt.NewTag("p", nbt.Int(0)),
nbt.NewTag("x", nbt.Int(-192)),
nbt.NewTag("y", nbt.Int(0)),
nbt.NewTag("z", nbt.Int(368)),
},
nbt.Compound{
nbt.NewTag("i", nbt.Int(1)),
nbt.NewTag("t", nbt.Int(34)),
nbt.NewTag("p", nbt.Int(12)),
nbt.NewTag("x", nbt.Int(-186)),
nbt.NewTag("y", nbt.Int(11)),
nbt.NewTag("z", nbt.Int(381)),
},
}),
nbt.NewTag("TerrainPopulated", nbt.Byte(1)),
nbt.NewTag("xPos", nbt.Int(-12)),
nbt.NewTag("zPos", nbt.Int(23)),
}),
})
if _, err := newChunk(-12, 23, dataTag); err != nil {
t.Fatalf("reveived unexpected error during testing, %q", err.Error())
}
}
func TestBiomes(t *testing.T) {
chunk, _ := newChunk(0, 0, nbt.Tag{})
for b := Biome(0); b < 23; b++ {
biome := b
for x := int32(0); x < 16; x++ {
for z := int32(0); z < 16; z++ {
chunk.SetBiome(x, z, biome)
if newB := chunk.GetBiome(x, z); newB != biome {
t.Errorf("error setting biome at co-ordinates, expecting %q, got %q", biome.String(), newB.String())
}
}
}
}
}
func TestBlock(t *testing.T) {
chunk, _ := newChunk(0, 0, nbt.Tag{})
testBlocks := []struct {
Block
x, y, z int32
recheck bool
}{
//Test simple set
{
Block{
ID: 12,
},
0, 0, 0,
true,
},
//Test higher ids
{
Block{
ID: 853,
},
1, 0, 0,
true,
},
{
Block{
ID: 463,
},
2, 0, 0,
true,
},
{
Block{
ID: 1001,
},
3, 0, 0,
true,
},
//Test data set
{
Block{
ID: 143,
Data: 12,
},
0, 1, 0,
true,
},
{
Block{
ID: 153,
Data: 4,
},
1, 1, 0,
true,
},
{
Block{
ID: 163,
Data: 5,
},
2, 1, 0,
true,
},
//Test metadata [un]set
{
Block{
metadata: nbt.Compound{
nbt.NewTag("testInt2", nbt.Int(1743)),
nbt.NewTag("testString2", nbt.String("world")),
},
},
0, 0, 1,
true,
},
{
Block{
metadata: nbt.Compound{
nbt.NewTag("testInt", nbt.Int(15)),
nbt.NewTag("testString", nbt.String("hello")),
},
},
1, 0, 1,
false,
},
{
Block{},
1, 0, 1,
true,
},
//Test tick [un]set
{
Block{
ticks: []Tick{{123, 1, 4}, {123, 7, -1}},
},
0, 1, 1,
true,
},
{
Block{
ticks: []Tick{{654, 4, 6}, {4, 63, 5}, {4, 5, 9}},
},
1, 1, 1,
false,
},
{
Block{},
1, 1, 1,
true,
},
}
for _, tB := range testBlocks {
chunk.SetBlock(tB.x, tB.y, tB.z, tB.Block)
if block := chunk.GetBlock(tB.x, tB.y, tB.z); !tB.Block.EqualBlock(block) {
t.Errorf("blocks do not match, expecting %s, got %s", tB.Block.String(), block.String())
}
}
for _, tB := range testBlocks {
if tB.recheck {
if block := chunk.GetBlock(tB.x, tB.y, tB.z); !tB.Block.EqualBlock(block) {
t.Errorf("blocks do not match, expecting:-\n%s\ngot:-\n%s", tB.Block.String(), block.String())
}
}
}
}
func TestHeightMap(t *testing.T) {
tests := []struct {
x, y, z int32
Block
height int32
}{
{0, 0, 0, Block{}, 0},
{1, 0, 0, Block{ID: 1}, 1},
{1, 1, 0, Block{ID: 1}, 2},
{1, 0, 0, Block{}, 2},
{1, 1, 0, Block{}, 0},
{2, 10, 0, Block{ID: 1}, 11},
{2, 12, 0, Block{ID: 1}, 13},
{2, 12, 0, Block{}, 11},
{2, 10, 0, Block{}, 0},
{3, 15, 0, Block{ID: 1}, 16},
{3, 16, 0, Block{ID: 1}, 17},
{3, 16, 0, Block{}, 16},
{3, 15, 0, Block{}, 0},
{4, 31, 0, Block{ID: 1}, 32},
{4, 32, 0, Block{ID: 1}, 33},
{4, 32, 0, Block{}, 32},
{4, 31, 0, Block{}, 0},
{5, 16, 0, Block{ID: 1}, 17},
{5, 32, 0, Block{ID: 1}, 33},
{5, 32, 0, Block{}, 17},
{5, 16, 0, Block{}, 0},
}
chunk, _ := newChunk(0, 0, nbt.Tag{})
for n, test := range tests {
chunk.SetBlock(test.x, test.y, test.z, test.Block)
if h := chunk.GetHeight(test.x, test.z); h != test.height {
t.Errorf("test %d: expecting height %d, got %d", n+1, test.height, h)
}
}
}
|
// Template Source: BaseEntityCollectionPage.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.models.TermsAndConditionsAcceptanceStatus;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionRequestBuilder;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.requests.TermsAndConditionsAcceptanceStatusCollectionResponse;
import com.microsoft.graph.http.BaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Terms And Conditions Acceptance Status Collection Page.
*/
public class TermsAndConditionsAcceptanceStatusCollectionPage extends BaseCollectionPage<TermsAndConditionsAcceptanceStatus, TermsAndConditionsAcceptanceStatusCollectionRequestBuilder> {
/**
* A collection page for TermsAndConditionsAcceptanceStatus
*
* @param response the serialized TermsAndConditionsAcceptanceStatusCollectionResponse from the service
* @param builder the request builder for the next collection page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final TermsAndConditionsAcceptanceStatusCollectionResponse response, @Nonnull final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder builder) {
super(response, builder);
}
/**
* Creates the collection page for TermsAndConditionsAcceptanceStatus
*
* @param pageContents the contents of this page
* @param nextRequestBuilder the request builder for the next page
*/
public TermsAndConditionsAcceptanceStatusCollectionPage(@Nonnull final java.util.List<TermsAndConditionsAcceptanceStatus> pageContents, @Nullable final TermsAndConditionsAcceptanceStatusCollectionRequestBuilder nextRequestBuilder) {
super(pageContents, nextRequestBuilder);
}
}
|
b'What is the value of 7 + 11 + (24 - 58)?\n'
|
/***
* ASM: a very small and fast Java bytecode manipulation framework
* Copyright (c) 2000-2011 INRIA, France Telecom
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package mockit.external.asm4;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* A Java field or method type. This class can be used to make it easier to
* manipulate type and method descriptors.
*
* @author Eric Bruneton
* @author Chris Nokleberg
*/
public class Type {
/**
* The sort of the <tt>void</tt> type. See {@link #getSort getSort}.
*/
public static final int VOID = 0;
/**
* The sort of the <tt>boolean</tt> type. See {@link #getSort getSort}.
*/
public static final int BOOLEAN = 1;
/**
* The sort of the <tt>char</tt> type. See {@link #getSort getSort}.
*/
public static final int CHAR = 2;
/**
* The sort of the <tt>byte</tt> type. See {@link #getSort getSort}.
*/
public static final int BYTE = 3;
/**
* The sort of the <tt>short</tt> type. See {@link #getSort getSort}.
*/
public static final int SHORT = 4;
/**
* The sort of the <tt>int</tt> type. See {@link #getSort getSort}.
*/
public static final int INT = 5;
/**
* The sort of the <tt>float</tt> type. See {@link #getSort getSort}.
*/
public static final int FLOAT = 6;
/**
* The sort of the <tt>long</tt> type. See {@link #getSort getSort}.
*/
public static final int LONG = 7;
/**
* The sort of the <tt>double</tt> type. See {@link #getSort getSort}.
*/
public static final int DOUBLE = 8;
/**
* The sort of array reference types. See {@link #getSort getSort}.
*/
public static final int ARRAY = 9;
/**
* The sort of object reference types. See {@link #getSort getSort}.
*/
public static final int OBJECT = 10;
/**
* The sort of method types. See {@link #getSort getSort}.
*/
public static final int METHOD = 11;
/**
* The <tt>void</tt> type.
*/
public static final Type VOID_TYPE = new Type(VOID, null, ('V' << 24)
| (5 << 16) | (0 << 8) | 0, 1);
/**
* The <tt>boolean</tt> type.
*/
public static final Type BOOLEAN_TYPE = new Type(BOOLEAN, null, ('Z' << 24)
| (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>char</tt> type.
*/
public static final Type CHAR_TYPE = new Type(CHAR, null, ('C' << 24)
| (0 << 16) | (6 << 8) | 1, 1);
/**
* The <tt>byte</tt> type.
*/
public static final Type BYTE_TYPE = new Type(BYTE, null, ('B' << 24)
| (0 << 16) | (5 << 8) | 1, 1);
/**
* The <tt>short</tt> type.
*/
public static final Type SHORT_TYPE = new Type(SHORT, null, ('S' << 24)
| (0 << 16) | (7 << 8) | 1, 1);
/**
* The <tt>int</tt> type.
*/
public static final Type INT_TYPE = new Type(INT, null, ('I' << 24)
| (0 << 16) | (0 << 8) | 1, 1);
/**
* The <tt>float</tt> type.
*/
public static final Type FLOAT_TYPE = new Type(FLOAT, null, ('F' << 24)
| (2 << 16) | (2 << 8) | 1, 1);
/**
* The <tt>long</tt> type.
*/
public static final Type LONG_TYPE = new Type(LONG, null, ('J' << 24)
| (1 << 16) | (1 << 8) | 2, 1);
/**
* The <tt>double</tt> type.
*/
public static final Type DOUBLE_TYPE = new Type(DOUBLE, null, ('D' << 24)
| (3 << 16) | (3 << 8) | 2, 1);
private static final Type[] NO_ARGS = new Type[0];
// ------------------------------------------------------------------------
// Fields
// ------------------------------------------------------------------------
/**
* The sort of this Java type.
*/
private final int sort;
/**
* A buffer containing the internal name of this Java type. This field is
* only used for reference types.
*/
private final char[] buf;
/**
* The offset of the internal name of this Java type in {@link #buf buf} or,
* for primitive types, the size, descriptor and getOpcode offsets for this
* type (byte 0 contains the size, byte 1 the descriptor, byte 2 the offset
* for IALOAD or IASTORE, byte 3 the offset for all other instructions).
*/
private final int off;
/**
* The length of the internal name of this Java type.
*/
private final int len;
// ------------------------------------------------------------------------
// Constructors
// ------------------------------------------------------------------------
/**
* Constructs a reference type.
*
* @param sort the sort of the reference type to be constructed.
* @param buf a buffer containing the descriptor of the previous type.
* @param off the offset of this descriptor in the previous buffer.
* @param len the length of this descriptor.
*/
private Type(int sort, char[] buf, int off, int len)
{
this.sort = sort;
this.buf = buf;
this.off = off;
this.len = len;
}
/**
* Returns the Java type corresponding to the given type descriptor.
*
* @param typeDescriptor a field or method type descriptor.
* @return the Java type corresponding to the given type descriptor.
*/
public static Type getType(String typeDescriptor) {
return getType(typeDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given internal name.
*
* @param internalName an internal name.
* @return the Java type corresponding to the given internal name.
*/
public static Type getObjectType(String internalName) {
char[] buf = internalName.toCharArray();
return new Type(buf[0] == '[' ? ARRAY : OBJECT, buf, 0, buf.length);
}
/**
* Returns the Java type corresponding to the given method descriptor.
* Equivalent to <code>Type.getType(methodDescriptor)</code>.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the given method descriptor.
*/
public static Type getMethodType(String methodDescriptor) {
return getType(methodDescriptor.toCharArray(), 0);
}
/**
* Returns the Java type corresponding to the given class.
*
* @param c a class.
* @return the Java type corresponding to the given class.
*/
public static Type getType(Class<?> c) {
if (c.isPrimitive()) {
if (c == Integer.TYPE) {
return INT_TYPE;
} else if (c == Void.TYPE) {
return VOID_TYPE;
} else if (c == Boolean.TYPE) {
return BOOLEAN_TYPE;
} else if (c == Byte.TYPE) {
return BYTE_TYPE;
} else if (c == Character.TYPE) {
return CHAR_TYPE;
} else if (c == Short.TYPE) {
return SHORT_TYPE;
} else if (c == Double.TYPE) {
return DOUBLE_TYPE;
} else if (c == Float.TYPE) {
return FLOAT_TYPE;
} else /* if (c == Long.TYPE) */{
return LONG_TYPE;
}
} else {
return getType(getDescriptor(c));
}
}
/**
* Returns the Java method type corresponding to the given constructor.
*
* @param c a {@link Constructor Constructor} object.
* @return the Java method type corresponding to the given constructor.
*/
public static Type getType(Constructor<?> c) {
return getType(getConstructorDescriptor(c));
}
/**
* Returns the Java method type corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the Java method type corresponding to the given method.
*/
public static Type getType(Method m) {
return getType(getMethodDescriptor(m));
}
/**
* Returns the Java types corresponding to the argument types of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java types corresponding to the argument types of the given
* method descriptor.
*/
public static Type[] getArgumentTypes(String methodDescriptor) {
if (methodDescriptor.charAt(1) == ')') return NO_ARGS;
char[] buf = methodDescriptor.toCharArray();
int off = 1;
int size = 0;
while (true) {
char car = buf[off++];
if (car == ')') {
break;
} else if (car == 'L') {
while (buf[off++] != ';') {
}
++size;
} else if (car != '[') {
++size;
}
}
Type[] args = new Type[size];
off = 1;
size = 0;
while (buf[off] != ')') {
args[size] = getType(buf, off);
off += args[size].len + (args[size].sort == OBJECT ? 2 : 0);
size += 1;
}
return args;
}
/**
* Returns the Java type corresponding to the return type of the given
* method descriptor.
*
* @param methodDescriptor a method descriptor.
* @return the Java type corresponding to the return type of the given
* method descriptor.
*/
public static Type getReturnType(String methodDescriptor) {
char[] buf = methodDescriptor.toCharArray();
return getType(buf, methodDescriptor.indexOf(')') + 1);
}
/**
* Computes the size of the arguments and of the return value of a method.
*
* @param desc the descriptor of a method.
* @return the size of the arguments of the method (plus one for the
* implicit this argument), argSize, and the size of its return
* value, retSize, packed into a single int i =
* <tt>(argSize << 2) | retSize</tt> (argSize is therefore equal
* to <tt>i >> 2</tt>, and retSize to <tt>i & 0x03</tt>).
*/
public static int getArgumentsAndReturnSizes(String desc) {
int n = 1;
int c = 1;
while (true) {
char car = desc.charAt(c++);
if (car == ')') {
car = desc.charAt(c);
return n << 2
| (car == 'V' ? 0 : (car == 'D' || car == 'J' ? 2 : 1));
} else if (car == 'L') {
while (desc.charAt(c++) != ';') {
}
n += 1;
} else if (car == '[') {
while ((car = desc.charAt(c)) == '[') {
++c;
}
if (car == 'D' || car == 'J') {
n -= 1;
}
} else if (car == 'D' || car == 'J') {
n += 2;
} else {
n += 1;
}
}
}
/**
* Returns the Java type corresponding to the given type descriptor. For
* method descriptors, buf is supposed to contain nothing more than the
* descriptor itself.
*
* @param buf a buffer containing a type descriptor.
* @param off the offset of this descriptor in the previous buffer.
* @return the Java type corresponding to the given type descriptor.
*/
private static Type getType(char[] buf, int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
case '[':
len = 1;
while (buf[off + len] == '[') {
++len;
}
if (buf[off + len] == 'L') {
++len;
while (buf[off + len] != ';') {
++len;
}
}
return new Type(ARRAY, buf, off, len + 1);
case 'L':
len = 1;
while (buf[off + len] != ';') {
++len;
}
return new Type(OBJECT, buf, off + 1, len - 1);
case '(':
return new Type(METHOD, buf, 0, buf.length);
default:
throw new IllegalArgumentException("Invalid type descriptor: " + new String(buf));
}
}
// ------------------------------------------------------------------------
// Accessors
// ------------------------------------------------------------------------
/**
* Returns the sort of this Java type.
*
* @return {@link #VOID VOID}, {@link #BOOLEAN BOOLEAN},
* {@link #CHAR CHAR}, {@link #BYTE BYTE}, {@link #SHORT SHORT},
* {@link #INT INT}, {@link #FLOAT FLOAT}, {@link #LONG LONG},
* {@link #DOUBLE DOUBLE}, {@link #ARRAY ARRAY},
* {@link #OBJECT OBJECT} or {@link #METHOD METHOD}.
*/
public int getSort() {
return sort;
}
/**
* Returns the number of dimensions of this array type. This method should
* only be used for an array type.
*
* @return the number of dimensions of this array type.
*/
public int getDimensions() {
int i = 1;
while (buf[off + i] == '[') {
++i;
}
return i;
}
/**
* Returns the type of the elements of this array type. This method should
* only be used for an array type.
*
* @return Returns the type of the elements of this array type.
*/
public Type getElementType() {
return getType(buf, off + getDimensions());
}
/**
* Returns the binary name of the class corresponding to this type. This
* method must not be used on method types.
*
* @return the binary name of the class corresponding to this type.
*/
public String getClassName() {
switch (sort) {
case VOID:
return "void";
case BOOLEAN:
return "boolean";
case CHAR:
return "char";
case BYTE:
return "byte";
case SHORT:
return "short";
case INT:
return "int";
case FLOAT:
return "float";
case LONG:
return "long";
case DOUBLE:
return "double";
case ARRAY:
StringBuffer b = new StringBuffer(getElementType().getClassName());
for (int i = getDimensions(); i > 0; --i) {
b.append("[]");
}
return b.toString();
case OBJECT:
return new String(buf, off, len).replace('/', '.');
default:
return null;
}
}
/**
* Returns the internal name of the class corresponding to this object or
* array type. The internal name of a class is its fully qualified name (as
* returned by Class.getName(), where '.' are replaced by '/'. This method
* should only be used for an object or array type.
*
* @return the internal name of the class corresponding to this object type.
*/
public String getInternalName() {
return new String(buf, off, len);
}
// ------------------------------------------------------------------------
// Conversion to type descriptors
// ------------------------------------------------------------------------
/**
* Returns the descriptor corresponding to this Java type.
*
* @return the descriptor corresponding to this Java type.
*/
public String getDescriptor() {
StringBuffer buf = new StringBuffer();
getDescriptor(buf);
return buf.toString();
}
/**
* Appends the descriptor corresponding to this Java type to the given
* string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
*/
private void getDescriptor(StringBuffer buf) {
if (this.buf == null) {
// descriptor is in byte 3 of 'off' for primitive types (buf == null)
buf.append((char) ((off & 0xFF000000) >>> 24));
} else if (sort == OBJECT) {
buf.append('L');
buf.append(this.buf, off, len);
buf.append(';');
} else { // sort == ARRAY || sort == METHOD
buf.append(this.buf, off, len);
}
}
// ------------------------------------------------------------------------
// Direct conversion from classes to type descriptors,
// without intermediate Type objects
// ------------------------------------------------------------------------
/**
* Returns the internal name of the given class. The internal name of a
* class is its fully qualified name, as returned by Class.getName(), where
* '.' are replaced by '/'.
*
* @param c an object or array class.
* @return the internal name of the given class.
*/
public static String getInternalName(Class<?> c) {
return c.getName().replace('.', '/');
}
/**
* Returns the descriptor corresponding to the given Java type.
*
* @param c an object class, a primitive class or an array class.
* @return the descriptor corresponding to the given class.
*/
public static String getDescriptor(Class<?> c) {
StringBuffer buf = new StringBuffer();
getDescriptor(buf, c);
return buf.toString();
}
/**
* Returns the descriptor corresponding to the given constructor.
*
* @param c a {@link Constructor Constructor} object.
* @return the descriptor of the given constructor.
*/
public static String getConstructorDescriptor(Constructor<?> c) {
Class<?>[] parameters = c.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
return buf.append(")V").toString();
}
/**
* Returns the descriptor corresponding to the given method.
*
* @param m a {@link Method Method} object.
* @return the descriptor of the given method.
*/
public static String getMethodDescriptor(Method m) {
Class<?>[] parameters = m.getParameterTypes();
StringBuffer buf = new StringBuffer();
buf.append('(');
for (int i = 0; i < parameters.length; ++i) {
getDescriptor(buf, parameters[i]);
}
buf.append(')');
getDescriptor(buf, m.getReturnType());
return buf.toString();
}
/**
* Appends the descriptor of the given class to the given string buffer.
*
* @param buf the string buffer to which the descriptor must be appended.
* @param c the class whose descriptor must be computed.
*/
private static void getDescriptor(StringBuffer buf, Class<?> c) {
Class<?> d = c;
while (true) {
if (d.isPrimitive()) {
char car;
if (d == Integer.TYPE) {
car = 'I';
} else if (d == Void.TYPE) {
car = 'V';
} else if (d == Boolean.TYPE) {
car = 'Z';
} else if (d == Byte.TYPE) {
car = 'B';
} else if (d == Character.TYPE) {
car = 'C';
} else if (d == Short.TYPE) {
car = 'S';
} else if (d == Double.TYPE) {
car = 'D';
} else if (d == Float.TYPE) {
car = 'F';
} else /* if (d == Long.TYPE) */{
car = 'J';
}
buf.append(car);
return;
} else if (d.isArray()) {
buf.append('[');
d = d.getComponentType();
} else {
buf.append('L');
String name = d.getName();
int len = name.length();
for (int i = 0; i < len; ++i) {
char car = name.charAt(i);
buf.append(car == '.' ? '/' : car);
}
buf.append(';');
return;
}
}
}
// ------------------------------------------------------------------------
// Corresponding size and opcodes
// ------------------------------------------------------------------------
/**
* Returns the size of values of this type. This method must not be used for
* method types.
*
* @return the size of values of this type, i.e., 2 for <tt>long</tt> and
* <tt>double</tt>, 0 for <tt>void</tt> and 1 otherwise.
*/
public int getSize() {
// the size is in byte 0 of 'off' for primitive types (buf == null)
return buf == null ? off & 0xFF : 1;
}
/**
* Returns a JVM instruction opcode adapted to this Java type. This method
* must not be used for method types.
*
* @param opcode a JVM instruction opcode. This opcode must be one of ILOAD,
* ISTORE, IALOAD, IASTORE, IADD, ISUB, IMUL, IDIV, IREM, INEG, ISHL,
* ISHR, IUSHR, IAND, IOR, IXOR and IRETURN.
* @return an opcode that is similar to the given opcode, but adapted to
* this Java type. For example, if this type is <tt>float</tt> and
* <tt>opcode</tt> is IRETURN, this method returns FRETURN.
*/
public int getOpcode(int opcode) {
if (opcode == Opcodes.IALOAD || opcode == Opcodes.IASTORE) {
// the offset for IALOAD or IASTORE is in byte 1 of 'off' for
// primitive types (buf == null)
return opcode + (buf == null ? (off & 0xFF00) >> 8 : 4);
} else {
// the offset for other instructions is in byte 2 of 'off' for
// primitive types (buf == null)
return opcode + (buf == null ? (off & 0xFF0000) >> 16 : 4);
}
}
// ------------------------------------------------------------------------
// Equals, hashCode and toString
// ------------------------------------------------------------------------
/**
* Tests if the given object is equal to this type.
*
* @param o the object to be compared to this type.
* @return <tt>true</tt> if the given object is equal to this type.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Type)) {
return false;
}
Type t = (Type) o;
if (sort != t.sort) {
return false;
}
if (sort >= ARRAY) {
if (len != t.len) {
return false;
}
for (int i = off, j = t.off, end = i + len; i < end; i++, j++) {
if (buf[i] != t.buf[j]) {
return false;
}
}
}
return true;
}
/**
* Returns a hash code value for this type.
*
* @return a hash code value for this type.
*/
@Override
public int hashCode() {
int hc = 13 * sort;
if (sort >= ARRAY) {
for (int i = off, end = i + len; i < end; i++) {
hc = 17 * (hc + buf[i]);
}
}
return hc;
}
/**
* Returns a string representation of this type.
*
* @return the descriptor of this type.
*/
@Override
public String toString() {
return getDescriptor();
}
}
|
b'What is the value of 21 - -2 - (2 + 11)?\n'
|
b'Calculate 10 - (-14 - -7) - 25.\n'
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>slickgrid-colfix-plugin example</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../bower_components/slickgrid/slick.grid.css" type="text/css" />
<link rel="stylesheet" href="../bower_components/slickgrid/css/smoothness/jquery-ui-1.8.16.custom.css" type="text/css" />
<link rel="stylesheet" href="../bower_components/slickgrid/examples/examples.css" type="text/css" />
<style>
body {margin: 0;}
.grid {background: white; outline: 0; border: 1px solid gray;}
.slick-row.active {background-color: #fcc;}
.idx {background-color: #f2f2f2; border-right: 1px solid #aaa; text-align: right; font-size: 0.8em; padding-right: 8px;}
</style>
</head>
<body>
<div id="my-grid" class="grid" style="width: 800px; height: 400px"></div>
<script src="../bower_components/slickgrid/lib/jquery-1.7.min.js"></script>
<script src="../bower_components/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"></script>
<script src="../bower_components/slickgrid/lib/jquery.event.drag-2.2.js"></script>
<script src="../bower_components/slickgrid/slick.core.js"></script>
<script src="../bower_components/slickgrid/slick.grid.js"></script>
<script src="../dist/slick.colfix.js"></script>
<script>
/** columns defination */
var columns = [
{id: '#', name: '', field: 'idx', width: 50, cssClass: 'idx'},
{id: 'col1', name: 'col 1', field: 'col1', width: 50},
{id: 'col2', name: 'col 2', field: 'col2', width: 80},
{id: 'col3', name: 'col 3', field: 'col3', width: 100},
{id: 'col4', name: 'col 4', field: 'col4', width: 200},
{id: 'col5', name: 'col 5', field: 'col5', width: 50},
{id: 'col6', name: 'col 6', field: 'col6', width: 300},
{id: 'col7', name: 'col 7', field: 'col7', width: 100},
{id: 'col8', name: 'col 8', field: 'col8', width: 200},
{id: 'col9', name: 'col 9', field: 'col9', width: 100}
];
/** grid options */
var options = {
enableColumnReorder: false,
explicitInitialization: true
};
/** data */
var data = [];
for (var i = 0; i < 500; i++) {
data[i] = {
idx: i,
col1: 'col 1-' + i,
col2: 'col 2-' + i,
col3: 'col 3-' + i,
col4: 'col 4-' + i,
col5: 'col 5-' + i,
col6: 'col 6-' + i,
col7: 'col 7-' + i,
col8: 'col 8-' + i,
col9: 'col 9-' + i
};
}
/** SlickGrid */
var grid = new Slick.Grid('#my-grid', data, columns, options);
// register colfix plguin
grid.registerPlugin(new Slick.Plugins.ColFix('#'));
// initialize
grid.init();
</script>
</body>
</html>
|
b'-9 + -3 + (22 + 17 - 29)\n'
|
import Immutable from 'immutable';
import * as ActionType from '../../actions/auth/auth';
const defaultState = Immutable.fromJS({
loggedIn: false,
});
function authReducer(state = defaultState, action) {
const {
loggedIn,
} = action;
switch (action.type) {
case ActionType.VERIFIED_LOGIN:
return state.merge(Immutable.fromJS({ loggedIn }));
default:
return state;
}
}
export default authReducer;
|
/**
* Copyright (c) 2015, Alexander Orzechowski.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Currently in beta stage. Changes can and will be made to the core mechanic
* making this not backwards compatible.
*
* Github: https://github.com/Need4Speed402/tessellator
*/
Tessellator.Model.prototype.drawObject = Tessellator.Model.prototype.add;
|
b'What is (8 - (-13 + (24 - 1))) + 26?\n'
|
b'Evaluate -46 + 41 + (3 - 0) - (-21 + -1).\n'
|
b'What is the value of 1 + (4 - (15 + -20))?\n'
|
b'5 - (7 + 6 + (0 - -1)) - -4\n'
|
System.register(["angular2/test_lib", "angular2/src/test_lib/test_bed", "angular2/src/core/annotations_impl/annotations", "angular2/src/core/annotations_impl/view", "angular2/src/core/compiler/dynamic_component_loader", "angular2/src/core/compiler/element_ref", "angular2/src/directives/if", "angular2/src/render/dom/direct_dom_renderer", "angular2/src/dom/dom_adapter"], function($__export) {
"use strict";
var AsyncTestCompleter,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
dispatchEvent,
expect,
iit,
inject,
beforeEachBindings,
it,
xit,
TestBed,
Component,
View,
DynamicComponentLoader,
ElementRef,
If,
DirectDomRenderer,
DOM,
ImperativeViewComponentUsingNgComponent,
ChildComp,
DynamicallyCreatedComponentService,
DynamicComp,
DynamicallyCreatedCmp,
DynamicallyLoaded,
DynamicallyLoaded2,
DynamicallyLoadedWithHostProps,
Location,
MyComp;
function main() {
describe('DynamicComponentLoader', function() {
describe("loading into existing location", (function() {
it('should work', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
expect(dynamicComponent).toBeAnInstanceOf(DynamicComp);
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
it('should inject dependencies of the dynamically-loaded component', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<dynamic-comp #dynamic></dynamic-comp>',
directives: [DynamicComp]
}));
tb.createView(MyComp).then((function(view) {
var dynamicComponent = view.rawView.locals.get("dynamic");
dynamicComponent.done.then((function(ref) {
expect(ref.instance.dynamicallyCreatedComponentService).toBeAnInstanceOf(DynamicallyCreatedComponentService);
async.done();
}));
}));
})));
it('should allow to destroy and create them via viewcontainer directives', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><dynamic-comp #dynamic template="if: ctxBoolProp"></dynamic-comp></div>',
directives: [DynamicComp, If]
}));
tb.createView(MyComp).then((function(view) {
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
dynamicComponent.done.then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
view.context.ctxBoolProp = false;
view.detectChanges();
expect(view.rawView.viewContainers[0].views.length).toBe(0);
expect(view.rootNodes).toHaveText('');
view.context.ctxBoolProp = true;
view.detectChanges();
var dynamicComponent = view.rawView.viewContainers[0].views[0].locals.get("dynamic");
return dynamicComponent.done;
})).then((function(_) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
async.done();
}));
}));
})));
}));
describe("loading next to an existing location", (function() {
it('should work', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
})));
it('should return a disposable component ref', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoaded, location.elementRef).then((function(ref) {
loader.loadNextToExistingLocation(DynamicallyLoaded2, location.elementRef).then((function(ref2) {
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;DynamicallyLoaded2;");
ref2.dispose();
expect(view.rootNodes).toHaveText("Location;DynamicallyLoaded;");
async.done();
}));
}));
}));
})));
it('should update host properties', inject([DynamicComponentLoader, TestBed, AsyncTestCompleter], (function(loader, tb, async) {
tb.overrideView(MyComp, new View({
template: '<div><location #loc></location></div>',
directives: [Location]
}));
tb.createView(MyComp).then((function(view) {
var location = view.rawView.locals.get("loc");
loader.loadNextToExistingLocation(DynamicallyLoadedWithHostProps, location.elementRef).then((function(ref) {
ref.instance.id = "new value";
view.detectChanges();
var newlyInsertedElement = DOM.childNodesAsList(view.rootNodes[0])[1];
expect(newlyInsertedElement.id).toEqual("new value");
async.done();
}));
}));
})));
}));
describe('loading into a new location', (function() {
it('should allow to create, update and destroy components', inject([TestBed, AsyncTestCompleter], (function(tb, async) {
tb.overrideView(MyComp, new View({
template: '<imp-ng-cmp #impview></imp-ng-cmp>',
directives: [ImperativeViewComponentUsingNgComponent]
}));
tb.createView(MyComp).then((function(view) {
var userViewComponent = view.rawView.locals.get("impview");
userViewComponent.done.then((function(childComponentRef) {
view.detectChanges();
expect(view.rootNodes).toHaveText('hello');
childComponentRef.instance.ctxProp = 'new';
view.detectChanges();
expect(view.rootNodes).toHaveText('new');
childComponentRef.dispose();
expect(view.rootNodes).toHaveText('');
async.done();
}));
}));
})));
}));
});
}
$__export("main", main);
return {
setters: [function($__m) {
AsyncTestCompleter = $__m.AsyncTestCompleter;
beforeEach = $__m.beforeEach;
ddescribe = $__m.ddescribe;
xdescribe = $__m.xdescribe;
describe = $__m.describe;
el = $__m.el;
dispatchEvent = $__m.dispatchEvent;
expect = $__m.expect;
iit = $__m.iit;
inject = $__m.inject;
beforeEachBindings = $__m.beforeEachBindings;
it = $__m.it;
xit = $__m.xit;
}, function($__m) {
TestBed = $__m.TestBed;
}, function($__m) {
Component = $__m.Component;
}, function($__m) {
View = $__m.View;
}, function($__m) {
DynamicComponentLoader = $__m.DynamicComponentLoader;
}, function($__m) {
ElementRef = $__m.ElementRef;
}, function($__m) {
If = $__m.If;
}, function($__m) {
DirectDomRenderer = $__m.DirectDomRenderer;
}, function($__m) {
DOM = $__m.DOM;
}],
execute: function() {
ImperativeViewComponentUsingNgComponent = (function() {
var ImperativeViewComponentUsingNgComponent = function ImperativeViewComponentUsingNgComponent(self, dynamicComponentLoader, renderer) {
var div = el('<div></div>');
renderer.setImperativeComponentRootNodes(self.parentView.render, self.boundElementIndex, [div]);
this.done = dynamicComponentLoader.loadIntoNewLocation(ChildComp, self, div, null);
};
return ($traceurRuntime.createClass)(ImperativeViewComponentUsingNgComponent, {}, {});
}());
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "annotations", {get: function() {
return [new Component({selector: 'imp-ng-cmp'}), new View({renderer: 'imp-ng-cmp-renderer'})];
}});
Object.defineProperty(ImperativeViewComponentUsingNgComponent, "parameters", {get: function() {
return [[ElementRef], [DynamicComponentLoader], [DirectDomRenderer]];
}});
ChildComp = (function() {
var ChildComp = function ChildComp() {
this.ctxProp = 'hello';
};
return ($traceurRuntime.createClass)(ChildComp, {}, {});
}());
Object.defineProperty(ChildComp, "annotations", {get: function() {
return [new Component({selector: 'child-cmp'}), new View({template: '{{ctxProp}}'})];
}});
DynamicallyCreatedComponentService = (function() {
var DynamicallyCreatedComponentService = function DynamicallyCreatedComponentService() {
;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedComponentService, {}, {});
}());
DynamicComp = (function() {
var DynamicComp = function DynamicComp(loader, location) {
this.done = loader.loadIntoExistingLocation(DynamicallyCreatedCmp, location);
};
return ($traceurRuntime.createClass)(DynamicComp, {}, {});
}());
Object.defineProperty(DynamicComp, "annotations", {get: function() {
return [new Component({selector: 'dynamic-comp'})];
}});
Object.defineProperty(DynamicComp, "parameters", {get: function() {
return [[DynamicComponentLoader], [ElementRef]];
}});
DynamicallyCreatedCmp = (function() {
var DynamicallyCreatedCmp = function DynamicallyCreatedCmp(a) {
this.greeting = "hello";
this.dynamicallyCreatedComponentService = a;
};
return ($traceurRuntime.createClass)(DynamicallyCreatedCmp, {}, {});
}());
Object.defineProperty(DynamicallyCreatedCmp, "annotations", {get: function() {
return [new Component({
selector: 'hello-cmp',
injectables: [DynamicallyCreatedComponentService]
}), new View({template: "{{greeting}}"})];
}});
Object.defineProperty(DynamicallyCreatedCmp, "parameters", {get: function() {
return [[DynamicallyCreatedComponentService]];
}});
DynamicallyLoaded = (function() {
var DynamicallyLoaded = function DynamicallyLoaded() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded, {}, {});
}());
Object.defineProperty(DynamicallyLoaded, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded;"})];
}});
DynamicallyLoaded2 = (function() {
var DynamicallyLoaded2 = function DynamicallyLoaded2() {
;
};
return ($traceurRuntime.createClass)(DynamicallyLoaded2, {}, {});
}());
Object.defineProperty(DynamicallyLoaded2, "annotations", {get: function() {
return [new Component({selector: 'dummy'}), new View({template: "DynamicallyLoaded2;"})];
}});
DynamicallyLoadedWithHostProps = (function() {
var DynamicallyLoadedWithHostProps = function DynamicallyLoadedWithHostProps() {
this.id = "default";
};
return ($traceurRuntime.createClass)(DynamicallyLoadedWithHostProps, {}, {});
}());
Object.defineProperty(DynamicallyLoadedWithHostProps, "annotations", {get: function() {
return [new Component({
selector: 'dummy',
hostProperties: {'id': 'id'}
}), new View({template: "DynamicallyLoadedWithHostProps;"})];
}});
Location = (function() {
var Location = function Location(elementRef) {
this.elementRef = elementRef;
};
return ($traceurRuntime.createClass)(Location, {}, {});
}());
Object.defineProperty(Location, "annotations", {get: function() {
return [new Component({selector: 'location'}), new View({template: "Location;"})];
}});
Object.defineProperty(Location, "parameters", {get: function() {
return [[ElementRef]];
}});
MyComp = (function() {
var MyComp = function MyComp() {
this.ctxBoolProp = false;
};
return ($traceurRuntime.createClass)(MyComp, {}, {});
}());
Object.defineProperty(MyComp, "annotations", {get: function() {
return [new Component({selector: 'my-comp'}), new View({directives: []})];
}});
}
};
});
//# sourceMappingURL=dynamic_component_loader_spec.es6.map
//# sourceMappingURL=./dynamic_component_loader_spec.js.map
|
b'-55 + 50 + (0 - -13) + -1\n'
|
b'-6 + 92 + -88 + -5 + -1\n'
|
var fusepm = require('./fusepm');
module.exports = fixunoproj;
function fixunoproj () {
var fn = fusepm.local_unoproj(".");
fusepm.read_unoproj(fn).then(function (obj) {
var inc = [];
if (obj.Includes) {
var re = /\//;
for (var i=0; i<obj.Includes.length;i++) {
if (obj.Includes[i] === '*') {
inc.push('./*.ux');
inc.push('./*.uno');
inc.push('./*.uxl');
}
else if (!obj.Includes[i].match(re)) {
inc.push('./' + obj.Includes[i]);
}
else {
inc.push(obj.Includes[i]);
}
}
}
else {
inc = ['./*.ux', './*.uno', './*.uxl'];
}
if (!obj.Version) {
obj.Version = "0.0.0";
}
obj.Includes = inc;
fusepm.save_unoproj(fn, obj);
}).catch(function (e) {
console.log(e);
});
}
|
exports.login = function* (ctx) {
const result = yield ctx.service.mine.login(ctx.request.body);
if (!result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: `please check your username and password`,
}
return;
}
ctx.body = {
access_token: result.access_token,
msg: 'login success',
};
ctx.status = 200;
}
exports.signup = function* (ctx) {
const result = yield ctx.service.mine.signup(ctx.request.body);
if (!result.result) {
ctx.status = 400;
ctx.body = {
status: 400,
msg: result.msg,
}
return;
}
ctx.status = 201;
ctx.body = {
status: 201,
msg: 'success',
}
}
exports.info = function* (ctx) {
const info = yield ctx.service.mine.info(ctx.auth.user_id);
if (info == null) {
ctx.status = 200;
ctx.body = {
status: 200,
msg: 'there is no info for current user',
}
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.statistics = function* (ctx) {
const info = yield ctx.service.mine.statistics(ctx.auth.user_id);
if (info == null) {
ctx.status = 200;
ctx.body = {
shares_count: 0,
friends_count: 0,
helpful_count: 0,
};
return;
}
ctx.body = info;
ctx.status = 200;
}
exports.accounts = function* (ctx) {
const accounts = yield ctx.service.mine.accounts(ctx.auth.user_id);
ctx.body = accounts;
ctx.status = 200;
}
exports.update = function* (ctx) {
let profile = ctx.request.body;
profile.id = ctx.auth.user_id;
const result = yield ctx.service.mine.update(profile);
if (result) {
ctx.status = 204;
return;
}
ctx.status = 500;
ctx.body = {
msg: 'update profile failed',
}
}
exports.avatar = function* (ctx) {
const parts = ctx.multipart();
const { filename, error } = yield ctx.service.mine.avatar(parts, `avatar/${ctx.auth.user_id}`);
if (error) {
ctx.status = 500;
ctx.body = {
status: 500,
msg: 'update avatar failed',
};
return false;
}
ctx.status = 200;
ctx.body = {
filename,
msg: 'success',
}
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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.11"/>
<title>V8 API Reference Guide for node.js v7.2.1: v8::Maybe< T > 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>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</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">V8 API Reference Guide for node.js v7.2.1
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<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><a href="namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</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="inherits.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)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1Maybe.html">Maybe</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#friends">Friends</a> |
<a href="classv8_1_1Maybe-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">v8::Maybe< T > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><code>#include <<a class="el" href="v8_8h_source.html">v8.h</a>></code></p>
<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:a486b608c21c8038d5019bd7d75866345"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a486b608c21c8038d5019bd7d75866345"></a>
V8_INLINE bool </td><td class="memItemRight" valign="bottom"><b>IsNothing</b> () const </td></tr>
<tr class="separator:a486b608c21c8038d5019bd7d75866345"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adc82dc945891060d312fb6fbf8fb56ae"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adc82dc945891060d312fb6fbf8fb56ae"></a>
V8_INLINE bool </td><td class="memItemRight" valign="bottom"><b>IsJust</b> () const </td></tr>
<tr class="separator:adc82dc945891060d312fb6fbf8fb56ae"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a4959bad473c4549048c1d2271a1a73e0"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a4959bad473c4549048c1d2271a1a73e0"></a>
V8_INLINE T </td><td class="memItemRight" valign="bottom"><b>ToChecked</b> () const </td></tr>
<tr class="separator:a4959bad473c4549048c1d2271a1a73e0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae2e1c6d0bd1ab5ff8de22a312c4dbb37"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ae2e1c6d0bd1ab5ff8de22a312c4dbb37"></a>
V8_WARN_UNUSED_RESULT V8_INLINE bool </td><td class="memItemRight" valign="bottom"><b>To</b> (T *out) const </td></tr>
<tr class="separator:ae2e1c6d0bd1ab5ff8de22a312c4dbb37"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a02b19d7fcb7744d8dba3530ef8e14c8c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a02b19d7fcb7744d8dba3530ef8e14c8c"></a>
V8_INLINE T </td><td class="memItemRight" valign="bottom"><b>FromJust</b> () const </td></tr>
<tr class="separator:a02b19d7fcb7744d8dba3530ef8e14c8c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0bcb5fb0d0e92a3f0cc546f11068a8df"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a0bcb5fb0d0e92a3f0cc546f11068a8df"></a>
V8_INLINE T </td><td class="memItemRight" valign="bottom"><b>FromMaybe</b> (const T &default_value) const </td></tr>
<tr class="separator:a0bcb5fb0d0e92a3f0cc546f11068a8df"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adf61111c2da44e10ba5ab546a9a525ce"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="adf61111c2da44e10ba5ab546a9a525ce"></a>
V8_INLINE bool </td><td class="memItemRight" valign="bottom"><b>operator==</b> (const <a class="el" href="classv8_1_1Maybe.html">Maybe</a> &other) const </td></tr>
<tr class="separator:adf61111c2da44e10ba5ab546a9a525ce"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5bbacc606422d7ab327c2683462342ec"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a5bbacc606422d7ab327c2683462342ec"></a>
V8_INLINE bool </td><td class="memItemRight" valign="bottom"><b>operator!=</b> (const <a class="el" href="classv8_1_1Maybe.html">Maybe</a> &other) const </td></tr>
<tr class="separator:a5bbacc606422d7ab327c2683462342ec"><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:aeb9593e125b42d748acbd69b72c89f37"><td class="memTemplParams" colspan="2"><a class="anchor" id="aeb9593e125b42d748acbd69b72c89f37"></a>
template<class U > </td></tr>
<tr class="memitem:aeb9593e125b42d748acbd69b72c89f37"><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="classv8_1_1Maybe.html">Maybe</a>< U > </td><td class="memTemplItemRight" valign="bottom"><b>Nothing</b> ()</td></tr>
<tr class="separator:aeb9593e125b42d748acbd69b72c89f37"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aeff0e7fedd63cfebe9a5286e2cd8552d"><td class="memTemplParams" colspan="2"><a class="anchor" id="aeff0e7fedd63cfebe9a5286e2cd8552d"></a>
template<class U > </td></tr>
<tr class="memitem:aeff0e7fedd63cfebe9a5286e2cd8552d"><td class="memTemplItemLeft" align="right" valign="top"><a class="el" href="classv8_1_1Maybe.html">Maybe</a>< U > </td><td class="memTemplItemRight" valign="bottom"><b>Just</b> (const U &u)</td></tr>
<tr class="separator:aeff0e7fedd63cfebe9a5286e2cd8552d"><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<class T><br />
class v8::Maybe< T ></h3>
<p>A simple <a class="el" href="classv8_1_1Maybe.html">Maybe</a> type, representing an object which may or may not have a value, see <a href="https://hackage.haskell.org/package/base/docs/Data-Maybe.html">https://hackage.haskell.org/package/base/docs/Data-Maybe.html</a>.</p>
<p>If an API method returns a Maybe<>, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a TerminateExecution exception was thrown. In that case, a "Nothing" value is returned. </p>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
|
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Student Id</th>
<th>Student Name</th>
<th>Course</th>
<!--<th>
<select class="form-control" name='Year Level' required>
<option> THIRD YEAR</option>
<option> ALL</option>
<option> FIRST YEAR</option>
<option> SECOND YEAR</option>
<option> FOURTH YEAR</option>
</select>
</th>-->
<th colspan="2">Action</th>
</tr>
<?php
// fetch the records in tbl_enrollment
$result = $this->enrollment->getStud($param);
foreach($result as $info)
{
extract($info);
$stud_info = $this->party->getStudInfo($partyid);
$course = $this->course->getCourse($coursemajor);
?>
<tr>
<td><?php echo $stud_info['legacyid']; ?></td>
<td><?php echo $stud_info['lastname'] . ' , ' . $stud_info['firstname'] ?></td>
<td><?php echo $course; ?></td>
<!--<td></td>-->
<td>
<?php if($stud_info['status'] != 'C'){
?>
<a class="a-table label label-info" href="/rgstr_build/<?php echo $stud_info['legacyid'];?>">View
Records <span class="glyphicon glyphicon-file"></span></a>
<?php } ?>
</td>
</tr>
<?php
//}
}
?>
</table>
|
<?php
/*
Template Name: Full Page Width Template
*/
get_header();
while ( have_posts() ) {
the_post();
get_template_part( 'content', 'page-full' );
} // end of the loop
get_footer();
|
b'Evaluate -1 + 24 + (20 + -15 + 0 - -1).\n'
|
'use strict';
/**
* The basic http module, used to create the server.
*
* @link http://nodejs.org/api/http.html
*/
alchemy.use('http', 'http');
/**
* This module contains utilities for handling and transforming file paths.
* Almost all these methods perform only string transformations.
* The file system is not consulted to check whether paths are valid.
*
* @link http://nodejs.org/api/path.html
*/
alchemy.use('path', 'path');
/**
* File I/O is provided by simple wrappers around standard POSIX functions.
*
* @link http://nodejs.org/api/fs.html
*/
alchemy.use('graceful-fs', 'fs');
/**
* Usefull utilities.
*
* @link http://nodejs.org/api/util.html
*/
alchemy.use('util', 'util');
/**
* The native mongodb library
*
* @link https://npmjs.org/package/mongodb
*/
alchemy.use('mongodb', 'mongodb');
/**
* The LESS interpreter.
*
* @link https://npmjs.org/package/less
*/
alchemy.use('less', 'less');
/**
* Hawkejs view engine
*
* @link https://npmjs.org/package/hawkejs
*/
alchemy.use('hawkejs', 'hawkejs');
alchemy.hawkejs = new Classes.Hawkejs.Hawkejs;
/**
* The function to detect when everything is too busy
*/
alchemy.toobusy = alchemy.use('toobusy-js', 'toobusy');
// If the config is a number, use that as the lag threshold
if (typeof alchemy.settings.toobusy === 'number') {
alchemy.toobusy.maxLag(alchemy.settings.toobusy);
}
/**
* Load Sputnik, the stage-based launcher
*/
alchemy.sputnik = new (alchemy.use('sputnik', 'sputnik'))();
/**
* Real-time apps made cross-browser & easy with a WebSocket-like API.
*
* @link https://npmjs.org/package/socket.io
*/
alchemy.use('socket.io', 'io');
/**
* Recursively mkdir, like `mkdir -p`.
* This is a requirement fetched from express
*
* @link https://npmjs.org/package/mkdirp
*/
alchemy.use('mkdirp', 'mkdirp');
/**
* Base useragent library
*
* @link https://npmjs.org/package/useragent
*/
alchemy.use('useragent');
/**
* Enable the `satisfies` method in the `useragent` library
*
* @link https://www.npmjs.com/package/useragent#adding-more-features-to-the-useragent
*/
require('useragent/features');
|
b'(-6 - 0) + -13 + 68 + -63\n'
|
package billing
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// OperationsClient is the billing client provides access to billing resources for Azure subscriptions.
type OperationsClient struct {
BaseClient
}
// NewOperationsClient creates an instance of the OperationsClient client.
func NewOperationsClient(subscriptionID string) OperationsClient {
return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List lists the available billing REST API operations.
func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List")
defer func() {
sc := -1
if result.olr.Response.Response != nil {
sc = result.olr.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.olr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", resp, "Failure sending request")
return
}
result.olr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.OperationsClient", "List", resp, "Failure responding to request")
return
}
if result.olr.hasNextLink() && result.olr.IsEmpty() {
err = result.NextWithContext(ctx)
return
}
return
}
// ListPreparer prepares the List request.
func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
const APIVersion = "2020-05-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/providers/Microsoft.Billing/operations"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client OperationsClient) listNextResults(ctx context.Context, lastResults OperationListResult) (result OperationListResult, err error) {
req, err := lastResults.operationListResultPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "billing.OperationsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/OperationsClient.List")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.List(ctx)
return
}
|
b'What is 6 + -8 - -4 - 7?\n'
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "walletview.h"
#include "addressbookpage.h"
#include "askpassphrasedialog.h"
#include "bitcoingui.h"
#include "clientmodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "overviewpage.h"
#include "receivecoinsdialog.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "transactiontablemodel.h"
#include "transactionview.h"
#include "walletmodel.h"
#include "miningpage.h"
#include "ui_interface.h"
#include <QAction>
#include <QActionGroup>
#include <QFileDialog>
#include <QHBoxLayout>
#include <QProgressDialog>
#include <QPushButton>
#include <QVBoxLayout>
WalletView::WalletView(QWidget *parent):
QStackedWidget(parent),
clientModel(0),
walletModel(0)
{
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
QHBoxLayout *hbox_buttons = new QHBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
QPushButton *exportButton = new QPushButton(tr("&Export"), this);
exportButton->setToolTip(tr("Export the data in the current tab to a file"));
#ifndef Q_OS_MAC // Icons on push buttons are very uncommon on Mac
exportButton->setIcon(QIcon(":/icons/export"));
#endif
hbox_buttons->addStretch();
hbox_buttons->addWidget(exportButton);
vbox->addLayout(hbox_buttons);
transactionsPage->setLayout(vbox);
receiveCoinsPage = new ReceiveCoinsDialog();
sendCoinsPage = new SendCoinsDialog();
miningPage = new MiningPage();
addWidget(overviewPage);
addWidget(transactionsPage);
addWidget(receiveCoinsPage);
addWidget(sendCoinsPage);
addWidget(miningPage);
// Clicking on a transaction on the overview pre-selects the transaction on the transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
// Pass through messages from sendCoinsPage
connect(sendCoinsPage, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Pass through messages from transactionView
connect(transactionView, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
}
WalletView::~WalletView()
{
}
void WalletView::setBitcoinGUI(BitcoinGUI *gui)
{
if (gui)
{
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), gui, SLOT(gotoHistoryPage()));
// Receive and report messages
connect(this, SIGNAL(message(QString,QString,unsigned int)), gui, SLOT(message(QString,QString,unsigned int)));
// Pass through encryption status changed signals
connect(this, SIGNAL(encryptionStatusChanged(int)), gui, SLOT(setEncryptionStatus(int)));
// Pass through transaction notifications
connect(this, SIGNAL(incomingTransaction(QString,int,qint64,QString,QString)), gui, SLOT(incomingTransaction(QString,int,qint64,QString,QString)));
}
}
void WalletView::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
overviewPage->setClientModel(clientModel);
miningPage->setClientModel(clientModel);
}
void WalletView::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setWalletModel(walletModel);
receiveCoinsPage->setModel(walletModel);
sendCoinsPage->setModel(walletModel);
miningPage->setWalletModel(walletModel);
if (walletModel)
{
// Receive and pass through messages from wallet model
connect(walletModel, SIGNAL(message(QString,QString,unsigned int)), this, SIGNAL(message(QString,QString,unsigned int)));
// Handle changes in encryption status
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SIGNAL(encryptionStatusChanged(int)));
updateEncryptionStatus();
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(processNewTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
// Show progress dialog
connect(walletModel, SIGNAL(showProgress(QString,int)), this, SLOT(showProgress(QString,int)));
}
}
void WalletView::processNewTransaction(const QModelIndex& parent, int start, int /*end*/)
{
// Prevent balloon-spam when initial block download is in progress
if (!walletModel || !clientModel || clientModel->inInitialBlockDownload())
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
QString date = ttm->index(start, TransactionTableModel::Date, parent).data().toString();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent).data(Qt::EditRole).toULongLong();
QString type = ttm->index(start, TransactionTableModel::Type, parent).data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent).data().toString();
emit incomingTransaction(date, walletModel->getOptionsModel()->getDisplayUnit(), amount, type, address);
}
void WalletView::gotoOverviewPage()
{
setCurrentWidget(overviewPage);
}
void WalletView::gotoHistoryPage()
{
setCurrentWidget(transactionsPage);
}
void WalletView::gotoReceiveCoinsPage()
{
setCurrentWidget(receiveCoinsPage);
}
void WalletView::gotoSendCoinsPage(QString addr)
{
setCurrentWidget(sendCoinsPage);
if (!addr.isEmpty())
sendCoinsPage->setAddress(addr);
}
void WalletView::gotoMiningPage()
{
setCurrentWidget(miningPage);
}
void WalletView::gotoSignMessageTab(QString addr)
{
// calls show() in showTab_SM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_SM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void WalletView::gotoVerifyMessageTab(QString addr)
{
// calls show() in showTab_VM()
SignVerifyMessageDialog *signVerifyMessageDialog = new SignVerifyMessageDialog(this);
signVerifyMessageDialog->setAttribute(Qt::WA_DeleteOnClose);
signVerifyMessageDialog->setModel(walletModel);
signVerifyMessageDialog->showTab_VM(true);
if (!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
bool WalletView::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
return sendCoinsPage->handlePaymentRequest(recipient);
}
void WalletView::showOutOfSyncWarning(bool fShow)
{
overviewPage->showOutOfSyncWarning(fShow);
}
void WalletView::updateEncryptionStatus()
{
emit encryptionStatusChanged(walletModel->getEncryptionStatus());
}
void WalletView::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt : AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
updateEncryptionStatus();
}
void WalletView::backupWallet()
{
QString filename = GUIUtil::getSaveFileName(this,
tr("Backup Wallet"), QString(),
tr("Wallet Data (*.dat)"), NULL);
if (filename.isEmpty())
return;
if (!walletModel->backupWallet(filename)) {
emit message(tr("Backup Failed"), tr("There was an error trying to save the wallet data to %1.").arg(filename),
CClientUIInterface::MSG_ERROR);
}
else {
emit message(tr("Backup Successful"), tr("The wallet data was successfully saved to %1.").arg(filename),
CClientUIInterface::MSG_INFORMATION);
}
}
void WalletView::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void WalletView::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if (walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void WalletView::usedSendingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::usedReceivingAddresses()
{
if(!walletModel)
return;
AddressBookPage *dlg = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab, this);
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->setModel(walletModel->getAddressTableModel());
dlg->show();
}
void WalletView::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0)
{
progressDialog = new QProgressDialog(title, "", 0, 100);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setMinimumDuration(0);
progressDialog->setCancelButton(0);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
}
else if (nProgress == 100)
{
if (progressDialog)
{
progressDialog->close();
progressDialog->deleteLater();
}
}
else if (progressDialog)
progressDialog->setValue(nProgress);
}
|
from scrapy.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import HtmlResponse
from FIFAscrape.items import PlayerItem
from urlparse import urlparse, urljoin
from scrapy.http.request import Request
from scrapy.conf import settings
import random
import time
class fifaSpider(Spider):
name = "fifa"
allowed_domains = ["futhead.com"]
start_urls = [
"http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps"
]
def parse(self, response):
#obtains links from page to page and passes links to parse_playerURL
sel = Selector(response) #define selector based on response object (points to urls in start_urls by default)
url_list = sel.xpath('//a[@class="display-block padding-0"]/@href') #obtain a list of href links that contain relative links of players
for i in url_list:
relative_url = self.clean_str(i.extract()) #i is a selector and hence need to extract it to obtain unicode object
print urljoin(response.url, relative_url) #urljoin is able to merge absolute and relative paths to form 1 coherent link
req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL
req.headers["User-Agent"] = self.random_ua()
yield req
next_url=sel.xpath('//div[@class="right-nav pull-right"]/a[@rel="next"]/@href').extract_first()
if(next_url): #checks if next page exists
clean_next_url = self.clean_str(next_url)
reqNext = Request(urljoin(response.url, clean_next_url),callback=self.parse) #calls back this function to repeat process on new list of links
yield reqNext
def parse_playerURL(self, response):
#parses player specific data into items list
site = Selector(response)
items = []
item = PlayerItem()
item['1name'] = (response.url).rsplit("/")[-2].replace("-"," ")
title = self.clean_str(site.xpath('/html/head/title/text()').extract_first())
item['OVR'] = title.partition("FIFA 16 -")[1].split("-")[0]
item['POS'] = self.clean_str(site.xpath('//div[@class="playercard-position"]/text()').extract_first())
#stats = site.xpath('//div[@class="row player-center-container"]/div/a')
stat_names = site.xpath('//span[@class="player-stat-title"]')
stat_values = site.xpath('//span[contains(@class, "player-stat-value")]')
for index in range(len(stat_names)):
attr_name = stat_names[index].xpath('.//text()').extract_first()
item[attr_name] = stat_values[index].xpath('.//text()').extract_first()
items.append(item)
return items
def clean_str(self,ustring):
#removes wierd unicode chars (/u102 bla), whitespaces, tabspaces, etc to form clean string
return str(ustring.encode('ascii', 'replace')).strip()
def random_ua(self):
#randomise user-agent from list to reduce chance of being banned
ua = random.choice(settings.get('USER_AGENT_LIST'))
if ua:
ua='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36'
return ua
|
b'-6 + (7 - (-1 - 0)) + 0\n'
|
#include "NL_ImguiD3D11Renderer.h"
#include <d3d11.h>
#include <d3dcompiler.h>
#include <imgui.h>
namespace NLE
{
namespace GRAPHICS
{
struct VERTEX_CONSTANT_BUFFER
{
float mvp[4][4];
};
ImguiD3D11Renderer::ImguiD3D11Renderer() :
_vertexBuffer(nullptr),
_indexBuffer(nullptr),
_vertexShaderBlob(nullptr),
_vertexShader(nullptr),
_inputLayout(nullptr),
_vertexConstantBuffer(nullptr),
_pixelShaderBlob(nullptr),
_pixelShader(nullptr),
_fontSampler(nullptr),
_fontTextureView(nullptr),
_rasterizerState(nullptr),
_blendState(nullptr),
_depthStencilState(nullptr),
_vertexBufferSize(5000),
_indexBufferSize(10000)
{
}
ImguiD3D11Renderer::~ImguiD3D11Renderer()
{
}
bool ImguiD3D11Renderer::initialize(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
if (!createDeviceObjects(device, devCon))
return false;
if (!createFontAndTextures(device, devCon))
return false;
return true;
}
bool ImguiD3D11Renderer::createDeviceObjects(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
// By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A)
// If you would like to use this DX11 sample code but remove this dependency you can:
// 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [prefered solution]
// 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL.
// See https://github.com/ocornut/imgui/pull/638 for sources and details.
// Create the vertex shader
{
static const char* vertexShader =
"cbuffer vertexBuffer : register(b0) \
{\
float4x4 ProjectionMatrix; \
};\
struct VS_INPUT\
{\
float2 pos : POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
\
PS_INPUT main(VS_INPUT input)\
{\
PS_INPUT output;\
output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\
output.col = input.col;\
output.uv = input.uv;\
return output;\
}";
D3DCompile(vertexShader, strlen(vertexShader), nullptr, nullptr, nullptr, "main", "vs_4_0", 0, 0, &_vertexShaderBlob, nullptr);
if (!_vertexShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return false;
if (device->CreateVertexShader((DWORD*)_vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), nullptr, &_vertexShader) != S_OK)
return false;
// Create the input layout
D3D11_INPUT_ELEMENT_DESC local_layout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
if (device->CreateInputLayout(local_layout, 3, _vertexShaderBlob->GetBufferPointer(), _vertexShaderBlob->GetBufferSize(), &_inputLayout) != S_OK)
return false;
// Create the constant buffer
{
D3D11_BUFFER_DESC desc;
desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER);
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
device->CreateBuffer(&desc, nullptr, &_vertexConstantBuffer);
}
}
// Create the pixel shader
{
static const char* pixelShader =
"struct PS_INPUT\
{\
float4 pos : SV_POSITION;\
float4 col : COLOR0;\
float2 uv : TEXCOORD0;\
};\
sampler sampler0;\
Texture2D texture0;\
\
float4 main(PS_INPUT input) : SV_Target\
{\
float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \
return out_col; \
}";
D3DCompile(pixelShader, strlen(pixelShader), nullptr, nullptr, nullptr, "main", "ps_4_0", 0, 0, &_pixelShaderBlob, nullptr);
if (!_pixelShaderBlob) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob!
return false;
if (device->CreatePixelShader((DWORD*)_pixelShaderBlob->GetBufferPointer(), _pixelShaderBlob->GetBufferSize(), nullptr, &_pixelShader) != S_OK)
return false;
}
// Create the blending setup
{
D3D11_BLEND_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.AlphaToCoverageEnable = false;
desc.RenderTarget[0].BlendEnable = true;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
device->CreateBlendState(&desc, &_blendState);
}
// Create the rasterizer state
{
D3D11_RASTERIZER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.FillMode = D3D11_FILL_SOLID;
desc.CullMode = D3D11_CULL_NONE;
desc.ScissorEnable = true;
desc.DepthClipEnable = true;
device->CreateRasterizerState(&desc, &_rasterizerState);
}
// Create depth-stencil State
{
D3D11_DEPTH_STENCIL_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.DepthEnable = false;
desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
desc.DepthFunc = D3D11_COMPARISON_ALWAYS;
desc.StencilEnable = false;
desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
desc.BackFace = desc.FrontFace;
device->CreateDepthStencilState(&desc, &_depthStencilState);
}
return true;
}
bool ImguiD3D11Renderer::createFontAndTextures(ID3D11Device* device, ID3D11DeviceContext* devCon)
{
// Build texture atlas
ImGuiIO& io = ImGui::GetIO();
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// Upload texture to graphics system
{
D3D11_TEXTURE2D_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Width = width;
desc.Height = height;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_DEFAULT;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
desc.CPUAccessFlags = 0;
ID3D11Texture2D *pTexture = NULL;
D3D11_SUBRESOURCE_DATA subResource;
subResource.pSysMem = pixels;
subResource.SysMemPitch = desc.Width * 4;
subResource.SysMemSlicePitch = 0;
device->CreateTexture2D(&desc, &subResource, &pTexture);
// Create texture view
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
ZeroMemory(&srvDesc, sizeof(srvDesc));
srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = desc.MipLevels;
srvDesc.Texture2D.MostDetailedMip = 0;
device->CreateShaderResourceView(pTexture, &srvDesc, &_fontTextureView);
pTexture->Release();
}
// Store our identifier
io.Fonts->TexID = (void *)_fontTextureView;
// Create texture sampler
{
D3D11_SAMPLER_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
desc.MipLODBias = 0.f;
desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
desc.MinLOD = 0.f;
desc.MaxLOD = 0.f;
device->CreateSamplerState(&desc, &_fontSampler);
}
return true;
}
void ImguiD3D11Renderer::render(ID3D11Device* device, ID3D11DeviceContext* devCon, ImDrawData* drawData)
{
// Create and grow vertex/index buffers if needed
if (!_vertexBuffer || _vertexBufferSize < drawData->TotalVtxCount)
{
if (_vertexBuffer) { _vertexBuffer->Release(); _vertexBuffer = nullptr; }
_vertexBufferSize = drawData->TotalVtxCount + 5000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = _vertexBufferSize * sizeof(ImDrawVert);
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
desc.MiscFlags = 0;
if (device->CreateBuffer(&desc, nullptr, &_vertexBuffer) < 0)
return;
}
if (!_indexBuffer || _indexBufferSize < drawData->TotalIdxCount)
{
if (_indexBuffer) { _indexBuffer->Release(); _indexBuffer = nullptr; }
_indexBufferSize = drawData->TotalIdxCount + 10000;
D3D11_BUFFER_DESC desc;
memset(&desc, 0, sizeof(D3D11_BUFFER_DESC));
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.ByteWidth = _indexBufferSize * sizeof(ImDrawIdx);
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
if (device->CreateBuffer(&desc, nullptr, &_indexBuffer) < 0)
return;
}
// Copy and convert all vertices into a single contiguous buffer
D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource;
if (devCon->Map(_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK)
return;
if (devCon->Map(_indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK)
return;
ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData;
ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData;
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
memcpy(vtx_dst, &cmd_list->VtxBuffer[0], cmd_list->VtxBuffer.size() * sizeof(ImDrawVert));
memcpy(idx_dst, &cmd_list->IdxBuffer[0], cmd_list->IdxBuffer.size() * sizeof(ImDrawIdx));
vtx_dst += cmd_list->VtxBuffer.size();
idx_dst += cmd_list->IdxBuffer.size();
}
devCon->Unmap(_vertexBuffer, 0);
devCon->Unmap(_indexBuffer, 0);
// Setup orthographic projection matrix into our constant buffer
{
D3D11_MAPPED_SUBRESOURCE mapped_resource;
if (devCon->Map(_vertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK)
return;
VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData;
float L = 0.0f;
float R = ImGui::GetIO().DisplaySize.x;
float B = ImGui::GetIO().DisplaySize.y;
float T = 0.0f;
float mvp[4][4] =
{
{ 2.0f / (R - L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f / (T - B), 0.0f, 0.0f },
{ 0.0f, 0.0f, 0.5f, 0.0f },
{ (R + L) / (L - R), (T + B) / (B - T), 0.5f, 1.0f },
};
memcpy(&constant_buffer->mvp, mvp, sizeof(mvp));
devCon->Unmap(_vertexConstantBuffer, 0);
}
// Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!)
struct BACKUP_DX11_STATE
{
UINT ScissorRectsCount, ViewportsCount;
D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE];
ID3D11RasterizerState* RS;
ID3D11BlendState* BlendState;
FLOAT BlendFactor[4];
UINT SampleMask;
UINT StencilRef;
ID3D11DepthStencilState* DepthStencilState;
ID3D11ShaderResourceView* PSShaderResource;
ID3D11SamplerState* PSSampler;
ID3D11PixelShader* PS;
ID3D11VertexShader* VS;
UINT PSInstancesCount, VSInstancesCount;
ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation
D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology;
ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer;
UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset;
DXGI_FORMAT IndexBufferFormat;
ID3D11InputLayout* InputLayout;
};
BACKUP_DX11_STATE old;
old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE;
devCon->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects);
devCon->RSGetViewports(&old.ViewportsCount, old.Viewports);
devCon->RSGetState(&old.RS);
devCon->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask);
devCon->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef);
devCon->PSGetShaderResources(0, 1, &old.PSShaderResource);
devCon->PSGetSamplers(0, 1, &old.PSSampler);
old.PSInstancesCount = old.VSInstancesCount = 256;
devCon->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount);
devCon->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount);
devCon->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer);
devCon->IAGetPrimitiveTopology(&old.PrimitiveTopology);
devCon->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset);
devCon->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset);
devCon->IAGetInputLayout(&old.InputLayout);
// Setup viewport
D3D11_VIEWPORT vp;
memset(&vp, 0, sizeof(D3D11_VIEWPORT));
vp.Width = ImGui::GetIO().DisplaySize.x;
vp.Height = ImGui::GetIO().DisplaySize.y;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = vp.TopLeftY = 0.0f;
devCon->RSSetViewports(1, &vp);
// Bind shader and vertex buffers
unsigned int stride = sizeof(ImDrawVert);
unsigned int offset = 0;
devCon->IASetInputLayout(_inputLayout);
devCon->IASetVertexBuffers(0, 1, &_vertexBuffer, &stride, &offset);
devCon->IASetIndexBuffer(_indexBuffer, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0);
devCon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
devCon->VSSetShader(_vertexShader, NULL, 0);
devCon->VSSetConstantBuffers(0, 1, &_vertexConstantBuffer);
devCon->PSSetShader(_pixelShader, NULL, 0);
devCon->PSSetSamplers(0, 1, &_fontSampler);
// Setup render state
const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f };
devCon->OMSetBlendState(_blendState, blend_factor, 0xffffffff);
devCon->OMSetDepthStencilState(_depthStencilState, 0);
devCon->RSSetState(_rasterizerState);
// Render command lists
int vtx_offset = 0;
int idx_offset = 0;
for (int n = 0; n < drawData->CmdListsCount; n++)
{
const ImDrawList* cmd_list = drawData->CmdLists[n];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w };
devCon->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId);
devCon->RSSetScissorRects(1, &r);
devCon->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset);
}
idx_offset += pcmd->ElemCount;
}
vtx_offset += cmd_list->VtxBuffer.size();
}
// Restore modified DX state
devCon->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects);
devCon->RSSetViewports(old.ViewportsCount, old.Viewports);
devCon->RSSetState(old.RS); if (old.RS) old.RS->Release();
devCon->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release();
devCon->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release();
devCon->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release();
devCon->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release();
devCon->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release();
for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release();
devCon->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release();
devCon->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release();
for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release();
devCon->IASetPrimitiveTopology(old.PrimitiveTopology);
devCon->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release();
devCon->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release();
devCon->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release();
}
}
}
|
# encoding: utf-8
require 'spec_helper'
describe Optimizer::Algebra::Projection::ExtensionOperand, '#optimizable?' do
subject { object.optimizable? }
let(:header) { Relation::Header.coerce([[:id, Integer], [:name, String], [:age, Integer]]) }
let(:base) { Relation.new(header, LazyEnumerable.new([[1, 'Dan Kubb', 35]])) }
let(:relation) { operand.project([:id, :name]) }
let(:object) { described_class.new(relation) }
before do
expect(object.operation).to be_kind_of(Algebra::Projection)
end
context 'when the operand is an extension, and the extended attribtue is removed ' do
let(:operand) { base.extend { |r| r.add(:active, true) } }
it { should be(true) }
end
context 'when the operand is an extension, and the extended attribtue is not removed ' do
let(:operand) { base.extend { |r| r.add(:active, true) } }
let(:relation) { operand.project([:id, :name, :active]) }
it { should be(false) }
end
context 'when the operand is not an extension' do
let(:operand) { base }
it { should be(false) }
end
end
|
# MondrianRedisSegmentCache
Mondrian ships with an in memory segment cache that is great for standalone deployments of Mondrian, but doesn't
scale out with multiple nodes. An interface is provided for extending Mondrian with a shared Segment Cache and
examples of other implementations are in the links below.
In order to use Mondrian with Redis (our preferred caching layer) and Ruby (our preferred language -- Jruby) we had
to implement the SegmentCache interface from Mondrian and use the Redis notifications api.
Mondrian's segment cache needs to be able to get/set/remove cache items and also get any updates from the caching server
as other nodes are getting/setting/removing entries. This means that we need to use both the notifications and subscribe
api's from Redis.
http://stackoverflow.com/questions/17533594/implementing-a-mondrian-shared-segmentcache
http://mondrian.pentaho.com/api/mondrian/spi/SegmentCache.html
https://github.com/pentaho/mondrian/blob/master/src/main/mondrian/rolap/cache/MemorySegmentCache.java
https://github.com/webdetails/cdc
http://redis.io/topics/notifications
## Installation
Add this line to your application's Gemfile:
gem 'mondrian_redis_segment_cache'
And then execute:
$ bundle
Or install it yourself as:
$ gem install mondrian_redis_segment_cache
## Usage
If using Rails you can put the configuration in an initializer
```ruby
require 'redis'
require 'mondrian_redis_segment_cache'
# Setup a Redis connection
MONDRIAN_REDIS_CONNECTION = Redis.new(:url => "redis://localhost:1234/2")
MONDRIAN_SEGMENT_CACHE = ::MondrianRedisSegmentCache::Cache.new(MONDRIAN_REDIS_CONNECTION)
# Register the segment cache with the Mondrian Injector
::Java::MondrianSpi::SegmentCache::SegmentCacheInjector::add_cache(MONDRIAN_SEGMENT_CACHE)
```
In Redis we use the notifications api, so you must turn it on!
It is off by default because it is a new feature and can be CPU intensive. Redis does a ton, so there is a minimum of notifications
that must be turned on for this gem to work.
`notify-keyspace-events Egex$`
This tells Redis to publish keyevent events (which means we can subscribe to things like set/del) and to publish the generic commands
(like DEL, EXPIRE) and finally String commands (like SET)
The SegmentCache uses these notifications to keep Mondrian in sync across your Mondrian instances.
It also eager loads the current cached items into the listeners when they are added to the cache. This allows
an existing cache to be reused between deploys.
Cache expiry is handled by the options `:ttl` and `:expires_at`
If you want a static ttl (time to live) then each key that is inserted will be set to expire after the ttl completes. This is
not always optimal for an analytics cache and you may want all keys to expire at the same time (potentially on a daily basis).
If you want all keys to expire at the same time you should use `:expires_at` in the options hash. This should be the hour that
you want all keys to expire on. 1 being 1am, 2 being 2am, 15 being 3pm and so on.
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from scipy.spatial import distance
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn import decomposition # PCA
from sklearn.metrics import confusion_matrix
import json
import ml.Features as ft
from utils import Utils
class Identifier(object):
def __init__(self):
columns = ['mean_height', 'min_height', 'max_height', 'mean_width', 'min_width', 'max_width', 'time', 'girth','id']
self.data = DataFrame(columns=columns)
self.event = []
@staticmethod
def subscribe(ch, method, properties, body):
"""
prints the body message. It's the default callback method
:param ch: keep null
:param method: keep null
:param properties: keep null
:param body: the message
:return:
"""
#first we get the JSON from body
#we check if it's part of the walking event
#if walking event is completed, we
if __name__ == '__main__':
# we setup needed params
MAX_HEIGHT = 203
MAX_WIDTH = 142
SPEED = 3
SAMPLING_RATE = 8
mq_host = '172.26.56.122'
queue_name = 'door_data'
# setting up MQTT subscriber
Utils.sub(queue_name=queue_name,callback=subscribe,host=mq_host)
|
b'What is 3 + -4 + (-20 - (-40 + 24))?\n'
|
b'Evaluate 8 + (7 + -12 - (12 + -2 + -9)).\n'
|
@echo off
CLS
%header%
echo.
if not exist "Programme\HackMii Installer" mkdir "Programme\HackMii Installer"
echo Downloade den HackMii Installer...
start /min/wait Support\wget -c -l1 -r -nd --retr-symlinks -t10 -T30 --random-wait --reject "*.html" --reject "%2A" --reject "get.php@file=hackmii_installer_v1.0*" "http://bootmii.org/download/"
move get.php* hackmii-installer_v1.2.zip >NUL
start /min/wait Support\7za e -aoa hackmii-installer_v1.2.zip -o"Programme\HackMii Installer" *.elf -r
del hackmii*
:endedesmoduls
|
<ng-container *ngIf="preview.user && !authHelper.isSelf(preview.user)">
<user-info [user]="preview.user">
</user-info>
</ng-container>
<!-- description + image -->
<label-value [label]="i18n.voucher.voucher">
{{ preview.type.voucherTitle }}
</label-value>
<ng-container *ngIf="buyVoucher.count === 1; else multiple">
<label-value [label]="i18n.transaction.amount">
{{ buyVoucher.amount | currency:preview.type.configuration.currency }}
</label-value>
</ng-container>
<ng-template #multiple>
<label-value [label]="i18n.voucher.numberOfVouchers">
{{ buyVoucher.count }}
</label-value>
<label-value [label]="i18n.voucher.amountPerVoucher">
{{ buyVoucher.amount | currency:preview.type.configuration.currency }}
</label-value>
<label-value [label]="i18n.voucher.totalAmount">
{{ preview.totalAmount | currency:preview.type.configuration.currency }}
</label-value>
</ng-template>
<label-value *ngIf="preview.type.gift === 'choose'" kind="fieldView"
[label]="i18n.voucher.buy.usage"
[value]="buyVoucher.gift ? i18n.voucher.buy.usageGift : i18n.voucher.buy.usageSelf">
</label-value>
<label-value *ngIf="preview.type.gift === 'never'" kind="fieldView"
[label]="i18n.voucher.buy.usage" [value]="i18n.voucher.buy.usageAlwaysSelf">
</label-value>
<!-- payment fields -->
<ng-container *ngFor="let cf of paymentCustomFields">
<label-value
[hidden]="!fieldHelper.hasValue(cf.internalName, buyVoucher.paymentCustomValues)"
[label]="cf.name"
[labelPosition]="labelOnTop((layout.ltsm$ | async), cf) ? 'top' : 'auto'">
<format-field-value [customValues]="buyVoucher.paymentCustomValues"
[fields]="paymentCustomFields" [fieldName]="cf.internalName">
</format-field-value>
</label-value>
</ng-container>
<!-- custom fields -->
<ng-container *ngFor="let cf of voucherCustomFields">
<label-value
[hidden]="!fieldHelper.hasValue(cf.internalName, buyVoucher.voucherCustomValues)"
[label]="cf.name"
[labelPosition]="labelOnTop((layout.ltsm$ | async), cf) ? 'top' : 'auto'">
<format-field-value [customValues]="buyVoucher.voucherCustomValues"
[fields]="voucherCustomFields" [fieldName]="cf.internalName">
</format-field-value>
</label-value>
</ng-container>
<ng-container *ngIf="preview.confirmationPasswordInput">
<hr *ngIf="layout.gtxxs$ | async">
<confirmation-password focused
[formControl]="form.get('confirmationPassword')"
[passwordInput]="preview.confirmationPasswordInput"
[createDeviceConfirmation]="createDeviceConfirmation"
(confirmationModeChanged)="confirmationModeChanged.emit($event)"
(confirmed)="confirmed.emit($event)">
</confirmation-password>
</ng-container>
|
b'Calculate -36 + -15 + 31 + 5.\n'
|
#!/bin/bash
cp index.html /var/www/
cp -r js /var/www
cp -r img /var/www/img
|
# Minitest::Mock::Easily
use MiniTest::Mock with easier API
## Installation
Add this line to your application's Gemfile:
gem 'minitest-mock-easily'
And then execute:
$ bundle
Or install it yourself as:
$ gem install minitest-mock-easily
## Usage
```
include MockEasily
m = mock do
expect :hello, 'hello'
expect :world, 'world'
end
assert_equal 'hello', m.hello
assert_equal 'world', m.world
```
## Contributing
1. Fork it ( http://github.com/<my-github-username>/minitest-mock-easily/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
b'-20 + 47 + (-8 - 20)\n'
|
b'Evaluate 15 - (2 + 2) - (-37 + 26).\n'
|
b'-8 + -15 + 5 + -5 + 8 + 15\n'
|
b'Calculate -20 - -14 - (2 - 8) - (5 - 1).\n'
|
b'Evaluate 11 + 5 - (11 + 10).\n'
|
package se.dsv.waora.deviceinternetinformation;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
/**
* <code>ConnectionActivity</code> presents UI for showing if the device
* is connected to internet.
*
* @author Dushant Singh
*/
public class ConnectionActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiate view
TextView connectivityStatus = (TextView) findViewById(R.id.textViewDeviceConnectivity);
// Get connectivity service.
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Get active network information
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
// Check if active network is connected.
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected) {
// Set status connected
connectivityStatus.setText(getString(R.string.online));
connectivityStatus.setTextColor(getResources().getColor(R.color.color_on));
// Check if connected with wifi
boolean isWifiOn = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
if (isWifiOn) {
// Set wifi status on
TextView wifiTextView = (TextView) findViewById(R.id.textViewWifi);
wifiTextView.setText(getString(R.string.on));
wifiTextView.setTextColor(getResources().getColor(R.color.color_on));
} else {
// Set mobile data status on.
TextView mobileDataTextView = (TextView) findViewById(R.id.textViewMobileData);
mobileDataTextView.setText(getString(R.string.on));
mobileDataTextView.setTextColor(getResources().getColor(R.color.color_on));
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.